// Rather than doing this in separate methods, do it once as a global for everything
var $j = jQuery.noConflict();

$j(document).ready(function(){
	// Apply the hover effect for item lists - this should probably be replaced with adding and removing a class rather then setting the style directly
	$j(".odd,.even").mouseover(function() {
		$j(this).css("backgroundColor", "#ccc");
	}).mouseout(function(){
		if ($j(this).hasClass("odd")) {
			$j(this).css("backgroundColor", "#eee");
	    }
		else {
			$j(this).css("backgroundColor", "#fff");
	}
    });
	
	// Apply rounded corners
	roundTheBoxes.init();
	
	applyHelpLinks();
	
	// Clear the search and category search boxes of their default values when they get focus
	$j(".clearTextBox, #cat-search, #search").focus(function() {
		var el = $j(this);
		if(el.val() === el.attr("defaultValue")) {
			el.val("");	
		}
	});
	
	
	// Handle anchor links on the page with a base href 
	$j("a[href^='\#']").each(function() {
		this.href = window.location.pathname + this.href.substr(this.href.indexOf('#'));
	});
});


/* Rounded cornering for OU panels */
var roundTheBoxes = {
init: function() {
	  var imgPath = '/shop/static/img/bgs/';
	  $$('*.softcorners').each(function(panel) {
	      if(!panel.hasClass('no-corners')) {
		  if(panel.getParent().hasClass('product-unwrapped-wrapper')) {
		      panel.addClass('bg');
		      roundTheBoxes.bottomCorners(imgPath,panel);
		  } else {
		      roundTheBoxes.allCorners(imgPath,panel);
		  }
	      }
	  });
      },
allCorners: function(imgPath,panel) {
	  (new Element('img').addClass('panel-tl').setProperties({'src':imgPath+'cat_panel_tl.png'}).injectInside(panel));
	  (new Element('img').addClass('panel-tr').setProperties({'src':imgPath+'cat_panel_tr.png'}).injectInside(panel));
	  var bl = new Element('img').addClass('panel-bl').setProperties({'src':imgPath+'cat_panel_bl.png'}).injectInside(panel);
	  var br = new Element('img').addClass('panel-br').setProperties({'src':imgPath+'cat_panel_br.png'}).injectInside(panel);
	  if(window.ie6 && panel.hasClass('home')) {
	      bl.setStyle('bottom','-1px');
	      br.setStyle('bottom','-1px');
	  }
      },
bottomCorners: function(imgPath,panel) {
	  (new Element('img').addClass('panel-bl').setProperties({'src':imgPath+'cat_panel_bl.png'}).injectInside(panel));
	  (new Element('img').addClass('panel-br').setProperties({'src':imgPath+'cat_panel_br.png'}).injectInside(panel));
      }
};

function PopUp(oLink) {
	oLink = oLink.href||oLink;
	window.open(oLink,
		    'mywin',
		    'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=0,width=450,height=450');
}

function decode_utf8(s) {
	// PC 04/06/09 - Google Chrome and Opera throw an error on calling decodeURIComponent, so ignore it and return the original string
	try {
		return decodeURIComponent(escape(s.replace(/\+/g, ' ')));
	} catch (error) {
	
	}
	return s.replace(/\+/g, ' ');
}

function decode_BasketCurrency(s) {
	// PC 04/06/09 - On Firefox, IE etc. we end up with a  character before the pound sign, but on chrome and opera we do not
	// which causes a JavaScript error that then stops all code running.
	//
	// The problem is ultimately to do with character encodings, shop.master has a meta tag that sets the encoding to utf-8.
	// I'm assuming that the server has a different encoding which is used when the cookie values are written although
	// I haven't checked this.
	
	// find the first occurrence of the pound character and return the contents of the string from that point onwards
	var pos = s.indexOf("\xa3");
	if (pos != -1 && pos > 0) {
		s = s.substr(pos);
	}
	return s;
}

