/**
 * @author Sam Cartwright
 */

	/***********************************************************************************************
	
		Large Images Scripts
	
	***********************************************************************************************/
	/***********************************************************************************************
	FUNCTION OVERLAY
	Overlay is the main function in this script, at present it creates the basic HTML structure of 
	the overlay, then it detects the URL of the image  currently displayed and rewrites it to give 
	the large image then it adds this to the #largeImage SRC and appends the lot to the DOM in the 
	body tag.
	
	OBJECTS CREATED
	* #overlay - the grey, semi-opaque background which covers the whole page
		* #largeImageWrapper - scrollable wrapper for the image to sit in
			* #largeImageTitleBar - a title bar which contains buttons
				* #closeOverlay - button which cancels the overlay
			* #largeImage - The Large Image itself
	
	***********************************************************************************************/
	function overlay(){
		//Build Overlay
		$overlay = $('<div id="overlay"><div><div id="largeImageWrapper"><div id="largeImageTitleBar"><img src="/mm5/graphics/largeImage/close2.png" id="closeOverlay"></div><img id="largeImage"></div></div></div>');
		
		//photo URL retrieval and rewritind
		imageURL = $('#mainimage>div:first>img:first').attr('src');
		imageURLArray = imageURL.split("-");
		imageIdentifier = imageURLArray[imageURLArray.length-1].split(".");
		imageIdentifier = imageIdentifier[0];
		imageURLArray.splice(imageURLArray.length-1, 1);
		
		
		if(imageIdentifier.match(/m[0-9]/i)){
			imageIdentifier = imageIdentifier.replace(/m/i, "F");
			imageURL = imageURLArray.join("-");
		} else {
			imageIdentifier = "F1";
			imageURL = imageURL.substring(0, imageURL.length-4);
		}
		imageURL = imageURL + "-" + imageIdentifier + ".jpg";		
		
		$overlay.find('#largeImage').attr("src", imageURL);

		//append overlay and adjust for IE users
		$('body').append($overlay);
		
		if($('#overlay').css('position') == 'absolute'){
			$('#overlay').height($(document).height());
			$('#overlay').css('padding-top',$('body').scrollTop() + 15);	
			$('#overlay>div').height($(window).height() - 30);
		}
		$('#overlay').show();
		

	};
	/***********************************************************************************************
	FUNCTION RESIZE
	This function ensures that the image never overflows the sides of the #largeImageWrapper Box
	
	***********************************************************************************************/	
	function resize(){
		largeImageWidth = $('#largeImage').width();
		largeImageWrapperWidth = $('#largeImageWrapper').width();
		if(largeImageWidth > largeImageWrapperWidth){
			$('#largeImage').css('width', '730');
		}
	};
	
	/***********************************************************************************************
	FUNCTION LARGEIMAGES
	This function sets up the page with the large image controlls and defines the most basic event 
	handling.
	
	OBJECTS CREATED
	* #enlargeSmall - The text version of the click to enlarge control
	
	***********************************************************************************************/
	function largeImages(){
		$('#mainimage').addClass('hasLargeImage').append('<p style="text-align: center;"><a href="javascript:;" id="enlargeSmall" onclick="javascript:pageTracker._trackEvent(\'content\', \'image actions\', \'enlarge\');"><img src="/mm5/graphics/largeImage/enlargeSmall.png" style="margin-right: 5px; position: relative; top: 5px;">Click to Enlarge Image</a></p>');

		$('body').click(function(event){
			if ($(event.target).is('#overlay, #closeOverlay')) {
				$('#overlay').remove();
			}else if ($(event.target).is('#enlargeImage, #enlargeSmall, #mainimage img')){
				overlay();
				resize();
			}
		});
	};
	
	
	/***********************************************************************************************
	FUNCTION MM_openBrWindow
	opens a new browser window. god know why it has such a stupid name
	
	OBJECTS CREATED
	* new window
	* 
	***********************************************************************************************/

	function MM_openBrWindow(theURL,winName,features) { //v2.0
		window.open(theURL,winName,features);
	};

	/***********************************************************************************************
	FUNCTION TEXTBOXDEFAULTS
	makes default text in search and other boxes disappear on click events.

	
	***********************************************************************************************/

	function textBoxDefaults(){
		var active_color = '#1A1A1A'; // Colour of user provided text
		var inactive_color = '#999'; // Colour of default text
		$("input.default-value").css("color", inactive_color);
		var default_values = new Array();
		$("input.default-value").focus(function(){
			if (!default_values[this.id]) {
				default_values[this.id] = this.value;
			}
			if (this.value == default_values[this.id]) {
				this.value = '';
				this.style.color = active_color;
			}
			$(this).blur(function(){
				if (this.value == '') {
					this.style.color = inactive_color;
					this.value = default_values[this.id];
				}
			});
		});
	};

	
	
	/***********************************************************************************************
	FUNCTION categoryPageHoverBehaviour
	makes category page li elements clickable and adds border highlight
	
	***********************************************************************************************/
	function categoryPageHoverBehaviour(){
		$('#productlist li, #subCatList li').hover(function(){
			$(this).css({
				'border': 'solid 2px #666666',
				'cursor': 'pointer'
			});
		}, function(){
			$(this).css({
				'border': 'solid 2px #CCCCCC'
			});
		});
		$('#productlist li, #subCatList li').click(function(event){
			window.location = $(this).find('a:first').attr('href');
		});
	}

