function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; 
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; 
  document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;  

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,   // true if required
                         fld_msg)// explanatory text for the info/error msg
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "ERROR: " + fld_msg + " field is required");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         fld_msg)// explanatory text for the info/error msg
{
  var stat = commonCheck (vfld, ifld, true, fld_msg);
  if (stat != proceed) return stat;

  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//            validateEqualPassword
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validateEqualPassword 
												(vpass,   			// pass to be validated
												 vpass_confirm, // pass confirmation to be validated
                         ifld)   	// id of element to receive info/error msg
{
	fld_msg = 'Both password and password confirmation should be filled.';
	
  var stat = commonCheck (vpass, ifld, true, fld_msg);
  if (stat != proceed) return stat;
  
  var stat = commonCheck (vpass_confirm, ifld, true, fld_msg);
  if (stat != proceed) return stat;
  
  if (trim(vpass.value) != trim(vpass_confirm.value)) {
    msg (ifld, "error", "ERROR: Password and Password Confirmation are not equal");
    setfocus(vpass);
    return false;
  }
  
  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,   // true if required
                         fld_msg)// explanatory text for the info/error msg
{
  var stat = commonCheck (vfld, ifld, reqd, fld_msg);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "ERROR: " + fld_msg + " is not a valid e-mail address");
    vfld.value="";
	setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "Unusual e-mail address - check if correct");
  else
    msg (ifld, "warn", "");
  return true;
};


// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,   // true if required
												 fld_msg)// explanatory text for the info/error msg
{
  var stat = commonCheck (vfld, ifld, reqd, fld_msg);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "ERROR: " + fld_msg + " is not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (ifld, "error", "ERROR: " + fld_msg + " has " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn", fld_msg + " has " + numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "warn", fld_msg + " has only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "warn", "");
  }
  return true;
};

// -----------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// -----------------------------------------

function validateAge    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,   // true if required
												 fld_msg)// explanatory text for the info/error msg
{
  var stat = commonCheck (vfld, ifld, reqd, fld_msg);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "ERROR: " + fld_msg + " doesn't have a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR: " + fld_msg + " doesn't have a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", fld_msg + " is older than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "Bit young for this, aren't you?");
    else        msg (ifld, "warn", "");
  }
  return true;
};

function validateCreditCard(vfld, // element to be validated
                         ifld,   	// id of element to receive info/error msg
                         reqd,   	// true if required
												 fld_msg) 
{
  var stat = commonCheck (vfld, ifld, reqd, fld_msg);
  if (stat != proceed) return stat;
  
	var tfld = trim(vfld.value);
	var v = "0123456789";
	var w = "";
	for (var i=0; i < tfld.length; i++) {
	x = tfld.charAt(i);
	if (v.indexOf(x,0) != -1)
	w += x;
	}
	var j = w.length / 2;
	if (j < 6.5 || j > 8 || j == 7) {
		msg (ifld, "error", "ERROR: " + fld_msg + " is not a valid Credit Card Number");
    setfocus(vfld);
	vfld.value="";
		return false;
	}
	var k = Math.floor(j);
	var m = Math.ceil(j) - k;
	var c = 0;
	for (var i=0; i<k; i++) {
	a = w.charAt(i*2+m) * 2;
	c += a > 9 ? Math.floor(a/10 + a%10) : a;
	}
	for (var i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
	if (c%10 == 0) {
		return true;
	} else {
		msg (ifld, "error", "ERROR: " + fld_msg + " is not a valid Credit Card Number");
    setfocus(vfld);
		return false;
	}
}



function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
      
   if (sText.length <= 0){
   		IsNumber = false;
   }
   
   return IsNumber;
}

//Valida si un Campo es un numero positivo
function validateIsPositive(vfld, // element to be validated
                         ifld,   	// id of element to receive info/error msg
                         reqd,   	// true if required
												 fld_msg) 
{	
	
	var stat = commonCheck (vfld, ifld, reqd, fld_msg);
  if (stat != proceed) return stat;
	
	var tfld = trim(vfld.value);
	
	if (IsNumeric(tfld) && tfld != ''){
		if (tfld > 0) {
				msg (ifld, "warn", "");
				return true;
			}
			else {
				msg (ifld, "error", "ERROR: " + fld_msg + " must be higher than zero. If you don't want to use this feature click on the disable button");
    		setfocus(vfld);
				return false;
			}
	}
	else {
		msg (ifld, "error", "ERROR: " + fld_msg + " must a valid number");
    setfocus(vfld);
		return false;
	}
	
}

function clearMessage(ifld) // id of element to receive info/error msg
{
	msg (ifld, "warn", "");
	return true;
}


function GoBack()
{
	document.form.action.value = '';
	document.form.submit();
}

