//refresh banners every 30 seconds
var totalRef = -1;
var lastTime = new Date();
var BANNER_REFRESH_TIME = 31500;
var GA_CATEGORY_SEARCH = "Search";
var GA_CATEGORY_NAVIGATION = "Navigation";

var GA_EVENT_TOP_MOVIES = "TopMovies";
var GA_EVENT_TOP_SERIES = "TopSeries";
var GA_EVENT_FEED = "Feed";

var GA_NAVIGATION_HOME = "Home";
var GA_NAVIGATION_CONTACT = "Contact";
var GA_NAVIGATION_NEWS = "News";
var GA_NAVIGATION_SUGGEST_IDEA = "Suggest an idea";
var GA_NAVIGATION_FORUM = "Forum";
var GA_NAVIGATION_HELP = "Help";
var GA_NAVIGATION_KEY_CLOUD = "Keyword Cloud";
var GA_NAVIGATION_KEY_STATS = "Keyword Stats";
var GA_NAVIGATION_ENGINE_STATS = "Engine Stats";
var GA_NAVIGATION_USER_PROFILE = "User Profile";
var GA_NAVIGATION_USER_LOGIN = "User Login";
var GA_NAVIGATION_USER_LOGOUT = "User Logout";
var GA_NAVIGATION_USER_LOGIN_FB = "User Login Facebook";
var GA_NAVIGATION_USER_SIGNUP = "User Signup";

var GA_LABEL_KEYWORD_PREFIX = "KW";

var AUTOCOMPLETE_MIN_LENGTH = 3;

var QUANTSERVE_URL = 'http://edge.quantserve.com/quant.js';
var WIBIYA_TOOLBAR_URL = 'http://cdn.wibiya.com/Toolbars/dir_0690/Toolbar_690613/Loader_690613.js';

