// Code to determine the browser and version.
//----------------------------------------------------------------------------
function Browser() {
  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isOP    = false;  // Opera
  this.isNS    = false;  // Netscape
  this.version = null;

  ua = navigator.userAgent;

  s = "Opera";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isOP = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as Netscape 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }

  s = "MSIE";
  if ((i = ua.indexOf(s))) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
}

function text_numbersonly(myfield, e, dec) {
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
   return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;
// decimal point jump
else if (dec && (keychar == ".")) {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}


function isBlank(val) {
 if (val.length == 0) { return true; }
 for (var i=0; i < val.length; i++) { if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n")) { return false; } }
  return true;
}

function isEmpty(oval) {
 var val=toString(oval);
 if (val.length == 0) { return true; }
 for (var i=0; i < val.length; i++) { if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "0") && (val.charAt(i) != "\n")) { return false; } }
  return true;
}

function redirectPage(page) {
	return false; //for now
}

function percent_format(v) {
  v = (Math.round((v-0)*100))/100;
  v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
  return v+"%";
}


function checkAll2(checkboxes,flag,button) {
	var newValue=true;
    if(flag.value=='true') {
		newValue=true;
        flag.value='false';
        button.value='Uncheck All';
    } else {
		newValue=false;
        flag.value='true';
        button.value='Check All';
    }

	for(var i=0;i<checkboxes.length;i++) { checkboxes[i].checked = newValue; }
	return true;
}

function checkAll(checkboxes,value) {
	var value = true;
	for(var i=0;i<checkboxes.length;i++) { checkboxes[i].checked = value; }
}
function checkemail(str){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)) return true; else return false;
}

