var date1;
var date2;
var errormessage = "";

function xalert(message)
{
	if (errormessage == "") errormessage = message; else
	errormessage = errormessage + "\n" + message;
}

function total_alert()
{
	alert (errormessage);
	errormessage = "";
}
function checkdate2(input,compare)
{
	// var validformat= new RegExp([0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2});

	 var returnval=false;
	 if (!validformat.test(input))
	 	xalert("Invalid Date Format. Please correct and submit again.");
	 else{ //Detailed check for valid date ranges
		 var yearfield=input.split("-")[0];
		 var monthfield=input.split("-")[1];
		 var dayfield=input.split("-")[2];
		 var dayobj = new Date(yearfield, monthfield-1, dayfield);
		 if (compare == 'date1') date1 = dayobj;
		 if (compare == 'date2') date2 = dayobj; 
		 if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield) )
		 	xalert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
		 else {
		 // 	xalert ('Correct date');
		 	returnval=true
			}
	 }
	return returnval;
}

function checkdate3(input, compare)
{
   // Regular expression used to check if date is in correct format
   var pattern = new RegExp('(19|20)[0-9]{2}-(0|1)[0-9]-[0-3][0-9]');
   
   
   if(input.match(pattern))
   {
      var date_array = input.split('-');
      var day = date_array[2];

      // Attention! Javascript consider months in the range 0 - 11
      var month = date_array[1] - 1;
      var year = date_array[0];

      // This instruction will create a date object
      source_date = new Date(year,month,day);
	 if (compare == 'date1') date1 = source_date;
	 if (compare == 'date2') date2 = source_date; 
      if(year != source_date.getFullYear())
      {
         xalert('Year is not valid!');
         return false;
      }

      if(month != source_date.getMonth())
      {
         xalert('Month is not valid!');
         return false;
      }

      if(day != source_date.getDate())
      {
         xalert('Day is not valid!');
         return false;
      }
   }
   else
   {
      xalert('Date format is not valid!');
      return false;
   }
   return true;
}

function isLaterThanToday(input)
{
	 var yearfield=input.split("-")[0];
	 var monthfield=input.split("-")[1];
	 var dayfield=input.split("-")[2];
	 var dayobj = new Date(yearfield, monthfield-1, dayfield);
	 var today = new Date();
	 if (dayobj > today) return true;
	 return false;
}

function FormatCanadianPostal(postalcodefield)
{
	var finalValue = "";
	var validchars = 'ABCEGHJKLMNPRSTVXY';
	var validnums = '0123456789';
	var validspace = ' -';
	var validcurrent;
	
 	var entry = postalcodefield.value.toUpperCase();
	if (entry.length >= 4)
	{
		if (validspace.indexOf(entry.charAt(3))==-1)
		{
//			xalert (entry.substring(0,3));
			entry = entry.substring(0,3) + ' ' + entry.substring (3);
		}
	}
	
	for (var x=0; x<entry.length; x++)
	{
		if (x==0) validcurrent = validchars;
		if (x==1) validcurrent = validnums;
		if (x==2) validcurrent = validchars;
		if (x==3) validcurrent = validspace;
		if (x==4) validcurrent = validnums;
		if (x==5) validcurrent = validchars;
		if (x==6) validcurrent = validnums;
		if (x == 3) finalValue = finalValue + ' ';
		else
		{
			if (validcurrent.indexOf(entry.charAt(x))!=-1)
			{
				finalValue = finalValue + entry.charAt(x);
			};
		}
	};
	
	postalcodefield.value = finalValue;
}
function checkdate(fieldname,msg)
{
	if (isDate(fieldname.value)==false){
		xalert(msg)
		return false;
	}
    return true
}


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

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++){   
        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 isDate(dtStr){
	var daysInMonth = DaysArray(12);
	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);
	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){
		xalert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		xalert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		xalert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		xalert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		xalert("Please enter a valid date");
		return false;
	}
return true
}

