// Define variables
var menu_timeout = 0;
var rotate = 0;

// Ready
$(document).ready(function() {
    $("a[rel^='prettyPhoto']").prettyPhoto();
	
	//$().jSnow();

    // Background stuff
    background_resize();
    $(window).resize(function() {
        background_resize();
    });

    // Rotate home page
    if ($('#home').length)
    {
        rotate = setTimeout(function() {
            show_promotion('next', true);
        }, 10000);
    }

    // Car menu
    $('#header ul li:first a, #cars').hover(function() {
        clearTimeout(menu_timeout);

        $('#header ul li:first').addClass('active_models');
        $('#cars').show();
        $('#info_options a').hide();
    }).mouseleave(function() {
        menu_timeout = setTimeout(function() {
            $('#header ul li:first').removeClass('active_models');
            $('#cars').hide();
            $('#info_options a').show();
        }, 100);
    });

    // Banners
    $('#banners').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'both',
        animation: 'slow',
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null,
        itemVisibleInCallback: {
            onAfterAnimation:  mycarousel_itemVisibleInCallbackAfterAnimation
        }
    });

    // Banners
    $('#banners_two').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'both',
        animation: 'slow',
        initCallback: mycarousel_initCallback_2,
        buttonNextHTML: null,
        buttonPrevHTML: null,
        itemVisibleInCallback: {
            onAfterAnimation:  mycarousel_itemVisibleInCallbackAfterAnimation_2
        }
    });

    // Top offers
    $('#top_offers ul').jcarousel({scroll: 1, animation: 'fast'});

    // Years in history
    $('#years ul').jcarousel({scroll: 3, animation: 'slow'});

    // Search
    $('#header form input').focus(function() {
        if ($(this).val() == 'бързо търсене')
        {
            $(this).val("");
        }
    });

    // Table and lis colours
    $('#data tr:even td').each(function() {
        $(this).addClass('even');
    });

    // Customcheckbox
    get_custom_checkbox();

    // DateTime Picker
    $(".datetime-input").datepicker({ dateFormat: 'yy-mm-dd' });

    // Unsupported browser IE6
    if ($.browser.msie && $.browser.version.substr(0,1) == '6')
    {
        $('body').append('<div id="unsupport"><p>Използвате стар браузър. Моля преминете към <a href="http://getfirefox.com">FireFox</a>, <a href="http://www.opera.com/download/">Opera</a>, <a href="http://www.apple.com/safari/">Safari</a> или <a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Internet Explorer 7+</a>. Благодарим Ви! [<a href="javascript:;" class="close">затвори</a>]</p></div>');
        $('#unsupport a.close').click(function() {
            $('#unsupport').remove();
        });
    }

    // For fun
    if ( window.addEventListener ) {
        var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
        window.addEventListener("keydown", function(e){
            kkeys.push( e.keyCode );
            if ( kkeys.toString().indexOf( konami ) >= 0 )
                randomize();
        }, true);
    }
});

// When background is loadet
$('#background img').load(function() {
    background_resize();
});

// Banners
function mycarousel_initCallback(carousel) {
    jQuery('#banners .jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
};
function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
    $('#banners .jcarousel-control a').removeClass('active');

    var active = idx-1;
    $('#banners .jcarousel-control a:eq('+active+')').addClass('active');
    //console.log('Item #' + idx + ' is now visible');
};