/****************************************************************************************
 * 
 * 	Lovely compact swap image script we use now.
 * 
 ***************************************************************************************/

function update(url,index,isSuper) {
document['PhotoBig'].src=url;
}


/****************************************************************************************
 * 
 * 	Home page scripts
 * 
 ***************************************************************************************/
function homePageBuilder(){

	$('#miniFeed>ul>li>a').click(function(event){
		$(this).siblings('div').slideToggle('fast');
		
		$expander = $(this).find('img');
		
		$expander.each(function(){
			if ($(this).attr('src') == "http://www.facewest.co.uk/dev/newTemplate/images/expand.gif" || $(this).attr('src') == '/dev/newTemplate/images/expand.gif') {
				$(this).attr('src', 'http://www.facewest.co.uk/dev/newTemplate/images/contract.gif');
			}
			else {
				$(this).attr('src', 'http://www.facewest.co.uk/dev/newTemplate/images/expand.gif');
			};
		});
		
	});
	$('#infoLinks a').eq('1').attr('href', 'https://secure.facewest.co.uk/facewest/mm5/merchant.mvc?Screen=OINF&Store_Code=fw');
	
	$("a.tab").click(function(event){
		event.preventDefault();
		$(".active").removeClass("active");
		$(this).addClass("active");
		$(".banner").hide();
		
		var content_show = $(this).attr("title");
		$("#" + content_show).fadeIn("fast");
		
		
	});
	
}
/****************************************************************************************
 * 
 *  Status Bellows controls the behaviour of the STATUS page
 * 
 ***************************************************************************************/


function statusBellows(){
	$('.expander').hide();
	
	hash = parent.location.hash;
	if (hash != "#1" && hash != "#" && hash != "") {
		hash = hash.substring(1, hash.length - 1);
		$('#' + hash + ' .expander').show();
	}
	
	$('#status>li>a').click(function(event){
		if($(this).siblings('.expander').is(':visible') == true){
		 $(this).siblings('.expander').slideUp();
		 parent.location.hash = 1;
		 } else {
		$(this).siblings('.expander').slideDown();
		$(this).closest('li').siblings('li').children('.expander').slideUp();
		parent.location.hash = $(this).closest('li').attr('id') + "1";
		
		}
	});
	
	$('#informationMenu ul a').click(function(event){
		if ($('#status').size() > 0) {
			$('.expander').hide();
			hash = event.target.hash;
			window.location.hash = hash;
			hash = hash.substring(1, hash.length - 1);
			$('#' + hash + ' .expander').slideDown();
			return false;
		}
	});
}		



/****************************************************************************************
 * 
 * 	Currency Swap Display code
 * 
 ***************************************************************************************/

