/*
	Copyright DTDigital         :: www.dtdigital.com.au ::
	Unauthorised modification / use is a criminal offence, and
	will be prosecuted to the fullest extent permitted by law.
	All Rights Reserved
*/

// jQuery functions that run on "dom ready"

var _jQueryLoaded = (typeof(jQuery) == "function");

if (_jQueryLoaded)
{
	$(document).ready(function()
	{
		
		ButtonsInit();
		Popupbox();
		ProductFiltersInit();
		ShoppingBagInit();
		ProductListingInit();
		ProductUpsellInit();
		SubnavHoverInit();
		MainNavHoverInit();
		StoreListingInit();
		ClickableDiv();
		ColorspotActive();
		
		// Makes links open in new window when they have rel=external
		$("a[rel=external]").attr("target", "_blank");
		// Use below method if using thickbox, matches class rather than rel
		$("a.external-link").attr("target", "_blank"); 
		
		// IE 6 PNG fix for elements:
		// Elements to "fix" are stored in array for readability, converted back to string to feed into fix.
		var DD_fix =
			[
			 	".sb-expanded .shopping-bag-summary_js",
				".zoom-overlay"
			].toString();

		(typeof DD_belatedPNG == "object") ? DD_belatedPNG.fix(DD_fix) : "";
		
		/*
		DD_roundies.addRule('.rounded-corners-small', '2px');
		DISABLED BECAUSE OF INTERFERENCE WITH CLICKED FILTERS AND ANIMATION ETC.
		*/
		
		// Stops IE 6 flicker on hover of link with background image
		if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
			try {
				document.execCommand("BackgroundImageCache", false, true);
			} catch(err) {}
		}

		// Adds default blur text to all empty inputs with this class according to title="" attribute
		$(".fieldhint").fieldhint();
		
		// Auto-complete for the search box on the Stores page
		$(".search1_autocomplete").autocomplete(
		//"WebServices/LocationFinder.asmx/LocationAutoSuggest?country=" + $.query.get('country'),
		location.href.substr(0,location.href.indexOf('/stores/')) + "/WebServices/LocationFinder.asmx/LocationAutoSuggest?country=" + location.href.substr((location.href.indexOf('/stores/') + 8), 2),
			{
				delay: 0,
				minChars: 3,
				maxItemsToShow: 10
			}
		);
		
		// Shopping cart row hover background colour (this for IE6 only)
		if ($.browser.msie && $.browser.version<7) {
			$(".sb-expanded .cart_items tbody tr").not(".non_item").mouseover(function(){$(this).addClass("hover");}).mouseout(function(){$(this).removeClass("hover");});
		}
		
		//$(".colour_dropdown").msDropDown();
		
	});
}

function ButtonsInit()
{
	if ($.browser.msie && $.browser.version<7) {
		
		function BtnMouseOver1()
		{
			$(this).addClass("btn-hover");
		}
		function BtnMouseOut1()
		{
			$(this).removeClass("btn-hover");
		}
		$("input.btn").mouseover(BtnMouseOver1).mouseout(BtnMouseOut1);
	
		$("input.btn-click-disable").click(function(){
			$(this).removeClass("btn-hover").unbind('mouseenter',BtnMouseOver1).unbind('mouseleave',BtnMouseOut1);
		});
		
		function ParseOtherHover(midClass)
		{
			function BtnMouseOver2()
			{
				$(this).addClass("btn-"+midClass+"-hover");
			}
			function BtnMouseOut2()
			{
				$(this).removeClass("btn-"+midClass+"-hover");
			}
			$("input.btn-"+midClass).mouseover(BtnMouseOver2).mouseout(BtnMouseOut2);
	
			$("input.btn-click-disable").click(function(){
				$(this).removeClass("btn-"+midClass+"-hover").unbind('mouseenter',BtnMouseOver2).unbind('mouseleave',BtnMouseOut2);
			});
		}
		
		ParseOtherHover("sml");
		ParseOtherHover("mdm");
		ParseOtherHover("lrg");
		ParseOtherHover("same");
		ParseOtherHover("cross");
		
	}
	
	$(".btn-click-disable").click(function(){
		if ($(this).hasClass("btn-disabled"))
		{
			return false;
		}
		else
		{
			$(this).addClass("btn-disabled");
		}
	});
	
	$(".btn-mdm-printreceipt").show();
		
	$(".update-cart").hide();
	
}

