/*************************************/
//       ImageSwap
/*************************************/

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];}
}



//determining the browser type
var brwsr_ns = (document.layers ? true : false);
var brwsr_ie = (document.all ? true : false);
var brwsr_navig = navigator.userAgent;
var brwsr_moz = (brwsr_navig.indexOf("Gecko")>=0 ? true : false);

var DEFAULT_DIALOG_OPTIONS = 'width=800, height=600, status=1, resizeable=1, scrollbars=1';

/*
	this function returns an event object
	depending on browser type
*/

function getEvnt()
{
  return brwsr_ie ? event : eventObj;
}

function openWindow(url, windowName, options)
{
  if (options.length == 0)
  {
    options = DEFAULT_DIALOG_OPTIONS;
  } //end if
	
  return window.open(url, windowName, options);
} //end function openWindow 

/*
	this function returns the array
	index if a value is found, otherwise
	it returns -1
*/

Array.prototype.indexOf = function(value) {
  for (var i=0; i<this.length; i++)
  {
    if (this[i] == value) return i;
  } //end for
	
  return -1;
};

function checkUncheckAll(frm, field) {
  var elements = frm.elements;
	for(var i=0; i<elements.length; i++) {
	  if(elements[i].type == "checkbox" && elements[i].disabled == false) {
		  if(field.value == "Check All") {
			  elements[i].checked = true;
			} //end if check all
			else {
			  elements[i].checked = false;
			} //else clear all
		} //end if its a checkbox element
	} //end for

	if(field.value == "Check All") {
	  field.value = " Clear All ";
	} //end if check all
	else {
	  field.value = "Check All";
	} //else clear all 
	
	return true;
} //end function check_uncheck

//Global variable set at start of script
var emptyString = " field is blank. Please enter a "

/*
	this function returns true
	if a given string is float value
	.0 or 0.0 or 0.00
*/

function isFloat(str)
{
	var pattern = /^\d*\.\d+$/;
	return pattern.test(str);
} //end function isFloat  

/*
	this function returns true
	if a given string is integer value
	0 or 1 or 1000000000 etc
*/

function isInteger(str)
{
	var pattern = /^\d+$/;
	return pattern.test(str);
} //end function isInteger 

/*
	same as isInteger
*/

function isDigits(str) 
{
	var pattern = /^\d+$/;
	return pattern.test(str);
} //end function isDigits 

function isNumber(str) {
  var mychar, numdecs = 0;
  for (i = 0; i < str.length; i++) 
	{
    mychar = str.charAt(i)
    if ((mychar >= "0" && mychar <= "9") || mychar == ".") 
  	{
      if (mychar == ".")
        numdecs++
    } //end if
    else
  	{
      return false;
  	} //else
  } //end for
	
  if (numdecs > 1)
	{
    return false;
	} //end if

  return true;
} //end function isNumber

/*
	this function makes sure that user
	is entering integers only
*/

function onKeyPressInteger()
{
  try
  {
    var inptChar = String.fromCharCode(getEvnt().keyCode);
    if (isDigits(inptChar))
		{
  		return true;
		} //end if
  } //try
  catch (e) {} 
	
	return false;
} //end function onKeyPressInteger

/*
	this function makes sure that user
	is entering float value only
*/

function onKeyPressFloat()
{
  try
  {
    var inptChar = String.fromCharCode(getEvnt().keyCode);
    if (isNumber(inptChar))
		{
  		return true;
		} //end if
  }
  catch (e) {} 
	
	return false;
} //end function onKeyPressFloat 

function onKeyPressTimeRange()
{
  try
  {
    var inptChar = String.fromCharCode(getEvnt().keyCode);
    if (isDigits(inptChar) | inptChar==":" | inptChar=="a" | inptChar=="p" | inptChar=="m" | inptChar=="-")
		{
  		return true;
		} //end if
  } //try
  catch (e) {}
	
  return false;
} //end function onKeyPressTimeRange 

function onKeyPressTime()
{
  try
  {
    var inptChar = String.fromCharCode(getEvnt().keyCode);
    if (isDigits(inptChar) | inptChar==":" | inptChar=="a" | inptChar=="p" | inptChar=="m" )
		{
  		return true;
		} //end if
  } //try
  catch (e) {}

  return false;
} //end function onKeyPressTime 

