var validation_count = new Array(); // used for validating fields.. ie postal code... dont submit if they are invalid

// used in contactForm 
function popup(window_name)
{
  window.open(window_name,'new_window','width=0,height=0,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
}

/**
  * Function : dump()
  * Arguments: The data - array,hash(associative array),object
  *    The level - OPTIONAL
  * Returns  : The textual representation of the array.
  * This function was inspired by the print_r function of PHP.
  * This will accept some data as the argument and return a
  * text that will be a more readable version of the
  * array/hash/object that is given.
*/
function dump(arr,level)
{
  var dumped_text = "";
  if(!level)
  {
    level = 0;
  }
  
  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++)
  {
    level_padding += "    ";
  }
  
  if(typeof(arr) == 'object')
  { //Array/Hashes/Objects
    for(var item in arr)
    {
      var value = arr[item];
   
      if(typeof(value) == 'object')
      { //If it is an array,
        dumped_text += level_padding + "'" + item + "' ...\n";
        dumped_text += dump(value,level+1);
      }
      else
      {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  }
  else
  { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
} 

function getSelect(obj, label)
{
    index = document.forms["main"].elements[label].selectedIndex;
    value = document.forms["main"].elements[label].options[index].value;
    if (value != '') {
        document.getElementById(label).value = value;
        goServ();
    }
}

function goServ()
{
    document.main.submit();
}

function openDiv(divID, divName, moduleCount)
{
  for (i = 0; i < moduleCount; i++) {
    modID = i;    
    if (divName + modID == divID) {
      show_div(divID);      
    }
    else {
      hide_div(divName + modID);
    }
  }
}

function show_div(foo){
  document.getElementById(foo).style.display = "block";
}

function hide_div(foo) {
  document.getElementById(foo).style.display = "none";
}

function time_date (stamp)
{
  if (stamp == 0 || stamp == '')
  {
    return_date = 'N/A';
  }
  else
  {
    var time_date = new Date();
    return_date = new Date (stamp * 1000);
    return_date = date_ddmmyy(return_date)
  }
  return return_date;
}

function date_date (stamp)
{
  if (stamp == 0 || stamp == '')
  {
    return_date = 'N/A';
  }
  else
  {
    var time_date = new Date();
    return_date = new Date (stamp * 1000);
    return_date = date_ddmmyy(return_date)
  }
  return return_date;
}

function date_ddmmyy(stamp)
{
    date = new Date(stamp);
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    
    return "" + (m<10?"0"+m:m) + "/" + (d<10?"0"+d:d) + "/" + (y);
}

function confirm_popup(message)
{
    return window.confirm(message);
}

function disp_alert(message)
{
    return window.alert(message)
}

function add_day(fieldName)
{    
    var date = document.getElementById(fieldName).value;    
    date = Date.parse(date);
    var setDate = new Date(date+(24*60*60*1000));
    document.getElementById(fieldName).value = date_ddmmyy(setDate);
}

function remove_day(fieldName)
{
    var date = document.getElementById(fieldName).value;    
    date = Date.parse(date);
    var setDate = new Date(date-(24*60*60*1000));
    document.getElementById(fieldName).value = date_ddmmyy(setDate);
}

function getOffset(what, offsettype) 
{
  var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
  var parentEl = what.offsetParent;
  
  while (parentEl != null)
  {
    totaloffset=(offsettype == "left")? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
    parentEl = parentEl.offsetParent;
  }
  
  return totaloffset;
}

function autoComplete (field, select, property, forcematch)
{
  var found = false;
  for (var i = 0; i < select.options.length; i++)
  {
    if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) >= 0) {
      found=true;
      break;
    }
  }
  
  if (found) {
    select.selectedIndex = i;
  }
  else
  {
    select.selectedIndex = -1;
  }
  
  if (field.createTextRange)
  {
    if (forcematch && !found)
    {
      field.value = field.value.substring(0,field.value.length-1);
      return;
    }
          
    var cursorKeys = '8;46;37;38;39;40;33;34;35;36;45;';
    if (cursorKeys.indexOf(event.keyCode+";") == -1)
    {
      var r1 = field.createTextRange();
      var oldValue = r1.text;
      var newValue = found ? select.options[i][property] : oldValue;
      if (newValue != field.value)
      {
        field.value = newValue;
        var rNew = field.createTextRange();
        rNew.moveStart('character', oldValue.length);
        rNew.select();
      }
    }
  }
}

function add_option(value, text, index, formName, selectName)
{    
    var select = eval("document.forms[formName]." + selectName);
    select.options[index] = new Option(text, value);
}

function remove_options(selectName)
{
    var select = document.getElementById(selectName);
    var selectLength = select.length;
    for (var i = 0; i < selectLength; i++) {
        select.remove(select[i]);
    }
}
// give it the value in the drop down and the name of drop down
//    and it will select it for you
function set_drop_down(value_to_set_to, selectName)
{
    var select = document.getElementById(selectName);
    var selectLength = select.length;
    for (var i = 0; i < selectLength; i++) {
        if (select.options[i].value == value_to_set_to){
          select.options[i].selected = true;
        }
    }
  
}

function IsNumeric(passedVal)
{
  return /^\d+$/.test(passedVal) ? true : false;;
}

function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function press_enter(funcName)
{
    if (event && event.which == 13)
    {
        eval(funcName);
    }
    else
    {
        return true;
    }
}

function popupWindow(file_name, window_name, window_width, window_height, scrollable)
{
	childWindow = window.open(file_name, window_name,'width='+window_width+',height='+window_height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+scrollable+',copyhistory=yes,resizable=yes');
	childWindow.window.opener = self;
}

function open_google_map(postal)
{
	popupWindow('google_map.php?postal='+postal, 'map', 515, 440);
}

function validate_postal(postal)
{
	if(postal.search(/^[A-Z][0-9][A-Z](\s)?[0-9][A-Z][0-9]$/gi) != -1)
		return true;
		
	return false;
}

function validate_onBlur(node, regex, variable)
{
	if(node.value.search(regex) != -1 || node.value == '')
	{
		node.setAttribute('style', 'border-color: #ccc;');
			eval("validation_count['"+variable+"'] = 0");
		return true;
	}
	else
	{
		node.setAttribute('style', 'border-color: red;');
		eval("validation_count['"+variable+"'] = 1");
		return false;
	}
}

function onSubmit_validate()
{
	var passed = true;
	var error = '';
	
	for(i in validation_count)
	{
		if(validation_count[i] == 1)
		{
			error += 'You have validation errors. Notice the red field(s)\n';
			passed = false;
			break;
		}
	}
	
	if(error != '')
	{
		alert(error);
	}
	
	return passed;
}

function showHideObject(layer_ref) {

  if(layer_ref != ""){
    var current = document.getElementById(layer_ref).style.display;
    
    if(current == "block") {
      state = "none";
    }else {
      state = "block"; 
    }
      
    if (document.all) { //IS IE 4 or 5 (or 6 beta)
      eval( "document.all." + layer_ref + ".style.display = state");
    }
    if (document.layers) { //IS NETSCAPE 4 or below
      document.layers[layer_ref].display = state;
    }
    if (document.getElementById && !document.all) {
      maxwell_smart = document.getElementById(layer_ref);
      maxwell_smart.style.display = state;
    }
  }
  
  
}

function IsNumericFormCheck(input_value){

  if (!IsCurrency(input_value.value)){
    alert("You must enter a numeric value or else you're price may not be saved properly");
    
  }

}

function IsCurrency(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;
         }
      }
   return IsNumber;
   
}

