var g_stripCount = 0;
var g_modelYear = '2010';

var Application = {
    year : g_modelYear,
    make : "",
    model  : "",
    trim : "",
    firstName : "",
    lastName : "",
    financing : "",
    timeframe : "",
    email : "",
    phone : "",
    address : "",
    city : "",
    state : "",
    zip : "",
    contactTime : "",
    comments : "",
    url : ""
};


function popState(stateId) {
    $("#" + stateId).append('<option selected="selected" value="">--Select a state--</option>' +
	'<option value="AL">Alabama</option>' +
	'<option value="AK">Alaska</option>' +
	'<option value="AZ">Arizona</option>' +
	'<option value="AR">Arkansas</option>' +
	'<option value="CA">California</option>' +
	'<option value="CO">Colorado</option>' +
	'<option value="CT">Connecticut</option>' +
	'<option value="DE">Delaware</option>' +
	'<option value="FL">Florida</option>' +
	'<option value="GA">Georgia</option>' +
	'<option value="HI">Hawaii</option>' +
	'<option value="ID">Idaho</option>' +
	'<option value="IL">Illinois</option>' +
	'<option value="IN">Indiana</option>' +
	'<option value="IA">Iowa</option>' +
	'<option value="KS">Kansas</option>' +
	'<option value="KY">Kentucky</option>' +
	'<option value="LA">Louisiana</option>' +
	'<option value="ME">Maine</option>' +
	'<option value="MD">Maryland</option>' +
	'<option value="MA">Massachusetts</option>' +
	'<option value="MI">Michigan</option>' +
	'<option value="MN">Minnesota</option>' +
	'<option value="MS">Mississippi</option>' +
	'<option value="MO">Missouri</option>' +
	'<option value="MT">Montana</option>' +
	'<option value="NE">Nebraska</option>' +
	'<option value="NV">Nevada</option>' +
	'<option value="NH">New Hampshire</option>' +
	'<option value="NJ">New Jersey</option>' +
	'<option value="NM">New Mexico</option>' +
	'<option value="NY">New York</option>' +
	'<option value="NC">North Carolina</option>' +
	'<option value="ND">North Dakota</option>' +
	'<option value="OH">Ohio</option>' +
	'<option value="OK">Oklahoma</option>' +
	'<option value="OR">Oregon</option>' +
	'<option value="PA">Pennsylvania</option>' +
	'<option value="RI">Rhode Island</option>' +
	'<option value="SC">South Carolina</option>' +
	'<option value="SD">South Dakota</option>' +
	'<option value="TN">Tennessee</option>' +
	'<option value="TX">Texas</option>' +
	'<option value="UT">Utah</option>' +
	'<option value="VT">Vermont</option>' +
	'<option value="VA">Virginia</option>' +
	'<option value="WA">Washington</option>' +
	'<option value="WV">West Virginia</option>' +
	'<option value="WI">Wisconsin</option>' +
	'<option value="WY">Wyoming</option>');
}


/***
 * Class EzCarPricesMini300
 */
function EzCarPricesMini300(id) {
    this.pages = new Array(5);
    this.currentPage = 0;

    this.widget = $("#" + id);
    this.widget.empty();
    this.createPages();
    this.showPage(0);
    this.initNextStepButtons();
    this.demo();
}

EzCarPricesMini300.prototype.demo = function() {
    this.vehicleWidget.previewStrip.loadContent('', '');
}

///
/// Loads the pages of the form into memory.
///
EzCarPricesMini300.prototype.createPages = function() {
    this.pages[0] = this.createPage0();
    this.pages[1] = this.createPage1();
    this.pages[2] = this.createPage2();
    this.pages[3] = this.createPage3();
    this.pages[4] = this.createPage4();

    // create page status attributes and put each page in the DOM
    var i;
    for (i = 0; i < this.pages.length; i++) {
        this.pages[i].completed = false;
        this.pages[i].hasError = false;
        this.pages[i].css("opacity", "0");
        this.widget.append(this.pages[i]);
    }
}

