// JavaScript Document
/* -- Sunset Ford --- */
/* --------------- Functions that need to run after the document loads -------------------*/

$(document).ready(function(){	
	$.get("/navigation-file.html", function(data){
		loadNav(data);
	});
	
	setupNav();
	
// live search tool/advanced search switch

   $('.search-toggle').click(function(event) {
        event.preventDefault();
        $('#advanced-search-container').toggleClass('active');
        $('.ls-container').toggleClass('active');
     });
   
	$(".ls-controls a.button").click(function (event) {
	
		document.forms["ls-form"].submit();	
	});
       


// Detailed inventory full name validation

		$('#Form2').unbind('submit');
		$('#Form2').submit(function() {
			var goodToGo = true;
			var errorStr = ""
			
			var fullName = document.getElementById("Text1").value;
			fullName = jQuery.trim(fullName);
			
			if (!fullName.match(" ")){
			goodToGo = false;
			errorStr = errorStr + "Please enter your full name.\n";
			}
			
			if (!goodToGo){
				alert(errorStr);
			}
			return goodToGo;
			//return false;
		});

	// quick nav functionality
	$("#locations-button").parent().click(function(event){
		event.preventDefault();
		if($("#locations-list").is(":hidden")) {
			$("#locations-list").slideDown(350);
		}
	},function(){
		if($("#locations-list").is(":visible")) {
		   $("#locations-list").slideUp(100);
		}
   });

	// 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'});
     $("#stwrapper").removeClass("quick-link");
		event.preventDefault();
		event.stopPropagation();  
	});
   
   $("#sharethis-button").click(function(event){
										
     $("#stwrapper").addClass("quick-link");
	});
   
	// dealer info dropdown functionality
	$("#dealer-info").hover(function(){
		if($(this).children("#locations-list").is(":hidden")) {
			$(this).children("#locations-list").slideDown(350);
		}
	},function(){
		if($(this).children("#locations-list").is(":visible")) {
			$(this).children("#locations-list").slideUp(100);
		}
   });

	// extended nav functionality

	$(".secondary-pages #extended-nav .nav-level1 ul").hide();

	$(".secondary-pages #extended-nav").hover(function(){
		if($("#extended-nav li > ul > li").is(":hidden")) {
			$("#extended-nav li > ul").slideDown(350);
		}
	},function(){
		$("#extended-nav li > ul").hide();
   });
	 
	// end extended nav 

	// collapse VIP and search area 
	
     $("#main #vip-expanded").hide();
     $("#search-expanded").hide();


	// options nav bar functionality

   $("#options-nav .nav-items .button-item").mouseenter(function(event){
     $(this).siblings().children(".sub-nav-items").fadeOut(500);
     $(this).children(".sub-nav-items").fadeIn(500);
   });

	// VIP coupon functionality

   $("#main #vip-coupon").mouseover(function(event){
     $("#main #vip-expanded").slideDown(300);
   });
   
   $("#main #vip-coupon").mouseleave(function(event){
     $("#main #vip-expanded").fadeOut(300);
   });
   
	$("#vip-coupon select").mouseleave(function(event) { event.stopPropagation(); });
	$("#vip-coupon input").mouseleave(function(event) {
		event.stopPropagation();
	});
	
	// VIP show message after form submit
	
	$("#vip-expanded .errors").each( function () {
		if ($(this).html() != '') {
			$(this).parents("#vip-expanded").show();
		}
	});
	$("#vip-expanded .success").each( function () {
		if ($(this).html() != '') {
			$(this).parents("#vip-expanded").show();
		}
	});
	$("#vip-expanded .close-item").click(function(event){
		$("#vip-expanded").fadeOut(100);
   });
	
	// Model Landing VIP functionality
	$(".model-landing #vip-expanded fieldset#section-alpha a.btn").click(function(event){
	$(".model-landing #vip-expanded fieldset#section-beta").show();
   });
	
	$(".model-landing #vip-expanded .cancel-item").click(function(event){
		$(".model-landing #vip-expanded fieldset#section-beta").hide();
   });
	
	$(".model-landing #vip-expanded .errors").each( function () {
		if ($(this).html() == '<strong>Some errors were detected in your form:</strong><br>Invalid verification code.') {
			$(".model-landing #vip-expanded fieldset#section-beta").show();
		}
	});

	
	
	// search bar functionality

   $("#search-bar").mouseover(function(event){
		$("#search-expanded").stop(false,true).fadeIn(100);
   });
   
    $("#search-bar").mouseleave(function(event){
		$("#search-expanded").stop(false,true).fadeOut(50);
   });
	  
	$("#search-bar select").mouseleave(function(event) { event.stopPropagation(); });
	$("#search-bar input").mouseleave(function(event) {
		event.stopPropagation();
	});

