// JavaScript Document

var ROOT_URL = 'http://' + document.domain + '/';

var holder = null;
var bLoaded = false;

function createRequestObject() {
	var req_object;  // the variable to hold the object
	var browser = navigator.appName;
	if (browser == "Microsoft Internet Explorer") {
		req_object = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else {
		req_object = new XMLHttpRequest();
	}
	return req_object;
}

// this is what sets up AJAX calls
var http = createRequestObject();

/////////////////
// Cookie AJAX //
/////////////////
function clearCookies() {
	var val = confirm("Are you sure you want to change your location and start over?  This will clear all products from your order as well.");
	if (val){
		http.open('post', ROOT_URL+'data/reset.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleReset;
		http.send();
	}
}

function handleReset() {
	if (http.readyState == 4) {
		window.location = ROOT_URL+'serviceable/';
	}
}
///////////////// -- Cookie AJAX


//////////////////////////////
// Contact Information AJAX //
//////////////////////////////
function getContactInfo() {
	var index = document.getElementById('slcContact').selectedIndex;
	var val = document.getElementById('slcContact').options[index].value;
	http.open('post', ROOT_URL+'data/getContacts.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handleContact;
	http.send('dId=' + val);
}

function handleContact() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('contactInformation').innerHTML = res;
		document.getElementById('contactForm').style.display = 'none';
	}
}
////////////////////////////// -- Contact Information AJAX


/////////////////////////
// Serviceability AJAX //
/////////////////////////
function getServiceable() {
	var adr = document.getElementById('txtAddress').value;
	var zip = document.getElementById('txtZip').value;
	if (adr.length > 3 && zip.length >= 5) {
		http.open('post', ROOT_URL+'data/serviceable.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleAddresses;
		http.send('address=' + adr + '&zip=' + zip);
	}
	else {
		alert("Please fill in the address and zip code fields!");
		document.getElementById('txtAddress').focus();
	}
}

function handleAddresses() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('adrRes').innerHTML = res;
		if (document.getElementById('addressResults').style.display == 'none') {
			document.getElementById('addressResults').style.display = 'block';
		}
	}
}

function verifyServiceable() {
	var index = document.getElementById('slcServiceableResults').selectedIndex;
	var val = document.getElementById('slcServiceableResults').options[index].value;
	if (val != '-1') {
		http.open('post', ROOT_URL+'data/setLocation.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleVerify;
		http.send('hse=' + val);
	}
	else {
		alert("We're sorry but that address is not serviceable. Please check that your information is correct.");
	}
}

function handleVerify() {
	if (http.readyState == 4) {
		var res = http.responseText;
		alert("Contratulations! Your address is serviceable!");
		window.location = "../get_service/services.php";
	}
}
///////////////////////// -- Serviceability AJAX


//////////////////
// Locator AJAX //
//////////////////
function getNeighborhoods() {
	var zip = document.getElementById('txtZip').value;
	http.open('post', ROOT_URL+'data/locator.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handleNeighborhoods;
	http.send('zip=' + zip);
}

function handleNeighborhoods() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('nbrResults').innerHTML = res;
		document.getElementById('neighborhoodResults').style.display = 'block';
	}
}

function verifyNeighborhood(type) {
	var index = document.getElementById('slcNeighborhoods').selectedIndex;
	var tmp = document.getElementById('slcNeighborhoods').options[index].value;
	if (tmp == "-1") {
		alert("We're sorry but that is not a serviceable location!");
	}
	else {
		var vals = tmp.split(";");
		var zip = vals[0];
		var nbr = vals[1];
		
		http.open('post', ROOT_URL+'data/setLocation.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		switch (type) {
			case 'GS':
				http.onreadystatechange = handleVerifyNeighborhoodS;
				break;
			case 'CL':
				http.onreadystatechange = handleVerifyNeighborhoodC;
				break;
		}
		http.send('zip=' + zip + '&nbr=' + nbr);
	}
}

function handleVerifyNeighborhoodS() {
	if (http.readyState == 4) {
		var res = http.responseText;
		var fwd = document.getElementById('hidForward').value;
		if (fwd == '') {
			window.location = ROOT_URL + 'get_service/services.php';
		}
		else {
			window.location = fwd;
		}
	}
}

function handleVerifyNeighborhoodC() {
	if (http.readyState == 4) {
		var res = http.responseText;
		window.location = ROOT_URL + 'channel_lineups/lineups.php';
	}
}
////////////////// -- Locator AJAX


