//********************************************************************************************
// utils.js
//  @author:kcowan@cytopia.cc
//  @version 1.0
//
//  &copy;2003 cpr associates, inc.
//  
//  a set of utilities providing some java-styled javascript objects for a web page.
//
//   --> <code> Request object </code>
//        loads in params from request.  obtainable via request.getParameter("myParam");
//
//
//   --> <code> StringTokenizer </code>
//           similar to the Java Object. Takes an string and a delimeter for arguments, and returns an array of strings.
//
//           sample useage:
//               tokenizer = new StringTokenizer();
//               var str = "foo, bar, bee, bop";
//               var delimeter = ",";
//               my_tokens_array = tokenizer.tokenize(str, delimeter);
//
//
//   --> <code> StringBuffer </code>
//        allows for creations of a buffer for concatenating long strings, etc.
//         example usage:
//          buffer = new StringBuffer();
//          buffer.append("my string foo"+varBar);
//
//    --> Array DOM extensions
//        adds 'pop' and 'push', and Iterator functionality to javascript Array object
//
//    --> <code> Iterator object </code>
//         similar to the Java Iterator object. 
//         used in lieu of 'for' statement to iterate through
//         an array using:
//  
//              itr = myArray.iterator();
//
//              while(itr.hasNext()){
//                   itr.next();
//              }
//     
//
//
//*********************************************************************************************
//*************************************************************************************
//  CODE SAMPLE
//*************************************************************************************
/*

    *Note: this method provides usage demonstrations for the Array, 
	StringBuffer, Request and Iterator DOM Extensions.


 function testDOMUtils(){

		testOne = new Array(); // create New array

		// add objects using the 'push(myObj)' method
		testOne.push("one");
		testOne.push("two");
		testOne.push("three");
		testOne.push("four");

		buf = new StringBuffer(); // instantiate new StringBuffer

		// gather up elements for output
		resEle = document.getElementById("results");
		reqEle = document.getElementById("requestLayer");
		paramEle = document.getElementById("paramLayer");
		
     try{

		itr = testOne.iterator(); // get Array Iterator instance
		buf.append("<UL>");
		while(itr.hasNext()){ // use the Iterator 'hasNext()' method.  returns false when complete

		   buf.append("<li>"+itr.next()+"</li>");// append to the buffer the next item in the array using iteraor 'next()' method
		}

	    buf.append("</ul>");

		   resEle.innerHTML = buf.toString();
		   buf.reset();

          itreq = request.getParameters().iterator(); // get parameters from Request object using Iterator object
		  buf.append("<ul> Request Parameters");

		  while(itreq.hasNext()){
		     var reqName = itreq.next().name;
			 var reqValue = itreq.next().value;

		     buf.append("<li>"+reqName+" is "+reqValue+"</li>");
			 }
			 buf.append("</ul>");
			 reqEle.innerHTML = buf.toString();

			 buf.reset();
			 buf.append("<ul>");
			 buf.append("GET PARAM FROM REQUEST TEST: <BR>");
			 buf.append("<li> param: "+request.getParameter('me')+" .</li>"); // get single param from Request object
			 buf.append("</ul>");

               tokenizer = new StringTokenizer();
               var str = "foo,bar,bee,bop";
               var delimeter = ",";
              my_tokens_array = tokenizer.tokenize(str, delimeter);

			  token_iter = my_tokens_array.iterator();
			  buf.append("<ul> String Tokenizer Test");
			  while(token_iter.hasNext()){
				  buf.append("<li>" + token_iter.next() + "</li>";
				  }
			  buf.append("</ul>");

			 paramEle.innerHTML = buf.toString();

		   }catch(anErr){
				alert("an error occured: "+anErr.message);
		   }

		   
 }
*/
//*************************************************************************************
//  LICENSE AGREEMENT
//*************************************************************************************
/*
     These extensions are free software; you can redistribute it and/or modify it 
     under the terms of the GNU General Public License as published by the 
     Free Software Foundation; either version 2 of the License, or (at your 
     option) any later version, as long as this header remains in tact.

     This program is distributed in the hope that it will be useful, but WITHOUT 
     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
     FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
*/
//  
//*************************************************************************************


