/**
 * init form (prepare for submit, visual tweaks)
 */
function glow_initForms() {			
	////////////////////////////////////
	// form validation	
	$("FORM.glow-validateform").submit(function(){
		// trigger richtext update of underlying field prior to validation
		//if(tinyMCE) tinyMCE.triggerSave();		
	}).validate({
		//debug:true,
		errorClass:"error",
		meta:"validate",
		ignoreTitle: true,
		submitHandler: function(form){
			glow_submitForm(form);
		},
		errorPlacement: function(error, element) {			
			element = $(element)[0];				
			$(element.form).find("label.errorlabel[rel=" + element.id + "]").html($(error).html());
	    },
		highlight:function(element,errorClass) {
			// only bother highlighting if it's not already visible
			var errLabel = $(element.form).find("label.errorlabel[rel=" + element.id + "]:hidden");			
			$(element).addClass(errorClass);
			errLabel.show();
			errLabel.css('display','block');	
			$(errLabel).fadeOut(function() {
				$(errLabel).fadeIn();
				errLabel.css('display','block');
			});			
		},
		unhighlight:function(element,errorClass){
			var errLabel = $(element.form).find("label.errorlabel[rel=" + element.id + "]");			
			$(element).removeClass(errorClass);
			errLabel.hide();
		}
	});
	
	$("FORM.glow-validateform").each(function(){
		var anchorName = $(this).attr('id');		
		$(this).data('anchorName', anchorName);
	});
	
	// trigger pre-validation for any forms which have 'showErrors' set
	try {
		$("FORM.glow-validateform.showErrors").validate().form();
	}catch(e){}

	// change date fields to datepicker widget
	$(":input.datepicker").datepicker({
						dateFormat:'dd-M-yy',
					    showOn: "both",
					   	buttonImage: "/templates/images/calendar.gif",
					    buttonImageOnly: true
					})
					.attr("readonly", "readonly")
					.addClass("embed");	
					
	// time picker
	$(":input.timepicker").timeEntry({
		spinnerImage: '/templates/images/spinner.png',
		spinnerBigImage: '/templates/images/spinnerBig.png'
	});
}

/** 
 * perform form submission (post validate)
 * @param {Object} theForm
 */
function glow_submitForm(theForm){	
	var bRedirect = $(':input[name=_glowRedirect]', theForm).val()=="true";
	var sAction = $(theForm).attr('action');
	var container = $(theForm).parents('.glow-form-container');	

	// if bRedirect is false we will submit this form via ajax
	if(!bRedirect){
		$.blockUI();		
		$(theForm).ajaxSubmit({
			cache		: false,
			dataType	: "json",
			data 		: {isAJAX:true},
			success:function(data,statusText){
				$.unblockUI();
				var sMessage = $(data.message);
				
				// EVERYTHING OK?
				if (statusText == 'success' && data.success) {
					var sRelocate = data.relocate;
					if(window.console) console.log(sRelocate);
					
					// relocate to defined page if defined
					if( sRelocate != undefined && $.trim(sRelocate).length > 0){
						document.location.href = sRelocate;
						// continue on to display any return messages while the page relocates
					}
					// relocate to anchor tag
					if( sMessage != "" ){
						var anchorName = $(theForm).data('anchorName');
						$(sMessage).prepend('<a name="' + anchorName +  '"></a>');
						$(container).replaceWith(sMessage);
						document.location = '#' + anchorName;
					}
				
				// OTHERWISE FAIL
				} else {
					alert('An error was encountered with your submission. \nPlease try again later.');
					if(window.console) console.log("submit error: ",data);
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown) {
			  	// typically only one of textStatus or errorThrown 
			  	// will have info
			 	// this; // the options for this ajax request
			 	$.unblockUI();
			 	alert('An error was encountered with your submission. \nPlease try again later.');
				if(window.console) console.log("submit error: ",arguments);
			}

		});
		return false;
	}else{
		// normal submit	
		theForm.submit();	
		return true;
	}	
}

