/*..............................................................................
...............................I$$Z$$$$$$$$$$Z$,................................
........................IZ$$$$$$$$$$$$$$$$$$$$$$$$$$$$..........................
................. ..$$$$$$$~..$$$$$$...............$$Z$$$$......................
.................Z$$$$.......$$$$$$...................$$$$$$$...................
...............Z$$Z........+$$$$$$..................$$$$$$$$$$$,................
.............~$ZZ.........$$$$$$$............... Z$Z$$$$$$...+$$$...............
............$$$..........$$$$$$$$........... +$$$$$$$$$$$=.....$$Z .............
...........,$$..........Z$$$$$$$$~.......$$$$$$$$$$$$$$$$.......$$Z.............
...........$$:..........$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$Z.........$$.............
...........$$..........$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ .........$$.............
...........7$$........$$$$$$$$$$$$$$$$$$.. .$$$$$$$$$$..........7$$.............
............$$Z......Z$$$$$$$$$$$$$..........$$$$$$$$...........$$..............
.............$Z$....$$$$$$$$$$$..............$$$$$$$..........$Z$...............
..............$$$Z..$$$$$$$?................+$$$$$$........ $$$$................
................Z$$$$$$Z7...................$$$$$$.......~$$$$..................
...................Z$$$$I.. ...............$$$$$Z....~$$$$$?....................
......................$$$$$$$$$7.........Z$$$$$$$$$$$$$$........................
...........................+$$$$$$$$$$$$$$$$$$$$$$$.............................
................................................................................
................................................................................
................................................................................
................................ ...............................................
.$$$.....$$=.$$$.....Z$$.$$$.....$$..:$$$$$$$$$...$$$$$$$$$....$$$$$$$$$=..$$...
.$$$.....$$=..$$Z...$$$..$$$.....$$..:$$$$$$Z$$$..$$$$$$$$$$..$$$$$$$$$$=..$$...
.$$$.....$$=...$$$.$$$...$$$.....$$..:$$.....$$$..$$.....$$$..$$:.....$$=..$$...
.$$$$$$$$$$=....$$$$$....$$$.....$$..:$$.....$$$..$$.....$$$..$$:.....$$=..$$...
.$$Z.....$$=.....$$$.....$$$.....$$..:$$.....$$$..$$.....$$$..$$$$$$$$$$=..$$...
.$$$.....$$=.....$$$.....$$$.....$$..:$$.....$$$..$$.....Z$$..$$:....,$$=..$$...
.$$$.....$$=.....$$$.....$$$$$$$$$$..:$$.....$$$..$$$$$$$$$$..$$:.....$$=..$$...
................................................................................
..............................................................................*/

/* ########################################################################### *
/* ##### MODULE          : MAIN
/* ##### AUTHORS         : TIM MACKAY & KRISTIAN TASEVSKI
/* ##### CONTACT         : TMACKAY@DELOITTE.COM.AU & KTASEVSKI@DELOITTE.COM.AU
/* ##### LAST MODIFIED   : 24/09/2010
/* ########################################################################### */

/* Declare a namespace for the site */
/* Global variables */


var pageFeature_height;
var dropDownHeight;
var dropIsAnimating = false;
var hoveringIn = false;
var hoveringOut = false;


$(document).ready(function () {

    menu_init();
    showroomSubnav();
    removeUnwantedText();
    $('input').customInput();

    //gets the previous sibling of the currently selected item and changes its bottom
    // border from a dotted border to a solid border
    articleSubNavStyles();

    //DOM helper function that adds first class to selected elements
    isLast("#nav_vehicle_selector_block > .nav_vehicle:nth-child(3n)");
	isLast(".opportunities_table .meta .sub:nth-child(3n)");
    isFirst(".article_text > .article_related");
    isFirst(".landing_page > .article");
    //addClearBefore(".footer-wrap");
    addEvenClass();

    //Set initial values of search boxes in footer
    setInputValues();

    //Visual Initialisation
    visualInit();

    //Functional Initialisation
    functionalInit();


    //Gets the wallpaper from an inline image on the page and appends it to the pagewrapper div
    setWallpaper();

    //IE Fixes
    init_classHelpers();
});


function functionalInit() {
	eventsExpandContract();
	showHomeBgFlash();
	pricingLandingPostcode();
	clearInputs();
	pricingOffersIframe();
	tabsMenu();
	newsArchiver();
	footerSearch();
	faqPage();
	pricingDetailsRevealMore();
	//resizeIframe(height);
}
	