function onChangeFloat(field, fieldName)
{
  field.value = field.value.replace(/,/g,'.');
  field.value = field.value.replace(/\D^\./g,'');
  if (!isNumber(field.value)) 
	{
    alert(fieldName + ': Please input number. Use "." (dot) as decimal symbol.');
    field.value = '';
    return false;
  } //end if
	
  return true;
} //end function onChangeFloat 

function onChangeInteger(field, fieldName)
{
  field.value = field.value.replace(/\D/g,'');
  if (!isDigits(field.value)) 
	{
    alert(fieldName + ': Please input number');
    field.value = '';
    return false;
  } //end if
	
  return true;
} //end function onChangeInteger 

function showError(show, errElementId)
{
  var e = document.getElementById(errElementId);
  if (e != null)
  {
    if (show)
    {
      e.style.visibility = "visible";
    } //end if
    else
    {
      e.style.visibility = "hidden";
    } //else
  } //end if

  return show;
} //end function showError 

function isBlank(str) 
{
  return isNull(str);
} //end function isBlank

function isSize(str, size) 
{
  return (str.length == size);
} //end function isSize

function dialogListValidation(num, formfieldname, messagefieldname) 
{
  if (num == -1)
  {
    alert(messagefieldname + ":  requires a value. Please select a value.");
    formfieldname.focus();
    return false
  } //end if
  else
	{
    return true;
	} //else
} //end function dialogListValidation

function isInRange(myfield, fname, num1, num2) 
{
  var i = parseFloat(myfield.value);
  if (isNaN(num1) && isNaN(num2))
  {
    return true;
  } //end if

  if (isNaN(num2))
  {
    if(i >= num1)
      return true
    else
      alert(fname + ": enter a number greater than or equal to " + num1);
  } //end if
	
  if (isNaN(num1))
  {
    if(i <= num2)
      return true
    else
      alert(fname + ": enter a number less than or equal to " + num1);
  } //end if

  if (!isNaN(num1) && !isNaN(num2))
	{
    if ((i >= num1) && (i <= num2))
		{
      return true;
		} //end if
    else
    {
      alert(fname + ": enter a number between " + num1 + " and " + num2);
    } //else
	} //end if
	
  myfield.focus();
	
  return false;
} //end function 

function stripNonDigits(str) 
{
  var i, mychar, newstring = "";
  for (i = 0;  i < str.length; i++) 
	{
    mychar = str.charAt(i);
    if (isDigits(mychar))
		{
      newstring += mychar;
		} //end if
  } //end for
	
  return newstring;
} //end function stripNonDigits 

function stripChars(str, chars) 
{
  var i, mychar, newstring = "";
  for (i = 0;  i < str.length; i++) 
	{
    mychar = str.charAt(i);
    if (chars.indexOf(mychar) == -1)
		{
      newstring += mychar;
		} //end if
  } //end for
	
  return newstring;
} //end function stripChars

function validateString(myfield, s) 
{
  if (notNull(myfield.value)&& notBlank(myfield.value))
	{
    return true;
	} //end if
  else 
	{
    myfield.focus()
    alert("The " + s + emptyString + s)
    return false
  } //else
} //end function validateString 

/*
	this function returns true if
	str has atleast 1 character
*/

function notBlank(str) 
{
  for (i = 0; i < str.length; i++) 
	{
    if (str.charAt(i) != " ")
		{
      return true;
		} //end if
  } //end for
	
  return false;
}

/*
	this function return true if str
	is null or 0 length
*/

function isNull(str) 
{
  return (str.length == 0);
}

/*
	this function checks if a given date is correct
	yyyy-mm-dd or yyyy/mm/dd or yyyy.mm.dd
*/

