//Add a trim function to the String class
String.prototype.trim=function(){
   return this.replace(/^\s+|\s+$/g,"");
};

//an external function that does the same great for passing to Array.forEach() see below
function trim(str){
  if(typeof(str)!="String"){ return str;}
  return str.replace(/^\s+|\s+$/g,"");
}

/* 
  For FF when traversing the HTTPRequestObject.requestXML to get a 
  node value it uses textContent.  ie Uses .text so instead of using ugly code
  to test for the browser we make FF act like ie
*/ 
if(!document.all){
  Node.prototype.__defineGetter__("text", function() { return this.textContent; });
}

/* 
A Dean Edwards 'lil gem.  extend the Arrays 
so instead of wrtting  for (var i in arry) fn(arry[i]);
        we can write-> Array.forEach(arry,fn);
*/

if (!Array.forEach) { // mozilla already supports this
    Array.forEach = function(object, block, context) {
        for (var i = 0; i < object.length; i++) {
            block.call(context, object[i], i, object);
        }
    };
}

Array.prototype.getElement=function(idx,occurance){
		var len=this.length;
		if(!occurance){ occurance=1;}
		var count=0;
		for(var x=0;x<len;x++){
			if(this[x].name==idx){
				 count++;
				 if(count==occurance){
				 	return this[x];		
				 }
			}
		}
};

if(typeof(fileBrowserCallBack) == "undefined"){
  fileBrowserCallBack= function (field_name, url, type, win) {
	// This is where you insert your custom filebrowser logic
	alert("Example of filebrowser callback: field_name: " + field_name + ", url: " + url + ", type: " + type);
	// Insert new URL, this would normaly be done in a popup
	win.document.forms[0].elements[field_name].value = "someurl.htm";
  };
}



function setSelect(p){
  	var ele=p[0];
  	var param=p[1];
  	if(ele==""){ return;}
  	var el=document.getElementById(ele);
  	var x=0;
  	for(;x<el.options.length;x++){
  		if(el.options[x].value==param){
  			break;
  		}
  	}
  	try{
  	  el.selectedIndex=x;
  	}catch(e){}
  }


function list_change_order(ctrEle,dir){    
      var list=document.getElementById(ctrEle);
      var idx=list.selectedIndex;
      
      if(dir==-1 && idx==0){ return;} //1st is selected can not move up
      if(dir==1 && idx==list.options.length-1){ return;} //last is selected can not move down
      
      var src={};
      src.text=list[idx].text;
      src.value=list[idx].value;
      
      var dest={};
      dest.text=list[idx+dir].text;
      dest.value=list[idx+dir].value;
      
      list.options[idx].text=dest.text;
      list.options[idx].value=dest.value;
      
      list.options[idx+dir].text=src.text;      
      list.options[idx+dir].value=src.value;     
      list.selectedIndex=idx+dir;
}

function list_change_order_swap(ctrEle){
      var list=document.getElementById(ctrEle);
      var idx=list.selectedIndex;
	  var tot=list.options.length;
	  newPos=prompt("Enter the position to move the selected item to [1-"+tot+"]",1);
	  if(!Number(newPos)){ alert("You did not enter a valid number [1-"+tot+"]");return;}
	  if(newPos<1){ alert("You did not enter a valid number [1-"+tot+"]");return;}
	  if(newPos>tot){alert("You did not enter a valid number [1-"+tot+"]");return;}
	  if(idx+1==newPos){ return;} //already at the move to pos
	  var ops=[];
	  mv=null;
	  count=0;
	  while(list.options.length){
	  	if(count++==idx){mv=list.options[0];}
	  	else{ ops[ops.length]=list.options[0];}
	  	list.options[0]=null;
	  }
	  count=1;
	  for(x=0;x<ops.length;x++){
	  	  if(count++==newPos){
	  	  	list.options[list.options.length]=mv;
	  	  	mv=null;
	  	  }
	  	  list.options[list.options.length]=ops[x];
	  }
	  if(mv){list.options[list.options.length]=mv;}
}

function associate(srcId,destId){    
      var src=document.getElementById(srcId);
      var dest=document.getElementById(destId);
      
      for(x=0;x<src.options.length;x++){
    	  if(src.options[x].selected){    		    
    		  	var opt=new Option(src.options[x].text,src.options[x].value);
    		  	dest[dest.options.length]=opt;
    		  	src.options[x]=null;
    		  	x--;//we found one so we need to back up one    		  	
    	  }
      }      
}

function removeSelecion(srcId){    
      var src=document.getElementById(srcId);
      
      var x= src.selectedIndex;
      var srcOpt=src.options[x];
      
      src.options[x]=null;
}



function goToAdminPage(){
  var el=document.getElementById('admin_page_sel');
  var url=el.options[el.selectedIndex].value;
  document.location.href=url;
}
function gotoUrl(who){
  	document.location.href=who.value;
}