///////////////////
// Products AJAX //
///////////////////
function getProducts(type, callback) {
	document.getElementById('legal_IP').style.display = 'none';
	document.getElementById('legal_TP').style.display = 'none';
	document.getElementById('legal_CP').style.display = 'none';
	var tmp = document.getElementById('spa').value;
	var vals = tmp.split(";");
	var sys = vals[0];
	var prin = vals[1];
	var agent = vals[2];
	document.getElementById('type').value = type;
  document.getElementById('mandAddonsBox').style.display = 'none';
	document.getElementById('addonsBox').style.display = 'none';
  var sPath = pathBuilder('data/products.php','type=' + type + '&sys=' + sys + '&prin=' + prin + '&agent=' + agent);
  
  //If called from EOS, cat on the product that was selected previously
  if (document.getElementById("EOSCalculator")) {
    if (document.getElementById(type).value.length > 0) {
      sValue = document.getElementById(type).value;
      sPath = sPath + "&sValue=" + sValue;
    }   
  } 

  http.open('get', sPath);
	http.setRequestHeader('Content-Type', 'text/xml');
  if (document.getElementById("EOSCalculator")){
    http.onreadystatechange = oServiceCalculator.getProductsCallback; 
  } else {
    http.onreadystatechange = handleProducts;
  }

	http.send(null);
	document.getElementById('legal_'+type).style.display = 'block';
}

//Determines appropriate question marks and & for a path.
//This is for location spoofing in EOS.
function pathBuilder(sPage, sPath) {
  //If root url contains a questionmark.
  if (ROOT_URL.indexOf('?') > 0){
    return ROOT_URL+sPage+"&"+sPath;
  } else {
    return ROOT_URL+sPage+"?"+sPath;
  }
}

function handleProducts() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('products').innerHTML = res;
	}
}

