/*
 *
 * validation.js
 *
 * Copyright 2007 Mediaspectrum, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Mediaspectrum, Inc.
 *
 */

String.prototype.trim = String_trim;

function String_trim()
{
	return this.replace(/^\s+|\s+$/g, "");
}

function isDigit(c) {
	var numcheck = /\d/;
	return numcheck.test(c);
}

function isBackSpace(c) {
	var numcheck = /[\b]/;
	return numcheck.test(c);
}

function isNonSymbol(k) {
	return k == undefined;
}

function isNumber(e) {
	var keynum
	var keychar

	if(window.event) {
		keynum = e.keyCode;
	} else if(e.which) {
		keynum = e.which;
	}
	keychar = String.fromCharCode(keynum);
	return isDigit(keychar) || isBackSpace(keychar) || isNonSymbol(keynum);
}

function trimAll(s) {
	return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function isNumberField(value) {
	var v = trimAll(value);
	var numcheck = /[^\d*]/;
	return !numcheck.test(v);
}

function switchRequired(signid, value, id) {
	if(id && value && signid) {
		var select = document.getElementById(id);
		var sign = document.getElementById(signid);
		if(select && sign) {
			var v = select.options[select.selectedIndex].value;
			if(v == value) {
				sign.style.display = "inline";
			} else {
				sign.style.display = "none";
			}

		}
	}
}

function switchRequiredRadio(signid, value, id, groupName) {
//	alert("function switchRequiredRadio");
	if(id && value && signid) {
		var radio = document.getElementById(id);
		var sign = document.getElementById(signid);
		if(radio && sign) {
			var v = radio.value;
			if(v == value) {
				sign.style.display = "inline";
			} else {
				sign.style.display = "none";
			}
			document.getElementById(groupName).value = radio.value;
		}
	}
}

// e-mail address validation script
function checkEmail(emailStr) {
	var function_specific = null;
	try {
		function_specific = checkEmail_specific;
	}
	catch (err) {
	}
	if (function_specific) {
		return function_specific(emailStr);
	}
   if (emailStr.length == 0) {
	   return true;
   }
   var emailPat=/^(.+)@(.+)$/;
   var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
   var validChars="\[^\\s" + specialChars + "\]";
   var quotedUser="(\"[^\"]*\")";
   var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
   var atom=validChars + '+';
   var word="(" + atom + "|" + quotedUser + ")";
   var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
   var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
   var matchArray=emailStr.match(emailPat);
   if (matchArray == null)
	   return false;
   var user=matchArray[1];
   var domain=matchArray[2];
   if (user.match(userPat) == null)
	   return false;
   var IPArray = domain.match(ipDomainPat);
   if (IPArray != null) {
	   for (var i = 1; i <= 4; i++) {
		  if (IPArray[i] > 255)
			 return false;
	   }
	   return true;
   }
   var domainArray=domain.match(domainPat);
   if (domainArray == null)
	   return false;
   var atomPat=new RegExp(atom,"g");
   var domArr=domain.match(atomPat);
   var len=domArr.length;
   if ((domArr[domArr.length-1].length < 2) ||
	   (domArr[domArr.length-1].length > 3))
	   return false;
   if (len < 2)
	   return false;
   return true;
}

// phone validation script
function checkPhone(value) {
	var function_specific = null;
	try {
		function_specific = checkPhone_specific;
	}
	catch (err) {
	}
	if (function_specific) {
		return function_specific(value);
	}

	var phoneStr = trimAll(value);
	if (phoneStr.length == 0) {
		return true;
	}
	var phonePat=/^(\+?[\d ]+)? *(\([\d ]+\))? *\d[\d\- .]*\d$/;
	return phonePat.test(phoneStr);
}

// zip code validation script
function checkZipcode(value, format) {
	var str = trimAll(value);
	if (str.length == 0) {
		return true;
	}
	var pattern = /^\d{5}\-\d{4}$/;
	if(format == "us5") {
		pattern=/^\d{5}$/;
	}
	return pattern.test(str);
}

/*
// zip code validation script
function checkDate_(value) {
//	alert("function checkDate 0 value = " + value);
	dateVerify(value);

	if(!value) return true;
	var ok = true;
	var format = "mm/dd/yyyy";
	var a = format.match(/(mm|dd|yyyy)/gi);
	var splitter = format.replace(/(mm|dd|yyyy)/gi, "");
	if(splitter.length < 2) return false;
	var year;
	var month;
	var day;
	try {
		var a2 = value.split(splitter.charAt(0));
		for (var i = 0; i < a.length; i++) {
			switch (a[i].toLowerCase()) {
				case 'yyyy': year = a2[i]; break;
				case 'mm': month = (new Number(a2[i])) - 1; break;
				case 'dd' : day = a2[i]; break;
			}
		}
	} catch(e)   {
		ok = false;
	}
	if (!(isNumberField(String(day)) && isNumberField(String(month)) && isNumberField(String(year)))) ok = false;
	if (ok) {
		if (month > 11 || day > 31) ok = false;
		if (month < 0 || day < 1 || year < 1) ok = false;
	}
	if (ok) {
		if (day > getDaysInMonth(month + 1, year)) ok = false;
	}
	return ok;
}
*/

// GET NUMBER OF DAYS IN MONTH
function getDaysInMonth(month,year)  {
	var days;
	if (month==1 || month==3 || month==5 || month==7 || month==8 ||
		month==10 || month==12)  days=31;
	else if (month==4 || month==6 || month==9 || month==11) days=30;
	else if (month==2)  {
		if (isLeapYear(year)) {
			days=29;
		}
		else {
			days=28;
		}
	}
	return (days);
}


// CHECK TO SEE IF YEAR IS A LEAP YEAR
function isLeapYear (Year) {
	if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
		return (true);
	}
	else {
		return (false);
	}
}