function setObject(object_id, in_value) {
  
  if (object_id != ""){
    document.getElementById(object_id).value = in_value;
  }
  
}

function swapImage(object_id, new_src) {

  if (object_id != ""){
    var obj = document.getElementById(object_id);
		
		if(obj){
			obj.src = new_src;
		}
  }
  
}

function hideReviewInpsectionTabs(activeTab) {

	
	hide_div("div_inspection_details");
	hide_div("inspector_notes_div");
	hide_div("div_report_container");
	hide_div("div_photo_container");
	hide_div("div_message_container");
	
	setInactiveTab('inspection_details_link');
	setInactiveTab('inspector_notes_link');
	setInactiveTab('report_container_link');
	setInactiveTab('photo_container_link');
	//alert(activeTab);
	//activeTab.style.color = 'grey';
	
}

function setInactiveTab(inactiveTab) {
	//document.getElementById(inactiveTab).style.color = 'grey';
}

function toggleInspectionFlag(el, flagId) {
  var flagIcon = $(flagId);
  if (el.checked) {
    flagIcon.className = "inspectionFlagChecked";
    el.value = 1;
  } else {
    flagIcon.className = "inspectionFlag";
    el.value = 0;
  }
}

function reloadReviewInspection() {
	
	
		window.location.reload();		
	
}

