
/*
	NOTE -:
	Am using $(window).load() for the image resizer because the javaScript needs to check
	image widths and heights. But, because webkit browsers (Chrome and Safari) loads
	JavaScript concurrently, rather than after the images & CSS, I need to wait
	until the pages are totally loaded.
*/
$(window).load(function() {
   	
	// =========================================== Stretch the sidebar on the static pages all the way down
	if(jQuery("#sidebar_inner").height() < jQuery("#sidebar_right").height()) { jQuery("#sidebar_inner").height(jQuery("#sidebar_right").height()) } 


	$(".carousel").jCarouselLite({
        btnNext: ".new_car_next",
        btnPrev: ".new_car_prev",
		visible: 4,
		auto: 3000,
	    speed: 400

    });	
	
	// *------------------------------------------------------------------------------------------------------- *
	// 	Shrink images down to fit within their wrappers.
	// 	USAGE: 	The parameters of this function is a string list - ala jQuery - of
	// 			the IDs and classes of the various wrappers surrounding the images you wish to shrink
	adjustThumbs(".listItemThumb, .details_thumbImg, .home_promotions a, .cma_image_thumb, .repairer_thumb");
	// *------------------------------------------------------------------------------------------------------- *
});

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

$(document).ready( function() {

	
	// =========================================== CODE FOR DROP-DOWNS IN PRIMARY NAVIGATION
	jQuery(".dropdownMenu").bgiframe();
	$(".primaryNav li").hover(
		function()
		{ 
			$(this).find(".dropdownMenu").parent().addClass("dropdownParentHover");
			$(this).find(".dropdownMenu").show();
			$(this).find(".dropdownMenu").hover(
				function()
				{
					$(this).find("a").hover(
						function() { $(this).find("img").css({"left": $(this).width(), "display":  "block"}); },
						function() {  }
					);	
				},
				function(){ /*$(this).parent().removeClass("dropdownParentHover"); $(this).hide();*/}
			); 
		},
		function()
		{ 
			$(this).removeClass("dropdownParentHover"); 
			$(this).find(".dropdownMenu, img").hide();
		}
	);

	// =========================================== ASSIGN ZEBRA CLASSES TO EVERY SECOND ITEM 
	var i = 0;
	jQuery(".details_specs table tr, .maincontent .form_row, .maincontent #sidebar_right .inner_content table tr, .news_headline").each( function(i){
		i % 2 == 0 ? jQuery(this).addClass("zebra_row_0") : jQuery(this).addClass("zebra_row_1");
		i++;
	});
	
	// =========================================== Apply SIFR to the header / site name
	/*
	if(typeof sIFR == "function")
	{
		// This is the preferred "named argument" syntax
		sIFR.replaceElement(named({sSelector:".header h1", sFlashSrc:"flash/Template1/nissanAGmedium.swf", sColor:"#FFFFFF", sWmode:"transparent", sCase: "upper"}));
		//sIFR.replaceElement(named({sSelector:".used_car_search h2", sFlashSrc:"flash/Template1/nissanAGmedium.swf", sColor:"#FFFFFF", sWmode:"transparent", sCase: "upper"}));
	};
	*/

	// =========================================== Apply the PNG fix for IE6
	$(document).pngFix(); 
	
	$(".home_tabs").tabs();
	
	jQuery(".lightbox, .lightbox a").lightBox();

   	$(".carsofweek_carousel").jCarouselLite({
        btnNext: ".carofweek_next",
        btnPrev: ".carofweek_prev",
		visible: 1,
		auto: 3000,
	    speed: 400

    });
    
    $(".promotions_carousel").jCarouselLite({
        btnNext: ".promotions_next",
        btnPrev: ".promotions_prev",
		visible: 1,
		auto: 4000,
	    speed: 400

    });
	
	// =========================================== SLIDERS FOR THE USED CAR SEARCH
	var getDate = new Date();
	var getYear = getDate.getFullYear() +1;
	 
	var currentYearFrom = querySt("YearFrom");
	var currentYearTo = querySt("YearTo");
	var currentPriceFrom = querySt("PriceFrom");
	var currentPriceTo = querySt("PriceTo");
	
	if (currentYearFrom==undefined){
	    currentYearFrom=1985;
	}
	if (currentYearTo==undefined){
	    currentYearTo=getYear;
	}
	if (currentPriceFrom==undefined){
	    currentPriceFrom=1000;
	}
	if (currentPriceTo==undefined){
	    currentPriceTo=50000;
	}
	
	//jQuery(".slider_handle_to").text("'" + getYear.toString().slice(2));
	
	jQuery(".slider-year").slider({
		range: true,
		animate: false,
		min: 1980, max: getYear,
		values: [currentYearFrom, currentYearTo],
		slide: function(event, ui) {
			jQuery(".tooltip_current_year").show();
			jQuery(this).mousemove(function(e){
				jQuery(".tooltip_current_year").text(ui.value);
				jQuery(".tooltip_current_year").css({'left' : jQuery(ui.handle).css("left"), 'margin-left' : -( jQuery(".tooltip_current_year").width() /2)});
			});
			jQuery(".slider_year_from").val(jQuery(".slider-year").slider("values", 0));
			jQuery(".slider_year_to").val(jQuery(".slider-year").slider("values", 1));
		},
		stop: function(event, ui) {/* jQuery(".tooltip_current_year").hide(); */
		    jQuery(".tooltip_current_year").blur(function(){
		            jQuery(this).hide();
		        }
		    );
		}
	});
	jQuery(".slider_year_from").val(currentYearFrom);
	jQuery(".slider_year_to").val(getYear);

	jQuery(".slider-price").slider({
		range: true,
		animate: true, 
		step:500,
		min: 500, max: 99999,
		values: [currentPriceFrom, currentPriceTo],
		slide: function(event, ui) {
			jQuery(".tooltip_current_price").show();
			jQuery(this).mousemove(function(e){
				jQuery(".tooltip_current_price").text(ui.value);
				jQuery(".tooltip_current_price").css({'left' : jQuery(ui.handle).css("left"), 'margin-left' : -( jQuery(".tooltip_current_price").width()/2)});
			});
			jQuery(".slider_price_from").val(jQuery(".slider-price").slider("values", 0));
			jQuery(".slider_price_to").val(jQuery(".slider-price").slider("values", 1));
		},
		stop: function(event, ui) { /*jQuery(".tooltip_current_price").hide();*/ }
		
	});
	jQuery(".slider_price_from").val(currentPriceFrom);
	jQuery(".slider_price_to").val(currentPriceTo);


	// =========================================== KEYBOARD EVENTS
	$(document).keypress( function (e) {
		if(e.which == 120 && jQuery(".overlay").css("visibility") == "visible" )
		{
			jQuery(".overlay").css( { "visibility" : "hidden" } ); 
		}
	});
	
	/* =========================================== Find out if the difference between the foreground and background colours is ok. If not, assign a class. */
	var colourTabVal, colourTabText;
	var background, foreground;
	jQuery(".colourTab").each(function(){
		colourTabVal = jQuery(this).css("background-color");
		colourTabText = jQuery(this).css("color");
		background = colourTabVal.slice(4, (colourTabVal.length)-1).split(", ");
		foreground = colourTabText.slice(4, (colourTabText.length)-1).split(", ");
		luminosityCheck(background[0], background[1], background[2], foreground[0], foreground[1], foreground[2]) > 4 ?  jQuery(this).addClass("darkBG") : jQuery(this).addClass("lightBG"); 
	});
});

