var ie4                 = false;
var ie5                 = false;
var ns4                 = false;
var ns6                 = false;
var mac                 = false;
var running             = false;
var timerId             = null;
var delay               = 300;
var currentMenu         = null;
var previousMenu        = null;
var loaded              = false;
var testing             = false;
var allopened           = false;
var homepage            = false;
var dir_images          = 'images/';

function safemail(name,domain,subject,display,css) {
  css       = (css)     ? ' class="' + css + '"' : '';
  subject   = (subject) ? '?subject=' + subject : '';
  displayed = (display) ? display : name + '@' + domain;
  mailto    = name + '@' + domain + subject;
  document.write('<a href="mailto:' + mailto + '"' + css + '>' + displayed + '</a>');
}
function StartTimer(event){running = true; timerId = setTimeout(event,delay);}
function StopTimer(){running = false; clearTimeout(timerId);}
function Popup(title,filename,w,h,scroll,resizable){if (title == ''){ title = 'popup'; }if (scroll == 'scroll'){ scroll = 'yes'; }else{ scroll = 'no'; }if (resizable == 'lock'){ resizable = 'no'; }else{ resizable = 'yes'; }winOptions = eval("'width="+w+",height="+h+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+scroll+",resizable="+resizable+",copyhistory=no'");window.open(filename,title,winOptions);return;}
function SetFocus(fieldname,formname){if (formname == ''){ formname = 'form'; }if (eval("document."+formname+".elements[fieldname].value == ''")){ eval("document."+formname+".elements[fieldname].focus();"); }}
function DisableButton(obj) {
 obj.src = 'images/btn_processing.gif';
 obj.disabled = true;
 obj.style.border='none';
}

function SetElementPosition(id,top,left){
  if (testing) { alert("SetElementPosition\nid = "+id+"\ntop = "+top+"\nleft = "+left); }
  if (ns4) {
    eval('document.'+id).top = top;
    eval('document.'+id).left = left;
  } else if (ns6) {
    document.getElementById(id).style.top = top;
    document.getElementById(id).style.left = left;
  } else {
    eval(id).style.top  = top;
    eval(id).style.left = left;
  }
}
function SetVisibility(id,flag) {
  if (ns4) {
    var str = (flag) ? 'show' : 'hide';
    eval("document."+id).visibility = str;
  } else if (ns6) {
    var str = (flag) ? 'visible' : 'hidden';
    document.getElementById(id).style.visibility = str;
  } else {
    var str = (flag) ? 'visible' : 'hidden';
    eval("document.all."+id).style.visibility = str;
  }
}
function getImageTop(imgID) {
  if (ns4) return eval(imgID).y;
  else return getRealTop(imgID);
}
function getImageLeft(imgID) {
  if (ns4) return eval(imgID).x
  else return getRealLeft(imgID);
}
function getRealTop(imgElem) {
  yPos = eval(imgElem).offsetTop;
  tempEl = eval(imgElem).offsetParent;
  while (tempEl != null) {
    yPos += tempEl.offsetTop;
    tempEl = tempEl.offsetParent;
  }
  return yPos;
}
function getRealLeft(imgObj) {
	xPos = eval(imgObj).offsetLeft;
	tempObj = eval(imgObj).offsetParent;
  while (tempObj != null){
    xPos   += tempObj.offsetLeft;
    tempObj = tempObj.offsetParent;
  }
	return xPos;
}
function getImageWidth(id) {
  if (ie4){
    return eval('document.all.'+id).style.pixelWidth;
  } else if (ns4) {
    return eval('document.'+id).width;
  } else {
    return document.getElementById(id).offsetWidth;
  }
}
function getElementWidth(id) {
  if      (ie4){ return eval('document.all.'+id).offsetWidth; }
  else if (ns4){ return eval('document.'+id).clip.width; }
  else         { return document.getElementById(id).offsetWidth; }
}
function getElementHeight(id) {
  if      (ie4){ return eval('document.all.'+id).offsetHeight; }
  else if (ns4){ return eval('document.'+id).clip.height; }
  else         { return document.getElementById(id).offsetHeight; }
}
function layerWrite(id,text) {
  if (ns4) {
    var lyr = document.layers[id].document;
    lyr.open();
    lyr.write(text);
    lyr.close();
  } else if (ns6) {
    rng = document.createRange();
    el = document.getElementById(id);
    rng.setStartBefore(el);
    htmlFrag = rng.createContextualFragment(text);
    while (el.hasChildNodes()) el.removeChild(el.lastChild);
    el.appendChild(htmlFrag);
  } else if (ie4 || ie5) {
    document.all[id].innerHTML = text;
  }
}
function in_array(needle,haystack) {
  for (i=0; i<haystack.length; i++) {
    if (haystack[i] == needle) { return true; }
  }
  return false;
}
///////////////////////////
///////////////////////////