//validates parameters given with the URL
function validateParameters() {
	var form = document.getElementById("AdInfoForm");
	
	
	/*var function_specific = null;
	try {
		function_specific = validateForm_specific;
	}
	catch (err) {
	}
	if (function_specific) {
		return function_specific(form);
	}*/

	var elements = form.elements;
	var errors = new Array(0);;
	for (var i = 0; i < elements.length; i++) {
		var element = elements[i];
		var elementName = element.name;
		var commonName = elementName.replace(/\d*$/, "");
		var reqObject = getReqObject(commonName);
		if ("" + reqObject == "null")
		{
			continue;
		}
		var type = reqObject.type;
		var title = reqObject.title;

		//it's unlikely that file name will be sent with URL 
		/*if(type == "file") {
			if (!validateFileName(element.value.trim()))
				return false;
			
		} else */
		if(type == "adnumber") {
			if (!checkAdNumber(element.value)) {
				errors.push(getJSMessage(ADMUMBER_ERROR));
				element.disabled=false;
				//alert(getJSMessage(ADMUMBER_ERROR));
				//return false;
			}
		}
		else if(type == "integer") {
			if(!isNumberField(element.value)) {
				errors.push(getJSMessage(NUMERUC_ERROR, title));
				element.disabled=false;
			}
		}
		else if(type.indexOf("minlength") >= 0) {
			var minlength = type.substring(9, type.length);
			var fieldLength = 0;
			if (element.value) {
				fieldLength = element.value.length;
			}
			if (fieldLength > 0 && fieldLength < parseInt(minlength)) {
				errors.push(getJSMessage(MINLENGTH_ERROR, title, minlength));
				element.disabled=false;
			}
		}

		else if(type == "email") {
			if(!checkEmail(element.value)) {
				errors.push(getJSMessage(EMAIL_ERROR));
				element.disabled=false;
			}
		}
		else if(type == "phone") {
			if(!checkPhone(element.value)) {
				errors.push(getJSMessage(PHONE_NUMBER_ERROR));
				element.disabled=false;
			}
		}
		else if(type == "zipcode5") {
			if(!checkZipcode(element.value, "us5")) {
				errors.push(getJSMessage(ZIP_CODE_ERROR));
				element.disabled=false;
			}
		}
		else if(type == "zipcode10") {
			if(!checkZipcode(element.value, "us10")) {
				errors.push(getJSMessage(ZIP_CODE_ERROR));
				element.disabled=false;
			}
		}
		else if(type == "date") {
			if(element.value && !checkDate(element.value)) {
				errors.push(getJSMessage(DATE_ERROR));
				element.disabled=false;
				enableDate();
			}
		}
	}
	
	//display information about errors
	if (errors.length > 0) {
		var errorList = "Following error(s) found: \n ";
		for (var j = 0; j < errors.length; j++) {
			errorList += errors[j] + ". \n ";
		}
		alert(errorList);
	}
	return true;
}

