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

(function($){

	//FYI: Why are these functions in an object?
	//Because in IE6 there was persistent error 'object does not have this method or function' error
	//when calling functions contained in global.js
	//This method resolves that. Improvements are welcome.

	$.global = {

		/**
		 * 	Add hover fx to top navigation by displaying sub-navigation: for IE6 only
		 *
		 *	arguments - none
		 *	results	---	li elements are displayed via CSS
		 */
		ie6hover: function(){
			if ($.browser.msie && $.browser.version == 6) { //Checks for Internet Explorer 6
				$("#topNav_level_1 li")
					.each(function(index, el){
						//if this list has a sub-menu then show them
						if($(el).children().length > 1){
							$(el).hover(
								//mouse over
								function(){
									$(el).find("ul")
										.css({"display":"block"});
								},
								//mouse out
								function(){
									$(el).find("ul")
										.css({"display":"none"});
								}
							);
						}
					}
				);
			}
		},


		/**
		 * IE6 hover fix on button elements
		 */
		 ie6_button_hover_fix:function(){

			$(".button button").hover(

				function(){

					var el = $(this);
					var hoverClass = el.parent().attr("class").split("_button")[0].split(" ")[1]+"_hover";
					el.data('hoverclass',hoverClass);
					if(el.children().length === 1){

						el.children("span").css("text-decoration","underline");
					}
					else{

						el.css("text-decoration","underline");

					}

					el.parent().addClass(hoverClass);



				},
				function(){

					var el = $(this);
					el.parent().removeClass(el.data('hoverclass'));
					if(el.children().length === 1){

						el.children("span").css("text-decoration","none");
					}
					else{

						el.css("text-decoration","none")

					}




				}



			);




		 }
        ,
		/**
		 * Stops users from multi-clicking on specific submit buttons
		 */
		preventDoubleSubmit: function(){
			$(".prevent_double_submit")
				.click(function(event){
					//disable button
                    var $this = $(this);

					$this.addClass("disabled");

					//if on the payment details form then display overlay
					if($(event.target).parents("form").attr("id") == "payment_details"){
						checkForErrors();
					}
				}
			);
		},

		/**
		 *	Animate the opacity of the top navigation  (fadeInTopNav, fadeOutTopNav)
		 */
		fadeInHeader: function(){
			$(".header_overlay")
				.stop()
				.css({'opacity':'0', 'display':'block'})
				.animate({opacity:0.5}, 500);
		},
		fadeOutHeader: function(){
			$(".header_overlay")
				.stop()
				.animate({opacity:0}, 500);
		},

		/**
		 *	Bind mouseout/mouseover events to elements of id "header_cont"
		 * 	in order to animate the opacity of the top navigation
		 */
		headerOpacity: function(){
			var queryString = "#header";
			
			var header = $("#header");
			header.append('<div class="header_overlay"></div>');
			
			var featuresNavigation = $("#features_navigation");
			if(featuresNavigation.length > 0){
				featuresNavigation.append('<div class="header_overlay"></div>');
				queryString += ", #features_navigation";
			}
			
			$(".header_overlay").css({'height':header.height() + "px"});
			
			$(queryString).hover(function(){
				$.global.fadeInHeader();
			},function(){
				$.global.fadeOutHeader();
			});
		},

		/** 	---------- Mini Basket ----------
		 *		Gets minibasket counter and product information. Also handles minibasket actions
		 */
		 loadMiniBasket: function(){
			$.ajax({
				url: "/pws/ssnMiniBasketCount.jsp",
				cache: false,
				success: function(html){
					$("#mini_basket a").html(html);
					if($("#mini_basket #mini_basket_summary").hasClass("active")){
						$("#mini_basket a").addClass("active").addClass("highlight_background");
					}
				}
			});
		},

		 enableSubmit: function(){
			$(".prevent_double_submit")
				.each(function(index,el){
                    var $el = $(el);

					//enable button
					$el.removeClass('disabled')
                        .css({"cursor":"pointer"});
				}
			);
		},

		/**
		 *	Get the maximum height
		 *	Returns either the body's or window height, whichever is greater and the scroll distance
		 *
		 *	arguments - none
		 *	results ---	maxHeight (number) + scroll distance
		 */
		getMaxHeight: function(){
			var maxHeight = 0;


			//get heights
			var bodyHeight = $("body").height();
			var windowHeight = $(window).height();

			//which one is greater?
			if(bodyHeight >= windowHeight){
				maxHeight = bodyHeight;
			} else if(windowHeight >= bodyHeight){
				maxHeight = windowHeight;
			}

			//add window scroll distance
			//return maxHeight + $(window).scrollTop();
			return maxHeight;
		},

        /**
         * @desc    :displays elements attribute as an info display
         * @param   :{Object} args, makes use of the following properties
         *          :target css selector for target element
         *          :attrInfo name of attribute
         *          :klass class of info display
         *          :parentTarget css selector to ancestor to append info to
         *          :parentId css selector to ancestor with ID to use for creating a unique ID
         * @result  :adds a span element to page containing attribute
         */
        displayElementAttr: function(args){
            try {

                //special case
                if($("body").hasClass("ly_categorylist")){
                    var categorylistPage = true;
                }
                //get element
                var $target = $(args.target);

                $target.each(
                    function(index, el){
                        var $el = $(el);
                        var attrString = $el.attr(args.attrInfo);

                        //validate attribute
                        if(attrString !== '' && attrString !== null){
                            //create info display using class and parentId
                            var infoId = ['dea', $el.parents(args.parentId).attr('id'),args.klass.replace(' ','_')].join('_');

                            //put in a container
                            var $info = $("<div />")
                                            .addClass(args.klass)
																						.addClass('highlight_background')
                                            .attr('id',infoId).hover(function(){$el.trigger('mouseover');return false;}, function(){$el.trigger('mouseout');return false;});

                            var attrStringArr = attrString.split(":");

                            if(attrStringArr.length > 0){
                                $(attrStringArr).each(function(index,el){
                                    var $p = $("<p />").html(el);

                                    if(index === 0){$p.addClass('first');}

                                    $info.append($p);
                                });
                            }

                            var $eventTarget;
                            var $parentTarget
                            var $mouseTarget;

                            //stop flickering on category list page
                            if(args.target === '#category_list .product_link'){
                                $mouseTarget = $el.parents("li:first");
                            } else {
                               $mouseTarget = $el;
                            }

                            //attach to mouse in/out
                            $mouseTarget.mouseover(
                                //mouse in
                                function (event) {
                                    $eventTarget = $(event.target);
                                    if(args.parentTarget === 'this'){
                                        $parentTarget = $el;
                                    } else {
                                        $parentTarget = $($eventTarget.parents(args.parentTarget).eq(0));

                                    }

                                    //add info if not already added
                                    if(!$parentTarget.find(['#',infoId].join('')).length > 0){
                                        $parentTarget.prepend($info);
                                    }
                                    $el.attr(args.attrInfo,'');
                                });
                            $mouseTarget.mouseleave(
                                //mouse out
                                function (event){
                                    $eventTarget = $(event.target);
                                    //to prevent flickering but there has to be a better way
                                    if(!$eventTarget.hasClass(args.klass)){
                                        $eventTarget = $(event.target);
                                        $parentTarget = $($eventTarget.parents(args.parentTarget).eq(0));

                                        $info.remove();

                                        $el.attr(args.attrInfo, attrString);
                                    }
                                }
                            );
                        }
                    }
                );
            } catch (exception) {
                if(window.console && window.debug){
                    console.warn('Error displaying Element Attr: ' + exception);
                }
            }
        }
	};

	$.fn.block = function(options) {

		//add an event listener to the window and expand/shrink the
		//fresca block overlay to cover the whole screen when the window is resized

		/**
		 *	Resize fresca block to always have the same height as the window
		 *
		 *	arguments - none
		 *	results ---	fresca block height is equal to window height (number)
		 */
		function resizeFrescaBlock(){
			var height = $(window).height();
			var width = $(window).width();
			
			
			if(width < 950 && $("#product_details_popup").is(":visible")){
				width = 950 + parseInt($("#product_details_popup").css("left")) + parseInt($(window).scrollLeft());
			}
			
			if(width < $("body").width()){
				width = $("body").width();
			}
						
			$(".fresca_block").css({
				'height':height,
				'width':width
			});
		}

		//event listener
		$(window).resize(function(){resizeFrescaBlock()});

		//don't run if there is already one on the page
		if(!$(".fresca_block").length > 0){
			var opts = $.extend({}, $.fn.block.defaults, options);

			var overlay = $("<div></div>");
			overlay.attr("class", "fresca_block");
			overlay.css({
				position: "absolute",
				top: 0,
				left: 0,
				background: opts.colour,
				opacity: 0,
				width: $("body").width(), //using the body's width seems to give more consistent results
				height: $.global.getMaxHeight(),
				zIndex: 3000
			});
			

			overlay.click(function(){
				$("#product_close").click();
			});

			//if IE6 then put in an iframe to make sure it sits above drop down menus
			if($.browser.msie && $.browser.version == 6){
				prependIframe(overlay);
			}
			$(this).css({"position":"relative"}).append(overlay);

			if(opts.revealSpeed > 0){
				overlay.animate({
					opacity: opts.revealOpacity
				}, opts.revealSpeed);
			} else {
				overlay.css("opacity",opts.revealOpacity);
			}

			return $(this);
		}
	};

	$.fn.block.opts = {};

	$.fn.block.defaults = {
		revealSpeed: 2000,
		revealOpacity: 0.7,
		concealSpeed: 500,
		colour: "#000"
	};

	$.fn.unblock = function(options) {
		var opts = $.extend({}, $.fn.unblock.defaults, options);
		var overlay = $(this).children("div.fresca_block");
		if(opts.concealSpeed > 0){
			overlay.animate({
				opacity:0
			}, opts.concealSpeed, function(){
				overlay.remove();
			});
		} else {
			overlay.remove();
		}
	};

	$.fn.unblock.opts = {};

	$.fn.unblock.defaults = {
		concealSpeed: 500
	};

	$.fn.refreshblock = function(options) {
		var opts = $.extend({}, $.fn.unblock.defaults, options);
		var overlay = $(this).children("div.fresca_block");
		overlay.css({
			width: $(this).width(),
			height: $(this).height()
		});
	};

	$.fn.refreshblock.opts = {};
	$.fn.refreshblock.defaults = {};

	$.fn.pngfix = function(){
		if($.browser.msie && $.browser.version == '6.0'){
			$.each($(".png_fix"),function(){
				var sizingMethod = "crop";
				if($(this).is(".scalePng")){
					var sizingMethod = "scale";
				}
				$(this).wrap("<span class='pngWrap'></span>");
				var test = $(this).parent();
				$(this).parent(".pngWrap").css({
					"display":"block",
					"width":$(this).width(),
					"height":$(this).height(),
					"background-image":"none",
					"filter":"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(this).attr("src")+"',sizingMethod='"+sizingMethod+"')"
				});
				$(this).css('display','none');
			});
		}
	};


})(jQuery);