// Load Images for rotation
	if($("body").is("#main")) {
		$.get("/home-image-rotation.html", function(data){
			setupRotation(data);
		});
	}
	
	// open up any top menu items where there are erros in the form
	$(".nav-expanded .errors").each( function () {
		if ($(this).html() != '') {
			$(this).parents(".nav-expanded").show();
		}
	});
	
	$(".nav-expanded .success").each( function () {
		if ($(this).html() != '') {
			$(this).parents(".nav-expanded").show();
		}
	});
	
	
// LIVE SEARCH AJAX

	//$("input.liveSearch").change( function () {liveSearch(this);});
	//$("input.liveSearch").change( function (e) {liveSearch(this,e);});
	$("input.liveSearch").keyup( function (e) {liveSearch(this,e);});
	$("input.liveSearch").keydown( function (e) {liveSearchControls(this,e);});
	$("input.liveSearch").click( function (e) {liveSearch(this,e);});
	
	$("input.liveSearch").attr('autocomplete', 'off');
	
	$(".ls-results li").live('mouseover', function (e) {
		$(this).addClass('selected').siblings().removeClass('selected');
	});
	
	// prevent the blur from interfering with clicking
	$(".ls-results").hover(function (e) {
		$("input.liveSearch").unbind('blur');
	}, function (e) {
		$("input.liveSearch").blur( function (e) {liveSearchDisplay(this,e);});
	});
	
	// create a live event to catch hover of items in the list
	
	inQuery = false;
	queryMissed = false;
	queryCounter = 0;
	lastQuery = '';
	//isTyping = false;
	timeDelay = 400; //miliseconds 1000 milisec = 1 sec
	curTime = 0;
	prevTime = 0;
	date = new Date();
	
	function liveSearchDisplay (object, e) {
		
		if(!$(object).hasClass('fullSearch')) {			
			var result = $(object).parents().siblings('.ls-results-container').children('.ls-results');
			var list = $(result).children('ul').children('li');
		} else {
			var result = $(object).parents().siblings('.ls-results-container').children('.ls-results-full');
			var list = $(result).children('.gallery-list');
		}
		
		if(e.type == 'blur') {
			$(result).hide();
			//alert('blur:hide');
		} else {
			if($(list).length > 0) {
				$(result).show();
				//alert('show');
			} else {
				$(result).hide();
				//alert('hide');
			}
		}
	}
	
	function liveSearchControls (object, e) {
			
		result = $(object).parents().siblings('.ls-results-container').children('.ls-results');
		selected = $(result).children('ul').children('li.selected');
		list = $(result).children('ul');

		// catch return
		if(e.keyCode == '13') {
			//$("input.liveSearch").unbind('blur');
			curSelectedHref = $(selected).children('a').attr('href');
			if(curSelectedHref) {
				window.location = curSelectedHref;
				e.preventDefault();
				clearAltField($("input.liveSearch"));
			}/* else {
				$(object).parents('.ls-form').submit();
			}*/
		}

		// catch up/down arrow
		if(!$(liveSearchControl).hasClass('fullSearch')) {				
			if(e.keyCode == '38' || e.keyCode == '40') {
				if($(selected).length > 0) {
					//alert('selected');
					if(e.keyCode == '38') {
						//alert($(selected).previous().length);
						if($(selected).prev().length > 0) $(selected).toggleClass('selected').prev().toggleClass('selected');
					} else if(e.keyCode == '40') {
						//alert($(selected).previous().length);
						if($(selected).next().length > 0) $(selected).toggleClass('selected').next().toggleClass('selected');
					}
				} else if ($(list).children('li').length > 0) {
					//alert($(list).children('li:first').length);
					if(e.keyCode == '40') $(list).children('li:first').toggleClass('selected');
				}
			}
		}
	}
	
	// Source for Function: www.somacon.com/p355.php
	function trim(stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	}

	liveDebug = $("#primary-division p");
	//$(liveDebug).html('');

	function liveSearch (object, e) {
		
		//if(typeof e.keyCode != 'undefined') e.keyCode = '';
		//if(typeof e.type != 'undefined') e.type = '';
		
		//$(liveDebug).append('<p>-------</p><p>Call Live Search</p>');
		
		// catch navigation
		//if(e.keyCode == '37' || e.keyCode == '38' || e.keyCode == '39' || e.keyCode == '40' || e.keyCode == '13' || e.keyCode == '32') {
		if(e.keyCode <= 40 && e.keyCode != 8 || e.keyCode == 144) {
			//liveSearchControls(object, e);
			//$(liveDebug).append('<p>Key Capture</p>');
		} else {
			
			// Get Query
			query = $(object).val();
			liveSearchControl = object;
			
			//$(liveDebug).append('<p>'+e.type+e.keyCode+'</p>');
			
			if (typeof e.keyCode != 'undefined') {
				liveWaiting = true;
			} else {
				liveWaiting = false;
			}
			
			if(e.type != 'click' && typeof e.keyCode != 'undefined') {
			
				// start timer
				date = new Date();
				curTime = date.getTime();
				
				debugTime = (prevTime + timeDelay) - curTime;
				//$(liveDebug).append('<p>Time Diff: '+debugTime+' </p>');
				
					if(((prevTime + timeDelay) - curTime) <= 0 && prevTime >0) {
						liveWaiting = false;
						//queryMissed = true;
						//setTimeout("advanceActive()", timerLen);
						clearTimeout(liveTimeout);
						//$(liveDebug).append('<p>Dont Wait!!!</p>');
					} else {
						if(typeof liveTimeout != 'undefined') clearTimeout(liveTimeout);
						liveTimeout = setTimeout(function(){
							//$(liveDebug).append('<p><b>TimeOut Called</b></p>');
							$("input.liveSearch").keyup();
						}, timeDelay);
						//queryMissed = true;
						//$(liveDebug).append('<p>Waiting...</p>');
					}
				
				if(query > '') prevTime = curTime;
			}
			
			
			//$(liveDebug).append('<p>QUERY: '+query+' - LAST: '+lastQuery+'</p>');
			
			if(!$(object).hasClass('fullSearch')) {			
				result = $(object).parents().siblings('.ls-results-container').children('.ls-results');
			} else {
				result = $(object).parents().siblings('.ls-results-container').children('.ls-results-full');
			}
				
			if(!query) {
				prevTime = 0;
				$(result).html('');
				liveSearchDisplay (object, e);
			} else if((trim(lastQuery) == trim(query)) && !queryMissed) {
				liveSearchDisplay (object, e);
				//$(liveDebug).append('<p><b>display old data</b> '+(trim(lastQuery) == trim(query))+' && '+!queryMissed+' || '+liveWaiting+'</p>');
			} else if(inQuery) {
				// if in query do nothing until query is finished.
				queryMissed = true;
				//$(liveDebug).append('<p><b>WAITING IN A QUERY</b></p>');
			} else if(!liveWaiting){
				//$(liveDebug).append('<p><b style="color: red">QUERY DATA</b></p>');
				inQuery = true;
				$(liveSearchControl).toggleClass('loading');
								
				// -- build the XML Query --
				if(!$(liveSearchControl).hasClass('fullSearch')) {			
					xmlQuery = "live-search.php?query=" + query;
				} else {
					xmlQuery = "live-search-full.php?query=" + query;
				}
				
				lastQuery = query;
				
				$.get(xmlQuery, function(data){
					// Do something with the search request.
					queryCounter++;
					inQuery = false;
					$(result).html(data);
					$(liveSearchControl).toggleClass('loading');
					liveSearchDisplay (object, e);
					//$(liveDebug).append('<p>-- data returned --</p>');
					if(queryMissed == true) {
						liveSearch(object, e);
						queryMissed = false;
					} else {
						prevTime = 0;
					}
					
				});
			}
		}
			
	}// liveSearch
	
	// assign special labels to liveSearch
	$("#main input.liveSearch").each(function(index) {
		checkAltField(this);
		
		$(this).focus(function () {clearAltField(this);});
		$(this).blur(function () {checkAltField(this);});
		
	});
	
	// clear liveSearch special labels on submit
	$("#main #ls-form .button").click(function() {
		$("#main input.liveSearch").each(function(index) {
			clearAltField(this);
		});
	});
	
	// clear the field if it is equal to alt
	function clearAltField(object) {
		alt = $(object).attr("alt");
		value = $(object).val();
		if(value == alt) $(object).val('');
	}
	
	// set the field equal to alt if it is empty
	function checkAltField(object) {
		alt = $(object).attr("alt");
		value = $(object).val();
		if(value == "") $(object).val(alt);
	}
	
});

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

