// Define our object for keeping track of what's going on.
document.shop 				= { searchParams : [], bnPath : '', pageNo : '' , trackers : []};
document.shop.domain 		= document.domain.replace(/.*?\.?([^.]+\.(com|co.uk|net|l))/, ".$1");
document.shop.fullDomain 	= document.domain.replace(/(.+\.(com|co.uk|net|l)\/).*/, "$1");


$(document).ready(function () {

	// Admin stuff.
	$('.control_delete').bind('click', confirmDelete);
	$('#edit_tabs').tabs();
	
	/* if (typeof tinyMCE != 'undefined') {
		tinyMCE.init({
			theme : 			'advanced',
			mode: 				'textareas',
			editor_selector: 	'html_edit',
			convert_urls: 		false
		});
	} */
	
	
	// Lightbox and click tracker for galleries.
	$('#Images a').lightBox({
		imageLoading:			'/css/images/lightbox-ico-loading.gif',
		imageBtnPrev:			'/css/images/lightbox-btn-prev.gif',
		imageBtnNext:			'/css/images/lightbox-btn-next.gif',
		imageBtnClose:			'/css/images/lightbox-btn-close.gif',
		imageBlank:				'/css/images/lightbox-blank.gif'
	});
	
	// Internal JS action goals for google optimizer.
	if (typeof(homeGoals) != "undefined") {
		$.each(homeGoals, function(i, g) { 
			$(g.Target).bind(g.Action, function (e) {
				if (! document.shop.trackers['t'+g.Code]) { // only run once per action.
					document.shop.trackers['t'+g.Code] = 1;
					testTracker._trackPageview('/'+g.Code+'/goal');
				}
			});
		});
	}
	

	// If this is a browse page, then load the search.
	if ($('#OrderBy').length > 0) {
		parseURL();
		
		$('#SortOrder').bind('change', function(e) {
			document.shop.searchParams.s_sort = $(e.target).val();
			newURL();
		});
	}
	
	// If it's a detail page, or some other one with an order form then load up the option selectors.
	if ($('#PurchaseForm').length > 0) {
		setOptions(window.itemOptions);
		
		$('select.p_opt').change(function(e) {
			scanOptions($(e.target).attr('id'), $(e.target).val(), window.itemOptions, false);
		});
		
		$('#PurchaseForm').bind('submit', function (e) {
			pageTracker._trackPageview('/cart/add/');
		});
	}
	
	$('#CheckoutLink').bind('click', function (e) {
		try {
			pageTracker._trackPageview('/cart/checkout/');
			pageTracker._addTrans(ecomCart.Id, ecomCart.Affiliation, ecomCart.Total, '', '', '', '', '');
			$.each(ecomItems, function (key, item) { pageTracker._addItem(item.OrderId, item.ItemId, item.Name, item.Category, item.Price, item.Quantity); });
			pageTracker._trackTrans();
		} catch (err) {}
	}); 
	
	// Track the outbound link links to amazon.
	$('#AmazonBuy a').bind('click', function (e) {
		try {
			var clickedLink = $(e.target).attr('id');
			pageTracker._trackPageview('/link/'+clickedLink);
		} catch (err) {}
	}); 
		
	
	// When the search box is used, create a URL based on the search and redirect to it.
	$('#SearchForm').bind('submit', function (e) {
		var newSearchParams = { s_sort : document.shop.searchParams.s_sort };// Remember the last order method?
		newSearchParams.s_kw = $('#search_keywords').val();
		document.shop.searchParams = newSearchParams; // Over-write any existing filters as this is a new search.
		document.shop.bnPath = $('#search_domain').val();
		newURL();
		e.preventDefault();
	}); 
	
	// Merge in new custom price sort options -- To add.
	
	
	
}); // end of all the initialisation stuff that needs to run once the page is loaded.






function confirmDelete() { return confirm('sure about that?'); }


function setSite() {
	$.cookie('editing', $('#SiteSelector :select').val(), {domain: document.shop.domain, expires: 300, path: '/'});
}


