//Validate the whole form. function checkWholeForm(theForm) {						var error="";		var i=0;		var j=0;		var countRadio=0;		var codeError="";		var validEmail="";		var reqField=new Array();		var codevalue=new Array();		        removeIcons();//clear the page 		reqField =reqFields(theForm);									for (i=0;i<3;i++)   {				error+=isEmpty(reqField[i][0],reqField[i][1]);   //check if fields are empty         		}								error+=checkDropdown(theForm.country.selectedIndex,"country");		    validEmail=checkEmail (theForm.email.value);//validate emails		if(validEmail!="") { //an error msg was returned				error+=validEmail;		}     		else {//email is valid, validate the confirm email field				error+=confirmEmail (theForm.confirm_email.value,theForm.email.value);		}				error+=isEmpty(reqField[3][0],reqField[3][1]); 							for (i=0; i<theForm.device_driver.length; i++) { 						if (theForm.device_driver[i].checked) 	{				      countRadio++;           				}				}  				error+= checkRadio(countRadio,"devicedriver");						//We want to do a different check for the postal code, hence stopping before the last element in reqField.		for (i=4; i<reqField.length - 1; i++)  {						error+=isNumeric (reqField[i][0],reqField[i][1]); //if phone are not empty, check that they only contain numeric		}				//Check the postal code		error+=isValidPostalCode(reqField[8][0],reqField[8][1]);		       error+=validAllCode (theForm);				if (error.length>1) { //there are errors, display them on the screen and return false						warning(error,0);				return false;		}				return true;}//this function is used to add a warning icon by an indicated field on the page//It takes the id of the field then looks up its parent (column td or td1 followed by the name of the object) in the tree node.//The icon inserted after the text on the object parent area. 	function addIcon(obj){	 if (document.getElementById("icon"+obj)==undefined) {					 			var warningImg=newImage("http://developer.apple.com/images/icon_warning.gif","Warning Icon","20","20","icon"+obj,"0");	//create warning icon						if (obj.search(/creator/)==-1)  {//if object is a not creator code field				document.getElementById("td"+obj).insertBefore(warningImg,document.getElementById("td"+obj).firstChild); //	get the column that contains the field and insert the warning icon before the field							}			else {	//object is a creator code field 								    document.getElementById("td1"+obj).insertBefore(warningImg,document.getElementById("td1"+obj).firstChild);//get the column that contains the field and insert the warning icon before the field													}			      }      }//valid all creator code fieldsfunction validAllCode (theForm){		var error="";		var j=0;		var codeError="";		var codeValue=new Array();				var newHex =new Array();	    var k=0;		var allInput=document.getElementsByTagName("input"); 				for (var i=0;i<allInput.length;i++) 		{		//if the id of an element contain creatorcode then it is a creatorcode field				if (allInput[i].id!="" && allInput[i].id!=undefined){						if (allInput[i].id.search(/^creatorcode*/)!=-1)    {   																		//check if the field is not empty											codeError=isEmpty(theForm[allInput[i].id].value,allInput[i].id);																									if (codeError=="")  {     //the code field is not empty 																								var myValue= new Array (theForm[allInput[i].id].value,theForm[allInput[i].id].name);//get the value and the name of teh field eg ZPAP and creatorcode2																												if (myValue.length==8)  { 																codeValue[j]= myValue.toUpperCase();//convert to uppercase if the length is 8 														}														else {																codeValue[j]= myValue;														}																																				codeError=validCode(theForm[allInput[i].id].value,allInput[i].id);   //validate creator code     	   														if (codeError!="")   {//a string was returned																	  if (codeError==theForm[allInput[i].id].value){  //if the error msg is the name of the creator code field then we have an invalid hex 																	  																			  newHex[k]=codeError;//keep track of the invalid hex																			  k++;																	  }																	  else 	{ //the string returned is an error msg																			  error+= codeError;																		  }																										         }								                        j++;																		  }										else 	  {												if (error.search(codeError)==-1) {														error+=codeError;	   														}																				}					                     }	//end of if 			            }//end of if 	}//end of for 			if (newHex.length>1) {				error+=newHex.join(", ")+" are not legal hexadecimal codes. The values need to be between Hex 20 (Decimal 32) and 7F (Decimal 127)(inclusive)\n";	}	else  if  (newHex.length==1)  {				error+=newHex[0]+" is not a legal hexadecimal code. The values need to be between Hex 20 (Decimal 32) and 7F (Decimal 127)(inclusive)\n";	}		if (codeValue.length >1) {			if (isUnique(codeValue)) { //check if there are no duplicate					error+="Please be sure that each Creator Code entered below is unique\n";							}			}	error=removeDuplicate(error);//remove duplicate errors from the string							return error;}//Check whether an array contains dupplicate value. function isUnique(obj){		var error="";   		var found=false;		var j=1;		obj.sort(); //sort the array of codes									for (var i=0;i<obj.length;i++) 	{								if (j<obj.length ) {						   if ((obj[i][0]==obj[j][0]) ){	//duplicates were found  							   addIcon(obj[i][1]); //add warning icon 							  addIcon(obj[j][1]);//add warning icon 							   						   found=true;						  }				 }				 j++;		}				return found;  }			//It is used to remove all the displayed icons and error mesages on the page	function removeIcons (){         			var allImgs=document.getElementsByTagName("img"); 				var existDiv=document.getElementById("warningdiv"); //this div contains all the error messages		var existClaim=document.getElementById("duplicatebox");//this div is used to display codes already existing in the db						if (existDiv!=null) {					existDiv.parentNode.removeChild(existDiv); //if the div exists then remove it from the interface		}		if (existClaim!=null) {					existClaim.parentNode.removeChild(existClaim); //if the div exists then remove it from the interface		}								//search for teh icons among all the img tags on the page		for (var i=0;i<allImgs.length;i++) 		{						if (allImgs[i].id!="" && allImgs[i].id!=undefined){						if (allImgs[i].id.search(/^icon*/)!=-1)    allImgs[i].parentNode.removeChild (allImgs[i]);     								}		}	    	  }//Remove duplicate values from an string.//It takes a string as an argument and returns another one.//The string is converted into an array, then sorted.//It compares values in the array and puts blank in the //array slot when it has a match.function removeDuplicate (error){        var temp= error.split("\n");		temp.sort();			var newObj =new Array();				for (var i=0;i<temp.length;i++)		{						if (temp[i]!=" ")    {						for (var j=i+1;j<temp.length;j++) {														if (temp[i]==temp[j]) {										temp[j]=" ";																}												}				}						}		j=0;			for (var i=0;i<temp.length;i++) {				if (temp[i]!=" ") {										newObj[j]=temp[i]+"\n";						j++;					}		}		return newObj.join("\n");		}    	  //validate code entered in a creator code field//It takes the value and the name of the textbox as arguments.//The error message is blank if the creator code does not have any errors.//The error message is a string if the creator code contains errors. //It calls the addIcon function to display an error icon by the field side.function validCode (strn,fieldName){		var error="";		var codeError="";		var codeLength=strn.length;				switch(codeLength)		{				case 4:										codeError=isLowerCase(strn,fieldName);				if (codeError!="")   {							error+=codeError;											}				break;												case 8: 				codeError=isHex(strn,fieldName);				if (codeError!="")   {						error+= codeError;				}						break;								default: 				error+="Enter either 4-character ASCII or 8-character hexadecimal character codes\n";				addIcon(fieldName); //remove whitespace from string then send result to addIcon				break;		}								return error;}//It uses the ascii table to check if a four character string contains only lower case characters or is valid ascii//It returns an error msg if the number of lower case characters is equal to 4 or if the number of ascii characters//is not equal to 4.function isLowerCase(strn,fieldName){		var error="";		var lowerFlag=0;		var Ascii=0;		var isNumber=0;				for(var i=0;i<4;i++) 		{			   var result=strn.charCodeAt(i);			   						   if ((96<result) && (result<123) ) {			   			lowerFlag++;          //CHECK IF lowercase			   	}					   if ((31<result) && (result<128))  {			   				Ascii++;        // CHECK IF ASCII			   }							  					}			    if (Ascii!=4) {	    		error+="Four character codes must consist of lower ASCII characters between decimal 32  and decimal 127 (inclusive) and cannot contain all lower case characters\n";	     }			     		if (lowerFlag==4) {				error+= "Four character codes must consist of lower ASCII characters between decimal 32  and decimal 127 (inclusive) and cannot contain all lower case characters\n";		}								 if (error!="") {				 addIcon(fieldName); //remove whitespace from string then send result to addIcon		}		 					   		return error;}//It finds the child of a node or the previous sibling of a node//It loopds tru the tree until a valid node (not null or undefined)//is foundfunction findKin (obj,relation) {    var objectId=document.getElementById(obj);    var creatorParent="";	var temp="";		if (relation=="previousSibling") {			temp=objectId.previousSibling;	}	else if (relation=="lastChild") {			temp=objectId.lastChild;	}	   if ((temp.id==undefined) || (temp.id==""))     {				creatorParent=temp;  				  			while(creatorParent.id==undefined || creatorParent.id=="")          				creatorParent= creatorParent.previousSibling;                       }                else {        	creatorParent=temp;         }	            return creatorParent;}//delete code field from page//It gets the id of the creator code to be removed.//If the id is not null then it looks for the creator code  parent (cell) and grandparent (row). //It then checks whether the addAnotherCode is among the creator code parent children.//If it is among the children, the addAnotherCode will be inserted in the last cell of the previous row. //Proceed to remove the row containing the creator code to be deleted.function deleteCode(obj){		var objectId=obj.id;		var countNode=0;												if  (objectId!=null) {  								var codeNb=objectId.substring(10,objectId.length);												var creatorParent=document.getElementById("td3creatorcode"+codeNb);					var creatorGrdPrnt=document.getElementById("trcreatorcode"+codeNb);										var creatorGrdPrntPrevSib=findKin(creatorGrdPrnt.id,"previousSibling"); //find previous row  this is where teh error is, should go to prev node but going prev inedex if idex=1 prev will be 0 even though got 2 nodes before , check addmore counter shuld increase and not decrease													//check if addAnotherCode button is among the column children					for (var i=0; i<creatorParent.childNodes.length; i++){	       								if (creatorParent.childNodes[i].id=="addAnotherCode") {								             countNode++;            								}             						  }						  											if (countNode>0) {							codeNb=creatorGrdPrntPrevSib.id.substring(13,creatorGrdPrntPrevSib.id.length); //get index 											var creatorGrdPrntPrevSibChld=document.getElementById("td3creatorcode"+codeNb);							var creatorGrdPrntPrevSibChild=findKin(creatorGrdPrntPrevSibChld.id,"lastChild");  							creatorGrdPrntPrevSibChld.insertBefore(document.getElementById("addAnotherCode"),creatorGrdPrntPrevSibChild.nextSibling);				  					}							    document.getElementById("addCode").removeChild(creatorGrdPrnt);									}							 		}//Create a new Input element.// It takes the type, size, maxlength, name, id, href, width, and class name of the div to be createdfunction newInput (mySize,myMaxlength,myName,myClass,myId,myType,myValue,myFunction){		var newInput=document.createElement("input");		if (mySize!="") {				newInput.setAttribute("size",mySize);		      }				if (myMaxlength!="") {				newInput.setAttribute("maxlength",myMaxlength);		      }				if (myName!="") {		       newInput.setAttribute("name",myName);		      }       		if(myClass!="") {		       newInput.setAttribute("class",myClass);		      }		if(myId!="") {		     newInput.setAttribute("id",myId);		    } 		if (myType!=""){		     newInput.setAttribute("type",myType);		     }  						if(myValue!="")  {		     newInput.setAttribute("value",myValue);			    } 		if(myFunction!="")	{		      newInput.setAttribute("onclick",myFunction);  		     }  		return newInput;}//This function determines the next number for the creator code field.//It looks for creator codes among all the form input fields, then looks//for the greatest index among them. That index is incremented then returned.function nextCodeIndex() {        var last=0;		var allInput=document.getElementsByTagName("input"); 				for (var i=0;i<allInput.length;i++) 		{						if (allInput[i].id!="" && allInput[i].id!=undefined){										if (allInput[i].id.search(/^creatorcode*/)!=-1) {								last=Math.max(allInput[i].id.substring(11,allInput[i].id.length),last);						}															}		}								last++;return last;}//Add more creator code to the page.//If the user clicked the "OK" button on the prompt box, only creator code will be added.//if the user entered a number X in the prompt box, X creator code will be added to the UI//If the user clicked the "cancel" button, no creator code will be added.//Once a new creator code is created, it is followed by a delete code button and the addAnotherCode button.function addMoreCode(){			        var counter=nextCodeIndex();							var addAnotherCodeId=document.getElementById("addAnotherCode");									var newTr=newRow ("left","top","trcreatorcode"+counter);				var new1Td=newColumn("210","td1creatorcode"+counter);				var new2Td=newColumn("20","td2creatorcode"+counter);				var new3Td=newColumn("418","td3creatorcode"+counter);									var mySpan =document.createElement("span");				mySpan.setAttribute("class","red");							    var newText =document.createTextNode("*");				var new1Img=newImage("http://developer.apple.com/images/1dot.gif","","20","1","");				var new2Img=newImage("http://developer.apple.com/images/1dot.gif","","20","1","");				var new3Img=newImage("http://developer.apple.com/images/1dot.gif","","20","1","img"+counter+"3");								var new1Input=newInput ("30","8","creatorcode"+counter,"quarterfield","creatorcode"+counter,"text","","");				var new2Input=newInput ("","","deleteCode"+counter,"","deleteCode"+counter,"button","Delete Code","deleteCode(this);"); 												mySpan.appendChild(newText);				new3Td.appendChild(new1Input);				new3Td.appendChild(new2Img);	   				new3Td.appendChild(new2Input);				new3Td.appendChild(new3Img);				new3Td.appendChild(addAnotherCodeId);								new2Td.appendChild(new1Img);			   			    new1Td.appendChild(mySpan);				newTr.appendChild(new1Td);				newTr.appendChild(new2Td);				newTr.appendChild(new3Td);								counter++;							document.getElementById("addCode").appendChild(newTr);			}//Create a Img element//It takes the src, alt, width, height, id, and border as arguments.function newImage(mySrc,myAlt,myWidth,myHeight,myId,myBorder){		var newImg=document.createElement("img");		if (mySrc!="")     newImg.setAttribute("src",mySrc);		if (myAlt!="")     newImg.setAttribute("alt",myAlt);		if (myWidth!="")   newImg.setAttribute("width",myWidth);		if (myHeight!="")  newImg.setAttribute("height",myHeight);		if (myBorder!="")  newImg.setAttribute("border",myBorder);		if (myId!="")      newImg.setAttribute("id",myId)		return newImg;			}//Create a Tr element//It takes the align, valign , and id as argumentsfunction newRow (myAlign,myValign,myId){		var newTr=document.createElement("tr");		if(myAlign!="")   newTr.setAttribute("align",myAlign);		if(myValign!="")  newTr.setAttribute("valign",myValign);		if(myId!="")      newTr.setAttribute("id",myId);		return newTr;}//Create a Td element//It takes the width and Id as arguments.function newColumn(myWidth,myId){		var newTd=document.createElement("td");		if(myWidth!="")   newTd.setAttribute("width",myWidth);		if(myId!="")      newTd.setAttribute("id",myId);				return newTd;}//Check whether a creator code contains only hex numbers and returns an error message.//It takes the value and the name of the creator code  as arguments.//The error message is blank if the textbox contains only hex numbers.//The error message is a string if the textbox does not contain hex numbers. //It calls the addIcon function to display an error icon by the field side.function isHex(strng,fieldName){		var error="";		var wordRight=/^[a-fA-F0-9]*$/;						if (!(wordRight.test(strng))) 		  {					   error="Eight-character codes must use legal hexadecimal digits only (0-9,A-F), in the range of Hex 20 - Hex 7F(inclusive)\n";			   addIcon(fieldName); //remove whitespace from string then send result to addIcon		}				else {							var j=0;					var k=2;					var numberRight=/^\d*$/;															for (var i=0;i<4;i++) {										var target =strng.substring(j,k);								if (!(numberRight.test(target[0]))) {											error=strng;							addIcon(fieldName); //remove whitespace from string then send result to addIcon												break;										}										else {											  var result=parseInt(target,16);//convert															   if ((result < 32 )|| (127< result)){									error=strng;							   		addIcon(fieldName); //remove whitespace from string then send result to addIcon													  break;							   }					}					j=k;					k=k+2;										}//end of for 										}        return error;}//Return an array of arrays made of a textbox value and its name.function reqFields(theForm){    	var reqFields=  new Array(new Array(theForm.company.value,"company name"),    					new Array(theForm.first_name.value,"first name"),						new Array(theForm.last_name.value,"last name"),						new Array(theForm.product_name.value,"product name"),									new Array(theForm.area_code.value,"area code"),						new Array(theForm.country_code.value,"country code"),						new Array(theForm.phone_number.value,"phone number"),							new Array(theForm.phone_extension.value,"phone extension"),						new Array(theForm.postal_code.value,"postal code")												);                        return reqFields;}// Check whether a radio button was seleted and returns an error message.//It takes the radio button value and the name of the radio as arguments.//The error message is blank if the user selected a radio.//The error message is a string if the user did not check anything. //It calls the addIcon function to display an error icon by the field side.function checkRadio(checkvalue,fieldName) {		var error = "";		if (!(checkvalue==1)) {				error = "Device Driver\n";    				addIcon(fieldName); //remove whitespace from string then send result to addIcon		 }		 return error;}// Check whether a contry was selected from the drop dowm menu and returns an error message.//It takes the user choice and the name of the textbox as arguments.//The error message is blank if the user chose a country.//The error message is a string if the user did not choose anything. //It calls the addIcon function to display an error icon by the field side.function checkDropdown(choice,fieldName) {		var error = "";		if (choice == "0") {				error = "Country\n";				addIcon(fieldName); //remove whitespace from string then send result to addIcon		}    		return error;		}    //Check whether a textbox value contains only numbers and returns an error message.//It takes the value and the name of the textbox as arguments.//The error message is blank if the textbox contains only numbers.//The error message is a string if the textbox does not contain numbers. //It calls the addIcon function to display an error icon by the field side.function isNumeric (strng,fieldName){		var error="";						var numberRight=/^\d*$/;				if (!(numberRight.test(strng))) {					error=capitalizeWord(fieldName)+" can only contain numeric characters\n";					if ((fieldName=="area code")|| (fieldName=="phone number")||						(fieldName=="country code") ||(fieldName=="phone extension"))  {							addIcon("phone");					 }								else {						 addIcon(fieldName.replace(/\s/g,"")); //remove whitespace from string then send result to addIcon					}     		}		return error;}//Check whether a textbox value contains only numbers, letters, dashes, or spaces and returns an error message.//Empty strings are OK.//It takes the value and the name of the textbox as arguments.//The error message is blank if the textbox contains only numbers.//The error message is a string if the textbox does not contain numbers. //It calls the addIcon function to display an error icon by the field side.function isValidPostalCode(string, fieldName){	var error = "";	var pattern = /^[\w -]*$/;		//If the string is empty, forget it.  Otherwise, error out if we don't preg_match		if(!(pattern.test(string)) && string != '') {		error=capitalizeWord(fieldName)+" can only contain alphanumeric characters\n";		if ((fieldName=="area code")|| (fieldName=="phone number")||			(fieldName=="country code") ||(fieldName=="phone extension"))  {				addIcon("phone");		 }					else {			 addIcon(fieldName.replace(/\s/g,"")); //remove whitespace from string then send result to addIcon		}	}	return error;}//Create the warning box //It makes the page jump to the top once the warning box has been added.//It takes a string  and a number as arguments. The string contains all the errors on the page//separated either by a \n or $. If the number is 0 then these errors were checked by JavaScript. //If the number is 1 then the errors were checked by PHP.function warning(errorsMsg,number){			var existDiv=document.getElementById("warningdiv");			if (existDiv!=null) existDiv.parentNode.removeChild(existDiv);					var error=new Array();			var newP=document.createElement("p");			var newPMsg=document.createTextNode("Please correct the following and resubmit the form:");			var newList =document.createElement("ul"); 												var newWarnBox=newDivision("warning","warning","","","warningbox");			var newDiv=newDivision("warningdiv","warningdiv","href","650px","");						var warningImg=newImage("http://developer.apple.com/images/icon_warning.gif","Warning Icon","20","20","divwarn","0");				       	if (number==0)  {	       				error=errorsMsg.split("\n"); //error checked by JavaScript 	       	}				       	else if (number==1) {	       			error=errorsMsg.split("$ "); //error checked by PHP	       	}			       		 			newWarnBox.appendChild(newPMsg); 									for (var i=0;i<error.length;i++) { 								if (error[i]!="") {					      var errorMsg = document.createTextNode(error[i]);  				          var newSquare=document.createElement("li");					      newSquare.appendChild(errorMsg);					      newList.appendChild(newSquare);					}			}			newWarnBox.appendChild(newList);			newDiv.appendChild(newWarnBox);						document.getElementById("CreatorCodeReg").parentNode.insertBefore(newDiv,document.getElementById("CreatorCodeReg"));			document.location.href="#top";	  }//Create a new link element.// It takes the name, id, href, width, and class name of the div to be createdfunction newLink(myName,myId){		var newLink=document.createElement("a");		if(myName!="")  newDiv.setAttribute("name",myName);		if(myId!="")    newDiv.setAttribute("id",myId);				return newDiv;				}//Create a new div element.// It takes the name, id, href, width, and class name of the div to be createdfunction newDivision(myName,myId,myHref,myWidth,myClass){		var newDiv=document.createElement("div");		if(myName!="")  newDiv.setAttribute("name",myName);		if(myId!="")    newDiv.setAttribute("id",myId);		if(myHref!="")  newDiv.setAttribute("href",myHref);		if(myWidth!="")  newDiv.style.width=myWidth;		if(myClass!="") newDiv.setAttribute("class",myClass);		return newDiv;				}//Validate the confirm email field and returns an error message.//It checks whether the confirm email is empty, or match the email field value.//It takes the the email and confirm fields values as arguments.//It calls the addIcon function to display an error icon by the confirm email side.function confirmEmail(search,target){		var error="";		if (search == "")   {					error+= "Confirm your Email Address\n";		}					else {					if (search!=target) {					error+="The email addresses you entered are different\n";				}		}		if (error!="")  {				addIcon("confirm");			}			return error;}//Validate the email field and returns an error message.//It checks whether the email is empty, valid, or contains illegal characters.//It takes the value and the name of the email textbox as arguments.//It calls the addIcon function to display an error icon by the email side.function checkEmail (strng,fieldName) {		var error="";		if (strng == "") {				error += "Email Address\n";			}			else  {					var emailFilter=/^.+@.+\..{2,4}$/;					if (!((emailFilter.test(strng)))) {							error += "Enter a valid Email Address\n";					}							else {				        //test email for illegal characters					     var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/;						 if (strng.match(illegalChars)) {						 		error += "The Email Address contains illegal characters\n";						 }							}			}	    if (error!="") {	    		addIcon("email");	    	}		    return error;    }//Check whether a textbox is empty or not and returns an error message.//It takes the value and the name of the textbox as arguments.//The error message is blank if the textbox is not empty.//The error message is a string if the textbox is empty. //It calls the addIcon function to display an error icon by the field side.function isEmpty(strng,fieldName) {		var error = "";								if (strng.length == 0 )   {				  if (fieldName.search(/^creatorcode*/)==-1)  {				  			error = capitalizeWord(fieldName)+"\n";				  }							  else {				  		error = "Creator Code cannot be empty\n";					  }				  			    addIcon(fieldName.replace(/\s/g,"")); //remove whitespace from string then send result to addIcon   		}		return error;	  }//this function is used to capitalize the first characters of each word in an expressionfunction capitalizeWord(strng){	var temp=strng.split(" ");		for(var i=0;i<temp.length;i++) {			temp[i]=temp[i].substring(0,1).toUpperCase()+temp[i].substring(1,temp[i].length);   	}				return temp.join(" ");}