// JavaScript Document

/* --------------- Functions that need to run after the document loads -------------------*/

$(document).ready(function(){
				
// collapse VIP and search area 
     $("#vip-expanded").hide();
     $("#search-expanded").hide();


// payment calculator functionality

if ($("#inv-payment").length) {
	
		var monthlypayment = 0;
		var price = 0;
		var downpayment = 0;
		var rate = 0;
		var term = 0;
		
		var monthlyestimate = 0;
		var vehicleCost = 0;
		
		var vehiclePageQuery = "";
		var newVehiclePageUrl = "";
		var usedVehiclePageUrl = "";
		
		function paymentCalculator() {
			downpayment = $('#inv-payment #downpayment-paymentcalc').val();
			price = $('#inv-payment #vehicleprice').val() - downpayment;
			term = $('#inv-payment #term-paymentcalc').val();
			
			if($('#inv-payment #apr-paymentcalc').val() != "" && $('#inv-payment #apr-paymentcalc').val() >= 0 ){
			rate = ($('#inv-payment #apr-paymentcalc').val()) / 100;
			ratePercent = ($('#inv-payment #apr-paymentcalc').val());
			}else {
				rate = 0;
				ratePercent = 0;
			}
			
			if(downpayment == "" || downpayment < 0 ){
				downpayment = 0;				
			}
			
			// calculate price
		
			var monthIntRate = rate / 12;
			ratePlus = eval(monthIntRate+1);
			pow = Math.pow( ratePlus, term );
			
			if(rate != 0){
				divider = (1 - (1 / pow)) / monthIntRate;
				monthlypayment = price / divider;
			}else{
				monthlypayment = price / term;
			}

			monthlypayment = Math.round(monthlypayment*100)/100;

			$('#inv-payment #monthlypayment').html(monthlypayment);			
		}
		
	// Payment Calculator calculations			   
	$('#inv-payment input').keyup(function(event) {
		paymentCalculator();										 
	});
	
	$('#inv-payment select').change(function(event) {
		paymentCalculator();										 
	});
	
	$(document).ready(function() {
		paymentCalculator();
		
		$('#inv-payment .close-btn').toggle(function(event) {
			$('#inv-payment-inner').slideUp('slow');
			$('#inv-payment .close-btn').html('[+] Show payment calculator');
			$('#inv-payment').removeClass('active');
	},function() {
			$('#inv-payment-inner').slideDown('slow');
			$('#inv-payment .close-btn').html('[-] Hide');
			$('#inv-payment').addClass('active');
		});
	});
	
}

//homepage footer text expand functionality

   $(".expand-btn").toggle(function(event){
     $("#footer-text p").show();
	 $(".expand-btn").html("Show Less...");
   }, function(event){
	   $("#footer-text p").not("#footer-text p.short-desc").hide();
	 $(".expand-btn").html("Show More...");
	   }
   );
   
/*
	$("#vip-coupon").mouseleave(function(event){
		$("#vip-expanded").fadeOut(300);
	});
   
	$("#vip-coupon select").mouseleave(function(event) { event.stopPropagation(); });
	$("#vip-coupon input").mouseleave(function(event) {
	event.stopPropagation();
	});
*/

// share this functionality on Model Landing pages

   $("#share-this-link").click(function(event){										
     $("#stwrapper").css({'visibility':'visible', 'top':'250px','left':'500px'});
     $("#stwrapper iframe").css({'visibility':'visible'});
		event.preventDefault();
		event.stopPropagation();  
	});	

// Load Images for rotation
	if($("body").is("#main")) {
		$.get("/site-resources/home-page-image-rotation.html", function(data){
			setupRotation(data);
		});
	}
	
	// radio buttons and checkboxes events work differently in IE. OnChange doesnt work the same.
	$("#inventory-search input").not("#search-stock input, input#search-submit").click(function(event){
		$("#inventory-search #search-submit").click();
	});
		
	$("#search-stock input, #inventory-search select").change(function(){
		$("#inventory-search #search-submit").click();
	});

});