function displayProductInformation(){
	var products = $("#category_list .product a, #complete_the_look .product a, #category_list_outlet .product a");
	products.live("mouseover",function(){
		$(this).siblings(".product_information").show().hover(function(){$(this).show()},function(){$(this).hide()});
	}).live("mouseout",function(){
		$(this).siblings(".product_information").hide();
	});
}

/** 	Displays error messages for the appropriate form
 *		arguements ----	(html object) errors: containing error messages,
 *						(event object) event: in order to know where to append the message when there are multiple forms
 *		precondition --	error messages are present, event object is available
 *		results ------- error message(s) are made visible inside appropriate form
 */
function displayErrorMessages(errors, event){
	try{
		if($(errors).find("li").length > 0){ //if there are error messages to show
			targetForm = $(event.target);	//who triggered the error and where to show it

			//if there is a current error message
			if(targetForm.find("#error_messages_cont").length > 0){
				//replace it
				$("#error_messages_cont").remove("ul").append(errors);
			} else {
				//prepare error message for display
				if($(".fcp_errors").length > 0){ //there are fcp_errors add it to that
					$(".fcp_errors ul").append($(errors).find('li'));
				} else {
					errorMsgsCont = $("<div id='error_messages_cont' class='errors' />");
					errorMsgsCont.prepend("<h4>Sorry, some information appears to be incorrect: </h4>");
					errorMsgsCont.append(errors);
				}

				//display it
				if($("body").hasClass("ly_paymentdetails")){
					//if we are on the payment details page append it just above the card-type input
					$(event.target).find("#cardType")
						.parent()
						.parent()
						.prepend(errorMsgsCont);

					$.global.enableSubmit();
				} else {
					if($(".fcp_errors").length < 1){ //have we already added it?
						targetForm.prepend(errorMsgsCont);
					}
				}
			}
		}
	} catch(e){
		if(window.console && window.debug){
			console.log("Error displaying error message(s): " + e);
		}
	}
}

