﻿/* Global Variables */
var currentBrand = null;
var currentModel = null;
var currentSuperType = "Carros";

var mycarousel_itemList = new Array();
var isIE6 = false;
function mycarousel_initCallback(carousel) {
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });

    initFadeHover(".jcarousel-prev");
    initFadeHover(".jcarousel-next");

};
function mycarousel_itemLoadCallback(carousel, state) {
    if (state != 'init')
        return;

    //  $(".jcarousel-container").animate({ 'opacity': 1 }, 850);
    //  $(".bottomArea").stop().animate({ 'opacity': 1 }, 350);
    $(".jcarousel-prev").css("visibility", "visible");
    $(".jcarousel-next").css("visibility", "visible");
};
function mycarousel_getItemHTML(item) {
    return '<a href="/' + currentSuperType + '/' + item + '/"><img src="/Content/img/Brands/small/' + item + '.png" width="75" height="75" alt="' + item + '" border=0/></a>';
};
function mycarousel_itemAddCallback(carousel, first, last, data) {
    mycarousel_itemList = data.split('|');
};
function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
    if (mycarousel_itemList[idx - 1] == currentBrand) {
        $(".jcarousel-item-" + i).addClass("selected");
    }
    initFadeHover(".jcarousel-item-" + i);
    initFadeActivate(".jcarousel-item-" + i);
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
};
var superCarrosList = null;
var currentIndex = 0;
var currentVehicule = 0;
var losSuperCarrosAnimated = true;
function nextSuperCarros() {
    currentIndex++;
    // alert(superCarrosList.list.length);
    currentIndex = (currentIndex < superCarrosList.list.length) ? currentIndex : 0;
    //alert(currentIndex);
    var vehicule = superCarrosList.list[currentIndex];
    loadSupperCarros(vehicule);


    if (losSuperCarrosAnimated) setTimeout("nextSuperCarros()", 7000);
}
function previousSuperCarros() {
    currentIndex--;
    // alert(superCarrosList.list.length);
    currentIndex = (currentIndex < 0) ? superCarrosList.list.length - 1 : currentIndex;
    //alert(currentIndex);
    var vehicule = superCarrosList.list[currentIndex];
    loadSupperCarros(vehicule);

}
function pauseLosSuperCarros() {
    losSuperCarrosAnimated = false;
    $("#losSuperCarros .pause").hide();
    $("#losSuperCarros .play").show();

}
function playLosSuperCarros() {
    losSuperCarrosAnimated = true;
    $("#losSuperCarros .pause").show();
    $("#losSuperCarros .play").hide();
    nextSuperCarros();

}