//****************************************************************************
//  TEMP PROTOTYPE OBJECT and Methods
//****************************************************************************

function Temp(){}

function _iniTemp(){

	this.popWinParams = "";
	this.displayManager = null;
	this.storageIsActive = false;
	this.parentList = new Array();
	this.count = 0;
}


function setPopWinParams(heit, wide){

//height=375,width=610,scrollbars=yes,resizable=yes,location=yes

	try{
	if(wide){
		var width = wide;//Math.round(getWindowWidth()*wide);
	} else {
		var width = Math.round(getWindowWidth()*.8);
	}

	if(heit){
		var height = heit;//Math.round(getWindowHeight()*heit);
	}else {
		var height = Math.round(getWindowHeight()*.6);
	}

	tmp.popWinParams = "height="+height+",width="+width+",scrollbars=yes,resizable=yes";
	}catch(anErr){
	tmp.popWinParams = "height=375,width=610,scrollbars=yes,resizable=yes,location=yes";
	}

	


}

function setPopWinParamsDebug(heit, wide){

	

	var width = Math.round(800);
	var height = Math.round(500);

	 tmp.popWinParams = "height="+height+",width="+width+",scrollbars=yes,resizable=yes,location=yes,status=yes";

}


function getPopWinParams(){

	return tmp.popWinParams.toString();
}

function setDisplayManager(dispMgr){
	tmp.displayManager = dispMgr;
	tmp.storageIsActive = true;
}

function getDisplayManager(){
	return tmp.displayManager;
}



//****************************************************************************
// UUID OBJECT
//****************************************************************************

function UUID(){
  this.alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}

function _genUUID(prefix){

	if(!prefix){
		prefix = "";
	}
	var id1 = prefix+Math.round(9999999999*Math.random());
	var id2 = prefix+Math.round(9999999999*Math.random());
	var txt1 =  this.getRandomLetters(4);
	var txt2 =  this.getRandomLetters(5);
	var txt3 =  this.getRandomLetters(4);
	var id = txt3 + id1 + txt2 + id2 + txt1;
	id = this.scramble(id);

	//alert("new Id "+id);
	return id;
}

   function _getRandomLetters(strLen){
	 
	 tempStr = "";

	 for(i=0; i<strLen; i++){
		randInt = Math.round(this.alphabet.length*Math.random());
        tempStr += this.alphabet.charAt(randInt);
	 }
	 return tempStr;
   }

   function _scramble(id){
	   tid = "";
      for(i=0; i<id.length; i++){
		  int1 = Math.round(id.length*Math.random());
		  
          tid += id.charAt(int1);

	  }
	  return tid;
   }

UUID.prototype.getRandomLetters = _getRandomLetters;
UUID.prototype.genUUID = _genUUID;
UUID.prototype.scramble = _scramble;

//****************************************************************************
//  ITERATOR PROTOTYPE OBJECT
//****************************************************************************

function Iterator(){
	this.count = 0;
	this.max   = 0;
	this.firstRun = true;
}

function _iteratorHasNext(){

	if(!this.firstRun){
	    this.count++;
	} else {
		this.firstRun = false;
	}

	if(this.count < this.max){
		return true;
	}else {
		this.count = 0;
		this.firstRun = true;
		return false;
	}

}

function _getArrayItemFromIterator(){

	return this.array[this.count];
}

function _getIteratorIndex(){
	return this.count;
}

function _getIteratorSize(){
	return this.max;
}


//****************************************************************************
//  REQUEST PROTOTYPE OBJECT
//****************************************************************************

function Request(locale){

    this.url = unescape(locale);
	this.params = new Array();
}

function RequestParameter(name, value){
	this.name = name;
	this.value = value;

}

function _getParameters(){
	return this.params;
}

function _setParameter(name, value){

	parameter = new RequestParameter(name, value);
	this.params.push(parameter);
}