///
/// Displays the page represented by the number that was passed in.
///
EzCarPricesMini300.prototype.showPage = function(pageNum) {
    var self = this;
    var oldPage = this.currentPage;
    // make sure the "display" property of the new page is set to full transparency
    this.pages[pageNum].css("opacity", "0");

    // swap the z-index of the old page and the z-index of the new page
    var oldZIndex = this.pages[oldPage].css("z-index");
    this.pages[oldPage].css("z-index", this.pages[pageNum].css("z-index"));
    this.pages[pageNum].css("z-index", oldZIndex);
    this.currentPage = pageNum;

    // make the old page not visible so that we don't have that "bounce back" effect
    this.pages[oldPage].css("opacity", "0");

    // show the current page
    this.pages[self.currentPage].fadeTo("slow", 1, function() {
        // we need this line to remove opacity changes since IE stupidly drops
        // cleartype when filters are used.
        if ($.browser.msie) {
            self.pages[self.currentPage][0].style.removeAttribute('filter');
            self.pages[self.currentPage][0].style.removeAttribute('opacity');
        }
        self.track(self.currentPage+1); // numbered from 1 instead of 0
    });

    // if we are showing the last page then show the link and the car selected   
    if (pageNum == 4) {
        $("#lastPageCar").html(Application.year + ' ' + Application.make + ' ' + Application.model + ' now!');
//        this.getStyleId(Application.make, Application.model, function(data1) {
//            var styleId = data1.d;
//            getTrueCarPrice(styleId, function(data2) {
//                var truecar = data2.d;
//                $("#lastPageLink").attr("href", "http://www.truecar.com/" + truecar.Url);
//                $("#lastPageLink").attr("target", "_blank");
//            });
//        });
    }
}


///
/// Creates an iframe to impress google analytics.
///
EzCarPricesMini300.prototype.track = function(pageNumber) {
    var frame = document.createElement("iframe");
    frame.src = 'size300-static-tracking/step' + pageNumber + '.html?utm_source=' + g_dtxGenId + '&utm_campaign=ezcarprices_widget';
    frame.style.display = "none";
    document.body.appendChild(frame);
}



///
/// Sets up the "Next Page" button so that they take the user to the next page.
///
EzCarPricesMini300.prototype.initNextStepButtons = function() {
    var self = this;
    function onClick() {
        if (self.checkPage(self.currentPage)) {
			$(this).css("background-image", "url('/images/nextStrip.png')");
            self.showPage(self.currentPage + 1);
		}
        return false;
    }
    function onPage2Click() {
        if (self.checkPage(2)) {
			$(this).attr("background-image", "url('/images/nextStrip.png')");
            $("#page2Button")[0].disabled = true;
            self.submitLead();
        }
    }
    function onPage3Click() {
        var checkboxes = $(".dealerCheckBox");
        $(this).attr("background-image", "url('/images/nextStrip.png')");
        var i;
        for (i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
				
                self.postDealerBack(checkboxes[i].value);
            }
        }
        self.showPage(self.currentPage + 1);
    }
	function prevPageClick() {
		self.showPage(self.currentPage - 1);
	}
    $("#page0Button, #page1Button").click(function() { return onClick() });
    $("#page2Button").click(function() { return onPage2Click() });
    $("#page3Button").click(function() { return onPage3Click() });
	$("#prevPageClicker1, #prevPageClicker2, #prevPageClicker3").click(function() { return prevPageClick() });
	$(document.body).append('<div class="startOver"><span id="carTeaseText"></span><a href="javascript:history.go(0)">Select a New Car</a></div>');
}

EzCarPricesMini300.prototype.onCarClick = function(self, image) {
    Application.make = $(image).attr("make");
    Application.model = $(image).attr("model");
    $("#carTeaseText").html(Application.year + ' ' + Application.make + ' ' + Application.model + ' - ');
    self.showPage(self.currentPage + 1);
}

