﻿
function Initiate()
{
    // TODO: Add error handling code registration here.
    
}


/*
    --------------------------------------------------------------------------------------------------------------- HOME PAGE
*/
var lastBestDealSwitched = 1;
var bestDealsMouseOver = false;

//
//  Page Initiation Code.
//
function DefaultInitiate()
{
    $("#nonSpecific > a:first").click(function(ob) { VSCClickChange(ob); });
    $("#specific > a:first").click(function(ob) { VSCClickChange(ob); });

    $("#nonSpecific > a:first").click();

    //$("#vdcUsed").hide();
    //setTimeout(switchBestDeals, 1000);
}
function HomeToggle(obj)
{
    var text = $(obj).text();
    $(".home_tabs > li[class*=on]").removeClass("on");
    $(obj).parent().addClass("on");

    window.setTimeout(function() { $("#" + text).fadeIn(500); }, 100)
    $(".best_deals_div").filter(":not(#" + text + ")").fadeOut(250);



}
// Switch between home page best deals panes.
function switchBestDeals()
{
    if (bestDealsMouseOver == false)
    {
        if (lastBestDealSwitched == 0)
        {
            // show new cars
            $("#vdcUsed").fadeOut(700, function() { $("#vdcNew").fadeIn(1300); });
        }
        else
        {
            // show used cars
            $("#vdcNew").fadeOut(700, function() { $("#vdcUsed").fadeIn(1300); });

        }
        lastBestDealSwitched = lastBestDealSwitched == 0 ? 1 : 0;
    }
    setTimeout(switchBestDeals, 5000);
}
// Toggle between home page Vehicle Search Types.
function VSCClickChange(ob)
{
    var id = null;
    if (ob.srcElement) id = ob.srcElement.parentNode.id;
    else id = ob.target.parentNode.id;

    if (id == "nonSpecific")
    {
        $("#nonSpecific").fadeOut(500);
        $("#specific").fadeIn(500);
    }
    else
    {
        $("#specific").fadeOut(500);
        $("#nonSpecific").fadeIn(500);
    }
}


/*
    --------------------------------------------------------------------------------------------------------------- RESULTS PAGE
*/
//
// Page initiation Code
//
function ResultsPageInitiate()
{
    //alert("initiate");
    $(':checkbox').filter(function()
    {
        return this.id.match(/C[0-9]+_[0-9]+_[0-9]+/);
    }).click(function(e) { CompareClick(e); });

    CompareToggleButton();
    CompareInitiate();
}
var arrSelected = new Array();

function CompareInitiate()
{
    var arrIndexes = $("input[type=hidden]").filter(function()
    {
        return this.id.match(/hidCompare/);
    }).val().split("|");

    for (var i = 0; i < arrIndexes.length; i++)
    {
        if (arrIndexes[i] == "") continue;
        var obj = $("#C" + arrIndexes[i])[0];
        obj.checked = true;

        CompareClick_UI(arrIndexes[i], obj, false);
    }
}
function CompareClick(e)
{
    var obj = e.srcElement ? e.srcElement : e.target;
    var id = obj.id.substring(1);
    CompareClick_UI(id, obj, true);
}
function CompareClick_UI(id, obj, appendHidValue)
{
    if (obj.checked)
    {
        $("#TR" + id).addClass("S");
        arrSelected.push(id);
    }
    else
    {
        $("#TR" + id).removeClass("S");
        arrSelected.pop(id);
    }
    if (arrSelected.length == 4)
    {
        $(':checkbox:not(:checked)').filter(function()
        {
            return this.id.match(/C[0-9]+_[0-9]+_[0-9]+/);
        }).attr("disabled", "disabled");
    }
    else
    {
        $(':checkbox:not(:checked)').filter(function()
        {
            return this.id.match(/C[0-9]+_[0-9]+_[0-9]+/);
        }).removeAttr("disabled");
    }

    $("#compare_message").html("You can select <em>" + (4 - arrSelected.length) + "</em> more vehicle" + (arrSelected.length == 3 ? "" : "s") + " for comparison.");

    CompareToggleButton();

    if (appendHidValue)
    {
        $("input[type=hidden]").filter(function()
        {
            return this.id.match(/hidCompare/);
        }).val(arrSelected.join("|"));
    }
}
function CompareToggleButton()
{
    if (arrSelected.length > 1)
    {
        $("input[type=button]").filter(function()
        {
            return this.id.match(/btnCompare/);
        }).removeAttr("disabled");
    }
    else
    {
        $("input[type=button]").filter(function()
        {
            return this.id.match(/btnCompare/);
        }).attr("disabled", "disabled");
    }
}
function TOG(id, srcImg)
{
    var o = $("#" + id);
    o.toggle();

    var imgURL = srcImg.src;
    imgURL = imgURL.substring(0, imgURL.lastIndexOf("/"));
    
	if (o.is(':visible'))
	{
	    srcImg.src = imgURL + "/minus_button.gif";
	}
	else
	{
	    srcImg.src = imgURL + "/plus_button.gif";
	}
}



