/*
	This function is pretty generic, if checks all elements of the given form and returns an error
	if ANY of them are empty.
*/
function checkForm(name) {
        var form = document.forms[name];
        for(var i=0; i<form.length; i++) {
                if(form.elements[i].value=='') {
                        alert('ERROR\n\nAll fields are required.');
                        return false;
                }
        }
        return true;
}

/*
	This function does exactly what you expect it to do, it filters out all characters and returns
	only numbers.

	Pass the object in
*/
function onlyNumbers(obj) {
        obj.value = obj.value.replace(/[^\d]/g, '');
}

/*
	This function filters out all letters and most characters. It's useful for limiting input for
	phone and fax numbers.
		Allowed: 0-9, spaces, #, +, (, ), and -

	Pass the object in
*/
function filterNumbers(obj) {
        obj.value = obj.value.replace(/[^\d\s\#\+\(\)\-]/g, '');
}

/*
	This function filters out odd characters. It's useful for limiting input for nearly any field,
	such as addresses, names, locations, etc.
		Allowed: a-z (case insensitive), 0-9, spaces, periods, ', #, commas, and -

	Pass the object in
*/
function filterChars(obj) {
        obj.value = obj.value.replace(/[^A-Z\d\s\.\'\#\,\-]/ig, '');
}

/*
	This function is used to format a number as a price. It strips leading 0's and adds .00 if only 
	a dollar amount is specified
*/
function makePrice(obj) {
	value = ''+obj.value; //replace doesn't work if the type is not a string, so, we make every value a string
	if(value=='' || parseFloat(value)==0) {
		obj.value='0.00';
		return;
	}
	value = value.replace(/[^\d\.]/g, '');
	if(value.indexOf('.')!=-1) {
		valueArr = value.split('.');
		value = '0'+valueArr[0]+'.'+valueArr[1]+'0';
	}
        value = Math.round(value*100)/100 + '';//add the '' to keep it a string
	var priceArr = value.split('.'); //strip everything but numbers and .'s and split by .

	//Process the dollar amount
	if(!priceArr[0] || priceArr[0]==0) { 	//if there is nothing in dollar amount, make it 0
		priceArr[0]='0';
	} else {		//strip leading 0's
		priceArr[0] = priceArr[0].replace(/^0+/g, '');
	}

	//process the change amount
	if(!priceArr[1]) { 	//if there are no cents, fix it
		priceArr[1]='00';
	} else {		//format existing cents
		priceArr[1] = priceArr[1].substring(0,2); //trim the cents to 2 characters
		while(priceArr[1].length<2) { //pad the cents to 2 characters
			priceArr[1]=priceArr[1]+'0';
		}
	}

	obj.value = priceArr[0]+'.'+priceArr[1];
}

/*
	This function is used to check date inputs. It tests for the MM/DD/YY format and strips out illegal characters.
	Ideally, it would also accept an options perameter to use the MM/DD/YYYY format....
*/
function checkDate(obj) {
	//end silently if the field is empty
	if(obj.value.length==0) {
		return;
	}
	//filter out bad characters and return message on error
	var input = obj.value.replace(/[^0-9\/]/g, '');
	//split the values out to get the year
	if(input.indexOf('/') != -1) {
		var numArray = input.split('/');
		if(numArray[2] && numArray[2].length > 2) {
			//strip the year down to the last 2 digits
			input = numArray[0]+"/"+numArray[1]+"/"+numArray[2].substr(parseInt(numArray[2].length-2),2); 
		}
	}
	if(input.length != 8) {
		alert('"'+obj.value+'" is not a valid date');
		obj.value = '';
		return;
	}
	//check that the numbers are in proper mm/dd/yy format
	var numArray = input.split('/');
	if(numArray[0].length !=2 || numArray[1].length !=2 || numArray[2].length !=2) {
		alert('"'+obj.value+'" is not a valid date');
		obj.value = '';
		return;
	}
	//output the cleaned data
	obj.value = input;
}


/*files validateEmail are used in:
			villas.php
			yachts.php
			sports_contact.php
			newsletter.php
			contact.php
			job.php
			loginagent.php
			museums.php
			villa_form.php
			sports_contact.php
			pressroom.php
*/

/*function validateEmail(email) {
	alert("first");
   var reg = /^([a-z0-9_\-\.])+\@{1}[a-z0-9_-]+[.](([a-z]{2,6})|([a-z]{2,6}[.]{1}[a-z]{2,3}))$/i;
   if(reg.test(email) == false) {
      return false;
   } else {
      return true;   
   }

}*/

function validateEmail(str) {
/*
		var err = 0;
		var at="@"
		var dot="."	
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		var errorMessage = "Please enter a valid e-mail address"; 
		
		var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@.-_";
		var temp;
		for (var i=0; i< str.length; i++) {
			temp = "" + str.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") {
			err = 10;
			}
		}
		
		//check if blank spaces between periods and '-'s
		chunks = str.split(".");
		for(i=0;i < chunks.length; i++){
			if(chunks[i].length <1){
				err=20;
			}
		}
		
		chunks = str.split("-");
		if (chunks.length > 3){
			err=23;
		}
		for(i=0;i < chunks.length; i++){
			if(chunks[i].length <1){
				err=25;
			}
		}
	
		chunks = str.split("@");
		if (chunks.length != 2){
			//alert (errorMessage + " - must contain an'@'.");
			return false
		}
		
		periods = chunks[1].split("."); // if split after the '@' contains more than one period then error
		if (periods.length >3){
			err = 30;
		}
		
		periods = chunks[0].split("."); // if split before the '@' contains more than two periods then error
		if (periods.length>5){
			err = 40;
		}
		
		finalPeriod = str.lastIndexOf(".")
		if (finalPeriod >= (parseInt(str.length) - 2) || finalPeriod < (parseInt(str.length) - 10)){
			err = 50;
		}
		
		if (lstr < 7){
		    err = 60;
		}
		
		if (str.indexOf(at)==-1){
		   err = 70;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)>(lstr-5)){
		   err = 80;
		}

		
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0){
		   err = 90;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    err = 100;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   err = 110;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){ // cannot have a period immediately after the '@' symbol
		    err = 120;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    err = 130;
		 }
		
		if (err > 0){
			//alert(errorMessage);
		   //alert(errorMessage + err)
			return false
		}else{
 			return true
		}					
*/		

		/*if(str.match(/^([a-z0-9_\-\.])+\@{1}[a-z0-9_-]+[.](([a-z]{2,6})|([a-z]{2,6}[.]{1}[a-z]{2,3}))$/i))
		//if(str.match(/^[a-z0-9]+[a-z0-9_-]*(([\.])|([a-z0-9_-]*))[a-z0-9_-]+[@]{1}[a-z0-9_-]+[.](([a-z]{2,6})|([a-z]{2,6}[.]{1}[a-z]{2,3}))$/i)) 
		{
			return true;
		} else {
			return false;
		}*/
		//var reg = /^([a-z0-9_\-\.])+\@{1}[a-z0-9_-]+[.](([a-z]{2,6})|([a-z]{2,6}[.]{1}[a-z]{2,3}))$/i;
		var reg = /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i;
		if(reg.test(str) == false) {
			return false;
		} else {
			return true;   
		}
	}


// a better date validator- much more robust. checks in both mm/dd/yy or mm/dd/yyyy formats,
//checks for alpha characters, and invalid month, day, year values. Also checks leap year.
function isDateValid(docObjectValue){// returns 0 if false, 1 if true
	var err = 0;

	var valid = "0123456789/";
	var ok = "yes";
	var temp;
	for (var i=0; i< docObjectValue.length; i++) {
		temp = "" + docObjectValue.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			err=1;
			return 0
		}
	}

	mdySplitter = docObjectValue.split("/");
	if (mdySplitter.length != 3) {
		err=2;
		return 0
	}
	
	if (docObjectValue.length >10 ) {err=3;}//if 4 digit year, or single digit day/month, change to: .length > 10
	b = mdySplitter[0] // month
	d = mdySplitter[1] // day
	f = mdySplitter[2] // year
	if (b<1 || b>12) {err = 4;}
	if (d<1 || d>31) {err = 5;}
	if (f.length < 2)				// must have at least a two-digit year
		err = 6;
	else if (f.length < 3) {
		if (f<0 || f>99) {			// probably now an extraneous check since already validated as numeric
			err = 6;
		}
	}else{// un-flag for 4 digit year
		//if(f<2006 || f>2099){ //for 4 digit 
			err = 7;
		//}else{
		//	f=f.slice(2,4);
		//}
	}
	
	if (b==4 || b==6 || b==9 || b==11){//months with 30 days
		if (d==31) {err=8;}
	}
	if (b==2){
		var g=parseInt(f/4,10);
		if (isNaN(g)) {
			err=9;
		}
		if (d>29) {err=10;}
		if (d==29 && ((f/4)!=parseInt(f/4,10))) {
			err=11;
		}
	}	
	if (err>0) {
		//alert("Invalid "+ err);
		return 0
	} else {
		//alert("valid");
		return 1
   	}
}

// Returns a JavaScript Date object given a date string in mm/dd/yy or mm/dd/yyyy format.
function dateStringToDate(dateString)
	{
	var returnValue = null;
	
	// Can safely parse the date only if valid.
	
	if (isDateValid(dateString))
		{
		var mdySplitter = dateString.split("/");
		
		// Always parseInt(x, 10) so strings with a leading zero arent interpreted as octal!
		
		var year = parseInt(mdySplitter[2], 10);
		
		// Convert two digit year to four digit year.  Unix epoch can represent 1970 - 2038 so we can decide
		// which century is correct.
		
		if (year < 100)
			year += (year >= 70) ? 1900 : 2000;

		returnValue = new Date(year, parseInt(mdySplitter[0], 10) - 1, parseInt(mdySplitter[1], 10));		// Date(year, month - 1, day)
		}
	
	return returnValue;
	}

// Canonize a valid date to mm/dd/yy format.
function parseDate(date){
	DValid = isDateValid(date);
	if (DValid == 1){
		mdySplitter = date.split("/");
		b = mdySplitter[0] // month
		if(b.length < 2){
			b = '0'+b;
		}
		d = mdySplitter[1] // day
		if(d.length < 2){
			d = '0'+d;
		}
		f = mdySplitter[2] // year
		if (f.length > 2){ // 4 digit year
			f = f.substring(2);
		}		
		newDateString = b+"/"+d+"/"+f;
		return newDateString;
	}
	return null;
}