///
/// Page 0
///
EzCarPricesMini300.prototype.createPage0 = function() {
    var self = this;
    var page0Display = $('<div id="page0Display" class="widgetPage" style="z-index: 150">' +
        '<img id="page0Top" src="../images/300Page0Hdr.png" alt="Ready to Buy? Request a new car price quote and see what others really paid..."/>' +
        '</div>');
    this.vehicleWidget = new VehiclePreviewWidget(page0Display, self);
    page0Display.append('<br/><div class="nextStepButton" id="page0Button"></div>');
    page0Display.append(this.vehicleWidget);
    return page0Display;
}

///
/// Page 1
///
EzCarPricesMini300.prototype.createPage1 = function() {
    var page1Display = $('<div id="page1Display" class="widgetPage" style="z-index: 140">' +
        '   <div class="pageContent page1Content">' +
        '<img id="page1Top" src="../images/300Page1Hdr.png" alt="Ready to Buy? Request a new car price quote and see what others really paid..."/>' +
        '   <label for="fname" id="fnameLabel">First</label><input type="text" id="fname" name="fname"/>' +
        '   <label for="lname" id="lnameLabel">Last</label><input type="text" id="lname" name="lname"/><br/>' +
        '   <label for="email" id="emailLabel">Email</label><input type="text" id="email" name="email"/><br/>' +
        '   <label for="phone" id="phoneLabel">Phone</label><input type="text" id="phone" name="phone"/><br/>' +
        '   <label for="financing" id="financingLabel">Financing</label><select id="financing" name="financing">' +
        '       <option value="loan" selected="selected">Loan</option>' +
        '       <option value="lease">Lease</option>' +
        '       <option value="cash">Cash</option>' + 
        '   </select>' +
        '   <label for="timeframe" id="timeframeLabel">Timeframe</label><select id="timeframe" name="timeframe">' +
        '       <option value="7" selected="selected">Within a week</option>' +
        '       <option value="14">Within two weeks</option>' +
        '       <option value="30">Within a month</option>' + 
        '   </select><br/>' +
        '   </div>' +
        '   <div class="nextStepButton"><div id="prevPageClicker1"></div><div id="page1Button"></div></div>' +
        '</div>');
    return page1Display;
}

///
/// Page 2
///
EzCarPricesMini300.prototype.createPage2 = function() {
    var page2Display = $('<div id="page2Display" class="widgetPage" style="z-index: 130">' +
        '    <div class="pageContent page2Content">' +
        '<img id="page2Top" src="../images/300Page2Hdr.png" alt="Ready to Buy? Request a new car price quote and see what others really paid..."/>' +       
        '       <label for="address">Address</label><input type="text" id="address" name="address"/>' +
        '       <label id="zipLabel" for="zip" id="zipLabel">Zip</label><input type="text" id="zip" name="zip"/><br/>' +
        '       <label for="contactTime" id="contactTimeLabel">Contact Time</label><select id="contactTime" name="contactTime">' +
        '       <option value="any" selected="selected">Any</option>' +
        '       <option value="morning">Morning</option>' +
        '       <option value="afternoon">Afternoon</option>' +
        '       <option value="evening">Evening</option>' +
        '       <option value="night">Night</option>' +
        '       </select><br/>' +
        '       <label for="comments">Comments</label><textarea id="comments" name="comments"/><br/>' +
        '    </div>' +
        '    <div class="nextStepButton"><div id="prevPageClicker2"></div><div id="page2Button"></div></div>' +
        '</div>');
    return page2Display;
}

///
/// Page 3
///
EzCarPricesMini300.prototype.createPage3 = function() {
    var page3Display = $('<div id="page3Display" class="widgetPage" style="z-index: 120">' +
        '<div class="page3Content"><img id="page3Top" src="../images/300Page3Hdr.png" alt="Ready to Buy? Request a new car price quote and see what others really paid..."/></div>' +
        '<div class="dealerBox">' +
        '<ul id="dealerList"></ul>' +
        '</div>' +
        '<div class="nextStepButton"><div id="prevPageClicker3"></div><div id="page3Button"></div></div>' +
        '</div>');
    return page3Display;
}