function loadSupperCarros(vehicule) {
    //alert($("#losSuperCarros .container #losSuperCarros" + vehicule.ID));
    var el = $("#losSuperCarros .container #losSuperCarros" + vehicule.ID);

    if (!el.length) {
        var content = '<a href="/' + vehicule.Typo + '/' + vehicule.Brand + '/' + vehicule.Model + '/' + vehicule.ID + '.html"><img src="http://data.supercarros.com/used_cars/' + vehicule.ID + '_losSuperCarros.jpg"  class="photo" alt="' + vehicule.Brand + '"/></a> \
                        <div class="info"> \
                            <div class="title"> \
                                <span class="brand">' + vehicule.Brand + '</span> <span class="model">' + vehicule.Model + '</span> <span class="edition">' + vehicule.Edition + '</span> \
                            </div> \
                            <span class="year">' + vehicule.Year + '</span> <span class="price">' + vehicule.Price + '</span> \
                        </div>';
        $("#losSuperCarros .container").prepend("<div class='item' id='losSuperCarros" + vehicule.ID + "'>" + content + "</div>");
        vehicule.loaded = true;
    } else $("#losSuperCarros .container #losSuperCarros" + vehicule.ID).stop().css({ 'opacity': 1 });
    $("#losSuperCarros .container #losSuperCarros" + currentVehicule).css({ "z-index": 56 });
    $("#losSuperCarros .container #losSuperCarros" + currentVehicule).animate({ 'opacity': 0 }, 2000);
    currentVehicule = vehicule.ID;
    $("#losSuperCarros  a.details").attr("href", "/" + vehicule.Typo + "/" + vehicule.Brand + "/" + vehicule.Model + "/" + vehicule.ID + ".html");
    // alert("/Carros/" + vehicule.Brand + "/" + vehicule.Model + "/" + vehicule.ID + ".html");
    $("#losSuperCarros .container #losSuperCarros" + vehicule.ID).css({ "z-index": 55 });
    $("#losSuperCarros .pageCount .num").html(currentIndex + 1);
}
function initCarrousel(isVertical) {
    if (isNaN(isIE6) || isIE6 == null || !isIE6) {
        jQuery.get('/' + currentSuperType + '.txt', function(data) {
            mycarousel_itemList = data.split('|');
            var startPos = 1;
            for (i = 0; i < mycarousel_itemList.length; i++) {
                if (mycarousel_itemList[i] == currentBrand) {
                    startPos = i - 3;
                    if (startPos <= 0) startPos = mycarousel_itemList.length - (0 - startPos);
                }
            }
            jQuery('#bottomList').jcarousel({
            vertical: isVertical,
                start: startPos,
                scroll: 4,
                wrap: 'circular',
                itemLoadCallback: mycarousel_itemLoadCallback,
                itemVisibleInCallback: { onBeforeAnimation: mycarousel_itemVisibleInCallback },
                itemVisibleOutCallback: { onAfterAnimation: mycarousel_itemVisibleOutCallback },
                initCallback: mycarousel_initCallback
            });
        });
    }
}
jQuery(document).ready(function() {
    // alert("doc ready");
    $.history.init(loadHistory);

    if (!isIE6) {
        initFadeHover(".itemList li.level1");

        initFadeHover("#subMenu ul li");
        initFadeActivate("a.redButton, a.blueButton");
        initFadeHover("a.redButton,, a.blueButton");
    }
    initBrandSelector(".searchForm #brand", ".searchForm #vehiculeSuperType", false);
    initModelSelector(".searchForm #model", ".searchForm #brand", getSuperType);



    $(".searchForm #vehiculeSuperType").change();
    $(".searchForm #brand").change();

    $("#advanceSearch").submit(function() {
        var vehiculeType = currentSuperType; //$("#advanceSearch #vehiculeType").val();

        var brand = $("#advanceSearch #brand").val();
        var model = $("#advanceSearch #model").val();
        var url = "/" + vehiculeType + "/";
        if (brand != "") {
            url = url + brand + "/";
            if (model != null && model != "") url = url + model + "/";
        }
        this.action = url;

    });
    initPagging();

    $("#homeSearch #searchButton").click(
        function() {
            var vehiculeType = $("#homeSearch #vehiculeSuperType").val();

            var brand = $("#homeSearch #brand").val();
            var model = $("#homeSearch #model").val();
            var url = "/" + vehiculeType + "/";
            if (brand != "") {
                url = url + brand + "/";
                if (model != null && model != "") url = url + model + "/";
            }
            document.location = url;
        }
    );
    $("#buscarButton").hide();
    $("#searchLink").show();
    $('a[rel*=facebox]').facebox();
    $(document).bind('beforeReveal.facebox', function() {
        $("#facebox_overlay").animate({ 'opacity': 0.6 }, 500);
    });
    $(document).bind('close.facebox', function() {
        $("#facebox_overlay").animate({ 'opacity': 0 }, 500);
    });

    $("#mySuperCarros").load("/MySuperCarros/Nav/", function() {
    initWelcomeScreen();
    initLogonForm();
    
    
    });

    initSave();
    initRemove();
    $("#mySuperCarrosRegistration a#submit").click(function() { $("#mySuperCarrosRegistration").submit(); return false; });
    $("#mySuperCarrosForm2 a#submit").click(function() { $("#mySuperCarrosForm2").submit(); return false; });
});
function getSuperType() {
    //alert("ok");
    var el = $("#vehiculeSuperType");
    var ret = (el.length) ? el.val() : currentSuperType;
    //alert(ret);
    return ret;
    //{ "SuperType": ( }
}

function initModelSelector(modelSelector, brandSelector, superTypeF) {
    //alert("ok1");
    $(modelSelector).cascade(brandSelector, {
        ajax: { url: '/JSON/models/list.json'
        },
        template: function(item) {
            return "<option value='" + item.Name + "'>" + item.Name + "</option>";
        },
        match: function(selectedValue) {
       
            if (superTypeF == null) superTypeF = getSuperType;
            return (this.BrandName == selectedValue && this.SuperType == superTypeF());
        }
    }).bind("loaded.cascade", function(e, target) {
        //alert("ok");
        jQuery(this).prepend("<option value='' selected='true'>todos los modelos</option>");
        if (!isIE6) {
            if (currentModel != null && currentModel != "") {
                var m = jQuery(this).find("option[value='" + currentModel + "']");
                if (m != null && m[0] != null) {
                    m[0].selected = true;
                    $(this).addClass("active");
                } else {
                    jQuery(this).find("option:first")[0].selected = true;
                }
            } else {
                jQuery(this).find("option:first")[0].selected = true;
            }
        }
        jQuery(this).removeClass("disabled");
    });
}