/*
    --------------------------------------------------------------------------------------------------------------- BUILD VEHICLE PAGE
*/
var m_build_ExtraScroll = 0;
var m_build_AddedScroll = 0;
//
//  Page Initiation Code.
//
function BuildInitiate()
{
    m_prm = Sys.WebForms.PageRequestManager.getInstance();
    // Add handlers for end and begin request.
    m_prm.add_endRequest(BuildEndRequest);
    m_prm.add_beginRequest(BuildBeginRequest);

    if (document.getElementById("addedOptionsScroller") != null)
    {
        window.setTimeout(BuildEndRequest, 100);
    }
    
}
function BuildBeginRequest(sender, args)
{
    var clientId = args.get_postBackElement().id;

    if (clientId.indexOf("VOC") > -1)
    {
        m_build_ExtraScroll = $("#extrasControl")[0].scrollTop;
        m_build_AddedScroll = $("#addedOptionsScroller")[0].scrollTop;
    }

    $('#loadingDiv').height($('.wizardHolder').height());
    var inner = $('#loadingDiv > div');
    inner.css("margin-top", ($('.wizardHolder').height() / 2) - inner.height());
    
}
function BuildEndRequest(sender, args)
{
    var added = document.getElementById("addedOptionsScroller");
    var extra = document.getElementById("extrasControl");
    
    if (added != null)
    {
        // Fix the overflow for the added options div after AJAX postback. (IE hack!)
        $(added).height(10);
        $(added).height(150);
        $(added).css("overflow", "auto");

        added.scrollTop = m_build_AddedScroll;
        extra.scrollTop = m_build_ExtraScroll;
    }
    
    if ($("input[id*='hidEnumPurchaseTypes']").length > 0) {
        BuildFinanceTypeHelper_Initiate();
    }
}
var m_buildPurchaseTypeHelperStrings = new Array(""
                                                , ""
                                                , ""
                                                , ""
                                                , "Personal Contract Purchase (PCP) - When you buy a new or used car on personal contract purchase, sometimes also referred to as a personal contact plan, the car is leased from a finance company over a fixed term and you then have the option to return or purchase the car at the end of this contract. So you pay a monthly amount for the duration of the PCP contract termand then a final purchase amount should you want to buy the car."
                                                , ""
                                                , ""
                                                , ""
                                                , ""
                                                , "Hire Purchase (HP) - Hire purchase is a form of secured loan except rather than the loan being secured on your house, it is secured on the car you are buying. You pay regular monthly payments for the duration of the hire purchase contract term and, once all the payments have been made, you own the car. Should you default on your monthly payments the supplier has the right to reposess the car."
                                                );

function BuildFinanceTypeHelper_Initiate() {

    var hidPT = $("input[id*='hidEnumPurchaseTypes']")[0];
    var inpPTs = $("input[id*='lstPurchaseType']");
    var labPTs = $("label[for*='lstPurchaseType']");
    var arrPTs = hidPT.value.split("|");

    for (var f = 0; f < inpPTs.length; f++) {
        var inp = inpPTs[f];
        var lab = labPTs[f];
        lab.title = m_buildPurchaseTypeHelperStrings[arrPTs[f]];
        inp.title = m_buildPurchaseTypeHelperStrings[arrPTs[f]];
        $(inp).tooltip({ extraClass: 'FinanceHelpToolTip',
            showBody: " - "
        });
        $(lab).tooltip({ extraClass: 'FinanceHelpToolTip',
            showBody: " - "
        });
        //        $(inp).tooltip({ bodyHandler: function() {
        //        return eval("m_buildPurchaseTypeHelperStrings[" + arrPTs[f] + "];");
        //        }
        //        });
    }
}