/**
 *	This is essentially a helper method for displayErrorMessages
 *	Fresca validation updates the error messages on the focus event on the fields
 *	Depending on how the error messages are displayed these need to be removed when there are
 * 	no more error messages
 *
 *	arguements --------	form (html object)
 *	precondition ------	form (html object)
 *	result ------------	hides all elements of class "error" in the form
 */
function clearErrorMessages(form){
	try {
		$(form).find(".errors").each(function(index,el){
			$(el).css({"display":"none"});
		});
	} catch(e){
		if(window.console && window.debug){
			console.log("Error clearing error message(s): " + e);
		}
	}
}

/**
 *	Removes popup_link_cont div from the page
 *
 *	arguements --------	none
 *	precondition ------	popup_link_cont div element appended to the page
 *	result ------------	fresca_block and popup_link_cont div removed
 */
function removePopupLink(){
	$("body").unblock();
	$("#popup_link_cont").remove();
}

/**
 *	Opens target of anchor elements in a popup
 *
 *	arguements --------	none
 *	precondition ------	anchor element with class of 'popup_link'
 *						if the anchor element has a name use it as the id for the popup content
 *	result ------------	div displayed on the page
 */
function popupLink(){
	try {
		//for each anchor
		$(".popup_link").each(function(index,el){

			//when i click on it
			$(el).click(function(event){
				//get url
				var linkUrl = $(el).attr('href');
                
				//if we are not on the homepage: for some reason this unpauses the flash
				if(!$("body").hasClass('ly_basic')){
					//if there is no fresca block
					if($('.fresca_block').length <= 0){
						$("body").block({delegate:true});
					}
				}

				//create popup
				var popupLinkCont = $("<div id='popup_link_cont'></div>");
				popupLinkCont.css({
					'padding-top':80 + $(window).scrollTop()
				});

				var content = $("<div class='content'></div>");
				//use the name attribute to specify an id for the popup content
				var nameAttr = $(el).attr('name');

				if(typeof nameAttr == 'string'){content.attr('id',nameAttr);}

				//get content
				$.ajax({
				    url: linkUrl,
					type: "GET",
					beforeSend: function(request){
						popupLinkCont.append(content);

						$("body div:first").append(popupLinkCont);

						//its loading..
						content.addClass('loading');
					},
					success: function(data){
						var response = $(data).find(".mainContent").html();

						content.removeClass('loading');

						try {
							if(response !== null){
								content.html(response);
							} else {
								content.html("<p class='no_content_found cufon'>Sorry, no content found</p>");
							}
						} catch(e){
							if(window.console && window.debug){
								console.warn("Error getting content, " + e);
							}
						}

						//size guide popup
						if(nameAttr == 'size_guide_popup'){
							bodyPartsNav();
							$('#popup_link_cont').addClass('js');
						}
				    },
                    complete: function (){
                        //add close button
                        addCloseButton({'destination':'#popup_link_cont .content', 'target':'#popup_link_cont'});

                        Cufon.replace('#popup_link_cont .cufon');
						
                    }
				});

				event.preventDefault();
			});
		});

	} catch(e){
		if(window.console && window.debug){
			console.warn("Error with popup link: " + e);
		}
	}
}

