$(document).ready(function(){
    /*initialize quicksearch*/

    /* check if platform hasn't brands on load */
    if($("select#brand_id").children().length <= 2) /* 2 = 1 ("--select all--") + 1 (the only brand)*/
    {
        /* platform hasnt brand, hide all unnecessary controls */
        $("div#brand_id_select").hide();
        $("table.tohide").hide();
    }

    /* 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(){
        var brandRs = $selectBrand.is(':hidden') ? '' : $selectBrand.val();

        $.getJSON("/en/ajax/get-detail-url",{
            format: 'json',
            platform_rs: $selectPlatform.val(),
            brand_rs: brandRs,
            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();
    
    
    
    
    // ------------ HOMEPAGE SELECT BOX --------------------
    $("#title-choose-manufacturer").removeClass('select-active');
    $("#title-list-manufacturer").addClass('hid');
    
    
    var showManufacturerMenu = function(hoverElement, showedElement){
        hoverElement.hover(
            function(){
                if (hoverElement.hasClass('select-passive')) {return;}
                showedElement.removeClass('hid');
                hoverElement.addClass('select-active');
            },
            function(){
                hoverElement.removeClass('select-active');
                showedElement.addClass('hid');
            }
        );
        showedElement.hover(
            function(){
                if (hoverElement.hasClass('select-passive')) {return;}
                showedElement.removeClass('hid');
                hoverElement.addClass('select-active');
            },
            function(){
                hoverElement.removeClass('select-active');
                showedElement.addClass('hid');
            }
        );
    }

    var stopLoad = function() {
        document.body.style.cursor = 'default';
        $("#title-choose-model span").text(translate['SELECT_YOUR_MODEL']);
    }

    var startLoad = function() {
        document.body.style.cursor = 'wait';
        $("#title-choose-model span").html(translate['LOADING']+'&hellip; <img src="/images/loading.gif" alt=""> ');
        window.setTimeout(function(){
            stopLoad();
        }, 10000);
    }



    showManufacturerMenu($("#title-choose-manufacturer"), $("#title-list-manufacturer"));
    showManufacturerMenu($("#title-choose-model"), $("#title-list-model"));


    var $request = 0;
    $("#title-list-manufacturer a").click(function(){
        var $platformName = $(this).text();
        var $manufacturerRs = $(this).attr('name');
        
        /*if ($platformName == $("#title-choose-manufacturer span").text())  {
            return false;
        }*/
        $("#title-choose-manufacturer span").text($platformName);
        
        
        // waiting
        $("#title-list-manufacturer").addClass('hid');
        $("#title-choose-manufacturer").removeClass('select-active');

        var getModelsWithLinksByManufacturerRs = function(manufacturerRs, prefix) {
            startLoad();
            $.getJSON("/en/ajax/get-models-with-links-by-manufacturer-rs",{
                format: 'json',
                manufacturer: manufacturerRs,
                prefix: prefix
            }, function(options) {

                $("#title-choose-model").addClass('select-active');
                $("#title-list-model").removeClass('hid');

                var text = '';

                if ('alphabet' in options) {

                    if ($('#title-list-model div.clr div.alphabet').length > 0 && prefix) {
                        $('#title-list-model div.clr div.alphabet2').remove();
                        $('#title-list-model div.clr div.alphabet a.active').removeClass('active');
                        $('#title-list-model div.clr div.alphabet a.prefix-' + prefix).addClass('active');
                        text += $("#title-list-model div.clr").html();
                        text += '<div class="alphabet alphabet2">';
                    } else {
                        text += 'Select first letter:<br><div class="alphabet">';
                    }

                    $.each(options['alphabet'], function(index, value) {
                        text += '<a href="#'+ index +'" class="prefix-' + index + '">' +
                                index.replace(/-$/, "").replace('-', '&#8209;') +
                                '</a> ';
                    })
                    text += '</div>';
                } else if (options.length > 0 && options[0].length >= 1) {
                    $.each(options, function(index, value){
                        var list = '<ul'+(index==(options.length-1) ? ' class="l"' : '')+'>';
                        $.each(value, function(index, value){
                            list += '<li class="homepage-phone-select"><a href="'+value['optionValue']+'">'+value['optionDisplay']+'</a></li>';
                        });
                        list += '</ul>';

                        text += list;
                    });
                } else {
                    text = translate['NO_MODELS_AVIABLE'];
                }

                stopLoad();
                $("#title-choose-model").removeClass('select-passive');
                $("#title-list-model div.clr").html(text);
                
                $('li.homepage-phone-select a').click(function(){
                    window.analytics.trackers.push(['_trackEvent', 'Pages', 'Select phone', 'Used']);
                    sleep(100);
                });

                if ('alphabet' in options) {
                    $("#title-list-model div.clr div.alphabet a").click(function() {
                        var prefix = $(this).attr('href').substr(1);
                        getModelsWithLinksByManufacturerRs(manufacturerRs, prefix);
                        return false;
                    });
                }

                if (prefix) {
                    if (
                        $('#title-list-model div.box-hid2 a.back').length > 0 ||
                        $('#title-list-model div.clr div.alphabet').length > 0
                    ) {
                        return;
                    }
                    
                    $("<a href='#' class='back'>back</a>").prependTo('#title-list-model div.box-hid2').click(function() {
                        getModelsWithLinksByManufacturerRs(manufacturerRs);
                        return false;
                    });
                } else {
                    $('#title-list-model div.box-hid2 a.back').remove();
                }
            });
        }

        getModelsWithLinksByManufacturerRs($manufacturerRs);

        return false;
    });
    // ------------ HOMEPAGE SELECT BOX --------------------
    
    
    
    
    // ------------ DETAIL PAGE HTC WIDGET --------------------
    $('#htc-widget-imei-submit').click(function(){
        var $imei = $('#htc-widget-imei-input').val();
        if ($imei.length == 0) {
            return false;
        }
        
        document.body.style.cursor = 'wait';
        
        $.getJSON("/en/ajax/htc-widget-imei",{
            format: 'json',
            imei: $imei
        }, function($message){
            $('#htc-widget-message').html($message);
            document.body.style.cursor = 'default';
        });
        
        return false;
    });
    // ------------ DETAIL PAGE HTC WIDGET --------------------
    
});

$.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('---');
    }

};



$.fn.initVideoBox = function(youtubeCode, swfCode)
{
    
}


// -------------- 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 --------------------

var searchRoute = new GaBaseRoute('/$1/search/$2', '/$1/search?q=$2');
window.analytics.router.addRoute(searchRoute);

var homepagePlatformSelected = false;

window.analytics.callOnReady(function(){
    $('input#homepage-phone-find').click(function(){
        window.analytics.trackers.push(['_trackEvent', 'Pages', 'Find phone', 'Used']);
        sleep(100);
    });
    $('li.homepage-select-platform a').click(function(){
        if (! homepagePlatformSelected) {
            homepagePlatformSelected = true;
            window.analytics.trackers.push(['_trackEvent', 'Pages', 'Select phone', 'Platform selected']);
        }
    });
});

