// get the current price from the basket html element
function getBasketPrice() {var re=new RegExp('-?[0-9]+\.[0-9]{2}');var m=re.exec($('#shippingTotalPrice').html()); var s="";for(i=0;i<m.length;i++) {s=s+m[i]+"\n";} return Math.ceil(s);}

//GIR 0AA

//
function getDynamicShip() {
	var countryCode = $('#countriesListing').val();
	var postalCode = $('#dynPostalCode').val();
	
	$('#newModalContent').attr('style', 'text-align: center;');
	$('#newModalContent').html('<img src="images/ajaxLoader.gif" />');
	
	weight = getWeight(getBasketPrice());
	
	$.ajax({
		type: "POST",
		url: "http://catalog.fullpond.com/cisco_fedex/default.asp",
		data: "postalcode="+postalCode+"&country="+countryCode+"&weight="+weight+"&submit=Submit",
		dataType: "xml",
		success: function(xml) {
			sReturn = "<div style=\"font-weight: 700; font-size: 14px; margin-bottom: 6px;\">Estimated Shipping / Handling</div><table style=\"text-align: left;\">\n";
			$(xml).find('option').each(function(){
				var xName = $(this).find('name').text();
				var rPrice = parseFloat($(this).find('price').text());
				var xPrice = rPrice + getHandling(rPrice) + getP3m();
				xPrice = '$'+xPrice.toFixed(2);
				sReturn = sReturn + "<tr><td style=\"width: 180px;\">"+xName+"</td><td style=\"width: 80px;\">"+xPrice+"</tr>\n";
			});
			sReturn = sReturn + '</table><p style="font-size: 12px; color: #AAAAAA;">This is just an estimation. Actual shipping/handling charge may vary.</p><button id="cancelDynamicPostal" onclick="$.modal.close()">Close</button>';
			$('#simplemodal-container').animate({
				width: "280px",
				marginLeft: "70px"
				}, 200, 'linear');
			$.modal;
			$('#newModalContent').html(sReturn);
		}
	});
	
}

// 
function getHandling(price) {
	var handling = new Array();
	handling[25] = 21.34;
	handling[50] = 21.45;
	handling[100] = 23.15;
	handling[200] = 24.84;
	handling[300] = 28.28;
	handling[400] = 33.11;
	handling[500] = 35.59;
	
	var lReturn = 0;
	for (var k in handling) {if (price<k) {lReturn=handling[k];break;}}
	if (lReturn == 0) {lReturn = (price * .08); lReturn = lReturn.toFixed(2);}
	return lReturn;
}

// we were going to put in something but i forgot, return 7 because its lucky
function getP3m() {return 7;}

// run the incoming number through a hash table and find a matching value. this is based on a rate average on over 4300 orders.
function getWeight(price) {
	var weight = new Array();
	weight[500] = 27;
	weight[400] = 19;
	weight[300] = 13;
	weight[200] = 9;
	weight[100] = 6;
	weight[50] = 3;
	weight[25] = 2;
	
	var iReturn = 0;
	for (var k in weight) {if (price>k) {iReturn=weight[k];break;}}
	if (iReturn == 0) {iReturn = 1;}
	return iReturn;
}

//
function showDRBox() {
	$('#framework-main-bottom').after('<div id="newModal"></div>');
	$('#newModal').html('<div id="newModalContent"></div>');
	$('#newModal').modal({overlayCss: {backgroundColor: '#000000', cursor: 'wait'}, containerCss: {width: 420, backgroundColor: '#FFFFFF', border: '3px solid #999999', padding: '10px'}, onClose: function (dialog) {$.modal.close(); $('#newModal').remove();}});
	$.ajax({url: 'script/approxForm.html', cache: false, success: function (html) {$('#newModalContent').html(html);}});
}

