/**
 * 
**/
var gjaOnLoadWindowFuncs = new Array(); //The gjaOnLoadWindowFuncs array holds all of the functions you wish to run when the page loads.
//var gjsGappCloseWindowImg = '<img src="includes/GappEdit/images/GappCloseWindow.gif" alt="Click to Close" width="12" height="11" border="0">';
//var needToConfirm;
var gjbOnSubmitting = false;
var selectCtrl=new Array();//holds the selected indexes of select control, used with the oneClickSelect() function
/**
*example:
*  <select id="mySel2" name=mySel2 multiple onClick="oneClickSelect(this);">
*    <option>aaa
*    <option>bbb
*    <option>ccc
*    <option>ddd
*    <option>eee
*    <option>fff
*  </select>
**/
function oneClickSelect(theSel){
  theIndex=theSel.selectedIndex;
//alert(theSel.id);
//alert(theSel.options[theIndex].text);
//alert(theSel.options[theIndex].value);
//alert(theIndex);

  selectCtrl[theSel.name+theIndex]=(selectCtrl[theSel.name+theIndex])?false:true;
  $('option',theSel).each(function(i){theSel.options[i].selected=(selectCtrl[theSel.name+i])?true:false;});
  
//  $('#'+theSel.id).unbind();

//  theSel.options[theIndex].select();//selected=selectCtrl[theSel.name+theIndex];
}

function selectCount(lBox,lBoxDiv){
//alert(lBox);
  $('#'+lBoxDiv).html('0');
  $('#'+lBox+' option:selected').each(function(i){$('#'+lBoxDiv).html(i+1)});
}

/**
  * Checks/unchecks all options of a <select> element
  *
  * @param   string   the element name
  * @param   boolean  whether to check or to uncheck the element
  *
  * @return  boolean  always true
  */
function setSelectOptions(lBox, do_check){
//alert(lBox);
  selectCtrl=new Array();//The global array for the oneClickSelect()
  $('#'+lBox+' option').each(function(){this.selected=do_check;});
  
  return true;
} // end of the 'setSelectOptions()' function

/**
  * The next 2 functions markAllRows(form), unMarkAllRows(form) is used in the GappTable.php file
  * and it mark/unmark table rows for batch processes eg. delete
  *
  * @param   string   the form name
  * @param   string   the element name
  * @param   boolean  whether to check or to uncheck the element
  *
  * @return  boolean  always true
  */
function markAllRows(form) {
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == 'checkbox') {
			form.elements[i].checked = true
		}	  
	}
}
function unMarkAllRows(form) {
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == 'checkbox') {
			form.elements[i].checked = false
		}	  
	}
}

/**
*This function is to move select options between selects
*It is used in gapptype_2_swap.php, gapptype_2_lookup.php, pop_ajax_lookup() in module gappeditCore
*  
*/
/*function moveSwap(fbox_select, tbox_select, isLookup) {
//alert('moveswap');
  var fbox = document.getElementById(fbox_select);
  if(isLookup){
    var tbox = parent.document.getElementById(tbox_select);
//alert('isLookup');
  }else{
    var tbox = document.getElementById(tbox_select);
  }
//alert(tbox);
  
  var c=0;
  for (var i=fbox.options.length-1; i >= 0; i--) {
    var oOption = fbox.options[i];
    if (oOption != null && oOption.selected) {
//alert(oOption.text);
//      tbox.appendChild(oOption);
      var no = new Option();
      no.value = oOption.value;
      no.text = oOption.text;
      tbox[c] = no;      
      c++;
    }
  }
//alert(tbox);
  tbox.focus();
  tbox.options[0].selected=true;
  return true;
}*/

//or use jQuery equvalent - "onsubmit"=>"$('#$compname',parent.document).val($('#fileupload___').val());parent.cClick();",
function movePopup(pfComp, ptComp){
  var fComp = document.getElementById(pfComp);
  var tComp = parent.document.getElementById(ptComp);

  tComp.value = fComp.value;
  tComp.focus();
}