$(document).ready(function(event){
	var loc = false;
	var currency;
	countryCookie = $.cookie('country');
	currencyCookie = $.cookie('currency');
	$loader = $('<div id="ajaxLoader"><img/></div>').find('img').attr('src', '/dev/ajax-loader.gif');
	
	/********** Find the client's location *************/
	
	if(countryCookie){
		loc = countryCookie;
	}
	else if (google.loader.ClientLocation) {
      var loc = google.loader.ClientLocation;
      loc= loc.address.country_code;

    }
	
	/************* Build display message ***************/
	if (loc == 'GB') {
		if (!currencyCookie) {
			currency = 'GBP';
		} else {
			currency = currencyCookie;
		}
		$('#currencySwitch').html('<h4><img src="http://www.facewest.co.uk/countries/GB.png"> Free UK Shipping, prices in ' + currency + '</h4><a href="javascript:;"><p>Set shipping charges and currency</p></a>');
		
	 } else if (countryCookie && currencyCookie) {
			$('#currencySwitch').html('<h4>Shipping Country: <img src="http://www.facewest.co.uk/countries/' + loc + '.png" class="shippingCountry"> Currency: ' + currencyCookie + '</h4><a href="javascript:;"><p>Set shipping charges and currency</p></a>');
			currency = currencyCookie;
	 } else {
	 	$('#currencySwitch').html('<h4>International information</h4><a href="javascript:;"><p>Set shipping charges and currency</p></a>');
		currency = 'GBP';
	 };
	/************** Add event listener to launch currency Modal *************/
    $('#currencySwitch a, a.currencySwitch ').click(function(event){
		pageTracker._trackEvent('Header', 'currency', 'currencySwitchModal');
		$('body').append($loader);
		
        currencySwitchBox(loc, currency);
    });
});