function Init() {
  SetBrowser();
  if (ie5 || ns6) { LoadMenus(); }
  loaded = true;
}

function SetBrowser() {
  agent = navigator.userAgent.toLowerCase();
  mac   = (agent.indexOf("mac")!=-1);
  ie4   = (document.all && !document.getElementById) ? true : false;
  ie5   = (document.all && document.getElementById)  ? true : false;
  ns4   = (document.layers)                          ? true : false;
  ns6   = (document.getElementById && !document.all) ? true : false;
  if (testing){ alert("agent: "+agent+"\nmac: "+mac+"\nie4: "+ie4+"\nie5: "+ie5+"\nns4: "+ns4+"\nns6: "+ns6+"\n"); }
}

function LoadMenus() {
  for (var i=3; i<=7; i++) {
    navId    = 'nav'+i;
    menuId   = 'menu'+i+'Div';
    shadowId = 'menubg'+i+'Div';
    
    //get anchor
    anchorObj = eval('document.getElementById("'+navId+'")');
    
    //set position
    t = getImageTop(anchorObj);
    l = getImageLeft(anchorObj);
    
    //set top and left
    menuTop = t + 48;
    menuLeft = l + 0;
    
    //one off
    if (i == 8) {
      menuLeft -= 55;
    }
    
    //set position
    SetElementPosition(menuId,menuTop,menuLeft);
    
    //shadow
    menuWidth  = getElementWidth(menuId);
    menuHeight = getElementHeight(menuId);
    if (menuWidth > 1 && menuHeight > 1) {
      var tempstring,writestring;
      tempstring = '<img src="'+dir_images+'shadow.gif" width="'+menuWidth+'" height="'+menuHeight+'" alt="" border="0">';
      writestring =  (!(mac && (ie4 || ie5))) ? '<table cellpadding="0" cellspacing="0" border="0"><tr><td class="transparent">'+tempstring+'</td></tr></table>' : tempstring;
      layerWrite(shadowId,writestring);
      shadowTop  = menuTop + 2;
      shadowLeft = menuLeft + 2; 
      SetElementPosition(shadowId,shadowTop,shadowLeft);
    }
  }
}

function Show(id) {
  if (running) { StopTimer(); }
  currentMenu = id;
  if (currentMenu != previousMenu && previousMenu != null) { Hide(previousMenu); }
  eval('document.getElementById("menu'+id+'Div").style.visibility = "visible"');
  eval('document.getElementById("menubg'+id+'Div").style.visibility = "visible"');
  previousMenu = currentMenu;
}

function Hide(id) {
  if (id == null) { return; }
  eval('document.getElementById("menu'+id+'Div").style.visibility = "hidden"');
  eval('document.getElementById("menubg'+id+'Div").style.visibility = "hidden"');
}