/**
 *	@desc           Appends a close button to the target
 *  @args           {Object} containing the following properties -
 *                  {String} destination, css path to html element to append itself to
 *                  {String} target, html element to hide on click, if a target is not supplied then it is assumed to be the same as the destination
 *                  {String} btnId, id of button
 *                  {Object} button, jQuery object containing HTML element to add click event to
 *	@preconditions  valid css path
 * 	@results        adds close button to destination html element
 *					on click, the close button removes fresca block and removes the target from the body
 */
function addCloseButton(args){
	try {
        var $closeButton;
        var $destination;

        if(!args.button){ //we dont have a button create one
            $closeButton = $("<a href='#' class='close_button'>Close Pop up</a>");
            $destination = $(args.destination);
        } else {
            $closeButton = $(args.button);
        }

        $closeButton.bind('click',function(){
            if(window.console && window.debug){
                console.log(['addCloseButton: testing click event'].join(' '));
            }

        });

        if(args.btnId){$closeButton.attr('id', args.btnId);}

        if(!args.target){args.target = args.destination;}

        var $target = $(args.target);

        if(window.console && window.debug){
            console.log(['addCloseButton: $target.length = ', $target.length].join(' '));
        }

		if($target.length > 0){
			//listeners
			$closeButton.hover(function(){
				$(this).addClass("highlight_text");
			},function(){
				$(this).removeClass("highlight_text");
			}).click(function(event){
                if(window.console && window.debug){
                    console.log(['addCloseButton: close button clicked'].join(' '));
                }

                $("body").unblock();

				if($("body").hasClass('ly_basic')){var homepage = true;}

                if(args.target === '#popup_link_cont'){
                    var popuplinkCont = true;
                }

				if(homepage && popuplinkCont){
					try {
						//before removing popup
                        //for 3rd party flash support provide javascript callback so they can unpause flash movie
						closingPopup(event);
					} catch(e){
						//do nothing
					}
				}

                //update the URL
                $.bbq.pushState({'ID':'productClose'});

                $target.remove();
				

				if(homepage && popuplinkCont){
					try {
						//after popup is removed
						popupClosed(event);
					} catch(e){
						//do nothing
					}
				}
				event.preventDefault();
			});

            if(window.console && window.debug){
                console.log(['addCloseButton: args.destination = ', args.destination, '$destination = ', $destination].join(' '));
            }

            //add button
            if($destination){ $destination.prepend($closeButton); }
            
		} else {
			throw 'Invalid arguments. Please specify at least a valid destination'
		}
	} catch(e){
	    if(window.console && window.debug){
	        console.warn("Error adding close button, " + e);
	    }
	}
}

