var commonIds = new Array('economyItem','economy_intlItem');
var switchPackageNames = new Array("economy", "economy_intl");
var domesticOptions = {0:0,1:1,2:2};
var internationalOptions = {3:3,4:4,5:5};
var styleIds = new Array('col_economy','col_int_economy');
var winLoaded = false;
var clientId = Math.round(1000*Math.random());
var errorCount = 0;
var asyncCallCount = 0;
var selectedItems;
var selectedItemKeys;
var serverCallDone = true;
function init() {
	DWRUtil.useLoadingMessageQQ();
	getItems();
}

DWRUtil.useLoadingMessageQQ = function(message) {
var loadingMessage;
if (message) loadingMessage = message;
else loadingMessage = "Loading";
DWREngine.setPreHook(function() {
serverCallDone = false;
var disabledZone = $('disabledZone');
if (!disabledZone) {
disabledZone = document.createElement('div');
disabledZone.setAttribute('id', 'disabledZone');
disabledZone.style.position = "absolute";
disabledZone.style.zIndex = "1000";
disabledZone.style.left = "0px";
disabledZone.style.top = "0px";
disabledZone.style.width = "100%";
disabledZone.style.height = "100%";
document.body.appendChild(disabledZone);
var messageZone = document.createElement('div');
messageZone.setAttribute('id', 'messageZone');
messageZone.style.position = "absolute";
messageZone.style.top = "0px";
messageZone.style.right = "0px";
messageZone.style.background = "red";
messageZone.style.color = "white";
messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
messageZone.style.padding = "4px";
disabledZone.appendChild(messageZone);
var text = document.createTextNode(loadingMessage);
messageZone.appendChild(text);
}
else {
$('messageZone').innerHTML = loadingMessage;
disabledZone.style.visibility = 'visible';
}
});
DWREngine.setPostHook(function() {
serverCallDone = true;
$('disabledZone').style.visibility = 'hidden';
});
}


if (window.addEventListener) {
	window.addEventListener("load", init, false);
}
else if (window.attachEvent) {
	window.attachEvent("onload", init);
}
else {
	window.onload = init;
}

function enableContinue(enable) 
{
   var continueButton = document.getElementById("continue");
   if (continueButton != null)
   {
      if (enable == true)
         continueButton.disabled = false;
	   else
		 continueButton.disabled = "disabled";
	}
}

function getItems()
{	
    enableContinue(false);
	var entityType = $('entityType').value;
	var state = $('entityState').value;
	asyncCallCount++;
	packageView.createView(entityType,state,{callback:populateView, async:asyncCall, errorHandler:function(message) {errorCount++;packageView.logError( "ClientId-" + clientId + " :ErrorCount-" + errorCount + " :AsynCall-" + asyncCallCount + " msg:"+ message + ",entityType:" + entityType + ",state:" + state); alert("Please press F5 or refresh your browser to view the most current information."); }});
}

var disableDiscount = new Boolean(false);

var descriptions = new Array();
var descriptionsIndex = 0;

var domesticPrices = new Array();
var domesticPricesIndex = 0;

var internationalPrices = new Array();
var internationalPricesIndex = 0;

var packagePrices = {
	0:domesticPrices,
	1:internationalPrices
};

var packageIndexes = {
	0:domesticPricesIndex,
	1:internationalPricesIndex
};

