/*
	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();
		InitRolloverInputs();
		Popupbox();
		Hoverbox();
		ClearInput();
		
		// Price filter found on range & pricing / specs pages
		PriceFilterer();
		
		// 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");
		
		// External dealer hiding elements when query string is present
		var hideThese = $(".noshow");
		var showThese = $(".show");
		var changeThese = $(".textchange")
		var queryString = location.search.substring(1, location.search.length);
		if(queryString.indexOf("show=false") != -1)
		{
			$.each(hideThese,
			function()
				{
					$(this).css({ display: "none"});
				}
			);
			$("a").each(
				function()
				{
					var currentLink = $(this).attr("href");
					$(this).attr("href", currentLink + "?show=false");
				}
			);			
			$.each(showThese,
			function()
				{
					$(this).css({ display: "block"});
				}
			);
			$.each(changeThese,
			function()
				{
					$(this).text("Range &amp; Specifications");
				}
			);
						
		}
		
		$('a#print-link').click(function() {
			window.print();	
			return false;
		});
	});
}

var _RolloverNavigationLoaded = false;
function InitRolloverNavigation()
{
	if (_jQueryLoaded && !_RolloverNavigationLoaded)
	{
		$(".rollover-navigation a").each(function()
		{
			$(this).find("img.navitem_prejs").each(function()
			{
				$(this).attr("class", "navitem_off");
			
				var newImage = $(this).clone();
		
				var newImageSrc = newImage.attr("src").replace("_0.gif", "_1.gif");
				newImage.attr("src", newImageSrc);
		
				newImage.attr("class", "navitem_hover");
		
				newImage.insertAfter(this);
			});
			
			$(this).focus(
				function()
				{
					$(this).toggleClass("hover");
				}
			).blur(
				function()
				{
					$(this).toggleClass("hover");
				}
			);
		});
		
		_RolloverNavigationLoaded = true;
	}
}

function InitRolloverInputs()
{
	if (_jQueryLoaded)
	{
		$(".rollover-input").each(function()
		{
			var imageSrc = $(this).attr("src");
			var imageName = imageSrc.substring(imageSrc.lastIndexOf("swap_") + 5, imageSrc.lastIndexOf("_"));
			
			for (var preloadLoop=0; preloadLoop < 3; preloadLoop++)
			{
				if (eval("typeof(b" + imageName + preloadLoop + ")") != "object")
				{
					eval("b" + imageName + preloadLoop + " = new Image()");
					eval("b" + imageName + preloadLoop + ".src = 'assets/swap_" + imageName + "_" + preloadLoop + ".gif'");
				}
			}
			
			$(this).mouseover(function()
			{
				$(this).attr("src", eval("b" + imageName + "1.src"));
			});
			
			$(this).mousedown(function()
			{
				$(this).attr("src", eval("b" + imageName + "2.src"));
			});
			
			$(this).mouseout(function()
			{
				$(this).attr("src", eval("b" + imageName + "0.src"));
			});

		});
	}
}

function PriceFilterer()
{
	$(".custom-select-container02").click(function(e){
		var tag = e.target;
		
		if(tag.nodeName === "LI")
		{
			var StateValue = tag.firstChild.nodeValue;
			
			$("#Pricing .multi-column06:visible").hide();
			
			$("#" + StateValue + "_Prices").toggle();
			if(typeof sIFR === "object"){
				// font replacement won't happen onload to hidden items
				// Do replacement on now visible headings
				sIFR.replace(kievitbold, {
					selector: 'h2.subtitle05a'
					,transparent: true
					,css: ['.sIFR-root { color: #3E3A3D; }']
				});
			}
		}
	});
}

/*
Client-side access to querystring name=value pairs
Version 1.3
28 May 2008
http://adamv.com/dev/javascript/querystring
License (Simplified BSD): http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;
// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		this.params[name] = value;
	}
}
Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}
Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}
/*
// To parse the current page's querystring:
var qs = new Querystring()
// To parse a given querystring - should not begin with a "?":
var qs2 = new Querystring("name1=value1&name2=value2&name3=value3")
// The following returns "value1"
var v1 = qs2.get("name1")
// The following returns "whoops"
var v1 = qs2.get("non-existent-parameter", "whoops")
// The following returns null
var v1 = qs2.get("non-existent-parameter")
// qs.contains(name) returns true if parameter "name" exists, else false.
// The following returns an alert box with "value1":
if (qs2.contains("name1")){ alert(qs2.get("name1"));}
*/