///
/// Page 4
///
EzCarPricesMini300.prototype.createPage4 = function() {
    var page4Display = $('<div id="page4Display" class="widgetPage" style="z-index: 110">' +
    '<h2 class="lastPageThanks">Thank you!</h2>' +
    '<p class="lastPageEnticement">Get your TrueCar Price Report for the <br/>'+ 
    '<span id="lastPageCar"></span></p>' +
    '<a id="lastPageLink">' + 
    '<img id="page4Image" src="../images/300Page4Image.png" alt="Ready to Buy? Request a new car price quote and see what others really paid..."/>' +
    '</a></div>');
    return page4Display;
}


///
/// Calls the correct function to check the contents of a page for errors
///
EzCarPricesMini300.prototype.checkPage = function(currentPage) {
    var success = false;
    switch (currentPage) {
        case 0:
            success = this.checkPage0();
            break;
        case 1:
            success = this.checkPage1();
            break;
        case 2:
            success = this.checkPage2();
            break;
        default:
            success = true;
            break;
    }
    return success;
}


EzCarPricesMini300.prototype.checkPage0 = function() {
    var success = true;
    Application.make = $("#makeSelect")[0].options[$("#makeSelect")[0].selectedIndex].text;
    Application.model = $("#modelSelect")[0].options[$("#modelSelect")[0].selectedIndex].text;
	$("#carTeaseText").html(Application.year + ' ' + Application.make + ' ' + Application.model + ' - ');
    if (Application.make == "Select a Make") {
        success = false;
    }
    return success;
}

EzCarPricesMini300.prototype.checkPage1 = function() {
    var success = true;
    // remove the stars from the errors so we start fresh
    $(".star").remove();

    Application.year = g_modelYear;
    Application.firstName = $("#fname").val();
    if (Application.firstName.length < 2) {
        $("#fname").after('<span class="star">*</span>');
        success = false;
    }
    Application.lastName = $("#lname").val();
    if (Application.lastName.length < 2) {
        $("#lname").after('<span class="star">*</span>');
        success = false;
    }
    Application.email = $("#email").val();
    if (Application.email.length < 3 ||
        Application.email.indexOf('@') < 0 ||
        Application.email.indexOf('.') < 0) {
        $("#email").after('<span class="star">*</span>');
        success = false;
    }
    Application.phone = $("#phone").val();
    Application.phone = Application.phone.replace(/[-\)\(\s]/g, '');
    if (Application.phone.length != 10) {
        $("#phone").after('<span class="star">*</span>');
        success = false;
    }
    Application.financing = $("#financing").val();
    Application.timeframe = $("#timeframe").val();
    return success;
}

EzCarPricesMini300.prototype.checkPage2 = function() {
    var success = true;
    Application.address = $("#address").val();
    if (Application.address.length < 2) {
        $("#address").after('<span class="star">*</span>');
        success = false;
    }
    Application.zip = $("#zip").val();
    if (Application.zip.length < 4 ||
        Application.zip.length > 7) {
        $("#zip").after('<span class="star">*</span>');
        success = false;
    }
    Application.contactTime = $("#contactTime").val();
    Application.comments = $("#comments").val();
    return success;
}

///
/// Posts the lead to DTX
///
EzCarPricesMini300.prototype.submitLead = function() {
    var self = this;
    function callback(data) {
        self.handlePostResponse(data.d);
    }
    
    $.get(
        "/services/DataService.svc/PostLead",
        {
            dtxGenId: g_dtxGenId,
            campaignId: g_campaignId,
            year: Application.year,
            make: Application.make,
            model: Application.model,
            trim: Application.trim,
            firstName: Application.firstName,
            lastName: Application.lastName,
            email: Application.email,
            phone: Application.phone,
            financing: Application.financing,
            timeframe: Application.timeframe,
            address: Application.address,
            city: Application.city,
            state: Application.state,
            zip: Application.zip,
            contactTime: Application.contactTime,
            comments: Application.comments
        },
        callback,
        "json"
    );
}