function setAdminNavDisplay(val){
	var ele=document.getElementById("admin_page_sel");
	if(!ele){return;}
	for(var x=0;x<ele.options.length;x++){
		if(ele.options[x].value.indexOf("/"+val+"/")!=-1){ break;}
	}
	if(x==ele.options.length){ return;} //this editor page is not selectable from the dropdown
	ele.selectedIndex=x;
}

function selectAssociated(){
	var selObj =document.getElementsByTagName('select');	
	for(var x=0;x<selObj.length;x++){		
		var sel=selObj[x];
		if(!/^associated\d/.test(sel.id)) {continue;}
		for(var y=0;y<sel.options.length;y++){
			sel.options[y].selected=true;
		}
	}
}
				
function logout(){
	document.getElementById("admin_logout").submit();
}


//requires that the ajax.js file has been incluided

function getTimeStamp(mode,target,page,parameters){
   /*
  mode = 4 TIME        A time - The supported range is 00:00:00 to 23:59:59. MySQL displays DATE values in HH:MM:SS format
  mode = 3 DATE        A date - The supported range is 1000-01-01 to 9999-12-31. MySQL displays DATE values in YYYY-MM-DD format
  mode = 2 DATETIME -  A date and time combination The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59. MySQL displays DATETIME values in YYYY-MM-DD HH:MM:SS format
  mode = 1 TIMESTAMP - A timestamp The range is 1970-01-01 00:00:00 to sometime in the year 2037. MySQL displays TIMESTAMP values in YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD or YYMMDD format, depending on whether M is 14 (or missing), 12, 8 or 6, but allows you to assign values to TIMESTAMP columns using either strings or numbers. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation because it is automatically set to the date and time of the most recent operation if you dont give it a value yourself
   */
  var ele=document.getElementById(target);
  var val=ele.value;
  
  var params={};
  params.id=target;
  params.value=ele.value;
  params.mode=mode;
  
  doModalClose = getTimeStamp_close;//FireFox compatability
    
    //Open the dialog box
  if(!page) {page="/common/html/calendar.html";}
  if(!parameters){
  	parameters="dialogWidth:225px;dialogHeight:260px;help:no;status:no";
  }
  var dateObj =
	window.showModalDialog(page, params,parameters);

  if (document.all){
	 doModalClose(dateObj);
  }
  
}

function getTimeStamp_close(returnObj){
  if(!returnObj){return;}
  document.getElementById(returnObj.id+"_disp").innerHTML=returnObj.value;
  document.getElementById(returnObj.id).value=returnObj.value;
}


function lookupFieldValue(fieldName,lookupTable,lookupField,addToSelect,maxSelectAble){
	    if(maxSelectAble){ __MAX_SELECTABLE__=maxSelectAble;}
  		var params={};
  		params.fieldName=fieldName;
  
  		if(addToSelect){
  			if(maxSelectAble){
  				var sel=document.getElementById(fieldName);
  				if(sel.options.length==maxSelectAble){
  					alert("You can not add any more items to this field.");
  					return;
  				}
  			}
  			doModalClose = lookupFieldValueSelect_close;//FireFox compatability
  		}else{
  			doModalClose = lookupFieldValue_close;//FireFox compatability
  		}
    
    	//Open the dialog box
  		var dateObj =window.showModalDialog("/DialogFind/Entry/"+lookupTable+"/"+lookupField, params,
			       "dialogWidth:400px;dialogHeight:400px;help:no;status:no");

  		if (document.all){
	 		doModalClose(dateObj);
  		}

}

function lookupFieldValue_close(returnObj){
  if(!returnObj){ return;}
  document.getElementById(returnObj.fieldName+"_display").value=returnObj.displayValue;
  document.getElementById(returnObj.fieldName).value=returnObj.value;
}

function lookupFieldValueSelect_close(returnObj){
  if(!returnObj){ return;}
  var sel=document.getElementById(returnObj.fieldName);
  
  var opt=new Option(returnObj.displayValue,returnObj.value);
  for(var x=0;x<sel.options.length;x++){
  	if(sel.options[x].value==returnObj.value){
  		alert("No duplicates allowed: "+returnObj.displayValue);
  		return;
  	}
  }
  sel.options[sel.options.length]=opt;
}


function FTPFileSelect(browseType, field,callback){
	var features = "dialogWidth:400px; dialogHeight:400px; help:no; status:no; resizable:no; scroll:auto; unadorned:yes;";		

	var myUrl= '';		
	switch(browseType){
		case 'file':  myUrl="All";break;
		case 'image':  myUrl="Img";break;
	}

	var obj ={};
	obj.fieldName=field;		
		
	doModalClose=FTPFileSelect_close;
	FTPFileSelect_close.callbackFn=callback;
	
	var ob=window.showModalDialog("/admin/FileUpload/Browse"+myUrl, obj, features);
	
	if(document.all){		    
		doModalClose(ob,callback);
	}
}
	
