$(document).ready(function(){
    /* show/hide table of brand_images */
    $("#allOp").click(function(event){
        if($('.tohide').is(':hidden'))
        {
            $('.tohide').show();
            $('#allOp').html(translate['VIEW_LESS_NETWORKS']);
        }
        else
        {
            $('.tohide').hide();
            $('#allOp').html(translate['VIEW_ALL_NETWORKS']);
        }
    });

    /*
     * Login div shows when mouse is over the Log in link.
     * If mouse is over div or any of the input elements have focus, the div will not be closed.
     */
    var $loginDiv = $('#logindiv');
    var isMouseOverLoginDiv = false;
    var hasLoginDivFocus = false;
    var loginDivCloseTimeout = 2000;
    var timer = null;

    var closeLoginDiv = function() {
        if (isMouseOverLoginDiv || hasLoginDivFocus) {
            updateLoginDivTimer();
            return;
        }

        $loginDiv.hide('slow');
    }

    var updateLoginDivTimer = function () {
        // clear possible previously set timeout
        clearTimeout(timer);

        // set fresh timeout
        timer = setTimeout(closeLoginDiv, loginDivCloseTimeout);
    }

    $loginDiv.mouseover(function(e) {
        isMouseOverLoginDiv = true;
        updateLoginDivTimer();
    });

    $loginDiv.mouseout(function(e) {
        isMouseOverLoginDiv = false;
    });

    $('input', $loginDiv).focus(function(e) {
        hasLoginDivFocus = true;
        updateLoginDivTimer();
    });
    
    $('input', $loginDiv).blur(function(e) {
        hasLoginDivFocus = false;
    });

    $('#loginlink').mouseover(function(event) {
        if ($loginDiv.is(':hidden')) {
            $loginDiv.show('slow');
        }

        updateLoginDivTimer();
    });


    /*
     * Language div
     */
    $('#langlink').mouseover(function(event){
        $('#langdiv').show('slow');
    });

    //make sure lang div stays shown on mouse over
    $('#langdiv').hover(
        function(event){
            $('#langdiv').show('slow');
        },
        function(event){
            $('#langdiv').hide('slow');
        }
        );


/* FIND PHONE */
    /* redirect on platform select */
    $("select#platform_id").change(function(){
        $.getJSON("/en/ajax/redirect-to-platform-find",{
            format: 'json',
            platform_id: $("select#platform_id").val(),
            list: $("input#list").val(),
            page: $("input#page").val()
        }, function(url){
            window.location = url;
        })
    });

    /* redirect on brand select */
    $("select#brand_id").change(function(){
        $.getJSON("/en/ajax/redirect-to-platform-brand-find",{
            format: 'json',
            platform_id: $("select#platform_id").val(),
            brand_id: $("select#brand_id").val(),
            list: $("input#list").val(),
            page: $("input#page").val()
        }, function(url){
            window.location = url;
        })
    });
/* END FIND PHONE */
    
    
    
    /*
     * Quick search of phone
     */
    var $selectPlatform = $("select#qsearch-platform");
    var $selectBrand = $("select#qsearch-brand");
    var $selectModel = $("select#qsearch-model");

    var buildQuickSearchHtml = function (options, defaultOptionDisplay) {
        // prepend the default option
        options.unshift({optionValue: '', optionDisplay: defaultOptionDisplay});

        var optionsHtml = '';
        $.each(options, function(i, option) {
            optionsHtml += '<option value="'+ option.optionValue +'">'+ option.optionDisplay +'</option>';
        });

        return optionsHtml;
    }

    // platform select -> populate brands OR hide brand select and trigger population of phones
    $selectPlatform.change(function() {
        var selectedPlatform = $(this).val();

        $.getJSON("/en/ajax/get-brands-by-platform-rs",{
            format: 'json',
            platform_rs: selectedPlatform
        }, function(options) {
            if (options.length == 1) {
                $selectBrand.hide().trigger('change');
                return;
            }

            $selectBrand.html(buildQuickSearchHtml(options, translate['SELECT_BRAND'])).show()

            // if there is just the Select brand option, disable select
            if (options.length == 1) {
                $selectBrand.attr('disabled', true);
            } else {
                $selectBrand.removeAttr('disabled');
            }

            $selectModel.attr('disabled', true);
        });
    });

    // brand select -> populate phones
    $selectBrand.change(function() {
        var url, params;

        // choose source of phones according to brand select
        if ($selectBrand.is(':hidden')) {
            url = '/en/ajax/get-models-by-platform-rs';
            params = {
                format: 'json',
                platform_rs: $selectPlatform.val()
            };
        } else {
            url = '/en/ajax/get-models-by-brand-rs';
            params = {
                format: 'json',
                platform_rs: $selectPlatform.val(),
                brand_rs: $(this).val()
            };
        }

        $.getJSON(url, params, function(options) {
            $selectModel.html(buildQuickSearchHtml(options, translate['SELECT_PHONE']));

            // if there is just the Select phone option, disable select
            if (options.length == 1) {
                $selectModel.attr('disabled', true);
            } else {
                $selectModel.removeAttr('disabled');
            }
        })
    });

    // phone select -> redirect to detail
    $selectModel.change(function(){
        $.getJSON("/en/ajax/get-detail-url",{
            format: 'json',
            platform_rs: $selectPlatform.val(),
            brand_rs: $selectBrand.val(),
            phone_rs: $selectModel.val()
        }, function(url){
            if (url.length == 0) {
                document.body.style.cursor = 'wait';
                window.location.reload();
                return;
            }

            document.body.style.cursor = 'wait';
            window.location = url;
        })
    });

    // on init set quick search to default state & simulate the change event
    $selectBrand.html('<option value="">'+ translate['SELECT_BRAND'] +'</option>').show().attr('disabled', true);
    $selectModel.html('<option value="">'+ translate['SELECT_PHONE'] +'</option>').show().attr('disabled', true);

    
    
    
    

    // Checkout county select
    $('div.province input[type=radio]').change(function(){
        $.fn.checkoutCountryChange();
    });
    $('#select_country_code').change(function(){
        $.fn.checkoutCountryChange();
    }).change();
    
    
});