function _setParameters(){
	
	try{

	     url = this.url;
	     var index = Math.ceil(url.indexOf("?")+1);
		 var end = url.length;
		 params = url.substr(index, end);
		 paramsArray = params.split("&");

		if(index){
			//alert("request params "+paramsArray.length);
			iter = paramsArray.iterator();
			while(iter.hasNext()){
				
			 request_param = paramsArray[iter.index()].split("=");
			
			 parameter = new RequestParameter(request_param[0], unescape(request_param[1]));

			   if(parameter.name != "?"){
			        this.params.push(parameter);
			        //alert(parameter.name+" has a value of "+parameter.value);
			    }//fi
			
		    }//rof
		 }//fi

	}catch(anErr){
	
			alert("error parsing request: \n "+anErr.message);

			window.status = "Error: "+anErr.message;
	}

}

function _getParameter(name){
	try{
    iter = this.params.iterator();
		while(iter.hasNext()){
			reqParams = iter.next();

			if(reqParams.name == name){
				return reqParams.value;
	        }
	  }
	}catch(anErr){
		alert("error getting parameter: "+anErr.message);
	}
 return false;
}
function _setPage(){

	var pageIndex = this.url.lastIndexOf("//");
	var paramIndex = this.url.indexOf("?");
	this.page = this.url.substr(pageIndex, paramIndex);

}
function _getPage(){
	return this.page;
}


//****************************************************************************
//  STRING TOKENIZER PROTOTYPE OBJECT
//****************************************************************************

function StringTokenizer(){

	this.string = "";
	this.delimeter = ","; // set to comma by default
	this.tokens = new Array();
}

function _tokenize(string, delimeter){
	//alert("tokenize: "+string);

     tempString = new String();
	 token_array = new Array();

	 for(i=0; i<string.length; i++){
          if(string.charAt(i) == delimeter){
			  token_array.push(tempString);
			//  alert("push token: "+tempString);
			  tempString = new String();
		  } else {
			  tempString += string.charAt(i);
		  }
			  

	 }
	 if(tempString.length>0){
	 token_array.push(tempString);
	 }
	 this.tokens = token_array;
    // alert("returning: "+token_array.length+" with tokens: "+token_array.toString());
	 return token_array;

}

function _getTokens(){
	return this.tokens;
}

StringTokenizer.prototype.tokenize = _tokenize;
StringTokenizer.prototype.getTokens = _getTokens;



//****************************************************************************
//  STRING BUFFER PROTOTYPE OBJECT
//****************************************************************************

function StringBuffer(){
	this.string = new String();
} // string buffer object


function _appendToBuffer(string){

	this.string += string;
}
function _bufferToString(){
	return this.string;
}

function _resetBuffer(){
	this.string = new String();
}


//****************************************************************************
//  ARRAY DOM EXTENSIONS
//****************************************************************************

// ARRAY DOM EXTENTIONS
//  extends the Array object in the dom
//

// removes item from array. returns a fresh array
//
// useage:  myArray = myArray.pop(anObject);
//
//------------------------------------------------
function _pop(anObject){

	tempArray = new Array();
	itr = this.iterator();

	while(itr.hasNext()){
		if(itr.next() != anObject){
			tempArray.push(itr.next());
		}
	}

	return tempArray;
}
// adds an obeject to array
function _push(anObject){

	var count = this.length++;
	this[count] = anObject;

	return this;
}

function _getIteratorForArray(){

	iter = new Iterator();
	iter.max = this.length;
	iter.array = this;

	return iter;
}

function _reverseArrayOrder(){
   tempArray = new Array();
   for(dci=this.length-1; dci>=0; dci--){
		tempArray.push(this[dci]);
   }

   return tempArray;

}



//****************************************************************************
//  DATE DOM EXTENSIONS
//****************************************************************************

function date_getInstancesForDay(dayInt){ // returns an array of dates for this day in this month of the date obj
    tempArray = new Array();

   for(di=1; di<this.getDaysInMonth(); di++){
		tdate = new Date();
		tdate.setMonth(this.getMonth());
		tdate.setFullYear(this.getFullYear());
		tdate.setDate(di);

		if(tdate.getDay() == dayInt){
			tempArray.push(di);
		}
   }

   return tempArray;

}