function loadNav (data) {
	$('#nav-shop-new').html($(data).children('#nav-shop-new').html());
	$('#nav-shop-used').html($(data).children('#nav-shop-used').html());
	
	// Show the exterior / interior images of each vehicle as it is hovered over.
	$(".model-item a").hover( function() {
		$(this).parent().siblings(".model-desc").show();
	}, function() {
		$(this).parent().siblings(".model-desc").hide();
	});
	
	// Hide the drop down menu options when cars are being hovered over.
	$("#new-vehicle-list .expanded-primary > ul").hover( function() {
		$("#new-vehicle-list .expanded-secondary .nav-item").hide();
	}, function() {
		$("#new-vehicle-list .expanded-secondary .nav-item").show();
	});
	
	// close-X  dropdown functionality
	$(".nav-expanded .close-item").click(function(event){
		$(".nav-expanded").fadeOut(100);
   });
	
}

var navHideDelay = new Array();

function setupNav () {
// primary nav functionality
	navDelay = 150;
	
	// prevent the main site menu from being clicked on.
	$('#nav-page-list > a').click(function (data) {
		data.preventDefault();
	});
	
	$("#nav-bar select").mouseleave(function(event) { event.stopPropagation(); });
	$("#nav-bar input").mouseleave(function(event) {
		event.stopPropagation();
	});
	
	$("#nav-bar").mouseenter( function(){
		navHover = true;
	});
	
	$("#nav-bar").mouseleave( function(){
		navHover = false;
		
		if(navHideDelay[0]) {clearTimeout(navHideDelay[0]);}
		// Prevent the menu from hiding to quickly
		navHideDelay[0] = setTimeout(function() {
			if(navHover != true) {$("#nav-bar > li > .nav-expanded").not(":hidden").fadeOut(navDelay);}
		}, navDelay);
	});
	
	$("#nav-bar > li").mouseenter(function(){
			if ($(this).siblings().children(".nav-expanded").not(":hidden").length == 0) {
				$(this).children(".nav-expanded").slideDown(navDelay);				
			} else {
				$(this).siblings().children(".nav-expanded").stop(true, true).hide();
				$(this).children(".nav-expanded").show();
			}
	});
}

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('<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) {
		//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)]);
	$("#container").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);		
}