/**
 *	Hides source of click event and displays an HTML element
 *	for each element with class of 'toggle_pair'
 *
 *	precondition ----- elements with class of 'toggle_pair'
 *	results ---------- shows elements with the class specified in the 'name' attribute appended with '_show'
 *						hides elements with the specified 'name' attribute string appended with '_hide'
 */
 function togglePairs(){
	//For each element with class
	try {
		$(".toggle_pair").each(
			function(index, el){
				//..when add an event listener for click events
				$(el).click(
					function(event){
						//..so that when clicked show the target element
						var target_el = $(el).attr("name");

						//if there is one to hide..
						if($("." + target_el + "_hide").length > 0){
							//..do that first
							$("." + target_el + "_hide").animate(
								{'opacity':0},
								800,
								function(){
									$("." + target_el + "_hide").css({'display':'none'});

									$("." + target_el + "_show")
										.animate({'opacity':1},
											800,
											function(){
												$("." + target_el + "_show").css({"display":"block"});
											}
										);
								}
							);
						} else {
							$("." + target_el + "_show")
								.animate({'opacity':1},
									800,
									function(){
										$("." + target_el + "_show").css({"display":"block"});
									}
								);
						}

						event.preventDefault();
					}
				);
			}
		);
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error, " + e);
		}
	}
 }
/**
 *  Submits the parent form when an HTML element register is changed
 *
 *	arguments ---- menuElPath (alphanumeric) css path of the HTML element to register selection
 *
 *  preconditions - selector element belongs to a parent form (html element)
 *  results ------- the parent form is submitted
 */
function submitOnChange(menuElPath){
	try {
		//if we are submiting a postcode lookup then don't validate please
		var $menuElPath = $(menuElPath);

		if(menuElPath === "#searchAddressID"){
			if($(menuElPath).length > 0){
				$(".validate").addClass("ignore");

				$menuElPath.bind("change",
					function(event){
						useThisAddress(this.form);
				});
			}
		}

		if($menuElPath.length > 0){
			$menuElPath.each(function(index, el){

				//issues with IE6 so we have to listen for click on radio buttons and change on select menus
				if($(el).attr('type').indexOf('select') === 0){
					$(el).bind("change", function(event){
						$(event.target).parents("form").submit();
					});
				} else {
					$(el).click(function(event){
						$(event.target).parents("form").submit();
					});
				}

			});
		} else {
			throw "menu element not found. Please check path and arguements";
		}
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error, submitting on change: " + e);
		}
	}
}

/**
 *  Clear search input on focus
 *
 *	arguments ---- none
 *
 *  preconditions - element with id "keywords"
 *  results ------- the input is cleared on focus
 */
function clearSearchInput(){
	try {
		$("#keywords").bind("focus",
			function(event){
				$(event.target).attr("value","");
			}
		);
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error clearing input, " + e);
		}
	}
}

/**
 *  Clear all inputs of a form
 *
 *	arguments ---- form to clear
 *
 *  preconditions - form has inputs
 *  results ------- value of the inputs is set to an empty string
 */
function clearAllInputs(form){
	try {
		$(form)
			.find("input")
			.each(function(index,el){
				$(el).attr("value","");
			}
		);
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error clearing input, " + e);
		}
	}
}

/**
 *  Add current page indicator to top navigation by adding/removing class of "selected"
 *
 *	arguments ---- none
 *
 *  preconditions - called on page load
 *				  -	layout added as class to body element
 *				  -	top navigation has links:
						"collections", "shop", "brands", "stores", "about", "newsletter", "help", "account", "search"
 *  results ------- class of selected is added to a single list element with a class of "level_1"
 */