function unHider(fld)
{
	fld.style.display = 'block';
}
function hider(fld)
{
	fld.style.display = 'none';
}

// Estas son la funciones de AJAX

function handleHttpResponse() {   
// readyState of 4 signifies request is complete
	if (http.readyState == 4) {
// status of 200 signifies sucessful HTTP call        	
      if(http.status==200) 
      {
        var results=http.responseText;
      	document.getElementById('frm_error').innerHTML = results;
	      if (trim(results) != '') 
	      {
	      	document.getElementById('BOX_Name').focus();
	      }
      }
  }
}

function getHTTPObject() {
  var xmlhttp;

  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject){
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (!xmlhttp){
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
    }   
	}
  return xmlhttp;
}

var http = getHTTPObject(); // We create the HTTP Object

function checkPw(form) {
pw1 = form.BOX_Password.value;
pw2 = form.BOX_Confirm_Password.value;

if (pw1 != pw2) {
var msgErr = "ERROR: Password and Confirmation do not match.";
document.getElementById('frm_error').innerHTML = msgErr;
document.getElementById('BOX_Confirm_Password').focus();
	return false;
	}
else return true;
}



// -----------------------------------------
//               Next & Prev
// for Paged Results
// 
// -----------------------------------------
function Next_Form(current)
	{
	document.form.HID_CurrentPage.value = current + 1;
	document.form.submit();
	}	
	
function Prev_Form(current)
	{			 
	document.form.HID_CurrentPage.value = current - 1;
	document.form.submit();
	}	
	
	
// -----------------------------------------------------------
//               Scripts for Validate Date
// 
// 
// -----------------------------------------------------------
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, field){
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;
	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){
		alert("The date format should be : mm dd yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month for "+field)
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day for "+field)
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear+" for "+field)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date for ")
		return false
	}
return true
}

function ValidateDate(prefijo, field){
	var dt = "";
	var str_month = 'BOX_' + prefijo + 'DateTimeMonth';
	var str_day = 'BOX_' + prefijo + 'DateTimeDay';
	var str_year = 'BOX_' + prefijo + 'DateTimeYear';
	
	dt+= eval ('document.form.'+str_month+'.value')+ '/' +
			 eval('document.form.'+str_day+'.value') + '/' +
			 eval('document.form.'+str_year+'.value');

	return isDate(dt, field);
}

function DateComparison(prefijo1, operator, prefijo2 ){
	var str_month1 = 'BOX_' + prefijo1 + 'DateTimeMonth';
	var str_day1 = 'BOX_' + prefijo1 + 'DateTimeDay';
	var str_year1 = 'BOX_' + prefijo1 + 'DateTimeYear';
	var str_month2 = 'BOX_' + prefijo2 + 'DateTimeMonth';
	var str_day2 = 'BOX_' + prefijo2 + 'DateTimeDay';
	var str_year2 = 'BOX_' + prefijo2 + 'DateTimeYear';
	
	var month1 = eval ('parseInt(document.form.'+str_month1+'.value)');
	var day1 = eval ('parseInt(document.form.'+str_day1+'.value)');
	var year1 = eval ('parseInt(document.form.'+str_year1+'.value)');
	var month2 = eval ('parseInt(document.form.'+str_month2+'.value)');
	var day2 = eval ('parseInt(document.form.'+str_day2+'.value)');
	var year2 = eval ('parseInt(document.form.'+str_year2+'.value)');
	// alert ('1 y:'+year1+' m:'+month1+' d:'+day1+'\n'+'2 y:'+year2+' m:'+month2+' d:'+day2);

	switch(operator){
		case '=': if(day1.toInt() == day2.toInt() && month1.toInt() == month2.toInt() && year1.toInt() == year2.toInt())
								 return true;
							else
								return false;
		break;
		case '<': 
			if(year1 < year2 ||
			year1 == year2 && month1 < month2 ||
			year1 == year2 && month1 == month2 && day1 < day2)
			{
				return true;
			} else {
				return false;
			}
		break;

		case '>': if(year1 > year2 ||
								year1 == year2 && month1 > month2 ||
								year1 == year2 && month1 == month2 && day1 > day2)
								return true;
							else
								return false;
		break;
		case '<=': if( DateComparison(prefijo1,'<', prefijo2) || 
									 DateComparison(prefijo1,'=',prefijo2) )
							 	return true;
							 else
							 	return false;
		break;
		case '>=': if( DateComparison(prefijo1,'>', prefijo2) || 
									 DateComparison(prefijo1,'=',prefijo2) )
							 	return true;
							 else
							 	return false;
		break;
		default: alert('Invalid Comparison Operator');
						 return false;
		break;
									
	}
}