function currencySwitchBox(clientLocation, clientCurrency){    
	if ($('#currencyModal').size() == 0) {
		/******************* Initialise variables ************************/
		/* jQuery Objects */
		var $currencySelects;
		var $countrySelects;
		var $currencyModal;
		/* Objects */
		var countriesArray = [];
		var currenciesArray = [];
		/* Variables */
		var countrySelected;
		var currencySelected;
		var country;
		var currency;
		var shippingRate;
		/* Maths Constants */
		var VATRate = 1.175;
		
		/******************** Library functions ************************/
		function currencyFilter(element, index, array){
			return (element.code == currencySelected)
		}

		function countryFilter(element, index, array){
			return (element.name == countrySelected || element.code == countrySelected)
		}
		
		function getCountry(array){
			try {
				country = array.filter(countryFilter);
			} catch(err){
				country = array.filterArray(countryFilter);
			}
			return country[0];
		}
		function getCurrency(array){
			try {
				currency = array.filter(currencyFilter);
			} catch(err){
				currency = array.filterArray(currencyFilter);
			}
			return currency[0];
		}
		
		
		/******************** Make Ajax Calls ****************************/
		
		$.getJSON("/mm5/merchant.mvc?Screen=JSONCountries", function(data){
			countriesArray = data.countries;
			return countriesArray;
		});
		$.getJSON("/mm5/merchant.mvc?Screen=JSONCurrencies", function(data){
			currenciesArray = data.currencies;
			return currenciesArray;
		});
		
		/********************* Build Currency Modal **********************/
		$("body").ajaxComplete(function(request, settings){
			
			$('body').append(settings);
			
			$('#ajaxLoader').remove();
			if (countriesArray.length > 0 && currenciesArray.length > 0 && $('#currencyModal').size() == 0) {
				/* Basic Structure */
				$currencyModal = $('<div id="currencyModal" style="background-color: #ffffcc;"><form><h4>Currency selection</h4> <a href="javascript:;" ><img src="/dev/currencySwitch/closeCurrencyModal.png" id="closeCurrencyModal"></a><input type="image" alt="Select options" id="currencyModalSubmission" src="https://secure.facewest.co.uk/facewest/mm5/graphics/buttons/continue.jpg"></form><div id="currencyModalShippingInfo" /></div>');
				/* Select box for countries */
				$countrySelects = $('<p>My shipping country is: <select name="country"><option value="invalid">[select shipping country]</option></select> <a href="javascript:;" class="tooltipTrigger"></a></p>');
				$.each(countriesArray, function(i, country){
					$countrySelects.find('select').append('<option value="' + country.code + '" class="country">' + country.name + '</option>');
				});
				/* Select Box for currencies */
				$currencySelects = $('<p>My preferred display currency is: <select name="currency"><option value="invalid">[select currency]</option></select> <a href="javascript:;" class="tooltipTrigger"></a></p>');
				$.each(currenciesArray, function(i, currency){
					$currencySelects.find('select').append('<option value="' +  currency.code + '" class="currency">' + currency.symbol + ", " + currency.name + '</option>');
				});
				
				

				/* Stick it all together and write to the DOM */
				$currencyModal.find('h4').after($countrySelects, $currencySelects);
				$currencyModal.append('<p><strong class="currencyModalError" /></p>');
				$('#header').append($currencyModal);

				
				/***************** Set initial position of selects *****************/
				if (clientLocation) {
					$('select[name=country]').val(clientLocation);
					if (!currencyCookie) {
						countrySelected = clientLocation;
						country = getCountry(countriesArray);
						
						currencySelected = country.currencyDefault;
						
						
					}
					else {
						countrySelected = clientLocation;

						currencySelected = clientCurrency;
						
					}
					$('select[name=currency]').val(currencySelected);
					
					try {
						country = getCountry(countriesArray);
						currency = getCurrency(currenciesArray);
						
						/******** recalculate shipping rate based on shipping country & currency **********/
						
						shippingRate = country.shippingRate * currency.rate;
						
						if (country.taxable) {
							shippingRate = shippingRate * VATRate;
						}
						if (shippingRate == 0) {
							shippingRate = "Free Standard Delivery";
						}
						else {
							shippingRate = currency.symbol + shippingRate.toFixed(2);
						}
						
						$('#currencyModalShippingInfo').html('<h4>Shipping to ' + country.name + '</h4><p>Shipping Rate: ' + shippingRate + '</p><p>' + country.shippingNotes + '</p>');
					}
					catch(err){}
				}
		
			
				/********************************************************************
				 * 
				 * 	Add event listener for modification of select boxes.
				 * 
				 * This must remain a change event listener and not a click, no matter
				 * how many times Sam forgets and breaks it.
				 * 
				 ********************************************************************/
				$('#currencyModal').live('change', function(event){
					
					/************* Changing value of Country select **********/
					if ($(event.target).is('select[name=country]')) {
						
						if ($(event.target).find('option:selected').val() != "invalid") {
							
							/*********** work out which country's selected, get it's default currency and select that ************/
							countrySelected = $(event.target).find('option:selected').attr('value');
							country = getCountry(countriesArray);
							$('select[name=currency]').val(country.currencyDefault);
							
							currencySelected = country.currencyDefault;
							currency = getCurrency(currenciesArray);
								
							/*********** Calculate shipping rate based on shipping country *****************/	
							shippingRate = country.shippingRate * currency.rate;
							if(country.taxable){
								shippingRate = shippingRate * VATRate;
							}
							if(shippingRate == 0){
								shippingRate = "Free Standard Delivery";
							} else {
								shippingRate = currency.symbol + shippingRate.toFixed(2);
							}
							
							$('#currencyModalShippingInfo').html('<h4>Shipping to ' + country.name + '</h4><p>Shipping Rate: ' + shippingRate + '</p><p>' + country.shippingNotes + '</p>');

						}
					}
					
					/************** changing value of currency select ****************/
					if ($(event.target).is('select[name="currency"]')){
						
						countrySelected = $('option.country:selected').attr('value');
						country = getCountry(countriesArray);
						
						currencySelected = $(event.target).find('option:selected').attr('value');
						currency = getCurrency(currenciesArray);

						/******** recalculate shipping rate based on shipping country & currency **************/	

						shippingRate = country.shippingRate * currency.rate;

						if(country.taxable){
							shippingRate = shippingRate * VATRate;
						}
						if(shippingRate == 0){
							shippingRate = "Free Standard Delivery";
						} else {
							shippingRate = currency.symbol + shippingRate.toFixed(2);
						}
						$('#currencyModalShippingInfo').html('<h4>Shipping to ' + country.name + '</h4><p>Shipping Rate: ' + shippingRate + '</p><p>' + country.shippingNotes + '</p>');

					}
				});
				
				/*************** Add Listeners for #currencyModal click events *****************/
				$('#currencyModal').live('click', function(event){
					/* Click on the close button */
					if ($(event.target).is('#closeCurrencyModal')) {
						$('#currencyModal').remove();
						location.reload();
					}
					
					/* Click on the submit button */
					if ($(event.target).is('#currencyModalSubmission')) {
						
						event.preventDefault();
						/* Ascertain whether country is selected and attempt to write cookie */
						countrySelected = $('[name=country] option:selected').attr('value');
						if (countrySelected == 'invalid') {
							$('#currencyModalSubmission .currencyModalError').text('Invalid Country Selected');
							return false;
						} else {
							$.cookie('country', countrySelected, {
								expires: 30,
								domain: '.facewest.co.uk',
								path: '/'
							});
						}
						/* Ascertain whether currency is selected and attempt to write cookie */
						currencySelected = $('[name=currency] option:selected').attr('value');
						if (currencySelected == 'invalid') {
							$('#currencyModalSubmission .currencyModalError').text('Invalid Currency Selected');
							return false;
						} else {								
							$.cookie('currency', currencySelected, {
								expires: 30,
								domain: '.facewest.co.uk',
								path: '/'
							});
						}
						
						/* Delete the modal and reload the page */
						$('#currencyModal').remove();
						location.reload();
						
						
					}
					
				})
			}
			
		});
	}
};
/***********************************************************************
 * ********************************************************************
 * 
 * 
 * 		Externally Developed Scripts
 * 
 *
 * ********************************************************************
 ***********************************************************************/