function checkDate(myfield, fname) 
{
  var a,b,c,d,e,f, err=0;
  a = myfield.value;
	
  if (a.length != 10)
	{
  	return false;
	} //end if
	
  b = parseInt(a.substring(0, 2),10)// month;
  c = a.substring(2, 3)// '/';
  d = parseInt(a.substring(3, 5),10)// day;
  e = a.substring(5, 6)// '/';
  f = parseInt(a.substring(6, 10),10)// year;
	
  if ((b<1 || b>12 || isNaN(a.substring(0, 2)) || a.substring(0, 2).indexOf('.') !=-1) ) 
	{
  	return false;
	} //end if
	
  if (!checkDateFormat(a))
	{
  	return false;
	} //end if
	
  if ((d<1 || d>31|| isNaN(a.substring(3, 5)) || a.substring(3, 5).indexOf('.') != -1) ) 
	{
	  return false;
	} //end if
	
	//acceptable years range
  if (f<0000 || f>9999 || isNaN(a.substring(6, 10)) || a.substring(6, 10).indexOf('.') !=-1) 
	{
	return false;
	} //end if
	
  if (b==4 || b==6 || b==9 || b==11)
	{
    if (d==31) 
		{
		  return false
		} //end if
  } //end if
	
  if (b == 2)
	{
    var g = parseInt(f/4,10);
    if (isNaN(g)) 
  	{
      return false;
    }
    if (d>29) 
  	{
    	return false
  	} //end if
    if (d==29 && ((f/4)!= parseInt(f/4,10)))
		{
		  return false;
		} //end if
  } //end if
	
	return true;
	
} //end function checkDate 

/*
	following functions will remove spaces
	from a given string
	usage str.trim()
*/

String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() 
{
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() 
{
	return this.replace(/\s+$/,"");
}

/*
	this function checks the date format
	yyyy/mm/dd or yyyy-mm-dd or yyyy.mm.dd
*/

function checkDateFormat(str)
{
  var pattern = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
  return pattern.test(str);
} //end function checkDateFormat

/*
	this function checks US Zip code format
	99999 or 99999-9999
*/

function checkZipCode(str)
{
  var pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
  return pattern.test(str);
} //end function checkZipCode

/*
	this function checks Canadian Postal code format
	Z5Z-5Z5 or Z5Z5Z5
*/

function checkPostalCode(str)
{
  var pattern = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
  return pattern.test(str);
} //end function checkPostalCode

/*
	this function checks time format
	HH:MM or HH:MM:SS or HH:MM:SS.mmm
*/

function checkTimeFormat(str)
{
  var pattern = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;
  return pattern.test(str);
} //end function checkTimeFormat

/*
	this function checks ip address format
	999.999.999.999
*/

function checkIPAddress(str)
{
  var pattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  return pattern.test(str);
} //end function checkIPAddress

/*
	this function checks dollar amount format
	100, 100.00, $100 or $100.00
*/

function checkDollarAmount(str)
{
  var pattern = /^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/;
  return pattern.test(str);
} //end function checkDollarAmount

/*
	this function checks social security number format
	999-99-9999 or 999999999
*/

function checkSocialSecurityNumber(str)
{
  var pattern = /^\d{3}\-?\d{2}\-?\d{4}$/;
  return pattern.test(str);
} //end function checkSocialSecurityNumber

/*
	this function checks social insurance number format
	999999999
*/

function checkSocialInsuranceNumber(str)
{
  var pattern = /^\d{9}$/;
  return pattern.test(str);
} //end function checkSocialInsuranceNumber


/*
	this function checks social insurance number format
	9999999999 or 999-999-9999
*/

function checkPhoneFormat(str) 
{
	var pattern = /^\d{3}(\-)*\d{3}\1\d{4}$/;
	return pattern.test(str);
} //end function checkPhoneFormat 

/*
	this function checks email format
	john@domain.com or john.doe@email.ca
*/

function checkEmailFormat(str)
{
  var pattern = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{2,6})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2,6})*$)/i;
	return pattern.test(str);
} //end function checkEmailFormat 

String.prototype.ucwords = function()
{
  var str_arr = this.split(" ");
	var new_str = "";
	for(var i=0; i<str_arr.length; i++)
	{
	  new_str += str_arr[i].charAt(0).toUpperCase() + str_arr[i].substr(1) + " ";
	} //end for i
	
	return new_str.trim(); 
}; //end prototype