var Basket = new function() {
    this.Msg = function() {
            var m = this.message;
            if (m) {
                    Cookie.set('BasketMsg', '', { path: '/shop', duration:-1 }); // mootools Cookie.remove is broken
            }
            return m?'<div id=\"basket-msg\">'+m+'</div>':'';
    };
    this.Total = function() {
		var t = this.total;
		return t?t:'';
    };
    this.Ship = function() {
           var s = this.shipping;
           return s?s:'';
    };
    this.Count = function() {
            var n = this.count;
            return ''+n+' item'+(n==1?'':'s');
    };
    this.Value = function() {
            var p = this.value;
            if (this.count > 0) {
				return p?'('+p+') ':'';
			}
            else {
				return '';
			}
    };
    var val = Cookie.get('BasketVal');
    this.message = decode_utf8(Cookie.get('BasketMsg')||'');
    var items = Cookie.get('BasketItems');
    var f = val?val.split('|'):[];
    var loggedin = "F";
    if (val && f.length==5) {
            this.count = f[0];
            this.value = decode_BasketCurrency(f[1]);//decodeURIComponent(escape(f[1]));
            loggedin = f[2];
            this.shipping = decode_BasketCurrency(f[3]);//decodeURIComponent(escape(f[3]));
            this.total = decode_BasketCurrency(f[4]);//decodeURIComponent(escape(f[4]));
    } else {
            this.count = 0;
            this.value = '\xa30.00';
            this.total = '\xa30.00';
            this.message = '';
            this.shipping = 'Free';
            items = '';
    }
   var css = "";
   if (items) {
	   css += '.atb_'+items.replace(/\|/g, ',.atb_') + 
	      "{background: no-repeat url(/shop/static/img/btns/btn_add-to-basket-off.gif);}\n";
	   // Apply a diffent add to basket button for the product details page.
	   css += 'div.department-details .atb_'+items.replace(/\|/g, ',.atb_') + 
	      "{background: no-repeat url(/shop/static/img/btns/btn_add_to_basket_off.gif);}\n";
	   css += '.atb_'+items.replace(/\|/g, ' a,.atb_') + " a," +
	          '.atb_'+items.replace(/\|/g, ' input,.atb_') + " input" +
	   " {visibility:hidden;}\n";
   }
   if (loggedin!="T") { css += " #myaccount-links a.logoutButton {display:none}\n #myaccount-links span.logout {display:none}"; }
   if (css) {
	   document.write("<style>"+css+"</style>");
   }
}();

var RecentlyViewed = new function() {
	this.Add = function(catalog, product) {
		var old = Cookie.get('RecentView') || '';
		var products = old.split(';');
		var newprod = catalog + '/' + product;
		var newlist = [];
		for (var i = 0; i < products.length; i++) {
		    var s = products[i];
			if (s && s != newprod) { newlist.push(s); }
		}
		if (newlist.length > 3) {
			newlist = newlist.splice(newlist.length-3, 3);
		}
		newlist.push(newprod);
		Cookie.set('RecentView',
		 newlist.join(';'),
		 { path: '/shop', duration: 28 });
	};
	this.View = function() {
		var rv = $('recentlyviewed');
		if (rv) {
			var seen = Cookie.get('RecentView') || '';
			if (seen) {
				var updater = new Ajax();
				updater.initialize('/shop/recentlyviewed.aspx?seen='+encodeURIComponent(seen),
				 { update: rv, method:'get'});
				updater.request();
			}
		}
	};
}();

function SetDerestrict(div,uid,lid,img)
{
	var drdiv = $(div);
	if (drdiv)
	{
		var dr=(drdiv.innerHTML=="0"?"1":"0");
		var updater = new Ajax();
		updater.initialize('setderestrict.aspx?u='+encodeURIComponent(uid)+'&l='+encodeURIComponent(lid)+'&d='+encodeURIComponent(dr),
					 { update: drdiv, method:'get', onComplete: function(response) { 
							if (response == "0" || response == "1") {
								var imgobj = document.getElementById(img);
								if (Number(response)) { imgobj.src="/shop/static/img/icons/icon_ticked.gif"; }
								else { imgobj.src="/shop/static/img/icons/icon_unticked.gif"; }
							}
						} 
					 });
		updater.request();
		
	}
	return false;
}

function clickButton(event,button)
{
	if (event.keyCode == 13)
	{
		var bt = document.getElementById(button);
		if (bt)
		{
			bt.click();
			return false;
		}
	}
}

