function CEP_getValue(elem) {
  var isRadio = false;
  
  if( $("input[name=" + elem + "]").is(":radio") ) {
    isRadio = true;
  } else {
    elem = document.getElementById(elem);
  }
  
  var etype,val='';
  if (etype=elem.type) {
	if (etype == "text" || etype == "textarea" || etype == "button" || etype == "hidden" || etype == "file" || etype == "password") {
	  val=elem.value;
	}
	else if(etype == "checkbox") {
	  if (elem.checked) {
		val=elem.value;
	  }
	}
	else if(etype == "select-one") {
	val=elem.options[elem.selectedIndex].text;
	}
  }
  else if (isRadio) {
    val = $("input[name=" + elem + "]:checked").val();
  }
  return val;
}

/***** FOR JQUERY DATEPICKER *****/

CEPdays = [
  [4, 22, 2011, "Good Friday"],
  [5, 30, 2011, "Memorial Day"],
  [7, 4, 2011, "Independence Day"],
  [9, 5, 2011, "Labor Day"],
  [11, 11, 2011, "Veteran's Day"],
  [11, 24, 2011, "Thanksgiving Day"],
  [11, 25, 2011, "Thanksgiving Friday"],
  [12, 23, 2011, "Christmas Holiday"],
  [12, 24, 2011, "Christmas Eve"],
  [12, 30, 2011, "For New Year 2012"]
];

function CEPholidays(date) {
    for (i = 0; i < CEPdays.length; i++) {
      if (date.getMonth() == CEPdays[i][0] - 1
          && date.getDate() == CEPdays[i][1]
	  	  && date.getFullYear() == CEPdays[i][2]) {
        return [false, '', CEPdays[i][3]];
      }
    }
  return [true, ''];
}

function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
    if (noWeekend[0]) {
        return CEPholidays(date);
    } else {
        return noWeekend;
    }
}


/***** FORMFIELD OBJECT FUNCTIONS *****/
				
function formField() {
  this.id = arguments[0];
  if( $("input[name=" + this.id + "]").is(":radio") ) {
    this.isRadio = true;
  } else {
    this.isRadio = false;
  }
  this.msg = arguments[0] + "-msg";
  this.msgBody = arguments[0] + "-msg"; // This is so it can be manually reset later (for multi-field lines)
  this.iconBox = arguments[0] + "-iconbox"; // Currently only used by Credit Card fields
  this.helptext = arguments[2];
  this.isRequired = 0;
  this.isCC = 0;
  if (arguments[1] == "required") {
	this.isRequired = 1;
  } else if (arguments[1] == "required:cc") {
	this.isRequired = 1;
	this.isCC = 1;
  }
  this.parameters = new Array();
  this.errmsgs = new Array();
  var j = 0;
  for(var i=3; i<arguments.length; i+=2) {
	this.parameters[j] = arguments[i];
	this.errmsgs[j] = arguments[i+1];
	j++;
  }
  this.focused = false;
  this.active = false;
  this.valid = false;
  this.initialize = fieldInitialize;
  this.validate = fieldValidate;
  this.setHelp = fieldSetHelp;
  this.clearHelp = fieldClearHelp;
  this.accordionSection = null;
}
			
function fieldInitialize() {
  if("this.isRadio") {
    var jQid = "[name=" + this.id + "]";
  } else {
    var jQid = "#" + this.id;
  }
  var jQref = this;
  
  $(jQid).mouseover( function () {
    jQref.setHelp();
  });
  
  $(jQid).mouseout( function () {
    jQref.clearHelp();
  });
  
  $(jQid).focus( function () {
    jQref.focused = true;
	jQref.setHelp();
  });
  
  $(jQid).blur( function () {
    jQref.focused = false;
	jQref.active = !jQref.validate();
	if (jQref.accordionSection != null) {
	  if (jQref.accordionSection.activeValidating == true) {
	    jQref.accordionSection.validate();
	  }
	}
  });
  
  $(jQid).keyup( function () {
    if (jQref.active) {
	  if (jQref.accordionSection != null) {
	    if (jQref.accordionSection.activeValidating == true) {
		  jQref.accordionSection.validate();
		} else { jQref.validate(); }
	  } else {
	    jQref.validate();
	  }
	}
  });
  
  
}
			
