var core = {

	init: function() {
		$.historyInit(core.pageload);

		core.ajaxinits();

		core.scrollinits();

		//core.jqzoominits();

		core.basketinits();

		core.innerfadeinits();
		
		core.homepagefades();

	},

	productsclick: function(pagehash) {
		// Tried calling loadContent directly but didn't work.. no idea why.
		$('.load').remove();
		$('#productajax').fadeOut('def', function() { 
			core.loadContent(pagehash);
		});
		return false;
	},

	loadContent: function(pagehash) {
		// insert loading animation here.
		// moves to a new page. 
		// pageload is called at once. 
		// hash don't contain "#", "?"
		var hash = pagehash.replace(/^.*#/, '');
		$.historyLoad(hash);
	},

	pageload: function(hash) {
		// alert('pageload: ' + hash);
		// hash doesn't contain the first # character. It's removed by the historyinit function.
		if(hash) {
			$('.jqZoomWindow').remove();
			// restore ajax loaded state
			// Fix for IE
			if($.browser.msie) {
				hash = encodeURIComponent(hash);
			}

			var hashSplit = hash.split('-');
			if (hashSplit[0] == 'product') {
				var toLoad = '?page=' + hashSplit[0] + '&product=' + hashSplit[1] + ' #productsection';
				$('#productajax').load(toLoad,'', function() {
					document.title = 'An English Hand \u00BB Products \u00BB ' + hashSplit[1];
					core.innerfadeinits();
					//$('.scrollable').remove();
					var cellPosition = $('.scrollable-container').position();
					// alert(cellPosition.left);
					// alert(cellPosition.top);
					var offsetleft = 0 - cellPosition.left;
					var offsettop = 0 - cellPosition.top;
					$('div.scrollable').scrollable({
						item: 'a',
						size: 4,
						hoverClass: 'hover',
						clickable: false,
						easing: 'custom',
						speed: 1000
					}).navigator().find('a').tooltip({
						tip: '#tooltip',
						//effect: 'slide',
						//slideOffset: 30,
						// offset: [30, 90],
						offset: [offsettop, offsetleft]
						// relative: true
					});
				});
			} else if (hashSplit[0] == 'productdetails') {
				if (hashSplit[2] != undefined) {
					var colourid = '&productcolourid=' + hashSplit[2];
				} else {
					var colourid = '';
				}

				var toLoad = '?page=' + hashSplit[0] + '&productid=' + hashSplit[1]  + colourid + ' #product-details-main';
				$('#productajax').load(toLoad,'', function() {
					var productname = $('#product-details h1').text();
					document.title = 'An English Hand \u00BB ' + productname;
					core.swapimginits();
					core.jqzoominits();
				});
			}
		} else {
			// start page
			// $('#productajax').empty();
		}
	},


	// Might have to use the init instead and set a event/load thing
	// showNewContent: function() {
		// alert('test');
		//$('#productajax').fadeIn('slow');
	// },


	ajaxinits: function() {
		$('#productajax').ajaxSend(function(evt, request, settings) {
			// $('#contentarea').append('<li>Starting request at ' + settings.url + '</li>');
			$('#loadingholder').prepend('<div class="load">LOADING...</div>');
		});

		$('#productajax').ajaxSuccess(function(evt, request, settings) {
			// $(this).append('<li>Successful Request!</li>');
			$('.load').remove();
			$('#productajax').fadeIn('def');
		});
	},


	scrollinits: function() {
		$.easing.custom = function (x, t, b, c, d) {
			return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
		}

	},

	jqzoominits: function() {
		//var events = $('.jqzoom').data("events");
                if(!$.browser.safari) {
		  $('.jqzoom').unbind(); // Also a problem for safari
                }
		//$('.jqzoom').removeAttr('style'); // This is a problem for safari
		if ($(".jqZoomWindow").length != 0) $(".jqZoomWindow").remove();
		if ($(".jqZoomPup").length != 0) $(".jqZoomPup").remove();

		// $('.preload').remove();
		var jqzoptions =
		{
			zoomWidth: 458,
			zoomHeight: 318,
			position: 'left',
	                yOffset: 0,
        	        xOffset: 10,
                	showEffect:'fadein',
	                hideEffect:'fadeout',
        	        fadeoutSpeed: 'slow',
			title: false
		}


		$('.jqzoom').jqzoom(jqzoptions);
		//$('.jqzoom').bind('jqzoom', jqzoptions);
	},

	changeProductImage: function (newimageurl) {
		// alert(newimageurl);
		$('.preload2').remove();
		// Remember to not use &amp; for new src in javascript.
		var newurl = '/libs/image.php?width=239&height=318&image=' + newimageurl;
		if ($('#pimage-wrap').find('img').attr('src') != newurl) {
			var imgnew = new Image();
			var zoomedImg = new Image();
			var divwrap = $('#pimage-wrap');
			var imgwrap = divwrap.find('img').fadeTo('medium', 0.5, function() {
				$(imgnew).load(function () {
					imgwrap.fadeTo('fast', 1);
					divwrap.find('img').attr('src', newurl);
					divwrap.find('a').attr('href', newimageurl);
					$('#pimage-wrap').append('<div class="preload2">Loading zoom</div>');
					$(zoomedImg).load(function () {
						core.jqzoominits();
						$('.preload2').remove();
						// $('.jqzoom').trigger('mouseleave'); No longer needed :-}
					}).attr('src', newimageurl);
				}).attr('src', newurl);
			});
		}
		return false;
	},

	changeProductThumbs: function (thumbslist, productid, productcolourid) {
		var thumbsArray = thumbslist.split(':');
		// Change the main product image to the first thumb.
		core.changeProductImage(thumbsArray[0]);
		core.changeProductSizeList(productid, productcolourid);
		// Have to make all variables in the foreach loop into arrays so that the load callback can identify them uniquely.
		var newSRCURL = [];
		var thumbToChange = []; // A html img tag id
		var thumbLinkToChange = []; // A html a tag id
		var thumbVal = []; // Just the direct path of the thumbnail image file
		var thumbOnClick = []; // The direct path of the thumbnail image file inserted into onclick statement
		var newclick = [];
		var thumbImg = []; // Javascript preload image.
		$.each(thumbsArray, function(i, val) {
			thumbImg[i] = new Image();
			// Remember to not use &amp; for new src in javascript.
			newSRCURL[i] = '/libs/image.php?width=53&height=70&image=' + val;
			thumbVal[i] = val;
			thumbToChange[i] = '#thumb' + i;
			thumbLinkToChange[i] = '#thumbLink'  + i;
			if ($(thumbToChange[i]).attr('src') != newSRCURL[i]) {
				var imgFade = $(thumbToChange[i]).fadeTo('medium', 0.5, function() {
					$(thumbImg[i]).load(function () {
						imgFade.fadeTo('fast', 1);
						$(thumbToChange[i]).attr('src', newSRCURL[i]);
						//$(thumbLinkToChange[i]).attr('href', thumbVal[i]);
						// Need to unbind the current click event before we bind a new one.
						$(thumbLinkToChange[i]).unbind();
						$(thumbLinkToChange[i]).click(function() {
							return core.changeProductImage(thumbVal[i]);
						});
					}).attr('src', newSRCURL[i]);
				});
			}
		});
		return false;
	},

	changeProductSizeList: function (productid, productcolourid) {
		var toLoad = '?page=productdetails&productid=' + productid + '&productcolourid=' + productcolourid +' #p-size-div';
		$('#p-size-div-ajax').load(toLoad,'', function() {
			// Init something on ajax load?
		});
	},

	swapimginits: function() {
		$('.thumbsaclass').click(function() {
			var imgSrcAttr = $(this).find('img').get(0).src;
			var srcsub = imgSrcAttr.split('=');
			// alert(imgSrcAttr);
			// alert(srcsub[3]);
			return core.changeProductImage(srcsub[3]);
		});
	},

	ajaxaddtobasket: function() {
		$.post("?page=basket&addtobasket=true", $("#addtobasketform").serialize(),
			function(data){
				//alert('\'' + data + '\'');
				var ajaxresponse = jQuery.trim(data);
				var ajaxresponseSplit = ajaxresponse.split(':');
				if (ajaxresponseSplit[0] == 'success') {
					var productname = $('#product-details h1').text();
					$('#shoppingitems a').html(ajaxresponseSplit[1] + ' Items £' + ajaxresponseSplit[2]);
					$('#main').append('<div id="dialog" title="Added to basket"><p style="text-align: center; padding: 10px 0px 0px 0px;">' + productname + ' added to your shopping basket.</p></div>');

					$("#dialog").dialog({
						autoOpen: true,
						bgiframe: true,
						modal: true,
						buttons: {
							'Continue Shopping': function() {
								$('.dialog').remove();
								$(this).dialog('close');
							},
							'Go To Basket': function() {
								$('.dialog').remove();
								window.location = "?page=basket"
								$(this).dialog('close');
							}
						}
					});

				}
			}, "text");
		return false;
	},

	ajaxmoredetails: function(theproductid) {
		$.get("?page=moredetails", { productid: theproductid },
			function(data){
				// alert('\'' + data + '\'');
				var productname = $('#product-details h1').text();
				$('#main').append('<div id="dialog" title="' + productname + '">' + data + '</div>');

				$("#dialog").dialog({
					autoOpen: true,
					bgiframe: true,
					modal: true,
					buttons: {
						Close: function() {
							$('.dialog').remove();
							$(this).dialog('close');
						}
					}
				});
			});
		return false;
	},

	innerfadeinits: function() {
		$('ul#producttypeimages').innerfade({
			speed: 1000,
			timeout: 5000,
			type: 'sequence',
			containerheight: '198px'
		});
		
		$('ul#philosophyimages').innerfade({
			speed: 1000,
			timeout: 5000,
			type: 'sequence',
			containerheight: '262px'
		});
	},

	basketinits: function() {
		$('.deleteitembutton').click(function() {
			$(this).parents('tr').fadeOut('normal', function() {
				$(this).remove();
			});
		});
	},
	
	homepagefades: function() {
		$("#homecufflinks").hide();
		$("#homebelts").hide();
		$("#hometies").hide();
		$("#homeluggage").hide();
		$("#homeluggagetitle").hide();

		$('#homecufflinks').fadeIn('slow', function() { 
			$('#homebelts').fadeIn('slow', function() { 
				$('#hometies').fadeIn('slow', function() { 
					$('#homeluggage').fadeIn('slow');
					$('#homeluggagetitle').fadeIn('slow');
				});
			});
		});
		
	}
	
}