//view is what comes back from the xhr request
function populateView(view) 
{
	//used for disabling the discount on states with strikethrough pricing
	disableDiscount = false;

	//reset descriptions and prices
	//of stored elements
	descriptions = new Array();
	descriptionsIndex = 0;
	domesticPrices = new Array();
	domesticPricesIndex = 0;
	internationalPrices = new Array();
	internationalPricesIndex = 0;
	
	//find the "selected" items - disable the others by default
	getSelectedItemKeys();
	
	//find the checked item and remember it
	getCheckedItem();
	
	//replace the insides of element named "itemList" with the packageItems using 
	//these callback methods
	//we scrape them instead and put them into the descriptions and packagePrices objects
	DWRUtil.addRows("itemList", view.packageItems, [ getDescription, getEconomy, getEconomyInternational ]);

	//set descriptions
	$("libertyDescription").innerHTML = descriptions[0];
	$("starsAndStripesDescription").innerHTML = descriptions[1];
	$("freedomDescription").innerHTML = descriptions[2];
	
	//set package prices
	$("libertyChoice").innerHTML = packagePrices[0][0];
	$("starsAndStripesChoice").innerHTML = packagePrices[0][1];
	$("freedomChoice").innerHTML = packagePrices[0][2];
	$("libertyInternationalChoice").innerHTML = packagePrices[1][0];
	$("starsAndStripesInternationalChoice").innerHTML = packagePrices[1][1];
	$("freedomInternationalChoice").innerHTML = packagePrices[1][2];

	var row = view.packages[0];
	var cellFuncs = [getPackageEconomy, getPackageEconomyInternational];

	for (var j = 0; j < cellFuncs.length; j++) {
		var func = cellFuncs[j];
		var reply = func(row);
	}

	var _internationalCost = view.internationalCost;
	var _stateFee =  view.stateFee;


	//update the state fees
	for(var k=0; k<commonIds.length; k++) {				
		var stateFeeEle = $('stateFee_' + commonIds[k] );
		
	    var totalStateFee = 0.0;
		
		if(commonIds[k].indexOf('_intlItem')>-1)
		{
		   if (view.stateFeeDetails != null)
		   {
		      for (var j = 0; j < view.stateFeeDetails[3].length; j++)
		      {
		         totalStateFee += view.stateFeeDetails[3][j].price;
		      }
		   }
		}
		else
		{
		   if (view.stateFeeDetails != null)
		   {
		      for (var j = 0; j < view.stateFeeDetails[0].length; j++)
		      {
		         totalStateFee += view.stateFeeDetails[0][j].price;
		      }
		   }
		}
		
		if (view.stateFeeDetails == null)
		{
		   if(commonIds[k].indexOf('_intlItem')>-1)
		      totalStateFee = Number(_internationalCost) + Number(_stateFee);
		   else
		      totalStateFee = _stateFee;
		}
		
		stateFeeEle.value = currencyFormat(totalStateFee);
		stateFeeEle.innerHTML = currencyFormat(totalStateFee);	
	}

	if(!winLoaded) {
		var pkgEle = $(view.selectedProductType + 'Package');
		pkgEle.checked = true;
		pkgEle.onclick();
		if(view.entityType != null) {
			DWRUtil.setValue($('entityType'), view.entityType);
		}
		DWRUtil.setValue($('entityState'), view.state);					
	} else {
		disableSelectedColumn(false);
	}

	//hiding the discount if cost > actualCost
	if (disableDiscount == true) {
	  show("callout_Discount_Codes_disabled");
	  hide("callout_Discount_Codes");
	} else {
	  show("callout_Discount_Codes");
	  hide("callout_Discount_Codes_disabled");
	}
	setCheckedItem(rememberCheckedIndex);
	getSelectedItems();			  
	refreshTotalCost();				
	winLoaded = true;
	enableContinue(true);
}

var rememberCheckedIndex = -1;

//find the checked items() {
function getCheckedItem() {
	//reset the checked index
	rememberCheckedIndex = -1;
	var bundles = document.getElementsByName(commonIds[0]);
	//find which item is "checked" and remember its index
	findChecked:
	for(i = 0; i < bundles.length; i++) {
		if(bundles[i].checked == true) {
			rememberCheckedIndex = i;
			break findChecked;
		}
	}
}

//reselect the checked item (and its corresponder) after switching states
function setCheckedItem(itemNumber) {
	var bundles = document.getElementsByName(commonIds[0]);
	if(itemNumber >= 0) {
		if(itemNumber < bundles.length) {
			bundles[itemNumber].checked = "checked";
			bundles = document.getElementsByName(commonIds[1]);
			bundles[itemNumber].checked = "checked";
		}
	}
}



//find the items that are "selected"
//I'm not sure this does anything
function getSelectedItemKeys()
{	
	//create a new array
	selectedItemKeys = new Array();
	
	//for each of the common cell IDs
	for(var i=0; i<commonIds.length; i++) {
		
		//get an id
		var commonId = commonIds[i];
		
		//at the array index IDs with this id, create a new array
		selectedItemKeys[commonId]= new Array();
		
		//copy that array to a new variable
		var itemKeyArray = selectedItemKeys[commonId];
		
		//create a new array of objects with the common id as their name
		var items = document.getElementsByName(commonId);				
		
		//iterate through it
		for(var j=0; j<items.length; j++) {
		
			//if any are checked, 
			if(items[j].checked) {
				//copy their value into the array
				itemKeyArray[items[j].value] = items[j].value;
			}
		}
	}
}