function dropProduct(type) {
	var ans = confirm("Are you sure you want to delete this product?");
	if (ans) {
		http.open('post', ROOT_URL+'data/dropProducts.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleDropProducts;
		http.send('type=' + type);
	}
}

function handleDropProducts() {
	if (http.readyState == 4) {
		var res = http.responseText;
		window.location.reload();
	}
}
/////////////////// -- Products AJAX


/////////////////
// Addons AJAX //
/////////////////
function getAddons(elem) {
	var prod = elem.value;
	var type = document.getElementById('type').value;
	var tmp = document.getElementById('spa').value;
	var vals = tmp.split(";");
	var sys = vals[0];
	var prin = vals[1];
	var agent = vals[2];
  var sPath = pathBuilder('data/addons.php','prod=' + prod + '&sys=' + sys + '&prin=' + prin + '&agent=' + agent + '&type=' + type);
	
  //If called from EOS, cat on the product that was selected previously
  if (document.getElementById("EOSCalculator")) {
    if (document.getElementById(type).value.length > 0) {
      sValue = eval(type+"_addons").value;
      sPath = sPath + "&sValue=" + sValue;
    }   
  } 
  
  http.open('get', sPath);
	http.setRequestHeader('Content-Type', 'text/xml');
  http.onreadystatechange = handleAddons;
	http.send(null);
}

function handleAddons() {
	if (http.readyState == 4){
		var res = http.responseText;
		document.getElementById('addons').innerHTML = res;
		// sethtml('addons', res);
		document.getElementById('addonsBox').style.display = 'block';

    //Resize for EOS.
    if (document.getElementById("EOSCalculator")) {
      if (document.getElementById('addons')){
        document.getElementById('tableAddons').width = '100%';
      }
      verifyAdd();
    }
	}
}

function getMandatoryAddons(elem) {
	holder = elem; // holder is a global variable that holds the element to pass for the callback var
	var prod = elem.value;
	var type = document.getElementById('type').value;
	var tmp = document.getElementById('spa').value;
	var vals = tmp.split(";");
	var sys = vals[0];
	var prin = vals[1];
	var agent = vals[2];

	document.getElementById('mandAddons').innerHTML = '';
	document.getElementById('mandAddonsBox').style.display = 'none';
	
	var sPath = pathBuilder('data/mandAddons.php','prod=' + prod + '&sys=' + sys + '&prin=' + prin + '&agent=' + agent + '&type=' + type);
	http.open('get', sPath);
	http.setRequestHeader('Content-Type', 'text/xml');
	http.onreadystatechange = handleMandatoryAddons;
	http.send(null);
}

function handleMandatoryAddons() {
	if (http.readyState == 4){
		var res = http.responseText;

		if (trim(res) != "none") {
			document.getElementById('mandAddons').innerHTML = res;
			// sethtml('addons', res);
			document.getElementById('mandAddonsBox').style.display = 'block';
		}

    //Resize for EOS.
    if (document.getElementById("EOSCalculator") && trim(res) != "none") {
      if (document.getElementById('mandAddons')){
        document.getElementById('tableMandAddons').width = '100%';
      }
      verifyAdd();
    }
		http = createRequestObject(); // redefining the request object to eliminate infinite loop in firefox
		getAddons(holder); // holder is a global variable that holds the element to pass for the callback var
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
///////////////// -- Addons AJAX


////////////////////
// Selection AJAX //
////////////////////
function addProduct(radios, mandRadios) {
	var x=0;
	var addons = '';
	var elems = document.getElementsByTagName("input");
	for (var i=0; i<elems.length; i++) {
		if (elems[i].type == "checkbox" && elems[i].checked) {
			if (addons != ''){
				addons += ";";
			}
			addons += elems[i].value;
		}
	}
	// getRadioValue is in the controls.js file
	var prod = getRadioValue(radios);
	if (typeof(mandRadios) != '' && typeof(mandRadios) != 'undefined') {
		var mandAdds = getRadioValue(mandRadios);
		var mandEncoded = '&mandAdds=' + mandAdds;
	}
	else {
		var mandEncoded = '';
	}
	var type = document.getElementById('type').value

	http.open('post', ROOT_URL+'data/setProducts.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handleProductAdd;
	http.send('prod=' + prod + '&type=' + type + '&adds=' + addons + mandEncoded);
}


function addEOSProduct(radios) {
	var x=0;
	var addons = '';
  var mandRadios = '';
  if (document.getElementsByName("rbMandAdd").length > 0) {
    mandRadios = document.getElementsByName("rbMandAdd");
  }
	var elems = document.getElementsByTagName("input");
	for (var i=0; i<elems.length; i++) {
		if (elems[i].type == "checkbox" && elems[i].checked) {
			if (addons != ''){
				addons += ";";
			}
			addons += elems[i].value;
		}
	}
	
	// getRadioValue is in the controls.js file
	var prod = getRadioValue(radios);
	var type = document.getElementById('type').value

  eval(type).value = prod;
	if (typeof(mandRadios) != '' && typeof(mandRadios) != 'undefined' && document.getElementsByName("rbMandAdd").length > 0) {
    eval(type+"_mandAddons").value = getRadioValue(mandRadios);
	} else {
    eval(type+"_mandAddons").value = '';
  }

  if (addons.length > 0) {
    eval(type+"_addons").value = addons + ";" + eval(type+"_mandAddons").value;
  } else {
    eval(type+"_addons").value = eval(type+"_mandAddons").value;
  }

  //alert(eval(type+"_addons").value);

  oServiceCalculator.getOrder();
}

function verifyAdd() {
  if (document.getElementById("EOSCalculator")) {
    addEOSProduct(document.frmGetService.product);
  }  
}

function handleProductAdd() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('notice').innerHTML = res;
		document.getElementById('notice').style.display = 'block';
		document.getElementById('notice').focus();
		//document.getElementById('orderButton').style.color = '#ED8E00';
		
		var t = setTimeout("document.getElementById('notice').style.display = 'none'", 6000);
		window.scroll(0,0);
		var textColorTween1 = new ColorTween(document.getElementById('orderButton').style, "color", Tween.regularEaseIn, 'FFFFFF', 'ED8E00', 2);
		textColorTween1.start();
		var colorTween = new ColorTween(document.getElementById('notice').style, "backgroundColor", Tween.bounceEaseOut, 'FFFFFF', 'FBE69B', 3);
		colorTween.start();

	}
}
//////////////////// -- Selection AJAX


/////////////////////////////////////
// Order Address Verification AJAX //
/////////////////////////////////////
function getAddresses() {
	if (document.getElementById('txtName').value.length < 4) {
		alert('Please enter your full name');
		document.getElementById('txtName').focus();
	}
	else if (document.getElementById('txtAddress').value.length < 4) {
		alert('Please enter your complete street address');
		document.getElementById('txtAddress').focus();
	}
	else if (document.getElementById('txtPhone').value.length < 12) {
		alert('Please enter your phone number in this format (000-000-0000)');
		document.getElementById('txtPhone').value = '';
		document.getElementById('txtPhone').focus();
	}
	else {
		var address = document.getElementById('txtAddress').value;
		var zip = document.getElementById('txtZip').value;
		var phone = document.getElementById('txtPhone').value;
		http.open('post', ROOT_URL+'data/getAddresses.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleAddresses;
		http.send('address=' + address + '&zip=' + zip + '&phone=' + phone);
	}
}

function verifyAddress() {
	var index = document.getElementById('slcAddress').selectedIndex;
	var hse = document.getElementById('slcAddress').options[index].value;
	var name = document.getElementById('txtName').value;
	var phone = document.getElementById('txtPhone').value;
	var email = document.getElementById('txtEmail').value;
	if (hse != '-1'){
		http.open('post', ROOT_URL+'data/setLocation.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = handleAddressVerify;
		http.send('hse=' + hse + '&name=' + name + '&phone=' + phone + '&email=' + email);
	}
	else {
		alert("We're sorry but that address appears to be unserviceable.  Please check to ensure that you have correctly entered your address information.");
	}
}

function handleAddressVerify() {
	if (http.readyState == 4) {
		var res = http.responseText;
		//alert(res);
		window.location = ROOT_URL+'get_service/order-confirm.php';
    //window.location = ROOT_URL+'get_service/order-customerinfo.php';
	}
}
///////////////////////////////////// -- Order Address Verification AJAX


////////////////////////
// Press Release AJAX //
////////////////////////
function getPressReleases() {
	var index1 = document.getElementById('slcYear').selectedIndex;
	var year = document.getElementById('slcYear').options[index1].value;
	var index2 = document.getElementById('slcQuarter').selectedIndex;
	var quarter = document.getElementById('slcQuarter').options[index2].value;
	var sendText = '';
	if (year != '-1') {
		sendText += 'year=' + year;
		var flag = 1;
	}
	if (quarter != '-1') {
		if (flag == 1) {
			sendText += '&';
		}
		sendText += 'quarter=' + quarter;
	}
	
	http.open('post', ROOT_URL+'data/getPressReleases.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handlePressReleases;
	http.send(sendText);
}

function handlePressReleases() {
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('pressReleaseRes').innerHTML = res;
	}
}
//////////////////////// -- Press Release AJAX


////////////////////////////
// Contact Messaging AJAX //
////////////////////////////
function sendMessage() {
	var index = document.getElementById('slcIssue').selectedIndex;
	var issue = document.getElementById('slcIssue').options[index].value;
	var name = document.getElementById('txtName').value;
	var mailId = document.getElementById('dId').value;
	var address = document.getElementById('txtAddress').value;
	var city = document.getElementById('txtCity').value;
	var state = document.getElementById('txtState').value;
	var zip = document.getElementById('txtZip').value;
	var phone = document.getElementById('txtPhone').value;
	var email = document.getElementById('txtEmail').value;
	var accnt = document.getElementById('txtAccount').value;
	var comments = document.getElementById('txaComments').value;
	var ip = document.getElementById('hidIp').value;
	
	var sendText = "to=" + mailId;
	sendText += "&name=" + name;
	sendText += "&address=" + address;
	sendText += "&city=" + city;
	sendText += "&state=" + state;
	sendText += "&zip=" + zip;
	sendText += "&email=" + email;
	sendText += "&phone=" + phone;
	sendText += "&account=" + accnt;
	sendText += "&issue=" + issue;
	sendText += "&comments=" + comments;
	sendText += "&ip=" + ip;
	
	http.open('post', ROOT_URL+'data/sendMessage.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handleMessageReturn;
	http.send(sendText);
}

function handleMessageReturn() {
	if (http.readyState == 4) {
		var res = http.responseText;
		alert(res);
		document.getElementById('contactForm').style.display = 'none';
	}
}
//////////////////////////// -- Contact Messaging AJAX


/////////////////////////
// Location Reset AJAX //
/////////////////////////
function resetLocation(type) {
	var choice = confirm("Are you sure you want to change your location?");
	
	if (choice) {
		var val = 1;
		http.open('post', ROOT_URL+'data/dropLocation.php');
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		switch (type){
			case 'GS':
				http.onreadystatechange = handleLocationChangeGS;
				break;
			case 'CL':
				http.onreadystatechange = handleLocationChangeCL;
				break;
		}
		http.send("val=" + val);
	}
}

function handleLocationChangeGS() {
	if (http.readyState == 4) {
		window.location = ROOT_URL+'get_service/';
	}
}

function handleLocationChangeCL() {
	if (http.readyState == 4) {
		window.location = ROOT_URL+'channel_lineups/';
	}
}
///////////////////////// -- Location Reset AJAX


/////////////////////////
//  Long-Distance AJAX //
/////////////////////////
function getPhoneRates(type) {
	http.open('post', ROOT_URL+'data/getPhoneRates.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handlePhoneRates;
	http.send("rtype=" + type);
}

function handlePhoneRates() {
	if (http.readyState == 1) {
		document.getElementById('indicator').style.display = 'block';
	}
	if (http.readyState == 4) {
		var res = http.responseText;
		document.getElementById('phoneRates').innerHTML = res;
		document.getElementById('indicator').style.display = 'none';
	}
}
///////////////////////// -- Long-Distance AJAX


/////////////////////////////////
//  Customer Information AJAX  //
/////////////////////////////////
function setCustomerInformation() {
	var isBillingSame = true;
	var altPhone = document.getElementById('txtAltPhone').value;
	var email = document.getElementById('txtEmail').value;
	var taxId = document.getElementById('txtTaxId').value;
	var dob = document.getElementById('txtDOB').value;
	
	var sendText = 'alt_phone=' + altPhone;
	sendText += '&email=' + email;
	sendText += '&tax_id=' + taxId;
	sendText += '&dob=' + dob;
	
	if (document.getElementById('chkIsSame').checked) {
		var nameB = document.getElementById('txtNameB').value;
		var temp = split(nameB, " ");
		var firstB = temp[0];
		var lastB = '';
		for (var i=1; i<count(temp); i++){
			lastB += temp[i];
		}
		var addressB = document.getElementById('txtAddressB').value;
		var cityB = document.getElementById('txtCityB').value;
		var stateB = document.getElementById('txtStateB').value;
		var zipB = document.getElementById('txtZipB').value;
		var phoneB = document.getElementById('txtPhoneB').value;
		isBillingSame = false;
		
		sendText += '&bFirst=' + firstB;
		sendText += '&bLast=' + lastB;
		sendText += '&bAddress=' + addressB;
		sendText += '&bCity=' + cityB;
		sendText += '&bState=' + stateB;
		sendText += '&bZip=' + zipB;
		sendText += '&bPhone=' + phoneB;
	}
	
	http.open('get', ROOT_URL+'data/sendMessage.php');
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = handleCustomerResponse;
	http.send(sendText);
}

function handleCustomerResponse() {
	if (http.readyState == 4) {
		window.location = ROOT_URL+'get_service/order-parameters.php';
	}
}

function getLineup(pdf) {
	window.open(ROOT_URL + 'channel_lineups/pdf/' + pdf, 'pdfWin');
}

function sethtml(div,content) {
 var search = content;
 var script;
 
 var is_singleq = 0; var singleq = "'";
 var is_doubleq = 0; var doubleq = '"';
 var is_escaped = 0; var escap = "\\";
 var layer = 0;
	   
 while( script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/)) {
	search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);
	if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break;
	block = search.substr(0, search.indexOf(RegExp.$1));
	search = search.substring(block.length + RegExp.$1.length);
	
	while(func = block.match(/(function(.+?)\((.*?)\)\s*\{)/)) {
	   eval(block.substr(0,block.indexOf(RegExp.$1)));
	   // for evaluating non functions
	   
	   block = block.substr(block.indexOf(RegExp.$1) + RegExp.$1.length);
	   name = RegExp.$2;
	   param = RegExp.$3;
	   
	   is_singleq = 0;
	   is_doubleq = 0;
	   is_escaped = 0;
	   layer = 0;
	   
	   
	   for(i=0;i<block.length;i++) {
		  c = block.substr(i,1);
		  
		  if ((is_singleq || is_doubleq) && is_escaped) {
			 is_escaped = 0;
		  } else if (!is_doubleq && (c==singleq)) {
			 is_singleq = !is_singleq;
		  } else if (!is_singleq && (c==doubleq)) {
			 is_doubleq = !is_doubleq;
		  } else if ((is_singleq || is_doubleq) && (c==escap)) {
			 is_escaped = 1;
		  } else if ( c=="{") {
			 layer++;
		  } else if ( c=="}") {
			 if ( layer==0 ) {
				break;
			 }
			 layer--;
		  }
	   }
	   
	   code = block.substr(0,i-1);
	   block = block.substr(i +1);
	   
	   code = code.replace(/\n/g, '\\n');
	   code = code.replace(/\r/g, '\\r');
	   code = code.replace(/'/g,"\\'");
	   
	   eval(name + " = new Function('"+param+"','"+code+"');");
	}
	eval(block); // for evaluating non functions
 }
 document.getElementById(div).innerHTML=content;
}