function mycarousel_initCallback_2(carousel) {
    jQuery('#banners_two .jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
};
function mycarousel_itemVisibleInCallbackAfterAnimation_2(carousel, item, idx, state) {
    $('#banners_two .jcarousel-control a').removeClass('active');

    var active = idx-1;
    $('#banners_two .jcarousel-control a:eq('+active+')').addClass('active');
    //console.log('Item #' + idx + ' is now visible');
};


// Background
function background_resize()
{
    var height = ($('#wrapper').height()) - 110;
    var width = $('body').width();

    /*
    var dimensions = {width: 0, height: 0};
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
    */
    
    $('#background').css({'height': height, 'width': width});


    $('#background img').css({'height':'auto','width':width});
    var bgr_height = $('#background img').height();

    if (height > bgr_height)
    {
        $('#background img').css({'height': height, 'width':'auto'});
    }
}

// Switch home page promotions
function show_promotion(goto, automate_rotation)
{
    clearTimeout(rotate);

    var promotion_code = $('#info_options input').val();
    
    // clear elements
    $('#info_options, #info_box, #background img').hide()
    $('#info_box').removeClass('right');
    $('#info_box').removeClass('document');
    $('#info_options p').attr('class', '');
    $('#info_box .document').remove();
    $('#info_box .video').remove();
    
    $.getJSON(_root + "application/xhr", { method: 'get_promotion', goto: goto, code: promotion_code }, function(data){
        // push data
        if (data.vat == 1)
        {
            $('#info_box strong').html('Цена от <em>0.00</em> лв. без ДДС');
        }
        else
        {
            $('#info_box strong').html('Цена от <em>0.00</em> лв.');
        }

        if (data.document)
        {
            $('#info_box .content').append("<a href='" + data.document + "' class='document' target='_blank'>изтегли оферта</a>");
        }

        if (data.video)
        {
            $('#info_box .content').append("<a href='" + _root + 'application/play_video?video=' + data.video + "&amp;iframe=true&amp;width=650&amp;height=350' rel='prettyPhoto' class='video'>видео клип</a>");
            $("#info_box .content a.video").prettyPhoto();
        }

        $('#info_box strong em').html(data.price);
        $('#info_box h2').html(data.title).attr('style', 'background-image: url(' + data.logo + ');');
        if (data.align == 1) { $('#info_box').addClass('right'); }
        $('#info_options p').attr('class', 'fixpng years_' + data.guarantee);
        if (data.quarantee > 0) { $('#info_options p').html(data.guarantee + 'години гаранция'); }
        $('#info_options input').val(data.promotion_id);

        $('#background img').bind('load', function() {
            $(this).fadeIn('fast', function() {
                $('#info_options, #info_box').fadeIn();
            });
        });
        $('#background img').attr('src', data.image);

        $('#info_box .prices').attr('href', _root + 'models/' + data.shortcut + '/calculator');
        $('#info_box .information').attr('href', _root + 'models/' + data.shortcut + '/technical_info');

        if (typeof(automate_rotation) != 'undefined')
        {
            rotate = setTimeout(function() {
                show_promotion('next', true);
            }, 10000);
        }
    });

    data = [];

    $("a[rel^='prettyPhoto']").prettyPhoto();
}

// Custom selects
$('.custom_select').click(function(){
    // Element properties
    var element = $(this);

    var element_name = $(this).attr("name");

    var element_position = $(this).position();

    var element_dimensions = $(this).innerWidth();

    // Select box
    var element_variables = $('#' + element_name);
    element.val($('option:selected', element_variables).text());
    if (element.val() == '') {
        element.val($('option:first', element_variables).text());
    }

    // When...
    element.each(function() {
        if (element_variables)
        {
            if (element_variables.css('display') == 'none')
            {
                var margin = parseInt($(this).css('margin-bottom'));

                // Set dimensions
                element_variables.css('left', element_position.left);
                element_variables.css('top', element_position.top - margin);
                element_variables.css('width', element_dimensions);

                // Set size
                var element_items = $('option', element_variables);
                var how_many_variables = element_items.length;
                if (how_many_variables == 1) how_many_variables = 2;
                if (how_many_variables > 5) how_many_variables = 5;
                element_variables.attr('size', how_many_variables);

                // Set actions
                element_variables.blur(function() {
                    element_variables.hide('fast');
                });

                element_variables.click(function() {
                    element.val($('option:selected', element_variables).text());
                    element_variables.hide('fast');

                    //element_variables.unbind('click');
                    //element_variables.trigger('change');
                });

                // Show it and set focus
                element_variables.fadeIn('fast');
                element_variables.focus();
            }
            else
            {
                element_variables.hide('fast');
            }
        }
    });
}).each(function(){
    var element_name = $(this).attr("name");
    var element_variables = $('#' + element_name);

    $(this).val($('option:selected', element_variables).text());
    if ($(this).val() == '') {
        $(this).val($('option:first', element_variables).text());
    }
});

// Custom checkbox
function get_custom_checkbox()
{
    $('.custom_checkbox').each(function() {
        var checkbox = $('input', $(this));
        var link = $('a', $(this));
        if (checkbox.is(':checked'))
        {
            link.addClass('checked');
        }

        link.bind('click', function() {
            if (link.hasClass('checked'))
            {
                link.removeClass('checked');
                checkbox.removeAttr('checked');
            }
            else
            {
                checkbox.attr('checked', 'checked');
                link.addClass('checked');
            }

            checkbox.trigger('change');
        });
    });
}
