/*
	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();
        InitHoverSwaps();
        Popupbox();
        ClearInput();
        InitHideShow();
        fancyCharacterCount();
		
		// Keep this to prevent js error in IE
		//var currentURL = window.location.pathname.toString().split("_")[0];
		//if((currentURL != "/") && (currentURL != "/default.aspx")) {
			//setSifrConfig();
		//}
		
        // 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 =
			[
			 	".brochure-promo img",
			 	".fCar a",
				".highlight-box img",
				".feature-8 img",
				".biNews img"
			].toString();

        (typeof DD_belatedPNG == "object") ? DD_belatedPNG.fix(DD_fix) : "";


        $(".link-no-scroll").attr("href", "javascript:void(0)");


        // Adds default blur text to all empty inputs with this class according to title="" attribute
        $(".fieldhint").fieldhint();

        // maintenance page full height bcg
        $(".pMaintenance").parents("html").height("100%");

        // Applies tooltip functionality
        tooltip();

    });
}

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.png", "_1.png");
				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 InitHoverSwaps()
{
	$(".hoverswap").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()");
				if (imageSrc.indexOf(".gif") > -1) {
					eval("b" + imageName + preloadLoop + ".src = 'Assets/swap_" + imageName + "_" + preloadLoop + ".gif'");
				} else if (imageSrc.indexOf(".jpg") > -1) {
					eval("b" + imageName + preloadLoop + ".src = 'Assets/swap_" + imageName + "_" + preloadLoop + ".jpg'");
				} else if (imageSrc.indexOf(".png") > -1) {
					eval("b" + imageName + preloadLoop + ".src = 'Assets/swap_" + imageName + "_" + preloadLoop + ".png'");
				}
			}
		}
		$(this).mouseover(function(){
			if ($(this).attr("class").indexOf("btn-disabled")<=-1)
			{
				$(this).attr("src", eval("b" + imageName + "1.src"));
			}
		});
		$(this).mouseout(function()
		{
			if ($(this).attr("class").indexOf("btn-disabled")<=-1)
			{
				$(this).attr("src", eval("b" + imageName + "0.src"));
			}
		});
		$(this).click(function()
		{
			$(this).attr("src", eval("b" + imageName + "2.src")).addClass("btn-disabled");
		});
		
	});
	
	$(".btn, .btn-small").click(function()
	{
		$(this).addClass("btn-disabled"); /* THIS NEEDS TO BE CHANGED to add another class that includes what the button says, e.g. "btn-close" becomes "btn-close btn-close-disabled" */
	});
}

function numbersOnlyInput() {
	$(".find-a-dealer .box01 .input-bg01 input, .popup_postcode .input01, input.numbers-only").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 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 = -55;
			
			ieTopPos = -(popup.height() + 5);
			ieLeftPos = -75;
			
			// 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 ClearInput() {
	
   var clearInputPrevious = '';
   // clear input on focus
	$('input:text').focus(function()
	  {
			if($(this).val()==$(this).attr('title'))
			{
				  clearInputPrevious = $(this).val();
				  $(this).val('');
			}
	});                       
	  // if field is empty afterward, add text again
	  $('input:text').blur(function()
	  {
			if($(this).val()=='')
			{
			$(this).val(clearInputPrevious);
			}
	});

}

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();
    }
  });
}

function InitHideShow()
{
	// hide all but the first
	var otherItems = $(".mList li");
	$(otherItems).removeClass("active");
	
	$(".mTitle").click(function()
	{
		var module = $(this).parent();
		
		if ($(module).hasClass("active")) {
				 module.removeClass("active");
    }
    else {
        $(".mList li").removeClass("active");
				module.addClass("active");
    }

		return false;
	});
}

function resizeFancybox() {
	var bodyHeight = $('body').outerHeight(true),
		parentDoc = window.parent.document,
		fancybox = $(parentDoc).find('#fancybox-inner'),
		fancyboxParent = $(fancybox).parents('#fancybox-wrap'),
		fancyboxHeight = $(fancybox).height();
		
	if(bodyHeight > fancyboxHeight) {
		fancybox.height(bodyHeight);
		fancyboxParent.height(bodyHeight+60);
	}
	else if(bodyHeight < fancyboxHeight) {
		fancybox.height(bodyHeight);
		fancyboxParent.height(bodyHeight+60);
	}
}

// Simple tooltip script without the need for plugins
this.tooltip = function() {
    /* CONFIG */
    var xOffset = -198;
    var yOffset = 6;
    // these 2 values are fallback values if the browser fails to determine the offset		
    /* END CONFIG */

    // Glossary link tooltip
    $("a.glossary").hover(function(e) {
        
        xOffset = $(this).offset().left - 198;
        yOffset = $(this).offset().top + 6;
        this.t = this.title;
        this.title = "";
        $(this).css({ position: "relative" });

        $("body").append("<div id='popup'><div class='popup-top'>&nbsp;</div><div class='popup-content'><div class='popup-padding'><div class='container-info noborder'><h4 class='tooltipPopup'>" + this.t.split("::::")[0] + "</h4><p>" + this.t.split("::::")[1] + "</p></div></div></div><div class='popup-btm'>&nbsp;</div></div>");
        var tooltipHeight = $("#popup").height();
        $("#popup")
			.css({
			    top: (yOffset - tooltipHeight) + "px",
			    left: (xOffset) + "px"
			}).show();
    }, function() {
        this.title = this.t;
        $("#popup").remove();
    })
};

function fancyCharacterCount() {
    $('.EnquiryTypeTextArea').NobleCount('#characterCount', {
        on_negative: 'go_red',
        max_chars: 1000,
        block_negative: true
    });
};