$(document).ready(function() {
    //resize maincol to fit into window
    hideBodyScroll();
    if ($('#maincol').height() > $(window).height() - $('#topmenu').height()) {
        $('#maincol').height($(window).height() - $('#topmenu').height());
    }
    setInterval("refreshCreative();", BANNER_REFRESH_TIME);
    $('.rounded').corner();
    $("#show_list .feed_day").each(function() {
        var h = $(this).find("ul").height();
        $(this).find(".date").height(h);
    });
    resizeEngineList('#e_ulist');
    resizeEngineList('#e_blist');

    //async loading bottom toolbar & quantserve script
    if (enable_widget == 1) {
        asyncLoad(WIBIYA_TOOLBAR_URL);
    }
    if (enable_suggestions == 1) {
        enableSearchSuggestions();

    }
    jQuery.ajax({
      dataType: 'script',
      url: QUANTSERVE_URL,
      success: function () {
        _qacct = "p-5fhUmGOptHfbU";
        quantserve();
      }
    });
    //load index banner
    if (last_search == '') {
	if (location.pathname != "/"){
	  $.post('/home/banner/index', '', function(response){
	      $('#banner-section').html(response);
	  });
	}
    }
    
    $("#collapse a, #collapse2 a").click(function() {
        collapseSidebar();
    });
    $('#collapse a, #collapse2 div a').mouseover(function(){
        if ($('#collapse').is(':visible')) {
            tooltip('#collapse', '#sidebar_tooltip', false);
        } else {
            tooltip('#arrow-resize', '#sidebar_tooltip', true,'show',-parseInt($('#arrow-resize').css('padding-top')));
        }
    });

    $('#collapse a, #collapse2 a').mouseout(function(){
        if ($('#collapse').is(':visible')) {
            tooltip('#collapse', '#sidebar_tooltip', false, 'hide');
        } else {
            tooltip('#collapse2', '#sidebar_tooltip', false, 'hide');
        }
    });

    $(window).resize(function() {
        if ($('#main-container').css('margin-left') == "22px") {
            collapseSidebar();
        }
        resizeIframe();
        $("#leftcol").css("min-height", $(window).height());
        //resize the banner section also
        $('#banner-section').width($(window).width() - 227);
        
        hideBodyScroll();
        resizeEngineList('#e_ulist');
        resizeEngineList('#e_blist');
    });
    resizeIframe();

    $('#search_form').submit(function(e) {
        if ($('input[name="data[query]"]').attr('value') != '') {
            if ($('input[name="data[query]"]').attr('value') != last_search) {
                $('input[name="data[new_search]"]').attr('value',Math.floor(Math.random()*10000001));
                last_search = $('input[name="data[query]"]').attr('value');
            }
            $.post('/engines/search', $(this).serializeArray(), function(response){
                $('#maincol').html(response);
                //for chrome & ie
                hideBodyScroll();
                resizeIframe();
                //resizeEngineList('#e_ulist');
                //resizeEngineList('#e_blist');
            });

            if (typeof(_gaq) != "undefined") {
                var engineTitle = $('#e_ulist li.engine.selected a').attr('title');
                if (engineTitle == undefined) {
                    engineTitle = 'SumoTorrent';
                }
                _gaq.push(['_trackEvent', GA_CATEGORY_SEARCH, engineTitle, last_search]);
                _gaq.push(['_trackEvent', GA_CATEGORY_SEARCH, GA_LABEL_KEYWORD_PREFIX + " " + last_search, engineTitle]);
            }

            return false;
        } else {
            $('#popup').show();
            return false;
        }
    });
    $('#top_movies a').click(function() {
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_EVENT_TOP_MOVIES, $(this).attr('title')]);
        }
    });

    $('#top_series a').click(function() {
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_EVENT_TOP_SERIES, $(this).attr('title')]);
        }
    });

    $('div.feed_day a').click(function() {
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_EVENT_FEED, $(this).attr('innerHTML')]);
        }
    });

    $('#logo a').click(function() {
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_HOME]);
        }
    });

    $('#tab_home').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_HOME]);
        }
    });

    $('#tab_contact').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_CONTACT]);
        }
    });

    $('#tab_news').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_NEWS]);
        }
    });

    $('#tab_idea_box').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_SUGGEST_IDEA]);
        }
    });

    $('#tab_forum').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_FORUM]);
        }
    });

    $('#tab_contact').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_CONTACT]);
        }
    });

    $('#tab_help').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_HELP]);
        }
    });

    $('#tab_keyword_cloud').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_KEY_CLOUD]);
        }
    });

    $('#tab_keyword_stats').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_KEY_STATS]);
        }
    });

    $('#tab_engine_stats').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_ENGINE_STATS]);
        }
    });

    $('#tab_account').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_LOGIN]);
        }
    });

    $('#tab_profile').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_PROFILE]);
        }
    });

    $('#tab_logout').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_LOGOUT]);
        }
    });

    $('#tab_login_fb').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_LOGIN_FB]);
        }
    });

    $('#tab_signup').find("a").click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_SIGNUP]);
        }
    });

    $('#profile_name').click(function(){
        if (typeof(_gaq) != "undefined") {
            _gaq.push(['_trackEvent', GA_CATEGORY_NAVIGATION, GA_NAVIGATION_USER_PROFILE]);
        }
    });

    $("#addToBookmarks").click(function() {
        $(this).hide();
        var _self = this;
        var query = $('input[name="data[query]"]').attr('value');
        if (query.length) {
            $.get('/users/addBookmark/' + query, function() {
                $(_self).show();
            });
        } else {
            $(_self).show();
        }
        return false;
    });

    //adding submenu functionality for stats menu
    $("ul.subnav").parent().append("<span></span>");
    $("#a_stats, #a_account, #a_help").mouseover(function() { //When trigger is clicked...
            //Following events are applied to the subnav itself (moving subnav up and down)
            $(this).parent().find("ul.submenu").slideDown('fast').show(); //Drop down the subnav on click

            $(this).parent().hover(function() {
            }, function(){
                    $(this).parent().find("ul.submenu").slideUp('fast'); //When the mouse hovers out of the subnav, move it back up
            });

            //Following events are applied to the trigger (Hover events for the trigger)
            }).hover(function() {
                    $(this).addClass("subhover"); //On hover over, add class "subhover"
            }, function(){	//On Hover Out
                    $(this).removeClass("subhover"); //On hover out, remove class "subhover"
    });
    FacebookHandler.initScripts(function () {
        jQuery("#tab_login_fb").live('click', function () {
            var fb = FacebookHandler.getInstance();

            fb.askForLogin(function (data) {
                // the user is logged on facebook, do el magic
                if (typeof(data.session) != "undefined") {
                    if (typeof(data.session.uid) != "undefined") {
                        var extId = parseInt(data.session.uid);

                        var postData = {
                            'external_id' : extId,
                            'external_login' : 1,
                            'external_handler' : 1
                        }
                        jQuery.ajax({
                            url: "/users/fbLogin",
                            data: postData,
                            type: "POST",
                            dataType: "json",
                            complete: function (ret) {
                                // check answer -> act properly!
                                if (ret != null && typeof(ret) != "undefined") {
                                    var result = jQuery.parseJSON(ret.responseText);
                                    if (typeof(result.isLogged) != "undefined") {
                                        if (result.isLogged == 1) {
                                            window.location = '/users/profile';
                                        }
                                        else {
                                            // display the login failed message
                                            console.log(result.isLogged);
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            });

            return false;
        });
    });

    $('#fb_info div').hover(function() {
        $(this).addClass('ui-state-highlight');
        }, function() {
            $(this).removeClass('ui-state-highlight');
        });
    $('#bookmark_star, #bookmark_star_collapsed').click(function(){
        idsString = '#bookmark_star, #bookmark_star_collapsed';
        if ($("#main-container").css("margin-left") == '22px') {
            collapseSidebar();
        }
        if ($(this).hasClass('bookmark-button')) {
            $(idsString).removeClass('bookmark-button');
            $(idsString).addClass('bookmark-button-click');
            ajaxLoader('#engine_list','load','custom-loader');
            $.post('/users/getAllBookmarks', '', function(response){
                $('#engine_list').html(response);
                resizeEngineList('#e_blist');
            });

        } else {
            $(idsString).removeClass('bookmark-button-click');
            $(idsString).addClass('bookmark-button');
            ajaxLoader('#engine_list','load','custom-loader');
            $.post('/engines/getAllEngines', '', function(response){
                $('#engine_list').html(response);
                resizeEngineList('#e_ulist');
            });

        }
    });
    $('#bookmark_star').mouseover(function(){
        tooltip('#bookmark_star', '#bookmark_tooltip', true);
    });
    $('#bookmark_star').mouseout(function(){
        tooltip('#bookmark_star', '#bookmark_tooltip', true, 'hide');
    });
    $('#bookmark_star_collapsed').mouseover(function(){
        tooltip('#bookmark_star_collapsed', '#bookmark_tooltip', true);
    });
    $('#bookmark_star_collapsed').mouseout(function(){
        tooltip('#bookmark_star_collapsed', '#bookmark_tooltip', true, 'hide');
    });
    $(function() {
            $('#e_ulist').sortable({
                containment: '#engine_list',
                opacity: 0.75,
                distance: 0.25,
                axis: 'y',
                stop: function(event, ui) {
                    reorderEngineList('#e_ulist');
                }
            });
    });

});

function reorderEngineList(target) {
    //save cookie for non-registered users, save in db for registered ones
    if (logged == '1') {
        var list = new Array();
        $(target+" li").each(function(){
            engine_id = $(this).attr('id').split('_');
            list.push(engine_id[1]);
        });
        var engineIds = {
            'ids': list.join(',')
        }
        jQuery.ajax({
            url: "/users/orderEngines",
            data: engineIds,
            type: "POST",
            dataType: "json",
            complete: function (ret) {
                if (ret != null && typeof(ret) != "undefined") {
                    var result = jQuery.parseJSON(ret.responseText);
                    if (result.status == "saved") {
                        $(loader).html('&nbsp;');
                        $(target).sortable("option", "disabled", false);
                        $('#nav_'+element).show();
                        ajaxLoader('#engine_list','load','custom-loader');
                        $.post('/engines/getAllEngines', '', function(response){
                            $('#engine_list').html(response);
                            resizeEngineList('#e_ulist');
                        });
                    }
                }
            }
        });
        ajaxLoader(loader,'save');
    } else {
        list = new Array();
        $(target+" li").each(function(){
            engine_id = $(this).attr('id').split('_');
            list.push(engine_id[1]);
        });
        engineIds = {
            'ids': list.join('-')
        }
        setCookie('tporder', engineIds.ids, 150);
    }
}

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function getMinDiff(datetwo) {
    //format = “Days”, Hours, Minutes, Seconds
    var seconds = (new Date()).getTime() - datetwo.getTime();
    var second = 1000, minute = 10 * second, hour = 60 * minute, day = 24 * hour;
    rformat = Math.round(seconds / minute);
    return rformat;
}

//refresh banners every 30 seconds
function refreshCreative() {
    if (getMinDiff(lastTime) < 1) {
        return false;
    }
    lastTime = new Date();

    totalRef += 1;
    if (totalRef >= 140)
        return false;
    if ($('#banner_top').length) $('#banner_top').load('/home/banner/index #banner_top');
    if ($('#banner_index_footer_first').length) $('#banner_index_footer_first').load('/home/banner/index_footer_first #banner_index_footer_first');
    if ($('#banner_index_footer_second').length) $('#banner_index_footer_second').load('/home/banner/index_footer_second #banner_index_footer_second');
    if ($('#banner_top_first').length) $('#banner_top_first').load('/home/banner/top_first #banner_top_first');
    if ($('#banner_top_second').length) $('#banner_top_second').load('/home/banner/top_second #banner_top_second');

    return false;
}

function switch_engine(id, noSubmit) {
    if ($('input[name="data[query]"]').attr("value")) {
        $("#popup").hide();
        $('.engine').removeClass('selected');
        $('#engine_' + id).addClass('selected');
        $('input[name="data[engine_id]"]').attr("value", id);
        if (!noSubmit && $('input[name="data[query]"]').attr("value")) {
            $('#search_form').submit();
        }
    } else {
        $("#popup").show();
    }
}

// removes scrollbars of the body, adds scrollbar to the main content, to the engine list,removes overflow of content if in search mode
function hideBodyScroll() {
    maincolSpace = 15;
//    $('body').css("overflow-y","hidden");
//    $('body').css("overflow-x","hidden");

    $('#maincol').height($(window).height() - $('#topmenu').height());
    if (last_search != '') {
        $('#maincol').css("overflow-y","hidden");
    }
    $('#maincol').css("overflow-x","hidden");
    //ie
    //$('#maincol').width($(window).width() - maincolSpace - $('#leftcol').width());
//    $('#shadow-container').height($('#maincol').height());
//    $("#leftcol").css("min-height", ($(window).height() - $('#logo').height()-100));
    
}

//resize engine iframe depending on window size
function resizeIframe() {
    //next step is to retrieve element spaces with jquery
    topmenuSpace = 20;
    usenetSpace = 65;
    bannerSpace = 10;
    bottomMargin = 10;
    rightColSpace = 40;
    shadowSpace = -25;
    //make the banner section appear fixed in position
    if ($("#torrent_window").length) {
        $('#banner-section').css('padding-left', '');
        $('#usenet-container').css('margin-left', '0px');
        $("#leftcol").css("height",'auto');

        $("#torrent_window").width($(window).width() - $("#leftcol").width() + shadowSpace);
        if ($('#rightcol').length) {
            $("#torrent_window").width($("#torrent_window").width() - $("#rightcol").width() - rightColSpace);
        }
        elementHeights = $("#topmenu").height()  + topmenuSpace + bottomMargin;
        if ($("#banner-section").length) {
            elementHeights += $("#banner-section").height() + bannerSpace;
        }
        if ($("#usenet-container").length) {
            elementHeights += $("#usenet-container").height() + usenetSpace;
        }
        $("#torrent_window").height($(window).height() - elementHeights);
    }
}
//resize list of engines container
function resizeEngineList(list) {
    if ($(list).length) {
        $(list).css("overflow-y", 'auto');
        $(list).css("overflow-x", 'hidden');
        $(list).height($(window).height() - $("#search_box").height()-140);
    }
}

//mark with css the menu tab when clicked
function activateTab(name, exception) {
    $('#topmenu li').removeClass('active');
    if (name != undefined) {
        $('#'+name).addClass('active');
    }
    if (exception != undefined) {
        $('#'+exception).addClass('active');
    }
}
//asynchronous loading of a script
function asyncLoad(url) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = url;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
}

function showProfileTab(name) {
    $('div.tab_content').hide();
    $('#subtab_'+name).show();
    $('span.round-menu').removeClass('round-menu-active');
    $('#menu_'+name).addClass('round-menu-active');
}

function ajaxLoader(element, action, loaderClass) {
    var text;
    if (action == undefined) {
        action = 'load';
    }
    if (loaderClass == undefined) {
        loaderClass = "loader";
    }
    switch (action) {
        case "load":
            text = "Loading...";
            break;
        case "save":
            text = "Saving...";
            break;
        case "none":
            text = "";
            break;

    }
    $(element).html('<div class="'+loaderClass+'"><img src="/img/ajax-loader.gif" alt="loader" align="bottom" /> ' + text + '</div>');
}

function searchBookmark(element, value, engine_id) {
    $('li.bookmark').removeClass('chosen');
    $(element).addClass('chosen');
    $('#search_form input[name="data[query]"]').attr("value", value);
    $('#search_form input[name="data[engine_id]"]').attr("value", engine_id);
    $('#search_form').submit();
}

function collapseSidebar() {
    shadowSpace = 15;
    collapserSpace = 15;
    paddings = 22;
    elementsWidth = shadowSpace + collapserSpace + paddings;
    sidebarSpace = $('#sidebar').width() + shadowSpace;
    if ($('#main-container').css('margin-left') == "227px") {
        $('#sidebar').hide();
        $('#collapse2').show();

        $('#banner-section').css('padding-left', '205px');
        $('#main-container').css('margin-left', '22px');
        //in search page
        if ($("#torrent_window").length) {
            $("#torrent_window").width($("#torrent_window").width() + sidebarSpace - elementsWidth);
            $("#usenet-container").width($("#usenet-container").width() + sidebarSpace - elementsWidth);
        }
    } else {
        //in search page
        if ($("#torrent_window").length) {
            $("#torrent_window").width($("#torrent_window").width() - sidebarSpace + elementsWidth);
            $("#usenet-container").width($("#usenet-container").width() - sidebarSpace + elementsWidth);
        }
        $('#banner-section').css('padding-left', '');
        $('#main-container').css('margin-left', '227px');
        $('#collapse2').hide();
        $('#sidebar').show();
    }
}

function tooltip(target, element, changePosition, action, deviation) {
    if (deviation == undefined) {
        deviation = 10;
    } else {
        deviation = 10 + deviation;
    }
    if (changePosition == undefined) changePosition = false;
    var position = $(target).offset();
    var topPos = 0;
    if (changePosition == true) {
        topPos = position.top - deviation;
    } else {
        topPos = position.top;
    }
//tooltip = $('<div></div>');
    $(element).css('top',  topPos + 'px').css('left', (position.left + $(target).width()) + 'px');
    if (action != undefined) {
        if (action == 'hide') {
            $(element).hide();
        } else {
            $(element).show();
        }
    } else {
        $(element).show();
    }
}

function highlightDelete(element) {
    $("#"+$(element).attr('id')+"_close").show();
    $(element).addClass('highlight');
}
function hideDelete(element) {
    $("#"+$(element).attr('id')+"_close").hide();
    $(element).removeClass('highlight');
}
function overDelete(element) {
    $(element).removeClass('engine-button-close-over');
    $(element).addClass('engine-button-close-clicked');
}
function outDelete(element) {
    $(element).removeClass('engine-button-close-clicked');
    $(element).addClass('engine-button-close-over');
}
function enableSearchSuggestions() {
    var ac = $("input.autocomplete").autocomplete({
        source: '/keyword/suggest/',
        autoFill: true,
        highlight: true,
        zIndex: 1002,
        minLength: AUTOCOMPLETE_MIN_LENGTH
    });
    //ac.setOptions({zIndex: 1002, minLength: AUTOCOMPLETE_MIN_LENGTH});
//    ac.autocomplete("option", "minLength", AUTOCOMPLETE_MIN_LENGTH);
    
    ac.keyup(function(event) {
      if (event.which == '13') {
          
          //console.log($(this));
          //hide autocomplete
          $('ul.ui-autocomplete').hide();
          $(this).blur();
          $(this).autocomplete("disable");
          $(this).autocomplete("enable");

      }
    });    
}