/* -------------------------------------------------------------------- */

/* ---------- START EXTRA FUNCTIONS --------- */

function setupRotation (data) {

	//default values
	itemClass = "nav-item";
	itemFirstClass = "first-item";
	itemLastClass = "last-item";
	timerLen = 8000; // equals 3 secs
	elementID = "banner-counter";
	
	$('#featured-content').append('<a id="mainbanner-link"></a><ul id="banner-counter"></ul>');	

	//parse data
	itemArray = data.split(",");
	itemArray.splice(itemArray.length - 1, 1); // remove the extra data
	itemArrayLen = itemArray.length;
	// data format: pagetitle,imageurl,linkurl

	//load images
	for (x = 1; x < itemArrayLen; x = x + 3) {		
		//image
		tmpValue = itemArray[x];
		itemArray[x] = new Image();
		itemArray[x].src = tmpValue;
	}
	
	//create html for the gallery nav
	for (x = 0; x < (itemArrayLen/3); x++) {
		
		if (x == 0) {
			itemTmpClass = itemClass + ' ' + itemFirstClass;
		} else if (x == itemArrayLen - 1) {
			itemTmpClass = itemClass + ' ' + itemLastClass;
		} else {
			itemTmpClass = itemClass;
		}
			
		$('#' + elementID).append('<li class="' + itemTmpClass + '"><a>' + (x+1) + '</a></li>');	
	}
	
	// When the gallery nav is clicked switch banner
	$('#' + elementID + ' > ' + '.' + itemClass).click(function () {
		// Clear the old timer. Switch to the clicked item, and restart the timer.
		clearTimeout(bannerTimer);
		switchActive(this);
		bannerTimer = setTimeout("advanceActive()", timerLen);		
	});
	
	switchActive();
	bannerTimer = setTimeout("advanceActive()", timerLen);
}

function activateEl(elementRef) {
	$(elementRef).addClass("active");
	$(elementRef).siblings().removeClass("active");
}

function switchActive (elementRef) {
	
	// Find the next element or use the passed element reference
	if (elementRef == null) {
		object = $('#' + elementID + ' > ' + '.active').next('.' + itemClass);
	} else {
		object = elementRef;
	}
	
	// If at the end then start over
	if ($(object).length == 0) {
		object = $('#' + elementID + ' > ' + '.' + itemClass + ':first-child');
	}

	// Find the element index
	var itemIndex = $('#' + elementID + ' > ' + '.' + itemClass).index(object);
	
	// Set the image, title, and url live
	$("#mainbanner-link > span").text(itemArray[(itemIndex * 3)]);
	$("#featured-content").css("background-image", 'url(' + itemArray[(itemIndex * 3) + 1].src + ')');
	$("#mainbanner-link").attr('href', itemArray[(itemIndex * 3) + 2]);

	activateEl(object);
}

function advanceActive () {
	switchActive();
	bannerTimer = setTimeout("advanceActive()", timerLen);		
}

/* ----- SEARCH FUNCTIONS ----- */

