// KAYA Global
$(document).ready(function(){
	kayaInit();
});
//var overlaysEnabled = true;
var disableOnSubmit = true; 
//var setFormButtonsEnabled = true;
//var debugMode = true;
/**
 * kayaInit()
 * 
 * To Enable add the following to the header before calling $cms.pageHeaderHTML
 * below are the settings used in conjunction with this file.
 * 	
 * 	var overlaysEnabled = true;  //turns on overlay support, also sets up Anchor <a> overrides to place member / intranet pages (login, change pw, reset pw, update profile, register) in overlays.
 * 	var disableOnSubmit = true; // sets up all submit buttons to disable on submit - this is useful to keep pages from submitting multiple times.
 *	var setFormButtonsEnabled = true; //sets up ui style buttons on the .formbutton class
 *
 *	var debugMode = false; // turns on debug mode.
 * 
 * @return void
 */
function kayaInit() {
	jQuery.ajaxSetup({
		scriptCharset: "utf-8",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		cache: false,
		type: "POST"
	});	

	$('form').each(function() {
		var form = $(this);
		form.submit(function(){
			if(typeof(disableOnSubmit) != 'undefined' && disableOnSubmit){
				$(form).find('input:submit').attr('disabled', 'disabled');
			}
			if(typeof(showProcessingOverlay) != 'undefined' && showProcessingOverlay){
				showProcessing();
			}
		});
	});

	initPage();

	pingMe();	
}

function initPage(){
	if(typeof(overlaysEnabled) != 'undefined' && overlaysEnabled){
		$('body').append('<div id="popupDialogBoxContainer" style="display:none;"></div>');
		$('body').append('<div id="confirmDialogBoxContainer" style="display:none;"></div>');
		$('body').append('<div id="messages" style="display:none;"></div>');
		
		$('#popupDialogBoxContainer').bind('dialogclose', function(event) {
			$('#popupDialogBoxContainer').kayadialog('close');
			$('#popupDialogBoxContainer').html('');
		});
	
		if(typeof(memberEnabled) != 'undefined' && memberEnabled) {			
			// new member login links
			$('a[href*="member/login"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Sign In', $(this).attr('href'), '#memberContentContainer', '#memberForm');
			});	

			$('a[href*="member/MemberLogin"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Sign In', $(this).attr('href'), '#memberContentContainer', '#memberForm');
			});	
			
			$('a[href*="member/logout"]').click(function(event) {
				event.preventDefault();
				memberLogOut();
			});			

			$('a[href*="member/MemberLogOut"]').click(function(event) {
				event.preventDefault();
				memberLogOut();
			});				
			
			$('a[href*="member/forgotpassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Password Reset Request', $(this).attr('href'), '#memberContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});	
			
			$('a[href*="member/MemberResetPassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Password Reset Request', $(this).attr('href'), '#memberContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});	
			
			$('a[href*="member/changepassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Change Password', $(this).attr('href'), '#memberContentContainer', '#memberForm');
			});	
			
			$('a[href*="member/MemberChangePassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Change Password', $(this).attr('href'), '#memberContentContainer', '#memberForm');
			});	
						
			$('a[href*="member/registration"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Member Registration', $(this).attr('href'), '#memberContentContainer', '#memberForm', null, function() { setupSelectableList('.selectable', '#memberLevelId'); });
			});						
			
			$('a[href*="member/MemberRegistration"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Member Registration', $(this).attr('href'), '#memberContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});				
			
			$('a[href*="member/updateprofile"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Profile', $(this).attr('href'), '#memberContentContainer', '#memberForm', function(){ window.location.href = '/index.html';}, function() { setupSelectableList('.selectable', '#memberLevelId'); });
			});		
			
			$('a[href*="member/MemberUpdateProfile"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Profile', $(this).attr('href'), '#memberContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});			
		}
			
		if(typeof(intranetEnabled) != 'undefined' && intranetEnabled) {
			// intranet login links
			$('a[href*="intranet/MemberLogin"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Sign In', '/cms-global/intranet/MemberLogin.do', '#intranetContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});
			
			$('a[href*="intranet/MemberLogOut"]').click(function(event) {
				event.preventDefault();
				employeeLogOut();
			});		
		
			$('a[href*="intranet/ResetPassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Password Reset Request', '/cms-global/intranet/MemberResetPassword.do', '#intranetContentContainer', '#memberForm', function(){ window.location.href = '/index.html'});
			});	
			
			$('a[href*="intranet/ChangePassword"]').click(function(event) {
				event.preventDefault();
				openDialogBox('Change Password', '/cms-global/intranet/MemberChangePassword.do', '#intranetContentContainer', '#memberForm', function(){ window.location.href = '/index.html';});
			});
		}
		
	}	
	setupHTMLTextareas();
	setupFileUploads();
	setupDatePickers();
	setupTextareaCounters();
	setupAutoCompletes();
	setupFormNotes();
	
	if(typeof(setFormButtonsEnabled) != 'undefined' && setFormButtonsEnabled){
		$('.formbutton').button();
	}

}

/**
 * kayaLog
 * @param text
 * @param overrideDebugModeSetting
 * @return logs to the console when available
 */
function kayaLog(text, overrideDebugModeSetting){
	if (isDebugMode()){
		console.log( text );
	}else if(overrideDebugModeSetting){
		if (typeof console != 'undefined' && typeof console.log == 'function'){
			console.log( text );			
		}
	}
}	