/*
    --------------------------------------------------------------------------------------------------------------- VEHICLE PAGE
*/
var m_VP_imageIndex = 0;
var m_VP_previousImage = null;
//
//  Page Initiation Code.
//
function RangeImageRotatorInitiate()
{
    $("#welcomeImg img").hide().css("position", "absolute");
    setTimeout(RangeImageRotate, 0);
}
function RangeImageRotate()
{
    if (m_VP_previousImage != null)
    {
        $(m_VP_previousImage).fadeOut(500)
    }
    if ($("#welcomeImg img").length > 0)
    {
        m_VP_previousImage = $("#welcomeImg img:nth-child(" + (m_VP_imageIndex + 1) + ")").fadeIn(500);

        m_VP_imageIndex++;
        if (m_VP_previousImage.length == 0)
        {
            m_VP_imageIndex = 0;
            RangeImageRotate();
            return;
        }
        setTimeout(RangeImageRotate, 3000);
    }
}

/*
--------------------------------------------------------------------------------------------------------------- Accordion Control
*/
function AccordionInitiate(id, activeTab)
{
    $("#" + id).accordion({ header: 'h3', selectedClass: 'sidebar_active', active:activeTab, autoHeight:true });
}




/*
--------------------------------------------------------------------------------------------------------------- TOOLTIP POPUP
*/

function displayTooltip(obj, desc, title, cssclass, horizontalAlign) {
	var tt = $(".tooltipContainer");
	var offset = $(obj).offset();
	var left = offset.left;

	tt.children('#cont').html(
		"<h3>" + title + "</h3>" +
		desc
	);

	tt.show();
	var top = (offset.top - tt.height()) - 60;
	tt.hide();


	tt.css("left", left);
	tt.css("top", top);
	tt.show();

	
	if (cssclass != "") {
		tt.addClass(cssclass);
	}

	if (horizontalAlign != null || horizontalAlign != "") {
		tt.attr("tooltipAlign", horizontalAlign);
	}
}
function hideTooltip() {
	$(".tooltipContainer").attr("class", "tooltipContainer");
	$(".tooltipContainer").removeAttr("tooltipalign");
	$(".tooltipContainer").hide();

}

$(document).mousemove(function (e) {
	var tt = $(".tooltipContainer");
	tt.css("top", (e.pageY - tt.height()) - 80);

	if (tt.attr("tooltipAlign") == "left") {
		tt.css("left", e.pageX - 150);
		
	}
	else if (tt.attr("tooltipAlign") == "center") {
		tt.css("left", e.pageX - 115);
		
	}
	else if (tt.attr("tooltipAlign") == "right") {
		tt.css("left", e.pageX);
		
	}
	else {
		tt.css("left", e.pageX);
	}
});



// ---------------  AUTOMATIC FONT RESIZE -----------------  //

// Changes font size of 'em' until it fits the full width of the 'span' container.
// Span must have autoFontSize specified as a class

function AutoResizeFont(container, direction) {

	$("." + container).each(function () {
		var em = $(this).children("em");
		var span = $(this);
		var fontSize = parseInt(em.css("font-size"));

		if (direction == "reduce") {
			while (em.width() > span.width() || em.height() > span.height()) {
				fontSize--;
				em.css("font-size", fontSize + "px");
			}
		}
		else if (direction == "increase") {
			while (em.width() < span.width() && em.height() < span.height()) {
				fontSize++;
				em.css("font-size", fontSize + "px");
			}
			if (em.width() > span.width() || em.height() > span.height()) {
				fontSize--;
				em.css("font-size", fontSize + "px");
			}
		}

		if (em.height() < span.height()) {
			var diff = span.height() - em.height();
			var curPad = parseInt(span.css("padding-top"));
			span.css("padding-top", (curPad + diff / 2) + "px");
		}
	});

}

