// Define our object for keeping track of what's going on.
document.shop = { searchParams : [], bnPath : '', pageNo : '' };

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();
	$('.filter_by').bind('change', updateFilters);
	
	// If this is a browse page, then load the search.
	if ($('#OrderBy')) {
		parseURL();
		
		$('#SortOrder').bind('change', function(e) {
			document.shop.searchParams.s_sort = $(e.target).val();
			newURL();
		});
	}
	
	$('#ShippingRate').bind('change', function(e) {
			var theURL = 'http://'+document.shop.fullDomain+'/cart/change_shipping/';
			theURL = theURL+$('#ShippingRate').val();
			window.location.href = theURL;
		});
	
	// 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();
	});
	
	
	// Lightbox for galleries.
	$('#Gallery 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'
	});
	
	// Track payments and ecommerce transactions.
	$('#GoogleCheckout input').bind('click', function (e) { ecomTrack('Google') });
	$('#PayPalButton').bind('click', function (e) { ecomTrack('Paypal') });

	
	
}); // end of all the initialisation stuff that needs to run once the page is loaded.

if (typeof tinyMCE != 'undefined') {
	tinyMCE.init({
		theme : 			'advanced',
		mode: 				'textareas',
		editor_selector: 	'html_edit',
		convert_urls: 		false,
		content_css : 		'/theme/tiny.css'
	});
}

function confirmDelete() { return confirm('sure about that?'); }

function setSite() {
	$.cookie('editing', $('#SiteSelector :select').val(), {domain: myDomain, expires: 300, path: '/'});
}

function updateFilters() {
	// Hardwire this as a category filter for now, but leave the semantics open.
	window.location.href = 'http://'+document.shop.fullDomain+'/admin/'+$('#filter_root').val()+'/cat:'+$('#cat').val();
}

// 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;
}

// Google ecommerce tracking.
function ecomTrack(paymentProvider) {
	try {
		pageTracker._trackPageview('/checkout/payment/');
		pageTracker._addTrans(ecomCart.Id, paymentProvider, ecomCart.Total, ecomCart.Tax, ecomCart.Shipping, '', '', '');
		$.each(ecomItems, function (key, item) { pageTracker._addItem(item.OrderId, item.ItemId, item.Name, item.Category, item.Price, item.Quantity); });
		pageTracker._trackTrans();
	} catch (err) {}
}




