/* AJAX METHODS
   Karol Golka
   Mar 29, 2005
   http://rangeRoamer.com
*******************************/

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

/* set submit button styles
--------------------------- */
function btnOver(obj)
{
	obj.style.backgroundColor='#668ED8';
	obj.style.color='#194180';	
	obj.style.cursor='pointer';
}
function btnOut(obj)
{
	obj.style.backgroundColor='#ACC4EB';
	obj.style.color='#668ED8';
	
}


/* highlight focus textboxes
--------------------------- */
function inputFocus(obj)
{
	obj.style.backgroundColor='#E4EBF9';
	obj.style.color='#000000';
	obj.style.fontWeight='bold';
}
function inputBlur(obj)
{
	obj.style.backgroundColor='#FFFFFF';
	obj.style.color='#333333';
	obj.style.fontWeight='normal';
}

/* checkout onload
--------------------------- */
function loadcheckout()
{
	document.getElementById('tbxFirstName').focus();
	if (document.getElementById('radShipBilling').checked)	
		flipShippingAddress('none');
	else
		flipShippingAddress('block');	
}


/* flip shipping address
--------------------------- */
function flipShippingAddress(setting)
{	
	if (setting == 'none')
		loadShippingMethods(document.getElementById('ddlCountry').value, 'internal');
	else
		loadShippingMethods(document.getElementById('ddlShCountry').value, 'internal');
		
	document.getElementById('tableOrderShippingDetails').style.display = setting;	
}

/* unused, just testing */
function flipShippingAddress_callback(res)
{
	
}

/* load shipping methods
--------------------------- */
function loadShippingMethods(id_country, control)
{
	if (document.getElementById('radShipDifferent').checked && control == 'ddlCountry')
		return;
	else
		// load shipping methods
		rangeRoamer.AJAXcart.LoadInternationalShippingMethods(id_country, loadShippingMethods_callback);		
}

/* callback for loadShippingMethods (loads select) */
function loadShippingMethods_callback(res)
{
	// display appropriate SELECT
	document.getElementById('spanShippingOptions').innerHTML = res.value;
	
	// update order summary (callback within a callback)
	setTimeout('shippingMethodChanged(' + document.getElementById('selShippingOptions').value + ')', 1000);	
}

/* Shipping Method Changed
--------------------------- */
function shippingMethodChanged(id_shipping)
{	
	// update order summary
	rangeRoamer.AJAXcart.UpdateOrderSummary(id_shipping, updateOrderSummary_callback);	
}
/* callback */
function updateOrderSummary_callback(res)
{
	// show order summary values
	document.getElementById('spanShippingTotal').innerHTML = res.value[1];
	document.getElementById('spanOrderTotal').innerHTML = res.value[2];
}
/* generic Add 2 Cart
--------------------------- */
function add2cart(id)
{
	/* add any product 'model' to cart */
	rangeRoamer.AJAXcart.Add2Cart(id, add2cart_callback);
}
/* callback */
function add2cart_callback(res)
{
	// if SIM/TOLLFREE conflict exists, alert
	// to speak with a consultant if you would like to purchase multiple SIMS/TOLLFREEs
	if (res.value[0] == '0')
	{
		/* redirect */
		location.href='http://www.rangeroamer.com/viewcart.aspx';
		}
	if (res.value[0] == '1')
	{
		// res.value[1] is the 1-800 custostomer services number
		//alert('ATTENTION!\r\nAt this time, your order can only have ONE SIM CARD and ONE TOLL-FREE NUMBER. If you would like to purchase multiple SIMs and Toll-Free numbers, please contact customer services at '+res.value[1] +
		//'.\r\n\r\nIf you would like to change your shopping cart selection, simply go to your shopping cart and remove your package and/or individual products.');
	}	
}
/* Add Package 2 Cart
--------------------------- */
function addpackage2cart(id)
{
	/* add any product 'model' to cart */
	rangeRoamer.AJAXcart.AddPackage2Cart(id, addpackage2cart_callback);
}
/* callback */
function addpackage2cart_callback(res)
{
	// if SIM/TOLLFREE conflict exists, alert
	// to speak with a consultant if you would like to purchase multiple SIMS/TOLLFREEs
	if (res.value[0] == '0')
	{
		/* redirect */
		location.href='http://www.rangeroamer.com/viewcart.aspx';
		}
	if (res.value[0] == '1')
	{
		// res.value[1] is the 1-800 custostomer services number
		alert('ATTENTION!\r\nAt this time, your order can only have ONE SIM CARD and ONE TOLL-FREE NUMBER. If you would like to purchase multiple SIMs and Toll-Free numbers, please contact customer services at '+res.value[1] +
		'.\r\n\r\nIf you would like to change your shopping cart selection, simply go to your shopping cart and remove your package and/or individual products.');
		}
	if (res.value[0] == '2')
	{
		location.href='http://www.rangeroamer.com/rental-dates.aspx';
		}

}