// Parse the current URL (if this is a browse/search page) and split it into its elements - path, search/filters, page number.
function parseURL() {
	pathArray = window.location.pathname.split('/');
	var foundSearch, currentSearchIndex = '';
	var bnPath = '/';
	
	for (var i=0; i < pathArray.length; i++) {
		if (pathArray[i]) { // Split seems to create initial and terminal blanks for some reason.
			if (foundSearch) {
				if (pathArray[i].indexOf(':') > 0) { 
					rawSearchArray = pathArray[i].split(':');
					for (var j=1; j <= rawSearchArray.length; j++) {
						if (j % 2) { currentSearchIndex = rawSearchArray[j-1]; } 
						else       { document.shop.searchParams['s_'+currentSearchIndex] = rawSearchArray[j-1];	} // need that s_ to avoid conflict with sort()
					}

					
				} else { document.shop.pageNo = pathArray[i] * 1; }
				
			} else {
				if (pathArray[i] == '-') { foundSearch = true; }
				else { bnPath = bnPath+pathArray[i]+'/'; }
				
			}
		}
	}
	
	if (bnPath) document.shop.bnPath = bnPath;					
}


// Take all the current state data, create a new URL from it, and go there.
function newURL() {
	var searchURL = '';
	var theURL = 'http://'+document.shop.fullDomain+document.shop.bnPath;

	for (var key in document.shop.searchParams) { 
			if (document.shop.searchParams[key]) { // Don't encode blank values.
				searchURL = searchURL+encodeURIComponent(key.substr(2))+':'+encodeURIComponent(document.shop.searchParams[key])+':'; 
			}
	}
	
	if (searchURL.length > 0) {	theURL = theURL+'-/'+searchURL.substr(0, searchURL.length -1)+'/';	}
	
	if (document.shop.pageNo > 0) theURL += document.shop.pageNo;

	window.location.href = theURL;
}

function scanOptions(findKey, findVal, theOptions) {
	$.each(theOptions, function(key, val) {
		$.each(val, function(subKey, subVal) {
			if (key == findKey && subKey == findVal) { // If we are at the right option level, and this is the one selected then set the following combo-boxes/ASIN field.
				setOptions(subVal);
				return;
			} else if ($('#'+key).val() == subKey) { // This is the selected value for this option, recurse/descend here.
				scanOptions(findKey, findVal, subVal)
			}
		});
	});
}

function setOptions(theOptions) {
	var optionHTML = quantityHTML = '';
	var first = 0;
	var allowed_quantity = 20;
	$.each(theOptions, function(key, val) { // There should only every be one of these.					
		if (key == 'ASIN') { // End of the run, set the product selected in the hidden field.
			if (typeof(val) != 'string') { // sometimes there is more than one ASIN for a variation, just find the cheapest for now.
				var lowestSoFar = val[0];
				$.each(val, function (i, a) {
					if (itemOffers[a].PR < itemOffers[lowestSoFar].PR) { lowestSoFar = a }
				});
				val = lowestSoFar;
			}
				
			$('#OID').val(itemOffers[val].OI);
			$('#SelectedPrice').html(itemOffers[val].PR);
			$('#Availability').html(itemOffers[val].AV);
			if (itemOffers[val].SS > 0) { $('#SuperSaver').show(); } else { $('#SuperSaver').hide(); }
			if (itemOffers[val].QA > 0) { 
				$('#InStock').html('<b>In Stock:</b> '+itemOffers[val].QA).show(); 
				allowed_quantity = Math.min(allowed_quantity, itemOffers[val].QA);
			} else { $('#InStock').hide(); }
			
			for (quant = 1; quant <= allowed_quantity ; quant++) {
				quantityHTML = quantityHTML+'<option value="'+quant+'">'+quant+'</option>';
			}
			
			$('#Quantity').html(quantityHTML);
			
		} else {
			$.each(val, function(nextKey, nextVal) {
				if (first++ == 0) { // If this is the first option then set the next combo-box with its values.
					setOptions(nextVal);
				}
				optionHTML = optionHTML+'<option value="'+nextKey+'">'+nextKey+'</option>';
			});
			
			$('#'+key).html(optionHTML);
		}
	});
}