function sendFlagEmail(flagId,inspectionId) {
	
	var url = "ajax/ajax_forms.php";
  var pars = "inspection_flag_types_id=" + flagId + "&"
  				 + "inspection_id=" + inspectionId + "&"
  				 + "action=sendFlagEmail";
  var options = { method : "POST",
                  asynchronous : true,
                  parameters : pars,
                  evalScripts : true,
                  onComplete : function() {
                  reloadReviewInspection();	
                  //alert('Email will be sent now');				              	
                  }
                };
  new Ajax.Request(url, options);
	
	
	
}



function addInspectionFlag(flagEl, inspectionId, currentFlags) {
  var flagId = flagEl.value;

  if(flagId=="None"){
  	
  alert("Please Select a flag");
  }else{
  var currentFlags=currentFlags;
  var ifDuplicate=currentFlags.split(',');
  var flag_email_id=1;
  
  for(i=0; i<ifDuplicate.length; i++) {
   	if(ifDuplicate[i]==flagId){
 			var postFlagIndict='false';
 			alert('Flag Already Added');  	 		
  	}
	}
	
	if(postFlagIndict=='false'){
	}else{
	var url = "ajax/ajax_forms.php";
  var pars = "inspection_flag_types_id=" + flagId + "&"
  				 + "inspection_id=" + inspectionId + "&"
  				 + "inspection_flag_email_id=" + flag_email_id + "&" 				 
  				 + "table=inspection_flags" + "&"
  				 + "action=add";
  var options = { method : "POST",
                  asynchronous : true,
                  parameters : pars,
                  evalScripts : true,
                  onComplete : function() {
                  sendFlagEmail(flagId,inspectionId);	
                  
                  
                  
                  							              	
                  }
                };
  new Ajax.Request(url, options);
  
		
	}
	
}
  
}




function deleteInspectionFlag(flagEl, inspectionId) {
  var flagId = flagEl;
	var url = "ajax/ajax_forms.php";
  var pars = "inspection_flag_types_id=" + flagId + "&"
  				 + "inspection_id=" + inspectionId + "&"
  				 + "table=inspection_flags" + "&"
  				 + "action=deleteFlag";
  var options = { method : "POST",
                  asynchronous : true,
                  parameters : pars,
                  evalScripts : true,
                  onComplete : function() {
                  reloadReviewInspection();					              	
                  }
                };
  new Ajax.Request(url, options);
 
  
}


function changeRequestType(inspection_type_id_el, inspectionId) {

  var inspection_type_id = inspection_type_id_el.value;
	var url = "ajax/ajax_forms.php";
  var pars = "inspection_type_id=" + inspection_type_id + "&"
  				 + "inspection_id=" + inspectionId + "&"
  				 + "table=inspection" + "&"
  				 + "action=changeRequestType";
  var options = { method : "POST",
                  asynchronous : true,
                  parameters : pars,
                  evalScripts : true,
                  onComplete : function() {
                  reloadReviewInspection();					              	
                  }
                };
  new Ajax.Request(url, options);
 
  
}




addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

