﻿function toggleDescriptionDiv (i) {
	var oDiv = document.getElementById("specialItemDescription"+i);
	if (oDiv.className.indexOf("hidden")>-1){
		oDiv.className = oDiv.className.split(" ")[0];
	} else {
		oDiv.className = oDiv.className + " hidden";
	}
}

/*#region specials */
var _specialsDataList = null;
var _specialsData = null;
var _specialsAnimation = false;
var _specialsWebService = true; 
var _fadeTime = 500;

function LoadSpecialsData(hostURL, accountId) {
	_specialsWebService = true; 
	$.ajax({
		type: "POST",
		url: hostURL + "masterpagewebservice.asmx/GetSpecialsList",
		data: "{accountId: "+accountId+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			specialsDataList = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			_specialsDataList = [];

			for (var i = 0; i < specialsDataList.length; i++) 
				_specialsDataList[i] = eval('(' + specialsDataList[i] + ')');

			_specialsWebService = false;

			GetData(accountId, '', '');
			PrepareSpecialsContent();
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

function GetIndex(id) {
	for (var i = 0; i < _specialsDataList.length; i++)
		if (_specialsDataList[i].SpecialId == id)
			return i;
	return 0;
}

function GetData(accountId, direction, id1) {
	if (id1 == '')
		direction = '';
	_specialsData = [];
	if (_specialsDataList == null || _specialsDataList.length == 0)
		return;
	switch (direction) {
		case "next":
			currentIndex = GetIndex(id1);
			if (currentIndex + 3 < _specialsDataList.length) {
				_specialsData = [_specialsDataList[currentIndex + 2], _specialsDataList[currentIndex + 3]];
			} else if (currentIndex + 3 == _specialsDataList.length) {
				_specialsData = [_specialsDataList[currentIndex + 2]];
			} else {
				GetData(accountId, '', '');
			}
			break;
		case "previous":
			currentIndex = GetIndex(id1);
			if (currentIndex > 1) {
				_specialsData = [_specialsDataList[currentIndex - 2], _specialsDataList[currentIndex - 1]];
			} else if (currentIndex == 0) {
				if (_specialsDataList.length % 2 == 1)
					_specialsData = [_specialsDataList[_specialsDataList.length - 1]];
				else
					_specialsData = [_specialsDataList[_specialsDataList.length - 2], _specialsDataList[_specialsDataList.length - 1]];
			} else {
				GetData(accountId, '', '');
			}
			break;
		default:
			if (_specialsDataList.length == 0)
				_specialsData = [];
			else if (_specialsDataList.length == 1)
				_specialsData = [_specialsDataList[0]];
			else 
				_specialsData = [_specialsDataList[0], _specialsDataList[1]];
			break;
	}
}

function getSpecials(hostURL, accountId, direction) {
	if (_specialsDataList == null) 
		LoadSpecialsData(hostURL, accountId);

	if (_specialsDataList == null || _specialsDataList.length < 3) 
		return;

	var hiddenSpecialIdFirst = $("#hiddenSpecialIdFirst").val();
	var hiddenSpecialIdSecond = $("#hiddenSpecialIdSecond").val();

	_specialsAnimation = true;

	$(".homeSpecialItems, .homeSpecialItemsEmpty").fadeTo(_fadeTime, 0,
		function() {
			_specialsAnimation = false; 

			GetData(accountId, direction, hiddenSpecialIdFirst);
			PrepareSpecialsContent();
		}
	);
}

function PrepareSpecialsContent() {
	if (!_specialsAnimation && !_specialsWebService){
		_specialsAnimation = true;
		FillOutSpecialsContent();
		$(this).oneTime(200, function(){ 
			$(".homeSpecialItems, .homeSpecialItemsEmpty").fadeTo(_fadeTime,1, function(){
				// fixing IE Fading issue
				$(".homeSpecial").css('background', $(".homeSpecial").css('background')); 
				$(".itemsFoundDiv").css('background', $(".itemsFoundDiv").css('background'));
			});	
		});
	}
}

function FillOutSpecialsContent() {
	if (_specialsData == "undefined" || _specialsData.length < 1) {
		$(".homeSpecialItems").addClass("hidden");
		$(".homeSpecialItemsEmpty").removeClass("hidden");
		$("#hiddenSpecialIdFirst").val(-1);
		$("#hiddenSpecialIdSecond").val(-1);
	} else {
		$(".homeSpecialItems").removeClass("hidden");
		$(".homeSpecialItemsEmpty").addClass("hidden");
		for(var i = 1; i <= 2; i++){
			var itemSuffix = "First";
			if(i == 2) 
				itemSuffix = "Second";

			if (i > _specialsData.length){
				$(".specialSwapDiv" + itemSuffix).addClass("hidden");
				$(".specialItemsNotFound" + itemSuffix).removeClass("hidden");
				$("#hiddenSpecialId" + itemSuffix).val(-1);
			} else {
				$(".specialSwapDiv" + itemSuffix).removeClass("hidden");
				$(".specialItemsNotFound" + itemSuffix).addClass("hidden");

				var special = _specialsData[i-1];
				$("#hiddenSpecialId" + itemSuffix).val(special.SpecialId);
				$("#a" + itemSuffix).attr("href", special.SpecialDetailLink);
				$("#image" + itemSuffix).attr("src", special.PhotoPath);

				if(special.AllAligible) {
					$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundNumberDiv fArial fBold fs26");
					$("#itemsFoundNumberDiv" + itemSuffix).html("ALL");
					$("#itemsFoundTextDiv" + itemSuffix).html("Customers Eligible ");
				} else {
					if(special.VehicleNum == '0') {
						$("#itemsFoundNumberDiv" + itemSuffix).removeClass("itemsFoundNumberDiv fArial fBold fs26");
						$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundTextDiv fArial fs10");
						$("#itemsFoundNumberDiv" + itemSuffix).html("<div style=\"padding-top: 7px; margin-left: 5px; margin-right: 5px;\">Currently no inventory for this special. Need a Quote?</div>");
						$("#itemsFoundTextDiv" + itemSuffix).html("<a href=\""+quickQuoteUrl+"\" rel='nofollow'>Click Here</a>");
					} else {
						$("#itemsFoundNumberDiv" + itemSuffix).removeClass("itemsFoundTextDiv fArial fs10");
						$("#itemsFoundNumberDiv" + itemSuffix).addClass("itemsFoundNumberDiv fArial fBold fs26");
						$("#itemsFoundNumberDiv" + itemSuffix).html(special.VehicleNum);
						$("#itemsFoundTextDiv" + itemSuffix).html("<a href="+special.InventoryLink+">Vehicles Found<br />With This Special</a>");
					}
				}
				$("#titleDiv" + itemSuffix).html("<a href="+special.SpecialDetailLink+">"+special.HeaderText+"</a>");
				$("#line1" + itemSuffix).html(special.Line1Text);
				$("#line2" + itemSuffix).html(special.Line2Text);
			}
		}
	}
}

/*#endregion*/


var _specPopupEventTimer = 0;
var _specPopupMouseMoveTime = 0; 
var _specPopupNeedToShow = false;
var _specPopupActiveItemId = null;
var _specPopupActiveItemNativeColor;
var _specPopupActiveItemTextColor;

var _specPopupMouseX = 0;
var _specPopupMouseY = 0;
var _specPopupVehicleInfoRowId;
var _specPopupVehicleHeader; 
var _specPopupVihiclePrice; 
var _specPopupVehicleImage; 
var _specPopupVehicleDescription; 
var _specPopupVehicleLink;

$(document).ready(function(){
	 setInterval('VehilceRowCycle()', 100);
});

function VehilceRowCycle() {
	_specPopupEventTimer++;
	if ( (_specPopupEventTimer - _specPopupMouseMoveTime) == 4){
		if (_specPopupNeedToShow){
			ShowVehicleInfoPopup();
			_specPopupNeedToShow = false;
			}
	}
}

function mX(evt) {
	if (evt.pageX && !$.browser.msie)
		return evt.pageX;
	else
		if (evt.clientX)
			return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	else
		return null;
}

function mY(evt) {
	if (evt.pageY && !$.browser.msie)
		return evt.pageY;
	else
		if (evt.clientY)
			return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	else
		return null;
}

function HideVehicleInfoPopup(){
	popupBody = document.getElementById('vehicleInfoPopup');
	if (popupBody == null) return;
    popupBody.style.display = 'none';
	if (_specPopupActiveItemId != null){
		document.getElementById(_specPopupActiveItemId).style.backgroundColor = _specPopupActiveItemNativeColor;
		document.getElementById(_specPopupActiveItemId).style.color = _specPopupActiveItemTextColor;

		_specPopupActiveItemId = null;
		}
}


function SpecialVehilceRowEventHandler(vehicleInfoRowId,vehicleHeader, vihiclePrice, vehicleImage, vehicleDescription, vehicleLink, e){
	_specPopupVehicleInfoRowId = vehicleInfoRowId;
	_specPopupVehicleHeader = vehicleHeader; 
	_specPopupVihiclePrice = vihiclePrice; 
	_specPopupVehicleImage = vehicleImage; 
	_specPopupVehicleDescription = vehicleDescription; 
	_specPopupVehicleLink = vehicleLink;
	_specPopupMouseMoveTime = _specPopupEventTimer;
	_specPopupNeedToShow = true;

	_specPopupMouseX = mX(e);
	_specPopupMouseY = mY(e);
}


function ShowVehicleInfoPopup() {
	if (_specPopupActiveItemId != null){
		document.getElementById(_specPopupActiveItemId).style.backgroundColor = _specPopupActiveItemNativeColor;
		document.getElementById(_specPopupActiveItemId).style.color = _specPopupActiveItemTextColor;
		}
	_specPopupActiveItemId = _specPopupVehicleInfoRowId;

	_specPopupActiveItemNativeColor = document.getElementById(_specPopupVehicleInfoRowId).style.backgroundColor;
	document.getElementById(_specPopupVehicleInfoRowId).style.backgroundColor = '#' + _attentionColor;
	_specPopupActiveItemTextColor = document.getElementById(_specPopupVehicleInfoRowId).style.color;
	document.getElementById(_specPopupVehicleInfoRowId).style.color = '#' + _pageColor;

	popupBody = document.getElementById('vehicleInfoPopup');

	if (popupBody == null)
		return;
	if (document.getElementById('vehicleInfoPopupLink').href != _specPopupVehicleLink) {
		document.getElementById('vehicleInfoPopupVehicleHeader').innerHTML = _specPopupVehicleHeader;
		document.getElementById('vehicleInfoPopupVehiclePrice').innerHTML = _specPopupVihiclePrice;
		document.getElementById('vehicleInfoPopupImage').src = _specPopupVehicleImage;
		document.getElementById('vehicleInfoPopupDescription').innerHTML = _specPopupVehicleDescription;
		document.getElementById('vehicleInfoPopupLink').href = _specPopupVehicleLink;
	}
	popupBody.style.display = 'block';

	var vehicleInfoTop;
	var vehicleInfoLeft;

	var popupHeight = document.getElementById('vehicleInfoPopup').offsetHeight;
	var vehicleInfoPopupArea = document.getElementById('vehicleInfoPopupArea').offsetHeight;
	var vehicleInfoArrowHeight = document.getElementById('vehicleInfoArrow').offsetHeight
	
	var wraperHeight = 10;
	if($.browser.msie)
		wraperHeight = 16;

	vehicleInfoTop = _specPopupMouseY - vehicleInfoPopupArea - vehicleInfoArrowHeight - wraperHeight;

	vehicleInfoLeft = _specPopupMouseX;

	popupBody.style.top = vehicleInfoTop;
	popupBody.style.left = vehicleInfoLeft;
}

var numPopups = 1; 

function ShowControl(elementName){
	var div = document.getElementById(elementName);
	div.style.display = 'block';
}

function HideControl(elementName){
	var div = document.getElementById(elementName);
	div.style.display = 'none';
}

function SwitchPopup(num) {
    var div = document.getElementById('TabBody' + num);
    if (div.style.display == 'none'){
        HideAllPopups(num);
        div.style.display = 'block';
        document.getElementById('tabClose' + num).style.display = '';
        document.getElementById('tabOpen' + num).style.display = 'none';
    } else {
        div.style.display = 'none';
        document.getElementById('tabClose' + num).style.display = 'none';
        document.getElementById('tabOpen' + num).style.display = '';
	}
    return;
}

function HideAllPopups(num) { 
    var div;
    for (i=1; i <= numPopups; i++) {
        if (num != i) {
            HideControl('TabBody' + i);
            document.getElementById('tabClose' + i).style.display = 'none';
            document.getElementById('tabOpen' + i).style.display = '';
        }
    }
} 


/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end. 
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );