String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
$.fancybox.visible = function() {
    return $('#fancybox-wrap').is(':visible');
};

var Autonica = {
    base_url : function(){
        var url = location.href;  // entire url including querystring - also: window.location.href;
        var baseURL = url.substring(0, url.indexOf('/', 14));

        if (baseURL.indexOf('http://localhost') != -1) {
            // Base Url for localhost
            var url = location.href;  // window.location.href;
            var pathname = location.pathname;  // window.location.pathname;
            var index1 = url.indexOf(pathname);
            var index2 = url.indexOf("/", index1 + 1);
            var baseLocalUrl = url.substr(0, index2);

            return baseLocalUrl + "/";
        }
        else {
            // Root Url for domain name
            return baseURL + "/";
        }
    }(),
    media_url : 'http://static.autonica.com/',
    scroll_settings : {
        verticalDragMaxHeight:30,
        showArrows:true
    },
    updateFancybox : function() {
        $('a.fancybox').fancybox({
            onComplete:function(){
                var $imageWrapper = $('.image-wrapper');
                if($imageWrapper.find('li').length > 1){
                    $imageWrapper.jCarouselLite({
                        'circular':true,
                        'visible':1,
                        'btnNext':'.next',
                        'btnPrev':'.prev'
                    });
                }

                Autonica.updatePosition();
            }
        });
    },
    updatePosition : function() {
        var link = $('.content-nav li.active a').attr('href');
        if (!(typeof link == "undefined")) {
            var hash = link.split('#')[1];
            if (!(typeof hash == "undefined")) {
                var $element = $('#' + hash);
                $('.outer-content-wrap').stop().scrollTo($element, 0, {axis:'y'});
            }
        }
    },
    animateMovement : function($element, callback) {
        $element.closest('.outer-content-wrap').scrollTo($element, 1000, {
            'onAfter':function() {
                if (callback && typeof(callback) === "function") {
                    callback();
                }

            },
            axis:'y'
        });
    },
    animateContentNav : function() {
        //animate the up down movement
        var $contentNav = $('.content-nav li');
        $contentNav.find('.item').append('<div class="item-anim" />');

        $contentNav.find('a').bind('mouseenter',
                function() {
                    $(this).css('color', '#fff').find('.item-anim').animate({
                        width:'100%'
                    }, 'fast');
                }).bind('mouseleave', function() {
                    $(this).css('color', '#D31F18').find('.item-anim').stop(true).css({
                        width:'0'
                    });
                });
    },
    showSlider : function(field) {
        //show the sliders in the search forms
        var $slider = $('#slider-' + field);
        var $minInput = $slider.siblings('#' + field + '_0');
        var $maxInput = $slider.siblings('#' + field + '_1');
        var $label = $slider.siblings('label');
        var $span = $('<span />').addClass('text')

        $slider.after($span);


        var format = $minInput.attr('data-format');
        if (format === undefined) {
            format = '';
        }


        $maxInput.hide();
        $minInput.hide();

        var min = parseInt($minInput.attr('min'), 10);
        var max = parseInt($maxInput.attr('max'), 10);

        var text = ' Entre <em>' + format + min + '</em> y <em>' + format + max + '</em>';
        $span.html(text);

        var step = parseInt(( max - min ) / 100);
        $slider.slider({
            'range': true,
            'min':min,
            'max': max,
            'step':step,
            'values': [ min, max],
            'slide': function(event, ui) {
                $minInput.val(ui.values[0]);
                $maxInput.val(ui.values[1]);

                var text = ' Entre <em>' + format + ui.values[0] + '</em> y <em>' + format + ui.values[1] + '</em>';
                $span.html(text);
            },
            'stop':function(event, ui) {
                $slider.closest('form').submit();
            }
        });
    },
    ajaxUpdate : function() {
        //make the ajax update of the content
        var state = History.getState();
        var url = state.url.replace('http://autonica.com/', '/');



        $.fancybox.showActivity();
        $.getJSON(url, function(data) {
            var $toremove = $('.content').removeClass('active'),
                    $main_menu = $('#menu');

            var $newContent = $('<div />').addClass('content').addClass('active').addClass('new-content');
            $toremove.after($newContent).addClass('remove');

            //update the menu
            var $newActive = $main_menu.children(':has(a[href$="' + url + '"])');
            if ($newActive.length) {
                $newActive.addClass('active').siblings('.active').removeClass('active');
            } else {
                $main_menu.children().removeClass('active');
            }


            $newContent.html(data.content).fadeIn(function() {
                $('.content').not('.new-content').remove();
                $(this).removeClass('new-content');
            });


            $.fancybox.hideActivity();

            $toremove.stop(true, true).fadeOut(5000);
            $newContent.fadeIn(3000, function() {
                $('.content').not($newContent).stop().remove();
                Autonica.$menu.html(data.contentNav);

                $('#container .scroll').jScrollPane(Autonica.scroll_settings);
                Autonica.updateFancybox();
                Autonica.animateContentNav();
                $('select').selectbox({
                    animationSpeed:'fast',
                    listboxMaxSize:50
                });
            });
        });
    },
    //given a url returns only the path
    pathFromUrl:function(url){
        var a = document.createElement('a');

        a.href = url;
        var path = a.pathname;
        return path;
    }
};









