
// Checks form for required elements
// Fields to be validated must be supplied in a hidden field: txtRequiredInputs
// Additional validation options can be supplied via the field name: (fieldName-option)
// field names cannot contain dashes. Also, have a * as the end of the field name will validate all similarly named fields.
//
// text, textarea, password:
//   0 - blank
//   1 - numeric
//   2 - valid email address
//   3 - valid phone number
//	 4 - valid postal code
// select (single): checks to see if the first element isn't selected
// select (multiple): checks for at least one selected item
// radio/checkbox: checks to see if object is selected.
//   NOTE: radios/checkboxes will turn into arrays if more than one object of a name is detected.
//         Therefore, if a type is determined to be undefined, it is assumed to be a multi-element object.
//         Dynamically added nodes enter the dom tree, but somehow don't make it fully into javascript, so
//         new objects are added as additional array elements to the cloned nodes, rather than fully accessible
//         objects of their own.
//
// @param thisForm Form object to be tested
// @return true/false
function validateForm(thisForm) {
// Test if required inputs field exists
    if (!thisForm.txtRequiredInputs) {
        alert("DEVELOPER ERROR: Missing required inputs field.");
        return false;
    }

    if (trimSpace(thisForm.txtRequiredInputs.value) == "") {
		// If a user or developer does not want any required fields, so be it.
        return true;
    }

    var requiredInputs = thisForm.txtRequiredInputs.value.split(" ");

    for (var i = 0; i < requiredInputs.length; i++ ) {
	
        var formElementList = requiredInputs[i].split("-");
        var formItem = formElementList[0];
        var validationOption = formElementList[1];
        if (!validationOption) { validationOption = 0; }

        var validateList = new Array;   // sublist of form fields to validate
        if (formItem.indexOf("*") > 0) {
            formItem = formItem.replace(/\*/,"1");  // dynamic node array is based on first element name
            var curObject = eval("thisForm." + formItem);
            // object will not have a name if it is an array (possible if only 1 element in multi)
            if (!curObject.name) {
                for (var j = 0; j < curObject.length; j++) { validateList[formItem + "[" + j + "]"] = 1; }
            } else {
                validateList[formItem] = 1;
            }
        } else {
            validateList[formItem] = 1;
        }

        for (formElement in validateList) {
            curObject = eval("thisForm." + formElement);
            if (!curObject) {
                alert("DEVELOPER ERROR: " + formElement + " is an non-existant form element.");
                return false;
            }

            // check text and textareas
            if (curObject.type == "text" || curObject.type == "textarea" || curObject.type == "password") {
                var tempValue = trimSpace(curObject.value);
                if (!tempValue) {
                    alert("There is missing data in a required field.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 1 && isNaN(tempValue) && !iv_isValidPhone(tempValue)) {
                    alert("The value entered is not a number.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 2 && !iv_isValidEmail(tempValue)) {
                    alert("The email address entered is not in the correct format.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 3 && !iv_isValidPhone(tempValue)) {
                    alert("The value entered is not valid phone number.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 4 && !iv_isValidZip(tempValue)) {
                    alert("The value entered is not a valid zip code.");
                    curObject.focus(); curObject.select();
                    return false;
                }				
            } else if ((curObject.type == "select-one" && curObject.selectedIndex == 0) ||
                curObject.type == "select-multiple" && curObject.selectedIndex == -1) {
                if (curObject.selectedIndex == -1 || curObject.selectedIndex == 0) {
                    alert("Please make a selection from the list.");
                    curObject.focus();
                    return false;
                }
            } else if (curObject.type == "radio" || curObject.type == "checkbox") {
                if (!curObject.checked) { 
                    alert("There is missing data in a required field.");
                    curObject.focus();
                    return false;
                }
            } else if (curObject.type == "file") {
                if (curObject.value == "") { 
                    alert("There is missing data in a required field.");
                    curObject.focus();
                    return false;
                }

                var validExtensions = new Array("gif", "jpeg", "jpg", "png");
                var fileNameTemp = curObject.value.split(".");
                var fileExtension = fileNameTemp[fileNameTemp.length - 1];
                var passedFlag = false;
                fileExtension = fileExtension.toLowerCase();
                for (var j = 0; j < validExtensions.length; j++) {
                    if (fileExtension == validExtensions[j]) { passedFlag = true; break; }
                }

                if (!passedFlag) {
                    alert("The file you entered has an invalid file extension. Please change the name and try again.");
                    curObject.focus();
                    return false;
                 }
            } else if (!curObject.type) {
                var passedFlag = false;

                for (var j = 0; j < curObject.length; j++) {
                    if (curObject[j].checked) { passedFlag = true; }
                }

                if (!passedFlag) {
                    alert("There is missing data in a required field.");
                    curObject[0].focus();
                    return false;
                }
            }
        }
    }

    return true;
}

// ===== Date validation functions ====
function daysInFebruary (year){
// A year is a leap year if it is divisible by 4 but not by 100.  
// Exceptionally, a year that's divisible by 400 is a leap year.
	var numDays= 28;
	if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
	  numDays = 29;
	}
    return numDays;
}
function DaysArray(n) {
    tempDays = new Array(n);
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {tempDays[i] = 30}
		if (i==2) {tempDays[i] = 29}
   } 
   return tempDays
}

function iv_isValidDate(argDay, argMonth, argYear) {
	var daysInMonth = DaysArray(12)
	var strMonth=argMonth;
	var strDay=argDay;
	var strYr=argYear;
    // Declaring valid date character, minimum year and maximum year
    var minYear=1900;
    var maxYear=2100;

	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 (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYr.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid year")
		return false
	}
	
return true
}



// ===== Support Functions =====
function LTrim(txt) {
    return txt.replace(/^[\s]+/g, "");
}

function RTrim(txt) {
    return txt.replace(/[\s]+$/g, "");
}

function trimSpace(txt) {
    var tmpTxt = LTrim(txt);
    return RTrim(tmpTxt);
}

// iv_isValidEmail - Checks to see if email format is correct.
// @param email Email address to validate.
// @returns boolean depending on success.
function iv_isValidEmail(email) {
    // See if we have any spaces.
	var space = email.indexOf(" ");
	if (space != -1) { return false; }

    // max length of email
    if (email.length > 75) { return false; }

    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!email.match(re)) { return false; }
    return true;
}

function iv_isValidPhone(phone) {
   var ValidChars = "0123456789.-";
   var isValidPhone=true;
   var Char;
    for (i = 0; i < phone.length && isValidPhone == true; i++) 
      { 
      Char = phone.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         isValidPhone = false;
         }
      }

    return isValidPhone;
}


