
var errors = new Array();

function addFormEvents() {
    var focusclass = 'highlighted';
    var idprefixlen = 8; 
    if(!document.createElement || !document.getElementsByTagName || !document.getElementById) 
	return false; 
   
    var lies = document.getElementsByTagName('li');
    var howManyLies = lies.length;

    for (i=0; i < howManyLies; i++) {
	var id = lies[i].id;
	if (id.length > idprefixlen && id.substring(0,idprefixlen) == "section_" ) {
	    addEvent(lies[i],'focus', function(){ addClass(this,focusclass); });
	    addEvent(lies[i],'focusin', function(){ addClass(this,focusclass); });
	    addEvent(lies[i],'blur', function(){ removeClass(this,focusclass); });
	    addEvent(lies[i],'focusout', function(){ removeClass(this,focusclass); });
	}
    }


}

function frmreset(){
    document.getElementById('btnsubmit').disabled = true;
    var errdivs = document.getElementsByTagName('span');
    for (i=0; i < errdivs.length; i++) {
	var errspan = errdivs[i];
	if (errspan.id.length > 6 && errspan.id.substring(0,6) == "error_")
	    errspan.innerHTML = '';
    }
    if (document.getElementById('divordertot') != null) {
	document.getElementById('divordertot').innerHTML = "<b>Total for this Order</b><br><div id=\"lineitems\"></div>Sub-total: $<div style=\"display: inline; vertical-align: bottom;\" id=\"subtotal\">0.00</div><br>GST: $<div style=\"display: inline; vertical-align: bottom;\" id=\"gst\">0.00</div><br>Ontario PST: $<div style=\"display: inline; vertical-align: bottom;\" id=\"on_rst\">0.00</div><br><b>Total due today: $</b><div style=\"display: inline; vertical-align: bottom; font-weight: bold;\" id=\"total\">0.00</div><br><br>";
	showDiv('divordertot');
    }
    window.scroll(0,0);
    fullvalidate();

}

function addError(whichField,parentId){
    errors[whichField] = parentId;
    document.getElementById('btnsubmit').disabled = true;
    if (document.getElementById('divordertot') != null)
	hideDiv('divordertot');		    
}

function removeError(whichField,parentId){
    errors[whichField] = "";
    var i;
    var noMoreErrors = true; // for this section
    var errCount = 0;
    for (i in errors) {
	if (errors[i] == parentId) noMoreErrors = false;
	if (errors[i] != "") errCount++;
    }
    if (errCount == 0) {
	document.getElementById('btnsubmit').disabled = false;
	if (document.getElementById('divordertot') != null)
	    showDiv('divordertot');
    }
    if (noMoreErrors)
	return true;
    return false;
}