function FTPFileSelect_close(ob,callbackFunc){
	if(callbackFunc){ ob=callbackFunc(ob);
	}else{
		if(FTPFileSelect_close.callbackFn){ ob=FTPFileSelect_close.callbackFn(ob);}
	}
	document.getElementById(ob.fieldName).value= ob.value;	
}


function populateProvinceSelect(messages,data){
	var fatal=getFatalMessage(messages);
	var targetname=data.getElement('target').value;
	var targetdata=data.getElement('provinces').value;
	var countryCode=data.getElement('country_code').value;
	var targ;
	
	if(targetname){
		targ=document.getElementById(targetname);
		while(targ.options.length){
			targ.options[0]=null;
		}
	}else{
		alert("Error no state select element specified");
	}

	if(fatal){
		if(countryCode==""){
			var lable=targ.getAttribute("droplable");
			if(lable){
				targ.options[targ.options.length]=new Option(lable,"");
				return;
			}
		}
		alert("The request cold not be completed due to the following errors:\n"+fatal);		
	}
	var x=1;
	
	if(targetname){
		var lable=targ.getAttribute("droplable");
		if(lable){
			targ.options[targ.options.length]=new Option(lable,"")
		}
		var dataA=targetdata.split(';');
		var sel=null;
		if(populateProvinceSelect.params)sel=populateProvinceSelect.params;
		for(x=0;x<dataA.length;x++){
			targ.options[targ.options.length]=new Option(dataA[x],dataA[x])
			if(sel==dataA[x]){
				targ.selectedIndex=x;
			}
		}
	}
}

//http://techpatterns.com/downloads/javascript_cookies.php
function Set_Cookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ){
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ){
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;			
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){
		return null;
	}
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ){ 
		document.cookie = name + "=" +(( path )? ";path=" + path : "") +
									  (( domain )? ";domain=" + domain : "" ) +
								";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function call_ajax_service(e,service,target,alt){
	if(window.event && !e){e=window.event;}
	var src,idx;
	switch(service){
		case"getProvince":
			src=(e.target)?e.target:e.srcElement;
			idx=src.selectedIndex;
			var parameters="countrycode="+encodeURI(src.options[idx].value)+"&target="+encodeURI(target);
			populateProvinceSelect.params=alt;
			_AJAX_.submitRequest("/common/webservice/GetProvince/",parameters,populateProvinceSelect);
			break;
		case"getCity":break;
		case"leapYearCheck":
			src=(e.target)?e.target:e.srcElement;
			idx=src.selectedIndex;
			var val=src.options[idx].value;
			var leapYear=isLeapYear(val);
			target=target.split(",");
			var monthOb=document.getElementById(target[0]);
			var month=convertMonthToInt(monthOb.options[monthOb.options.selectedIndex].value);
			if(month==2){
				var dayOb=document.getElementById(target[1]);
				var start=28;
				if(dayOb.options[0].value==""){start++;}if(leapYear){dayOb.options[start].disabled=false;
				start++;
			}
			if(dayOb.options.selectedIndex==start){
				dayOb.options.selectedIndex=0;}
				for(var x=start;x<dayOb.options.length;x++){dayOb.options[x].disabled=true;}
			}
			break;
		case"getDaysInMonth":
			src=(e.target)?e.target:e.srcElement;
			idx=src.selectedIndex;
			target=target.split(",");
			var targ=document.getElementById(target[0]);
			value=src.options[idx].value;
			value=convertMonthToInt(value);
			var dim=[0,31,28,31,30,31,30,31,31,30,31,30,31];
			var d=dim[value];
			var start=0;
			if(targ.options[0].value==""){start++;}
			for(var x=start;x<targ.options.length;x++){
				targ.options[x].disabled=false;
			}
			if(value==2){
				var year=document.getElementById(target[1]);
				var selYear=year.options[year.options.selectedIndex].value;
				if(isLeapYear(selYear))d++;
				if(targ.options.selectedIndex>d+start){targ.options.selectedIndex=0}
			}
			for(var x=d+start;x<targ.options.length;x++){
				targ.options[x].disabled=true;
			}
			break;
	}
}
function isLeapYear(year){
	if(isNaN(year))return false;
	if((year%4)==0){
		if(parseInt(year/100)==(year/100.0)){
			if(year%400==0){return false;}
		}else{
			return true;
		}
	}
	return false;
}
function convertMonthToInt(value){
	if(value==""){return 0;}
	if(parseInt(value)==value){return parseInt(value);}
	var months=["january","february","march","april","may","june","july","august","september","october","november","december"];
	var monthabbrev=["jan","feb","mar","apr","may","jun","jly","aug","sep","oct","nov","dec"];
	value=value.toLowerCase();
	for(var x=0;x<months.length;x++){
		if(months[x]==value){return x+1;}
	}
	for(var x=0;x<monthabbrev.length;x++){
		if(monthabbrev[x]==value){return x+1;}
	}
	return 1;
}