function updateLists(parentID) {

	//initialize default values
	var xmlQuery = '';
	var stack = '';
	if (typeof success == "undefined") {success = true;}
	
	// Setup the firstLoad array.
	if (typeof firstLoad == "undefined") {firstLoad = new Array();}
	
	if (typeof firstLoad[parentID] == "undefined") {
		firstLoad[parentID] = true;
		
		// hide the other input fields in the search if search-stock has text
		var stockChange = function (event) {
			if($(this).val() != '') {
				$(this).siblings("select, input").not(".search-button").attr('disabled', true).css("color", "#bbb");
				$("#" + parentID + " .search-count").hide();
			} else {
				$(this).siblings("select, input").not(".search-button").removeAttr('disabled').css("color", "#000");
				$("#" + parentID + " .search-count").show();
			}
		};
		
		$("#" + parentID + " .search-stock-num").keyup(stockChange);
		$("#" + parentID + " .search-stock-num").change(stockChange);
		$("#" + parentID + " .search-stock-num").mouseenter(stockChange);

	}
	
	// Prevent multiple calls at once
	$("#" + parentID + " select").unbind("change");
	$("#" + parentID + " .loading").text("Loading please wait...");

	// track selected items
	var selectArray = new Array();
		
	// build the query, save current selection, and build the stack option
	$("#" + parentID + " select").each( function() {
		var selectName = $(this).attr("name");
		var param = selectName;
		var selected = '';
		
		// remap name values for the script. they are setup to work when submitted to inventory
		if (param == 'new-used') {param = 'type';}
		if (param == 'exteriorcolor') {param = 'color';}
		
		// if first page loads pull params from the url, else pull selected values
		if(firstLoad[parentID]) {
			
			selected = get(selectName);
			if(selected) {selected = selected.replace(/\053/g, ' ');} // replaces all + (053) with a space.

		} else {
			selected = $(this).val();
		}
		
		//save current selection	
		selectArray[selectName] = selected;
				
		// default to any if value is blank. this is due to passing it to the inventory paramater.
		if(selected == null) {selected = 'any';}
		
		// build the query paramters
		xmlQuery = xmlQuery + "&" + param + "=" + selected;
		
		// build the stack paramter
		if(selected != 'any') {
			if(stack && param != 'make') {
				stack = stack + ',' + param;
			} else if(param != 'make'){
				stack = '&stack=make,' + param;
			}
		}
		
	});
			
	// -- build the XML Query --
	xmlQuery = "xmlproxy.php?url=http://blusolutions.homenetinc.com/saturnofsouthcountynew/models.asp?" + xmlQuery + stack;
	// -- clean the query --
	
	xmlQuery = xmlQuery.replace("?&","?"); // Remove the extra &
		
	// -- fetch xml --
	$.get(xmlQuery, function(data){
				
		// -- empty lists --
		$("#" + parentID + " select").not("#" + parentID + " .search-type").empty().each(function () {
			name = $(this).attr('name');
			if (name == "exteriorcolor") {name = "color";}
			$(this).append("<option value=''>Any " + name + "</option>");
		});

		// -- Load lists --	
		$(data).find("MAKE").each( function() {
			var marker = $(this);
			if(marker.text()) {$("#" + parentID + " .search-make").append("<option value='" + marker.text() + "'>" + marker.text() + "</option>");}
		});

		$(data).find("MODEL").each( function() {
			var marker = $(this);
			if(marker.text()) {$("#" + parentID + " .search-model").append("<option value='" + marker.text() + "'>" + marker.text() + "</option>");}
		});
				
		// Select / Reselect the correct values
		$("#" + parentID + " select").each( function() {
			var selectName = $(this).attr("name");
			var noMatch = true;
						
			$(this).children().each( function() {
				val1 = $(this).val();
				val2 = selectArray[selectName];
								
				if(val1) {val1 = val1.toLowerCase();}
				if(val2) {val2 = val2.toLowerCase();}

				if(val1 == val2) {
					$(this).attr("selected", "true");
					noMatch = false;
				}
			});
			
			// allows the list to get updated again, but keeps it from happening endlessly
			if(noMatch && success != false) {
				//alert(selectID + ' -- ' + selected + ' -- List is dirty - no vehicles?');
				success = false;
			} else {
				success = true;
			}
			
		});

		// Add the change event back		
		$("#" + parentID + " select").change( function() {updateLists(parentID);} );
		$("#" + parentID + " .loading").text("");
		
		firstLoad[parentID] = false;
		
		// if the list update was not successfull then update again
		if (!success) {updateLists(parentID);}

	}, "xml");
			
}

function get(param) {		
	var qsParm = new Array();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
		
	if (param) {
		return qsParm[param]; // if param is specified then just pass one back.
	} else {	
		return qsParm; // if no param spec. then pass all back.
	}
}