function validateForm(form) {
/*
	alert("function validateForm 0");
//	return true;
*/

	alert("xyz validateForm entered");

	var function_specific = null;
	try {
		function_specific = validateForm_specific;
	}
	catch (err) {
	}
	if (function_specific) {
		return function_specific(form);
	}

	var elements = form.elements;
	var filecount = 0;
	var fileListStarted = false;
	var fileListEnded = false;
	for (var i = 0; i < elements.length; i++) {
		var element = elements[i];
		var elementName = element.name;
		var commonName = elementName.replace(/\d*$/, "");
		var reqObject = getReqObject(commonName);
		if ("" + reqObject == "null")
		{
			continue;
		}
		var type = reqObject.type;
		var title = reqObject.title;

		if(type == "file") {
			if (!validateFileName(element.value.trim()))
				return false;
			if(element.value.trim() == "" && filecount == 0) {
				element.focus();
				alert(getJSMessage(EMPTY_FILE_NAME_ERROR));
				return false;
			}
			if (element.value.trim() != "")
				fileListStarted = true;
			if (fileListStarted && element.value.trim() == "")
				fileListEnded = true;
			if (fileListEnded && element.value.trim() != "") {
				alert(getJSMessage(EMPTY_FILE_NAME_ERROR));
				return false;
			}
			filecount++;
		}
		else if(type == "adnumber") {
	alert("xyz validateForm entered - type is adnumber");
			if (!checkAdNumber(element.value)) {
				alert(getJSMessage(ADMUMBER_ERROR));
				return false;
			}
		}
		else if(type == "integer") {
			if(!isNumberField(element.value)) {
				element.focus();
//				alert("Field \"" + title + "\" should be numeric");
				alert(getJSMessage(NUMERUC_ERROR, title));
				return false;
			}
		}
		else if(type.indexOf("minlength") >= 0) {
			var minlength = type.substring(9, type.length);
			var fieldLength = 0;
			if (element.value) {
				fieldLength = element.value.length;
			}
			if (fieldLength > 0 && fieldLength < parseInt(minlength)) {
				element.focus();
//				alert("" + title + " field must be " + minlength + " digits");
				alert(getJSMessage(MINLENGTH_ERROR, title, minlength));
				return false;
			}
		}

		else if(type == "email") {
			if(!checkEmail(element.value)) {
				element.focus();
				alert(getJSMessage(EMAIL_ERROR));
				return false;
			}
		}
		else if(type == "phone") {
			if(!checkPhone(element.value)) {
				element.focus();
				alert(getJSMessage(PHONE_NUMBER_ERROR));
				return false;
			}
		}
		else if(type == "zipcode5") {
			if(!checkZipcode(element.value, "us5")) {
				element.focus();
				alert(getJSMessage(ZIP_CODE_ERROR));
				return false;
			}
		}
		else if(type == "zipcode10") {
			if(!checkZipcode(element.value, "us10")) {
				element.focus();
				alert(getJSMessage(ZIP_CODE_ERROR));
				return false;
			}
		}
		else if(type == "date") {
			if(element.value && !checkDate(element.value)) {
				element.focus();
				alert(getJSMessage(DATE_ERROR));
				return false;
			}
		}
	}




/*
	var labels;
	if (document.getElementsByTagName) {// W3C DOM
		labels = document.getElementsByTagName("label");
	}
	if(labels && labels.length) {
		for(i = 0; i < labels.length; i++) {
			var id = labels[i].id;
			var title = id.substring(0, id.lastIndexOf("_"));
			var type = id.substring(id.lastIndexOf("_") + 1, id.length);
			var field;
			for(j = 0; j < labels[i].attributes.length; j++) {
				if(labels[i].attributes[j].name == "for") field = document.getElementById(labels[i].attributes[j].value);
			}
			if(field) {
				if(type == "file") {
					if(field.value.trim() == "") {
						field.focus();
						alert("File name shouldn't be empty");
						return false;
					}
				}
				if(type == "gppadnumber") {
					if (!checkGppAdNumber(field.value))
					return false;
				}
				if(type == "integer") {
					if(!isNumberField(field.value)) {
						field.focus();
						alert("Field \"" + title + "\" should be numeric");
						return false;
					}
				}
				if(type.indexOf("minlength") >= 0) {
					var minlength = type.substring(9, type.length);
					var fieldLength = 0;
					if (field.value) {
						fieldLength = field.value.length;
					}
					if (fieldLength > 0 && fieldLength < parseInt(minlength)) {
						field.focus();
						alert("" + title + " field must be " + minlength + " digits");
						return false;
					}
				}

				if(type == "email") {
					if(!checkEmail(field.value)) {
						field.focus();
						alert("Incorrect email");
						return false;
					}
				}
				if(type == "phone") {
					if(!checkPhone(field.value)) {
						field.focus();
						alert("Incorrect phone number");
						return false;
					}
				}
				if(type == "zipcode5") {
					if(!checkZipcode(field.value, "us5")) {
						field.focus();
						alert("Incorrect zip code");
						return false;
					}
				}
				if(type == "zipcode10") {
					if(!checkZipcode(field.value, "us10")) {
						field.focus();
						alert("Incorrect zip code");
						return false;
					}
				}
				if(type == "date") {
					if(!checkDate(field.value)) {
						field.focus();
						alert("Incorrect date");
						return false;
					}
				}
			}
		}
	}
*/
	return true;
}

