/**
 * Contains reusable functions for handling of forms. For functions specific
 * to handling of PWN forms see forms.js
 */

/**
 * Shows form error boxes for each field in the fieldArr
 *
 * fieldsArr is a multidimensional arr containing the field to validate and the
 * error message, or specify 'alert' as the field_name for an alert box.
 *
 * e.g
 * {
 *  {'message':'Please enter a valid email', 'field_name': 'email',
 *  {'message':'Please check the box', 'field_name': 'agree_terms_and_conditions'}
 *  {'message':'An error occurred', 'field_name': 'alert'}
 * }
 *
 * The error box and arrow are created with ids of fieldname-error-box and
 * field-name-error-pointer so their layout can be fine-tuned in CSS
 *
 * To seperate out language from functionality, the message can be passed as a JS constant.
 * If the constant has been specified in quotes, (it probably will if it came from PHP)
 * pass quotedConstants as true to eval them.
 *
 * @param array     fieldsArr       Form fields and error messages
 * @param string    formId          The id of the form being validated
 * @param null|bool quotedConstants True if the messages are values of javascript constants,
 *                                  but have been quoted
 * @param null|bool showMultiple    If true will show multiple error boxes, otherwise
 *                                  only the first error will be shown
 *
 * @return bool                     True if no error boxes were needed to be shown,
 *                                  otherwise true
 */
function showInputErrorsBoxes(fieldsArr, formId, quotedConstants, showMultiple) {

    if (showMultiple === undefined) {
        showMultiple = false;
    }
	
    if (quotedConstants === undefined) {
        quotedConstants = false;
    }

    // Hide all existing error boxes
    $('.error-box').remove();
    
    // If there is nothing to validate then validation has passed
    if (fieldsArr.length == 0) {
        return true;
    }

    // Loop round every field to show checkbox for
    for (fieldIndex in fieldsArr) {

		// If the constant is quoted then get the constant value
		if (quotedConstants) {
			fieldsArr[fieldIndex]['message'] = eval(fieldsArr[fieldIndex]['message']);
		}
	
		// If the field name is specified as alert, then show an alert box
		if (fieldsArr[fieldIndex]['field_name'] == 'alert') {
			alert(fieldsArr[fieldIndex]['message']);
		} else {
			// A field name has been specified, so show the red tooltip error

			// Get the input (or select etc) element
			fieldHandle = $("#" + formId + " [name=" + fieldsArr[fieldIndex]['field_name'] + "]");
			
			// Show error message,
			//fieldHandle.parent().after('<div class="error-box" style="z-index:1500;" id="' + fieldsArr[fieldIndex]['field_name'] + '-error-box"><div style="z-index:1501;" class="error-pointer png" id="' + fieldsArr[fieldIndex]['field_name'] + '-error-pointer"></div>' + fieldsArr[fieldIndex]['message'] + '</div>');
			fieldHandle.parent().after('<div class="nice-error-box" id="' + fieldsArr[fieldIndex]['field_name'] + '-error-box"><div class="nice-error-box-before"><img src="/img/nice-error-pointer.gif" alt="" /></div>' + fieldsArr[fieldIndex]['message'] + '<span class="error-box-close" onclick="$(this).parent(\'div\').hide();">x</span></div>');
			
			// Remove the error when the field the error message for becomes focused,
			fieldHandle.focusin(function() {
				$('#' + fieldsArr[fieldIndex]['field_name'] + '-error-box').remove();
			});
		}
		
        // Quit looping if we are not showing multiple messages
        if (!showMultiple) {
            return false;
        }
    }

    return false;
}


/**
 * Sets up default text for form text fields such as 'Enter email address here'
 * 
 * It will:
 *  * Insert the text on page load presuming the text box is empty
 *  * Remove the text on focus when the default text is present
 *  * Put the default text back in if the field is blank
 * 
 * Use like the following, and run when the page loads or when you initialise
 * the form:
 * 
 * defaultTextField($('#register_email'), 'Enter email address here');
 * 
 */
function defaultTextField(formElement, defaultText) {

	if (defaultText == undefined) {
		defaultText = formElement.val();
	}

	// Apply default text when page loads if the field is empty
	// formElement
	if (formElement.val() == '') {
		formElement.val(defaultText);
	}

	// Remove default text on focus
	formElement.focusin(function() {
		if (formElement.val() == defaultText) {
			formElement.val('');
		}
	});

	// Insert default text if field is empty when focus out
	formElement.focusout(function() {
		if (formElement.val() == '') {
			formElement.val(defaultText);
		}
	});
}

/**
 * Shows the ajax loader image after the specified jquery selected
 * submit element
 *
 * @param	image	Image src of the loader image
 * @param	appearAfter	Jquery selected element for the 
 * @param	idTag	Id tag the image should have, defaults to ajax_loader
 */
function formShowAjaxLoader(image, appearAfter, idTag, postop, posleft) {

	// Default idTag to ajax_loader if not specified
	if (idTag == null){
		idTag = 'ajax_loader';
	}

	// Insert loaderimage after specified element
	//appearAfter.html('<div id="' + idTag + '" style="font-size: 11px;><img src=' + image + ' alt="loading" /></div>');
	$('<div id="' + idTag + '" style="top: '+postop+'px; left: '+posleft+'px"><img src=' + image + ' alt="" /></div>').insertAfter(appearAfter);

	return true;
}

/**
 * Remove the ajax loader image, specifiy the idTag if you specified
 * one when calling formShowAjaxLoader();
 */
function formRemoveAjaxLoader(idTag) {
	// Default idTag to ajax_loader if not specified
	if (idTag == null){
		idTag = 'ajax_loader';
	}
	// Remove loader image
	$('#' + idTag).remove();
}

/**
 * One guess what this does
 */
function isValidEmail(email) {
	if (email === undefined) {
		return false;
	}
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return email.match(re);
}

/**
 * If an ajax form request gets an error (such 404) then call this function
 */
function formCommunicationError(idTag) {

	// Remove the ajax loader image
	formRemoveAjaxLoader(idTag);

	alert(FORM_COMMUNICATION_ERROR);
}

/**
 * Sets all checkboxes matched by selector to checkedBool state
 * eg: <input type="checkbox" onchange="formToggleAllCheckboxes(this.checked, 'input[name^=id]');">
 * @param checkedBool bool
 * @param selector Jquery selector of the checkboxes to toggle
 */
function formToggleAllCheckboxes(checkedBool, selector) {
    $(selector).each(function() {
        this.checked = checkedBool;
    });
}

