var objSubscriberForm = null;
/**
 * init form (prepare for submit, visual tweaks)
 */
function glow_initSubscribers() {
	// populate the form with applicable data
	//populateForm($("FORM.glow-validatesubscriberform"));

	////////////////////////////////////
	// form validation
	$("FORM.glow-validatesubscriberform").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_submitSubscriberForm(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();
		}
	});	
	
	// 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'
	});
}

function populateForm(theForm){
	var params = {
		module		: "subscriber",
		contenttype : "subscriber",
		contentid   : $(":input[name=_glowContentId",theForm),
		nocache     : 1
	}
	
	var jsonData = "";
	$.ajax({url:"/index.cfm?mode=subscriber", dataType:"json", type:"GET", data:params,
		success: function(jsonData){
			//console.log("data",jsonData);
			if( $(":input[name=subscriberId]", theForm).val() == "" ){
				$(":input[name=vchCurrentPassword]", theForm).remove();
			}
			$(":input",theForm).each(function(){
				var fieldName = "";
				var fieldValue = "";
				fieldName = $(this).attr('name');
				fieldValue = eval('jsonData.data.'+fieldName);
				$(this).val(fieldValue); 
			});
		}, error: function(data){
			console.log("error",data);	
		}
	});	
}

/** 
 * perform form submission (post validate)
 * @param {Object} theForm
 */
function glow_submitSubscriberForm(theForm){	
	var bRedirect = $(':input[name=_glowRedirect]', theForm).val()=="true";
	var sModule = $(':input[name=_glowModule]', theForm).val();
	var sAction = $(theForm).attr('action');
	var container = $(theForm).parents('.glow-subscriber-container');	

	// if bRedirect is false we will submit this form via ajax
	if(!bRedirect){
		// copy the form so that when we return we have
		// a reference to the pre-ajax call data set
		var formDataCopy = {isAjax:true};
		var fieldnames = [];
		$(":input",theForm).each(function(){		
			//$.log('set ',$(this).attr('name'),'=', $(this).val());
			formDataCopy[$(this).attr('name')] = $(this).val(); 
			fieldnames.push($(this).attr('name'));
		});
		formDataCopy['fieldnames'] = fieldnames.join(',');
		//$.log('DATA:',formDataCopy);
	
		$.blockUI();
		$.ajax({
			url			: "/index.cfm?module=subscriber",
			cache		: false,
			dataType	: "xml",
			data 		: formDataCopy,
			success:function(xmldata,statusText){
				$.unblockUI();
				var sMessage = $(xmldata).find('message').text();
				if(window.console) console.log(sMessage,statusText);
				if (statusText == 'success' && $(xmldata).find('success').text()=="true") {
					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;
					}
				} else {
					if( sMessage == "" ){
						alert('An error was encountered with your submission. \nPlease try again later.');
					} else {
						alert(sMessage);
					}
					if(window.console) console.log("submit error P1: ",xmldata);
				}
			},
			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 P2: ",arguments);
			}

		});
		return false;
	}else{
		// normal submit	
		theForm.submit();	
		return true;
	}	
}

function showResponse(theForm, formData,xmldata){
	var sResponse = $(xmldata).find('content').text();
	if( sResponse != "" ){
		// remove any glow references from the form
		$(".glow-subscriber-container").replaceWith(sResponse);
	}
	var sURL = $(xmldata).find('url').text();
	if( sURL != "" ){
		document.location.href = sURL;
	}
	return true;
}