function indicateCurrentPage(){
	try {
		//get the current layout
		var currentLayout = $("body").attr("class");

		//remove class(es)
		$("#header_links a").each(
			function(index,el){
				var rootLink = $(el).parents("li:last");

				var anchorText = $(rootLink)
									.find("a:first")
									.html()
									.toLowerCase();
				//get rid of whitespace
				anchorText = $.trim(anchorText);

				rootLink.removeClass("selected");

				//what page are we on?
				switch(currentLayout){
					case "ly_categorycollections":
						//add class
						if(anchorText === "collections"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_categorylist":
						if(anchorText === "shop"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_categorybrand":
						if(anchorText === "brands"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_storefinder":
						if(anchorText === "stores"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_content":
						//could be help, about or search landing page so check left nav
						var leftNavLink = $("#left_nav_cont").find("a:first").html();

						if(leftNavLink){
							leftNavLink = $("#left_nav_cont").find("a:first").html().toLowerCase();
							leftNavLink = $.trim(leftNavLink);

							if(anchorText === "help" && leftNavLink === "how to order"){
								rootLink.addClass("selected");
							} else if(anchorText === "about" && leftNavLink === "about us"){
								rootLink.addClass("selected");
							}
						} else { //search results page does not have a left nav so must be this
							if(anchorText === "search"){
								rootLink.addClass("selected");
							}
						}

						break;

					case "ly_registerprospect": //newsletter
						if(anchorText === "newsletter"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_loginregister":
						if(anchorText === "account"){
							$(rootLink).addClass("selected");
						}

						break;

					case "ly_myaccount":
						if(anchorText === "account"){
							$(rootLink).addClass("selected");
						}

						break;

					case"ly_searchresults":
						if(anchorText === "search"){
							$(rootLink).addClass("selected");
						}

						break;

					default:
						//do nothing
						;
				}

			}
		);

	} catch(e){
		if(window.console && window.debug){
			console.warn("Error clearing input, " + e);
		}
	}
}


/**
 *	Prepends an iframe to an HTML element so that it sits on top of drop down menus
 *	for IE6 only
 *
 *	arguments --------- html element
 *	preconditions ----- target (html element),
 *						ie6 browser
 *	results ----------- prepends invisible iframe element to target element
 */
 function prependIframe(target){
	try {
		if($.browser.msie && $.browser.version == 6){
			if(target){
				var iframe = $("<iframe id='myFrame' src='/pws/blank.html' frameBorder='0'></iframe>");

				iframe.css({
					"display":"block",
					"position":"absolute",
					"top":0,
					"height":"100%",
					"width":"100%",
					"opacity":0,
					"z-index":-10
				});

				$(target).prepend(iframe);
			} else {
				throw "Please supply an element to append the iframe to.";
			}
		}
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error prepending iframe, " + e);
		}
	}
}

/**
 *	Prepends an iframe to an HTML element so that it sits on top of drop down menus
 *	for IE6 only
 *
 *	arguments --------- css path for id of select menu html element
 *	preconditions ----- select menu html element has an option of other
 *	results ----------- reveals label and input and input for other title
 */
 function showOtherTitle(cssPath){
	$(cssPath).bind("change",
		function(event){
			if(event.target.value.toLowerCase() == 'other'){
				$("#otherTitleField").fadeIn();
			}
		}
	);
 }

/* postcode lookups: before i tried to make it work on payment details page */
function setPostcodeMode(checkoutAddressMode, value) {
	if(checkoutAddressMode.length == undefined)
	{
		checkoutAddressMode.value = value;
	}
	else
	{
		checkoutAddressMode[0].checked = true;
		checkoutAddressMode[0].value = value;
	}
}

function postcodeLookup(form) {
	$('.validate').addClass("ignore");	//override the form validation

	if(form.id == 'create_new_billing_address' || form.id == 'create_new_billing_address'){ //on payment details page
		setPostcodeMode(form.checkoutAddressMode,'postcodeSearch');
	} else {
		form.search.value='true';
		form.isSearchPostcode.value='true';
	}


	form.submit();
}

function useThisAddress(form) {
	var formID = form.id ;

	if(formID == 'create_new_billing_address'){ //on payment details page
		setPostcodeMode(form.checkoutAddressMode,'postcodeFetch');
	} else {
		form.search.value='true';
	}

	var addressSelected = false;

	if(formID == 'add_new_address_form'){
		if(form.searchAddressID.selectedIndex > 0){
			addressSelected = true;
		}
	} else if(formID == 'create_new_billing_address'){
		if(form.postcodeAddressID.selectedIndex > 0){
			addressSelected = true;
		}
	}

	if (addressSelected) {
		form.submit();
	}
}

/**
 *	Scrolls the body/html document to an html element
 *
 *	@param target (string) css path to element to scroll to

 *	@param options contains
 *	 delay (boolean) animate to target after interval
 *	 interval (number) time lag before animation in milliseconds
 * 	 callback to be called at end of animation
 *	preconditions - target exists in document
 *	see - http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12
 */
function animateTo(target,options){
	var runonce = false;

	try {
		var $target = $(target);

		if($target.length > 0) {
			var targetOffset = $target.offset().top;
            //targetOffset = targetOffset/3;

			if(options){
				if(options.delay){
					if(interval){
						var wait = window.setInterval(
							function(){
								$('html,body').animate(
									{scrollTop: targetOffset},
									800,
									function (){
										if(!runonce){
											if(options.param){
												options.callback(options.param);
											} else {
												options.callback();
											}
											runonce = true;
										}
									}
								);
								clearInterval(wait);
							},
							options.interval
						);
					} else { //no custom interval
						var wait = window.setInterval(
							function(){
								$('html,body').animate(
									{scrollTop: targetOffset},
									800,
									function (){
										if(!runonce){
											if(options.param){
												options.callback(options.param);
											} else {
												options.callback();
											}
											runonce = true;
										}
									}
								);
								clearInterval(wait);
							},
							500
						);
					}
				} else { //no delay
					$('html,body').animate(
						{scrollTop: targetOffset},
						800,
						function (){
							if(!runonce){ //to prevent it from running twice
								if(options.param){
                                    if(options.popupURL){ //to trigger fresca block
                                        options.callback(options.param, false);
                                    }else{
                                        options.callback(options.param);
                                    }

								} else {
                                    if(typeof options.callback === 'function'){
                                        options.callback();
                                    }
								}
								runonce = true;
							}
						}
					);
				}
			}else{ //just get on with it, nothing fancy
				$('html,body').animate(
					{scrollTop: targetOffset},
					800
				);
			}
		} else {
             if(typeof options.callback === 'function'){
                options.callback();
            } else{
                throw 'Target not found and no callback specified';
            }
		}
	} catch(e){
		if(window.console && window.debug){
			console.warn("Error in animateTo(), " + e);
		}
	}

	return false;
}

//issues with using UpdateAddressAction to populate address fields so change action
/**
 *	Changes form action from UpdateAddressAction to CreateAddressAction
 * 	arguments - form (html element)
 */
function updateFormAction(form){
	var formAction = $(form).attr('action');

	if(formAction  === '/pws/secure/UpdateAddress.ice'){
		$(form).attr('action','/pws/secure/CreateAddress.ice');
	}
}

function handleFeaturesSelect(){
	var featureForm = $("#change_feature");
	
	if(featureForm.length > 0){
		
		var featureSelect = featureForm.find("select[name='page']");
		var featureForward = featureForm.find("input[name='pgForward']").val();
				
		var currentPageKey = window.location.pathname.replace("/fcp/content/","").replace("/"+featureForward,"");
		
		if(currentPageKey !== ""){
			var currentOption = featureSelect.find("option[value='"+currentPageKey+"']");
			if(currentOption.length > 0){
				currentOption.attr("selected",true);
			} else {
				featureSelect.prepend('<option value="">'+featureForm.find("legend").html()+'</option>');
				featureSelect.find("option:first").attr("selected",true);
			}
		} else {
			featureSelect.prepend('<option value="">'+featureForm.find("legend").html()+'</option>');
			featureSelect.find("option:first").attr("selected",true);
		}
		
		featureForm.submit(function(e){
			
			e.preventDefault();
			
			var page = featureSelect.val();
			var pgForward = featureForward;
			
			if(page != ""){			
				window.location = "/fcp/content/"+ page +"/"+ pgForward;
			}
		});
		
		featureSelect.change(function(){
			featureForm.submit();
		});
		
	}
}


/*--------------- end before i tried to make it work on payment details page */
$(document).ready(function(){
	
	if ($.browser.msie && $.browser.version == 6) {
	$.global.ie6_button_hover_fix();

	}
	$.global.headerOpacity();

	$.global.loadMiniBasket();
	$.global.preventDoubleSubmit();

	togglePairs();
	
	$("#navigation li a:not(.highlight_text), #sub_navigation a:not(.highlight_text)").hover(function(){
		if(!($(this).hasClass("active") || $(this).hasClass("highlight_background"))){
			$(this).addClass("highlight_text");
		}
	},function(){
		$(this).removeClass("highlight_text");
	});
	
	//if on the search results page
	if($(".ly_searchresults").length > 0 || $(".ly_storefinder").length > 0){
		submitOnChange(".search_filters");
	}

	//if on the store finder page
	if($(".ly_storefinder").length > 0){
		submitOnChange(".entrySelector");
		submitOnChange(".itemSelector");
	}

	//clear search input on focus
	if($("#keywords").length > 0){
		clearSearchInput();
	}

	//update top nav
	indicateCurrentPage();

	//for registration forms only with other title inputs
	if($("#otherTitle").length > 0){
		showOtherTitle('#titlefield');
	}

	//if there is a postcode lookup button on the page
	if($("#postcode_lookup_btn").length > 0){
		$("#postcode_lookup_btn").click(function(event){
			postcodeLookup(this.form);
		});

		//select address
		$("#postcode_address_id").bind("change",function(event){
			useThisAddress(this.form);
		});

		submitOnChange("#searchAddressID");

	}

	//if there is a popup link
	if($(".popup_link").length > 0){
		popupLink();
	}


	//if we are on the payment details page
	if($("body").hasClass("ly_paymentdetails")){
		//clear form when we click on don't save

	}

	if($.browser.msie && $.browser.version === "6.0"){
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	}
	
	displayProductInformation();
	
	handleFeaturesSelect();

});

/*
 * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,p){var i,m=Array.prototype.slice,r=decodeURIComponent,a=$.param,c,l,v,b=$.bbq=$.bbq||{},q,u,j,e=$.event.special,d="hashchange",A="querystring",D="fragment",y="elemUrlAttr",g="location",k="href",t="src",x=/^.*\?|#.*$/g,w=/^.*\#/,h,C={};function E(F){return typeof F==="string"}function B(G){var F=m.call(arguments,1);return function(){return G.apply(this,F.concat(m.call(arguments)))}}function n(F){return F.replace(/^[^#]*#?(.*)$/,"$1")}function o(F){return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(H,M,F,I,G){var O,L,K,N,J;if(I!==i){K=F.match(H?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);J=K[3]||"";if(G===2&&E(I)){L=I.replace(H?w:x,"")}else{N=l(K[2]);I=E(I)?l[H?D:A](I):I;L=G===2?I:G===1?$.extend({},I,N):$.extend({},N,I);L=a(L);if(H){L=L.replace(h,r)}}O=K[1]+(H?"#":L||!K[1]?"?":"")+L+J}else{O=M(F!==i?F:p[g][k])}return O}a[A]=B(f,0,o);a[D]=c=B(f,1,n);c.noEscape=function(G){G=G||"";var F=$.map(G.split(""),encodeURIComponent);h=new RegExp(F.join("|"),"g")};c.noEscape(",/");$.deparam=l=function(I,F){var H={},G={"true":!0,"false":!1,"null":null};$.each(I.replace(/\+/g," ").split("&"),function(L,Q){var K=Q.split("="),P=r(K[0]),J,O=H,M=0,R=P.split("]["),N=R.length-1;if(/\[/.test(R[0])&&/\]$/.test(R[N])){R[N]=R[N].replace(/\]$/,"");R=R.shift().split("[").concat(R);N=R.length-1}else{N=0}if(K.length===2){J=r(K[1]);if(F){J=J&&!isNaN(J)?+J:J==="undefined"?i:G[J]!==i?G[J]:J}if(N){for(;M<=N;M++){P=R[M]===""?O.length:R[M];O=O[P]=M<N?O[P]||(R[M+1]&&isNaN(R[M+1])?{}:[]):J}}else{if($.isArray(H[P])){H[P].push(J)}else{if(H[P]!==i){H[P]=[H[P],J]}else{H[P]=J}}}}else{if(P){H[P]=F?i:""}}});return H};function z(H,F,G){if(F===i||typeof F==="boolean"){G=F;F=a[H?D:A]()}else{F=E(F)?F.replace(H?w:x,""):F}return l(F,G)}l[A]=B(z,0);l[D]=v=B(z,1);$[y]||($[y]=function(F){return $.extend(C,F)})({a:k,base:k,iframe:t,img:t,input:t,form:"action",link:k,script:t});j=$[y];function s(I,G,H,F){if(!E(H)&&typeof H!=="object"){F=H;H=G;G=i}return this.each(function(){var L=$(this),J=G||j()[(this.nodeName||"").toLowerCase()]||"",K=J&&L.attr(J)||"";L.attr(J,a[I](K,H,F))})}$.fn[A]=B(s,A);$.fn[D]=B(s,D);b.pushState=q=function(I,F){if(E(I)&&/^#/.test(I)&&F===i){F=2}var H=I!==i,G=c(p[g][k],H?I:{},H?F:2);p[g][k]=G+(/#/.test(G)?"":"#")};b.getState=u=function(F,G){return F===i||typeof F==="boolean"?v(F):v(G)[F]};b.removeState=function(F){var G={};if(F!==i){G=u();$.each($.isArray(F)?F:arguments,function(I,H){delete G[H]})}q(G,2)};e[d]=$.extend(e[d],{add:function(F){var H;function G(J){var I=J[D]=c();J.getState=function(K,L){return K===i||typeof K==="boolean"?l(I,K):l(I,L)[K]};H.apply(this,arguments)}if($.isFunction(F)){H=F;return G}else{H=F.handler;F.handler=G}}})})(jQuery,this);
/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);

if($.browser.msie && $.browser.version == '6.0'){
    (function($) {
	$(window).load(function(){
            $("ul#looks").css('visibility','visible');
            $("div#thumbnails ul").css('visibility','visible');
        });

    })(jQuery);
}
