// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

var min_year = 1900; // defines lowest year in year menu
var max_year = 2005; // defines highest year in the year menu

// make this false to prevent the weekday element from being displayed
var weekday_showing = false;

// make this true to make dayofweek return a number (0-6)
var dayofweek_returned_as_number = false;

// make this true to make month return a number (0-11)
var month_returned_as_number = true;

if (min_year <= 400)
	alert("Minimum year must be higher than 400 for this algorithm to work.");
	
// The following code adds three methods to the built-in Date object
function _strMonth() {
	var months = new Array("January", "February", "March", "April",
	   "May", "June", "July", "August", "September", "October", 
	   "November", "December");
return months[this.getMonth()];
}

function _strDay() {
	var days= new Array("Sunday", "Monday", "Tuesday", "Wednesday", 
	    "Thursday", "Friday", "Saturday");
return days[this.getDay()];
}

function _weekOf() {
	sunday = ((arguments[0]==null) || (!arguments[0])); // Check for optional argument
return (new Date(this - ((this.getDay() - ((sunday) ? 0 : 1)) *24*60*60*1000)));
}

// Add these methods to all dates
Date.prototype.weekOf = _weekOf;
Date.prototype.strMonth = _strMonth;
Date.prototype.strDay = _strDay;

function changeDays(numb,date_form,aname) {
	MonthCtrl = eval("date_form." + aname +"month");
	DayCtrl = eval("date_form." + aname +"day");
	YearCtrl = eval("date_form." + aname +"year");
	
	mth = eval(MonthCtrl.selectedIndex);
	sel = eval(YearCtrl.selectedIndex);
	yr = eval(YearCtrl.options[sel].text);

	if (numb != 1) {
		numDays = numDaysIn(mth,yr);
		eval("date_form." + aname +"day.options.length="+numDays) ;
		for (i=27;i<numDays;i++) {
			j=i+1;
			eval("date_form." + aname +"day.options["+i+"].text = "+j);
		}
	}
}
	
function numDaysIn(mth,yr) {
	if (mth==3 || mth==5 || mth==8 || mth==10) return 30;
	else if ((mth==1) && leapYear(yr)) return 29;
	else if (mth==1) return 28;
	else return 31;
}

function leapYear(yr) {
	if (((yr % 4 == 0) && yr % 100 != 0) || yr % 400 == 0)
		return true;
	else
		return false;
}

function arr() {
	this.length=arr.arguments.length;
	for (n=0;n<arr.arguments.length;n++) {
		this[n] = arr.arguments[n];
	}
}

weekdays = new arr("Sun.","Mon.","Tues.","Wed.", "Thurs.","Fri.","Sat.");
 
months = new arr("Jan.","Feb.","Mar.","Apr.","May","Jun.","Jul.","Aug.","Sep.","Oct.","Nov.","Dec.");
 
var cur = new Date();

function getWeekDay(mth,day,yr) {
	first_day = firstDayOfYear(yr);
	for (num=0;num<mth;num++) {
		first_day += numDaysIn(num,yr);
	}
	first_day += day-1;
return first_day%7;
}

function firstDayOfYear(yr) {
	diff = yr - 401;
	return parseInt((1 + diff + (diff / 4) - (diff / 100) + (diff / 400)) % 7);
}

// fixes a Netscape 2 and 3 bug
function getFullYear(d) { // d is a date object
	yr = d.getYear();
	if (yr < 1000)
		yr+=1900;
	return yr;
}


function datedrop(myname,feeddate){
	//alert (feeddate);
	if(!feeddate)
	{
		d=new Date();
		edmonth=d.getMonth();
		edday=d.getDate();
		edyear=d.getFullYear();
	}
	else
	{
		d=new Date(feeddate)
		edmonth=d.getMonth();
		edday=d.getDate();
		edyear=d.getFullYear();
	}

	// write month element
	
	document.write("<select name="+myname+"month size=1 onChange='changeDays(0,this.form,"+'"'+myname+'"'+")'>");
	for (i=1;i<13;i++)
	 document.write("<option"+(month_returned_as_number?" value="+i:"")
	  +(edmonth==i-1?" selected":"")+">"+months[i-1]+"\n");

	// write day element
	document.write("</select><select name="+myname+"day size=1 onChange='changeDays(0,this.form,"+'"'+myname+'"'+")'>\n");
	for (i=1;i<=numDaysIn(d.getMonth(),getFullYear(d));i++)
	 document.write("<option"+(edday==i?" selected":"")+">"+i+"\n");

	// write year element
	document.write("</select><select name="+myname+"year size=1 onChange='changeDays(0,this.form,"+'"'+myname+'"'+")'>\n");
	for (i=min_year;i<max_year;i++)
	 document.write("<option"+(edyear==i?" selected":"")+">"+i+"\n");
	document.write("</select>");
}	

function validateForm(obForm, aFields)
{
	if (checkForEmpties(obForm, aFields) == false ||
	 checkForPhoneNumbers(document.ccForm.phone) == false ||
	 checkForValidMail(obForm, aEmail) == false ||
	 checkAgreement(document.ccForm) == false)
	{
		return false;
	}
	else
	{
		return true;
	}
}

/*An array of values from the form */
aFields = new Array();
aFields.push("name");
aFields.push("position");
aFields.push("company");
aFields.push("address");
aFields.push("city");
aFields.push("province");
aFields.push("postalcode");
aFields.push("emailaddress");


/*An array of values from the form */
aEmail = new Array();
aEmail.push("emailaddress");