function refreshTotalCost()
{
	for(var i=0; i<commonIds.length; i++)
		{
			var commonId = commonIds[i];
			var commonIdItems = selectedItems[commonId];
			var totalSelectedCost = 0;
		for(var j=0; j<commonIdItems.length; j++)
		{
			totalSelectedCost = Number(totalSelectedCost) + Number(commonIdItems[j]);
		}	
		var packagePriceEle = $('price_' + commonId + 'Package');						
		var stateFeeEle = $('stateFee_' + commonId );
		var totalCost = Number(packagePriceEle.innerHTML) + Number(totalSelectedCost) + Number(stateFeeEle.innerHTML);
		var totalCostEle = $('totalCost_' + commonId);
		totalCostEle.value = currencyFormat(totalCost);
		totalCostEle.innerHTML = currencyFormat(totalCost);					
		}
}

//
function getSelectedItems() {

	//create/reset a selectedItems array
	selectedItems = new Array();
	
	//for all of the commonIDs
	for(var i=0; i< commonIds.length; i++) {
		//look at current id
		var commonId = commonIds[i];
		
		selectedItems[commonId]= new Array();
		var itemArray = selectedItems[commonId];
		var items = document.getElementsByName(commonId);				
		for(var j=0; j<items.length; j++)
		{
			if(items[j].checked)
			{
				//var index = itemArray.push( $('price_' + items[j].name + items[j].value).innerHTML);
			}
		}			  		
	}
}	

var stopRecheck = false;

//select the corresponding item
function selectCorrespondingItem(item) {
	
	if(!stopRecheck) {
		//find this item's form
		var thisForm = item["form"];

		//find the index of this element
		var radioIndex = 0;
		var radios = document.getElementsByName(item.name);
		findIndex:
		for(i = 0; i < radios.length; i++) {
			if(radios[i] === item) {
				radioIndex = i;
				break findIndex;
			}
		}

		//get the corresponding element name
		var corresponder = (item.name == commonIds[0]) ? commonIds[1] : commonIds[0];

		//select the corresponding item
		var correspondingRadio = document.getElementsByName(corresponder)[radioIndex];
		correspondingRadio.checked = "checked";

		//you're about to call the onclick of this corresponder, which calls this method too
		stopRecheck = true;
		
		//make this particular item "hot"
		makeHotItem(item);
		
		//call this 
		correspondingRadio.onclick();
	} else {
		stopRecheck = false;
	}
}

//get parent container or bundle option
function getContainer(item) {
	return item["parentNode"]["parentNode"]["parentNode"]["parentNode"]["parentNode"];
}

//make no items hot
function clearHots() {

	//set all items to not hot
	//get the items
	var theseItems = document.getElementsByName(commonIds[0]);
	var thoseItems = document.getElementsByName(commonIds[1]);
	
	//get all of their parents
	var allItems = new Array();
	var allItemsIndex = 0;
	for(i = 0; i < theseItems.length; i++) {
		allItems[allItemsIndex++] = theseItems[i];
	}
	for(i = 0; i < thoseItems.length; i++) {
		allItems[allItemsIndex++] = thoseItems[i];
	}
	
	//remove "_hot" from the className of all of the containers
	for(i = 0; i < allItems.length; i++) {
		var currentItem = getContainer(allItems[i]);
		if(currentItem["className"].indexOf("_hot") >= 0) {
			currentItem["className"] = currentItem["className"].substring(0,currentItem["className"].indexOf("_hot"));
		}
	}
}

//makes the current selected bundle item "hot"
function makeHotItem(item) {
	//make nothing hot
	clearHots();


	//if you have an item, make that item hot
	
	if(item) {
		getContainer(item)["className"] += "_hot";
	}
}
//find a selected item by column number
function findHot(columnNumber) {
	if(columnNumber) {
		//get all items with the corresponding name
		var possibleHots = document.getElementsByName(commonIds[columnNumber]);
		
		//iterate through the possible items and look for a checked item
		findChecked:
		for(j = 0; j < possibleHots.length; j++) {
			if(possibleHots[j].checked == true) {
				makeHotItem(possibleHots[j]);
				break findChecked;
			}
		}
	}
}

function updateTotalCost(item)
{
	var commonId = item.name;
	var packagePrice = $('price_' + commonId + 'Package').innerHTML;
	var stateFee = $('stateFee_' + commonId ).innerHTML;
	var itemPrice = $('price_' + item.id).innerHTML;
	totalCost = Number(packagePrice) + Number(stateFee) + Number(itemPrice);
	$('totalCost_' + commonId ).innerHTML = currencyFormat(totalCost);
	
	//make sure corresponding item is selected
	selectCorrespondingItem(item);
}

