/*
 $Rev: 285 $ | $LastChangedBy: brieb $
 $LastChangedDate: 2007-08-27 14:05:27 -0600 (Mon, 27 Aug 2007) $
 +-------------------------------------------------------------------------+
 | Copyright (c) 2004 - 2007, Kreotek LLC                                  |
 | All rights reserved.                                                    |
 +-------------------------------------------------------------------------+
 |                                                                         |
 | Redistribution and use in source and binary forms, with or without      |
 | modification, are permitted provided that the following conditions are  |
 | met:                                                                    |
 |                                                                         |
 | - Redistributions of source code must retain the above copyright        |
 |   notice, this list of conditions and the following disclaimer.         |
 |                                                                         |
 | - Redistributions in binary form must reproduce the above copyright     |
 |   notice, this list of conditions and the following disclaimer in the   |
 |   documentation and/or other materials provided with the distribution.  |
 |                                                                         |
 | - Neither the name of Kreotek LLC nor the names of its contributore may |
 |   be used to endorse or promote products derived from this software     |
 |   without specific prior written permission.                            |
 |                                                                         |
 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS     |
 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT       |
 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      |
 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   |
 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT        |
 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,   |
 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY   |
 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT     |
 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   |
 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.    |
 |                                                                         |
 +-------------------------------------------------------------------------+
*/

function parseCookie(){
	//this function looks for the cookie element cookieName
	//in the cookie(s) in a document and returns its value
	
	var allcookies = document.cookie;
	var cookieArray = allcookies.split(";"); //may not be neccessary but it seems cleaner
	var cookieName = "c4modelsdotcomid="; //cookie name and an equals(=) sign added
	var pos;
	var value = false;
	
	for(i = 0; i < cookieArray.length; i++){
		//go the array
		pos = cookieArray[i].indexOf(cookieName);
		if(pos != -1){//if the cookie name is found
			
			value = cookieArray[i].substring(cookieName.length + pos, cookieArray[i].length);//extract the value
			break;
			
		}//end if
		
	}//end for
	
	return value;
	
}//end function --parseCookie--

function validateForm(theform){
	
	var i;
	var thereturn=true;
	var errorMessage="";
	
	var redirect;
	var sessId;
	
	
	//skip validation if cancel
	//NEEDED OR NOT?
	/*if (theform["cancelclick"]){
		if (theform["cancelclick"].value!=0) return true;
	}//end if*/


	//need to itterate though all fields... if you find
	// --not found-- anywhere.... invlaidate the form
	for(i=0;i<theform.length;i++){
		if(theform[i].value && theform[i].value=="--not found--"){
			errorMessage+=" * One or more fields have an invalid input.\n";
			thereturn=false;
			break;
		}//end if
	}//end for
		
	//validate required fields first
	for(i=0;i<requiredArray.length;i++){
		if(!theform[requiredArray[i][0]].value) {
			errorMessage+=" * "+requiredArray[i][1]+"\n";
			thereturn=false;
		}//end if
	}//end for
	
	//next integers
	for(i=0;i<integerArray.length;i++){
		var numcheck=theform[integerArray[i][0]].value;
		if(!validateInteger(numcheck)) {
		errorMessage+=" * "+integerArray[i][1]+"\n";
			thereturn=false;
		}//end if
	}//end for
	
	//next real numbers
	for(i=0;i<realArray.length;i++){
		var numcheck=theform[realArray[i][0]].value;
		if(numcheck =="") theform[realArray[i][0]].value="0";
		if(numcheck !="" && !validateReal(numcheck)) {
			errorMessage+=" * "+realArray[i][1]+"\n";
			thereturn=false;
		}//end if
	}//end for
	
	//next phone numbers
	for(i=0;i<phoneArray.length;i++){
		var thevalue=theform[phoneArray[i][0]].value;
		if(thevalue && !validatePhone(thevalue)) {
			errorMessage+=" * "+phoneArray[i][1]+"\n";
			thereturn=false;
		}//end if
	}//end for
	
	//next email
	for(i=0;i<emailArray.length;i++){
		var thevalue=theform[emailArray[i][0]].value;
		if(thevalue && !validateEmail(thevalue)) {
			errorMessage+=" * "+emailArray[i][1]+"\n";
			thereturn=false;
		}//end if
	}//end for
	
	//next password
	for(i=0;i<passArray.length;i++){
		var id = passArray[i][0];
		var thevalue = theform[id].value;
		var dupvalue = theform[id+"dup"].value;
		if(thevalue && !validatePass(thevalue, dupvalue)) {
			errorMessage += " * "+passArray[i][1]+"\n";
			thereturn = false;
		}//end if
	}//end for
	
	//Check for correct session.
	sessId = parseCookie();
	//add "c"
	sessId = "c" + sessId;
	redirect = getObjectFromID(sessId);
	
	if(!redirect){
		errorMessage += " * Your session has expired or you are not allowing cookies.\n";
		thereturn = false;
	}//end if
	
	if(errorMessage == "")
		theform.action = redirect.value;
	
	if(errorMessage!=""){
		errorMessage="\n"+errorMessage;
		
		alert("Form cannot be processed\n"+errorMessage);
		//showModal(errorMessage,"Cannot Save",300);
	}//end if
	
	
	
	if(thereturn){
		theform.submit();
	}//end if
	
}//end function --validateForm--