function formatCurrencyNow(o, n, dig, dec){
    new function(c, dig, dec, m){
        addEvent(o, "keypress", function(e, _){
            if((_ = e.key == 45) || e.key > 47 && e.key < 58){
                var o = this, d = 0, n, s, h = o.value.charAt(0) == "-" ? "-" : "",
                    l = (s = (o.value.replace(/^(-?)0+/g, "$1") + String.fromCharCode(e.key)).replace(/\D/g, "")).length;
                m + 1 && (o.maxLength = m + (d = o.value.length - l + 1));
                if(m + 1 && l >= m && !_) return false;
                l <= (n = c) && (s = new Array(n - l + 2).join("0") + s);
                for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += dig);
                n && n < l && (s[l - ++n] += dec);
                _ ? h ? m + 1 && (o.maxLength = m + d) : s[0] = "-" + s[0] : s[0] = h + s[0];
                o.value = s.join("");
            }
            e.key > 30 && e.preventDefault();
        });
    }(!isNaN(n) ? Math.abs(n) : 2, typeof dig != "string" ? "," : dig, typeof dec != "string" ? "." : dec, o.maxLength);
}

function getElementByIdCompatible (the_id) {
if (typeof the_id != 'string') {
return the_id;
}
if (typeof document.getElementById != 'undefined') {
return document.getElementById(the_id);
} else if (typeof document.all != 'undefined') {
return document.all[the_id];
} else if (typeof document.layers != 'undefined') {
return document.layers[the_id];
} else {
return null;
}
}

function fcn(e, numdec) {

			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
	var keynum = -1;
	if(window.event) {// IE
		keynum = e.keyCode;
	} else if(e.which) {// Netscape/Firefox/Opera
		keynum = e.which;
	}
	if( (keynum == 45) || (keynum > 47 && keynum < 58) || keynum == 8 || keynum == 127) {
	    var decimal = '.';
		var dig = ',';
		var signifigance = 0;  // currency would be two decimal places
		var negEntered = (keynum==45);
		//var o = self;
		var o = e.target;
		var d = 0;
		var maxlen = o.maxLength;
		if (maxlen < 0 || maxlen > 1000) maxlen = -1;
		var negative = o.value.charAt(0) == "-" ? "-" : "";
		var s = (o.value.replace(/^(-?)0+/g, "$1")) + String.fromCharCode(keynum);
		s = s.replace(/\D/g, "");
		var len = s.length;
		if (len == 0 || (s+0 == 0) ) negative = "";
		if (maxlen + 1) {
			d = o.value.length - len + 1;
			o.maxLength = maxlen + d;
		}
		/*
		var output = getElementByIdCompatible('test');
		output.innerHTML = 
		    'decimal = '+decimal.toString()+'<br/>'+
			'dig = '+dig.toString()+'<br/>'+
			'signifigance = '+signifigance.toString()+'<br/>'+
			'negEntered = '+negEntered.toString()+'<br/>'+
			'keynum = '+keynum.toString()+'<br/>'+
			'numdec = '+numdec.toString()+'<br/>'+
			'd = '+d.toString()+'<br/>'+
			'maxlen = '+maxlen.toString()+'<br/>'+
			'negative = '+negative.toString()+'<br/>'+
			's = '+s.toString()+'<br/>'+
			'len = '+len.toString()+'<br/>';
			*/
		
		
		
		if(maxlen + 1 && len >= maxlen && !negative) return false;
		
		len <= (signifigance = numdec) && (s = new Array(signifigance - len + 2).join("0") + s);
		
		for(var i = (len = (s = s.split("")).length) - signifigance; (i -= 3) > 0; s[i - 1] += dig);
		
		signifigance && signifigance < len && (s[len - ++signifigance] += decimal);
		
		negEntered ? (negative ? maxlen + 1 && (o.maxLength = maxlen + d) : s[0] = "-" + s[0]) : s[0] = negative + s[0];
		
		o.value = s.join("");
	}
	keynum > 31 && e.preventDefault();
	//keynum > 30 && e.returnValue = false;
}	