function getItemColumn(item, colNo)
{
	var commonId = commonIds[colNo];
	var itemObj = eval('item[' + colNo + ']');
	if(itemObj.restricted)
	{
		return 'n/a';
	}
	if(itemObj.included)
	{
		return '<img src="images/checkmark_off.gif" width="23" height="18" />';
	}
	else
	{
		var isChecked = '';
		if(selectedItemKeys[commonId][itemObj.itemId] != null)
		{						
			//alert(commonId + itemObj.itemId	+ " user selected");
			isChecked = ' checked="checked" ';
		}
		if(!winLoaded && itemObj.inCart)
		{		
			//alert(commonId + itemObj.itemId	+ " in cart");	
			isChecked = ' checked="checked" ';
		}
		return '<input type="radio" disabled="disabled" price="66" name="' +  commonId  + '" id = "'+ commonId + itemObj.itemId +'" value="'+ itemObj.itemId +'"'+ isChecked +' onclick="updateTotalCost(this);"><label>$<span id = "price_'+ commonId + itemObj.itemId +'" value="'+ itemObj.cost +'">' + itemObj.cost + '</span></label>';
	}
}
function getPackageColumn(item, colNo) {

	var commonId = commonIds[colNo];
	var packageObj = eval('item[' + colNo + ']');
	var radioEle = $(commonId + 'Package');
	radioEle.value = packageObj.itemId;
	var priceEle = $('price_' + commonId + 'Package');
	priceEle.value = packageObj.cost;
	priceEle.innerHTML = packageObj.cost;
	//alert(item.actualCost);
	if(Number(packageObj.actualCost) > Number(packageObj.cost))
	{
	  var actualpriceEle = $('actualprice_' + commonId + 'Package');
	  actualpriceEle.innerHTML = "$" + packageObj.actualCost + "<br/>";
	  disableDiscount = true;
	}
	else
	{
	  var actualpriceEle = $('actualprice_' + commonId + 'Package');
	  actualpriceEle.innerHTML = "";		
	}
	var totalCostEle = $('totalCost_' + commonId);
	totalCostEle.innerHTML = packageObj.cost;
	totalCostEle.value = packageObj.cost;
	
	var packageDescription = $('packageDescription');
	packageDescription.innerHTML = packageObj.detailDescription;
}
function TestTotal()
{
	var items = document.getElementsByName('economyItem');
	var total = 0;
	for(var i=0; i<items.length; i++)
	{
		if(items[i].checked)
		{
			total += Number($(items[i].name + items[i].value).value);
		}
	}
	alert(total);
}
function ViewDoc()
{
	var newWin = window.open('','EIN_Detail','status=no,scrollbars=yes,resizable=yes');
	newWin.document.write('<TEXTAREA rows=50 cols=50>');
	newWin.document.write(window.document.body.innerHTML);
	newWin.document.write('</TEXTAREA>');
}
function selectPkg(colNo)
{
	//clear the "hot" items
	clearHots();

	//disable the selected column's radios and tds
	disableSelectedColumn(true);				

	//set the element named "commonIds[colNo] + 'PackageType'" to checked
	$(commonIds[colNo] + 'PackageType').checked = true;
	
	//make a note that the current selected column corresponds to commonIds[colNo]
	$("selectedItemType").value = commonIds[colNo];

	//get all of the elements with the name stored in id="selectedItemType"
	//and store them in the golbal items collection
	items = document.getElementsByName($('selectedItemType').value);
	
	//enable the selected column's radios and tds
	disableSelectedColumn(false);					

	//look through the switchPackageNames array
	for(i = 0; i < switchPackageNames.length; i++) {
		//get the element named switchPackageNames[i] + "Pkg"
		//and set its class/className to "thItem_selected" or "thItem" if
		//it corresponds to the selected column or not
		$(switchPackageNames[i] + "Pkg").setAttribute("class",((i == colNo) ? "thItem_selected" : "thItem"));
		$(switchPackageNames[i] + "Pkg").setAttribute("className",((i == colNo) ? "thItem_selected" : "thItem"));
	}

	//then find the "hot" radio items in this column if any
	findHot(colNo);

}
function disableSelectedColumn(disable)
{
	//get the elements that share the name of the value of the selectedItemType hidden input
	var items = document.getElementsByName($('selectedItemType').value);

	//iterate through
	for(var i=0; i<items.length; i++) {
		//disable them or not, depending on argument
		items[i].disabled = disable;
	}
	
	//if the disable argument is false
	if(!disable)
	{
		//find the stateFee element
		var stateFee = $('stateFee');
		
		//find the current type of selected item
		var itemTypeSelected = 	$('selectedItemType').value;
		
		//state fee for the selected item
		var stateFeeEle = $('stateFee_' +  itemTypeSelected);
		
		//get the innerHTML (for value)
		stateFee.value = stateFeeEle.innerHTML;
		
		//figure out which column equates to the type of item
		var selectedIndex = 0;
		for(; selectedIndex<commonIds.length; selectedIndex++)
		{
			if(commonIds[selectedIndex] == itemTypeSelected)
				break;
		}
		
		//call selectCols to handle this column as "selected"
		selectCols(selectedIndex);
	}
}
function validateForm()
{
	if(!serverCallDone)
		return false;
	var state = $('entityState').value;
	if(state == "")
	{
		alert("Please select a state");
		return false;
	}
	document.redesignincForm.action = incPath + "entityPackage.do";
	return true;
}
function addDiscount() {
	var discountCode = $('discCode').value;
	packageView.addDiscount(discountCode,{callback:displayDiscountMessage});
}
function displayDiscountMessage(msg) {
	var discountMsgEl = $("discMsg");
	discountMsgEl.innerHTML = msg;
	highlight("discMsg","#FFFFFF");
}