// Credit Card Validation Javascript
// copyright 12th May 2003, by Stephen Chapman, Felgall Pty Ltd

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function validateCreditCard(ccNum) {
 /*
  *  This function validates a credit card entry.
  *  If the checksum is ok, the function returns true.
  */
   var odd = 1;
   var even = 2;
   var calcCard = 0;
   var calcs = 0;
   var ccNum2 = "";
   var aChar = '';
   var cc;
   var r;
   
   for(var i = 0; i != ccNum.length; i++) {
      aChar = ccNum.substring(i,i+1);
      if(aChar == '-') {
         continue;
      }

      ccNum2 = ccNum2 + aChar;
   }
   
   cc = parseInt(ccNum2);
   if(cc == 0) {
      return false;
   }
   r = ccNum.length / 2;
   if(ccNum.length - (parseInt(r)*2) == 0) {
      odd = 2;
      even = 1;
   }
   
   for(var x = ccNum.length - 1; x > 0; x--) {
      r = x / 2;
      if(r < 1) {
         r++;
      }
      if(x - (parseInt(r) * 2) != 0) {
         calcs = (parseInt(ccNum.charAt(x - 1))) * odd;
      }
      else {
         calcs = (parseInt(ccNum.charAt(x - 1))) * even;
      }
      if(calcs >= 10) {
         calcs = calcs - 10 + 1;
      }
      calcCard = calcCard + calcs;
   }
   
   calcs = 10 - (calcCard % 10);
   if(calcs == 10) {
      calcs = 0;
   }
   
   if(calcs == (parseInt(ccNum.charAt(ccNum.length - 1)))) {
      return true;
   }
   else {
      return false;
   }
}