if (Modernizr.history) {
    (function(window) {



        // Prepare our Variables
        var History = window.History,
                $ = window.jQuery;

        // Check to see if History.js is enabled for our Browser

        if (!History.enabled) {
            return false;
        }

        $(document).ready(function() {




            // Ajaxify our Internal Links
            $(this).find('a.ajaxy').live('click', function(event) {
                // Continue as normal for cmd clicks etc
                if (event.which == 2 || event.metaKey) {
                    return true;
                }
                // Ajaxify this link
                var $this = $(this), url = $this.attr('href'), title = $this.attr('title') || null;
                History.pushState(null, title, url);

                event.preventDefault();
            });

            //Load the ajax
            $(window).bind('statechange', function() {
                Autonica.ajaxUpdate();

            });
        });
    })(window);
}

$(document).ready(function() {
    Autonica.$menu = $('.content-nav');
    Autonica.$im = $('<img>');


    $('a.cotice').live('click',function(e){
        e.preventDefault();
        if(location.pathname == '/repuestos/'){
            var url  = this.href + '?chasis=1'
        }else{
            var url = this.href
        }
        $.fancybox({
            'type':'iframe',
            'height':570,
            'href'			: url,
            'onComplete':Autonica.updatePosition
        });
    });
    $(' a.specs-link').live('click',function(e){
        e.preventDefault();
        $.fancybox({
            'autoDimensions':false,
            'width':'800px',
            'height':'500px',
            'href'			: this.href,
            'onComplete':function(){
                Autonica.updatePosition();
            }
        });
    });

    Autonica.animateContentNav()
    Autonica.updateFancybox();

    $('select').selectbox({
        'animationSpeed':'fast'
    });

    //hide transparent-background so it wont show in the initial scroll effect
    $('.section > .transparent-background').css('display', 'none');

    Autonica.$im.attr('src', Autonica.media_url + 'img/ajax-loader.gif').addClass('load-anim');

    //use jscrollpane only with correct box model
    if ($.support.boxModel) {
        $('#container .scroll').jScrollPane(Autonica.scroll_settings);

    }

    $('.filter select').live('change',function(){
        $(this).closest('.filter').submit();
    });
    $('.filter').live('submit',function(e){
        e.preventDefault();
        $.fancybox.showActivity();
        var $elem = $(this);
        var data = $elem.serialize();

        $.post( $elem.attr('action') ,data, function(data) {
            $.fancybox.hideActivity();

            $elem.closest('.section').find('.filter-list').quicksand($(data).find('li'), {
                        'adjustHeight':false,
                        'easing': 'easeInOutQuad',
                        'duration':800
                    }, function() {
                        Autonica.updateFancybox()
                    });
        });
    });


    Autonica.showSlider();


    $(window).resize(function() {
        Autonica.updatePosition();
    });

    $('html').ajaxSend(function(event, xhr) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    });

    //Navigate using keyboard
    $(document).keydown(function(e) {
        if (e.keyCode == 38) { // up
            $('.content-nav li.active').prev('li').find('a').click();
            e.preventDefault();
        } else if (e.keyCode == 40) { // down
            $('.content-nav li.active').next('li').find('a').click();
            e.preventDefault();
        } else if (e.keyCode == 27) {
            if ($('#new-cars-wrap').is(':visible')) {
                $('#new-cars-wrap').fadeOut();
            }
        }

    });

    //Hide car selector
    $(document).click(function() {
        if ($('#new-cars-wrap').is(':visible')) {
            $('#new-cars-wrap').fadeOut();
        }
    });
    $('#new-cars-show').click(function(e) {
        $('#new-cars-wrap').fadeToggle();
        e.preventDefault();
        e.stopPropagation();
    });

    $('.content-nav a').live('click', function(e) {

        Autonica.$menu.children(':has(a[href$="' + $(this).attr('href') + '"])').addClass('active').siblings('.active').removeClass('active');

        var href = $(this).attr('href');
        var hash = '#' + href.split('#')[1];
        var $element = $(hash);


        if ($element.is('.cover')) {
            $('.section > .transparent-background').fadeOut();
            Autonica.animateMovement($element);
        } else {
            Autonica.animateMovement($element, function() {
                $('.section > .transparent-background').fadeIn('medium');
            });
        }

        e.preventDefault();
    });


    // Color Picker
    $('.color-picker-box a').live('click', function(e) {
        $('.colors-load').fadeIn('fast');
        var $nextColor = $('.next-color'),
                url = $(this).attr('href'),
                $curImg = $('.cur-color img'),
            // Show loading animation until image has really loaded
                _im = $('<img />');

        _im.bind("load", function() {
            $('.colors-load').stop(true).fadeOut('fast');
            $('.next-color').stop(true).css('width', '0').animate(
                    {
                        width:'100%'
                    },
                    1500,
                    function() {
                        $curImg.attr('src', url);
                        $(this).width(0).children('img').remove();
                    }
            );
        });
        // append to target node / element
        $nextColor.append(_im);
        // set the src attribute now, after insertion to the DOM
        _im.attr('src', url);
        e.preventDefault();
    });

    $('a.video-fancybox').live('click',function(e){
        e.preventDefault();
        var href = $(this).attr('href').replace(new RegExp("watch\\?v=", "i"), 'v/') ;
        $.fancybox({
            'padding'		: 0,
            'autoScale'		: false,
            'transitionIn'	: 'none',
            'transitionOut'	: 'none',
            'title'			: this.title,
            'width'		: 680,
            'height'		: 495,
            'href'			: href,
            'type'			: 'swf',
            'swf'			: {
                'wmode'		: 'transparent',
                'allowfullscreen'	: 'true'
            },
            'onComplete':function(){
                Autonica.updatePosition();
            }
        });
    });

    $('#menu a').not('#new-cars-show').click(function(e){
        if(location.pathname == Autonica.pathFromUrl($(this).attr('href'))){
            $('.content-nav a:first').click();
        }
    });

});