///
/// Posts the lead to DTX using the reservation id from the previous post attempt.
///
EzCarPricesMini300.prototype.postDealerBack = function(reservationId) {
    var self = this;
    function callback(data) {
        // do nothing
    }

    $.get(
        "/services/DataService.svc/PostDealerBack",
        {
            dtxGenId: g_dtxGenId,
            campaignId: g_campaignId,
            reservationId: reservationId,
            year: Application.year,
            make: Application.make,
            model: Application.model,
            trim: Application.trim,
            firstName: Application.firstName,
            lastName: Application.lastName,
            email: Application.email,
            phone: Application.phone,
            financing: Application.financing,
            timeframe: Application.timeframe,
            address: Application.address,
            city: Application.city,
            state: Application.state,
            zip: Application.zip,
            contactTime: Application.contactTime,
            comments: Application.comments
        },
        callback,
        "json"
    );
}


///
/// Handles the response from a post to DTX. If there is more than one dealer
/// it will move to the next page, otherwise the last page is shown.
///
EzCarPricesMini300.prototype.handlePostResponse = function(dealers) {
    var self = this;
    if (typeof dealers != 'undefined' && typeof dealers.length != 'undefined' && dealers.length > 0) {
        var dealerDisplay = $("#dealerList");
        var i;
        for (i = 0; i < dealers.length; i++) {
            var checked = 'checked="checked"';
            if (i >= 5) {
                checked = '';
            }
            dealerDisplay.append('<li><label><table class="dealerListItemTable">' +
            '<tr>' +
            '<td class="checkBoxContainer"><input type="checkbox" class="dealerCheckBox" value="' + dealers[i].ReservationId + '" ' + checked + '/></td>' +
            '<td><p>' +
            dealers[i].Name + '<br/>' +
            dealers[i].Street + '<br/>' +
            dealers[i].ZipCode + '<br/>' +
            '</p></td>' +
            '</tr>' +
            '</table></label></li>');
        }

        if (dealers.length > 1) {
            // go to the next page
            self.showPage(self.currentPage + 1);
            return;
        }
    }
    // go to the last page
    self.showPage(self.currentPage + 2);
    return;
}

EzCarPricesMini300.prototype.getStyleId = function(make, model, callback) {
    $.get(
        "/services/DataService.svc/GetStyleId",
        { make: make,
          model: model },
        callback,
        "json"
    );
}


/***
 * Class VehiclePreviewWidget 
 */
function VehiclePreviewWidget(widget, containerClass) {
    this.widget = widget;
    this.topPart = $('<div id="vehicleSelectorTop"></div>');
    this.makeBox = $('<select id="makeSelect" name="makeSelect"></select>');
    this.modelBox = $('<select id="modelSelect" name="modelSelect"></select>');
    this.bottomPart = $('<div id="vehicleSelectorBottom"></div>');

    this.topPart.append(this.makeBox);
    this.topPart.append(this.modelBox);
    this.widget.append(this.topPart);

    this.previewStrip = new VehiclePreviewStrip(this.bottomPart, containerClass);
    this.widget.append(this.bottomPart);
    this.initEvents(containerClass);
}

VehiclePreviewWidget.prototype.initEvents = function() {
    var self = this;

    // add the listing functionality to the select boxes
    var selectBoxes = new VehicleSelectBoxes(self.makeBox[0], self.modelBox[0]);

    function onMakeChanged() {
        selectBoxes.handleMakeOnChange(selectBoxes);
        self.previewStrip.loadContent(
            self.makeBox[0].options[self.makeBox[0].selectedIndex].text,
            self.modelBox.val());
    }
    function onModelChanged() {
        self.previewStrip.scrollToModel(self.modelBox.val());
    }
    self.makeBox.change(function() { onMakeChanged() });
    self.modelBox.change(function() { onModelChanged() });
}