/****************************************************************************************
 * 
 * 	prototype for removing duplicates from arrays
 * 
 ***************************************************************************************/

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}






/***********************************************************************
 
 Prototype to emulate filter in ie
 
 
 ***********************************************************************/

Array.prototype.filterArray = function(fun /*, thisp*/){
	var len = this.length;
	if (typeof fun != "function") 
		throw new TypeError();
	
	var res = new Array();
	var thisp = arguments[1];
	for (var i = 0; i < len; i++) {
		if (i in this) {
			var val = this[i]; // in case fun mutates this
			if (fun.call(thisp, val, i, this)) 
				res.push(val);
		}
	}
	
	return res;
};

/**************************************************************************
 * 
 * jQuery Supersleight
 * 
 * ***********************************************************************/
 

jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: 'x.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
					self.css('position', 'relative');
				};
			});
		};
	});
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {

		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 1000,
		animation	: {height:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : false,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);


/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

	/***********************************************************************************************
	FUNCTION smoothScrolling
	sexy smooth scrolling for  #links
	
	***********************************************************************************************/
	function smoothScrolling(){
		$("a:not([onclick])[href^='#'][href!='#']").click(function(event){
			if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
				var $target = $(this.hash);
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
				
				if ($target.length) {
					var targetOffset = $target.offset().top - 30;
					$('html,body').animate({
						scrollTop: targetOffset
					}, 500);
					return false;
				}
			}
		});
		$("a:not([onclick])[href=#]").click(function(event){
			$('html,body').animate({
				scrollTop: 0
			}, 500);
			return false;
		});
	}



/*******************************************************
 * 
 * Page Constructor
 * 
 */

$(document).ready(function(){

	textBoxDefaults();
	
	categoryPageHoverBehaviour();
	smoothScrolling();
	if ($('#status')){
		statusBellows();
	}
	
	if ($('#miniFeed').size()>0){
		homePageBuilder();
	} else {
			/**** Mini Basket Event Code****/
					$('#launchMiniBasket').hoverIntent({
						
						timeout: 350,
						
						over: function(event){
							if( $('#miniBasket').size() == 0){
								$miniBasket = $('<div id="miniBasket" />');
								$miniBasket.hide();
								$miniBasket.load('/mm5/merchant.mvc?Screen=BASK-Mini&random=' + Math.random(), 
									function(request, settings){
										$(this).find('.product:even').css('background','#EEEEEE');
										$(this).appendTo('#launchMiniBasket').slideDown('fast');
										
									})
							}
						}, 
						out: function(){
						$miniBasket = $('#miniBasket');
						$miniBasket.slideUp('fast', function(){
							$miniBasket.remove();
						});
						
					}});
					
	}

	/**** Superfish menu code ****/

        $("ul.sf-menu").superfish(); 


					
				
}); 
