var glbElem;
var hk_timer;
var hk_searching;
var editorObj;
var error_color = 'red';

// Reorder General Lists
$(document).ready(function () 
{
        //  Header Sort function
        $('.span_header').click( function() {
	
			//  Reset the pagination pages
			$('.pagination-page').removeClass('active-page');
			$('#page_1').addClass('active-page');
	
            var field = $(this).attr('id');
            var table = $('#table').attr('value');
            $('#'+table+'_scrollDiv').scrollTop = 0;
            $('#'+table+'_page').value = 1;
			var order = 'ASC';
            openIndicator();
            
			$('.span_header').removeClass('asc').removeClass('desc').addClass('none');
			$('span_header').attr('sort_order', 'none');
			switch($(this).attr('sort_order')){
				case 'desc':
				case 'none':
					$(this).removeClass('none').addClass('asc');
					$(this).attr('sort_order', 'asc');
					break;
				case 'asc':
					order = 'DESC';
					$(this).removeClass('none').addClass('desc');
					$(this).attr('sort_order', 'desc');
					break;
			}
			xajax_reorder(field, order);
		});
		
		bindPaging();
});

//  Bind the paging events
function bindPaging(){
	
	//  Get the selected page
	$('.pagination-page').bind('click', function() {

		$('.pagination-page').removeClass('active-page');
		$(this).addClass('active-page');

		var selected = $(this).attr('id');
		selected = selected.substring(selected.indexOf('_')+1);
		$('#current_page_id').attr('value', selected);
		xajax_getSpecificPage(selected);
	});
	
}

//  Creates the trim() prototype function
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//  Load the CK Editor with Data
function loadEditor(c_text){
	editorObj.setData(c_text);
}

//  Initialize the CK Editor
function initializeEditor(e_elem, e_toolbar, e_width, e_height){
	editorObj = CKEDITOR.replace(e_elem,{
		toolbar: e_toolbar,
		width: e_width,
		height: e_height,
		on : {
			instanceReady : function( ev )
	            {
	                // Output paragraphs as <p>Text</p>.
	                this.dataProcessor.writer.setRules( 'p',
	                    {
	                        indent : false,
	                        breakBeforeOpen : false,
	                        breakAfterOpen : false,
	                        breakBeforeClose : false,
	                        breakAfterClose : false
	                    });
	            }
		}
	});
}

//  Initialize the CK Finder
function initializeFinder(){
	CKFinder.SetupCKEditor(editorObj, './');
}

//  Process the upload callback 
function processCallbackResponse(iframeId, uploadCallback){

	if (iframeId.detachEvent)  
		iframeId.detachEvent("onload", uploadCallback);  
	else  
		iframeId.removeEventListener("load", uploadCallback, false);

	// Message from server...  
	if (iframeId.contentDocument)
		response = iframeId.contentDocument.body.innerHTML;  
	else if (iframeId.contentWindow)
		response = iframeId.contentWindow.document.body.innerHTML;  
	else if (iframeId.document) 
		response = iframeId.document.body.innerHTML;  
	
	// Del the iframe...  
	setTimeout('iframeId.parentNode.removeChild(iframeId)', 3000);
	
	return response;
}

//  Form to be processed, action php, message div, processor id, completion msg
function fileUpload(form, action_url, div_id)  
{  
//	openIndicator();
	
	// Create the iframe...  
	var iframe = document.createElement("iframe");  
	iframe.setAttribute("id","upload_iframe");  
	iframe.setAttribute("name","upload_iframe");  
	iframe.setAttribute("width","0");  
	iframe.setAttribute("height","0");  
	iframe.setAttribute("border","0");  
	iframe.setAttribute("style","width: 0; height: 0; border: none;");  
  
	// Add to document...  
	form.parentNode.appendChild(iframe);  
	window.frames['upload_iframe'].name="upload_iframe";  
  
	iframeId = document.getElementById("upload_iframe");  
	
	/* TODO: Revise function to take callback function as a parameter  */
	var eventHandler = function() {
		uploadCallback(div_id, iframeId);
	}
  
	if (iframeId.addEventListener)  
		iframeId.addEventListener("load", eventHandler, true);  
	if (iframeId.attachEvent)  
		iframeId.attachEvent("onload", eventHandler);  
  
	// Set properties of form...  
	form.setAttribute("target","upload_iframe");  
	form.setAttribute("action", action_url);  
	form.setAttribute("method","post");  
	form.setAttribute("enctype","multipart/form-data");  
	form.setAttribute("encoding","multipart/form-data");  
  
	document.getElementById(div_id).innerHTML = "Saving...";  

	// Submit the form...  
	form.submit();	
}