/***
* Class VehiclePreviewStrip
*/
function VehiclePreviewStrip(parent, containerClass) {
    this.parent = parent;
    this.viewingArea = $("<div id='scrollArea'></div>");
    this.leftScroller = $("<div id='leftScroller'>&nbsp;</div>");
    this.rightScroller = $("<div id='rightScroller'>&nbsp;</div>");

    this.imageWidth = 104;
    this.imageHeight = 80;

    this.parent.append(this.leftScroller);
    this.parent.append(this.viewingArea);
    this.parent.append(this.rightScroller);
    
    this.containerClass = containerClass;

    this.preloadImages();
    this.toolTip = new ToolTip();
    this.initEvents();
}

VehiclePreviewStrip.prototype.initEvents = function() {
    var self = this;
    this.leftScroller.click(function() { self.scrollLeft() });
    this.rightScroller.click(function() { self.scrollRight() });
    this.leftScroller.hover(function() { self.longScrollLeft() }, function() { self.keepGoingLeft = false; });
    this.rightScroller.hover(function() { self.longScrollRight() }, function() { self.keepGoingRight = false; });
}

VehiclePreviewStrip.prototype.preloadImages = function() {
    var image = new Array();
    image[0] = new Image();
    image[0].src = "/images/arrow_activated_rev.gif";
    image[1] = new Image();
    image[1].src = "/images/nextStrip.png";
}

VehiclePreviewStrip.prototype.loadContent = function(make, model) {
    var self = this;
    self.getModelUrls(make);
}

VehiclePreviewStrip.prototype.displayContent = function(data) {
	var self = this;
    var vehicles = new Array();
    // don't use vehicles that don't match the current model year
    // so that we won't have repeated images
    var v;
    for (v = 0; v < data.length; v++) {
        if (data[v].ImageId.indexOf(g_modelYear) > -1) {
            vehicles[vehicles.length] = data[v];
        }
    }

    // show the vehicles
    this.viewingArea.empty();
    var vehicleList = $('<ul class="vehicleList"></ul>');
    vehicleList.css("width", (vehicles.length * this.imageWidth) + "px");

    var i;
    for (i = 0; i < vehicles.length; i++) {
        vehicleList.append('<li class="vehicleListItem">' +
                           '<img src="' + vehicles[i].ImageLink + '" ' +
                           'class="vehicleImages" ' + 
                           'id="stripImg' + i + '" ' +
                           'alt="" width="' + this.imageWidth + '" height="' + this.imageHeight + '" ' +
                           'make="' + vehicles[i].Make + '"' + ' ' +
                           'model="' + vehicles[i].Model + '"' + ' ' +
                           'imageid="' + vehicles[i].ImageId + '"' + ' ' +
                           'styleid="' + vehicles[i].StyleId + '"' + ' ' +
                           'msrp="' + vehicles[i].Msrp + '"' + ' ' +
                           'truecarprice="" ' +
                           'truecarurl="" ' +
                           'onerror="missingImage(this)"/></li>');
    }
    g_stripCount = vehicles.length;
    this.viewingArea.append(vehicleList);
    $(".vehicleImages").each(function() { self.affixPrice($(this)); });
    $(".vehicleImages").each(function() { $(this).click(function() { return self.containerClass.onCarClick(self.containerClass, this) }) });
    this.initThumbEvents();
    this.reAdjustSize();
}

VehiclePreviewStrip.prototype.affixPrice = function(image) {
	function affixPriceWorker(data) {
		var trueCarAveragePaid = data.d;
		image.attr("truecarprice", trueCarAveragePaid.Price);
        image.attr("truecarurl", trueCarAveragePaid.Url);
	}
	getTrueCarPrice(image.attr("styleid"), affixPriceWorker);
}

VehiclePreviewStrip.prototype.initThumbEvents = function() {
    var self = this;
    function over(e) {
		self.oldZIndex = $(this).css("z-index");
		$(this).css("z-index", 151);
		$(this).animate(
			{ width: self.imageWidth * 1.1,
			  height: self.imageHeight * 1.1,
			  marginTop: "-10px" },
			"fast",
			"swing",
			500
		);
        self.showVehicleInfo($(this));
    }
    
    function out(e) {
		$(this).css("z-index", 150);
		$(this).animate(
			{ width: self.imageWidth,
			  height: self.imageHeight,
			  marginTop: "0" },
		   "fast",
		   "swing",
			500
		);
		$(this).css("z-index", self.oldZIndex);
        self.hideVehicleInfo($(this));
    }
    $(".vehicleImages").hover(over, out);
}