function getReqObject(commonName) {
	for (var i = 0; i < requiredObject.length; i++) {
		if (requiredObject[i].name == commonName) {
			return requiredObject[i];
		}
	}
	return "null";
}

function checkAdNumber(fieldvalue) {
	var function_specific = null;
	try {
		function_specific = checkAdNumber_specific;
	}
	catch (err) {
	}
	if (function_specific) {
		return function_specific(fieldvalue);
	}
	return true;
}

function checkDate(inDate) {
//	alert("function checkDate 0 inDate = " + inDate);
	//checks whether entered value was 'N/A' and accepts it if appropreate format supported
	var naFormat = NA_DATE_FORMAT.toLowerCase();
	if (naFormat != null && inDate.toLowerCase() == naFormat) {
		return true;
	}
	var year;
	var month;
	var day;

	var timeunits = getTimeUnits();
	if (!timeunits) {
		alert("Invalid CALENDAR_DATE_FORMAT")
		return false;
	}
	var shortYear = timeunits[3];
	var delimiter1 = timeunits[4];
	var delimiter2 = timeunits[5];
	var dateArray = new Array();
	if (delimiter1 == delimiter2) {
		dateArray = inDate.split(delimiter1);
	}
	else {
		var dateArray1 = inDate.split(delimiter1);
		if (dateArray1.length != 2)
			return false;
		var dateArray2 = dateArray1[1].split(delimiter2);
		if (dateArray2.length != 2)
			return false;
		dateArray[0] = dateArray1[0];
		dateArray[1] = dateArray2[0];
		dateArray[2] = dateArray2[1];
	}

	if (dateArray.length != 3)
		return false;

	for (var i = 0; i < 3; i++) {
		var unitSymbol = timeunits[i].substring(0, 1).toLowerCase();
		switch (unitSymbol) {
			case "y":
				year = dateArray[i];
				break;
			case "d":
				day = dateArray[i];
				break;
			case "m":
				month = dateArray[i];
				break;
		}
	}
	if (shortYear)
		year = "20" + year;

	var trueDate = validateDate(year, month, day);
	if (!trueDate)
		return false;

	var now = new Date();
	var date = new Date();
	date.setFullYear(year);
	date.setMonth(month - 1);
	date.setDate(day);
	if (now.getTime() > date.getTime())
		return false;

	return true;
}

