var dtCh= "/";
var minYear=1900;
var maxYear=2100;

// formatPhone
// Takes a phone field and validates that the value of the field is a phone number.
// First, it strips out all but numbers. The value must have at least 10 digits. Any
// digits after the first 10 are the extension. Removes 1 if it is the first digit.
// If it is still a valid phone number (10 or more digits), it is formatted as
// (999) 999-9999 x9999
//
function formatPhone(phoneField) {
	num = ""
	if (phoneField.value.length == 0) {
		return
	}
	for (var x=0;x<phoneField.value.length;x++) {
		thisChar = phoneField.value.charAt(x)
		if (thisChar >= "0" && thisChar <= "9" && (x>0 || thisChar != "1")) {
			num = num + phoneField.value.charAt(x)
		}
	}
	if (num.length < 10) {
		alert('Invalid phone number. Enter 10 digits (plus optional extention)')
		phoneField.value=''
		setTimeout("document." + phoneField.form.name + "." + phoneField.name + ".focus()",100);
	} else {
		tempPhone=num.replace(/(\d{3})(\d{3})(\d{4})/,'('+'$1'+') '+'$2'+'-'+'$3'+' x')
		if (tempPhone.charAt((tempPhone.length - 1)) == "x") {
			tempPhone = tempPhone.substr(0,tempPhone.length - 2);
		}
		phoneField.value = tempPhone;
	}
}

// formatDate
// Takes a date field and validates that it is a valid date. After entry, the date
// is formatted as mm/dd/YYYY
//
function formatDate(dateField) {
	dtStr = dateField.value
	if (dtStr.length == 0) {
		return
	}
	var daysInMonth = DaysArray(12)
	if (dtStr.length == 5 && !isNaN(dtStr)) {
		dtStr = "0" + dtStr;
	}
	if (dtStr.length == 6 && !isNaN(dtStr)) {
		dtStr = dtStr.substring(0,2) + "/" + dtStr.substring(2,4) + "/" + dtStr.substring(4,6)
	}
	if (dtStr.length == 8 && !isNaN(dtStr)) {
		dtStr = dtStr.substring(0,2) + "/" + dtStr.substring(2,4) + "/" + dtStr.substring(4,8)
	}
	dtStr = dtStr.replace(/-/g, "/");
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	if (strYear.length==2) {
		if (strYear > 20) {
			strYear = "19" + strYear
		} else {
			strYear = "20" + strYear
		}
	}
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		dateField.value = "";
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		dateField.value = "";
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		dateField.value = "";
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		dateField.value = "";
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		dateField.value = "";
		setTimeout("document." + dateField.form.name + "." + dateField.name + ".focus()",100);
		return
	}
	newValue = day + "/" + year
	if (newValue.length < 7) {
		newValue = "0" + newValue;
	}
	newValue = month + "/" + newValue
	if (newValue.length < 10) {
		newValue = "0" + newValue;
	}
	dateField.value = newValue
}

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

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;
}

// formatNumber
// Takes a number field and a money flag and validates that it is a valid number. Strips out all but digits
// and formats the number with commas and a dollar sign, if the money flag is true.
//
function formatNumber(numberField,moneyFlag,maximumValue) {
	strString = numberField.value;
	var strValidChars = "$0123456789,.";
	var strChar;

	if (strString.length == 0) {
		return
	}

	newString = "";
	for (i = 0; i < strString.length; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			alert("Invalid number. Only chars '0123456789,' are allowed");
			numberField.value = "";
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return;
		}
		if (strChar == ".") {
			break;
		}
		if (strChar >= "0" && strChar <= "9") {
			newString += strChar;
		}
	}
	if (maximumValue != null & newString > maximumValue) {
		newString = maximumValue;
	}
	numberField.value = (moneyFlag ? "$" : "") + addCommas(newString);
}

// formatFloat
// Takes a number field and a money flag and validates that it is a valid number. Strips out all but digits
// and formats the number with commas and a dollar sign, if the money flag is true.
//
function formatFloat(numberField,moneyFlag,maximumValue) {
	strString = numberField.value;
	var strValidChars = "$0123456789,.";
	var strChar;

	if (strString.length == 0) {
		return
	}

	newString = "";
	for (i = 0; i < strString.length; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			alert("Invalid number. Only chars '0123456789,' are allowed");
			numberField.value = "";
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return;
		}
		if ((strChar >= "0" && strChar <= "9") || strChar == ".") {
			newString += strChar;
		}
	}
	if (maximumValue != null & newString > maximumValue) {
		newString = maximumValue;
	}
	numberField.value = (moneyFlag ? "$" : "") + addCommas(newString);
}

function addCommas(numString)
{
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(numString)) {
		numString = numString.replace(rgx, '$1' + "," + '$2');
	}
	return numString;
}

// checkEmail
// validates that the email field has a valid email address in it.
//
function checkEmail(emailField) {
	var str = emailField.value
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)

	if (lstr == 0) {
		return true;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr ||
		str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr ||
		str.indexOf(at,(lat+1))!=-1 || str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot ||
		str.indexOf(dot,(lat+2))==-1 || str.indexOf(" ")!=-1) {
		alert("Invalid E-mail Address");
		emailField.value = "";
		setTimeout("document." + emailField.form.name + "." + emailField.name + ".focus()",250);
		return false;
	}
	return true;
}

