var FZ = {
    boxCachTimes : {},
    cachedNews : {},
    cachesExpires : {},
    datePickerConfig : {
        showOn: 'button',
        buttonImage: '/images/themes/default/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        dayNamesMin: ['Н','П','В','С','Ч','П','С'],
        monthNamesShort: ['Яну','Фев','Мар','Апр','Май','Юни','Юли','Авг','Сеп','Окт','Ное','Дек'],
        yearRange: '1900:2000'
    },
    onReady : function(){
        $('ul#orbs').imgbubbles({factor:1.75}) //add bubbles effect to UL id="orbs"
        $('ul#squares').imgbubbles({factor:2.5}) //add bubbles effect to UL id="squares"
        $('#header').find('.login').find('a').hover(FZ.userMenuMouseOver, FZ.userMenuMouseOut);
        $('#side-top-news').find('.pagination').find('a.str').bind('click', {url:"/index/getNews/type/top/"}, FZ.getNews);
        $('#side-last-news').find('.pagination').find('a.str').bind('click', {url:"/index/getNews/type/last/"}, FZ.getNews);
        $('#side-most-commented-news').find('.pagination').find('a.str').bind('click', {url:"/index/getNews/type/most_commented/"}, FZ.getNews);
        $('.tab').find('a').live('click', FZ.tabChange);
        $('#side-forum').find('.pagination').find('a.str').bind('click', FZ.getTopics);
        $('#categories').find('a').hover(FZ.catsMouseOver, FZ.catsMouseOut);
        $('.menu .row1').find('a.nav').bind('mouseover', FZ.navMenuMouseOver);
        $(".moreGroups").bind('click', FZ.displayMoreGroups);
        $("#preview").bind('click', FZ.previewVideo);
        $("#datepicker").datepicker(FZ.datePickerConfig);
        //register and recover password forms
        $("#registerForm .form input, #recoverForm .form input").focus(FZ.Forms.showFormHints);
        $("#registerForm .form input, #recoverForm .form input").blur(FZ.Forms.hideFormHints);
        $(".registerFormLink, .registerFormLink2").click(FZ.Forms.openRegisterForm);
        $("#registration_close").click(FZ.Forms.closeRegisterForm);
        $("#recoverFormLink").click(FZ.Forms.openRecoverForm);
        $("#recover_close").click(FZ.Forms.closeRecoverForm);

        // user options
        // method to fill the teams combobox with correct values
        $("#chooseChamp").change(FZ.chooseChampionship);
        
        // login
        $("#topbar_username").focus(FZ.hideLoginHint);
        $("#topbar_username").blur(FZ.showLoginHint);



        //
        // method to check the remember me checkbox from the link
        $("#rememberMeLink").click(function(event){
            if($("#rememberMeCheckbox").attr("checked") == true){
                $("#rememberMeCheckbox").removeAttr("checked");
            }else{
                $("#rememberMeCheckbox").attr("checked", "checked");
            }
            return false;
        });

        $("#rememberMeCheckbox").click(function(event){
            event.stopPropagation();
        });
        
    },
    catsMouseOver : function(){
        var txt = $(this).find('img').attr('alt'),
            container = $('#categories'),
            containerWidth = container.width(),
            containerOffset = container.offset(),
            linkOffset = $(this).offset(),
            hintLeft = 0,
            element = $('<span></span>')
                .attr({id: 'cats-menu-hint'})
                .text(txt)
                .appendTo('body');

        hintLeft = linkOffset.left - element.width()/2 + 20;
        if(hintLeft < containerOffset.left){
            hintLeft = containerOffset.left;
        }else if(hintLeft + element.width() > (containerOffset.left + containerWidth)){
            hintLeft = containerOffset.left + containerWidth - element.width();
        }

        element.css({
            'position': 'absolute',
            'text-align': 'center',
            'z-index': 1,
            'left': hintLeft+'px',
            'top': (linkOffset.top + 20)+'px',
            'cursor': 'pointer'
        });
    },
    catsMouseOut : function(){
        $('#cats-menu-hint').remove();
    },
    userMenuMouseOver : function(){
        var txt = $(this).find('img').attr('alt'),
            offset = $(this).offset(),
            element = $('<span></span>')
                .attr({id: 'login-menu-hint'})
                .text(txt)
                .appendTo('body');

        element.css({
            'position': 'absolute',
            'text-align': 'center',
            'z-index': 1,
            'left': (offset.left - element.width()/2 + 20)+'px',
            'top': (offset.top + 42)+'px',
            'cursor': 'pointer'
        });
    },
    userMenuMouseOut : function(){
        $('#login-menu-hint').remove();
    },
    navMenuMouseOver : function(){
        var id = $(this).attr('id');
        id = id.replace('-trigger-', '-submenu-');
        if($('#' + id).length > 0){
            $('#' + id).addClass('active').siblings('.active').removeClass('active');
        }
    },
    getNews : function(e){
        var container = $(this).parent().parent().prev('.newstitle'),
            loadNewInfo = true;
        if($(this).hasClass('arrow')){
            var lastSelected = $(this).prevAll('.stractive');
            if(!lastSelected.next('.str').hasClass('arrow')){
                var page = parseInt(lastSelected.text()) + 1;
                lastSelected.removeClass('stractive').next('.str').addClass('stractive');
            }else{
                loadNewInfo = false;
            }
        }else{
            var page = parseInt($(this).text());
            $(this).addClass('stractive').siblings('.stractive').removeClass('stractive');
        }

        if(loadNewInfo){
            var url = e.data.url + 'p/' + page + '/';
            container.height(container.height()).children().fadeOut('fast');
            container.css('position', 'relative').append('<img class="spinner" src="/images/blog/ajax-loader.gif"/>');
            $.get(url, {},
            function(result){
                var html = '';
                for(var index in result){
                    html += '<div><img src="/images/blog/SidebarNewsTitleArrow.png" alt=""><a href="' + result[index].url + '">' + result[index].title + '</a></div>';
                }
                container.css('height', 'auto').html(html).fadeIn('fast');
                container.css('position', '').find('.spinner').remove();
            }
            , 'json');
        }
        return false;
    },
    getTopics : function(type, fromTab){
        fromTab == true ? true : false;
        var loadNewInfo = true;

        if(fromTab){
            var container = $('#' + type).parent().siblings('.forum');
            var pagination = $('#' + type).parent().nextAll('.pagination');
            pagination.find('a.str.stractive').removeClass('stractive');
            pagination.find('a.str:first').addClass('stractive');
            var page = 1;
        }else{
            var root = $(this).parent().parent();
            var type = root.prevAll('.tab').find('span').parent().attr('id');
            var container = root.prev('.forum');

            if($(this).hasClass('arrow')){
                var lastSelected = $(this).prevAll('.stractive');
                if(!lastSelected.next('.str').hasClass('arrow')){
                    var page = parseInt(lastSelected.text()) + 1;
                    lastSelected.removeClass('stractive').next('.str').addClass('stractive');
                }else{
                    loadNewInfo = false;
                }
            }else{
                var page = parseInt($(this).text());
                $(this).addClass('stractive').siblings('.stractive').removeClass('stractive');
            }
        }
        type = type.replace('side-forum-tab-', '');

        var url = '/forum/json_getTopics/type/' + type + '/p/' + page + '/';
        container.height(container.height()).children().fadeOut('fast');
        container.css('position', 'relative').append('<img class="spinner" src="/images/blog/ajax-loader.gif" />');
        if(loadNewInfo){
            $.get(url, {},
                function(result){
                    var html = '';
                    for(var index in result){
                        html += '<div><img src="/images/blog/SidebarNewsTitleArrow.png" alt=""><a href="' + result[index].url + '">' + result[index].title + '</a><span>от ' + result[index].author + ' ' + result[index].time + '</span></div>';
                    }
                    container.css('height', 'auto').html(html).fadeIn('fast');
                }
            , 'json');
        }
        return false;
    },
    getBgplayData : function(type){
        var container = $('#' + type).parent().siblings('.bgplay');
        type = type.replace('side-bgplay-tab-', '');
        var url = '/home/ajax_getIndexData/t/' + type + '/';
        container.height(container.height()).children().fadeOut('fast');
        container.css('position', 'relative').append('<img class="spinner" src="/images/blog/ajax-loader.gif" />');
        $.get(url, {},
            function(result){
                var html = '', classname;
                if(type == 'table'){
                    html += '<table cellspacing="0" cellpadding="2">';
                    html += '<tr>'
                    html += '<th colspan="8"><b>Kласиране след <span id="bgplay-round">' + result[0].matches + '</span>-и кръг</b></th>';
                    html += '</tr>';
                    html += '<tr class="heading">';
                    html += '<th>&nbsp;</th>';
                    html += '<th>Отбор</th>';
                    html += '<th title="Мачове">М</th>';
                    html += '<th title="Победи">П</th>';
                    html += '<th title="Равенства">Р</th>';
                    html += '<th title="Загуби">З</th>';
                    html += '<th title="Голова разлика">Г.р.</th>';
                    html += '<th>Точки</th>';
                    html += '</tr>';
                    for(var index in result){
                        classname = index % 2 == 0 ? ' class="grey"' : '';
                        html += '<tr' + classname + '>';
                        html += '<td>' + (parseInt(index) + 1) + '.</td>';
                        html += '<td style="text-align: left;">' + result[index].team_name + '</td>';
                        html += '<td>' + result[index].matches + '</td>';
                        html += '<td>' + result[index].win + '</td>';
                        html += '<td>' + result[index].draw + '</td>';
                        html += '<td>' + result[index].lost + '</td>';
                        html += '<td>' + result[index].goals_for + '-' + result[index].goals_against + '</td>';
                        html += '<td>' + result[index].points + '</td>';
                        html += '</tr>';
                    }
                }else if(type == 'matches'){
                    //console.log(result);
                    html += '<table class="last-matches">';
                    for(var index in result){
                        html += '<tr>';
                        html += '<td style="text-align: right;">' + result[index].home_name + '</td>';
                        html += '<td style="padding: 0 5px 0 5px"><a href="/home/bpl_match/id/' + result[index].match_id + '/">';
                        html += result[index].home_score + ' - ' + result[index].away_score + '</a></td>';
                        html += '<td style="text-align: left;">' + result[index].away_name + '</td>';
                        html += '</tr>';
                    }
                    html += '</table>';
                }
                container.css('height', 'auto').html(html).fadeIn('fast');
            }
        , 'json');
        return false;
    },
    tabChange : function(e){
        var self = $(this);
        var parentId = self.parent().attr('id');
        var otherTab = self.parent().siblings().find('span');
        var txt = self.text();
        self.parent().html('<span>' + txt + '</span>');

        txt = otherTab.text();
        otherTab.parent().html('<a href="#">' + txt + '</a>');

        if(parentId == 'side-forum-tab-recent' || parentId == 'side-forum-tab-last'){
            FZ.getTopics(parentId, true);
        }else if(parentId == 'side-bgplay-tab-table' || parentId == 'side-bgplay-tab-matches'){
            FZ.getBgplayData(parentId);
        }
        return false;
    },
    displayMoreGroups : function(){
        $("#window").remove();
        var offsetInfo = $(this).offset();
        var windowBox = $('<div id="window"><div class="heading"><a href="#">[X]</a></div><div class="content"><img src="/img/spinner.gif" /></div></div>');

        var top = 0;
        //var left = offsetInfo.left;
        var h = $(window).height();
        //var w = $(window).width();

        top = offsetInfo.top + 180 > h ? h - 180 + $(window).scrollTop() : offsetInfo.top;

        windowBox.css({"position": "absolute",
                        "left": (offsetInfo.left - 250)+"px",
                        "top": (top)+"px"});
        $("body").append(windowBox);

        $.ajax({
            url: $(this).attr('href'),
            cache: true,
            success: function(html){
                $("#window .content").html(html);

                $("#window .heading a").click(function(){
                    $("#window").remove();
                    return false;
                });
            }
        });
        return false;
    },
    previewVideo : function(){
        var url = $("#video_url").val();
        url = url.replace(/\//g, '');
        $.ajax({
            url: "http://sportbg.localhost/index/ajax_media/video/"+url,
            cache: false,
            success: function(html){
                $("#preview_area").html(html);
            }
        });
        return false;
    },
    showLoginHint : function(){
        if($(this).val() == ""){
            $(this).val("Потр. име");
        }
    },
    hideLoginHint : function(){
        if($(this).val() == "Потр. име"){
            $(this).val("");
        }
    },
    chooseChampionship : function(){
        var champId = $(this).val();
        $.ajax({
            url: "/index/ajax_teams/champId/"+champId,
            cache: true,
            success: function(html){
                $("#team").html('<option value="0" style="font-weight: bold;">Нямам</option>');
                $("#team").append(html);
            }
        });
    },
    Forms : {
        showFormHints : function(){
            $(this).nextAll(".alt").show();
            $(this).nextAll(".error").hide();
        },
        hideFormHints : function(){
            $(this).nextAll(".alt").hide();
        },
        openRegisterForm : function(){
            $("#registerForm").show();
            return false;
        },
        closeRegisterForm : function(){
            $("#registerForm").hide();
            return false;
        },
        openRecoverForm : function(){
            $("#recoverForm").show();
            return false;
        },
        closeRecoverForm : function(){
            $("#recoverForm").hide();
            return false;
        }
    }
}

$(function(){FZ.onReady();});

$(document).ready(function(){

// user media
// methods to switch between video and photo upload forms
if($("#media_video").length > 0){
    if($("#media_video").attr("checked") == true){
        $("#media_video_container").show();
        $("#media_photo_container").hide();
    }
}

if($("#media_photo").length > 0){
    $("#media_photo").click(function(){
        if($(this).attr("checked") == true){
            $("#media_photo_container").show();
            $("#media_video_container").hide();
        }
    });
}

if($("#media_video").length > 0){
    $("#media_video").click(function(){
        if($(this).attr("checked") == true){
            $("#media_video_container").show();
            $("#media_photo_container").hide();
        }
    });
}

// checkboxes
// methods to check, uncheck and reverse checkboxes
if($(".checkbox_control .checkboxes_checkall").length > 0){
    $(".checkbox_control .checkboxes_checkall").click(function(){
        $(this).parents(".checkbox_control").nextAll(".checkbox_container").find(".controlled_checkbox").attr("checked", "checked");
        return false;
    });
}

if($(".checkbox_control .checkboxes_uncheckall").length > 0){
    $(".checkbox_control .checkboxes_uncheckall").click(function(){
        $(this).parents(".checkbox_control").nextAll(".checkbox_container").find(".controlled_checkbox").removeAttr("checked");
        return false;
    });
}

if($(".checkbox_control .checkboxes_reverse").length > 0){
    $(".checkbox_control .checkboxes_reverse").click(function(){
        var container = $(this).parents(".checkbox_control").nextAll(".checkbox_container");
        container.find(".controlled_checkbox:checked").addClass("temp").removeAttr("checked");
        container.find(".controlled_checkbox:not(.temp)").attr("checked", "checked");
        container.find(".controlled_checkbox.temp").removeClass("temp");
        return false;
    });
}

// window
// visual feedback
var loginFeedback = $("#jsFeedback").text();
if(loginFeedback != ''){
    customAlert(loginFeedback);
    if($("#transfers").length > 0){
        var championshipId = $("#ch").val();
        if(championshipId == undefined || parseInt(championshipId) == 0){
            championshipId = 1;
        }else{
            championshipId = parseInt(championshipId);
        }

        var href = window.location.toString();
        var addToUrl = '';
        if(href.indexOf('offer/all') > 0){
            addToUrl = 'offer/all/';
        }else if(href.indexOf('offer/open') > 0){
            addToUrl = 'offer/open/';
        }
        window.location = "/index/transfers/ch/"+championshipId+"/"+addToUrl;
    }
}

//login form
//user friendly interface
if($("#topbar_username").length > 0){

}

// media
// hints for user publications and media uploads
function createHint(text, target){
    var hint = $("<div id='hint'></div>");
    hint.html(text);
    hint.css({"position": "absolute",
        "left": (target.offsetLeft + 20)+"px",
        "top": (target.offsetTop + 20)+"px",
        "width": "420px",
        "border": "2px solid #115e16",
        "padding": "10px",
        //"background-color": "#cfeecf",
        "background-image": "url('/images/themes/default/hbg.gif')",
        "background-repeat": "repeat",
        "color":"#002200"
    });
    $("body").append(hint);
}

if($("#show_hint_video").length > 0){
    $("#show_hint_video").mouseover(function(event){
        var hintText = $("#hint_video").html();
        createHint(hintText, event.target);
    });
    $("#show_hint_video").mouseout(function(event){
        $("#hint").remove();
    });
    $("#show_hint_video").click(function(event){
        return false;
    });
}

if($("#show_hint_photo").length > 0){
    $("#show_hint_photo").mouseover(function(event){
        var hintText = $("#hint_photo").html();
        createHint(hintText, event.target);
    });
    $("#show_hint_photo").mouseout(function(event){
        $("#hint").remove();
    });
    $("#show_hint_photo").click(function(event){
        return false;
    });
}

if($("#show_hint_source").length > 0){
    $("#show_hint_source").mouseover(function(event){
        var hintText = $("#hint_source").html();
        createHint(hintText, event.target);
    });
    $("#show_hint_source").mouseout(function(event){
        $("#hint").remove();
    });
    $("#show_hint_source").click(function(event){
        return false;
    });
}



});