/* generic remove from cart
--------------------------- */
function removefromcart(id, tag_id)
{
	/* add any product 'model' to cart */
	rangeRoamer.AJAXcart.RemoveFromCart(id, tag_id);
	location.reload();
}

/* generic remove package from cart
--------------------------- */
function removepackagefromcart(id, tag_id)
{
	// show confirm 	
//	if (confirm('This product belongs to a package. \r\nRemoving it will remove all other products belonging to this package\r\n\r\n\r\nARE YOU SURE YOU WANT TO REMOVE ALL THE PRODUCTS IN THIS PACKAGE?\r\n'))
//	{	
//		/* add any product 'model' to cart */
		rangeRoamer.AJAXcart.RemovePackageFromCart(id, tag_id);
		location.reload();	
//	}
//	else
//		return false
}

// CHECK REFERRER CODE
function checkReferrerCode()
{
	// get referrer code
	refcode = document.getElementById('tbxReferrerCode').value;
	
	// check if null
	if (!refcode)
		alert('Referrer Code cannot be blank!');
	else {
		
		// call AJAX method 
		rangeRoamer.AJAXcart.CheckReferrerCode(refcode, callback_checkReferrerCode);
	}	
}

function callback_checkReferrerCode(res)
{
	// check if error
	if (res.value[0] == '-1')
		alert(res.value[1]);
	else if (res.value[0] == '1')
	{	
		// show success message
		alert('CONGRATULATIONS!\r\n\r\nYour are eligible for a discount, and it is about to be applied as soon as you click ok.');
		
		// update order summary (callback within a callback), to refresh order summary
		setTimeout('loadcheckout()', 100);			
	}
	else if (res.value[0] == '2')
	{
		// show success message
		alert('POSIM successful.');
		
		// update order summary (callback within a callback), to refresh order summary
		setTimeout('loadcheckout()', 100);			
	}
	
	// clear textbox
	document.getElementById('tbxReferrerCode').value = '';
		
}

   function loadRentalDates() {
   	    // hide error	
	    $('lblError').hide();
    		
	    // check if we have both dates
	    if (document.getElementById('startDate').value != '' && document.getElementById('endDate').value != '')
	    {
	        var insurance = document.getElementById('chkHandsetInsurance').checked;
	        var pkg = getCheckedValue(document.getElementsByName('premiumPhone'));
	        
		    // show loading button
		    $('imgLoading').show();
    		
		    // call AJAX method 
		    rangeRoamer.AJAXcart.LoadRentalDates(
		        document.getElementById('startDate').value,
			    document.getElementById('endDate').value,
			    pkg,
			    document.getElementById('chkHandsetInsurance').checked,
			    document.getElementById('lstMoreAirtime').value,
			    callback_loadRentalDates);
    		
	    }  

   }

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function callback_loadRentalDates(res)
{
	// check if error
	if (res.value[0] == '-1')
	{
		// hide loading button
		$('imgLoading').style.display = 'none';
		$('orderSummary_btnAdd2Cart').hide();
		
		// show error
		$('lblError').style.display = 'block';
		$('lblErrorDetails').innerHTML = res.value[1];
		
		// clear items
        clearOrderLineItems();
	}
	else
	{
        // add order items
        updateOrderLineItems(res.value);

		// load rental weeks total
		$('spanOrderTotal').innerHTML = res.value[1];
		
		// show add2cart button
		$('orderSummary_btnAdd2Cart').show();
		
		// hide loading button
		$('imgLoading').hide();
	}	
}

function updateOrderLineItems(orderLineItems)
{
    clearOrderLineItems();
    if(orderLineItems.length > 1)
    {
        $('spanOrderTotal').innerHTML = orderLineItems[1];
        if(orderLineItems.length > 2)
        {
            var i;
            var lineItemsElement = $('orderLineItemsBody');
            for(i = 2; i < orderLineItems.length; i+=2)
            {
                if(orderLineItems[i].indexOf('Shipping') == -1)
                {
                    if(BrowserDetect.browser == "Explorer")
                    {
                        var myNewRow = lineItemsElement.insertRow();
                        myNewRow.className = 'lineItem';
                        var cell1 = myNewRow.insertCell();
                        cell1.className = 'lft';
                        var cell2 = myNewRow.insertCell();
                        cell2.className = 'rt';
                        cell1.innerHTML = orderLineItems[i];
                        cell2.innerHTML = '$<span>' + orderLineItems[i+1] + '<\/span>';
                    }
                    else
                    {
                        lineItemsElement.innerHTML += '<tr class="lineItem"><td class="lft">' + orderLineItems[i] + '<\/td><td class="rt">$<span>' + orderLineItems[i+1] + '<\/span><\/td><\/tr>';
                   
                    }
                }
            }
        }
    }
}

