/**
 *
 * Javascript for tcanetworks.ca
 *
 */
returnMoney = function(number) {
	var nStr = '' + Math.round(parseFloat(number) * 100) / 100;
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '.00';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
};
	
var cart = {};
//
// submit event cart form
//
cart.eventCheckoutSubmit = function() {
	var batchCount  = $('#batchCount').val() || 0;
	var ticketCount = $('#ticketCount').val() || 0;
	var totalCount  = batchCount + ticketCount;
	var isReadyToSubmit = true;
	
	if( totalCount < 1 ) {
		isReadyToSubmit = false;
		$('#ticketError').show();
	}
	else {
		$('#ticketError').hide();
	}
	
	var deliveryOption = $('#deliveryOption').val();

	if( deliveryOption != undefined  && deliveryOption == '') {
		isReadyToSubmit = false;
		$('#deliveryError').show();
	}
	else {
		$('#deliveryError').hide();
	}
	
	return isReadyToSubmit;
};
cart.changeDeliveryOption = function() {
	cart.calculateEventTotal();
}
//
// ticket count changed
//
cart.ticketCountChanged  = function(ticketCount) {
	$('#ticketCountInfo').html(ticketCount);
	cart.calculateEventTotal();
};
//
// batch ticket changed
//
cart.batchCountChanged   = function(batchCount)  {
	$('#batchCountInfo').html(batchCount);
	cart.calculateEventTotal();
};

cart.calculateEventTotal = function() {
	var batchCount = $('#batchCount').val();
	var batchPrice = $('#batchPrice').val();
	
	var ticketCount = $('#ticketCount').val();
	var ticketPrice = $('#ticketPrice').val();
	
	var deliveryOption = $('#deliveryOption').val();

	var batchTotal  = null;
	var ticketTotal = null;
	var total       = 0;
	
	if( deliveryOption && deliveryOption == 'is_delivery_courier') {
		total += 10;
	}
	
	if( batchCount && batchPrice ) {
		batchTotal = batchCount * batchPrice;
		total += batchTotal;
	}
	if(ticketCount && ticketPrice) {
		ticketTotal = ticketCount * ticketPrice;
		total += ticketTotal;
	}
	total = returnMoney(total);
	
	$('#eventCartTotal').html('$ ' + total);
}

/* On DOM Ready...
----------------------------------------------------------------------------------------------------*/
$(document).ready(function() {
	initRollovers($(".rollover"));		// pass where to apply rollover events
	preloadImages($(".rollover"));		// preload rollover images
	
	//-- event cart, format total
	$('#eventCartTotal').each( function() {
		cart.calculateEventTotal();
	})
});




/* FUNCTIONS
----------------------------------------------------------------------------------------------------*/

function goTo(url) {
	window.location.href = baseHref(url);
}

/**
 * Apply the base href to a url (if it exists)
 */
function baseHref(loc) {
	// loc is the relative path your wish to redirect to
	var b = document.getElementsByTagName('base');
	if (b && b[0] && b[0].href) {
		loc = b[0].href + loc;
	}
	return loc;
}


function goBack() {
	window.history.go(-1);
}


/**
 * Binds event handlers to swaps images for rollovers.
 *
 *	Expects: 			one or more DOM elements.
 *
 *  Elements should be:	an IMG node,
 *						an INPUT node of type 'image',
 *						an A or DIV node containing either of the above.
 *
 *  Image names must end with _over.* and _off.* to qualify for swapping.
 *		(ex. "btn-home_off.gif" triggers "btn-home_over.gif" on mouseover)
 *
 */
