/*
  file SDCOS_Utils.js
  This file defines various utility functions for the SDCOS webpages
  Initial: 2011-03-03
  Author J. Schaefer
  
  This file depends upon values definhed in SDCOS_inc.js!
  
*/


// Suggested routine to put wait cursor everywhere
function Busy(){
	setDocCursor('wait');
}

function setDocCursor(newcursor){

   document.body.style.cursor=newcursor;

   zz = document.getElementsByTagName('A');
   for (var i=0;i < zz.length; i++)
      zz[i].style.cursor=newcursor;

   zz = document.getElementsByTagName('INPUT');
   for (var i=0;i < zz.length; i++)
      zz[i].style.cursor=newcursor;
}
// 
function unBusy(){
	setDocCursor('default');
}

// Function used by login.html to build an xml login query structure
// <authenticate>
//  <user>NNNNNNNNNNN</user>
//  <pass>MMMMMMMMMMM</pass>
//  <email>foo@flup.com</email>
//  <force>No</force>
// </authenticate>
function buildLoginQuery(user,pass,email,force){
	var queryStr = "<authenticate>";
	queryStr += "<sender>"+encodeURIComponent(window.location.href)+"</sender>";
	queryStr = queryStr + "<user>"  + MD5(user) + "</user>";	
	var temp_pass = pass;
	if( temp_pass=="") temp_pass=Default_NULL_value;
	
	queryStr = queryStr + "<pass>"  + MD5(temp_pass) + "</pass>";	
	queryStr = queryStr + "<email>" + email + "</email>" ;
	
	var frcBx=(force?"Yes":"No");	
	queryStr = queryStr + "<force>" + frcBx + "</force>";
	queryStr = queryStr + "</authenticate>";
    return queryStr;
}// end function buildLoginQuery()

// Routine returnes the value of a parameter from the command line url
// If url is "www.sdorchids.com/index.html?param=foo", then the call gup('param') should return 'foo'
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// Routine is used by index.html to check the return status from an add/update/remove email command
function checkEmailStatus(){
  var email_status=gup('email_result');
  var email_action=gup('email_action');
  var email_path  =gup('email_id');
  var email_event =gup('email_level');
  if(email_status != ""){
	  var str = "Your request ";
	  if(email_action == "Remove"){ str += "to remove the email:";}
	  if(email_action == "Submit"){ str += "to add or update the email:";}
	  str+=email_path;
	  if(email_status == "TRUE"){
	      str += " succeeded.";
	  } else {
		  str+=" failed. ";
		  if(email_action == "Remove") str+="The email may have been deleted previously.";
		  if(email_action == "Submit") str+="This is a serious error. Contact the webmaster@sdorchids.com with details.";
	  }
	alert(str);
  }
}

var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos,loc,dir,stats,menus,tools,resize){
	if(arguments.length > 1){
		url=mypage;
	} else {
		url = "http://www.sdorchids.com/index.html";
	}
	
	if(arguments.length > 2){
		pagename=myname;
	} else {
		pagename = "General Info";
	}
	
	if(arguements.length > 3){
		target_width = w;
	} else {
		target_width = screen.width;
	}
	
	if(arguements.length > 4){
		target_height = h;
	} else {
		target_height = screen.height;
	}
	
	if(arguements.length > 5){
		scroll_bar = scroll;
	} else {
	    scroll_bar = "yes";
	}
	if(arguements.length > 6){
		screen_pos = pos;
	} else {
	    screen_pos = "center";
	}	
	if(arguements.length > 7){
		screen_loc = loc;
	} else {
	    screen_loc = "yes";
	}
	if(arguements.length > 8){
		use_dir = dir;
	} else {
	    use_dir = "yes";
	}
	if(arguements.length > 9){
		use_stats = stats;
	} else {
	    use_stats = "yes";
	}
	if(arguements.length > 10){
		use_menu = menus;
	} else {
	    use_menu = "yes";
	}
	if(arguements.length > 11){
		use_tool = tools;
	} else {
	    use_tool = "yes";
	}
	if(arguements.length > 12){
		use_resize = resize;
	} else {
	    use_resize = "yes";
	}

if(screen_pos=="random"){
 LeftPosition= (screen.width)?  Math.floor(Math.random()*(screen.width-w)):100;
 TopPosition =  (screen.height)?
                          Math.floor(Math.random()*((screen.height-h)-75)):100;
}

if(screen_pos=="center"){
  LeftPosition = (screen.width)?(screen.width-w)/2:100;
  TopPosition  = (screen.height)?(screen.height-h)/2:100;
}
else 
  if((screen_pos!="center" && screen_pos!="random") || screen_pos==null){
    LeftPosition=0;TopPosition=20
  }
settings='width='+target_width+',height='+target_height+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location='+screen_loc+',directories='+use_dir+',status='+use_stats+',menubar='+use_menu+',toolbar='+use_tool+',resizable='+use_resize;

win=window.open(url,pagename,settings);
}

var qsParm=new Array();
// This function retrieves the parameter string passed in the URL
// stored into the qsParm associative array by key ?foo=flup will
// be qsParm['foo']=="flup"
// 
function getGetParms(){

  var query=window.location.search.substring(1);
  var parms = query.split('&');
  for(var i=0;i<parms.length;i++){
	  var pos=parms[i].indexOf('=');
	  if(pos>0){
		var key=parms[i].substring(0,pos);		
		var val=unescape(parms[i].substring(pos+1));
		qsParm[key]=val;
	  }// end if(pos>0)
  }// end for(..)
}


// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setSessionCookie(c_name,value){
	var c_value=escape(value);
	document.cookie=c_name + "=" + c_value;
} 

function setCookie(c_name,value,exdays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name){
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0;i<ARRcookies.length;i++){
 	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
 	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
 	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name){
         return unescape(y);
      }
   }
}


function getsupportedprop(proparray){
    var root=document.documentElement //reference root element of document
    for (var i=0; i<proparray.length; i++){ //loop through possible properties
        if (typeof root.style[proparray[i]]=="string"){ //if the property value is a string (versus undefined)
            return proparray[i] //return that string
        }
    }
}

// SideMenu replacement routines - original source extracted from sidemenu.js and greatly modified for SDCOS JCS 1/27/12
//
// This function finds the obj2 span in the sidemenu html structure and opens the associated page
function tryMenuLoad(obj1,obj2){
	do_page_switch(obj2);
}

// This function performs the page switch.
function do_page_switch(obj){
	if(document.getElementById){
	  var spn0=document.getElementById(obj);
	  var spn1=spn0.getElementsByTagName('A');
	  var pg=spn1[0].href;
	  if(window.location != pg) window.location = pg;
   } 
}
// Function CloseAllMenus is called to close all submenus on the sidebar  menu structure.
function CloseAllMenus(){
	if(document.getElementById){
 	  var ar = document.getElementById("masterdiv").getElementsByTagName("span");
	  for(var i=0;i<ar.length;i++){
		  if (ar[i].className=="submenu") ar[i].style.display = "none";
	  }// end for(vari=0;i<ar.length;i++)
	}// end if(document.getElementById
}// end function CloseAllMenus

// This function finds the PageId and changes the background color for the sidebar menu structure.
function highlightPageId(obj){
	document.getElementById(obj).style.backgroundColor=SIDEMENUHIGHLIGHTCOLOR;
}

// This function opens the appropriate submenu block on the target page  for the sidebar menu structure
function openMenu(CurrSubMenu){
	if(document.getElementById){
		// Find the sub menu
	  var el = document.getElementById(CurrSubMenu);
	  if(el.style.display != "block"){
		  // if it does not have 'block' as a display value, close all menus and proceed to set the display value
		 CloseAllMenus();
		 el.style.display = "block";
	  } else {
	     el.style.display = "none";
	  } // end if(el.style.display != "block")
	}// end ftn if(document.getElementById)	
} // end function openMenu(CurrSubMenu)

// This function performs the onload tasks for the sidebar menu structure
function onLoadSideMenu(submenu,pageid){
	openMenu(submenu);
	highlightPageId(pageid);
}// end function onLoadSideMenu(submenu,pageid)

//IE does not support document.getElementsByClassName!
// This routine will check to see if the current browser needs such a function defined.
function checkForGetElementsByClassName(){

if (document.getElementsByClassName == undefined) {
	document.getElementsByClassName = function(className)	{
		var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
		var allElements = document.getElementsByTagName("*");
		var results = [];

		var element;
		for (var i = 0; (element = allElements[i]) != null; i++) {
			var elementClass = element.className;
			if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
				results.push(element);
		}// end for var i

		return results;
	}// end function(className)
}

} // end function checkForGetElementsByClassName()

//ID does not support the addEventListener function
// In all cases pass the element and the function name - NO PARAMETERS will be passed to the function!
//This routine handles the situation for onclick
function addOnClickHandler(el,ftnname,useCapt){
	if(el.addEventListener){
	    if(useCapt==undefined) useCapt=false;
		el.addEventListener('click',ftnname,useCapt);
	} else if(el.attachEvent){
		el.attachEvent('onclick',ftnname);
	} else {
		el.onclick=ftnname;
	}
}
//This routine handles the situation for onload
function addOnLoadHandler(el,ftnname,useCapt){
	if (el.addEventListener){ 
   	  if(useCapt==undefined) useCapt=false;
   	  el.addEventListener("unload", ftnname, useCapt);
    } else if (el.attachEvent){
  	  el.attachEvent("onunload", ftnname);
	} else {
  	  el.event=ftnname;
	}
}
//This routine handles the situation for onunload
function addOnUnLoadHandler(el, ftnname, useCapt){
	if (el.addEventListener){ 
   	  if(useCapt==undefined) useCapt=false;
   	  el.addEventListener("unload", ftnname, useCapt);
    } else if (el.attachEvent){
  	  el.attachEvent("onunload", ftnname);
	} else {
  	  el.onunload=ftnname;
	}
}

//This routine loads the single image for the banner region of all pages except index.html!
//A javascript call invoking the fetchImage.php script defines 4 variables containing data fetched from the picData table in the Db. 
// BnrImg_width is the width of the image 
// BnrImg_height is the height of the image
// BnrImg_title is the title of the image
// BnrImg_path is the path of the image relative to the SDOrchids root directory!
// Currently the width & height parameters are not used as all images are currently 140 px height.
function loadBannerImage(){
	var bnrimg=document.getElementById("BnrImg");
	bnrimg.title=BnrImg_title;
	bnrimg.src=BnrImg_path;
	// I've used EasyThumbs to make 140 height max images so may not need to set width & height fields! 2/21/12
	//	var imgratio=BnrImg_width/BnrImg_height;
	//	bnrimg.height=tgt_height; 
	//	bnrimg.width=tgt_height*imgratio;
}// end loadImage()