function moveSwap(fbox_select, tbox_select, isLookup, empty_tbox) {
//alert(t);//.removeOption(/./);
//alert(tbox_select);//.removeOption(/./);
  var clearBox=(empty_tbox)?true:false;

  var fbox = document.getElementById(fbox_select);
  if(isLookup){
    var tbox = parent.document.getElementById(tbox_select);
    //$('#'+tbox_select).removeOption(/./);
    //alert('islookup');
  }else{
    var tbox = document.getElementById(tbox_select);
  }

  if(clearBox){
    tbox.options.length=0;
  }
  
  var arrFbox = new Array();
  var arrTbox = new Array();
  var arrLookup = new Array();
  var i;
  for (i = 0; i < tbox.options.length; i++) {
    arrLookup[tbox.options[i].text] = tbox.options[i].value;
    arrTbox[i] = tbox.options[i].text;
  }
  var fLength = 0;
  var tLength = arrTbox.length;
  for(i = 0; i < fbox.options.length; i++) {
    arrLookup[fbox.options[i].text] = fbox.options[i].value;
    if (fbox.options[i].selected && fbox.options[i].value != "") {
      arrTbox[tLength] = fbox.options[i].text;
      tLength++;
    }else {
      arrFbox[fLength] = fbox.options[i].text;
      fLength++;
    }
  }
  
  arrFbox.sort();
  arrTbox.sort();
  fbox.length = 0;
  tbox.length = 0;
  var c;
  for(c = 0; c < arrFbox.length; c++) {
    var no = new Option();
    no.value = arrLookup[arrFbox[c]];
    no.text = arrFbox[c];
    fbox[c] = no;
  }
  for(c = 0; c < arrTbox.length; c++) {
    var no = new Option();
    no.value = arrLookup[arrTbox[c]];
    no.text = arrTbox[c];
    tbox[c] = no;
  }

  tbox.focus();
  tbox.options[0].selected=true;
//  try{
//    alert(tbox.onchange());
//  }catch(e){}

//  if(tbox.onchange().toString()){
//    tbox.onchange();//fire an onchange event for the to_select_box
//  }
  
//var sonchange = tbox.onchange.toString();
//var res = sonchange.match(/\{([^\}]*)\}/);//extract everything between the { and } brackets
//re = /\{.*?\}/;
//res = re.exec(tbox.onchange.toString());
//alert(res[1]);

//$(tbox).bind("myEvent",function(event,message1,message2) {
// 	alert(message1 + ' ' + message2);
// });
//$(tbox).trigger("myEvent",["Hello","World"]);
 
//$(tbox).bind("myEvent", tbox.onchange);
//$(tbox).trigger("myEvent");
}

function moveSwap2(fbox_select, tbox_select, pValSep) {
//alert(tbox_select);//.removeOption(/./);

  var valSeparator=(pValSep)?pValSep:' ';
  var fbox = document.getElementById(fbox_select);
  var tbox = parent.document.getElementById(tbox_select);

  var i;
  var fLength = 0;
  for(i = 0; i < fbox.options.length; i++) {
    if (fbox.options[i].selected && fbox.options[i].value != "") {
      tbox.value += fbox.options[i].text+valSeparator;
    }
  }
  
//alert(tbox.value);//.removeOption(/./);
  tbox.focus();
  tbox.selected=true;
}

/**
  * Checks to see if [Caps Lock] is on when you type into a <password> element
  * Example: <INPUT TYPE="Password" NAME="Password" SIZE=16 MAXLENGTH=16 onKeyPress="checkCapsLock(event)">
  *
  * @param   event   the onKeyPress() event of the <password> element
  *
  * @return  nothing
  */
function checkCapsLock(e, msg) {
	//var ctrlPressed = 0;
	//var altPressed = 0;
	var shiftPressed = 0;
	var charCode = 0;
	var myMsg = msg;//'Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';
	
	if (parseInt(navigator.appVersion)>3) {
		
		//var evt = navigator.appName=="Netscape" ? e:event;
		e = (e) ? e : event;
		charCode = (e.which) ? e.which : e.keyCode;
		
		if (navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4) {
			// NETSCAPE 4 CODE
			var mString = (e.modifiers+32).toString(2).substring(3,6);
			shiftPressed = (mString.charAt(0)=="1");
			//ctrlPressed = (mString.charAt(1)=="1");
			//altPressed  = (mString.charAt(2)=="1");
		} else {
			// NEWER BROWSERS [CROSS-PLATFORM]
			shiftPressed = e.shiftKey;
			//altPressed  = e.altKey;
			//ctrlPressed = e.ctrlKey;
		}
		
		if ((charCode >= 65 && charCode <= 90) && !shiftPressed) {
			alert(myMsg);
		} else if ((charCode >= 97 && charCode <= 122) && shiftPressed) {
			alert(myMsg);
		}
	
	}

}//end of function checkCapsLock