function get_field_name(field)
{
  var tmp_arr = field.getAttribute('name').split("_");
  var field_name = '';
  for(var i=0; i<tmp_arr.length; i++)
  {
    field_name += tmp_arr[i].ucwords() + " ";
  } //end for
	
	return field_name.trim();
} //end function get_field_name 

function check_permission(field, alt_field)
{
	if((field.readOnly || field.disabled) && alt_field != null)
	{
	  alert("PERMISSION DENIED!\n\nYou cannot modify this field.\nIt will be automatically filled by \""+get_field_name(alt_field)+"\"\n\n");
		return false;
	} //end if field is disabled
	
	return true;
} //end function check_permission 

/***************************************************
* this function will check the length of string
***************************************************/

function check_length(field, len) 
{
  if(field != null) {
	  if(field.value.length <= len) {
		  return true;
		} // if length within limit
		else {
		  field.select();
			field.focus();
			alert("Please limit the number of characters to "+len);
			return false;
		} // else too long
	} //if not null
	
	return true;
	
} //end function check_length

/***************************************************
* this function will check if a string is left blank
***************************************************/

function check_text(field) 
{
  
	if(field.value == '') {
		alert("Missing a required field: "+get_field_name(field));
		if(!field.disabled)
		{
	    field.select();
      field.focus();
		} //end if
		return false;
	}
	return true;
} //end function check_text()

/***************************************************
* this function will check if an option is selected or not
***************************************************/

function check_select(field) 
{
  if(field.selectedIndex == 0) {
	  alert("Missing required field");
		field.focus();
		return false;
	}
	
	return true;
} //end function check_select()

/***************************************************
* this function will check the date format: YYYY-MM-DD
***************************************************/

function check_date(dt) 
{
  if(dt.value.search(/\d{4}-\d{2}-\d{2}$/) != 0) {
	  alert("Please enter a valid date: YYYY-MM-DD");
		dt.select();
		dt.focus();
		return false;
	}
	
	return true;
} //end function check_date()

/***************************************************
* this function will check the email format: joe@johnson.com
***************************************************/

function check_email(email) 
{
  //got this string from http://www.codetoad.com/javascript/is_valid_email.asp
	if(!(email.value.indexOf(".") > 2 && email.value.indexOf("@") > 0)) {
	  alert("Please enter a valid email address\n\nExample: joe@johnson.com");
		email.select();
		email.focus();
		return false;
	} //if
	
	return true;
} //end function check_email()

/***************************************************
* this function will check the form required fields
***************************************************/

function check_form(frm) 
{
  return check_text(frm.email_name) &&
				 check_text(frm.password) &&
				 check_text(frm.password2) &&
				 check_text(frm.first_name) &&
				 check_text(frm.last_name);

} //end function check_form()


function check(field, val, numRows) 
{
//alert(numRows, val);
  if(numRows == 1) {
	   if(val == "check all")
        field.checked = true;
  		else
  		  field.checked = false;
	} // if not array
	else {
    for (i = 0; i < field.length; i++) 
		{
  	  if(val == "check all")
        field[i].checked = true;
  		else
  		  field[i].checked = false;
  	} // end for
	} // else its array
  if(val == "check all")
    return "clear all";
  else
    return "check all";
}

function delete_all(list) 
{
  for(i=0; i<list.length; i++) {
		 if(list[i].checked)
		 		window.location = "index.php?action=delete&id=" +list[i].getAttribute("value");
	}
}

function updateList(field) 
{
  window.location = "books.php?category=" + field.options[field.selectedIndex].value;
}

function check_client_type(field)
{
	if(field.form.do_action.value.toLowerCase() == "add")
	{
  	if(field.form.client_type.value.toLowerCase() == "builder")
  	{
  	  update_field(field.form.num_jobs, false, field.form.num_jobs.value);
  		return true;
  	} //end if
  	else
  	{
  	  update_field(field.form.num_jobs, true, "1");
  		alert("PERMISSION DENIED!\n\nThis option is only available for \"Builder\" Clients\n\n");
  		return false;
  	} //else
	} //end if
	else
	{
	  update_field(field.form.num_jobs, true, field.form.num_jobs.value);
	  alert("PERMISSION DENIED!\n\nYou cannot modify this field.\nPlease use \"Add a New Order\" to add more jobs\n\n");
	} //else not adding
} //end function check_client_type 