function ShoppingBagInit() {
	
	sb_e = $(".sb-expanded");
	
	sb_outside = $("<div class='sb-outside'></div>").insertBefore("#shoppingBagExpanded");
	
	isie6 = $.browser.msie && $.browser.version<7;
	
	if (isie6) { sb_iframe = $("<iframe src='' height='1' width='1'></iframe>").insertAfter(sb_e); }
	
	$(".shopping-bag-summary").addClass("shopping-bag-summary_js");

	$("#sb-trigger").click(openCartSummary);
	$("#sb-close").add(sb_outside).add("select").not(".sb-expanded select").click(closeCartSummary);
	
	sb_e.mouseover(function(){
		if ( typeof(window["closeCartTimeout1"]) != "undefined" ) {
			clearTimeout(closeCartTimeout1);
		}
	});
}

function openCartSummary() {
    sb_e.fadeIn("fast");

    if (isie6) {
        sb_iframe.css({
            width: (sb_e.width() + 2) + "px",
            height: (sb_e.height() + 2) + "px",
            zIndex: 6000,
            visibility: 'visible' // brings the popup back in to view,
        });

    }
    sb_outside.show();
    if (isie6) { sb_outside.css({ height: $("body").height() }); }
    return false;
}

function closeCartSummary() {
    sb_e.fadeOut("fast");
    if (isie6) {
        sb_iframe.css({
            width: "1px",
            height: "1px",
            visibility: 'hidden'
        });
    }
    sb_outside.hide();
    return false;
}

function Popupbox() {
	$('.popupbox-container').each(function () {
		var isie6 = $.browser.msie && $.browser.version<7;
		
		// options
		var distance = 0;
		var time = 200; //250
		var hideDelay = 5; //20
		
		var hideDelayTimer = null;
		
		// tracker
		var beingShown = false;
		var shown = false;
		
		var trigger = $('.trigger', this);
		var popup = $('.popupbox', this).css('opacity', 0);
		if (isie6) { var popupiframe = $("<iframe src='' height='1' width='1'></iframe>").insertAfter(popup); }

		// set the mouseover and mouseout on both element		
		$([trigger.get(0)/*, popup.get(0)*/]).mouseover(function () {
			
			topPos = -(popup.height() + 10);
			leftPos = -((popup.width()/2) - (trigger.width()/2));
			
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			
			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				
				// reset position of popup box
				popup
					.css({
						marginTop: topPos + "px",
						marginLeft: leftPos + "px",
						position: 'absolute',
						zIndex: 4001,
						display: 'block' // brings the popup back in to view,
					})
				
				// (we're using chaining on the popup) now animate it's opacity and position
					.animate({
						//top: '-=' + distance + 'px',
						opacity: 1
					}, time, 'swing', function() {
						// once the animation is complete, set the tracker variables
						beingShown = false;
						shown = true;
					});
				if (isie6) { 
					popupiframe
						.css({
							marginTop: topPos + "px",
							marginLeft: leftPos + "px",
							width: popup.width() + "px",
							height: popup.height() + "px",
							zIndex: 4000,
							visibility: 'visible' // brings the popup back in to view,
						});
				}
			}
		}).mouseout(function () {
				// reset the timer if we get fired again - avoids double animations
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				
				// store the timer so that it can be cleared in the mouseover if required
				hideDelayTimer = setTimeout(function () {
					hideDelayTimer = null;
					popup.animate({
					//top: '-=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
				// once the animate is complete, set the tracker variables
				shown = false;
				
				// hide the popup entirely after the effect (opacity alone doesn't do the job)
				popup.css('display', 'none');
				if (isie6) { popupiframe.css({margin: "0", width: "1px", height: "1px", visibility: 'hidden'}); }
				});
			}, hideDelay);
		});
	});

}