function initRollovers(domChunk) {

	var elems;
	var overSrc;

	// assign event handlers
	domChunk.bind("mouseover", function() {
		// find images that need to swapped
		if (this.tagName == "A" || this.tagName == "DIV") {
			elems = $(this).find("img[@src*='_off.']"); // for A tags look for suitable child images
		} else {
			elems = $(this);
		}

		// do the swap
		elems.each(function(){
			overSrc = (this.src).replace(/\_off\./, "_over.");
			this.src = overSrc;
		});
	});
	domChunk.bind("mouseout", function() {
		// find images that need to swapped
		if (this.tagName == "A" || this.tagName == "DIV") {
			elems = $(this).find("img[@src*='_over.']"); // for A tags look for suitable child images
		} else {
			elems = $(this);
		}
		
		// do the swap
		elems.each(function(){
			overSrc = (this.src).replace(/\_over\./, "_off.");
			this.src = overSrc;
		});
	});
}


/**
 * Preload images used in rollovers.
 */
function preloadImages(domChunk) {
	
	var elems;
	var preloadSrc;
	var preloadObj;
	
	domChunk.each(function() {
		
		// find images inside element that need to be preloaded
		if (this.tagName == "A" || this.tagName == "DIV") {
			elems = $(this).find("img[@src*='_off.']"); // for A tags look for suitable child images
		} else {
			elems = $(this);
		}
		
		// preload them
		elems.each(function() {
			preloadSrc = (this.src).replace(/\_off\./, '_over.');
			preloadObj = new Image();
			preloadObj.src = preloadSrc;
		});
		
	});
}


/**
 * Function called by Cancel buttons
 */
function goCancel() {
	window.location.href = "account/My_Account.html";
}


/**
 * Setup Region+Country form element linking
 */
function setupRegionLinking() {

	var selectCountry = $("select.form-select-country")[0];
	var selectRegion = $("select.form-select-region")[0];
	var inputRegion = $("input.form-input-region")[0];
	var selectRegionRow = $(selectRegion).parent().parent();
	var inputRegionRow = $(inputRegion).parent().parent();
	var origCountry = selectCountry.value;

	// on page load:
	switch (origCountry) {
		case 'CA':
			//default, do nothing
			break;
		//update the options for US if selected
		case 'US':
			loadRegions(origCountry, selectRegion);
			break;
		//show the region field if Country is not US or CA
		default:
			$("tr.hidden").removeClass("hidden");	// un-hide the input field
			$(selectRegion).parent().parent().addClass("hidden");	// hide the select
	}
	////

	// update regions when user changes Country
	$(selectCountry).change(function() {
		var currentCountry = this.value;
		
		if (currentCountry=='CA' || currentCountry=='US') {

			if (selectRegionRow.hasClass("hidden")) {
				inputRegionRow.addClass("hidden");
				selectRegionRow.removeClass("hidden");
			}
			
			loadRegions(currentCountry, selectRegion);
			
		} else {
			if (inputRegionRow.hasClass("hidden")) {
				selectRegionRow.addClass("hidden");
				inputRegionRow.removeClass("hidden");
			}
		}
	});
	////
	
	// make sure only one region gets submitted
	$("form.tcaform").submit(function() {
		if (selectCountry.value == 'CA' || selectCountry.value == 'US') {
			inputRegion.value = '';
		} else {
			selectRegion.value = '';
		}
	});
	////
}


/**
 * 	Loads Regions for specified Country via AJAX into specified select element
 */
function loadRegions(countryCode, selectElem) {

	var tempStr = '';
	
	$(selectElem).empty();	// remove current region list
	$(selectElem).append('<option value="">Loading...</option>');		// add loading message
	
	$.getJSON("http://mike.devel:8080/tcanetworks.com/wire/geographic-regions/"+countryCode+".json", function(json) {
		$("select.form-select-region option").remove();		// remove loading message
		
		for (var i=0; i < json.length; i++) {	//re-populate list
			tempStr = '<option value="' + json[i].code + '">' + json[i].text + '</option>';
			$(selectElem).append(tempStr);
		}
	});
}







/* DAVE'S
----------------------------------------------------------------------------------------------------*/
sfHover = function() {
	if( document.getElementById("nav") ) {
		var sfEls = document.getElementById("nav").getElementsByTagName("div");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}


if (window.attachEvent) window.attachEvent("onload", sfHover);


/**
 *
 */
function confirmDelete() {
	return confirm('Are you sure you wish to delete this item?');
}