/* --------------------------------------------------------------- 
 	Return the Luminosity value between two colours; a value 
 	less than 5 means the two colours are too similar
--------------------------------------------------------------- */
function luminosityCheck(r1, g1, b1, r2, g2, b2)
{
	var l1 = 	0.2126 * Math.pow(r1/255, 2.2) +
          		0.7152 * Math.pow(g1/255, 2.2) +
          		0.0722 * Math.pow(b1/255, 2.2);
	var l2 = 	0.2126 * Math.pow(r2/255, 2.2) +
          		0.7152 * Math.pow(g2/255, 2.2) +
          		0.0722 * Math.pow(b2/255, 2.2);
 	if(l1 > l2){
        return (l1+0.05) / (l2+0.05);
    }else{
        return (l2+0.05) / (l1+0.05);
    }


}

function showOverlay(e)
{
	jQuery(e).children(".overlayBG").bgiframe(); 						// Fix IE6 problem with input boxes
	jQuery(e).children(".overlayBG").height(jQuery(document).height());		// Set the overlay background to height of the page area
	jQuery(e).children(".overlayBG").fadeTo("fast", 0.8);					// Fade out the overlay background
	jQuery(e).css({"visibility" : "visible"}); 
	var indent = (jQuery(document).width() - jQuery(e).children(".popup_body").width()) / 2;
	jQuery(e).children(".popup_body").css( { "left" : indent } );
	jQuery("html, body").animate( { scrollTop: 0 }, "normal");
}