jQuery.fn.fieldhint = function () {
  return this.each(function (){
    // get jQuery version of 'this'
    var t = jQuery(this); 
    // get it once since it won't change
    var title = t.attr('title'); 
    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      t.blur(function (){
        if (t.val() == '') {
          t.val(title);
          t.addClass('fieldhint_blur');
        }
      });
      // on focus, set value to blank if current value 
      // matches title attr
      t.focus(function (){
        if (t.val() == title) {
          t.val('');
          t.removeClass('fieldhint_blur');
        }
      });

      // clear the pre-defined text when form is submitted
      t.parents('.fieldhintform').submit(function(){ // THIS USED TO SAY 'form:first()' / 'form' ...
          if (t.val() == title) {
              t.val('');
              t.removeClass('fieldhint_blur');
          }
      });

      // now change all inputs to title
      t.blur();
    }
  });
}

//script for faqs usin divs

function ProductFiltersInit()
{
	$(".filterSH-item").not(".filterSH-item-show").find(".filterSH-inside").hide();
	$(".filterSH-item").addClass("filterSH-item-hide");
	$(".filterSH-item-show").removeClass("filterSH-item-hide").removeClass("filterSH-item-show");
	$("p.filterSH-title").each(function(){
		var titleText = $(this).text() + " (click to expand)";
		$(this).wrapInner("<a></a>");
		$(this).children("a").attr("href","#").attr("title",titleText);
	});
	$(".filterSH-item .filterSH-title a")
		.click(function(){
			$(this).blur();
			if ($(this).parent().parent().hasClass("filterSH-item-hide")) {
				$(this).parent().parent().removeClass("filterSH-item-hide");
				$(this).parent().siblings(".filterSH-inside").slideDown("fast");
			} else {
				$(this).parent().parent().addClass("filterSH-item-hide");
				$(this).parent().siblings(".filterSH-inside").slideUp("fast");
			}
			return false;
		});
}

function ProductListingInit() {
	$(".product-item-image").hover(
      function () {
        $(this).addClass("hover");
				$(this).siblings(".product-details").addClass("hover");
      }, 
      function () {
        $(this).removeClass("hover");
				$(this).siblings(".product-details").removeClass("hover");
      }
    );
	$(".product-details").hover(
		function () {
			$(this).addClass("hover");
			$(this).siblings(".product-item-image").addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
			$(this).siblings(".product-item-image").removeClass("hover");
		}
	);
	$(".items .visual").hover(
		function () {
			$(this).addClass("hover");
			$(this).siblings(".description").addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
			$(this).siblings(".description").removeClass("hover");
		}
	);
	$(".items .description").hover(
		function () {
			$(this).addClass("hover");
			$(this).siblings(".visual").addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
			$(this).siblings(".visual").removeClass("hover");
		}
	);
}

function ProductUpsellInit() {
	$(".rp-listing li")
		.css("cursor","pointer")
		.click(function(){
		var mainlink = $(this).find("a.mainlink:first");
		var mainhref = mainlink.attr("href");
		if (mainlink.attr("target") == "_blank") {
			window.open(mainhref);
		} else {
			document.location = mainhref;
		}
	});
	$(".rp-listing li").hover(
		function () {
			$(this).addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
		}
	);
}

function SubnavHoverInit() {
	$("ul.sidebar-nav li").hover(
		function () {
			$(this).addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
		}
	);
}