function fieldValidate() {
  var val = CEP_getValue(this.id);
  var isValid = true;
  var showMsg = "&nbsp\;";
  
  if (!val && this.isRequired) {
	isValid = false;
	if (window.lang == "en") {
      showMsg = "This field is required";
	} else {
	  showMsg = "Esta informaci&oacute;n es necesaria";
	}
	
  } else if (!val && !this.isRequired) {
    isValid = true;
  } else {
    for (var i = 0; i<this.parameters.length; i++) {
      if (this.parameters[i] == "words:2") {
	    var expression=/(\S+)(\s+)(.+)$/;
		if(!(expression.test(val))) {
		  isValid = false;
		  showMsg = this.errmsgs[i];
		}
	  } else if (this.parameters[i].indexOf("maxlen:") != -1) {
	     var temp = parseInt(this.parameters[i].replace("maxlen:", ""), 10);  //convert temp to int
		 val = val + ""; //convert val to string (for access to .length property)
		 if (val.length > temp) {
		   isValid = false;
		   showMsg = this.errmsgs[i];
		 }	
	  } else if (this.parameters[i].indexOf("minlen:") != -1) {
	     var temp = parseInt(this.parameters[i].replace("minlen:", ""), 10);  //convert temp to int
		 val = val + ""; //convert val to string (for access to .length property)
		 if (val.length < temp) {
		   isValid = false;
		   showMsg = this.errmsgs[i];
		 }	
	  } else if (this.parameters[i].indexOf("len:") != -1) {
	     var temp = parseInt(this.parameters[i].replace("len:", ""), 10);  //convert temp to int
		 val = val + ""; //convert val to string (for access to .length property)
		 if (val.length != temp) {
		   isValid = false;
		   showMsg = this.errmsgs[i];
		 }		  
	  } else if (this.parameters[i] == "isphone") {
	      var expression=/((\(\d{3}\)?)|(\d{3}))([\s-.\/]?)(\d{3})([\s-.\/]?)(\d{4})/;
		  if (!(expression.test(val))) {
		    isValid = false;
			showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "isemail") {
		  var expression=/(".+"\s)?<?[a-zA-Z\._0-9]+[^\._]@([a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,6}>?;?/;
		  if (!(expression.test(val))) {
		    isValid = false;
			showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "nohtml") {
		  var expression=/<(.|\n)*?>/;
		  if ((expression.test(val))) {
		    isValid = false;
			showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "zip") {
		  var expression=/\d{5}/;
		  if (!(expression.test(val))) {
		    isValid = false;
			showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "iscurrency") {
		  var expression=/^(\$)?(([1-9]\d{0,2}(\,\d{3})*)|([1-9]\d*)|(0))(\.\d{2})?$/;
		  if (!(expression.test(val))) {
			  isValid = false;
			  showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "isinteger") {
		  var expression=/^[0-9]+$/;
		  if (!(expression.test(val))) {
			  isValid = false;
			  showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "istaxid") {
		  val = val.replace(/-/g, "");
		  var expression=/^[0-9]{9}$/;
		  if (!(expression.test(val))) {
			  isValid = false;
			  showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i].indexOf("sameas:") != -1) {
	     var temp = this.parameters[i].replace("sameas:", "");
		  var val2 = CEP_getValue(temp);
		  if (val != val2) {
			  isValid = false;
			  showMsg = this.errmsgs[i];
		  }
	  } else if (this.parameters[i] == "isCredit") {
		  isValid = false;
		  var expressionV=/^4[0-9]{12}(?:[0-9]{3})?$/;          // Visa
		  var expressionMC=/^5[1-5][0-9]{14}$/;                 // Master Card
		  var expressionA=/^3[47][0-9]{13}$/;                   // AMEX
		  var expressionDC=/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/;  // Diners Club
		  var expressionDN=/^6(?:011|5[0-9]{2})[0-9]{12}$/;     // Discover/Novus
		  
		  if (expressionV.test(val)) {
		    isValid = true;
			$("#" + this.iconBox).css("background-image", "url(/files/images/site-resources/credit-cards/visa.gif)");
		  } else if (expressionMC.test(val)) {
		    isValid = true;
			$("#" + this.iconBox).css("background-image", "url(/files/images/site-resources/credit-cards/mastercard.gif)");
		  } else if (expressionA.test(val)) {
		    isValid = true;
			$("#" + this.iconBox).css("background-image", "url(/files/images/site-resources/credit-cards/amex.gif)");
		  } else if (expressionDC.test(val)) {
		    isValid = true;
			$("#" + this.iconBox).css("background-image", "url(/files/images/site-resources/credit-cards/diners.gif)");
		  } else if (expressionDN.test(val)) {
		    isValid = true;
			$("#" + this.iconBox).css("background-image", "url(/files/images/site-resources/credit-cards/discover.gif)");
		  }
		  
		  
		  if (isValid == false) {
		    showMsg = this.errmsgs[i];
			$("#" + this.iconBox).css("background-image", "none");
	      } else {
			$("#" + this.iconBox).css("background-repeat", "no-repeat");
			$("#" + this.iconBox).css("background-position", "310px 0px");
		  }
	  }
    }
  }
  
  
  if (!isValid) {
	this.valid = false;
	this.active = true;
    if (!$("#" + this.msg).hasClass("invalid")) {
	  $("#" + this.msg).css("opacity", 0);
      $("#" + this.msg).removeClass();
	  $("#" + this.msg).addClass("invalid");
	  $("#" + this.msg).fadeTo("slow", 1);
	}
  } else {
	this.valid = true;
	if (!$("#" + this.msg).hasClass("valid")) {
	  $("#" + this.msg).css("opacity", 0);
      $("#" + this.msg).removeClass();
	  $("#" + this.msg).addClass("valid");
	  $("#" + this.msg).fadeTo("slow", 1);
	}
  }
  
  showMsg = "<span class='invalid-text'>" + showMsg + "</span>";
  $("#" + this.msgBody).html(showMsg);
  return isValid;
}

function fieldSetHelp() {
  if (!this.active && !this.valid && !$("#"+this.msg).hasClass("inf-form")) {
	  $("#" + this.msg).css("opacity", 0);
    $("#" + this.msg).removeClass();
    $("#" + this.msg).addClass("inf-form");
	$("#" + this.msgBody).html("<span class='inf-form-text'>" + this.helptext + "</span>");
	$("#" + this.msg).fadeTo("slow", 1);
  }
}

function fieldClearHelp() {
  if (!this.focused && $("#"+this.msg).hasClass("inf-form")) {
    $("#" + this.msg).removeClass();
	$("#" + this.msgBody).html("");
  }
}

/***** END FORMFIELD OBJECT FUNCTIONS *****/

/***** FORMFIELD FUNCTIONS *****/

function initializeFormFields(iFF) {
  for (var i = 0; i<iFF.length; i++) { iFF[i].initialize(); }
  return true;
}


function validateFormFields(vFF) {
  var isValid = true;
  for (var i = 0; i < vFF.length; i++) {
    if (!vFF[i].validate()) { isValid = false; }
  }
  return isValid;
}

/***** END FORMFIELD FUNCTIONS *****/

/***** ACCORDION FORM FUNCTIONS *****/

function accordionSection() {
  this.id = arguments[0];
  this.jqID = $("#" + this.id);
  this.head = this.jqID.children(".acc-head");
  this.label = this.head.children(".acc-label");
  this.h2 = this.head.children("h2");
  this.editButton = null;
  this.content = this.jqID.children(".acc-content");
  this.content.slideUp();
  this.next = null;
  this.prev = null;
  this.nextButton = null;
  this.prevButton = null;
  this.active = false;
  this.formFieldArray = null;
  if (arguments.length > 1) {  // optional second argument is an array of formFields
    this.formFieldArray = arguments[1];
	
	if (window.lang == "en") {
      this.h2.append("<div class=\"edit\">Make Changes</div>");
	} else {
      this.h2.append("<div class=\"edit\">Cambiar</div>");
	}
	
	for (i = 0; i<this.formFieldArray.length; i++) {
	  this.formFieldArray[i].accordionSection = this;
	}
  } else {
	if (window.lang == "en") {
	  this.h2.append("<div class=\"edit\">Review</div>");
	} else {
	  this.h2.append("<div class=\"edit\">Revisar</div>");
	}
  }
  this.activeValidating = false;
  
  this.initialize = accordionInitialize;
  this.setActive = accordionSetActive;
  this.setInactive = accordionSetInactive;
  this.validate = accordionValidate;
}

function accordionInitialize() {
  var jQid = "#" + this.id;
  var jQref = this;
  
  if(this.next != null && this.prev != null) {
	if (window.lang == "en") {
      this.content.append("<div class=\"acc-nav\"><button type=button class=acc-nav-prev>&laquo; Prev</button><button type=\"button\" class=\"acc-nav-next\">Next &raquo;</button></div>");
	} else {
    this.content.append("<div class=\"acc-nav\"><button type=button class=acc-nav-prev>&laquo; Atras</button><button type=\"button\" class=\"acc-nav-next\">Siguiente &raquo;</button></div>");
	}
	this.nextButton = this.content.find(".acc-nav-next");
	this.prevButton = this.content.find(".acc-nav-prev");
	
  } else if (this.next != null && this.prev == null) {
	if (window.lang == "en") {
      this.content.append("<div class=\"acc-nav\"><button type=\"button\" class=\"acc-nav-next\">Next &raquo;</button></div>");
	} else {
    this.content.append("<div class=\"acc-nav\"><button type=\"button\" class=\"acc-nav-next\">Siguiente &raquo;</button></div>");
	}
	this.nextButton = this.content.find(".acc-nav-next");
	
  } else if (this.next == null && this.prev != null) { //watch out for submit button on the last node
    
      if (this.content.children(".acc-nav")) {
		if (window.lang == "en") {
	      this.content.children(".acc-nav").find("input").before("<button type=\"button\" class=\"acc-nav-prev\">&laquo; Prev</button> or ");
		} else {
	    this.content.children(".acc-nav").find("input").before("<button type=\"button\" class=\"acc-nav-prev\">&laquo; Atras</button> o ");
		}
	  } else {
		if (window.lang == "en") {
          this.content.append("<div class=\"acc-nav\"><button type=\"button\" class=\"acc-nav-prev\">&laquo; Prev</button></div>");
		} else {
        this.content.append("<div class=\"acc-nav\"><button type=\"button\" class=\"acc-nav-prev\">&laquo; Atras</button></div>");
		}
	  }
	  this.prevButton = this.content.find(".acc-nav-prev");
  }
  
  jQref.head.click( function () { jQref.setActive(); });
  
  if (jQref.prev != null) {        // Prev button listener
    jQref.prevButton.click( function () {
	  jQref.prev.setActive();
	});
  }
  
  if (jQref.next != null) {       // Next button listener
    jQref.nextButton.click( function () {
	  jQref.next.setActive();
	});
  }
  
  jQref.head.mouseover( function () { jQref.jqID.addClass("hover");    });
  jQref.head.mouseout(  function () { jQref.jqID.removeClass("hover"); });
  
}

function accordionSetActive() {
  if(!this.active == true) {
	var i = null;
	  
	if(this.prev != null) {    //set all previous sections to inactive
	  i = this.prev;
	  while (i != null) {
	    if (i.active == true) {
	      i.setInactive();
		}
		i = i.prev;
	  }
	}
		  
	if(this.next != null) {    //set all subsequent sections to inactive
	  i = this.next;
	  while (i != null) {
	    if (i.active == true) {
	      i.setInactive();
		}
		i = i.next;
	  }
	}
    this.jqID.addClass("active");
	this.active = true;
	this.content.slideDown();
  }
}

function accordionSetInactive() {
  if(this.active == true) {
    this.jqID.removeClass("active");
	this.active = false;
	this.content.slideUp();
  }
}

function accordionValidate() {
  if(this.formFieldArray != null) {
    var isValid = validateFormFields(this.formFieldArray);
    this.activeValidating = true;
	
    if(!isValid) { 
	  this.jqID.addClass("acc-error"); 
	  this.jqID.removeClass("acc-valid");
	} else { 
	  this.jqID.addClass("acc-valid");
	  this.jqID.removeClass("acc-error");
	}
    return isValid;
  } else { return true; }  // if there's no formFields, just call it good.
}