VehiclePreviewStrip.prototype.scrollToModel = function(model) {
    var list = $(".vehicleImages");
    var scrollArea = $("#scrollArea");
    var offset = undefined;

    // instantly reset the position so that the offset is consistent
    scrollArea.scrollLeft(0);
    
    // find the offset
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].getAttribute("model") == model) {
            offset = $(list[i]).offset().left;
            break;
        }
    }
    
    // if we found the car, animate the scroll to it
    if (offset != undefined) {
        scrollArea.animate(
            { scrollLeft: (offset - this.imageWidth + 2) + "px" },
            "normal",
            "swing"
        );
    }
}

VehiclePreviewStrip.prototype.reAdjustSize = function() {
    $(".vehicleList").width(g_stripCount * this.imageWidth);
}

VehiclePreviewStrip.prototype.scrollRight = function() {
    var self = this;
    var scrollArea = $("#scrollArea");
    scrollArea.animate(
        { scrollLeft: (scrollArea.scrollLeft() + self.imageWidth + 2) + "px" }
    );
    self.reAdjustSize();
}

VehiclePreviewStrip.prototype.scrollLeft = function() {
    var self = this;
    var scrollArea = $("#scrollArea");
    scrollArea.animate(
        { scrollLeft: (scrollArea.scrollLeft() - self.imageWidth + 2) + "px" }
    );
    self.reAdjustSize();
}

VehiclePreviewStrip.prototype.longScrollLeft = function() {
    var self = this;
    var scrollArea = $("#scrollArea");
    var speed = 4;
    var acceleration = 1.1;
    self.keepGoingLeft = true;

    // animate with a goal of around 30fps
    self.leftIntervalId = window.setInterval(function() {
        scrollArea.scrollLeft(scrollArea.scrollLeft() - (speed * acceleration));
        acceleration += 0.16;

        // this function is called on the hover event and it when this event ends
        // it is responsible for clearing the below flag
        if (!self.keepGoingLeft) {
            window.clearInterval(self.leftIntervalId);
        }
    }, 33);
    self.reAdjustSize();
}

VehiclePreviewStrip.prototype.longScrollRight = function() {
    var self = this;
    var scrollArea = $("#scrollArea");
    var speed = 4;
    var acceleration = 1.1;
    self.keepGoingRight = true;
    
    // animate with a goal of around 30fps
    self.rightIntervalId = window.setInterval(function() {
        scrollArea.scrollLeft(scrollArea.scrollLeft() + (speed * acceleration));
        acceleration += 0.16;

        // this function is called on the hover event and it when this event ends
        // it is responsible for clearing the below flag
        if (!self.keepGoingRight) {
            window.clearInterval(self.rightIntervalId);
        }
    }, 33);
    self.reAdjustSize();
}

VehiclePreviewStrip.prototype.showVehicleInfo = function(targetImg) {
	var self = this;
    var content = '<div class="vehicleInfo">' +
        '<span class="carName">'+ targetImg.attr("make") + ' ' + targetImg.attr("model") +'</span>' +
        '<span class="textContent">MSRP: '+ this.formatPrice(targetImg.attr("msrp")) +'</span><br/>' +
        '<span class="textContent">TrueCar Avg Price: '+ this.formatPrice(targetImg.attr("truecarprice")) +'</span> ' +
        '</div>';
	self.toolTip.show(content, 100, 50);
}


VehiclePreviewStrip.prototype.hideVehicleInfo = function(targetImg) {
	this.toolTip.hide();
}

///
/// Adds commas and dollar signs where appropriate.
///
VehiclePreviewStrip.prototype.formatPrice = function(price) {
	var str = price.toString();
    var back = "";
    for (var i = 1; i <= str.length; i++) {
        back += str.charAt(str.length - i);
        if (str.length - i != 0 && i % 3 == 0)
            back += ",";
    }
    var retval = "";
    for (var j = back.length; j > -1; j--) {
        retval += back.charAt(j);
    }
    return '$' + retval;
}