function initBrandSelector(brandSelector, superTypeSelector, caller) {
    $(brandSelector).cascade(superTypeSelector, {
        ajax: { url: '/JSON/brands/list.json'
        },
        template: function(item) {
            return "<option value='" + item.Name + "'>" + item.Name + "</option>";
        },
        match: function(selectedValue) {
            return true;  //this.BrandName == selectedValue;
        },
        getParentValue: function(parent) {
            // alert($(parent).val());
            return $(parent).val();
        },
        caller: caller
    }).bind("loaded.cascade", function(e, target) {
        jQuery(this).prepend("<option value='' selected='true'>todas las marcas</option>");
        if (!isIE6) {
            if (currentBrand != null && currentBrand != "") {
                var m = jQuery(this).find("option[value='" + currentBrand + "']");
                if (m != null && m[0] != null) {
                    m[0].selected = true;
                } else {
                    jQuery(this).find("option:first")[0].selected = true;
                }
            } else {
                jQuery(this).find("option:first")[0].selected = true;
            }
        }
        jQuery(this).removeClass("disabled");

    });
}
function initVehiculeTypesSelector(vehiculeTypesSelector, superTypeSelector, caller) {
    $(vehiculeTypesSelector).cascade(superTypeSelector, {
        ajax: { url: '/JSON/vehiculeTypes/list.json'
        },
        template: function(item) {
            return "<option value='" + item.Name + "'>" + item.Name + "</option>";
        },
        match: function(selectedValue) {
            return true;  //this.BrandName == selectedValue;
        },
        getParentValue: function(parent) {
            // alert($(parent).val());
            return $(parent).val();
        },
        caller: caller
    }).bind("loaded.cascade", function(e, target) {
        jQuery(this).prepend("<option value='' selected='true'>todos los tipos</option>");
        if (!isIE6) {

            jQuery(this).find("option:first")[0].selected = true;
        }
        jQuery(this).removeClass("disabled");

    });
}

