﻿var _dist = 500;
var _cookie_zip;
var default_loc = 'City or Zip Code';
var default_search = 'Looking for a car?';
var _cookie_loc = default_loc;
jQuery(function ($) {
    $("img[src$=png]").pngfix();
});

$(document).ready(function () {
    initialUi();
    initialData();
});

function initialUi() {
    if (getCookie('_loc'))
        _cookie_loc = getCookie('_loc');

    if (getCookie('_zip'))
        _cookie_zip = getCookie('_zip');

    $('#location').val(_cookie_loc);
    $('#buy-searchinput').val(default_search);

    var cache = {}, lastXhr;
    $('#location').focus(function () {
        if ($(this).val() == default_loc)
            $(this).val('');
    }).blur(function () {
        if ($(this).val() == '') {
            if (_cookie_loc)
                $(this).val(_cookie_loc);
            else
                $(this).val(default_loc);
        }
    }).autocomplete({
        autoFocus: true,
        minLength: 2,
        delay: 50,
        source: function (request, response) {
            var term = request.term;

            if (term in cache) {
                response($.map(cache[term], function (item) {
                    var _label = item.City + ', ' + item.State;
                    if (!/\D/.test(term))
                        _label += ' ' + item.Zip;
                    return {
                        label: _acHighlight(_label, term),
                        value: item.City + ", " + item.State,
                        zip: item.Zip
                    };
                }));
                return;
            }
            lastXhr = $.getJSON(svc_url + "/location/search?q=" + term + "&callback=?", function (data, status, xhr) {
                cache[term] = data;
                if (xhr == lastXhr) {
                    response($.map(data, function (item) {
                        var _label = item.City + ', ' + item.State;
                        if (!/\D/.test(term))
                            _label += ' ' + item.Zip;
                        return {
                            label: _acHighlight(_label, term),
                            value: item.City + ", " + item.State,
                            zip: item.Zip
                        };
                    }));
                }
            });
        },
        select: function (event, ui) {
            _cookie_loc = ui.item.value;
            _cookie_zip = ui.item.zip;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        // only change here was to replace .text() with .html()
        return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append($("<a></a>").html(item.label))
                        .appendTo(ul);
    };

    var cache2 = {}, lastXhr2;
    $('#buy-searchinput').focus(function () {
        if ($(this).val() == default_search)
            $(this).val('');
    }).autocomplete({
        minLength: 2,
        delay: 50,
        source: function (request, response) {
            var term = request.term;

            if (term in cache2) {
                response($.map(cache2[term], function (item) {
                    var _label = (item.Year.length > 0 ? item.Year + ' ' : '')
                        + (item.Make.length > 0 ? item.Make + ' ' : '')
                        + (item.Model.length > 0 ? item.Model + ' ' : '')
                        + (item.Trim.length > 0 ? item.Trim + ' ' : '');

                    return {
                        label: _acHighlight(_label, term),
                        value: _label
                    };
                }));
                return;
            }
            lastXhr2 = $.getJSON(svc_url + "/ac/search?q=" + term + "&callback=?", function (data, status, xhr) {
                cache2[term] = data;
                if (xhr == lastXhr2) {
                    response($.map(data, function (item) {
                        var _label = (item.Year.length > 0 ? item.Year + ' ' : '')
                            + (item.Make.length > 0 ? item.Make + ' ' : '')
                            + (item.Model.length > 0 ? item.Model + ' ' : '')
                            + (item.Trim.length > 0 ? item.Trim + ' ' : '');

                        return {
                            label: _acHighlight(_label, term),
                            value: _label
                        };
                    }));
                }
            });
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        // only change here was to replace .text() with .html()
        return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append($("<a></a>").html(item.label))
                        .appendTo(ul);
    };


    $('#zipcode').val(_cookie_zip);
    $('#s-zip').val(_cookie_zip);

    //    $('#buy-searchinput').autocomplete(svc_url + "/search/getac", {
    //        //$('#buy-searchinput').autocomplete("http://nyu/rest/search/getac", {
    //        minChars: 2,
    //        width: 450,
    //        scrollHeight: 360,
    //        delay: 50,
    //        selectFirst: false,
    //        max: 10,
    //        matchContains: true,
    //        autoFill: false,
    //        dataType: "jsonp",
    //        parse: function (data) {
    //            var rows = new Array();
    //            for (var i = 0; i < data.length; i++) {
    //                var str = "";
    //                if (data[i].Year && data[i].Year.toString().length > 0)
    //                    str += data[i].Year;
    //                if (data[i].Make && data[i].Make.length > 0)
    //                    str += " " + data[i].Make;
    //                if (data[i].Model && data[i].Model.length > 0)
    //                    str += " " + data[i].Model;
    //                if (data[i].Trim && data[i].Trim.length > 0)
    //                    str += " " + data[i].Trim;
    //                rows[i] = { data: data[i], value: $.trim(str), result: $.trim(str) };
    //            }
    //            return rows;
    //        },
    //        formatItem: function (row, i, n) {
    //            return ((row.Year) ? (row.Year + " ") : "") + row.Make + " " + row.Model + " " + row.Trim;
    //        }
    //    });

    $("form#buy-form").submit(function () {
        //        if ($('#buy-searchinput').val() == 'e.g. BMW 3 Series')
        if ($('#buy-searchinput').val() == '')
            return false;
        else {
            location.href = "search/q=" + $('#buy-searchinput').val() + ";z=" + _cookie_zip + ";dist=" + _dist + "?loc=" + _cookie_loc;
            return false;
        }
    });
    $("form#s-form").submit(function () {
        if (validateModifySearchInput()) {
            var m = $('#s-make option:selected').html() == "All" ? "" : $('#s-make option:selected').html();
            var md = $('#s-model option:selected').html() == "All" ? "" : $('#s-model option:selected').html();
            var yf = $('#s-year-min option:selected').val();
            var yt = $('#s-year-max option:selected').val();
            var pl = $('#s-price-min option:selected').val();
            var ph = $('#s-price-max option:selected').val();
            var ml = $('#s-mileage-min option:selected').val();
            var mh = $('#s-mileage-max option:selected').val();
            var _zip = $('#s-zip').val();
            var _dist = $('#s-dist option:selected').val();
            location.href = "search/m=" + m + ";md=" + md + ";z=" + _zip + ";dist=" + _dist + ";yf=" + yf + ";yt=" + yt + ";pl=" + pl + ";ph=" + ph + ";ml=" + ml + ";mh=" + mh;
            return false;
        } else {
            return false;
        }
    });
    loadBrowseData();
}

function initialData() {
}

function _acHighlight(text, term) {
    var matcher = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(term) + ")(?![^<>]*>)(?![^&;]+;)", "gi");
    return text.replace(matcher, "<strong>$1</strong>");
}

function validateModifySearchInput() {
    return true;
}
function browseType(vt) {
    var _zip = $('#s-zip').val();
    location.href = "search/vt=" + vt + ";z=" + _zip + ";dist=200";
}
function browsePrice(low, high) {
    var _zip = $('#s-zip').val();
    location.href = "search/pl=" + low + ";ph=" + high + ";z=" + _zip + ";dist=200";
}
function loadBrowseData() {
    $('#s-make options').remove();
    var m_options = '<option value="">All</option>';
    for (var i = 0; i < _b.makes.length; i++) {
        m_options += '<option value="' + _b.makes[i].id + '">' + _b.makes[i].text + '</option>';
    }
    $('#s-make').html(m_options);
    $('#s-model options').remove();
    $('#s-model').html('<option value="">All</option>');
    $('#s-model').attr("disabled", $('#s-make option:selected').html() == "All");
    $('#s-make').change(function () {
        var selected_index = $(this).val();
        $('#s-model options').remove();
        var md_options = '<option value="">All</option>';
        for (var i = 0; i < _b.makes[selected_index].models.length; i++) {
            md_options += '<option value="' + _b.makes[selected_index].models[i] + '">' + _b.makes[selected_index].models[i] + '</option>';
        }
        $('#s-model').html(md_options);
        $('#s-model').attr("disabled", false);
    });
    if ($('#s-make option:selected').html() != "All") {
        var selected_index = $('#s-make option:selected').val();
        $('#s-model options').remove();
        var md_options = '<option value="">All</option>';
        for (var i = 0; i < _b.makes[selected_index].models.length; i++) {
            md_options += '<option value="' + _b.makes[selected_index].models[i] + '">' + _b.makes[selected_index].models[i] + '</option>';
        }
        $('#s-model').html(md_options);
        $('#s-model').attr("disabled", false);
    }

}