function visualInit() {
	breadCrumbFix();
	//readMoreLink();
	highlightActiveSidepanelItems();
	bindNavVehicleHover();
	removeActiveLink();
	currentNavSibling();
	pageActions();
	boldNumberList();
	pricingLandingMarginFix();
	fixPagination();
	padIndexPageArticles();
	showSubItems();
	fixHovers();
	removeEmptyCategories();
	//buildUp();
}

    function eventsExpandContract() {
        if($('.events').html() == null){
            return;
        }

        // IE7 fix

        if (isIE(7, true) || isIE(8, true)) {
            
            $('.events .region .event table tbody tr:nth-child(2n-1)').css('background','#eaeaea');
         
        }

        var expandedHeight = 0;

        $('.region').each(function () {
            $(this).find('.event').each(function (index) {
                expandedHeight = $(this).parents('.region').height();
                if (index == 0) {
                    $(this).parents('.region').data('expandedHeight', expandedHeight);   
                }
                $(this).parents('.region').height(50);
            });
        });

        $('.events h3 a').bind('click', function () {

            var contractedHeight = 50;
            var isOpen = false;

            var thisRegion = $(this).parents('.region');
            var thisRegionHeight = $(this).parents('.region').height();

            // Should expand it
            if ($(this).hasClass('fn_region_expand')) {
                $(this).removeClass('fn_region_expand');
                $(this).addClass('fn_region_contract');

                expandedHeight = $(thisRegion).data('expandedHeight');

                $(thisRegion).animate({
                    height: expandedHeight
                }, 400, function () {
                    // Animation complete.
                });
            }

            // Should contract it
            else if ($(this).hasClass('fn_region_contract')) {
                $(this).removeClass('fn_region_contract');
                $(this).addClass('fn_region_expand');

                $(thisRegion).animate({
                    height: 50
                }, 400, function () {
                    // Animation complete.
                });
            }

            else {
                //"Error: Unknown class for anchor"
            }


            return false;
        });
    }

    function pricingDetailsRevealMore() {

        if ($('.pricing_details').html() == null) {
            return;
        }

        var offerCounter = 0;
        var htmlContainer;
        var shouldShowLink = false;
        var hasTerminatedDiv = false;
        var shouldOpen = true;

        

        $('.offer').each(function (index) {
            offerCounter++;

            if (index == 4) {
                shouldShowLink = true;
            }

            if (index > 3) {
                $(this).hide();
                $(this).css('border-bottom','none');
            }
        });

        if (shouldShowLink) {
            $('.offer').wrapAll("<div class='offerRow clearfix'/>");
            $('.offer:last').after("<p class='showMoreOffers'>View more prices</p>");
        }

        else {
            $('.offer').each(function (index) {
                $(this).css('border-top','1px solid #DEDEDE');
                $(this).css('border-bottom','1px solid #DEDEDE');
            });
        }


        // showMoreOffers hover handler
        $('.showMoreOffers').hover(function () {
            $(this).toggleClass('showMoreOffersHovered');
        });

        $('.showMoreOffers').bind('click', function () {

            $('.offer').each(function (index) {
                if (shouldOpen) {
                    if (index < 4) {
                        $(this).css('border-bottom','1px solid #DEDEDE');
                    }
                    $(this).fadeIn();
                }

                else {
                         //$(this).css('border-bottom', 'none');
                         if (index > 3) {
                            $(this).fadeOut();
                        }
                }

            });

            if (shouldOpen) {
                $(this).html('View less prices');
                $(this).css('border-top', '1px solid #DEDEDE');
                shouldOpen = false;
            }

            else {
                $(this).html('View more prices');
                $(this).css('border-top', 'none');
                shouldOpen = true;
            }

        });

    }
	
    function faqPage() {
        var openedCounter = 0;

        if ($('.faq_table').html() == null) {
            return;
        }

        // Hover handler for the switch
        $('.switch').bind('mouseover', function () {
            $(this).addClass('faqswitchHovered');
        });

        $('.switch').bind('mouseout', function () {
            $(this).removeClass('faqswitchHovered');
        });

        // Set heights of each of the faq sections
        $('.faq_table .faq').each(function () {
            var thisHeight = $(this).height();
            $(this).css('height', thisHeight);
        });

        $('.toHide').hide();

        // Click handler for h4
        $('.faq_table .faq h4').bind('click', function () {


            var currentState = $(this).parent().find('p.answer').attr('style');

            if (currentState != null) {
                currentState = currentState.toLowerCase();
            }

            if (currentState == null || currentState.search("none") != -1 || currentState == "") {
                $(this).parent().find('p.answer').fadeIn();
                $(this).css('background-position', '0 -39px');
                openedCounter++;

                var newHeight = $(this).parent().height() + $(this).parent().find('p.answer').height() + 15;
                $(this).parent().animate({
                    height: newHeight
                }, 400, function () {
                    // Animation complete.
                });
            }

            else {
                $(this).parent().find('p.answer').fadeOut();
                $(this).css('background-position', '0 2px');
                openedCounter--;

                var newHeight = $(this).parent().height() - $(this).parent().find('p.answer').height() - 15;
                $(this).parent().animate({
                    height: newHeight
                }, 400, function () {
                    // Animation complete.
                });
            }


            var totalCounter = 0;

            $(this).parents('.faq_listing').find('.faq p.answer').each(function () {
                totalCounter++;
            });

            // expand all and contract all logic
            if (openedCounter == 0) {
                var thisClass = $(this).parents('.faq_listing').find('h3 a').attr('class');
                thisClass = thisClass.replace('faqswitchExpand', '');
                thisClass = thisClass.replace('faqswitchContract', '');
                thisClass = thisClass + "faqswitchExpand";
                $(this).parents('.faq_listing').find('h3 a').attr('class', thisClass);

                $(this).parents('.faq_listing').find('h3 a span').attr('class', 'faqexpandOpen');
            }

            else if (openedCounter == totalCounter) {

                var thisClass = $(this).parents('.faq_listing').find('h3 a').attr('class');
                thisClass = thisClass.replace('faqswitchExpand', '');
                thisClass = thisClass.replace('faqswitchContract', '');
                thisClass = thisClass + "faqswitchContract";
                $(this).parents('.faq_listing').find('h3 a').attr('class', thisClass);

                $(this).parents('.faq_listing').find('h3 a span').attr('class', 'faqexpandClose');
            }

        });

        // Click handler for contract all
        $('.faq_listing .faqswitch span').bind('click', function () {

            var thisParentClass = $(this).parent().attr('class');

            if (thisParentClass.search('faqswitchExpand') != -1) {
                thisParentClass = thisParentClass.replace('faqswitchExpand', '');
                thisParentClass = thisParentClass + 'faqswitchContract';
                $(this).parent().attr('class', thisParentClass);
            }

            else if (thisParentClass.search('faqswitchContract') != -1) {
                thisParentClass = thisParentClass.replace('faqswitchContract', '');
                thisParentClass = thisParentClass + 'faqswitchExpand';
                $(this).parent().attr('class', thisParentClass);
            }

            var thisClass = $(this).attr('class')

            if (thisClass.search('Close') != -1) {
                $(this).removeClass('faqexpandClose');
                $(this).addClass('faqexpandOpen');

                $(this).parents('.faq_listing').find('.faq p.answer').each(function () {
					var isThisOpened = $(this).parent().find('h4').css('backgroundPosition');
					
					if(isThisOpened != null){
						if(isThisOpened.search("2px") == -1){
							$(this).parent().find('h4').css('background-position', '0 2px');
		                    $(this).fadeOut();
		                    openedCounter--;

		                    var newHeight = $(this).parent().height() - $(this).parent().find('p.answer').height() - 15;
		                    $(this).parent().animate({
		                        height: newHeight
		                    }, 400, function () {
		                        // Animation complete.
		                    });
						}
					}
					
					else {
						$(this).parent().find('h4').css('background-position', '0 2px');
	                    $(this).fadeOut();
	                    openedCounter--;

	                    var newHeight = $(this).parent().height() - $(this).parent().find('p.answer').height() - 15;
	                    $(this).parent().animate({
	                        height: newHeight
	                    }, 400, function () {
	                        // Animation complete.
	                    });
					}
					
					
					
                });
            }

            else if (thisClass.search('Open') != -1) {
                $(this).removeClass('faqexpandOpen');
                $(this).addClass('faqexpandClose');

                $(this).parents('.faq_listing').find('.faq p.answer').each(function () {
					var isThisOpened = $(this).parent().find('h4').css('backgroundPosition');

					if(isThisOpened != null){
						if(isThisOpened.search("2px") != -1){
							$(this).parent().find('h4').css('background-position', '0 -39px');
		                    $(this).fadeIn();
		                    openedCounter++;
		                    var newHeight = $(this).parent().height() + $(this).parent().find('p.answer').height() + 15;
		                    $(this).parent().animate({
		                        height: newHeight
		                    }, 400, function () {
		                        // Animation complete.
		                    });
						}
					}
					
					else {
						$(this).parent().find('h4').css('background-position', '0 -39px');
	                    $(this).fadeIn();
	                    openedCounter++;
	                    var newHeight = $(this).parent().height() + $(this).parent().find('p.answer').height() + 15;
	                    $(this).parent().animate({
	                        height: newHeight
	                    }, 400, function () {
	                        // Animation complete.
	                    });
					}
				 
                });
            }


        });

    }

    function footerSearch() {

        // Check if they entered an invalid entry into the postcode search

        $(".footer .search_block input[type='submit']").each(function (index) {

            $(this).parent().find("input[type='text']").keypress(function (event) {
                
                var thisValue = $(this).attr('value');
                if (event.keyCode == 13) {
                    $(this).parent().find("input[type='submit']").click();
                }
                //$('.top input#ctl00_HYU_PriceOffers1_txtTopPostcode').attr('value',thisValue);
            });


            if (index == 1) {

                $(this).bind('click', function () {

                    var inputValue = $(this).parent().find("input[type='text']").attr('value');
                    if (inputValue.search("Enter") != -1 || inputValue == "" || inputValue.length < 4 || isNaN(inputValue / 4) == true) {
                        $(this).parent().find("input[type='text']").attr('value', 'Enter a postcode');
                        $(this).parent().find("input[type='text']").css('color', 'red');
                        return false;
                    }


                });

                $(this).parent().find("input[type='text']").bind('blur', function () {
                    $(this).css('color', '#9E9E9E');
                })

                $(this).parent().find("input[type='text']").bind('focus', function () {
                    $(this).css('color', '#9E9E9E');
                })

            }

        });

		// Check to see if the invalid postcode error control is showing. If so, change the colour of the text
		if($('.checkPostcodeFormat').css('visibility') == 'visible'){
			$('.checkPostcodeInput').css('color', 'red');
		}

    }

    function showHomeBgFlash() {

        var windowWidth = $(window).width();
        if (windowWidth < 981) {
            $('#flashWrapper').html("<img src='" + wallpaper +"'/>");
            var wallpaper = $('#wallpaper img').attr("src");
            var wallpaperColor = $('#wallpaper').css("background-color");
            $("body").css({ backgroundImage: "url(" + wallpaper + ")", backgroundPosition: "center top", backgroundRepeat: "no-repeat", backgroundColor: wallpaperColor });
            $("body").css("width","900");
            $('#aspnetForm').css('background', 'none');
            return;
        }

        // If no javascript
        if ($("#flashWrapper").html() != null) {
            $("#flashWrapper").show();

        }

        
        if ($('div.edit-buttons').html() != null) {
            $("#flashWrapper").css('position', 'relative');
            $("#flashWrapper").css('top', '30px');
        }


    }

    function newsArchiver() {
        
        if($('.sidepanel .refinewidget').html() == null){
            return;
        }

        var isFirstItem = true;
        
        years = [];

        // build the years array and the navigational list items
        $('.sidepanel .refinewidget li').each(function(){
            var haveFoundMatch = false;
            var thisYear = $(this).find('span a span').html();
            thisYear = thisYear.substring(thisYear.indexOf("20"), thisYear.length);

            // first check that the information extracted is actually a year ( 4 digits and that it is a number )
            if(thisYear.length == 4 && (thisYear / 4) > 0){
                $(this).hide();
                // always push first item
                if(isFirstItem == true){
                    years.push(thisYear);
                    isFirstItem = false;
                    $(this).before("<li class='navigationListItem'><span><span><a href='#'><span class='RefineWidgetLinkText'>" + thisYear + "</span></a></span></span></li>");
                    
                }

                // loop through years array, if this item is already in the array
                for(var i=0; i<years.length; i++){
                    if(thisYear == years[i]){
                        haveFoundMatch = true;
                    }
                }

                // if there is no match, add
                if(haveFoundMatch == false){
                    $(this).before("<li class='navigationListItem'><span><span><a href='#'><span class='RefineWidgetLinkText'>" + thisYear + "</span></a></span></span></li>");
                    years.push(thisYear);
                }
            }
  
        });

        // click handler for the navigation list items
        $('.navigationListItem').bind('click', function () {
            var navigationYear = $(this).find('span a span').html();
            $('.sidepanel .refinewidget li').each(function () {

                var haveFoundMatch = false;
                var thisYear = $(this).find('span a span').html();
                thisYear = thisYear.substring(thisYear.indexOf("20"), thisYear.length);

                if (thisYear.length == 4 && (thisYear / 4) > 0) {

                    if ($(this).hasClass('navigationListItem') == false) {
                        $(this).hide();
                    }

                    if (thisYear == navigationYear) {
                        $(this).show();
                    }
                }
            });
            return false;
        });

        // if there is an active item, open the appropriate archive
       var activeYear = $('.sidepanel .refinewidget li.active').find('span a span').html(); 
       
       if(activeYear == null){
        return false;
       }
       
       activeYear = activeYear.substring(activeYear.indexOf("20"), activeYear.length);

        $('.navigationListItem').each(function(){
                var navigationYear = $(this).find('span a span').html();
                if(navigationYear == activeYear){
                    $(this).click();
                }
        });

    }

    function tabsMenu() {
        if($('.tabs-menu').html() == null){
            return;
        }

        var thisURL;
        var currentShown;

        $('.tabs-menu li').bind('click', function(){
            thisURL = $(this).find('a').attr('href');
            currentShown = $(this).parents('.tabs-menu').find('li.current a').attr('href');

            if(thisURL == currentShown ){
                return;
            }

            $(currentShown).hide();
            $(thisURL).fadeIn();

            $(this).parents('.tabs-menu').find('li.current').removeClass('current');
            $(this).addClass('current');
            $(this).parents('.tabs-menu').find('.previousListItem').removeClass('previousListItem');
            $(this).prev().addClass('previousListItem');
            return false;
        });



        
    }

    function fixHovers() {
        if($('.newsItems .article_back').html() != null){
            $('.newsItems .article_back').hover(
              function () {
                $(this).toggleClass("article_back_hovered");
              });

        }

        if($('.pricing_details .greyButton').html() != null){
            $('.pricing_details .greyButton').hover(
              function () {
                $(this).toggleClass("greyButtonHovered");
              });


        }

        $('.nav_vehicle_link_inner').each(function(){
            $(this).hover(
              function () {
                $(this).toggleClass("nav_vehicle_link_inner_hovered");
                $(this).parent().toggleClass("nav_vehicle_link_wrapper_hovered");
              });
        });

    }

    function buildUp(){
    $('.article').hover(function(e) {
      
      var this_ = $(this).html();
      $('.article').each(function(){
            if($(this).html() != this_){
                $(this).hoverFlow(e.type, { opacity: 0.5, top: 10 }, {
              duration: 600, 
              complete: function() {
                
              }});
            }
      });
        
      }, function(e) {

       $('.article').each(function(){
            $(this).hoverFlow(e.type, { opacity: 1, top: 0 }, 'fast');
        });
        
      });


    }

    function showSubItems() {
        $('.subItem').each(function(){
            $(this).show();
        });
    }

    function pricingOffersIframe() {
        if($('.pricing_details').html() != null){
             $('.dealerLocator').hide();
            $('.right .quicklinks #dealer').bind('click', function(){
                $(this).toggleClass('active');
                $('.dealerLocator').toggle();
            });
        }

    }
    
    var isFirstClick = true;
    var origValue;

    function clearInputs(){
        
        $('input[type="text"]').bind('focus',function(){
        
            var thisValue = $(this).attr('value');
            
            if($(this).attr('title') == ""){
                origValue = $(this).attr('value');
                $(this).attr('title', origValue);
                isFirstClick = false;
            }

            if(thisValue == $(this).attr('title')){
                $(this).attr('value','');
            }


        });

         $('input[type="text"]').bind('blur',function(){
        
            var thisValue = $(this).attr('value');

            if(thisValue == ''){
                $(this).attr('value',$(this).attr('title'));
            }
            isFirstClick = true;
        });

    }
	
	function padIndexPageArticles() {
        if($('.landing_page .article').html() != null){
            $('.landing_page .article:eq(0)').addClass("first");
        }
    }

    function fixPagination() {
        if($('.widgetPageLinks #NextLink').html() != null){
            var thisHTML = $('.widgetPageLinks #NextLink span').html();
            thisHTML = thisHTML.replace("&gt;","");
            $('.widgetPageLinks #NextLink span').html(thisHTML)
        }

        else if($('.SearchResults').html() != null){
            
            if($('#ctl00_ContentPlaceHolderMainNoAjax_pnlPageLinks').html() != null){
                var thisWholeHTML = $('#ctl00_ContentPlaceHolderMainNoAjax_pnlPageLinks').html();
                thisWholeHTML = thisWholeHTML.replace("Page","");
                $('#ctl00_ContentPlaceHolderMainNoAjax_pnlPageLinks').html(thisWholeHTML);
            }

            if($('#ctl00_ContentPlaceHolderMainNoAjax_NextLink').html() != null){
                var thisHTML = $('#ctl00_ContentPlaceHolderMainNoAjax_NextLink').html();
                thisHTML = thisHTML.replace("&gt;","");
                $('#ctl00_ContentPlaceHolderMainNoAjax_NextLink').html(thisHTML);

                $('#ctl00_ContentPlaceHolderMainNoAjax_NextLink').html(thisHTML + "<span class='chevronRight'></span>");
            }

            if($('#ctl00_ContentPlaceHolderMainNoAjax_PreviousLink').html() != null){
                var thisHTML2 = $('#ctl00_ContentPlaceHolderMainNoAjax_PreviousLink').html();
                thisHTML2 = thisHTML2.replace("&lt;","");
                $('#ctl00_ContentPlaceHolderMainNoAjax_PreviousLink').html(thisHTML2); 
                
                $('#ctl00_ContentPlaceHolderMainNoAjax_PreviousLink').html( "<span class='chevronLeft'></span>" + thisHTML2); 
            }
                    
        }
    }
	
	function resizeIframe(height) {
	
		if($('.dealerLocator').html() != null){
			//var iframeID = $('iframe').attr('id');
			var iframeID = $("iframe[id$='ifDealer']");
			//iframeID = iframeID.substring(iframeID.indexOf("ifDealer"),iframeID.length);
			document.getElementById(iframeID).height = parseInt(height)+60;
		}
	
		if($('#the_iframe').html() != null){
			// Resize iframe to full height
			// "+60" is a general rule of thumb to allow for differences in
		    // IE & and FF height reporting, can be adjusted as required..

		    if (!isNaN(parseInt(height) + 60)) {
		        document.getElementById('the_iframe').height = parseInt(height) + 60;
		    }   


			
		}
	}
	
    function pricingLandingPostcode(){
     
        $('.postcodeInput').attr('value','Postcode');


        if($('.pricing_landing').html() != null){
            $('.postcodeSearch').hide();
            $('.pricing_landing .offer input.orangeButton_large, .specialOffer input.orangeButton_small ').bind('click',function(){

                $('.postcodeSearch').each(function(){
                    $(this).fadeOut();
                });

                if( $(this).parent().find('.postcodeSearch').html() != null){
                    $(this).parent().find('.postcodeSearch').fadeIn();

				    return false;
                }
                
            });

            
            $('.postcodeSearch input[type="text"]').keypress(function(event) {
          
              var thisValue = $(this).attr('value');
              if(event.keyCode == 13){
			 
                $('.top .form span').hide();
                $(this).parent().find('input.postcodeSubmit').click();
              }
              //$('.top input#ctl00_HYU_PriceOffers1_txtTopPostcode').attr('value',thisValue);
            });
            
          
        }
        
    }
	
	//START DOM Helper functions
	function isLast(element) {
		$(element).addClass("is_last");
	}
	
	function pageActions(){
		$('#page_actions img').hover(
		  function () {
		    var thisSRC = $(this).attr('src');
			thisSRC = thisSRC.replace(".gif","");
			thisSRC = thisSRC + "-hover.gif";
			$(this).attr('src',thisSRC);
		  },
		  function() {
		    var thisSRC = $(this).attr('src');
			thisSRC = thisSRC.replace("-hover","");
			$(this).attr('src',thisSRC);
		  });
	}
	
	function isFirst(element) {
		$(element).first().addClass("is_first");
	}
	
	function bindNavVehicleHover(){
		$(".nav_vehicle").hover(function(){

        if($(this).hasClass('active')){
            return false;
        }
            $(this).toggleClass('hovered',250);
		});
	}
		
	function addClearBefore(element){
		$("<div class='clear' />").insertBefore(element);
	}
	function boldNumberList(){
		if($('ol li').html() != null){
		
			$('ol li').each(function() {
			//wrap each ol > li in a span so that our bold number effect renders properly, while
			//leaving the text normal weight.
		
				if($(this).find('p').eq(0).text()){
					// do nothing
					//$(this).css('border','1px dashed orange');
					return;
					
				} else{
					$(this).contents().wrap('<span />');
					//$(this).css('border','1px dashed purple');
				};
			});

		}
	}
	
	//Adds a class of 'even' to every second child element of the parent passed as argument
	function addEvenClass(){
		$("#searchResultsInfo li:nth-child(2n)").addClass("even");
	}

		
	// The global nav uses right borders to display the splits between nav items.
	// This function removes the right border from the previous sibling to the active item so that the visual layout doesn't look misaligned.
	function currentNavSibling() {
		$('.nav_global li.current').prev('li').find('span').css({border: "none"});
	}
	
	function menu_init(){
		// Store the original height of #page_feature for animation purposes
		pageFeature_height = $("#page_feature").css('height');

        // Highlight first selected car
        var firstCar = $(".nav_vehicle_selected img.selected_vehicle_logo").attr('src');
        if ($(firstCar).html() != null) {
					firstCar = firstCar.replace("_logo_small.jpg", "");
					firstCar = firstCar.replace("/Images/UserUploadedImages/", "");
					firstCar = firstCar.toLowerCase();
				}
				
        $('#nav_vehicle_selector_block .nav_vehicle').each(function(){
            var loopedCar = $(this).find('span').html();
            loopedCar = loopedCar.toLowerCase();

            if(firstCar.search(loopedCar) != -1){
                $(this).addClass('hovered active');
            }
        });
        

		/* Initialize hoverIntent delay plugin */
		var config = {
			sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
			interval: 20, // number = milliseconds for onMouseOver polling interval    
			over: hoverOver, // function = onMouseOver callback (REQUIRED)    
			timeout: 10, // number = milliseconds delay before onMouseOut    
			out: hoverOut // function = onMouseOut callback (REQUIRED)    
		};
		
		// remove the border after the last menu item
		$(".nav_global li:last span").css("background-image", "none");
		
		$(".primary").hoverIntent(config);
	}
		
	function hoverOver(e) {
  		var currNavItem = $(this);
     	// Get each of the list items and check if they have a subnav present (named 'dropdown')
  		currNavItem.each(function () {
  		    if ($(this).find('.dropdown').html() != null) {
  		        $(this).addClass("hovered", "50");
  		        $(this).find(".dropdown").fadeIn(100);
  		  
  		    }
  		});	
    }

	function hoverOut() {		
		$(this).removeClass("hovered","25");
		$(this).find(".dropdown").fadeOut(50);

  	}
	
    function navVehicleHoverOver(){
      $('.nav_vehicle.active').removeClass('hovered active');
      $(this).addClass('hovered active');
							
			// Check to see if the car that they clicked on is the one that is currently being displayed. In which case, the animation should not occur
				
			var currentCarText = $(this).find("span").text()
			currentCar = currentCarText.toLowerCase();
			
			visibleCar = $(".selected_vehicle_img").attr('src')
			visibleCar = visibleCar.replace("/Images/UserUploadedImages/","");
			visibleCar = visibleCar.replace("_large.jpg","");

			if(currentCar == visibleCar){
				// Same car !
				return
			}
			
			var navQuicklinks = [];
			var navQuicklinksTargets = [];
				
				$(this).find("ul li a").each(function(index){
					var thisHREF = $(this).attr('href');
					var thisTarget = $(this).attr('target');
					
					navQuicklinks.push(thisHREF);
					navQuicklinksTargets.push(thisTarget);
				});
				
				
			exploreURL = $(this).find(".exploreURL").text();
			
			$('.nav_vehicle_selected').fadeOut(200, function() {
				
				// The fadeOut animation has completed
				
				var imagePath = currentCar.replace(" ","_");
				
				$(".selected_vehicle_img").attr({src : "/Images/UserUploadedImages/" + imagePath + "_large.jpg"});
				$(".selected_vehicle_img").attr({alt : "Hyundai " + currentCar });	
				$(".selected_vehicle_logo").attr({src : "/Images/UserUploadedImages/" + imagePath + "_logo_small.jpg"});
				$(".selected_vehicle_logo").attr({alt : "Logo of Hyundai " + currentCar });	
				// $(".nav_vehicle_link_inner a").attr({href : "http://hyundai.com.au/" + currentCar});
				
				// Force width and height
				$(".selected_vehicle_img").attr({width : "286"});
				$(".selected_vehicle_img").attr({height : "175" });
				 
				// Update the Explore link	
				$(".nav_vehicle_selected .nav_vehicle_link_inner a").attr({href : "/" + exploreURL});
				$(".nav_vehicle_selected .nav_vehicle_link_inner a").html("Explore " + currentCarText);
				
				$('.nav_vehicle_selected ul li a').each(function(index,value){
					
					if(index >= navQuicklinks.length){
						$(this).parent().css('display','none');
					}
					else{
						$(this).parent().css('display','block');
						$(this).attr('href', navQuicklinks[index]);
						$(this).attr('target', navQuicklinksTargets[index]);
						
					}
				});
				
				$('.nav_vehicle_selected').fadeIn(200, function() {
					// The fadeIn animation has completed.
				  });
			  });
			
    }

    function navVehicleHoverOut() {

    }

	function showroomSubnav() {
		
		$(".selected_vehicle_img").attr({alt : "Hyundai i20"});	
		// get the current vehicle from the span title
		var currentCar;
		var exploreLink;
		var visibleCar;
        
        var config = {
			sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
			interval: 40, // number = milliseconds for onMouseOver polling interval    
			over: navVehicleHoverOver, // function = onMouseOver callback (REQUIRED)    
			timeout: 50, // number = milliseconds delay before onMouseOut    
			out: navVehicleHoverOut // function = onMouseOut callback (REQUIRED)    
		};
		
		$(".nav_vehicle").hoverIntent(config);

             $('.nav_vehicle').click(function() {
                var navigateTo = $(this).find(".exploreURL").text();
                navigateTo = "/" + navigateTo;
                window.location.href = navigateTo;
             });

		}


		
	function articleSubNavStyles() {
		$('.article_nav li.current').prev().find("a").css({
			borderBottom: "1px solid #dedede"
		})
		
        if($('.article_nav').html() == null){
            return;
        }

        $('.article_nav li.current').each(function(){

            var this_ = this;

            for(var i=0;i < 4; i++){
                var thisClass = $(this_).attr('class');
                thisClass = thisClass.search("topLevel");

                if(thisClass != -1){
                    $(this).addClass('currSibling');
                }

                else {
                    this_ = $(this).parent();
                }
            }

            
        });

		/* The solution below is much nicer but of course IE7 has to have a heart attack on the elegant solution hence the more complicated solution above ^
		var parentsArray = $('.article_nav li.current').parentsUntil('.article_nav');
		
		$(parentsArray[parentsArray.length - 2]).addClass('currSibling');
        */
	}
	
	function breadCrumbFix() {
		var breadCrumbs;
		if($('#breadcrumbs').html() == null) {
			return;
		}
		breadCrumbs = $('#breadcrumbs').html();

		while(breadCrumbs.search(" / ") != -1){
			breadCrumbs = breadCrumbs.replace(" / "," ");
		}
		
		$('#breadcrumbs').html(breadCrumbs);

		$('#breadcrumbs a').each(function () {
		    $(this).after("<img src='/Include/Hyundai/css/img/icon_chevron_right.gif'>");


		});
        	
	}
	
	function removeActiveLink(){
		if ($('.newsItems').html() != null) {
			$('.sidepanel li.active, .sidepanel dt.active').find('a').attr('href','');
			$('.sidepanel li.active, .sidepanel dt.active').find('a').click(function(){
				return false;
			});
		}
	}
	
	function readMoreLink() {
		if($('.newsItems').html() != null){
			$('.newsItems dd').each(function(){
				var readMoreLink = $(this).parent().find('dt a').attr('href');
				var thisHTML = $(this).html();
			$(this).parent().append("<div class='readMore'><a href='" + readMoreLink + "'>Read more</a></div>");
			});			
		}
	}
	
	function highlightActiveSidepanelItems() {
	
		var origPathname = window.location.href;
		var pathname = origPathname.substring(origPathname.indexOf("retain="), origPathname.length);

		$('.refinewidget li a span').each(function () {
		    var thisHTML = $(this).html();
		    var thisMonth = thisHTML.substring(0, 3);
		    var thisYear = thisHTML.substring(thisHTML.length - 4, thisHTML.length);
		    var searchString = thisMonth + "%20" + thisYear;


		    if (isIE(7, true)) {
		        searchString = searchString.replace('%20',' ');
		    }

		    if (pathname.search(searchString) != -1) {
		        $(this).parent().parent().addClass('active');
		    }

		    if (isNaN(thisYear / 4)) {
		        var thisHREF = $(this).parent().attr('href');
		        thisHREF = thisHREF.substring(thisHREF.indexOf("RefineModule="), thisHREF.length);

		        if (pathname.search(thisHREF) != -1) {
		            $(this).parent().parent().addClass('active');
		        }
		    }

		});
		
		var found = false;
		
		if(pathname.search("retain=") != -1){
			found = true;
		}
		
		if($('#section').hasClass('individualNewsItem') == true){
			found = true
		}
		
		if(found == true){
			$('.article_back').css("display","block");
		}
		
		else{
			$('.article_back').css("display","none");
		}
	}

	function removeEmptyCategories() {
	    var numberOfRefine;
	    if ($('.content_page .article .refinewidget').html() != null) {
	        $('.sidepanel .refinewidget').each(function (index) {
	            numberOfRefine = index;
	        });

	        numberOfRefine++;

            if(numberOfRefine < 2){
                var sidepanelHTML = $('.sidepanel').html();
                sidepanelHTML = sidepanelHTML.replace("Categories", "");
                $('.sidepanel').html(sidepanelHTML);
            }
        }

	}

		
	function removeUnwantedText() {
		//var searchText = $(".searchPanel:contains('_')");
		
		$('.searchPanel').contents().filter(function() {
		  return this.nodeType == 3;
			}).wrap('<p class="initial_search_value"></p>').end()
		}
		
	function setInputValues() {
		
		var searchVal = $('.footer .search_block .custom_input:eq(0) input').eq(0);
		searchVal.attr("value","Enter search");
		searchVal.focus(function(){
			if(this.value =='Enter search')
				{
					this.value = "";
				}
		});
		
		searchVal.blur(function(){
			if(this.value == '')
				{
					this.value = "Enter search";
				}
		});
		
		var locatorVal = $('.search_box input').eq(0);
		locatorVal.attr("value","Enter a postcode");
		locatorVal.focus(function(){
			if(this.value =='Enter a postcode')
				{
					this.value = "";
				}
		});
		locatorVal.blur(function(){
			if(this.value == '')
				{
					this.value = "Enter a postcode";
				}
		});
		
		var searchPageVal = $('#search_again input').eq(0);
		searchPageVal.attr("value","Enter search");
		searchPageVal.focus(function(){
			if(this.value =='Enter search')
				{
					this.value = "";
				}
		});
		searchPageVal.blur(function(){
			if(this.value == '')
				{
					this.value = "Enter search";
				}
		});
		
		$('.custom_radio_group .custom_radio input').eq(0).attr("checked", "checked");
		
		}
	
	
	function postcodeValue(){
		//Change input box to blank on form field focus
		var pcVal = $('.postcodeInput');
		pcVal.attr("value","Postcode");
		pcVal.focus(function(){
			if(this.value =='Postcode')
				{
					this.value = "";
				}
		});
		pcVal.blur(function(){
			if(this.value == '')
				{
					this.value = "Postcode";
				}
		});
	}


	$('.postcodeInput').click(function () {
	    //postcodeValue();
	});
	
	//Gets the wallpaper image from an inline image on the page and appends it to the pagewrapper tag.
	//The reason for this is Elcom.
	function setWallpaper() {
	    if ($('#pagewrapper').hasClass('landing_page') == true && $('#pagewrapper').hasClass('myhyundai_page')!=true) {
            return;
        }
		
		var wallpaper = $('#wallpaper img').attr("src");
		var wallpaperColor = $('#wallpaper').css("background-color");
		if ($("body").css('background-image') == null) {
			$("body").css({backgroundImage: "url('/Images/UserUploadedImages/140/fleet_wpCity.jpg')", backgroundPosition: "center top", backgroundRepeat: "no-repeat", backgroundColor : "#000000" });
} else {
			$("body").css({backgroundImage: "url(" + wallpaper + ")", backgroundPosition: "center top", backgroundRepeat: "no-repeat", backgroundColor : wallpaperColor });
		}

        //Concept cars background fix

        if($('#page_feature').find('#conceptCars').html() != null){
            $("body").css('backgroundPosition','center -52px');
        }
		
	}
	
	/* ########################################################################### *
	/* ##### CSS3 HELPER
	/* ########################################################################### */

	function init_classHelpers(){

		if(isIE(6, true)){

		}

		if(isIE(7, true)){
            selectorsFixes_firstChild();
			selectorsFixes_lastChild();
			selectorsFixes_nthChild();
		}
	}

    function selectorsFixes_firstChild(){
        
        if($('.awards_listing').html() != null){
            //$('.awards_listing:first').css('margin-top','-10px');
            $('.awards_listing:first').fadeOut();
            $('.awards_listing:first').fadeIn();
        }

    }
	
	function selectorsFixes_nthChild(){
		if($('.sitemap').html() != null){
			$('.utilities_page .sitemap ul li:nth-child(2)').css('background','#f3f3f3');
		}
	}

    function pricingLandingMarginFix() {
       if($('.pricing_landing').html() != null){

            $('.article > div.offer').each(function(index,value){
                if($('.pricing_landing .specialOffer').html() != null && ((index +1) % 4) == 0){
                    $(this).css('margin-right','0px');
                }

                else if ($('.pricing_landing .specialOffer').html() == null && index != 0) {
                    
                    if((index + 1) %5 == 0 ){
                        $(this).css('margin-right','0px');
                    }
                    
                }

            });

        }
    }
	
	function selectorsFixes_lastChild(){
		if($('.pricing_details').html() != null){
			$('.pricing_details .right .quicklinks ul li:last').css('margin-left','0px');
		}
		
		else if($('.pricing_landing').html() != null){
			$('.pricing_landing .right .offerRow .offer:last').css('margin-left','0px');
		}
		
		else if($('.sitemap').html() != null){
			$('.utilities_page .sitemap ul').each(function(){
				$(this).find('li:last').css("border-bottom","1px solid #c6c6c6");
			});
		}
		
	}
	
	/* ########################################################################### *
	/* ##### UTIL FUNCTIONS
	/* ########################################################################### */

	function isIE(version, lessThan){
		version = (version==undefined) ? 6 : version;
		lessThan = (lessThan==undefined) ? false : lessThan;

		if(lessThan){
			if (($.browser.msie)&&(parseInt($.browser.version)<=version)){
				return true;
			}
		} else {
			if (($.browser.msie)&&(parseInt($.browser.version)==version)){
				return true;
			}
		}

		return false;	
	}

	/* ########################################################################### *
	/* ##### HOVER INTENT INCLUDE
	/* ########################################################################### */

	/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