//make cells in a column "selected"
function selectCols(colNo) {

	//store the selected style from the styleIds array (column number = index)
	var selectedStyle = styleIds[colNo];

	//get all <td> elements
	var cTds = document.getElementsByTagName("TD");
	
	//iterate through the tds
	for (var i=0 ; i < cTds.length ; i++) {
		//compare to the styleIDs 
		for(var j=0 ; j < styleIds.length ; j++) {
			//if the className of this td is the selected style
			//or the className == the selected style + "_selected" (the active version)
			if (cTds[i].className==selectedStyle  || cTds[i].className==(selectedStyle + "_selected")) 
			{
				//set a value for "hot" if the radio array in this checked
				var hotAddednum = "";
				var innerRadios = cTds[i].getElementsByTagName("input");
				//if you have an input...
				if(innerRadios.length > 0) {
					for(k = 0; k < innerRadios.length; k++) {
						//and it's a radio
						if(innerRadios[k].type == "radio") {
							//and it's checked
							if(innerRadios[k].checked == true) {
								//use a different class
								hotAddednum = "_hot";
							}
						}
					}
				}
				
				//"select" the cells in this column by changing their css
				cTds[i].className = selectedStyle + "_selected" + hotAddednum;
				break;
			} else if(cTds[i].className==styleIds[j] + "_selected") {
				//turn this cell "off" if it's a known stylized column
				cTds[i].className = styleIds[j];
				break;
			}			   	
		}
	}   
}

var getDescription = function(item) {
	descriptions[descriptionsIndex++] = item[0].detailDescription;
}

var populateColumnItem = function(item, colNumber) {
	packagePrices[colNumber][packageIndexes[colNumber]++] = getItemColumn(item,colNumber);
}

//override the DWRUtil tr adder - don't want any TRs added
DWRUtil._addRowInner = function(cellFuncs, options) {
	for (var cellNum = 0; cellNum < cellFuncs.length; cellNum++) {
		cellFuncs[cellNum](options.rowData);
	}
};

var getEconomy = function(item) {
	return populateColumnItem(item,0);
}

var getEconomyInternational = function(item) {
	return populateColumnItem(item,1);
}

var getPackageEconomy = function(item) {
	getPackageColumn(item,0);
}

var getPackageEconomyInternational = function(item) {
	getPackageColumn(item,1);
}

function checkCALlc() {
  if ($('entityState').value == "CA" &&
      $('entityType').value == "LLC") {
       popMSG();
  }
  
  return true;
}

function validateNpsAndPcs() {
  return true;
}

function popMSG() {
  var winparm = "";
  var corptype = "";
  window.name = "parent";

  var url = "includes/californiaMsg.jsp";

  winparm = "width=600,height=380,resizable=yes,scrollbars=yes";
  var hWnd = window.open(url,"MSG",winparm);
  if (hWnd != null) {
    if (hWnd.opener == null) {
      hWnd.opener = self; window.name = "home"; hWnd.location.href=url;
    }
  }
}

function currencyFormat(amount) {
    var val = parseFloat(amount);
    if (isNaN(val)) {
        return "0.00";
    }
    if (val <= 0) {
        return "0.00";
    }
    val += "";
    if (val.indexOf('.') == -1) {
        return val+".00";
    } else {
        val = val.substring(0,val.indexOf('.')+3);
    }
    val = (val == Math.floor(val)) ? val + '.00' : ((val*10 == Math.floor(val*10)) ? val + '0' : val);
    return val;
}