//phone format code
var areacodeLength  = 3;
var firstThree      = 3;
var previousLength  = null;
var thisInput       = null;
var originalLength  = null;
var thisAreacode    = null;
var thisFirstThree  = null;
var thisLastFour    = null;
var phone_test      = false;
var international   = false;
function autoFormat(input,type) {
  //lock out NS4
  if (!document.layers) {
    if (type == 'phone') {
      //var temp_selection = input.selectionStart;
      //alert("selectionStart=" + input.selectionStart);
      var addFirstParen   = false;
      var addSecondParen  = false;
      var addDash         = false;
      thisInput           = input.value.replace(/[. ()-\/]/gi,'');
      //if first input is a "+" assume its an international number and do not format
      if (input.value.length == 1 && input.value == '+') { international = true; return true;}
      else if (input.value.length == 1 && input.value == '(') { previousLength = 1; return true;}
      //dont do anything on backspace
      else if (input.value.length >= previousLength && international == false) {
        thisAreacode    = thisInput.substr(0,3);
        thisFirstThree  = thisInput.substr(3,3);
        thisLastFour    = thisInput.substr(6,4);
        
        //add '('
        if (thisInput.length > 0) { addFirstParen = true; }
        //add ') '
        if (thisAreacode.length == areacodeLength) { addSecondParen = true; }
        //add '-'
        if (thisFirstThree.length == firstThree) { addDash = true; }
        
        //add everything, assign to field
        if (addFirstParen) { thisAreacode = '(' + thisAreacode; }
        if (addSecondParen) { thisAreacode += ') '; }
        if (addDash) { thisFirstThree += '-'; }
        if (phone_test) { alert('writing'); }
        input.value = thisAreacode + thisFirstThree + thisLastFour;
      }
      previousLength = input.value.length
      //if (temp_selection && temp_selection != 'undefined') { input.selectionStart = temp_selection; input.selectionEnd = temp_selection; }
    }
  }
}

function PadDecimals(num, decimal_places) {
  // pad decimal_places?
  if (decimal_places == '0') {
    // return integer part
    return parseInt(num);
  } else {
    // cast as string
    num = num + '';
    
    // get decimal part
    var dec = num.substr((num.indexOf('.')+1));
    
    // if no decimal part, set to 0
    if (num.indexOf('.') == -1) {
      dec = '0';
    }
    
    // pad
    while (dec.length < decimal_places) {
      dec += '0';
    }
    
    // put it all together
    str = parseInt(num) + "." + dec.substr(0, decimal_places);
    
    // return padded number
    return str;
  }
}

function CleanNumber(num) {
  // strip off non digits
  var regex = /[^-.0-9]/g;
  val = new String(num);
  val = val.replace(regex, '');
  return val;
}

function AddCommas(num) {
  num = num + '';
  if (isNaN(num) || num == '') {
    num = 0;
  } else {
    var regex = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
    arrNumber = num.split('.');
    arrNumber[0] += '.';
    do {
      arrNumber[0] = arrNumber[0].replace(regex, '$1,$2');
    } while (regex.test(arrNumber[0]));
    
    if (arrNumber.length > 1) {
      num = arrNumber.join('');
    } else {
      num = arrNumber[0].split('.')[0];
    }
  }
  
  return num;
}

function FormatNumber(num, decimal_places) {
  // only if decimal places
  if (decimal_places > 0) {
    // round number
    num = RoundNumber(num, decimal_places);
    
    // pad to decimal places
    num = PadDecimals(num, decimal_places);
  }
  
  return AddCommas(num);
}

function FormatCurrency(amount) {
	var i = parseFloat(amount);
  if (isNaN(i)) { i = 0.00; }
  
	var minus = '';
	if (i < 0) { minus = '-'; }
  
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
  
	return '$' + AddCommas(s);
}

function ShiftRight(theNumber, k) {
	if (k == 0) {
    return (theNumber);
	} else {
		var k2 = 1;
		var num = k;
		if (num < 0) {
      num = -num;
    }
		for (var i = 1; i <= num; i++) {
			k2 = k2*10;
		}
	}
  
	if (k>0) {
    return(k2*theNumber);
  } else {
    return(theNumber/k2);
  }
}

function RoundSigDig(theNumber, numDigits) {
	with (Math) {
    if (theNumber == 0) {
      return(0);
		} else if(abs(theNumber) < 0.000000000001) {
      return(0);
		} else { // warning: ignores numbers less than 10^(-12)
			var k  = floor(log(abs(theNumber))/log(10))-numDigits;
			var k2 = ShiftRight(round(ShiftRight(abs(theNumber),-k)),k);
			if (theNumber > 0) {
        return(k2);
			} else {
        return(-k2);
      }
	  }
  }
}

function RoundNumber(num, decimal_places) {
  // only if decimal places
  if (decimal_places > 0) {
    num = Math.round(num * Math.pow(10, decimal_places)) / Math.pow(10, decimal_places);
  } else {
    num = Math.round(num);
  }
  
  return (num);
}