//  Converts the parameter that's been passed in into a URL friendly name
function convertToURL(name){

	//  Trim off the white space if there is any
	name = name.trim();
	name = name.toLowerCase();
	
	//  Change out some of the special characters
	name = name.replace('&', 'and');
	name = name.replace('%', 'percent');
	name = name.replace('@', 'at');
	name = name.replace('+', 'plus');
	name = name.replace('=', 'equals');
	
	//  Perform Regex to clean up name
	var regex = /[^0-9 a-zA-Z-]+/g;
	name = name.replace(regex,'');
	name = name.replace(/\s+/g,'-');
	
	return name;
}

//  Opens the processing indicator
function openIndicator(){
	$.blockUI({ message: $('#indicator') }); 
}

//  Closes the processing indicator
function closeIndicator(){
	$.unblockUI();
	hk_searching = false;
}

function scrolling(elem){
	page = document.getElementById(elem+'_page');
	cPage = page.value-0;
	mPages = document.getElementById(elem+'_mpages').value-0;
	var max = document.getElementById(elem+'_scrollDiv').scrollHeight - document.getElementById(elem+'_scrollDiv').clientHeight; // bottom
	var curr = document.getElementById(elem+'_scrollDiv').scrollTop;
	if (curr >= max) {
		if(cPage < mPages){
			page.value++;
			openIndicator();
			xajax_getNextResultGroup(cPage);
		}
	}	
}

function hotkeySearch(){
	if(! hk_searching){
		clearTimeout(hk_timer);
		hk_timer = setTimeout('commitHotKeySearch()', 400);
	}
}

function commitHotKeySearch(){
	hk_searching = true;
	openIndicator();
	xajax_hotkeySearch(document.getElementById('searchText').value);
}

function clearWhiteSpace(){
	var txt, i;
	txt = document.getElementsByTagName('input');
	for(i=0; i<txt.length; i++){
		if(txt[i].type == 'text' && txt[i].value.match(/^\s*$/)){
			txt[i].value = '';
		}
	}
}

function delayedSetFocus(){
	if(glbElem != null)
    	glbElem.focus();
}

function verifyInfo(obj_id, msg_id){
	clearWhiteSpace();
	$(".manageForm label").css('color', 'black');
	var fck = 0;
	first = true;
	var errMsg = "Missing Required Information:";
	var valid = true;
	var item = '';
	var iVal = new String();
	
	for(var i=0;i<vf.length;i++){
		item = document.getElementById(vf[i][0]+"_id");
		
		//  If we have a CK Editor, use the getData() to get the information
		if($("#"+vf[i][0]+"_id").attr('editor')){
			iVal = editorObj.getData();
			$("#"+vf[i][0]+"_id").val(iVal);
		}
		else
			iVal = item.value;

		iVal = iVal.trim();
		if(obj_id == 0 || vf[i][2] > 0){
			switch (vf[i][1]){
				case 'email':
					if(! validEmail(iVal)){
						valid = false;
						errMsg += "\n"+vf[i][1];
						$("#"+vf[i][0]+"_lbl").css('color', error_color);
						if(first){
							glbElem = item;
							first = false;
						}
					}
					break;
				case 'phone':
					if(iVal.length != 10){
						valid = false;
			  			errMsg += "\n"+vf[i][1];
			  			$("#"+vf[i][0]+"_lbl").css('color', error_color);
			  			if(first){
			  				glbElem = item;
			    			first = false;
			  			}
					}
					break;
				default :
					if(iVal.length == 0 || iVal == 0){
						valid = false;
			  			errMsg += "\n"+vf[i][1];
			  			$("#"+vf[i][0]+"_lbl").css('color', error_color);
			  			if(first){
			  				glbElem = item;
			    			first = false;
			  			}
					}
					break;
			}
		}
	}
	if(! valid){
		if (msg_id != null){
			$("#"+msg_id).attr('innerHTML', 'Missing Required Information');
			//alert(errMsg);
		}
  		setTimeout('delayedSetFocus()', 100);
	}
	return valid;
}