function initSave() {

    $("a#save").unbind('click').click(function() {
        var button = this;
        jQuery.get(button.href, null, function(result) {
            $("span.label", button).html("Eliminar de MySuperCarros");
            button.href = button.href.replace("AddFavorite", "RemoveFavorite");
            $(button).removeClass("save");
            $(button).addClass("remove");
            initRemove();
        });
        return false;
    });
}
function initRemove() {
    $("a.remove").unbind('click').click(function() {
        var button = this;
        jQuery.get(button.href, null, function(result) {
            $("span.label", button).html("Guardar en MySuperCarros");
            button.href = button.href.replace("RemoveFavorite", "AddFavorite");
            $(button).removeClass("remove");
            $(button).addClass("save");
            initSave();
        });
        return false;
    });
}
function initLogonForm() {
    $("#mySuperCarrosForm").ajaxForm({
    target: '#mySuperCarros',
        success: function() {
            initWelcomeScreen();
            initLogonForm();
        },
        error: function() { alert("error"); }
    });
    //$("#mySuperCarrosForm #submitForm").click(function() { $("#mySuperCarrosForm").submit(); return false; });
}
function initWelcomeScreen() {
    $("#mySuperCarros a#logOut").click(function() {
        $("#mySuperCarros").load(this.href, null, initLogonForm);
        return false;
    });
}
function initPagging() {
    $("#listContainer .loader").width($("div.VehiculeList").width());
    $("#listContainer .loader").height($("div.VehiculeList").height());
    /* $("#listContainer .loader").width($("#listContainer").width() - 4);
    $("#listContainer .loader").height($("#listContainer").height() - 44);*/
    $("#listContainer .loader img").css("margin-left", ($("#listContainer .loader").width() - 31) / 2);
    $("#listContainer .loader img").css("margin-top", ($("#listContainer .loader").height() - 31) / 2);
    $("#listContainer a.next.active,#listContainer a.previous.active, div.displayMode a").click(loadContainer);
    $("a.inactive").click(function() { return false; });
    //initFadeHover("ul.ContentList li.vehicule");
    initSortSelector();
    $("#listContainer ul.ContentList a").click(function() {
        // deleteCookie("VehiculePosition");
        setCookie("VehiculePosition", $(this).attr("rel"), null, "/");
        return true;
    });
  /*  $("ul.ContentList li.vehicule").hover(function() {
        $("ul.techDetails", this).show();
    }, function() {
        $("ul.techDetails", this).hide();
    });*/
}
function loadContainer() {
    //$("#listContainer .loader").show().animate({ 'opacity': 0.4 }, 500);
    var page = this.href.replace(/^.*#/, '');
   
    
    var enc = Base64.encode(page);

    //$.history.load(this.href.replace(/^.*#/, ''));
    $.history.load(enc);
    /* $("#listContainer").load(page, function() {
    pageTracker._trackPageview(page);
    initPagging();
    });*/
    return false;
}
function initFadeHover(selector) {
    var target = $(selector);
    target.prepend('<span class="hover"></span>');
    $(".hover", target).stop().animate({ 'opacity': 0 }, 0);
    $(selector).hover(function() {
        $(".hover", this).stop().animate({ 'opacity': 1 }, 600)
    }, function() {
        $(".hover", this).stop().animate({ 'opacity': 0 }, 1000);
    });
    target.addClass("fadeHover");
}
function initFadeActivate(selector) {
    var target = $(selector);
    target.prepend('<span class="down"></span>');
    $(".down", target).stop().animate({ 'opacity': 0 }, 0);
    target.mousedown(function() {
        $(".down", this).stop().animate({ 'opacity': 1 }, 600)
    });
    target.mouseup(function() {
        $(".down", this).stop().animate({ 'opacity': 0 }, 800);
    });
    target.addClass("fadeActivate");
}
var sortBy = "pubDate";
var sortOrder = "DESC";
function initSortSelector() {
    var sortBySelector = $("#losUltimos .listActions ul.sorting");
    sortBySelector.click(function() {
        // alert("ok");
        $("div.title", sortBySelector).show();
        sortBySelector.removeClass("inactive");
        $("li", sortBySelector).removeClass("inactive").click(function() {
            var active = false;
            if ($(this).hasClass("active")) active = true;
            $("li", sortBySelector).addClass("inactive");
            $("li.active", sortBySelector).removeClass("active");
            $("li", sortBySelector).unbind('click');
            $(this).removeClass("inactive");
            $(this).addClass("active");
            $("div.title", sortBySelector).hide();

            $("#sortBy").attr("value", $("a", this).attr("rel"));
            sortBySelector.addClass("inactive");
            if (!active) $("a", this).each(loadContainer);
            return false;
        });
        return false;
    })
    $(".sortOrder").click(function() {

        $(".sortOrder.inactive").removeClass("inactive").addClass("active");
        $(this).removeClass("active").addClass("inactive");
        $("#order").attr("value", $(this).attr("rel"));
    }).click(loadContainer);
}
function changeOrder() {
    var v = $("#orderselect").val();
    if (v == 1 || v == 2) {
        $("#sortBy").attr("value", "pubDate");
    }
    if (v == 3 || v == 4) {
        $("#sortBy").attr("value", "Year");
    }
    if (v == 5 || v == 6) {
        $("#sortBy").attr("value", "Price");
    }
    if (v == 1 || v == 3 || v == 5) {
        $("#order").attr("value", "DESC");
    } else {
        $("#order").attr("value", "ASC");
    }

}
function changeSorting() {
    var url = $("#sortingSelector").val()
    //alert(url);
    var page = url.replace(/^.*#/, '');
   
    
    var enc = Base64.encode(page);

    //$.history.load(this.href.replace(/^.*#/, ''));
    $.history.load(enc);
    /* $("#listContainer").load(page, function() {
    pageTracker._trackPageview(page);
    initPagging();
    });*/
    return false;
   
    
}

/********----   HISTORY STUFF       ---********/
function loadHistory(hash) {
    if (hash) {
        // alert(hash);
        $("#listContainer ul.vehiculeList, #listContainer ul.vehiculeTable").show().animate({ 'opacity': 0.4 }, 300);
        $("#listContainer .loader").show();
        //$("#listContainer .loader").show().animate({ 'opacity': 0.4 }, 500);
        // var page = this.href;
        /* if ($.browser.msie) {
        // jquery's $.load() function does't work when hash include special characters like åäö.
        hash = encodeURIComponent(hash);
        }*/
        var dec = hash;
        if (dec.indexOf("http") < 0) {
            dec = Base64.decode(hash);
        }
        // alert(dec);

        $("#listContainer").load(dec, function() {
            // pageTracker._trackPageview(page);
            initPagging();
        });
    }
}