function newSubmitFunction() {
	// disclaimer for the rate acceptance box
	disclaimer = 'By clicking the Accept button, you agree that you have been made aware of the possible shipping charges. We will notify you via email if your actual shipping charges vary by 10%.';
	
	nsb = $('#newSubmitButton');
	
	// make it look like we're doing something important
	nsb.val('Please wait...');
	nsb.attr('disabled', 'disabled');
	
	postalCode = $('#ctl00_tcOuterContent_tcContent_lblAddressZip').html(); // grab the postal code
	countryCode = $('#ctl00_tcOuterContent_tcContent_lblAddressCountryCode').html() // grab the country code
	weight = getWeight(getBasketPrice()); // calculate the weight on estimation from price
	
	$('#framework-main-bottom').after('<div id="newModal"></div>'); // create a new div to use as the jModal
	$('#newModal').html('<div id="newModalContent"></div>'); // put another modal inside the first modal for some reason
	$('#newModal').modal({
		overlayCss: {
			backgroundColor: '#000000',
			cursor: 'wait' // behind the jModal, we want the cursor to look busy
		},
		containerCss: {
			width: 420,
			backgroundColor: '#FFFFFF',
			border: '3px solid #999999',
			marginTop: '-100px', // im not sure why but it looks stupid if you dont do this
			padding: '0 10px 10px 10px'
		},
		onClose: function (dialog) {
			$.modal.close(); // when you tell the modal to close, you have to tell it twice because it doesnt listen the first time apparently
			$('#newModal').remove();
			nsb.val('Submit Order'); // set the button back to normal
			nsb.removeAttr('disabled'); // see 1 line up
		}
	});
	
	// the table that we're displaying for rate acceptance
	sReturn = '<table width="420px;"><tr><td><h3>Shipping Confirmation</h3><p style="font-size: 12px; color: #777777; padding-bottom: 10px; border-bottom: solid 1px #CCCCCC;">Below are estimated FedEx shipping charges for international orders.</p></td></tr><tr><td><table id="putShippingHere"><tr><td><img src="images/ajaxLoader.gif" /></td></tr>';
	
	// cap off the table and add the disclaimer
	sReturn = sReturn + '</table></td></tr><tr><td><p style="font-size: 12px; color: #777777; padding-bottom: 10px; border-bottom: solid 1px #CCCCCC;">'+disclaimer+'</p><button id="cancelDynamicPostal" onclick="$.modal.close()" style="float: left;">Cancel</button><button id="cancelDynamicPostal" onclick="$(\'#ctl00_tcOuterContent_tcContent_btnContinue\').click(); $.modal.close()" style="float: right;">Accept</button><div style="clear: both;"></div></td></tr></table>';
	
	// set the html inside the modal to the table we created above
	$('#newModalContent').html(sReturn);
	
	// init a new string for the shipping rate information
	shReturn = '';
	
	// start the process to submit postalCode, countryCode, and weight to FedEx
	$.ajax({
		type: "POST",
		url: "http://catalog.fullpond.com/cisco_fedex/default.asp",
		//url: "results.xml", // mock data from FedEx for testing
		data: "postalcode="+postalCode+"&country="+countryCode+"&weight="+weight+"&submit=Submit", // data sent to fedex
		dataType: "xml", // returning xml
		success: function(xml) {
				// stroll through the xml that FedEx returns and get the method and price
				$(xml).find('option').each(function(){
					var xName = $(this).find('name').text();
					var rPrice = parseFloat($(this).find('price').text()); // turn the price string into a float
					var xPrice = rPrice + getHandling(rPrice) + getP3m(); // add in the shipping and handling, and the pick/pack/ship fee
					xPrice = '$'+xPrice.toFixed(2); // add a dollar sign and force the float to 2 decimal places
					shReturn = shReturn + "<tr><td style=\"width: 180px; padding-left: 40px;\">"+xName+"</td><td style=\"width: 80px;\">"+xPrice+"</tr>\n";
				});
				
				$('#putShippingHere').html(shReturn);
			
		}
	});
	
	// TODO: find out why I put this here
	return false;

}

var thisIsSet = 0;

$(document).ready(function() {
	initFader(); // start the fancy little fader on the front page
	
	currentPage = window.location.pathname.replace('/cisco/', '').replace("\.aspx", '').toLowerCase();
/*	
	// if we're on the basket page, show the "Dynamic Rates" link.
	if (currentPage == 'basket') {
		// why does this show up twice? im thinking the selector is grabbing both spans in the basket footer where this goes
		// $('#ctl00_tcOuterContent_tcContent_dgBasket_ctl03_lblShippingLabel').append('<a href="#" onclick="showDRBox(); return false;">Dynamic Rates</a>'); 
		if (thisIsSet == 0) {
			$('.basketshipping span:first').after('<br /><a href="#" onclick="showDRBox(); return false;">view&nbsp;estimated&nbsp;international&nbsp;shipping&nbsp;rates</a>'); 
			thisIsSet = 1
		}
	}
	
	// if we're on the billing page
	if (currentPage == 'billinglogo') {
		if ($('#ctl00_tcOuterContent_tcContent_lblAddressCountryCode').html() == "US") { 
			$('#newSubmitButton').click(function(){$('#ctl00_tcOuterContent_tcContent_btnContinue').click();});  // if they live in the US, just click submit order, they know the shipping charges
		} else {
			$('#newSubmitButton').click(function(){newSubmitFunction();}); // if elsewhere in the world, show them the rate acceptance box.
		}
	}

*/	
});

/*
 * ImageFader 1
 *
 * Copyright (c) 2008 Robertson Marketing Group Inc. (robertsonmarketing.com)
 *
 * $Date: 2008-06-25 14:22:17 -0400 (Wed, 25 June 2008) $
 * $Rev: 8 $
 */

var cells = ['#ifcell0', '#ifcell1', '#ifcell2', '#ifcell3'];

var initialSpeed = 8000; // how many milliseconds between pictures
var pauseTime = 8000; // how long to wait when a stop is clicked

var fadeInSpeed = 2000; // how long it takes the picture to fade in
var fadeOutSpeed = 2010; // how long it takes a picture to fade out

// dont change anything below this line!
var okayGo = false;
var checkI;
var activeCell = 0;

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(fun /*, thisp*/) {
		var len = this.length;
		if (typeof fun != "function")
			throw new TypeError();
		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in this)
				fun.call(thisp, this[i], i, this);
		}
	}
}

// runs imgFader() once every x amount of seconds
function initFader() {
	checkI = setInterval('imgFader()',initialSpeed);
	okayGo = true;
}

var hideAllCells = function(x) {$(x).fadeOut(fadeOutSpeed);}

function imgFader() {
	cells.forEach(hideAllCells); // hide all the cells
	(activeCell == (cells.length-1)) ? activeCell = 0 :	activeCell++; // set the active cell to the next one in the array, if at the end of the array, go back to 0
	$(cells[activeCell]).fadeIn(fadeInSpeed); // fade in the next cell
}

function pauseAt(x) {
	if (okayGo == true) {
		okayGo = false;
		if (activeCell == x) {
			clearInterval(checkI); // stop the pictures from changing
			setTimeout('initFader()', pauseTime); // set the loop to start again after x amount of seconds
		} else {
			clearInterval(checkI); // stop the pictures from changing
			cells.forEach(hideAllCells); // hide all the cells
			activeCell = x; // set the active cell
			$(cells[activeCell]).fadeIn(fadeInSpeed); // fade in the preferred cell
			setTimeout('initFader()', pauseTime); // set the loop to start again after x amount of seconds
		}
	}
}