/**
* @param   element fid - the field id
* @param   string cn - the div id to display the number of chars
* @param   string rn - the div id to display the number of remaining chars
* @param   int mc - The max length of the form input
* 
*/
function charCount(fid, cn, rn, mc) {
  var len = fid.value.length;
  if (len > mc) {
    fid.value = fid.value.substring(0, mc);
    len = mc;
  }
  
  if(document.getElementById(cn)){
  	document.getElementById(cn).innerHTML = len;
  }
  document.getElementById(rn).innerHTML = mc - len;
}//end of function charCount

/**
* @param   element fid - the field id
* @param   string value - if value = null then use the elemnt value
* @param   int hours - the number of hours for the cookie to expires
* @param   string path - 
* @param   string domain - 
* @param   bool secure - 
*/
function setCookie(fid, value, hours, path, domain, secure) {
//alert(hours);
  var sName = ((fid.name) ? fid.name : fid);
  var val = null;
//alert("sName1="+(sName instanceof Object));
  // (fid.length!=undefined) is to make it IE compatable
  if(sName instanceof Object && (sName instanceof Object ||sName.length!=undefined)){//sName will be an instance of object if it's a radio or checkbox
  //if(sName instanceof Object){//sName will be an instance of object if it's a radio or checkbox
    sName = sName[0].name;
    if(value){
      val = value;
    }else{
      for (var i = 0; i < fid.length; i++) {
        if (fid[i].checked) {
          break;
        }
      }
      val = fid[i].value;
    }  
  }else{
  	//if a value is not passed, use the element value
    val = ((value) ? value : fid.value);
  }
  
//alert(val+' - '+escape(val));

	var exp = new Date();
	var hoursFromNow = exp.getTime() + (hours*60*60*1000);
	exp.setTime(hoursFromNow);
//alert(((hours) ? '; expires=' + exp.toGMTString() : ''));

//	document.cookie = sName + '=' + escape(val) +
	document.cookie = sName + '=' + encodeURIComponent(val) +
	((hours) ? '; expires=' + exp.toGMTString() : '') +
	((path) ? '; path=' + path : '') +
	((domain) ? '; domain=' + domain : '') +
	((secure) ? '; secure' : '');
//alert(val);
//alert('Cookie has been set !!');
}

function getCookie(fid) {
//alert(name);
  var name = ((fid.name) ? fid.name : fid);
	var arg = name + '=';
	var retval = '';
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while(i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg){
			 retval = getCookieVal(j);
			 if(document.getElementById(name)){
			   document.getElementById(name).value = getCookieVal(j);
			 }
			break;
		}	
		i = document.cookie.indexOf(' ', i) + 1;
		if(i == 0) break;
	}
	
//alert(retval);
	return retval;
}
/*function deleteCookie(name,path,domain) {
	if (getCookie(name)) {
		document.cookie = name + '=' +
		((path) ? '; path=' + path : '') +
		((domain) ? '; domain=' + domain : '') +
		'; expires=Thu, 01-Jan-70 00:00:01 GMT';
	}
}*/

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf(';', offset);
	if(endstr == -1)
		endstr = document.cookie.length;
		
//	var retval = unescape(document.cookie.substring(offset, endstr));
	var retval = decodeURIComponent(document.cookie.substring(offset, endstr));
	
//	var retval = document.cookie.substring(offset, endstr);
//alert(retval);	
	return retval;
}

function isArray(obj) {
  if (obj.constructor.toString().indexOf("Array") == -1)
    return false;
  else
    return true;
}
/**
* Put caret focus to the first available input of the form
* If there where an validation error on an Input, set focus to the first error input
* @param sFrmName - the form to put the focus in
**/
function placeFocus(sFrmName) {
//alert('placeFocus = '+sFrmName+' ## sInputname = '+sInputName);
  $('#'+sFrmName+' :input:visible:enabled:first').focus();
}