/**
 * pingMe()
 * @return void
 * 
 * pings the server every 10 minutes to maintain the connection
 */
function pingMe() {
	var maxPings = 6;
	var pings = 0;

	$.get(
			'/ping.jsp', 
			function(data){
				if($('#ping')){
					$('#ping').html('Last Ping Access: ' +new Date());					
				}
			},
			'XML'
		);
	
	var pingWait = setInterval(function(){
		kayaLog('pinging server');
		$.get(
				'/ping.jsp', 
				function(data){ 
					$('#ping').html('Last Ping Access: ' +new Date());
				},
				'XML'
			);

		if(pings < maxPings){
			pings ++;
		}else{
			clearInterval(pingWait);
			if(typeof(memberEnabled) != 'undefined' && memberEnabled) {
				forceMemberLogOut();
			}else if(typeof(intranetEnabled) != 'undefined' && intranetEnabled) {
				forceEmployeeLogOut();
			}else{
				pingMe();
			}
		}
	},  10 * 60 * 1000)
	
}

/**
 * isDebugMode()
 * @return boolean
 * 
 * gets the state of the debug mode variable
 */
function isDebugMode(){
	if(typeof(debugMode) != 'undefined' && debugMode) {
		if (typeof console != 'undefined' && typeof console.log == 'function'){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}


/**
 * setupFormNotes()
 * @return
 */
function setupFormNotes(){
	var formNotes;
	if($('.formnotes').length < 1){
		$('form').each(function () {
			if($(this).find('.formbuttonline').length > 0){
				kayaLog($(this));
				formNotes = $('<div class="formnotes"><div class="requiredfielddesc"><span class="required">Required Information</span></div>');
				formNotes.insertBefore($(this).find('.formbuttonline'));				
			}
		});
	}
}

/**
 * setupDatePickers()
 * @return
 * 
 * automatic conversion of class to datepickers
 * Style Class '.dateTextfield' class on a textfield will create a datepicker textfield
 */
function setupDatePickers(){
	$('.dateTextfield').each(function() {
		createDatePicker($(this));
	});
	setupDateTimePickers();	
}

/**
 * setupDateTimePickers()
 * @return
 * 
 * automatic conversion of class to datetimepickers
 * Style Class '.dateTimeTextfield' class on a textfield will create a datetimepicker textfield
 */
function setupDateTimePickers(){
	$('.dateTimeTextfield').each(function() {
		createDateTimePicker($(this));
	});
}
/**
 * setupHTMLTextareas()
 * @return
 * 
 * automatic conversion of classes to fckeditors
 * Style Class 'htmlWebPageTextarea' class on a textarea will create a web page FCKeditor (WebPage toolbar)
 * Style Class 'htmlEmailTextarea' class on a textarea will create a email FCKeditor (Email toolbar)
 * Style Class 'htmlOneTextarea' class on a textarea will create a email FCKeditor (One toolbar)
 * Style Class 'htmlBasicTextarea' class on a textarea will create a email FCKeditor (Basic toolbar)  
 */
function setupHTMLTextareas() {	
	$('.htmlWebPageTextarea').each(function() {
		convertTextAreaToFCK($(this).attr('id'), 700, 400, 'WebPage');
	});

	$('.htmlEmailTextarea').each(function() {
		convertTextAreaToFCK($(this).attr('id'), 700, 400, 'Email');
	});

	$('.htmlOneTextarea').each(function() {
		convertTextAreaToFCK($(this).attr('id'), 700, 400, 'One');
	});

	$('.htmlBasicTextarea').each(function() {
		convertTextAreaToFCK($(this).attr('id'), 480, 320, 'Basic');
	});
}

/**
 * setupFileUploads()
 * @return
 * 
 * automatic conversion of classes to file uploads
 * Style Class 'uploadFormField' on a field (suggest hidden) will convert it to a file upload field.
 */
function setupFileUploads() {
	$('.uploadFormField').each(function() {
		if($(this).attr('id') != 'fileUploaded'){
			createFileUpload($(this));			
		}
	});
}

/**
 * setupTextareaCounters
 * @return
 * 
 * automatic conversion of classes to textareas with counters
 * Style Class 'needscounter' on a textarea field will be converted to include a counter
 */
function setupTextareaCounters() {
	$('.needscounter').each(function() {
		createTextareaCounter($(this));
	})
}

/**
 * setupAutoCompletes()
 * @return
 * automatic conversion of classes to auto completes
 * Style Class 'autoCompleteSelect' on a select list to turn it into an autocomplete
 */
function setupAutoCompletes() {
	$('.autoCompleteSelect').each(function() {
		createAutoComplete($(this));
	})
	
//	$('select').each(function() {
//		if($(this).size() >= 100){
//			createAutoComplete($(this));
//		}
//	});
}

function setupSelectableList(field, targetField){
	$(field).selectable({
		selected: function(event, ui){
			$(targetField).val(''+ui.selected.id);
		}
	});	
}

/**
 * convertFieldsetsToTabs()  BETA CODE
 * @return
 * 
 * automatic conversion of classes to tabs
 * Style Class 'tabbed' on group of fieldsets will convert each fieldset into a seprate tab.
 */
function convertFieldsetsToTabs(fieldId, selected){
	$('.tabbed').wrapAll('<div id="' + fieldId + '" class="tabsContainer"></div>');
	$('.formnotes').appendTo($('#'+fieldId));
	$('.formbuttonline').appendTo($('#'+fieldId));
	var checkExists = setInterval(function() {
		if($('#'+fieldId).html() != 'undefined'){
			clearInterval(checkExists);
			$('<ul></ul>').insertBefore('.tabbed:first');	
			var checkExistsAgain = setInterval(function() {
				if($('#'+fieldId +' > ul') != 'undefined'){
					clearInterval(checkExistsAgain);
					var tabIndex = 0;
					$('.tabbed').each(function() {
						$(this).wrap('<div id="tab_' + fieldId + '_' + tabIndex +'"></div>');	
						$('#'+fieldId +' > ul').append('<li><a href="#tab_' + fieldId + '_' + tabIndex+'">'+$(this).find("legend").text()+'</a></li>');
						$(this).removeClass('tabbed');
						tabIndex++;
						$(this).show();
					});
					$('#'+fieldId).tabs();
					
					if(selected != null){
						$('#'+fieldId).tabs('select', selected);						
					}
				}
			}, 50);
		}
	}, 50);
}

/**
 * convertTextAreaToFCK(textareaId, width, height, toolbarSet )
 * @param textareaId - the id of the textarea to convert
 * @param width - the width of the FCKeditor
 * @param height - the height of the FCKeditor
 * @param toolbarSet - the associated toolbar set to use
 * @return void
 * 
 * converts a given textarea to an FCKeditor
 */
function convertTextAreaToFCK(textareaId, width, height, toolbarSet ) {
	
	if(typeof(FCKeditor) != 'undefined'){
		var fckEditor = null;
		fckEditor = new FCKeditor(textareaId);
		fckEditor.BaseBath = "/FCKeditor/editor/";
		fckEditor.Height = height;
		fckEditor.Width = width;
		fckEditor.ToolbarSet = toolbarSet;
		fckEditor.ReplaceTextarea();

		// special handling for IE (AGAIN)
		if(jQuery.browser.msie == true){
			if(typeof(FCKeditorAPI) == 'undefined') {
				var isReady = setInterval(function() {	
					if(typeof(FCKeditorAPI) != 'undefined'){
						var editorInstance = FCKeditorAPI.GetInstance(textareaId);
						if(typeof(editorInstance) != 'undefined'){
							editorInstance.SetData($('#'+textareaId).clone().val());
							clearInterval(isReady);	
						}
					}
				}, 500);
			}

			$("#" + textareaId).parents('form:first').submit(function(event){
				var editorInstance = FCKeditorAPI.GetInstance(textareaId);
				if(typeof(editorInstance) != 'undefined'){
					var editorHTML = editorInstance.GetHTML(false);
					$("#" + textareaId).html(editorHTML);
					editorInstance.UpdateLinkedField();
					var isReady = setInterval(function() {
						if($("#" + textareaId).html() == editorHTML){
							clearInterval(isReady);
							return true;
						}
					}, 250);
				}
			});
		}
	}
}

/**
 * createDatePicker(filed)
 * @param filed
 * @return void
 * 
 * using the jQuery elemnet field create a datepicker
 */
function createDatePicker(field){
	$(field).datepicker({
		changeMonth: true,
		changeYear: true,
		showButtonPanel: true
	});
}

/**
 * createFileUpload(field)
 * @param field
 * @return
 * 
 * creates a file upload field with progress. and adds it just before the field passed.
 */
function createFileUpload(field) {
	$(field).attr('id', 'fileUploaded');
	$('<iframe id="file_upload" name="file_upload" src="/cms-global/fileupload/fileupload.form" frameborder="0" width="435px" height="55px" scrolling="no" class="fileUploadIFrame"></iframe>').insertBefore($(field));	
}

function createTextareaCounter(field){
	var maxChars = $(field).attr('maxlength');
	
	if(maxChars == "" || maxChars == "undefined"){
		maxChars = 255;
	}
	
	$(field).jqEasyCounter({
	    'maxChars': maxChars,
	    'maxCharsWarning': maxChars - 10,
	    'msgFontSize': '12px',
	    'msgFontColor': '#000',
	    'msgFontFamily': 'Arial',
	    'msgTextAlign': 'right',
	    'msgWarningColor': '#F00',
	    'msgAppendMethod': 'insertAfter'              
	});	
}

function createAutoComplete(field){
	$(field).kayacombo();
}

/**
 * getWebsiteBaseURL()
 * @return String
 * 
 * returns the base URL for the current website. 
 */
function getWebsiteBaseURL(){
	 var websiteBaseURL = "http://" + window.location.host;	
	 return websiteBaseURL;
}

/**
 * pause(millis)
 * @param millis
 * @return void
 * 
 * pauses for a give number of milliseconds
 */
function pause(millis) {
	 var date = new Date();
	 var curDate = null;
	 
	 do { 
	  curDate = new Date(); 
	 } while(curDate-date < millis);
}
/**
 * ajaxGetPageData(URL)
 * @param URL
 * @return Object
 * 
 * returns the returned web page data object of the ajax call.
 */
function ajaxGetPageData(URL){
	var outputObj;
	
	jQuery.ajax({
		type: "POST",
		url: URL,
		dataType: "html",
		cache: false,
		async:false,
		beforeSend: function(){
			return showSend(URL);
		},
		success: function(data, textStatus, xhr) {
			outputObj = data;
		},
		error: function(response, textStatus, errorThrown) {
			var msg = "Error retreiving Web Page from: "+URL+"\n";
			alert(msg + textStatus + " " + errorThrown);
		}
	});
	
	return outputObj;
}

/**
 * ajaxGetXmlData(URL)
 * @param URL
 * @return Object
 * 
 * returns the returned xml data object of the ajax call.
 */
function ajaxGetXmlData(URL){
	var outputObj;
	
	jQuery.ajax({
		type: "POST",
		url: URL,
		dataType: "xml",
		cache: false,
		async:false,
		beforeSend: function(){
			return showSend(URL);
		},
		success: function(data, textStatus, xhr) {
			outputObj = data;
		},
		error: function(response, textStatus, errorThrown) {
			var msg = "Error retreiving XML from: "+URL+"\n";
			alert(msg + textStatus + " " + errorThrown);
		}
	});
	
	return outputObj;
}

/**
 * ajaxGetScriptData(URL)
 * @param URL
 * @return Object
 * 
 * returns the returned text data object of the ajax call.
 */
function ajaxGetScriptData(URL){
	var outputObj;
	
	jQuery.ajax({
		type: "POST",
		url: URL,
		dataType: "script",
		cache: false,
		async:false,
		beforeSend: function(){
			return showSend(URL);
		},
		success: function(data, textStatus, xhr) {
			outputObj = data;
		},
		error: function(response, textStatus, errorThrown) {
			var msg = "Error retreiving Script Data from: "+URL+"\n";
			alert(msg + textStatus + " " + errorThrown);
		}
	});
	
	return outputObj;
}

/**
 * getScript(data, URL, contentContainer)
 * @param data
 * @param URL
 * @return void
 * 
 * gets the script data from the called page and loads it into the DOM.
 */
function getScript(data){
	try{
		var re = /((<[\s\/]*script\b[^>]*>)([\s\S]*?)(<\/script>))/gim;
		var match;
		var script = '';
		while(match = re.exec(data)) {

			if(match[3] != '' && match[3].indexOf('document.write') < 0){
				script = match[3];
				eval(script);
				if(isDebugMode()){
					alert("Scripts found in page :\n"+script);
				}
			}
		}
	}catch(error){
		if(isDebugMode()){
			alert(error.message);
		}
	}
}

/**
 * @depends jQuery, jQuery UI, jquery.form, dialogbox-jquery
 * kayaAdminDialog(elementId, title, URL, contentContainer, formId, callBack, onOpen, confirmClose, onClose)
 * @param elementId
 * @param title
 * @param URL
 * @param contentContainer
 * @param formId
 * @param callBack
 * @param onOpen
 * @param confirmClose
 * @param onClose
 * @return
 * 
 * general overlay - must use elementId, title, URL, and contentContainer.
 * 
 * elementId - the element to attach the dialog to.
 * title - the title that you want at the top of the dialog (the header)
 * contentContainer - is the ID of the container where the requested content resides (css format)
 * URL - the URL you wish to bring into the overlay dialog
 * 
 * formId - the ID of the form tag for processing the form submission inside the popup dialog (css format)
 * this is used to ensure that the form action does not redirect away from the popup dialog.
 * 
 * callBack FUNCTION - pass in a function as function() { ....script here.... } this will be called when the dialog submit cycle completes
 * onOpen FUNCTION - pass in a function as function() { ....script here.... } this will be called when the dialog is opened.
 * confirmClose STRING - pass in a string, calls a confirmation before the dialog closes. Takes a string and puts it in the confirmation dialog.
 * onClose FUNCTION - pass in a function as function() { ....script here.... } this will be called when the dialog closes
 */
function kayaDialog(elementId, title, URL, contentContainer, formId, callBack, onOpen, confirmClose, onClose){
	$(elementId).kayadialog({
			title : title, 
			url: URL, 
			targetElementId: contentContainer, 
			targetFormElementId: formId,
			width: 650,
			resizable: false,
			disableFormButtonOnSubmit: true,
			debugMode: isDebugMode(),
			beforeOpen: function(event,data) {
				kayaLog("kayaDialog beforeOpen");
				kayaLog(data);
				showSend(data.url);
				return true;
			},
			afterOpen: function(event, data){
				kayaLog("kayaDialog afterOpen");
				kayaLog(data);
				if(onOpen != null && onOpen != ""){
					onOpen();
				}
			},
			loadContents: function(event, data) {
				kayaLog("kayaDialog loadContents");
				kayaLog(data);
			},
			pageLoaded: function(event, data){
				kayaLog("kayaDialog pageLoaded");
				kayaLog(data);
				initPage();
			},
			validateInput: function(formData, jqForm, options) {
				return validateInput(formData, jqForm, options);
			},
			onFormReturn: function(event, data) {
				kayaLog("kayaDialog onFormReturn");
				kayaLog(data);		
				if(onOpen != null && onOpen != ""){
					onOpen();
				}
			},
			afterSubmit: function(event, data) {
				kayaLog("kayaDialog afterSubmit");
				kayaLog(data);
				if(callBack != null && callBack != ""){
					callBack();
				}				
			},
			beforeClose: function(event, data) {
				kayaLog("kayaDialog beforeClose");
				kayaLog(data);
				if(confirmClose != null && confirmClose != ""){
					return confirm(confirmClose);
				}
			},
			close: function(event, data) {
				kayaLog("kayaDialog close");
				kayaLog(data);
				if(onClose != null && onClose != ""){
					onClose();
				}
			}			
	});
	$(elementId).kayadialog('open');
}

/**
 * closeKayaDialog()
 * @return none
 * 
 * closes any open kayadialog
 */
function closeKayaDialog(onDialogClose){
	var $dialog = $('div:data(kayadialog)');
	if($dialog.length){
		$dialog.each(function() {
			$(this).kayadialog('close');			
		});
	}
	if(onDialogClose != null && typeof(onDialogClose) != 'undefined'){
		onDialogClose();
	}
}

/**
 * openDialogOverlay(title, siteUrl, containerId, formId)
 * @param title
 * @param siteUrl
 * @param containerId
 * @param formId
 * @return
 * 
 * general overlay - must use headerText, siteURL, and containerId. formId is optional
 * 
 * headerText is that you want at the top of the dialog (the header)
 * containerId is the ID of the container where the requested content resides
 * siteURL is the URL you wish to bring into the overlay dialog
 * formId is the ID of the form tag for processing the form submission inside the popup dialog
 * this is used to ensure that the form action does not redirect away from the popup dialog.
 * 
 * @deprecated
 * USE openDialogBox(title, siteUrl, containerId, formId, callBack, onDialogReady, confirmClose)
 */
function openDialogOverlay(title, URL, contentContainer, formId){
	openDialogBox(title, URL, '#'+contentContainer, '#'+formId);
}

/**
 * openDialogBoxOverlay(title, siteUrl, containerId, formId)
 * @param title
 * @param siteUrl
 * @param containerId
 * @param formId
 * @return
 * 
 * general overlay - must use headerText, siteURL, and containerId. formId is optional
 * 
 * headerText is that you want at the top of the dialog (the header)
 * containerId is the ID of the container where the requested content resides
 * siteURL is the URL you wish to bring into the overlay dialog
 * formId is the ID of the form tag for processing the form submission inside the popup dialog
 * this is used to ensure that the form action does not redirect away from the popup dialog.
 * 
 * @deprecated
 * USE openDialogBox(title, siteUrl, containerId, formId, callBack, onDialogReady, confirmClose)
 */
function openDialogBoxOverlay(title, URL, contentContainer, formId){
	openDialogBox(title, URL, '#'+contentContainer, '#'+formId);
}

/**
 * openDialogBox(title, URL, containerId, formId, callBack, onDialogReady, confirmClose)
 * @param title
 * @param URL
 * @param containerId
 * @param formId
 * @param callBack
 * @param onDialogReady
 * @param confirmClose  
 * @return
 * 
 * general overlay - must use title, URL, and containerId. formId is optional
 * 
 * headerText is that you want at the top of the dialog (the header)
 * containerId is the ID of the container where the requested content resides (css format i.e. #id)
 * siteURL is the URL you wish to bring into the overlay dialog
 * formId is the ID of the form tag for processing the form submission inside the popup dialog (css format i.e. #id )
 * this is used to ensure that the form action does not redirect away from the popup dialog.
 * 
 * callBack pass in a function as function() { ....script here.... } this will be called when the dialog cycle completes
 * onDialogReady pass in a function as function() { ....script here.... } this will be called when the dialog is populated.
 * confirmClose String of test to display when confirming the closure of the dialog.
 * 
 * @deprecated
 * USE kayaDialog(title, URL, contentContainer, formId, callBack, onDialogReady, confirmClose, callBack);
 */
function openDialogBox(title, URL, contentContainer, formId, callBack, onDialogReady, confirmClose){
	kayaDialog('#popupDialogBoxContainer', title, URL, contentContainer, formId, callBack, onDialogReady, confirmClose, callBack);
}

/**
 * @deprecated
 * USE closeDialogBox()
 **/
function hideDialogOverlay(){
	closeDialogBox();
}

/**
 * @deprecated
 * USE closeDialogBox()
 **/
function hideDialogBoxOverlay(){
	closeDialogBox();
}
//
///**
// * closeDialogBox()
// * 
// * closes open dialog box.
// **/
//function closeDialogBox(){
//	$('#popupDialogBoxContainer').dialog('close');
//}

/**
 * closeDialogBox()
 * 
 * closes open dialog box.
 **/
function closeDialogBox(onDialogClose){
	$('#popupDialogBoxContainer').kayadialog('close');
	if(onDialogClose != null){
		onDialogClose();
	}
}

/**
 * @deprecated
 * USE closeDialogBox()
 **/
function hideDialogOverlay(){
	closeDialogBox();
}

/**
 * @deprecated
 * USE closeDialogBox()
 **/
function hideDialogBoxOverlay(){
	closeDialogBox();
}

/**
 * closeDialogBox()
 * 
 * closes open dialog box.
 **/
function closeDialogBox(onDialogClose){
	$('#popupDialogBoxContainer').dialog('close');
	if(onDialogClose != null){
		onDialogClose();
	}
}

/**
 * getDialogBoxWidth(formId)
 * @param formId
 * @return Integer
 * 
 * returns the width to set the for the dialog box.
 */
function getDialogBoxWidth(formId){

	var width = 715;
	
	if(formId != null && formId != ''){
		var divWidth = $('#popupDialogBoxContainer').find(formId).parent().css('width');

		if(divWidth != 'auto' && divWidth != null && typeof(divWidth) != 'undefined'){
			width = parseInt(divWidth);
			width += 35;				
		}else if(divWidth == 'auto' || typeof(divWidth) == 'undefined'){
			divWidth = $('#popupDialogBoxContainer').find(formId).outerWidth(true);
			
			width = parseInt(divWidth);
			width += 35;
		}
	}
	
	if(jQuery.browser.msie == true){
		width += 35;
	}
	
	return width;
}

/**
 * comfirmDialogBox(title, confirmationHTML, yesFunction, noFunction)
 * @param title
 * @param confirmationHTML
 * @param yesFunction
 * @param noFunction
 * @return void
 * 
 * opens a dialog with yes and no functions - calls the yesFunction or noFunction depending on choice.
 */
function comfirmDialogBox(title, confirmationHTML, yesFunction, noFunction) {
	
	$('#confirmDialogBoxContainer').html('<span style="text-align:center;">'+confirmationHTML+'</span>');
	$('#confirmDialogBoxContainer').dialog({ 
		autoOpen: false,
		modal: true,
		resizable: false,
		hide: 'blind',
		title: title,
		buttons: {
			'No': function() {
				$(this).dialog('close');
				noFunction();
			},		
			'Yes': function() {
				$(this).dialog('close');
				yesFunction();
			}
		},
	    open: function() {
	      $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus(); 
	    }
	});
	
	$('#confirmDialogBoxContainer').dialog('open');	
}

//logs out a user - with confirmation dialog
function employeeLogOut() {
	var url = "/cms-global/intranet/MemberLogOut.do";
	
	$('#messages').html('<p>Are you sure you wish to log out?</p>');
	$('#messages').dialog({ 
		autoOpen: false,
		modal: true,
		resizable: false,
		hide: 'blind',
		title: 'Employee Log Out',
		buttons: {
			'No': function() {
				$(this).dialog('close');
			},		
			'Yes': function() {
				$(this).dialog('close');
				jQuery.ajax({
					type: "POST",
					url: url,
					dataType: "html",
					success: function(data, textStatus) {
						window.location.href = '/index.html?'+new Date().getTime();
					},
					error: function(response, status, errorThrown) {
						var msg = "Error retreiving Web Page from: "+url+"\n";
						alert(msg + errorThrown.status + " " + errorThrown.statusText);
					}
				});
			}
		},
	    open: function() {
	      $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus(); 
	    }
	});
	
	$('#messages').dialog('open');	
}


//logs out a user - with confirmation dialog
function forceEmployeeLogOut() {
	kayaLog("forceEmployeeLogOut() called");	
	var timeout = 60;
	confirmationHTML = "You have been idle for an hour now, you will be automatically logged out in <span id=\"timer\"><</span> seconds";
	
	var url = "/cms-global/intranet/MemberLogOut.do";
	
	$('#messages').html('<p>'+confirmationHTML+'</p>');
	$('#messages').dialog({ 
		autoOpen: false,
		modal: true,
		resizable: false,
		hide: 'blind',
		title: 'Employee Log Out',
		buttons: {
			'No': function() {
				$(this).dialog('close');
				clearInterval(timer);
				pingMe();
			},		
			'Yes': function() {
				$(this).dialog('close');
				jQuery.ajax({
					type: "POST",
					url: url,
					dataType: "html",
					success: function(data, textStatus) {
						window.location.href = '/index.html?'+new Date().getTime();
					},
					error: function(response, status, errorThrown) {
						var msg = "Error retreiving Web Page from: "+url+"\n";
						alert(msg + errorThrown.status + " " + errorThrown.statusText);
					}
				});
			}
		},
	    open: function() {
	      $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus(); 
	    }
	});
	
	$('#messages').dialog('open');	
	var timer = setInterval(function() {
		timeout--;
		$('#messages').find('#timer').html(timeout);
		
		if(timeout == 0){
			window.location.href='/cms-global/intranet/MemberLogOut.do';
		}
		
	}, 1000);	
}

//logs out a user - with confirmation dialog
function memberLogOut() {
	var url = "/cms-global/member/MemberLogOut.do";
	
	$('#messages').html('<p>Are you sure you wish to log out?</p>');
	$('#messages').dialog({ 
		autoOpen: false,
		modal: true,
		resizable: false,
		hide: 'blind',
		title: 'Member Log Out',
		buttons: {
			'No': function() {
				$(this).dialog('close');
			},		
			'Yes': function() {
				$(this).dialog('close');
				jQuery.ajax({
					type: "POST",
					url: url,
					dataType: "html",
					success: function(data, textStatus) {
						window.location.href = '/index.html?'+new Date().getTime();
					},
					error: function(response, status, errorThrown) {
						var msg = "Error retreiving Web Page from: "+url+"\n";
						alert(msg + errorThrown.status + " " + errorThrown.statusText);
					}
				});
			}
		},
	    open: function() {
	      $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus(); 
	    }
	});
	
	$('#messages').dialog('open');	
}


//logs out a user - with confirmation dialog
function forceMemberLogOut() {
	kayaLog("forceMemberLogOut() called");
	var timeout = 60;
	confirmationHTML = "You have been idle for an hour now, you will be automatically logged out in <span id=\"timer\"><</span> seconds";
	
	var url = "/cms-global/member/MemberLogOut.do";
	
	$('#messages').html('<p>'+confirmationHTML+'</p>');
	$('#messages').dialog({ 
		autoOpen: false,
		modal: true,
		resizable: false,
		hide: 'blind',
		title: 'Member Log Out',
		buttons: {
			'No': function() {
				$(this).dialog('close');
				clearInterval(timer);
				pingMe();
			},		
			'Yes': function() {
				$(this).dialog('close');
				jQuery.ajax({
					type: "POST",
					url: url,
					dataType: "html",
					success: function(data, textStatus) {
						window.location.href = '/index.html?'+new Date().getTime();
					},
					error: function(response, status, errorThrown) {
						var msg = "Error retreiving Web Page from: "+url+"\n";
						alert(msg + errorThrown.status + " " + errorThrown.statusText);
					}
				});
			}
		},
	    open: function() {
	      $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus(); 
	    }
	});
	
	$('#messages').dialog('open');	
	var timer = setInterval(function() {
		timeout--;
		$('#messages').find('#timer').html(timeout);
		
		if(timeout == 0){
			window.location.href='/cms-global/member/MemberLogOut.do';
		}
		
	}, 1000);	
}

/**
 * validateInput(formData, jqForm, options)
 * @param formData
 * @param jqForm
 * @param options
 * @return boolean
 * 
 * this function can be used to validate user input in dialogs prior to submission.
 */
function validateInput(formData, jqForm, options) { 

	var host = getWebsiteBaseURL();
	var formElement = jqForm[0];
	var valid = true;
	 
	// here we can do some validation if needed.
	if(isDebugMode()) {
		valid = showSubmit(formData, jqForm, options);
	}
	
	if(valid == false){
		$(formElement).find('input:submit').removeAttr('disabled');
	}	
	return valid;

}

//function to get the post data from an ajaxSubmit call
//only works if debugMode is enabled
function showSubmit(formData, jqForm, options) {
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 

    queryString = queryString.replace(/&/g, "\r\n");
    	    
    return confirm('Do you wish to submit the following? \n\n' + queryString); 
}

//function to get the post data from an ajaxSubmit call
//only works if debugMode is enabled
function showSend(siteURL) { 
	
	if(isDebugMode()) {
	    // jqForm is a jQuery object encapsulating the form element.  To access the 
	    // DOM element for the form do this: 
	    // var formElement = jqForm[0]; 
		siteURL = siteURL.replace("?", "\r\n");
	    siteURL = siteURL.replace(/&/g, "\r\n");
	    
	    return confirm('Do you wish to submit the following? \n\n' + siteURL); 
	}else{
		return true;
	}
}

// ALERTS
/**
 * alertPopupDialogOverlay(headerText, siteUrl, containerId)
 * @param headerText
 * @param siteUrl
 * @param containerId
 * @return void
 * 
 * Dialog overlay for Alerts ONLY, specifically setup to handle reading of, and managing 
 * Alerts
 */
function alertPopupDialogOverlay(headerText, siteUrl, containerId){
	openDialogBox(headerText, siteUrl, '#'+containerId);
}

/**
 * getAlertsDiv(alertsContainerId, showRead)
 * @param alertsContainerId
 * @param showRead
 * @return void
 * 
 * Gets the list of alerts for the current user (member, account, admin) and places them
 * in the specified container
 * 
 * alertsContainerId is the id of the content container for the alerts
 * showRead boolean to indicate rather to show read alerts or not
 */
function getAlertsDiv(alertsContainerId, showRead) {
	var siteUrl = "/cms-global/alert/GetAlerts.do" + 
	"?showRead="+showRead;

	jQuery.ajax({
		type: "GET",
		url: siteUrl, 
		dataType: "html",
		success: function(data, textStatus) {	
			var alertsData = $(data).find('#alertsContent').clone();
			$('#'+alertsContainerId).html(alertsData);
		},
		error: function(response, status, errorThrown) {
			alert(response.status + " " + status + " " + errorThrown);
		}
	});
}

/**
 * updateAlertsDiv(alertId, action, alertsContainerId, showRead)
 * @param alertId
 * @param action
 * @param alertsContainerId
 * @param showRead
 * @return void
 * 
 * performs a requested action and returns a new list of alerts
 * 
 * alertId the id of the alert to perform the action on
 * action the action to perform
 * alertsContainerId is the id of the content container for the alerts
 * showRead boolean to indicate rather to show read alerts or not
 */
function updateAlertsDiv(alertId, action, alertsContainerId, showRead) {
	var siteUrl = "/cms-global/alert/UpdateAlerts.do" +
	"?showRead=" + showRead + 
	"&action=" + action +
	"&alertId=" + alertId;
	
	jQuery.ajax({
		type: "GET",
		url: siteUrl, 
		dataType: "html",
		success: function(data, textStatus) {	
			var alertsData = $(data).find('#alertsContent').clone();
			$('#'+alertsContainerId).html(alertsData);
		},
		error: function(response, status, errorThrown) {
			alert(response.status + " " + status + " " + errorThrown);
		}
	});
}	

/**
 * getAlertsPopup(formId, alertsContainerId, showRead)
 * @param formId
 * @param alertsContainerId
 * @param showRead
 * @return void
 * 
 * opens the alert popup dialog overlay
 * 
 * headerText is what you want at the top of the dialog (the header)
 * alertsContainerId is the id of the content container for the alerts
 * showRead boolean to indicate rather to show read alerts or not
 */
function getAlertsPopup(formId, alertsContainerId, showRead) {
	var siteUrl = "/cms-global/alerts/GetAlerts.do?showRead="+showRead;
	alertPopupDialogOverlay('Read Alert', siteUrl, alertsContainerId)
}

/**
 * alertTakeAction(alertId, actionURL)
 * @param alertId
 * @return void
 * 
 * alertId the id of the alert to perform the action on.
 * actionURL the URL to go to, for taking action on this alert.
 */
function alertTakeAction(alertId, actionURL) {
	var siteUrl = "/cms-global/alert/UpdateAlerts.do" +
	"?action=takeaction" +
	"&alertId=" + alertId;
	
	jQuery.ajax({
		type: "GET",
		url: siteUrl, 
		dataType: "html",
		success: function(data, textStatus) {
			window.location = actionURL;
		},
		error: function(response, status, errorThrown) {
			alert(response.status + " " + status + " " + errorThrown);
		}
	});
}

/**
 * initPasswordValidation(passwordGuidelines, passwordRegEx)
 * @param passwordGuidelines
 * @param passwordRegEx
 * @return none
 * Sets up the password validation and strength
 */
function initPasswordValidation(passwordGuidelines, passwordRegEx){
	kayaLog("called initPasswordValidation");
	$('#loginPassword').pstrength({
		minChar: 8,
		minCharText : passwordGuidelines,
		debug: false
	});

	$('#loginPassword').pstrength.addRule('kayaPassword', 
		function (word, score) {
			if(word.length > 0){
				if(!word.match(passwordRegEx)){
					$('#loginPassword').removeClass("passwordValid").addClass("passwordInvalid");
				}else{
					$('#loginPassword').removeClass("passwordInvalid").addClass("passwordValid");					
				}
			}else{
				$('#loginPassword').removeClass("passwordInvalid").removeClass("passwordValid");
			}
			return word.match(passwordRegEx) && score;
		}, 
		0, 
		true
	);	
}

/**
 * checkPasswordsMatch()
 * @return none
 * Sets up the password / confirm password matching
 */
function checkPasswordsMatch(){
	if($('#passwordConfirmInfo').length < 1){
		$('<div class="passwordConfirmInfo" id="passwordConfirmInfo"></div>').insertAfter($('#loginPasswordConfirmed'));
	}
	if($('#loginPasswordConfirmed').val().length > 0){
		if($('#loginPassword').val() != $('#loginPasswordConfirmed').val()){
			$('#loginPasswordConfirmed').removeClass("passwordValid").addClass("passwordInvalid");
			$('#passwordConfirmInfo').html('<div class="passwordNotConfirmed"></div><div class="passwordConfirmInfoText">Passwords Do Not Match</div>');
		}else{
			$('#loginPasswordConfirmed').removeClass("passwordInvalid").addClass("passwordValid");	
			$('#passwordConfirmInfo').html('<div class="passwordConfirmed"></div><div class="passwordConfirmInfoText">Passwords Match</div>');
		}
	}else{		
		$('#loginPasswordConfirmed').removeClass("passwordInvalid").removeClass("passwordValid");
	}
}

/**
 * updateDisplayName()
 * @return none
 * Auto-Fill of the display name field based on first and last names
 */
function updateDisplayName(){
	kayaLog("called updateDisplayName");
	var firstName = $("#firstName").val();
	var lastName = $("#lastName").val();

	if(firstName != ""){
		$("#displayName").val(firstName +" " + lastName);
	}
}

/**
 * updateLoginName()
 * @return none
 * Auto-Fill of the login name based on the email address
 */
function updateLoginName(){
	kayaLog("called updateLoginName");
	var email = $('#email').val();
	if(email != ""){
		$("#loginName").val(email);
	}	
}

/**
 * checkFieldAvailable(searchURL, fieldName, fieldId, searchField)
 * @param searchURL
 * @param fieldName
 * @param fieldId
 * @param searchField
 * @return none
 * Checks if the entered value is already taken. This function is used only during registration.
 */
function checkFieldAvailable(searchURL, fieldName, fieldId, searchField, additionalCheckFunction){
	kayaLog("called checkFieldAvailable");
	var fieldValue = $('#'+fieldId).val();
	var url = searchURL+"?"+searchField+"="+fieldValue;
	var additiionalCheck = true;
	$.post(url, function(data){
		var jsonData = $.parseJSON(data);
		if(jsonData.response_code == "Success" && jsonData.response_data.length > 0){
			if(additionalCheckFunction != null && additionalCheckFunction != ""){
				additionalCheck = additionalCheckFunction(jsonData);
			}
			if(additionalCheck){
				$('#'+fieldId).css('border-color', 'red');
				if($('#'+fieldId+'Taken').length < 1){
					$('<div class="fielderror" id="'+fieldId+'Taken">That '+fieldName.charAt(0).toUpperCase() + fieldName.slice(1)+' is already taken, please choose a different '+fieldName+'</div>').insertAfter($('#'+fieldId));
				}				
			}else{
				$('#'+fieldId).css('border-color','#D1D1D1'); 
				$('#'+fieldId+'Taken').remove();				
			}
		}else{
			$('#'+fieldId).css('border-color','#D1D1D1'); 
			$('#'+fieldId+'Taken').remove();
		}	
	});
}

/**
 * setupTermsScrollCheck()
 * @return none
 * activates the terms agree checkbox upon full scroll of terms information
 */
function setupTermsScrollCheck(){
	kayaLog("called setupTermsScrollCheck", true);
	if($('#memberTermsData')[0].scrollHeight > 0){
		$('#memberTermsData').scroll(function(){
			if($('#memberTermsData').scrollTop() >= $('#memberTermsData').height()){
				$('#agreeToTerms').removeAttr('disabled');
			}
		});		
	}else{
		$('#agreeToTerms').removeAttr('disabled');		
	}
}

function getNewCaptcha(){
	kayaLog("called getNewCaptcha", true);	
	$('#captchaImage').attr("src","/jcaptcha.jpg");
}