function swallowEnter(event)
{
	if(event.keyCode==13)
	{
		event.keyCode = null;
		return;
	}
}

function confirmDelete(item, mesg)
{
    return confirm(mesg);
}



function showURLPopup(event, href) {
	jQuery.facebox(function() {
		ajaxRequest(href, {}, "An error occurred loading page: ", function(data) {		
			jQuery.facebox(data);
		}, function() {
			jQuery(document).trigger('close.facebox');
		});
	});

	event.returnValue = false;
	return false;
}

function applyHelpLinks() {
	$j("a[class*=help-link]").unbind("click").click(function(event) {
		showURLPopup(event, $j(this).attr("href"));

		return false;
	});
}
// Standard ajax request that doesn't block the UI, but does standard error handling etc.
function ajaxRequest(url, options, errorMsg, successFunction, errorFunction) {
	$j.ajax({
      type: "POST",
      url: url,
      data: options,
      // Ajax error handler
      error: function(xhr, status, error) {

		// Handle HTTP redirects - normally we should never get these as the browser should handle them automatically, however
		// IE doesn't always seem to do this which I think is security related going from HTTPS to HTTP url
		if (status == 301 || status == 302 || status == 303 || status == 307) {
			var loc = xhr.getResponseHeader('Location');
			if (loc !== null && loc !== "") {
				return ajaxRequest(loc, options, errorMsg, successFunction, errorFunction);
			}
		}
		else {
			if (errorMsg.length > 0) {
				if (errorFunction) {
					errorFunction();
				}
	        
				if (xhr.responseText.indexOf(errorConstants.AJAX_ERROR) != -1) {
					errorMessage("Error (" + xhr.status + ")", errorMsg + xhr.responseText.substr(errorConstants.AJAX_ERROR.length), 10000);
				}
				else {
					errorMessage("Error (" + xhr.status + ")", errorMsg + xhr.responseText, 10000);
				}
			}
			// return the error message to the calling function
			return xhr.responseText;
		}
      },
      // Ajax success handler
      success: function(responseText, textStatus) {
		// Otherwise assume success
		if (!handleAjaxResponse(responseText, errorMsg)) {
			if(successFunction) {
				if (responseText.indexOf(errorConstants.AJAX_SUCCESS) != -1) {
					successFunction(responseText.substr(errorConstants.AJAX_SUCCESS.length));
				}
				else {
					successFunction(responseText);
				}
			} 
			
			// return null to the caller to indicate success
			return null;
		}
      }
    });
}

var errorConstants = {
	AJAX_SUCCESS : "success:",
	AJAX_WARNING : "warning:",
	AJAX_ERROR : "error:",
	AJAX_REDIRECT : "redirect:",
	
	productListUrl : "/esi/unwrappedlist.aspx",
	productDetailsUrl : "/esi/productdetails.aspx"
};

function errorMessage(title, message, timeout) {
	var $m = $j('<div class="growlUIError"></div>');
	if (title) { $m.append('<h1>'+title+'</h1>'); }
	if (message) { $m.append('<h2>'+message+'</h2>'); }
	if (timeout === undefined) { timeout = 3000; }
    $j.blockUI({
		message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout: timeout, showOverlay: false,
		css: $j.blockUI.defaults.growlCSS
    });
}

function handleAjaxResponse(responseText, errorMsg) {
	if (handleAjaxRedirect(responseText) || handleAjaxError(responseText, errorMsg)) {
		return true;
	}
	
	return false;
}

function handleAjaxRedirect(responseText) {
	if (responseText.indexOf(errorConstants.AJAX_REDIRECT) != -1) {
		document.location.href = responseText.substr(errorConstants.AJAX_REDIRECT.length);
		
		return true;
	}
	
	return false;
}

function handleAjaxError(responseText, errorMsg) {
	if (responseText.indexOf(errorConstants.AJAX_ERROR) != -1) {
		if (errorMsg.length > 0) {
			errorMessage("Error", errorMsg + responseText.substr(errorConstants.AJAX_ERROR.length), 10000);
		}
		
		return true;
	}
	
	return false;
}