/**
* Toggle the fieldset type and all the fields under it, until it gets to the next fieldset
* Used in the gapptype_1_fieldset.php
**/
function toggleFieldSet(pControl){
//alert(pControl);
  $('#'+pControl).css('cursor','pointer').
    attr('title','Click to expand/collapse '+pControl).
    click(function(){
      var fieldset=$(this);
      if(fieldset.data('collapsed')){
        fieldset.data('collapsed',false);
      }else{
        fieldset.data('collapsed',true);
      }
			$(this).nextAll().each(function(){
			  if($(this).hasClass('.fieldset') || $(this).hasClass('.formbuttons_row')){
			    //alert($(this)+' False');
			    return false;
			  } else{ 
			    //alert($(this));
			    if(fieldset.data('collapsed')){
			      $(this).hide();
			      setCookie(pControl, 'collapsed', 0);
			    }else{
			      $(this).show();
			      setCookie(pControl, 'expanded', 0);
			    }
			  } 
			});
    });
}

function clearForm(form) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', form).each(function() {
  	var type = this.type;
  	var tag = this.tagName.toLowerCase(); // normalize case
  	// it's ok to reset the value attr of text inputs,
  	// password inputs, and textareas
//alert(type);
  	if (type == 'text' || type == 'password' || tag == 'textarea')
  	  this.value = "";
  	// checkboxes and radios need to have their checked state cleared
  	// but should *not* have their 'value' changed
  	else if (type == 'checkbox' || type == 'radio')
  	  this.checked = false;
  	// select elements need to have their 'selectedIndex' property set to -1
  	// (this works for both single and multiple select elements)
  	else if (tag == 'select')
  	  this.selectedIndex = -1;
  });
};

/**
* The javascript popup confirm box
**/
function confirmDialog_J(mess, href)	{
//alert('Delete !');
	if(confirm(mess)){
	  location.href=href;
		return true;
	}	

	return false;
}


/**
 * The populateOnLoadWindowFunc() function will set the window.onload function to
 * be executeOnLoadWindowFuncs() which will run all of your window.onload
 * functions.
 **/
function populateOnLoadWindowFunc(sFunc){
//alert('populateOnLoadWindowFunc:- '+sFunc);
	//gjaOnLoadWindowFuncs = sFunc.split(',');
	gjaOnLoadWindowFuncs = sFunc.split(':');
	window.onload = executeOnLoadWindowFuncs;
}

/**
 * The executeOnLoadWindowFuncs() function loops through the gjaOnLoadWindowFuncs array and
 * runs each function in the array.
 **/
function executeOnLoadWindowFuncs(){
	for(var i = 0;i < gjaOnLoadWindowFuncs.length;i++){
//alert(gjaOnLoadWindowFuncs[i]);
		eval(gjaOnLoadWindowFuncs[i]);
	}	
}


/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} true if the form is dirty, false otherwise.
 */
function formIsDirty(sForm){
	var retval = false;
	var form = document.getElementById(sForm);
//alert(form);
	if(! gjbOnSubmitting){
		for (var i = 0; i < form.elements.length; i++) {
		  var element = form.elements[i];
		  var type = element.type;
		  if (type == "checkbox" || type == "radio") {
		    if (element.checked != element.defaultChecked) {
		      retval = true;
		    }
		  } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
		    if (element.value != element.defaultValue)  {
		      retval = true;
		    }
		  } else if (type == "select-one" || type == "select-multiple") {
		    for (var j = 0; j < element.options.length; j++) {
		      if (element.options[j].selected != element.options[j].defaultSelected) {
		        retval = true;
		      }
		    }
		  }
		}
	}
	gjbOnSubmitting = false;
	return retval;
}

/**
* This is used to put a border around the menu image
* Used in the GappMenu.php class
* eg. class="menuimage" onMouseover="highlightMenuImage(this,'black')" onMouseout="highlightMenuImage(this,'white')"
**/
function highlightMenuImage(which,color){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
		which.style.borderColor=color
	}
}

/**
* Create a PHP session variable on a JavaScript event
* eg.	$retval .= "<input class=\"GappEditBTN\" type=button value=\"\" onclick=\"createSession('$sessionVar','$sessionVal');location.href='$_url'\">";
**/
function createSession(pVarName, pValue, pDelay){
//alert(pVarName+" -- "+pValue);
  pDelay = ((pDelay == undefined) ? 1000: pDelay);
//alert(pDelay);

  ajax_create_session(pVarName, pValue, pDelay); //This function is in includes/GappEdit/ajax/GappAjax.js
  setCookie(pVarName, pValue);
}