function checkurl(str) {
	var filter=/^[http|https]+\:\/\/((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?).*$/i
	if (filter.test(str)) return true; else return false;
}

function checkimage(str) {
	var filter=/\.(gif|jpeg|jpg)$/i
	if (filter.test(str)) return true; else return false;
}

function checklogin(str) {
	var filter=/^[\w-\ ]{4,16}$/i
	if (filter.test(str)) return true; else return false;
}

function checkpassword(str) {
	var filter=/^.{6,32}$/i
	if (filter.test(str)) return true; else return false;
}

function checkdate2(str) {
	var filter=/^\d\d\/\d\d\/\d{2,4}$/
	if (filter.test(str)) return true; else return false;
}

function check_usdate(str) {
  var filter=/^\d{1,2}\/\d{1,2}\/\d{2,4}$/
  if (filter.test(str)) return true; else return false;
}

function compare_dates(date1, date2){
  var arrDate1 = date1.split("/");
  var arrDate2 = date2.split("/");
  var rdate1= new Date(arrDate1[2],arrDate1[0]-1,arrDate1[1]);
  var rdate2= new Date(arrDate2[2],arrDate2[0]-1,arrDate2[1]);
  if ( rdate1 > rdate2) return false; else return true;
}

function compare_dates_strong(date1, date2){
  var arrDate1 = date1.split("/");
  var arrDate2 = date2.split("/");
  var rdate1= new Date(arrDate1[2],arrDate1[0]-1,arrDate1[1]);
  var rdate2= new Date(arrDate2[2],arrDate2[0]-1,arrDate2[1]);
  if ( rdate1 >= rdate2) return false; else return true;
}

function date_tousformat(date) {
  var y=date.getFullYear();
  var m=date.getMonth()+1;
  var d=date.getDate();
  if (m<10) m='0'+m;
  if (d<10) d='0'+d;
  return m+'/'+d+'/'+y;
}

function days_between(date1, date2) {
    var ONE_DAY = 1000 * 60 * 60 * 24;
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();
    var difference_ms = Math.abs(date1_ms - date2_ms);
    return Math.round(difference_ms/ONE_DAY);
}


function checkoccupants(str) {
	var filter=/^\d$/
	if (filter.test(str)) return true; else return false;
}

function checknumber(str) {
	var filter=/^\d+$/
	if (filter.test(str)) return true; else return false;
}

function checkcolor(str) {
	var filter=/^\#[\d\A\B\C\D\E\F\a\b\c\d\e\f]{6}$/
	if (filter.test(str)) return true; else return false;
}

function checkprice(str) {
	var filter=/^\d*(\.\d+)?$/
	if (filter.test(str)) return true; else return false;
}

function openPopup(URL, w, h) {
        var left = parseInt((screen.width - w) / 2);
        var top = parseInt((screen.height - h) / 2);
        var twindow=window.open(URL,'_blank',"buttons=no,directories=no,toolbar=no,location=no,status=no,menubar=no,titlebar=no,scrollbars=yes,resizable=yes,left="+left+",top="+top+",width="+w+",height="+h);
        twindow.focus();
}

function replaceLocation(href) {
    window.open(href,'_self',"",false);
    return;
}

function openPage(file,target) {
    if (target != '')
        target.window.location.href = file;
    else
        window.location.href = file;
}

function up_item(item) {
  with(document.forms['order_form']) {
    item_up.value=item;
    submit();
  }
}

function down_item(item) {
  with(document.forms['order_form']) {
    item_down.value=item;
    submit();
  }
}

function changeCurentPage(page_tag, curl) {
  var page_id=page_tag.options[page_tag.selectedIndex].value;
  eval("parent.location='"+curl+"&page="+page_id+"'");
}

function currency_format(num) {
  num = num.toString().replace(/[^\d\.]/g, '');
  if(isNaN(num)) num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
  num = num.substring(0,num.length-(4*i+3))+','+
  num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function currency_format_full(num) {
	  num = num.toString().replace(/[^\d\.\-]/g, '');
	  if(isNaN(num)) num = "0";
	  sign = (num == (num = Math.abs(num)));
	  num = Math.floor(num*100+0.50000000001);
	  cents = num%100;
	  num = Math.floor(num/100).toString();
	  if(cents<10) cents = "0" + cents;
	  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	  num = num.substring(0,num.length-(4*i+3))+','+
	  num.substring(num.length-(4*i+3));
	  return ( ((sign)?'':'-') + '$' + num + '.' + cents);
}

//tabs part
var RMTpanes = new Array();

function setupPanes(containerId, defaultTabId) {
  // go through the DOM, find each tab-container
  // set up the panes array with named panes
  // find the max height, set tab-panes to that height
  RMTpanes[containerId] = new Array();
  var maxHeight = 0; var maxWidth = 0;
  var container = document.getElementById(containerId);
  var paneContainer = container.getElementsByTagName("div")[0];
  var paneList = paneContainer.childNodes;
  for (var i=0; i < paneList.length; i++ ) {
    var pane = paneList[i];
    if (pane.nodeType != 1) continue;
    if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
    if (pane.offsetWidth  > maxWidth ) maxWidth  = pane.offsetWidth;
    RMTpanes[containerId][pane.id] = pane;
    if ( typeof (pane.style)  != "undefined") pane.style.display = "none";
  }
    paneContainer.style.height = maxHeight + "px";
    paneContainer.style.width  = maxWidth + "px";
    document.getElementById(defaultTabId).onclick();
}

function showPane(paneId, activeTab) {
  // make tab active class
  // hide other panes (siblings)
  // make pane visible

    for (var con in RMTpanes) {
    activeTab.blur();
    activeTab.className = "tab-active";
    if (RMTpanes[con][paneId] != null) { // tab and pane are members of this container
      var pane = document.getElementById(paneId);
      pane.style.display = "block";
      var container = document.getElementById(con);
      var tabs = container.getElementsByTagName("ul")[0];
      var tabList = tabs.getElementsByTagName("a")
      for (var i=0; i<tabList.length; i++ ) {
        var tab = tabList[i];
        if (tab != activeTab) tab.className = "tab-disabled";
      }
      for (var i in RMTpanes[con]) {
        var pane = RMTpanes[con][i];
        if (pane == undefined) continue;
        if (pane.id == paneId) continue;
        if ( typeof (pane.style)  != "undefined") pane.style.display = "none";
      }
    }
  }
  return false;
}

function setObjectClass(object, className) {
  if (object.getAttributeNode("class")) {
    for (var i = 0; i < object.attributes.length; i++) {
      var attrName = object.attributes[i].name.toUpperCase();
      if (attrName == 'CLASS') {
        object.attributes[i].value = className;
      }
    }
  // otherwise create a new attribute
  } else {
    object.setAttribute("class", className);
  }
}

function setCellColor(theCell, thePointerColor)
{
    if (thePointerColor == '' || typeof(theCell.style) == 'undefined') {
           return false;
        }
    theCell.style.backgroundColor = thePointerColor;
    return true;
}

function infowin(URL) {
  var day = new Date();
  var id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=400,left = 0,top = 0');");
}



function table_pager_submit(form_id, page, show_all, form_action) {
 document.getElementById('page').value=page;
 document.getElementById('show_all').value=show_all;
 if ( typeof(form_action) != 'undefined' && form_action != null && form_action != '' ) {
 	document.getElementById(form_id).action=form_action;
 }
 document.getElementById(form_id).submit();
}


//MM menu
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  var value=selObj.options[selObj.selectedIndex].value;
  if (value != 0) {
    eval(targ+".location='"+value+"'");
    if (restore) selObj.selectedIndex=0;
  }
}

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


  function yahoo_fixdialogbug(dlg) {
    if (YAHOO.env.ua.gecko) {
      /* Other part of workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=167801 !!?
      * I have no explanation for why the new thread (setTimeout) is needed, but it is. */
      YAHOO.util.Dom.addClass(dlg.form, "caretfix");

      dlg.showEvent.subscribe(function() {
        YAHOO.util.Dom.setStyle(dlg.form, "display", "none");

        var fixDisplay = function() {
          YAHOO.util.Dom.setStyle(dlg.form, "display", "block");
          try {
            dlg.firstFormElement.focus();
          } catch (e) {
            // Not related to the workaround, I just try/catch focus calls do avoid testing for the various conditions in which they could fail.
          }
        }
        setTimeout(fixDisplay, 0);
      });
    }
  }


 function print_page(url) {
  var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes, scrollbars=yes,width=650, height=600, left=100, top=25";
  var docprint=window.open(url,"",disp_setting);
  docprint.focus();
}

//cc verification
function validate_cc_number( cardNumber ) {
	// LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;

  for( i = 0; i < cardNumber.length; ++i ) {
  	ar[i] = parseInt(cardNumber.charAt(i));
  }

  for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
    ar[i] *= 2; // every second digit starting with the right most (check digit)
    if( ar[i] > 9 ) ar[i]-=9; // will be doubled, and summed with the skipped digits.
  }  // if the double digit is > 9, ADD those individual digits together

  for( i = 0; i < ar.length; ++i ) {
    sum += ar[i]; // if the sum is divisible by 10 mod10 succeeds
  }
  return (((sum%10)==0)?true:false);
}