var daysInMonth= new Array();
daysInMonth[1] = 31;
daysInMonth[2] = 29;
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function isInteger(s)
{
    var re = /^\d*$/;
    return re.test(s);
}

function isIntegerInRange (s, a, b)
{
    if (!isInteger(s)) return false;
    var num = parseInt(s, 10);
    return ((num >= a) && (num <= b));
}

function validateDate(year, month, day)
{
//	alert("function validateDate 0 year = " + year);
	if (!isYear(year) || !isMonth(month) || !isDay(day)) {
		return false;
	}

	var intYear = parseInt(year, 10);
	var intMonth = parseInt(month, 10);
	var intDay = parseInt(day, 10);

	if (intDay > daysInMonth[intMonth]) {
		return false;
	}
	if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) {
		return false;
	}

//	alert("function validateDate 0 return true");
	return true;
}

function daysInFebruary(year) {
	return (((year % 4 == 0) && (!(year % 100 == 0) || (year % 400 == 0))) ? 29 : 28);
}

function isMonth(s)
{
	return isIntegerInRange (s, 1, 12);
}

function isDay(s)
{
	return isIntegerInRange (s, 1, 31);
}

function isYear (s)
{
	if (!isInteger(s)) return false;
	return (s.length == 4);
}

function getTimeUnits()
{
	var format = CALENDAR_DATE_FORMAT.toLowerCase();
	var formatLength = format.length;
	if (formatLength != 8 && formatLength != 10)
		return false;

	var timeunits;
	var shortYear = false;
	if (formatLength == 8) {
		timeunits = format.match(/(yy|mm|dd)/gi);
		shortYear = true;
	}
	else {
		timeunits = format.match(/(yyyy|mm|dd)/gi);
	}
	if (timeunits.length != 3)
		return false;

	var splitter;
	if (shortYear)
		splitter = format.replace(/(yy|mm|dd)/gi, "");
	else
		splitter = format.replace(/(yyyy|mm|dd)/gi, "");
	if (splitter.length != 2)
		return false;

	timeunits[3] = shortYear;
	timeunits[4] = splitter.charAt(0);
	timeunits[5] = splitter.charAt(1);

	return timeunits;
}

function getJSMessage() {
	var argv = getJSMessage.arguments;
	var argc = argv.length;
	var mess = "" + argv[0];
	var repl;
	var replPos;
	for (var i = 1; i < argc; i++) {
		repl = "{" + (i - 1) + "}";
		replPos = mess.indexOf(repl);
		if (replPos < 0)
			continue;
		mess = mess.replace(repl, argv[i]);
	}
	return mess;
}

function validateFileName(fileName) {
	if (!fileName)
		return true;

	var allowedExtensions = "";
	try {
		allowedExtensions = ADDROP_ALLOWED_EXTENSIONS.trim();
	}
	catch (err) {
	}
	if (!allowedExtensions)
		return true;

	var ext = (fileName.substring(fileName.lastIndexOf(".") + 1)).toLowerCase();
	var extArray = allowedExtensions.split(',');

	for (var i = 0; i < extArray.length; i++) {
		var allowedExtension = extArray[i].trim().toLowerCase();
		if (allowedExtension == ext) {
			return true;
		}
	}

	alert(getJSMessage(EXTENSION_ERROR) + allowedExtensions);
	return false;
}