function popup(mylink, windowname) {
    if (typeof (mylink) == 'string') {
        href = mylink;
    } else { href = mylink.href; }

    params = 'width=' + screen.width;
    params += ', height=' + screen.height;
    params += ', top=0, left=0, toolbar=0,location=0,statusbar=0,menubar=0,resizable=0,scrollbars=0'
    params += ', fullscreen=yes,';

    popupWindow = window.open(href, windowname, params);
    if (window.focus) { popupWindow.focus() }
    return false

}

function isValid() {
	/* Client side validation, highlight fields */
	if(Page_ClientValidate() == false) {
		$.each(Page_Validators,function(index) {
			var currentItem = "#" + $(Page_Validators[index]).attr("id");
			
			var findChildSpan = $(currentItem).parents(".field01").find(".error").size();
			
			if(findChildSpan == 1){
				if(Page_Validators[index].isvalid == false) {
					$(currentItem).parents(".field01").addClass("field-error01");
				} else {
					$(currentItem).parents(".field01").removeClass("field-error01");
				}
			} else {
				var firstErrorSpan = $(this).parent().find("span.error:first").css("display");
				var secondErrorSpan = $(this).parent().find("span.error:last").css("display");
				if(firstErrorSpan == "inline" || secondErrorSpan == "inline"){
					$(currentItem).parents(".field01").addClass("field-error01");
				} else {
					$(currentItem).parents(".field01").removeClass("field-error01");
				}
			}

			
		});
	}
	
}

function Popupbox() {
	$('.popupbox-container').each(function () {
		var isie6 = $.browser.msie && $.browser.version<7;
		var isie7 = $.browser.msie && $.browser.version<8;
		
		// 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)*/]).click(function () {
			
			topPos = -(popup.height() + 3);
			leftPos = -35;
			
			ieTopPos = -(popup.height() + 5);
			ieLeftPos = -55;
			
			// 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) { 
					popup
						.css({
							marginLeft: ieLeftPos + "px" //fix position in ie6
					});
					popupiframe
						.css({
							marginTop: ieTopPos + "px",
							marginLeft: ieLeftPos + "px",
							width: 285,
							height: popup.height() + "px",
							zIndex: 4000,
							visibility: 'visible' // brings the popup back in to view,
						});
				}
				if (isie7) { 
					popup
						.css({
							marginLeft: ieLeftPos + "px" //fix position in ie6
					});
				}
				return false;
			}
		});
		popup.find(".btn-close-popup").click(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);
			 return false;
		});
	});

}

function numbersOnlyInput() {
	$(".input-bg01 input").keypress(function(e) {
		//if the letter is not digit then display error and don't type anything
		if (e.which != 8 && e.which != 0 && e.which != 13 && (e.which < 48 || e.which > 57)) {
			return false;
		}
	});
}

function Hoverbox() {
    $('.hoverbox-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 = $('.hoverbox', 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() + 2);
            leftPos = -10;
            $(this).removeAttr("title");

            // 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);
        });
    });

}

function ClearInput() {
	
	$(".global-search input:text").attr({ value: 'Search site' }).focus(function(){
            if($(this).val()=="Search site"){
               $(this).val("");
            }
       }).blur(function(){
            if($(this).val()==""){
               $(this).val("Search site");
            }
       });

}