function collapseBox(boxid) {
	if(document.getElementById(boxid).style.display=='block') document.getElementById(boxid).style.display='none';
	else document.getElementById(boxid).style.display='block';
}

var global_postalcode_count=0;

function PostalCode_UpdateInfo(tag_id) {
	global_postalcode_count++;
	setTimeout("PostalCode_UpdateInfoStep2("+global_postalcode_count+", '"+tag_id+"')", 1200);
}

function PostalCode_UpdateInfoStep2(currCount, tag_id) {
	if (currCount == global_postalcode_count) {
		global_postalcode_count=0;
		var postalcode_tag=document.getElementById(tag_id);
		var country_tag=document.getElementById('country_id');
		if (postalcode_tag != null && typeof(postalcode_tag) != undefined && postalcode_tag.value != ''  && country_tag != null && typeof(country_tag) != undefined ) {
			xajax_ajax_lookup_city_state_by_zipcode(postalcode_tag.value, country_tag.value, 'city', 'state_id');
		} else if ( country_tag != null && typeof(country_tag) != undefined ) {
			xajax_ajax_update_states(country_tag.value);
		}
	}
}

function PostalCode_UpdateInfoComplex(tag_id, strict) {
	global_postalcode_count++;
	setTimeout("PostalCode_UpdateInfoComplexStep2("+global_postalcode_count+", '"+tag_id+"', "+strict+")", 1200);
}

function PostalCode_UpdateInfoComplexStep2(currCount, tag_id, strict) {
	if (currCount == global_postalcode_count) {
		global_postalcode_count=0;
		var radioButtons = document.getElementsByName('country_type_id');
		var country_type_id = 1;
		for (var x = 0; x < radioButtons.length; x ++) {
            if (radioButtons[x].checked) {
                country_type_id = radioButtons[x].value;
            }
        }
		var postalcode_tag=document.getElementById(tag_id);
		var country_tag=document.getElementById('country_id');
		if (postalcode_tag != null && typeof(postalcode_tag) != undefined && postalcode_tag.value != ''  && country_tag != null && typeof(country_tag) != undefined ) {
		    if (strict == false || country_type_id != 3) {
                xajax_ajax_lookup_city_state_by_zipcode(postalcode_tag.value, country_tag.value, 'city', 'state_id');
		    }
		} else if ( country_tag != null && typeof(country_tag) != undefined ) {
			xajax_ajax_update_states(country_tag.value);
		}
	}
}

function CountryType_UpdateInfo() {
    var radioButtons = document.getElementsByName('country_type_id');
    var country_type_id = 1;
    var country_div = document.getElementById('div_country_id');
    var country_tag = document.getElementById('country_id');
    var country_id = 227;
    for (var x = 0; x < radioButtons.length; x ++) {
        if (radioButtons[x].checked) {
            country_type_id = radioButtons[x].value;
        }
    }
    if (country_type_id == 2) {
        country_id = 139;
    }
    if (country_type_id == 1 || country_type_id == 2) {
        country_div.style.display = 'none';
        for (var cj = 0; cj < country_tag.options.length; cj++) {
            if (country_tag.options[cj].value == country_id) {
                country_tag.selectedIndex = cj;
            }
        }
        xajax_ajax_update_states(country_tag.value);
    }

    if (country_type_id == 3) {
        country_div.style.display = '';
        xajax_ajax_update_states(country_tag.value);
    }
}