/* ----------------------------------- CALL THIS FUNCTION WHEN CANCELLING THE POPUP ----------------------------------- */
function closeOverlay(e)
{
	jQuery(".overlay").css({"visibility" : "hidden"});
}

// Adjust various images based on the wrappers containing them. 
// Call function as follows: adjustThumbs(strArgs);
// Where strArgs is a string list of the classes / IDs of the wrappers
function adjustThumbs(strArgs)
{
	var imgWrapperWidth, imgWidth, widthDiff;
	var imgWrapperHeight, imgHeight, heightDiff;
	
	jQuery(strArgs).each(function() 
	{
		imgWrapperWidth = jQuery(this).width();
		imgWidth = jQuery(this).find("img").width();
		imgWrapperHeight = jQuery(this).height();
		imgHeight = jQuery(this).find("img").height();
		
		if(imgWidth > imgWrapperWidth || imgHeight > imgWrapperHeight)
		{
			var widthProp = imgWidth / imgWrapperWidth;
			var heightProp = imgHeight / imgWrapperHeight;
			
			if(widthProp > 1 && ((1 / widthProp) * imgHeight) > imgWrapperHeight)
			{
				jQuery(this).find("img").css({"width" : parseInt((1 / widthProp) * imgWidth), "height" : parseInt((1 / widthProp) * imgHeight) });
			}
			
			if(heightProp > 1 && ((1 / heightProp) * imgWidth) > imgWrapperWidth)
			{
				jQuery(this).find("img").css({"width" : parseInt((1 / heightProp) * imgWidth), "height" : parseInt((1 / heightProp) * imgHeight) });
			}
			
			widthDiff = jQuery(this).find("img").width() - imgWrapperWidth;
			heightDiff = jQuery(this).find("img").height() - imgWrapperHeight;
			jQuery(this).find("img").css({"margin-left" : parseInt(-(widthDiff / 2)) });
			jQuery(this).find("img").css({"margin-top" : parseInt(-(heightDiff / 2)) });
		}
		else
		{
			jQuery(this).find("img").css({"margin-left" : parseInt((imgWrapperWidth - imgWidth) / 2), "margin-top" : parseInt((imgWrapperHeight - imgHeight) / 2) });
		}
		
	});
}


/***********************************************
* Bookmark site script- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}
 
function showHide(x)
{
	jQuery(x).toggle("normal", function(){
		if(jQuery("#sidebar_inner").height() < jQuery("#sidebar_right").height()) { jQuery("#sidebar_inner").height(jQuery("#sidebar_right").height()) } 						
	});
	
}