function frmvalidate(whichField){
  var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }
    var f = document.getElementById(whichField);
    var frmid = document.getElementById('frmid');
    var url = "/COR?type=3&frmid=" + frmid.value;
    if (whichField.substring(0,3) == "mf_") 
	url += "&field=" + whichField.substring(3,whichField.lastIndexOf("_"));
    else url += "&field=" + whichField
    var value="";
    if (f.type == "text" || f.type == "radio")
	value = f.value;
    else if (f.type == "select-one")
	value = f.options[f.selectedIndex].value;
    else return;
    // similarly for checked/unchecked and/or selectedIndex
    url += "&value=" + escape(value);
    
    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {	
		var xmlRes = xmlHttp.responseXML.documentElement;
		var xmlFields = xmlRes.getElementsByTagName('field');
		for(i=0; i < xmlFields.length; i++) {
		    var Id = getXMLVal(xmlFields[i],'Id');
		    if (Id == whichField.substring(3,whichField.lastIndexOf("_")))
			Id = "mf_" + Id + "_" + whichField.substring(whichField.lastIndexOf("_")+1);
		    var Valid = getXMLVal(xmlFields[i],'Valid');
		    var elem = document.getElementById(Id);
		    if (Id == null || Valid == null || elem == null) return;		    
		    var parent = elem.parentNode;
		    while(parent != null && parent.tagName.toUpperCase() != "LI")
			parent = parent.parentNode;
		    var errdiv, lbl;
		    if (parent != null && parent.tagName.toUpperCase() == "LI" && parent.id.substr(0,8) == "section_") {
			errdiv = document.getElementById('error_' + parent.id.substr(8));
			lbl = document.getElementById('label_' + parent.id.substr(8));
		    }
		    if (Valid == "false") {
			addError(Id,parent.id);
			if (errdiv) {
			    if (lbl) errdiv.innerHTML = ' &nbsp; &nbsp; Invalid ' + lbl.innerHTML;
			}
		    }
		    else {
			if(removeError(Id,parent.id)) {
			    if (errdiv) errdiv.innerHTML = '';
			}
			
			    var Price = getXMLVal(xmlFields[i],'Price');
			    var PriceLabel = getXMLVal(xmlFields[i],'PriceLabel');
			    var TaxClass = getXMLVal(xmlFields[i],'TaxClass');
			    if (Price == null || PriceLabel == null || TaxClass == null) return true;
			    Price = parseFloat(Price);
			    var lineitems = document.getElementById('lineitems');
			    var subtotal = document.getElementById('subtotal');
			    var gst = document.getElementById('gst');
			    var on_rst = document.getElementById('on_rst');
			    var total = document.getElementById('total');
			    if (lineitems == null || subtotal == null || gst == null || on_rst == null || total == null) return;
			    if (!on_rst.innerHTML.match(/^[0-9.]{1,6}$/) || !gst.innerHTML.match(/^[0-9.]{1,6}$/) || !subtotal.innerHTML.match(/^[0-9.]{1,6}$/) || !total.innerHTML.match(/^[0-9.]{1,6}$/)) return;
			    if (Id.substring(0,3) == "mf_") 
				Id = Id.substring(3,Id.lastIndexOf("_"));
			    var currItem = document.getElementById('lineitem_' + Id);
			    if (currItem != null) {
				// get its current price
				var currPrice = currItem.innerHTML.substring(currItem.innerHTML.indexOf("$")+1);
				if (!currPrice.match(/^[0-9.]{1,6}$/))
				    return;

				// assume taxclass is same
				// calculate tax based on current price and taxclass
				var currTax = 0;
				if (TaxClass == "ON_RST") {
				    // subtract from ON_RST
				    currTax = currPrice * 0.08;
				    if (compCurrency(on_rst.innerHTML,currTax,true))
					on_rst.innerHTML = calcCurrency(on_rst.innerHTML,currTax,true);
				    else return;
				}
				
				// substract from GST
				var currGST = currPrice * 0.06;
				if (compCurrency(gst.innerHTML,currGST,true))
				    gst.innerHTML = calcCurrency(gst.innerHTML,currGST,true);
				else return;

				// subtract from subtotal
				if (compCurrency(subtotal.innerHTML,currPrice,true))
				    subtotal.innerHTML = calcCurrency(subtotal.innerHTML,currPrice,true);
				
				// subtract from total
				var currTotal = parseFloat(currPrice) + parseFloat(currTax) + parseFloat(currGST)
				if (compCurrency(total.innerHTML,currTotal,true))
				    total.innerHTML = calcCurrency(total.innerHTML,currTotal,true);

				// remove the item from lineitems
				lineitems.removeChild(currItem);
			    }

			    var newItem = document.createElement('div');

			    // insert into lineitems
			    lineitems.insertBefore(newItem,null);
			    newItem.id = "lineitem_" + Id;
			    newItem.innerHTML = "- " + PriceLabel + " $" + Price;

			    // add to subtotal
			    if (compCurrency(subtotal.innerHTML,Price,false))
				subtotal.innerHTML = calcCurrency(subtotal.innerHTML,Price,false);

			    // calculate tax based on current price and taxclass
			    var currTax = 0;
			    if (TaxClass == "ON_RST") {
				// add to ON_RST
				currTax = Price * 0.08;
				if (compCurrency(on_rst.innerHTML,currTax,false))
				    on_rst.innerHTML = calcCurrency(on_rst.innerHTML,currTax,false);
				else return;
			    }

			    // calculate GST
			    var currGST = Price * 0.06;
			    if (compCurrency(gst.innerHTML,currGST,false))
				gst.innerHTML = calcCurrency(gst.innerHTML,currGST,false);
			    else return;

			    // update total
			    var currTotal = parseFloat(Price) + parseFloat(currTax) + parseFloat(currGST)
			    if (compCurrency(total.innerHTML,currTotal,false))
				total.innerHTML = calcCurrency(total.innerHTML,currTotal,false);
			    return true;
		    }
		}
        }
      }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function getXMLVal(xmlField,tagname){
    if(xmlField == null)
	return null;
    if(xmlField.getElementsByTagName(tagname)[0] != null) {
	if(xmlField.getElementsByTagName(tagname)[0].childNodes[0] != null)
	    return xmlField.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
	else return '';
    }
    else return null;
}