$.fn.checkoutCountryChange = function(){
    var $label = $('label[for=accept] b');

    var province = $('div.province input[type=radio]:checked').val();
    if (province == 'eu') {
        var $option = $('#select_country_code option:selected');
        var value = $option.attr('value');
        var label = $option.attr('label');

        $('div.country').show('slow');
        if (value == 0 || value == '--') {
            $label.text(translate['ACCEPT_IN_EU'].replace('<COUNTRY>', '---'))
        } else {
            $label.text(translate['ACCEPT_IN_EU'].replace('<COUNTRY>', label))
        }
    } else if (province == 'out-eu') {
        $('div.country').hide('slow');
        $label.text(translate['ACCEPT_OUT_EU']);
    } else {
        $('div.country').hide();
        $label.text('---');
    }

};



// -------------- YOUTUBE -----------------------
function Video(id, ytCode, s3link, width, height) {
    this.id = id;
    this.ytCode = ytCode;
    this.s3link = s3link;
    this.width = width;
    this.height = height;
}

function Player()
{
    var _jwplayerLoaded = false;
    var _videos = [];

    this.initVideo = function(key)
    {
        var video = _getPlayerById(key);
        if (video.ytCode) {
            _createYouTubePlayer(video);
        } else if (video.s3link) {
            _createJwPlayer(video);
        }
        _videos[_videos.length] = video;
    }


    this.addVideo = function(key, ytCode, s3link, width, height)
    {
        _videos[_videos.length] = new Video(key, ytCode, s3link, width, height);
    }
    
    
    this.onYouTubePlayerReady = function(playerId)
    {
        player = document.getElementById(playerId)

        if (player.getDuration() < 1) {

            video = _getPlayerById(playerId);
            if (!video) {
                return;
            }

            if (_getPlayerById(playerId).s3link.length > 0) { // try to load JW player
                $('#'+video.id).remove();
                _createJwPlayer(video);
            } else {
                player.playVideo();
            }
        }
    }
    

    function _createYouTubePlayer(video)
    {
        params = {allowScriptAccess: "always"};
        atts = {id: video.id};
        swfobject.embedSWF("http://www.youtube.com/v/" + video.ytCode + "?version=3&rel=0&fs=0&enablejsapi=1&playerapiid="+video.id,
                           video.id+'-yt', video.width, video.height, "9", null, null, params, atts);
    }


    function _loadJwPlayer()
    {
        if (_jwplayerLoaded) {
            return;
        }
        _jwplayerLoaded = true;

        var tag = document.createElement('script');
        tag.src = document.location.protocol + '//' + document.location.host + "/mediaplayer/jwplayer.js";
        $(tag).insertAfter($('head script:last'));
    }


    function _createJwPlayer(video)
    {
        _loadJwPlayer();
        jwplayer(video.id+'-jw').setup({ 
            flashplayer: "/mediaplayer/player.swf", 
            file: video.s3link,
            height: video.height, 
            width: video.width
        });
    }


    function _getPlayerById(id)
    {
        var result = false;
        $.each(_videos, function(key, video){
            if (video.id == id) {
                result = video;
            }
        });
        return result;
    }
}

var player = new Player();

function onYouTubePlayerReady(playerId)
{
    player.onYouTubePlayerReady(playerId);
}
// -------------- YOUTUBE -----------------------



// -------------- GOOGLE ANALYTICS CONFIGURATION --------------------