function MainNavHoverInit() {
	
	var hovernavtimeout = 0;

	$("#nav li#navWomen > a, #nav li#navMiss > a, #nav li#navMini > a, #nav li#navMove > a, #nav li#navRewds > a, #nav li#navBasics > a")
		.each(
			function () {
				$(this).siblings(".hovernav").attr("id","hovernav_"+$(this).parent().attr("id")).insertAfter("#footer-container");
			}
		)
		.hover(
			function () {
				var mnhOffsetLeft = ($(this).offset().left) + "px";
				var mnhOffsetTop = ($(this).offset().top+54) + "px"; //54 is the height of the #nav li
				if (hovernavtimeout)
				{
					clearTimeout(hovernavtimeout);
				}
				$(this).parent("li").siblings("li").children("a").removeClass("hover");
				$(".hovernav").hide();
				$(this).addClass("hover");
				$("#hovernav_"+$(this).parent().attr("id"))
					.css({
						 left: mnhOffsetLeft,
						 top: mnhOffsetTop
					})
					.show()
				;
			}
			, 
			function () {
				var linkid = $(this).parent().attr("id");
				var thisid = "#hovernav_" + linkid;
				hovernavtimeout = setTimeout("$('" + thisid + "').hide();$('#" + linkid + " a').removeClass('hover');",400);
			}
		)
	;
	
	$(".hovernav")
		.hover(
			function()
			{
				if (hovernavtimeout)
				{
					clearTimeout(hovernavtimeout);
				}
			}
			,
			function()
			{
				var thisid = "#" + $(this).attr("id");
				var linkid = thisid.replace("hovernav_","");
				hovernavtimeout = setTimeout("$('" + thisid + "').hide();$('#" + linkid + " a').removeClass('hover');",400);
			}
		)
	;
	
	$(".product-img")
		.mouseover(
			function()
			{
				$("#nav li > a").removeClass("hover");
				$(".hovernav").hide();
			}
		)
	;
	
}

function StoreListingInit() {

	$("div.hide").hide();
	$(".expand").show();
	
	$("a.expand").click(function()
	{
		if ($(this).hasClass("minus")){
			$(this).siblings("div.hide").hide().removeClass("on");
			$(this).removeClass("minus");
		} else {
			$("div.hide").hide();
			$(this).siblings("div.hide").show().addClass("on");
			
			// Changes image src of tabs when clicked.
			$("a.expand").each( function()
			{
				$(this).removeClass("minus");
			});
		
			$(this).toggleClass("minus");
		}
	});

}

function ClickableDiv() {
	$(".hoverbox a.mainlink")
		.parents("li")
			.css("cursor","pointer")
			.click(function(){
				var mainlink = $(this).find("a.mainlink:first");
				var mainhref = mainlink.attr("href");
				if (mainlink.attr("target") == "_blank") {
					window.open(mainhref);
				} else {
					document.location = mainhref;
				}
			})
		.find("*")
			.click(function(){;
				$(this).parents("li").click();
				return false;
			});
//	$(".hoverbox").hover(
//      function () {
//        $(this).css("background-color","#f8f8f8");
//      }, 
//      function () {
//        $(this).css("background-color","#ffffff");
//      }
//    );	
}

function ColorspotActive()
{
    
    //Set colour onload
    $(".colorspot_outer ul li a").each(function () {
        if($(this).hasClass("colorspot_active")) {
             $(this).css("border-color", $(this).css("background-color")); //ensure border matches swatch
        }
    });

    $(".colorspot_outer ul li a")
		.click(function () {
		    var bordercolor = $(this).css("background-color");
		    var thisClickedValue = $(this).attr("href").split("#")[1];
		    $(this).parent("li").parent("ul").parent(".colorspot_outer").children(".hidden_field_color").val(thisClickedValue);
		    $(this).parent("li").parent("ul").parent(".colorspot_outer").find("a").removeClass("colorspot_active");
		    $(this).addClass("colorspot_active");
		    $(".colorspot_active").css("border-color", $(this).css("background-color")); //ensure border matches swatch
		    return false;
		})
	;
}