function update_field(field, read_only, val)
{
  field.readOnly = read_only;
  field.value = val;
	if(read_only)
	{
  	field.blur();
	} //end if read_only
	else
	{
	  field.focus();
		field.select();
	} //else
} //end function update_jobs_field 

function validateOrderForm(frm)
{
	return check_text(frm.client_name) && check_text(frm.num_jobs);
} //end function validateOrderForm 

function validateScheduleForm(frm)
{
	return check_text(frm.installer_name) && check_text(frm.order_info);
} //end function validateOrderForm 

/*****************************************/
//       validatePasswordForm()
/*****************************************/
function validatePasswordForm(frm)
{ 
 // email
 if(frm.email.value == '')
 { var theStr = new String(frm.email.value);
   var index  = theStr.indexOf("@");
   var pindex = theStr.indexOf(".",index);
   
   if(theStr == "")
   { alert("Please enter your Vanwell membership Email Address.      ");
     frm.email.focus();
     return false;
   }
   if(theStr.indexOf("@") <= 0)
   { alert("Please enter valid Email Address.      \n\n"
         + "( yourname@yourdomain.com )      " );
     frm.email.focus();
     return false;
   }
   else if ( !((pindex > index+1) && (theStr.length > pindex+1)) )
   { alert("Please enter valid Email Address.      \n\n"
         + "( yourname@yourdomain.com )      " );
     frm.email.focus();
     return false;
   }
 }

 return true;
}

/*
	var plusImg = new Image();
	var minusImg = new Image();

	plusImg.src = "/images/arrow_box.gif";
	minusImg.src = "/images/arrow_box2.gif";
*/

function showHideSubMenu( menuNum )
{
  var theDiv = document.getElementById( "menu" + menuNum );
  var theImg = document.getElementById( "imgName" + menuNum );
  
  if( theDiv.style.display == "none" )
  {
    theDiv.style.display = "block";
    //theImg.src = minusImg.src;
  }
  else {
    theDiv.style.display = "none";
    //theImg.src = plusImg.src;
  } // end else
} // end showHide Function

function highlight(id) {
  eval(id + ".bgColor = 'C5BD9F'");
}

function unhighlight(id) {
  eval(id + ".bgColor = 'B3A988'");
}


function validateLoginForm(frm)
{ 
  // user_id
  if(frm.user_id.value=='')
  { 
	  alert('Please enter your member email address.      ');
    frm.user_id.focus();
    return false;
  }
  // password
  if(frm.password.value=='')
  { 
	  alert('Please enter Password.      ');
    frm.password.focus();
    return false;
  }
  return true;
}

function updateClientFields(field)
{
  if(field.value == 'individual')
	{
	  
	} //end if individual client
	else
	{
	
	} //else builder
} //end function updateClientFields 

function openMaxWindow(title, url)
{
  sOptions = 'status=yes, menubar=yes, scrollbars=yes, resizable=yes, toolbar=yes, fullscreen=yes';
  sOptions = sOptions + ', width=' + (screen.availWidth - 10).toString();
  sOptions = sOptions + ', height=' + (screen.availHeight - 122).toString();
  sOptions = sOptions + ', screenX=0, screenY=0, left=0, top=0';
  
  win = window.open('', title, sOptions);
  //win = window.open('');
  win.document.location = url;
  return win;
  //win.close();
} // end function openMaxWindow 

function highlight(str, flag) 
{
  var element = document.getElementById(str);
  if(element != null) 
	{
    element.src = "/images/link_" + str + "_" + (flag?"on":"off") + ".jpg";
  } //end if valid element
	
	if(flag)
	{
	  changeSplashTop(str);
	} //end if
	else
	{
	  changeSplashTop("plain");
	} //else
} //end function highlight

function changeSplashTop(src)
{
  var element = document.getElementById("splash_top");
	if(element != null)
	{
	  element.src = "/images/splash_" + src + ".gif";
	} //end if
} //end function changeSplashTop 

 