function date_yearIsLeapYear(){
  if ((this.getFullYear() % 4) == 0) {
		if ((this.getFullYear() % 100) == 0 && (this.getFullYear() % 400) != 0){
			return false;
		}
		return true;
	} else {
		return false;
	}
}

function date_getDaysInMonth(){
	dayArray = new Array();
	nmonth = this.getMonth();
	nyear = this.getFullYear();

	if(this.isLeapYear()){
		dayArray = this.lDOMonth;
	} else {
		dayArray = this.DOMonth;
	}
	return dayArray[nmonth];
}






// ASSORTED UTILITY METHODS
//******************************************************************************

function findFormElement(eleName){
	for(f1=0; f1<document.forms.length; f1++){
		currForm = document.forms[f1];
		for(fe=0; fe<currForm.elements.length; fe++){
			if(currForm.elements[fe].name == eleName || currForm.elements[fe].id == eleName){
				return currForm.elements[fe];
			}
		}
	}

	//*HACK
	// This should really only be looking for form elements.  
	// But in the advent that none is found, 
	// make a last ditch effort to return the element.
	ele = document.getElementById(eleName);
	if(ele){
		return ele;
	}

	return false;
}

function setRadioButtonSelected(radioId, radioValue){
	for(f1=0; f1<document.forms.length; f1++){
		currForm = document.forms[f1];
		for(fe=0; fe<currForm.elements.length; fe++){
			if(currForm.elements[fe].name == radioId || currForm.elements[fe].id == radioId){
				if(currForm.elements[fe].value == radioValue){
                   currForm.elements[fe].checked = true;
				   return true;
				}
			}
		}
	}

	return false;
}



// INSERTS params into a string from an array
//---------------------------------------------------------
	function insertParams(templateString, paramsArray){
        var stdOut = new String();
		stdOut = templateString;
		
		for(i=0; i<paramsArray.length; i++){

			var keyString = "%" + i;
			//alert("replace "+keyString+" with: "+paramsArray[i]);
            regExp = new RegExp(keyString, "g");
			stdOut = stdOut.replace(regExp, paramsArray[i]);
		}
		return stdOut;
	}


function genGuid(prefix){

	date = new Date();
	var id = prefix+Math.round(9999999999999*Math.random());
	//alert("new Id "+id);
	return id;
}


// PROTOTYYPE DEFINITIONS
//---------------------------------------------------------------
Array.prototype.pop              = _pop;
Array.prototype.push             = _push;
Array.prototype.iterator         = _getIteratorForArray;
Array.prototype.reverse          = _reverseArrayOrder;

Date.prototype.getInstancesForDay = date_getInstancesForDay;
Date.prototype.getDaysInMonth     = date_getDaysInMonth;
Date.prototype.isLeapYear         = date_yearIsLeapYear;

  // Non-Leap year Month days..
  Date.prototype.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 

  // Leap year Month days.. 
  Date.prototype.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

StringBuffer.prototype.append    = _appendToBuffer;
StringBuffer.prototype.toString  = _bufferToString;
StringBuffer.prototype.reset     = _resetBuffer;

Iterator.prototype.hasNext       = _iteratorHasNext;
Iterator.prototype.next          = _getArrayItemFromIterator;
Iterator.prototype.index         = _getIteratorIndex;
Iterator.prototype.size          = _getIteratorSize;


Request.prototype.getParameters  = _getParameters;
Request.prototype.setParameters  = _setParameters;
Request.prototype.setParameter   = _setParameter;
Request.prototype.getParameter   = _getParameter;
Request.prototype.getPage		 = _getPage;


RequestParameter.prototype.name  = "";
RequestParameter.prototype.value = "";


Temp.prototype.ini               = _iniTemp;


// ini default object
//-----------------------------------------

tmp = new Temp();
tmp.ini();

request = new Request(escape(window.location));
request.setParameters();