function clearOrderLineItems()
{
	var lineItems = $$(".lineItem");
	var i = 0;
	for(i = 0; i < lineItems.length; i++)
	{
	    lineItems[i].remove();
	}
	
	var shipping = $('shippingRow');
	if(shipping != null)
	{
	    $('shipping').remove();
	}
	
	$('spanOrderTotal').innerHTML = '0';
}


// Show Call In Code 
function ShowCallInCode()
{
	// control replacement
	document.getElementById('callincode').innerHTML = "<input type='text' id='tbxCallInCode' name='tbxCallInCode' /><a style='color: #ccc !important; margin-left: 5px;' href='#' onclick='ProcessCallInCode();void(0);'>Process</a>";
}

// Show Call In Code 
function ProcessCallInCode()
{
	// get call in code
	var callincode = document.getElementById('tbxCallInCode').value;
	
	// call AJAX method 
	rangeRoamer.AJAXcart.ProcessCallInCode(callincode, callback_ProcessCallInCode);
}

function callback_ProcessCallInCode(res)
{
	// check if error
	if (res.value[0] == '-1')
		alert(res.value[1]);
	else 
		// append query string
		location.href = res.value[1];
		
}


    
/********* calls the ajax cart for adding options and mins ****************/
/*

current inputs are 
  1. airtime
  2. premium plan
  5. insurance

buy only
  4. multiple phones


*/
function addMinutesAndOptions()
{
    // hide error	
   // $('lblError').hide();
    var airtime = document.getElementById('drpAirtime').value;
    var premium = getCheckedValue(document.getElementById('radPremiumAirtimePlan_0'))+getCheckedValue(document.getElementById('radPremiumAirtimePlan_1'));
    var insurance = getCheckedValue(document.getElementById('radInsurance_0'))+getCheckedValue(document.getElementById('radInsurance_1'));
    var multiplePhones = getCheckedValue(document.getElementById('radMultiplePhones_0'))+getCheckedValue(document.getElementById('radMultiplePhones_1'))+getCheckedValue(document.getElementById('radMultiplePhones_2'));
    // radAutoRecharge drpMinimumBalance drpRecharge 
		 
	// show loading button
	$('orderImgLoading').show();
		
	    // call AJAX method 
	    //AddMinutesAndOptions(string AIRTIME PRODUCT ID, bool premiumMinutesPlan,  bool insurance)
	    rangeRoamer.AJAXcart.AddMinutesAndOptions(
	        airtime,
	        premium,
	        insurance,
	        callback_addMinutesAndOptions)

}

function callback_addMinutesAndOptions(res)
{
	// check if error
	if (res.value[0] == '-1')
	{
		// hide loading button
		$('orderImgLoading').style.display = 'none';
		$('TripPlanner_orderSummary_btnAdd2Cart').hide();
		
		// show error
		$('lblError').style.display = 'block';
		$('lblErrorDetails').innerHTML = res.value[1];
		
		// clear items
        clearOrderLineItems();
	}
	else
	{
        // add order items
        updateOrderLineItems(res.value);

		// load rental weeks total
		$('spanOrderTotal').innerHTML = res.value[1];
		
		// show add2cart button
		$('TripPlanner_orderSummary_btnAdd2Cart').show();
		
		// hide loading button
		$('orderImgLoading').hide();
	}	
}

 


/******** ZC 5/12/09 - change the flag ********/
var currentFlag=0;
var numFlags=2;
function changeFlag()
{        
    if(currentFlag+1<numFlags)
    {
        currentFlag=currentFlag+1;
    }
    else
    {
        currentFlag=0;
    }    
    setFlagImage();

    PageMethods.SaveCurrentCountry( blank_callback);       
}

function blank_callback(res)
{
    alert('callback');
}

function setFlagImage()
{
    if(currentFlag == 0)
        document.getElementById('wucHeader_flag').src='/images/US_flag.jpg';
    else
        document.getElementById('wucHeader_flag').src='/images/CA_flag.jpg';

}


function changeFreeAmount()
{
    var bonusPercentage = document.getElementById('bonusPercentage').innerHTML;
    var dropSelectedIndex = document.getElementById('drpAirtime').selectedIndex;
    var airtime = document.getElementById('drpAirtime').options[dropSelectedIndex].text;
    document.getElementById('freeAmount').innerHTML= airtime*bonusPercentage/100;
}