/***************************************************
 * Function 	checkForEmpties
 * Purpose	This routine will check to see if the indicated fields
 *		have a value in them.  It returns true if all indicated
 *		fields have some sort of value in them, false otherwise.
 * Parms	obForm - The Form we are looking at
 *		aFldList - A list of fields to look at
 ***************************************************/
 function checkForEmpties(obForm, aFldList)
 {
 	sError = "Indicated Field is Blank!";
 	sIfExp = "bIfValue = sVal =='';" ;
 	
 	return commonCheckRoutine(obForm, aFldList, sIfExp, sError, null)
 }
 
 /*****************************************************************
*
*
*****************************************************************/
function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

/*****************************************************************
*
*
*****************************************************************/
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

/*****************************************************************
*
*
*****************************************************************/
function checkInternationalPhone(strPhone)
{
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length == minDigitsInIPhoneNumber);
}

/*****************************************************************
*
*
*****************************************************************/
function checkForPhoneNumbers(Phone)
{
	if ((Phone.value==null)||(Phone.value==""))
	{
		alert("Please Enter your Phone Number")
		Phone.focus()
		return false
	}
	if (checkInternationalPhone(Phone.value)==false){
		alert("Please Enter a Valid Phone Number in the Format XXX-XXX-XXXX or (XXX) XXX-XXXX.")
		Phone.value=""
		Phone.focus()
		return false
	}
	return true
 }
 
 /*******************************************************
 * Function Check For Valid Mail
 * Purpose	This routine will ensure that the given fields
 *				have a "valid" phone number contained within them.
 * Parms		obForm	- The Current form we are working with
 *				aFldList - The Set of fields that are to match.
 ********************************************************/
 function checkForValidMail(obForm, aFldList)
 {
		sMailPat = /^\w[\w\.-]*@[\w-]|\.([\w-]+\.)*\w$/;
		
		sError = "Incorrect Mail Format for Field";
		sIfExp = "bIfValue = !myRegExp.test(sVal);";
		
		return commonCheckRoutine(obForm, aFldList, sIfExp, sError, sMailPat);	
 }
 
 /***************************************************
 * Function 	
 * Purpose	
 * Parms	
 ***************************************************/ 
 function checkAgreement(form) 
 {
	  if (form.agreement.checked == false)
	  {
		  alert( 'You must acknowledge that you agree to the terms before continuing.');
		  return false;
	  } 
	  else 
	  { 
	  	return true;
	  }
  }
 
 /******************************************************
  * Function 	commonCheckRoutine
  * Purpose		We note that a lot of the checkroutines have 
  *				commanility in their approach to solving the 
  *				validation problem.  This routine will allow us
  *				to centralize a lot of the checking algorithm in
  *				on function so as to cut down on potential errors.
  * Parms		obForm  - The Form we are checking.
  *				aFldList - The List of fields we wish to check.
  *				sIfExp - The expression to evaluate for our If Statement
  *				sError - The error statement to be printed with the alert

  *				myRegExpr - An optional parameter that includes a 
  *								regular expression to evaluate.
  *								Note the sIfExpr must set a variable 
  *								bIfValue to work with with this function
  *								It Expression needs to starts as bIfValue =			
 	*********************************************************/
 function commonCheckRoutine(obForm, aFldList, sIfExpr, sError, myRegExp)
 {						
	for(i=0; i< aFldList.length; i++)
  	{
  		exp = "sVal = obForm." + aFldList[i] + ".value  ;";
  		eval(exp);
  				
  		eval(sIfExpr);
  				
  		if (bIfValue)
  		{
  			alert(sError);
  			exp = "obForm." + aFldList[i] + ".focus();";
  			eval(exp);
			//exp = "obForm." + aFldList[i] + ".select();";
			//eval(exp);
			//alert("Returning False from common Check Routine");
  			return false;
  		}				
  	}
  	return true;
 }

String.prototype.tokenize = tokenize;
function tokenize()
  {
     var input             = "";
     var separator         = " ";
     var trim              = "";
     var ignoreEmptyTokens = true;
     try {
       String(this.toLowerCase());
     }
     catch(e) {
       window.alert("Tokenizer Usage: string myTokens[] = myString.tokenize(string separator, string trim, boolean ignoreEmptyTokens);");
       return;
     }
     if(typeof(this) != "undefined")
       {
          input = String(this);
       }
     if(typeof(tokenize.arguments[0]) != "undefined")
       {
          separator = String(tokenize.arguments[0]);
       }
     if(typeof(tokenize.arguments[1]) != "undefined")
       {
          trim = String(tokenize.arguments[1]);
       }
     if(typeof(tokenize.arguments[2]) != "undefined")
       {
          if(!tokenize.arguments[2])
            ignoreEmptyTokens = false;
       }
     var array = input.split(separator);
     if(trim)
       for(var i=0; i<array.length; i++)
         {
           while(array[i].slice(0, trim.length) == trim)
             array[i] = array[i].slice(trim.length);
           while(array[i].slice(array[i].length-trim.length) == trim)
             array[i] = array[i].slice(0, array[i].length-trim.length);
         }
     var token = new Array();
     if(ignoreEmptyTokens)
       {
          for(var i=0; i<array.length; i++)
            if(array[i] != "")
              token.push(array[i]);
       }
     else
       {
          token = array;
       }
     return token;
  }
  function refreshAndClose(){
  var org_address = document.location.toString();
  var tokens = org_address.tokenize('?','',true);
  var variables = tokens[1].tokenize('&','',true);
  
  var address = tokens[0] + "?" + variables[1];
  var link = variables[variables.length-1];
  var temp = link.tokenize('=','',true);
  var i=2;
  while(temp[0] != "topLevel"){
    link = variables[variables.length - 2];
    temp = link.tokenize('=','',true);
    i++;
  }
  link = "link=" + temp[1] ;
  finalvar = address + "&" + link ;
  opener.location = finalvar;

  window.close();
}