/////////////////////////////////
function getLabelCheckedValue(radioObj) {
	if(!radioObj) return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
		{
			//return radioObj.value;
			return radioObj.parentNode.title;
		}
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			var parent = radioObj[i].parentNode.title;
			return parent;
		}
	}
	return "";
}
/////////////////////////////////
function getCheckedValue(radioObj) {
	if(!radioObj) return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function atLeastOneCheckbox(checkbox, msg)
{
	for (var i = 0; i < checkbox.length;i++)
	{
		if (checkbox[i].checked) return true;	
	}
	var elem = checkbox[0];
	xalert (msg);
	return false;
}
/////////////////////////////////
function validatePostNewItem()
{
		var returnvalue = true;

	if (isEmpty(document.getElementById('pagetitle'),"Please enter the product name...")) returnvalue = false;
		if (noSelectionZero	(document.getElementById('category_id'),'Please choose a category for this product...')) returnvalue = false;
	var date_available =document.getElementById('date_available');
	var date_expiry = document.getElementById('date_expiry');

	if (isEmpty(document.getElementById('price'),"Please enter the product price...")) returnvalue = false;
	if (!isNumeric(document.getElementById('price'),"Please enter a valid number for the product price...")) returnvalue = false;

	if (isEmpty(date_expiry,"Please enter the date when the sale ends...")) returnvalue = false;
	if (isEmpty(date_available,"Please enter the date when the sale starts...")) returnvalue = false;
		
	if (!checkdate3(date_available.value, 'date1')) returnvalue = false;
	if (!checkdate3(date_expiry.value, 'date2')) returnvalue = false;
	if (date2 < date1) { xalert("Sales end date cannot be earlier than sales start date");returnvalue = false}
	if (date2 == date1) { xalert("Sales end date cannot be the same as sales start date");returnvalue = false}
    if (!isLaterThanToday(date_expiry.value)) {xalert ("Please input a later date for the sales end date"); returnvalue = false}
	
	if (isEmpty(document.getElementById('summary'),"Please enter a description for this product...")) returnvalue = false;
	
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
}
/////////////////////////////////

/////////////////////////////////
function validateLogin()
{
	var returnvalue = true;

	if (isEmpty(document.getElementById('xlogin_username'),"Please enter your user name...")) returnvalue = false;
	if (isEmpty(document.getElementById('xlogin_password'),"Please enter your password...")) returnvalue = false;
	/////////////
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
}

function validateForgotPassword()
{
	var returnvalue = true;

	if (isEmpty(document.getElementById('email'),"Please enter your e-mail address...")) returnvalue = false;else	
	if (!emailValidator (document.getElementById('email'),"Please correct your e-mail address...")) returnvalue = false;
	if (isEmpty(document.getElementById('firstname'),"Please enter your first name...")) returnvalue = false;
	if (isEmpty(document.getElementById('lastname'),"Please enter your last name...")) returnvalue = false;
	
	/////////////
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
}
/////////////////////////////////
function validateShoppingCartRegister()
{
	var returnvalue = true;

	if (isEmpty(document.getElementById('email'),"Please enter your e-mail address...")) returnvalue = false;else	
	if (!emailValidator (document.getElementById('email'),"Please correct your e-mail address...")) returnvalue = false;

	if (isEmpty(document.getElementById('xusername'),"Please choose a user name...")) returnvalue = false;
	if (!isAlphanumeric(document.getElementById('xusername'),"Your username should consist of numbers and letters only")) returnvalue = false;
	if (!lengthRestrictionOK(document.getElementById('xusername'),4,15,"Your username should be between 4 - 15 characters")) returnvalue = false;
	
	if (isEmpty(document.getElementById('xpassword'),"Please enter your password...")) returnvalue = false;
	if (isEmpty(document.getElementById('firstname'),"Please enter your first name...")) returnvalue = false;	
	if (isEmpty(document.getElementById('lastname'),"Please enter your last name...")) returnvalue = false;
	if (isEmpty(document.getElementById('address'),"Please enter your address...")) returnvalue = false;
	if (isEmpty(document.getElementById('city'),"Please enter your city...")) returnvalue = false;

	// Empty Postal Codes are Allowed
	//if (isEmpty(document.getElementById('postal'),"Please enter a valid zip/postal code")) returnvalue = false;
	/////////////
	var passwd = document.getElementById('xpassword');
	var passwd_verify = document.getElementById('xpassword_verify');
	if (passwd.value.length > 0)
	 {
		if (isEmpty(passwd_verify,"Please enter your your password verification")) returnvalue = false;
		if (passwd.value != passwd_verify.value)
		 {
			 xalert ('Your password does not match with the verification');
			 returnvalue = false;
		 }
	 }
	/////////////
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
	
}
/////////////////////////////////
function validateUpgrade()
{
	var returnvalue = true;

	var mbr1 = document.getElementById('mbr1');
	var mbr2 = document.getElementById('mbr2');
	if (!mbr1.checked && !mbr2.checked)
	{
			 xalert ('Please choose at least one membership type');
			 returnvalue = false;
	}
	/////////////

	if (isEmpty(document.getElementById('cc_cardholder_name'),"Please enter the name on the credit card")) returnvalue = false;
	if (!isEmpty(document.getElementById('cc_num'),"Please enter a credit card number"))
	{
		if (!validateCreditCard(document.getElementById('cc_num').value))
		{
			xalert('Invalid credit card number');
			returnvalue = false;
		} 
	} else returnvalue = false;
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
	
}
/////////////////////////////////
function validateRegister()
{
	var returnvalue = true;

	// Mod by Rob - June 4, 2009
	// Use form.element instead of get elementbyid
	// Allows multiple forms with the same ids on inputs (email) to validate
	var vForm = document.getElementById('registeruser');
	if (isEmpty(vForm.email,"Please enter your e-mail address...")) returnvalue = false;else	
	if (!emailValidator (vForm.email,"Please correct your e-mail address...")) returnvalue = false;
	// End Mod
	
	if (isEmpty(document.getElementById('xusername'),"Please choose a user name...")) returnvalue = false;
	if (!isAlphanumeric(document.getElementById('xusername'),"Your username should consist of numbers and letters only")) returnvalue = false;
	if (!lengthRestrictionOK(document.getElementById('xusername'),4,15,"Your username should be between 4 - 15 characters")) returnvalue = false;
	
	if (isEmpty(document.getElementById('xpassword'),"Please enter your password...")) returnvalue = false;
	if (isEmpty(document.getElementById('firstname'),"Please enter your first name...")) returnvalue = false;	
	if (isEmpty(document.getElementById('lastname'),"Please enter your last name...")) returnvalue = false;
	if (isEmpty(document.getElementById('address'),"Please enter your address...")) returnvalue = false;
	if (isEmpty(document.getElementById('city'),"Please enter your city...")) returnvalue = false;

	//Empty Postal Codes are Allowed
	//if (isEmpty(document.getElementById('postal'),"Please enter a valid zip/postal code")) returnvalue = false;
	if (isEmpty(document.getElementById('cc_cardholder_name'),"Please enter the name on the credit card")) returnvalue = false;
	if (!isEmpty(document.getElementById('cc_num'),"Please enter a credit card number"))
	{
		if (!validateCreditCard(document.getElementById('cc_num').value))
		{
			xalert('Invalid credit card number');
			returnvalue = false;
		} 
	} else returnvalue = false;
	

	var mbr1 = document.getElementById('mbr1');
	var mbr2 = document.getElementById('mbr2');
	if (!mbr1.checked && !mbr2.checked)
	{
			 xalert ('Please choose at least one membership type');
			 returnvalue = false;
	}
	/////////////
	var passwd = document.getElementById('xpassword');
	var passwd_verify = document.getElementById('xpassword_verify');
	if (passwd.value.length > 0)
	 {
		if (isEmpty(passwd_verify,"Please enter your your password verification")) returnvalue = false;
		if (passwd.value != passwd_verify.value)
		 {
			 xalert ('Your password does not match with the verification');
			 returnvalue = false;
		 }
	 }
	/////////////
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
}

/////////////////////////////////
function validateUpdate()
{
		var returnvalue = true;
		
	var passwd = document.getElementById('password');
	var passwd_verify = document.getElementById('password_verify');
	if (passwd.value.length > 0)
	 {
		if (isEmpty(passwd_verify,"Please enter your your password verification")) returnvalue = false;
		if (passwd.value != passwd_verify.value)
		 {
			 xalert ('Your password does not match with the verification');
			returnvalue = false;
		 }
	 }
	/////////////
	if (returnvalue) return true;
	else
	{
		total_alert();
		return false;
	}
}



function noSelection(elem, helperMsg){
	if(elem.value == ""){
		xalert(helperMsg);
		return true;
	}else{
		return false;
	}
}

function noSelectionZero(elem, helperMsg){
	if(elem.value == "0"){
		xalert(helperMsg);
		return true;
	}else{
		return false;
	}
}

function isPostCode(the_entry){ // checks Canadian codes only
var entry =the_entry.replace(' ','');
var entry =entry.replace('-','');
var strlen=entry.length; if (strlen!==6){return false;}
entry=entry.toUpperCase();  // in case of lowercase
// Check for legal characters in string - note index starts at zero
if('ABCEGHJKLMNPRSTVXY'.indexOf(entry.charAt(0))<0) {return false;}
if('0123456789'.indexOf(entry.charAt(1))<0) {return false;}
if('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(2))<0) {return false;}
if('0123456789'.indexOf(entry.charAt(3))<0) {return false;}
if('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(4))<0) {return false;}
if('0123456789'.indexOf(entry.charAt(5))<0) {return false;}
return true;}

function isEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		xalert(helperMsg);
		return true;
	}
	return false;
}

function isGreaterThanZero(elem, helperMsg){
	var x = parseFloat(elem.value);
	if (x > 0.0)
	{
			return true;
	}else{
		xalert(helperMsg);
		return false;
	}
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		xalert(helperMsg);
		return false;
	}
}

function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		xalert(helperMsg);
		return false;
	}
}

function isAlphanumeric(elem, helperMsg){
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		xalert(helperMsg);
		return false;
	}
}

function lengthRestrictionOK(elem, min, max, msg){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
		return true;
	}else{
		xalert(msg);
		return false;
	}
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		xalert(helperMsg);
		return false;
	}

}

ddaccordion.init({
	headerclass: "submenuheader", //Shared CSS class name of headers group
	contentclass: "submenu", //Shared CSS class name of contents group
	revealtype: "mouseover", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	mouseoverdelay: 100, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc] [] denotes no content
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["", ""], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	//togglehtml: ["suffix", "<img src='/templates/topadvisorforum/images/plus.gif' class='statusicon' />", "<img src='/templates/topadvisorforum/images/minus.gif' class='statusicon' />"], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})