/*
    fullvalidate will receive the usual XML response and produce the usual error messages

*/
function fullvalidate(doSubmit){
  var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }

    if (!doSubmit) {
	var initprice = new Array("mf_profinstall_N","ipblock","filters","mf_modem_NONE","svc_type");
	var i;
	for (i in initprice) {
	    var vf = document.getElementById(initprice[i]);
	    if (vf != null) frmvalidate(initprice[i]);
	}
    }
    else {
	var required = new Array("bill_name_first","bill_name_last","bill_name_company","svc_nxx","svc_lineno","svc_name_first","svc_name_last","svc_name_company","svc_street_num","svc_street_name","svc_municipality","svc_postalcode");
	var i;
	for (i in required) {
	    var vf = document.getElementById(required[i]);
	    if (vf != null && vf.value.length == 0) {
		alert('Please fill in all required fields!'); 
		vf.focus();
		return;
	    }
	}
	var bill_email = document.getElementById('bill_email');
	var bill_nxx = document.getElementById('bill_nxx');
	var bill_lineno = document.getElementById('bill_lineno');
	if (bill_email != null && bill_nxx != null && bill_lineno != null) { // both exist, either required
	    if (bill_email.value.length == 0 && (bill_nxx.value.length != 3 || bill_lineno.value.length != 4)) {
		alert('A valid contact telephone or e-mail address must be specified!');
		return false;
	    }
	}
	var terms = document.getElementById('terms');
	if (terms != null && !terms.checked) {
		alert('You must agree to the Terms and Conditions of Service and Internet Use Policy!');
		terms.focus();
		return false;
	}
	document.getElementById('orderfrm').submit();   
    }
}


function addEvent( obj, type, fn )
{
    if (obj.addEventListener)
	obj.addEventListener( type, fn, true );
    else if (obj.attachEvent)
    {
	obj["e"+type+fn] = fn;
	obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
	obj.attachEvent( "on"+type, obj[type+fn] );
    }
}

function removeEvent( obj, type, fn )
{
    if (obj.removeEventListener)
	obj.removeEventListener( type, fn, false );
    else if (obj.detachEvent)
    {
	obj.detachEvent( "on"+type, obj[type+fn] );
	obj[type+fn] = null;
	obj["e"+type+fn] = null;
    }
}

// hasClass, addClass and removeClass written by Chris Sullins

function hasClass( element, className ) {
    return element.className.match( '\\b' + className + '\\b' );
}

function addClass( element, className ) {
    if( !element.className.match( '/\\b' + className + '\\b/' ) ) 
        element.className += ' ' + className;
}

function removeClass( element, className ) {
    element.className = element.className.replace( new RegExp( '\\b' + className + '\\b', 'g' ), '' );
}

function compCurrency(onpage,inscript,subtract) {
    if (subtract && (parseFloat(onpage) - parseFloat(inscript)).toFixed(2) >= 0)
	return true;
    else if (!subtract && (parseFloat(onpage) + parseFloat(inscript)).toFixed(2) >= 0)
	return true;
    else return false;
}

function calcCurrency(onpage,inscript,subtract) {
    if (subtract)
	return (parseFloat(onpage) - parseFloat(inscript)).toFixed(2);
    else return (parseFloat(onpage) + parseFloat(inscript)).toFixed(2);
}


/*function move_dslcheck2(e,prefix){
    if (e.keyCode == 13)
	return;
    var nxx = document.getElementById(prefix + '_nxx');
    var lineno = document.getElementById(prefix + '_lineno');
    if (nxx.value.length == 3) {
	lineno.select();
	lineno.focus();
	return;
    }
}*/
