
/*
	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()
	{
		InitRolloverNavigation();
		try {
        $(".sub-container").bgiframe({opacity:false});
        } catch (err) {}

	});
}

var _RolloverNavigationLoaded = false;
function InitRolloverNavigation()
{
	if (_jQueryLoaded && !_RolloverNavigationLoaded)
	{
		$("#nav a, #main-nav li").each(function()
		{
			$(this).focus(
				function()
				{
					$(this).toggleClass("hover");
				}
			).blur(
				function()
				{
					$(this).toggleClass("hover");
				}
			);
		});

		_RolloverNavigationLoaded = true;
	}
}

/**
 * Toggle the cart and wishlist.
 * These lists start collapsed and then remember their state (collapsed / expanded)
 * using cookies.
 *
 * @param target
 * @param link
 * @param expand
 * @return
 */
function toggleItems(target, link, expand) {
	// prepare expand
	var display = "block";
	var text    = "Collapse all items";
	link.addClass("minus")

	if (expand == "false") {
		// prepare collapse
		display = "none";
		text    = "Click to see all items";
		link.removeClass("minus")
	}
	// hide/ show items
	$("a." + target + "-link").css("display", display)
	// change text
	link.text(text);
	// set cookie (so the basket remains expanded or colapsed)
	$.cookies.set(target + "Expanded", expand);
}

function showHideWishListItemsOW(show) {

    $('#wishlist_items').css('display', show == "true" ? 'block' : 'none');
    $('#wishlist_expand').css('display', show == "true" ? 'none' : 'block');
    $('#wishlist_collapse').css('display', show == "true" ? 'block' : 'none');

	// Store the cookie for next time
    $.cookies.set("wishExpanded", show);
}

//Show/Hide Wish List.
$(function() {
	// on page load
	var expand = $.cookies.get("wishExpanded");
	if (expand != "true" && expand != "false") {
		// default to collapsed if no cookie is found
		expand = "false";
	}
	showHideWishListItemsOW(expand);

	// Just going with a string representation of boolean to
	// keep consistent with stored value in cookie
    $('#wishlist_expand').click(function() { showHideWishListItemsOW("true"); return false; });
    $('#wishlist_collapse').click(function() { showHideWishListItemsOW("false"); return false; });
});

//Show/Hide Shopping cart.
$(function() {
	$("a.showall-cart").css("display", "block");
	var link = $("a.showall-cart");

	// on page load
	var expand = $.cookies.get("cartExpanded");
	if (expand != "true" && expand != "false") {
		// default to collapsed
		expand = "false";
	}
	toggleItems("cart", link, expand)

	link.bind("click",
			function (event) {
				// toggle display and cookie at user's request
			    var toggleExpand = "false";
				if ($.cookies.get("cartExpanded") == "false") {
					toggleExpand = "true";
				}
				toggleItems("cart", link, toggleExpand);
				return false;
			});
});

/**
 * Enable the wait cursor during a ajax event.
 * @return
 */
function globalAjaxCursorChange() {
	$("html").bind("ajaxSend",
			  function(){
				 $(this).addClass('busy');
			  })
	         .bind("ajaxComplete",
	          function(){
	        	 $(this).removeClass('busy');
	          });
}
$(function() {globalAjaxCursorChange();});

/**
 * Submit forms when adding items to cart.
 */
$(document).ready(function() {
	bindAddToCartSubmissions('WN');
	bindAddToCartSubmissions('bsc');
	bindAddToCartSubmissions('rfy');

	
	$('#BRANDS').change(function(e) {
		$('#MODELS').val("");
		$('#filterForm').submit();
	});
	$('#MODELS').change(function(e) {
		$('#filterForm').submit();
	});

});

/**
 * Force all passwords to uppercase to work around a bug in the SAP kernel.
 */
$(function() {
 try {
    $(":password").bind("blur keypress",
            function(e){
                var oldVal =  $(this).val();
                $(this).val(oldVal.toUpperCase());
            });
  } catch (err) {
  }            
});

/**
 * Bind site intelligence to all form submissions.
 * Fields of type "password" or names matching "nolog_.*" are excluded
 * as they may contain sensitive information.
 * (See site-tracker.js.jsp)
 *
 */
$(function() {
    $("form.siTag").submit(
            function () {
                // protect application agaist site-intelligence errors
                try {
                    SiTrackFormData(this);
                    
                }
                catch(err) {
                    // fail without notification
                }
                return true;
            });
});

// =============================================================================
// Common Javascript Library
// =============================================================================

//------------------------------------------------------------------------------

function traceForm(form) {
    var debug = form.id + "[";
    if (form.elements && (form.elements.length > 0))
    {
        for (var i=0; i<form.elements.length; i++)
        {
            var el=form.elements[i];
            if (el.name)
            {
                var capture=true;
                if (capture && (el.type == "radio")) capture = el.checked;
                if (el.type == "file") capture = false;
                if (el.type == "password") capture = false;
                capture = checkBlacklist(el.name);
                if (el.type == "submit") capture = (el == form.siActivatedSubmit);
                if (capture)
                {
                    var field = escape(el.name)+"="+((el.type=="checkbox") ? ((el.checked) ? "true" : "false") : escape(el.value));
                    debug = debug + field + "\n";
                }
            }
        }
    }
    return debug + "]";
}

//------------------------------------------------------------------------------
// Misc Functions


/**
 * Submit a form using its id.
 *
 * @param formId
 * @return
 */
function submitFormById(formId) {
	$("#" + formId).submit();
	return false;
}


/**
 * Cross browser back button.
 */
function goBack() {
	history.back();
}

//------------------------------------------------------------------------------
// Basket functions


/**
 * Bind the add to cart link so that it submits the "add item" form.
 * @param suffix
 * @return
 */
function bindAddToCartSubmissions(suffix) {
    // select all add links. These links have the id of addToCartLink + suffix + index
    // For example addToCartLinkRP0
    var addLinks = $('a[id*=addToCartLink' + suffix + ']');

    for (i=0;i<addLinks.size();i++) {
    	// build a object to pass into the new click method
    	var data = {suffix: (suffix + i)};

    	var link = $('#addToCartLink' + data.suffix);

        // make sure that the existing click even will not be fired
    	link.attr('href','#');

        // bind a new event
    	link.bind('click',data, function (e) {
    		 $(this).unbind();
        	 e.preventDefault();

        	 // parse quantity
             var quantity = $('#ProductQuantityInput' + e.data.suffix);
             if (quantity.val() != parseInt(quantity.val())) {
            	 quantity.val(1);
             }

             // submit form
             var theForm = $('#addToBasketForm' + e.data.suffix);

             theForm.submit();
        });
   }
}

function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox

     return (key != 13);
}


function initHover(targetSelector, triggerSelector, tipSelector){
  $(targetSelector).each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 100;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;

    var trigger = $( triggerSelector, this);

    var popup = $(tipSelector, this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {

      // 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({
          top: 0,
          left: 60,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          left: '+=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
       }
    }).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({
          left: '+=' + 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');
        });
      }, hideDelay);
    });
  });

}