function scrollToCoordinates(pFormName) {
//alert(pFormName);
  //var xpos = getCookie(pFormName+"_xpos")
  var ypos = getCookie(pFormName+"_ypos")
//alert(ypos);
  //window.scrollTo(xpos, ypos);
  if(ypos){
    window.scrollTo(0, ypos);
  }
}
function saveScrollCoordinates(pFormName) {
  //var scrollx_value = (document.all)?document.body.scrollLeft:window.pageXOffset;
  var scrolly_value = (document.all)?document.body.scrollTop:window.pageYOffset;
  //setCookie(pFormName+"_xpos", scrollx_value);
  setCookie(pFormName+"_ypos", scrolly_value);
//alert(pFormName+"_ypos == "+scrolly_value);
} 

function setLookupValue(pField){
  //use parent. because lookup is called from an iframe
  var o = parent.document.getElementById(pField);
//alert(pField+" --- "+pValue);
//alert(o.name);
  
  var retval="";  
	for (var i = 0; i < listForm.elements.length; i++) {
		if (listForm.elements[i].type == 'checkbox' && listForm.elements[i].checked) {
			 temp = listForm.elements[i].value.split('=');
			//retval += listForm.elements[i].value;
			retval += temp[1];
		}	  
	}
	
//alert(retval);
  o.value = retval;
  
}

//Sample usage
//displayage (year, month, day, unit, decimals, rounding)
//Unit can be "years", "months", or "days"
//Decimals specifies demical places to round to (ie: 2)
//Rounding can be "roundup" or "rounddown"
//displayage(1997, 11, 24, "years", 0, "rounddown")
var one_day=1000*60*60*24
var one_month=1000*60*60*24*30
var one_year=1000*60*60*24*30*12

function displayage(yr, mon, day, unit, decimal, round){
  today=new Date()
  var pastdate=new Date(yr, mon-1, day)
  
  var countunit=unit
  var decimals=decimal
  var rounding=round
  
  finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year
  decimals=(decimals<=0)? 1 : decimals*10
  
  if (unit!="years"){
    if (rounding=="rounddown")
      return Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit;
    else
      return Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit;
  }else{
    yearspast=today.getFullYear()-yr-1
    tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
    pastdate.setFullYear(today.getFullYear())
    pastdate2=new Date(today.getFullYear()-1, mon-1, day)
    tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
    return yearspast+tail+" "+countunit;
  }
}

/**
*control - string the name of the input control
*unit - string valid values: "years","months","days"
*
*	    "onload"=>"posttextAge('testdate','years');",//fieldname,unit
*	    "onblur"=>"posttextAge('testdate','years');",//fieldname/unit
*Remember to poplate property:
*    "javascript_files"=>"??gappedit.js", in the $edit_prop array
*/
function posttextAge(control,unit,dateformat){
//alert('posttextAge '+control);
  unit=(unit)?unit:'years';
  dateformat =(dateformat)?dateformat:'y-m-d';
  val = $('#'+control+'___').val();
  if(!isNaN(parseFloat(val))){
    splitdate = val.split('-')
    //assumtion date format y-m-d
    retval = displayage(splitdate[0],splitdate[1],splitdate[2],unit,0,'rounddown');//in GappEdit/javascript/gappJGappFunc.js
    $('#'+control+"posttext").html('&nbsp;'+retval);//note it's NOT the fieldnameform field value
  }
}
/*
* count the rows of an <textarea>
*/
function countLines(strtocount, cols) {
//alert("countLines")  ;
    var hard_lines = 1;
    var last = 0;
    while ( true ) {
        last = strtocount.indexOf("\n", last+1);
        hard_lines ++;
        if ( last == -1 ) break;
    }
    var soft_lines = Math.round(strtocount.length / (cols-1));
    var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
    if ( hard ) soft_lines = hard_lines;
//alert(soft_lines);
    return soft_lines;
}

function isValidURL(url){
  var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
  if(RegExp.test(url)){
    return true;
  }else{
    return false;
  }
}

function isValidEmail(email){
  var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/
  if(RegExp.test(email)){
    return true;
  }else{
    return false;
  }
} 