///
/// Retrieves the URL for the models
///
VehiclePreviewStrip.prototype.getModelUrls = function(makeName) {
    var self = this;
    function callback(data) {
        self.displayContent(data.d);
    }
    
    // when empty, show the top 10 cars
    if (makeName == '') {
        makeName = 'top10';
    }
    
    $.get(
        "/services/DataService.svc/GetModelsForMake",
        { make: makeName },
        callback,
        "json"
    );
}


///
/// Creates a temporary popup window that disolves after a period of time
/// on its own. The tooltip is designed to display on a mouseover and
/// disappear when the object is no longer being hovered over.
///
function ToolTip() {
	this.parent = window;
	this.timeout = 6000; // milliseconds
	this.init();
}

ToolTip.prototype.init = function() {
	this.idNum = new Date().getMilliseconds();
	this.toolTip = $('<div id="toolTip' + this.idNum + '"class="tooltip">' + 
		'<div class="toolTipContent" id="toolTipContent' + this.idNum + '"></div>' +
		'</div>');
	this.toolTip.css("position", "absolute");
	this.toolTip.css("display", "none");
	this.toolTip.css("z-index", "1000");
	this.toolTip.css("background-color", "#91C4DF");
	this.toolTip.css("padding", "0");
	this.toolTip.css("margin", "0");

	var body = $(this.parent.document.getElementsByTagName("body")[0]);
	body.append(this.toolTip);
	this.trackMouse();
}

ToolTip.prototype.trackMouse = function() {
	var self = this;
	function onMouseMove(e) {
	    if (e.clientY > 160)
	        self.toolTip.css("top", 80);
	    else
	        self.toolTip.css("top", 200);
		
		if (e.clientX >= 150)
		    self.toolTip.css("left", 120);
		else
		    self.toolTip.css("left", 10);
	}
	// track mouse movements so that we know where to put the tooltip
	$().mousemove(onMouseMove);
}

ToolTip.prototype.show = function(content, width, height) {
	var self = this;
	//self.toolTip.width(width);
	//self.toolTip.height(height);
	
	var toolTipContent = $(self.parent.document.getElementById("toolTipContent" + self.idNum));
	toolTipContent.html(content);
	toolTipContent.css("font-size", "12px");
	toolTipContent.css("font-family", "Tahoma, sans-serif");
	toolTipContent.css("width", "100%");
	toolTipContent.css("padding", "0 0 5px 0");
    toolTipContent.css("margin", "0");
    toolTipContent.css("vertical-align", "top");
    toolTipContent.css("border", "1px solid black");
    
    var carName = $(self.parent.document).find(".carName");
    carName.css("display", "block");
    carName.css("background-color", "#4394db");
    carName.css("color", "white");
    carName.css("width", "100%");
    carName.css("margin", "0");
    carName.css("top", "0");
    carName.css("font-weight", "bold");
    carName.css("font-family", "Arial, Helvetica, sans-serif");
    carName.css("font-size", "12px");
    carName.css("border-bottom", "1px solid black");
    carName.css("text-align", "center");
    
    var txt = $(self.parent.document).find(".textContent");
    txt.css("padding", "5px 5px 0 5px");
    
    
	self.toolTip.show();
	// hide after a bit
	//window.setTimeout(function() { self.hide(); }, self.timeout);
}

ToolTip.prototype.hide = function() {
	var self = this;
	self.toolTip.hide();
}



function missingImage(image, self) {
    image.onerror = null;
    var node = $('#' + image.id);
    node.parent().remove();
    node.remove();
    g_stripCount = g_stripCount - 1;
}


function getTrueCarPrice(styleId, callback) {
	$.get(
        "/services/DataService.svc/GetTrueCarPrice",
        { styleId: styleId },
        callback,
        "json"
    );
}


function onReady() {
    var widget = new EzCarPricesMini300("ezCarPricesMini300");
    popState("state");
}
$(document).ready(onReady);