// Valid zip code patterns:
// 10018 or 10018-5001 or A9N 7B4
function iv_isValidZip(zip) {
   var zipRegex = new RegExp("^([0-9]{5})$|^([0-9]{5})-([0-9]{4})$|^([a-z][0-9][a-z] [0-9][a-z][0-9])$", "i");
   return zipRegex.test(zip);
}

function charLim (theForm,maxLen) {
	if (theForm.dilUsrOpt_Post.value == "") { 
    	alert("There is missing data in a required field."); 
    	return false; 
	}
	var outputText = '';	
	var arrVar = theForm.dilUsrOpt_Post.value.split(" ")
	for(var i = 0; i < arrVar.length; i++) {
		
		if (arrVar[i].length > maxLen) {
			var lengthVar = arrVar[i].length;
			j = Math.ceil(lengthVar / maxLen);
			startPos = 0;
			endPos = maxLen - 1;
			for(var k = 0; k < j; k++) {
				tempVar = arrVar[i].substring(startPos,endPos+1);  
				tempVar = tempVar+' ';
				startPos = endPos + 1;
				endPos = endPos + maxLen;
				outputText = outputText + tempVar;
			}
			arrVar[i] = outputText; 
		}
	}
	theForm.dilUsrOpt_Post.value = arrVar.join(' ');
	return true;
}

// iv_checkSweepsExpiration - Checks to see if a sweeps is expired and redirects to standard sweeps sorry page if it is.
function iv_checkSweepsExpiration(expireDate, currentDate) {
    // -- Date Information --
    currentDateArray = currentDate;
    currentDateArray = currentDateArray.split("/");
    currentDate = new Date(currentDateArray[0], currentDateArray[1] - 1, currentDateArray[2], currentDateArray[3], currentDateArray[4]);
    expireDateArray = expireDate;
    expireDateArray = expireDateArray.split("/");
    expireDate = new Date(expireDateArray[0], expireDateArray[1] - 1, expireDateArray[2], expireDateArray[3], expireDateArray[4]);
    
	if (currentDate >= expireDate) { 
       document.location.href = "http://www.ivillage.com/sweepstakes/sorry";
    } 
}
