// 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();

	// VIP coupon functionality
	$("#vip-coupon").mouseover(function(event){
		$("#vip-expanded").slideDown(300);
	});
   
	$("#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);
		});
		
		setupScrollingInventory();
	}
	
});

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

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

function setupScrollingInventory() {
	// #inv-special-next, #inv-special-prev
	// Inventory List: #new-list li.inventory-item
	
	//var $container = $('ul.inventory-list');
	//var totalWidth;
	//var $firstItem = $('#new-list li.inventory-item:first'); // use the first inventory element
	$items = '#new-list li.inventory-item';
	$currItem = 1;
	$display = 6;
	$itemTotal = $($items).length;
	
	$('#inv-special-prev').click(function() {
		if($currItem > 1) {
			$($items + ':nth-child('+ ($currItem-1) +')').show();
			$currItem--;
		}
		/*
		$container.animate({
			left: parseInt($container.css('left')) + $firstItem.outerWidth()
		});
		*/
	});		

	
	$('#inv-special-next').click(function() {
		if($currItem < ($itemTotal-$display+1)) {
			$($items + ':nth-child('+ $currItem +')').hide();
			$currItem++;
		}
		/*
		$container.animate({
			left: parseInt($container.css('left')) - $firstItem.outerWidth()
		});
		*/
	});
			
}

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);
		//alert("element null -- " + $(object).text());
	} else {
		//alert("element -- " + $(object).text());
		object = elementRef;
	}
	
	// If at the end then start over
	if ($(object).length == 0) {
		//alert("object is null");
		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();
	
	//alert(success);
	
	// 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;
			}
		}
		
	});
	
	//alert(stack);
		
	// -- 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 &
	
	//alert(xmlQuery);
	
	// -- fetch xml --
	$.get(xmlQuery, function(data){
		
		//alert('xml loaded');		
		
		// -- 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>");}
		});
/*
		$(data).find("COLOR").each( function() {
			var marker = $(this);
			if(marker.text()) {$("#" + parentID + " .search-color").append("<option value='" + marker.text() + "'>" + marker.text() + "</option>");}
		});

		$(data).find("TRIM").each( function() {
			var marker = $(this);
			if(marker.text()) {$("#" + parentID + " .search-trim").append("<option value='" + marker.text() + "'>" + marker.text() + "</option>");}
		});
		
		$(data).find("MINYEAR").each( function() {
			var marker = $(this);
		});
		
		$("#" + parentID + " .search-count").text($(data).find("MATCHES").attr('count'));
*/				


		/*
		$(data).find("BODYSTYLE").each( function() {
			var marker = $(this);
			if(marker.text()) {$("#bodystyle").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.
	}
}