// validateCCNumber
// takes the credit card type field, the number field, and a flag indicating whether to set
// the type or not. Credit card number is validated according to industry standards.
//
function validateCCNumber(typeField,numberField,setType)
{
	var ccNum = numberField.value;

	if (numberField.value.length>0)
	{
		if (!isInteger(ccNum))
		{
			alert('Please enter only numbers (no dashes or spaces) for the Credit Card number');
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return false;
		}

		if (!LuhnCheck(ccNum) || !validateCCType(typeField,ccNum,setType))
		{
			alert('Invalid credit card number');
			setTimeout("document." + numberField.form.name + "." + numberField.name + ".focus()",100);
			return false;
		}
	}
	return true;
}

// validateCCType
// validate the credit card number after setting the type
//
function validateCCType(typeField,cardNum,setType)
{
	var cardType = typeField.options[typeField.selectedIndex].value;
	var numType = "";

	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	if (((cardLen == 16) || (cardLen == 13)) && (firstdig == "4")) {
		numType = "VISA";
	} else if ((cardLen == 15) && (firstdig == "3") && ("47".indexOf(seconddig)>=0)) {
		numType = "AMEX";
	} else if ((cardLen == 16) && (firstdig == "5") && ("12345".indexOf(seconddig)>=0)) {
		numType = "MC";
	} else if ((cardLen == 16) && (first4digs == "6011")) {
		numType = "DISC";
	} else if ((cardLen == 14) && (firstdig == "3") && ("068".indexOf(seconddig)>=0)) {
		numType = "DINERS";
	}

	if (numType == "") {
		return false;
	}

	if (setType) {
		typeWasSet = false;
		for (var i=0;i<typeField.options.length;i++) {
			if (typeField.options[i].value == numType) {
				typeWasSet = true;
				typeField.selectedIndex = i;
				break;
			}
		}
		return typeWasSet;
	} else {
		if (numType != cardType && cardType != "") {
			return false;
		}
	}
	return true;
}

function LuhnCheck(str) {
	var result = true;

	var sum = 0;
	var mul = 1;
	var strLen = str.length;

	for (i = 0; i < strLen; i++) {
		var digit = str.substring(strLen-i-1,strLen-i);
		var tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
		if (mul == 1)
			mul++;
		else
			mul--;
	}
	if ((sum % 10) != 0)
		result = false;

	return result;
}

// checkPassword
// Take the first and second password field and validate that they are the same and that they contain
// the right number and type of characters.
//
function checkPassword(passwordField,password2Field) {
	if (password2Field != null) {
		if (passwordField.value.length > 0 && password2Field.value.length > 0 && passwordField.value != password2Field.value) {
			alert("Passwords are not the same...try again");
			passwordField.value = "";
			password2Field.value = "";
			setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
			return false;
		}
	}
	if (passwordField.value.length > 0 && passwordField.value.length < 6) {
		alert("Password must be 6 or more characters and contain at least 1 letter & 1 number");
		passwordField.value = "";
		if (password2Field != null) {
			password2Field.value = "";
		}
		setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
		return false;
	}
	password = passwordField.value.toLowerCase();
	if (password.search(/[a-z]/) == -1 || password.search(/[0-9]/) == -1) {
		alert("Password must be 6 or more characters and contain at least 1 letter & 1 number");
		passwordField.value = "";
		if (password2Field != null) {
			password2Field.value = "";
		}
		setTimeout("document." + passwordField.form.name + "." + passwordField.name + ".focus()",100);
		return false;
	}
	return true;
}

// setToday
// take a date field and fill it with today's date
//
function setToday(dateField) {
	var today = new Date();
	day = today.getDate();
	month = today.getMonth() + 1;
	year = today.getFullYear();
	newValue = day + "/" + year
	if (newValue.length < 7) {
		newValue = "0" + newValue;
	}
	newValue = month + "/" + newValue
	if (newValue.length < 10) {
		newValue = "0" + newValue;
	}
	dateField.value = newValue;
}

function checkKey(keyField) {
	newValue = "";
	for(var x=0;x<keyField.value.length;x++) {
		thisChar = keyField.value.charAt(x).toUpperCase();
		if (thisChar.search(/[A-Z]/) >= 0 || thisChar.search(/[0-9]/) >= 0 || "&_-".indexOf(thisChar) >= 0) {
			newValue = newValue + thisChar;
		}
	}
	keyField.value = newValue;
}

var slideWindow = null;

function openSlideShow(initialIndex,category) {

	var myWidth = screen.availWidth - 50;
	if (myWidth > 800) {
		myWidth = 800;
	}
	var myHeight = screen.availHeight - 50;
	if (myHeight > 600) {
		myHeight = 600;
	}
	var myLeft = Math.round((screen.availWidth - myWidth) / 2);
	var myTop = Math.round((screen.availHeight - myHeight) / 2)-25;

	if (myTop < 0) { myTop = 0; }
	if (screen.availHeight < 600) { myTop-=20; }

	var url = "slideshow.php?photo_id=" + initialIndex + "&category=" + category;

	if (slideWindow != null && !slideWindow.closed)
		slideWindow.close()
	slideWindow = window.open(url, 'slideshow', 'scrollbars=no,titlebar=no,location=no,status=no,toolbar=no,resizable=no,width='+myWidth+',height='+myHeight+',top='+myTop+',left='+myLeft);

	slideWindow.focus();
}