//validate a time (12 hour)
function validateTime(strValue){
	return (strValue == timeToString(stringToTime(strValue)))
}//end function


// validate dates
function validateDate(strValue) {
  return (strValue == dateToString(stringToDate(strValue)));
}//end function


//validate integer
function validateInteger(thevalue){
		while(thevalue.charAt(0)=="0") thevalue=thevalue.substring(1,thevalue.length);
		if(thevalue=="") thevalue="0";
		var newnum=parseInt(thevalue,10).toString();
		if(!(thevalue.length==newnum.length && newnum != "NaN")) return false; else return true;
}//end function


//validate realnumber
function validateReal(thevalue){
	
	while(thevalue.charAt(thevalue.length-1)=="0" && thevalue.indexOf(".")!=-1) thevalue=thevalue.substring(0,thevalue.length-1);
	if(thevalue.charAt(thevalue.length-1)==".") thevalue=thevalue.substring(0,thevalue.length-1);

	if (thevalue.charAt(0)==".") thevalue="0"+thevalue;
	if (isNaN(parseFloat(thevalue)) || thevalue.length!=((parseFloat(thevalue)).toString()).length) return false; else return true;
	
}//end function


// validate phone number
function validatePhone(thevalue){
	var phoneRegExpression = /^(?:[\+]?(?:[\d]{1,3})?(?:\s*[\(\.-]?(\d{3})[\)\.-])?\s*(\d{3})[\.-](\d{4}))(?:(?:[ ]+(?:[xX]|(?:[eE][xX][tT][\.]?)))[ ]?[\d]{1,5})?$/;
	return !(phoneRegExpression.exec(thevalue)==null);
}//end function


//look for a valid email address
// this is a loose validation
function validateEmail(thevalue){
	
  var result = false
  var theStr = new String(thevalue)
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;

}//end function --validateEmail--

function validatePass(thevalue, dupvalue){
	
	return(thevalue == dupvalue);
	
}//end function --validatePass--


//validate web page... make sure there is a http:// and at least on .
function validateWebpage(thevalue){
	
  var theaddress=thevalue.substring(8,thevalue.length-1);
  if(thevalue.substring(0,7)=="http://" && theaddress.indexOf(".",0) !=-1 ) return true;
  else return false;
  
}//end function


// Open an email
function openEmail(thefieldname){
	
	theemail= document.forms["record"][thefieldname].value;
	if(theemail!="" && validateEmail(theemail)) location.href="mailto:"+theemail;
	else alert("Email is either blank or invalid.");
	
}//end function


// Open a web page
function openWebpage(thefieldname){
	
	theweb= document.forms["record"][thefieldname].value;
	if(theweb!="" && validateWebpage(theweb)) {
		window.open(theweb);
	}
	else alert("Web address is either blank or invalid.");
	
}//end function


// checks and formats a field to dollars
function validateCurrency(theitem){
	
	theitem.value=numberToCurrency(currencyToNumber(theitem.value));
	
	//in case the field has an additional onchange code to be run
	if (theitem.thechange) theitem.thechange();
	
}//end function

function validatePercentage(thefield,precision){
	
	var percentage=getNumberFromPercentage(thefield.value);
	thefield.value=""+(Math.round(percentage*Math.pow(10,precision))/Math.pow(10,precision));
	if(thefield.value.indexOf(".")==-1) thefield.value+=".0";
	thefield.value+="%";
	
}//end function


function getNumberFromPercentage(thenumber){
	
	var markupnumber="";
	for(i=0;i<thenumber.length;i++){
		if (thenumber.charAt(i)!="%" && thenumber.charAt(i)!="+" && thenumber.charAt(i)!=",") markupnumber+=thenumber.charAt(i);
	}
	
	//get rid of trailing zeros and possibly "."
	while(markupnumber.charAt(markupnumber.length-1)=="0" && markupnumber.indexOf(".")!=-1) markupnumber=markupnumber.substring(0,markupnumber.length-1);
	if(markupnumber.charAt(markupnumber.length-1)==".") markupnumber=markupnumber.substring(0,markupnumber.length-1);

	if (isNaN(parseFloat(markupnumber)) || markupnumber.length!=((parseFloat(markupnumber)).toString()).length) markupnumber="0";
	markupnumber=parseFloat(markupnumber);
	return markupnumber;

}//end function --getNumberFromPercentage--


function checkUnique(tabledefid,column,checkvalue,excludeid){
	
	var theurl=APP_PATH+"checkunique.php?tdid="+parseInt(tabledefid);
	theurl=theurl+"&c="+encodeURIComponent(column);
	theurl=theurl+"&val="+encodeURIComponent(checkvalue);
	theurl=theurl+"&xid="+parseInt(excludeid);


	loadXMLDoc(theurl,null,false);
	
	response = req.responseXML.documentElement;
	thevalue = response.getElementsByTagName('isunique')[0].firstChild.data;
	
	if(thevalue==1) return true; else return false;
	
}//end function --checkUnique--