function validEmail(email){
    var tValid = true;
    if((email.length < 8) ||
        ((email.length>0) && (! email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi)))){
        tValid = false;
        if(first){
            first = false;
            glbElem = email;
        }
    }
    return tValid;
}

//  Allows for decimal numbers
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
        if(charCode == 32 || (charCode >= 44 && charCode <= 46)){
            return true;
        }
        else{
            return false;
        }
    }
    return true;
}

//  Allows for integers only. No decimals.
function pressedInteger(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;

	return true;
}

//  Allows for only SEO keys
function isSEOKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
        if(charCode == 32 || charCode == 37 || charCode == 39 || charCode == 46 || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)){
            return true;
        }
        else{
            return false;
        }
    }
    return true;
}

function clearForm(fck_elem){
	$("label").css('color', 'black');
	var elem;
	for(var i in cf){
		switch(cf[i][0]){
			case 'value':
				document.getElementById(i).value = cf[i][1];
				break;
			case 'innerHTML':
				document.getElementById(i).innerHTML = cf[i][1];
				break;
		}
	}
	if(fck_elem != null){
		loadEditor(fck_elem, '');
	}
	return false;
}

function keyCheck(evt, elem){
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if(charCode != 9){
		if(document.getElementById(elem+'_results').style.display == 'inline' && (charCode == 38 || charCode == 39 || charCode == 40 || charCode == 13)){
			var cSel = document.getElementById(elem+'_sel');
			var sel = cSel.selectedIndex;
			if((charCode == 39 || charCode == 13) && sel >=0){
				setSelection(elem, document.getElementById(elem+'_sel').value);
				return false;
			}
			else{
				sel += ((charCode==38)?-1:1);
				if(sel < 0)
					sel = 0;
				if(sel > (cSel.length-1))
				 sel = cSel.length-1;
				cSel.selectedIndex = sel;
			}
		}
		else
			setTimeout("hkSearch('"+elem+"')", 100);
	}
	else
		closeHKSearch(elem);
}

function confirmRemove(ct, eid){
	if(confirm(ct)){
		openIndicator();
		xajax_removeItem(eid);		
	}
	else{
		closeIndicator();
	}
}

function isEmpty(s){
	return ((s == null) || (s.length == 0))
}

function initializeSorter(){
	$("ul.sort_list").sortable({stop:function(i) {
		xajax_updateOrder($("ul.sort_list").sortable("toArray"));
		}
	});
}

function setBorder(elem){
	elem.style.border='1px solid #000000';
	elem.style.backgroundColor = '#FFFFCC';
}

function unsetBorder(elem){
	elem.style.border='1px solid #DDDDDD';
	elem.style.backgroundColor = '#FFFFEE';
}

//  Reset the Account user's password
function resetPassword(){
	var email = $('#uname_id').val();
	email = email.replace(/^\s*/, "").replace(/\s*$/, "");
	if (email.length > 0){
		$('#msg').attr('innerHTML', '&nbsp');
		$('#passwd_id').attr('value', '');
		$('#uname_lbl').css('color', '#000000');
		xajax_resetPassword(email);
	}
	else {
		$('#uname_lbl').css('color', 'red');
		$('#passwd_id').attr('value', '');
		$('#msg').attr('innerHTML', 'Please enter a valid email address');
	}
}

//  Validate Login
function validateLogin(){
	var vf = new Array();
	vf[0] = new Array("email", "Email Address", 1);
	vf[1] = new Array("password", "Password", 1);
	
	/*****  Add Validation Function here  *****/
	xajax_validateLogin(xajax.getFormValues('login'));
	
	return false;
}

