var smile_win = 0;

function invert_action_icon(is_on, target) { 
    $('#add_'+target+'_icon').css('display', is_on ? 'none' : 'inline'); 
    $('#del_'+target+'_icon').css('display', is_on ? 'inline' : 'none'); 
    
    $('div.add_'+target+'_icon').css('display', is_on ? 'none' : 'block'); 
    $('div.del_'+target+'_icon').css('display', is_on ? 'block' : 'none'); 
}

var fmenu_popup_delay = 1000; // delay in milliseconds after which popup menu will start loading
var colorbox_settings = {opacity: 0.6};

$(document).ready(function() { 

    //////// blocks ON/OFF initialization ///////
    $('a.switch_on').click(function() {
        var this_ptr = $(this);

        this_ptr.css('display', 'none');
        this_ptr.next().css('display', 'block');

        this_ptr.parent().parent().parent().removeClass('area_closed');
        this_ptr.parent().parent().parent().addClass('area_open area_open_special');
        this_ptr.parent().parent().next().slideDown('normal');

        // save in cookies if needed
        var block_id = this_ptr.attr('rel');
        if(block_id != '') 
            update_hidden_block_stage('hidden_blocks', true, block_id);
    });

    $('a.switch_off').click(function() {
        var this_ptr = $(this);

        this_ptr.css('display', 'none');
        this_ptr.prev().css('display', 'block');

        this_ptr.parent().parent().next().slideUp('normal', function() {
            this_ptr.parent().parent().parent().removeClass('area_open area_open_special');
            this_ptr.parent().parent().parent().addClass('area_closed');
        });

        // save in cookies if needed
        var block_id = this_ptr.attr('rel');
        if(block_id != '') 
            update_hidden_block_stage('hidden_blocks', false, block_id);
    });
    /////////////////////////////////////////////

    $('img.m_over').mouseover(function() {
        var prev = $(this).attr('src');
        $(this).attr('src', $(this).attr('rel'));
        $(this).attr('rel', prev);
    }).mouseout(function() {
        var prev = $(this).attr('src');
        $(this).attr('src', $(this).attr('rel'));
        $(this).attr('rel', prev);
    });

    // init ajax_load links
    init_filtering_links();
    
    // popup menu initialization
    $('#loading').clone().attr('id', 'fmenu_loading').appendTo('body');
    $('body').append('<div id="popup_menu_div" style="display:none"></div>');
    init_popup_menu(fmenu_popup_delay);

    // left menu initialization
    $('div.lmenu_header a').click(function() {
        var block = $(this).attr('rel');

        // parse block Id
        var rexp = new RegExp('lmenu_block_(\\d+)', "img");
        var found = rexp.exec(block);
        var block_id = found[1];
        /////////

        var cur_visible = !$('#'+block).is(':visible');
        update_hidden_block_stage('hidden_lmenu_blocks', cur_visible, block_id);
        
        // show/hide
        $('#'+block).toggle('fast');
        $(this).parent().toggleClass('lmenu_header_off');
    });

    // smart select initialization
    if(typeof($.fn.smart_select) == 'function')
        $('select.smart_select').smart_select();

    // init help tips
    if(typeof($.fn.tooltip) == 'function')
        $(".helptip").tooltip({ 
            position: "top right", 
            opacity: 1,
            relative: true,
            offset: [10, 5] 
        });

    // disable right-click for protected images !!! doesn't work in Opera
    $('img.protected').
        bind('contextmenu', function() { return false; }).
        bind('mouseup mousedown click', function(e) {
            if(e.button == 2 || e.button == 3) return false;
        });

    // init colorbox
    if(typeof($.fn.colorbox) == 'function')
        $("a.colorbox").colorbox(colorbox_settings);

    // popups
    $('a.close_popup').live('click', function() {
        tb_remove();
        return false;
    });
});

function init_filtering_links() {
    
    var container = (arguments.length >= 1) ? '#' + arguments[0] + ' ' : '';

    $('#loading').css('display', 'none');
    
    $(container + 'a.ajax_load').click(function(event) {
        
        var confirm_text = $(this).attr('rev');
        if(confirm_text != null && confirm_text != '' && !confirm(confirm_text)) 
            return false;

        $('#loading').css('top', event.pageY+15).css('left', event.pageX).css('display', 'block');

        var cd = new Date();
        var cont = $(this).attr('rel');
        var $href = $(this).attr('href');
        var more_onload = $(this).attr('more');

        $('#'+cont).load(
            $href + ($href.indexOf("no_header")!=-1?'':($href.indexOf('?')!=-1?'&':'?')+'no_header=1')+'&tms='+cd.getHours()+''+cd.getMinutes()+''+cd.getSeconds()+''+Math.random(), 
            null, function() { 
                init_popup_menu(fmenu_popup_delay, cont); 
                init_filtering_links(cont);   
                if(tb_init != 'undefined') tb_init('#' + cont + ' a.thickbox');
                
                if(typeof($.fn.colorbox) == 'function')
                    $('#' + cont + ' a.colorbox').colorbox(colorbox_settings);

                if(more_onload != null) eval(more_onload+'(\''+cont+'\')');
            }
        );
    });
    
    $(container + 'select.ajax_load').change(function(event) {
        
        var confirm_text = $(this).attr('rev');
        if(confirm_text != null && confirm_text != '' && !confirm(confirm_text)) 
            return false;

        var posX = findPosX(this);
        var posY = findPosY(this);

        $('#loading').css('top', posY+22).css('left', posX+30).css('display', 'block');

        var cd = new Date();
        var cont = $(this).attr('rel');
        var $href = $(this).val();

        $('#'+cont).load(
            $href + ($href.indexOf("no_header")!=-1?'':($href.indexOf('?')!=-1?'&':'?')+'no_header=1')+'&tms='+cd.getHours()+''+cd.getMinutes()+''+cd.getSeconds()+''+Math.random(), 
            null, function() { 
                init_popup_menu(fmenu_popup_delay, cont); 
                init_filtering_links(cont);   
                if(tb_init != 'undefined') tb_init('#' + cont + ' a.thickbox');
                
                if(typeof($.fn.colorbox) == 'function')
                    $('#' + cont + ' a.colorbox').colorbox(colorbox_settings);
            }
        );
    });
}

/***************************************************/
/********* Popup Menu ******************************/
/***************************************************/

var popup_menu_info = new Array(); // array of data for popup menus (ID -> target member Id)
var cur_popup_menu_id = 0; // popup menu ID which is currently being generated
var last_popup_menu_activity = timestamp(); // timestamp of last popup menu activity

setInterval("hide_not_active_popup()", 3000);

// should be executed only once per page loading (and for each AJAX part loading)
function init_popup_menu(delay) {
    
    var container = (arguments.length >= 2) ? '#' + arguments[1] + ' ' : '';
    /*popup_menu_info = new Array();  $('#popup_menu_div').empty();*/

    $(container + 'a.fmenu').mouseenter(function(event) {

        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        var Id = $(this).attr('rel');

        var x = event.pageX; // findPosX(this) + parseInt($(this).width()/2) + 'px';
        var y = event.pageY; // findPosY(this) + parseInt($(this).height()/2) + 'px';

        $('#popup_menu_div').css('left', x).css('top', y);
        $('#fmenu_loading').css('top', y).css('left', x);
        
        //debug("Mouse over object with ID :" + Id);

        if((popup_menu_info[Id] != null) && (Id == cur_popup_menu_id) && 
           ($('#fmenu_cont_'+Id).length || popup_menu_info[Id].showTimer)) {
            
            popup_menu_info[Id].OnObj = true;
            popup_menu_info[Id].OnMenu = popup_menu_info[Id].OnSubMenu = popup_menu_info[Id].OnProgress = false;

            if($('#fmenu_cont_'+Id).is(':hidden'))
                $('#popup_menu_div').css('display', 'block');

            //debug("Skipped mouse over object with ID :" + Id);
            return;
        }
        
        if(cur_popup_menu_id && (Id != cur_popup_menu_id)) {
            //debug("New ID " + Id + "detected, saving previous data");
        
            hide_popup_menu(cur_popup_menu_id);
            
            var cur_html = $('#popup_menu_div').html();
            if(cur_html.length) popup_menu_info[cur_popup_menu_id].html = cur_html;
            //alert(cur_html);
            
            $('#popup_menu_div').empty();
        
        } /*else if(popup_menu_info[Id] != null) 
            clear_timer_data(Id, true);*/

        cur_popup_menu_id = Id;

        var timer = setTimeout("show_popup_menu("+Id+")", delay);

        if(popup_menu_info[Id] == null) {
            //debug("Creating new data for ID :" + Id);
            popup_menu_info[Id] = {
                Id : $(this).attr('rel'), 
                showTimer : timer, 
                hideTimer : null, 
                showSubMenuTimer: null, 
                hideSubMenuTimer: null, 
                Url: gen_local_url('details', 'fmenu', 'm_id='+$(this).attr('rel')), 
                OnObj: true,
                OnMenu: false,
                OnSubMenu: false,
                OnProgress: false, 
                html : ''
            };
        } else {
            //debug("Using old data for ID :" + Id);
            popup_menu_info[Id].showTimer = timer;
            popup_menu_info[Id].OnObj = true;
            popup_menu_info[Id].OnMenu = popup_menu_info[Id].OnSubMenu = popup_menu_info[Id].OnProgress = false;
        }
    
    }).mouseleave(function() { 
        
        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        //cur_popup_menu_id = 0; // will be cleared in hide function
        var Id = $(this).attr('rel');
        
        popup_menu_info[Id].OnObj = false;
        
        clear_timer_data(Id);
        popup_menu_info[Id].hideTimer = setTimeout('hide_popup_menu('+Id+')', 200);
    });

    // init only once
    if(container == '')
        $('#fmenu_loading').mouseover(function() {

            // save last popup menu action timestamp
            last_popup_menu_activity = timestamp();

            if(popup_menu_info[cur_popup_menu_id] != null) {
                popup_menu_info[cur_popup_menu_id].OnProgress = true;
                popup_menu_info[cur_popup_menu_id].OnObj = popup_menu_info[cur_popup_menu_id].OnMenu = popup_menu_info[cur_popup_menu_id].OnSumMenu = false;
            }
        
        }).mouseout(function() {

            // save last popup menu action timestamp
            last_popup_menu_activity = timestamp();

            if(popup_menu_info[cur_popup_menu_id] != null) {
                popup_menu_info[cur_popup_menu_id].OnProgress = false;
                
                clear_timer_data(cur_popup_menu_id);
                popup_menu_info[cur_popup_menu_id].hideTimer = setTimeout('hide_popup_menu('+[cur_popup_menu_id]+')', 200); 
            
            } else setTimeout('hide_popup_menu()', 200); 
        });
}

// initialize AFTER html loading into #popup_menu_div
function init_fmenu() {
    
    //debug("Initializing evens for current menu: " + cur_popup_menu_id);

    $('#popup_menu_div div.fmenu').mouseenter(function() {
        
        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] != null) {
            popup_menu_info[cur_popup_menu_id].OnMenu = true;
            popup_menu_info[cur_popup_menu_id].OnObj = popup_menu_info[cur_popup_menu_id].OnProgress = popup_menu_info[cur_popup_menu_id].OnSubMenu = false;
            //debug("Mouse over main menu " + cur_popup_menu_id);
        
        } else hide_popup_menu();
    
    }).mouseleave(function() {

        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] != null) {
            popup_menu_info[cur_popup_menu_id].OnMenu = false;
            
            clear_timer_data(cur_popup_menu_id);
            popup_menu_info[cur_popup_menu_id].hideTimer = setTimeout('hide_popup_menu('+cur_popup_menu_id+')', 200); 
        
            //debug("Mouse out of main menu " + cur_popup_menu_id);
        
        } else hide_popup_menu(); 
    });

    $('#popup_menu_div div.fsubmenu').mouseenter(function() {

        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] != null) {
            var target = $(this).attr('id');

            popup_menu_info[cur_popup_menu_id].OnSubMenu = target;
            popup_menu_info[cur_popup_menu_id].OnObj = popup_menu_info[cur_popup_menu_id].OnProgress = popup_menu_info[cur_popup_menu_id].OnMenu = false;
        
            //debug("Mouse over submenu " + cur_popup_menu_id);
        } else hide_popup_menu();
    
    }).mouseleave(function() {
        
        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] != null) {
            var target = $(this).attr('id');
            
            popup_menu_info[cur_popup_menu_id].OnSubMenu = false;

            clear_timer_data(cur_popup_menu_id);
            popup_menu_info[cur_popup_menu_id].hideSubMenuTimer = setTimeout('hide_popup_submenu(\''+cur_popup_menu_id+'\', \''+target+'\')', 200); 
        
            //debug("Mouse out of submenu " + cur_popup_menu_id);
        } else hide_popup_menu();
    });

    $('#popup_menu_div div.fmenu_blank, #popup_menu_div div.fmenu_blank').click(function() {

        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if($(this).attr('rev') != null) {
            var wh = $(this).attr('rev').split(',');
            window.open($(this).attr('rel'), '', 'top=10,left=10,width='+wh[0]+',height='+wh[1]+',toolbar=0,directories=0,status=0,menubar=0,resizable=1,scrollbars=0');
        } else {
            window.open($(this).attr('rel'));
        }
    });
    
    $('#popup_menu_div div.fmenu_popup').click(function() {
        
        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        tb_show(null, $(this).attr('rel'), null);
    });

    $('#popup_menu_div div.fmenu_sub').mouseover(function() {

        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] == null) hide_popup_menu();

        var target = $(this).attr('rel');
        var offset = $(this).attr('rev');

        clear_timer_data(cur_popup_menu_id, false, false, false, true);
        popup_menu_info[cur_popup_menu_id].showSubMenuTimer = setTimeout('show_popup_submenu(\''+cur_popup_menu_id+'\', \''+target+'\', \''+offset+'\')', 200); 
        
        //debug("Mouse over item in main menu " + cur_popup_menu_id + "("+target+")");
    }).mouseout(function() {
        
        // save last popup menu action timestamp
        last_popup_menu_activity = timestamp();

        if(popup_menu_info[cur_popup_menu_id] == null) hide_popup_menu();

        var target = $(this).attr('rel');
        
        clear_timer_data(cur_popup_menu_id);
        popup_menu_info[cur_popup_menu_id].hideSubMenuTimer = setTimeout('hide_popup_submenu(\''+cur_popup_menu_id+'\', \''+target+'\')', 200); 
        //debug("Mouse out of item in main menu " + cur_popup_menu_id + "("+target+")");
    });
}

function show_popup_menu(Id) {

    popup_menu_info[Id].showTimer = 0;

    //debug("Starting displaying menu with ID :" + Id);
    $('#fmenu_loading').css('display', 'block');
 
    if((popup_menu_info[Id] != null) && (popup_menu_info[Id].html != '')) {

        //debug("Found old data for ID :" + Id);
        $('#popup_menu_div').html(popup_menu_info[Id].html);
        
        init_fmenu();
        $('#fmenu_loading').css('display', 'none');
        $('#popup_menu_div').css('display', 'block');
    
    } else {

        //debug("Loading data from server for ID :" + Id);
        $('#popup_menu_div').load(
            popup_menu_info[Id].Url, 
            null, 
            function() { 

                // save last popup menu action timestamp
                last_popup_menu_activity = timestamp();

                init_fmenu();
                $('#fmenu_loading').css('display', 'none');
                $('#popup_menu_div').css('display', 'block');
                var loaded_html = $('#popup_menu_div').html();
                
                // parse member Id from response
                var rexp = new RegExp('fmenu_cont_(\\d+)', "img");
                var found = rexp.exec(loaded_html);
                var Id = found[1];
                /////////

                popup_menu_info[Id].html = loaded_html;
                //debug("Loaded data from server for ID :" + Id);
            }
        );
    }
}

function hide_popup_menu() {
    
    var Id = (arguments.length >= 1) ? arguments[0] : null;
    //debug("Hiding menu for ID :" + (Id==null?'null':Id));
    
    // stop all timers
    if(Id != null && popup_menu_info[Id] != null) {

        if((Id == cur_popup_menu_id) && (popup_menu_info[Id].OnObj || popup_menu_info[Id].OnMenu || popup_menu_info[Id].OnProgress || (popup_menu_info[Id].OnSubMenu != false))) {
            popup_menu_info[Id].hideTimer = 0;
            //debug("No need to hide menu for ID :" + Id);
            return;
        }

        clear_timer_data(Id);
        popup_menu_info[Id].OnObj = popup_menu_info[Id].OnProgress = popup_menu_info[Id].OnSubMenu = popup_menu_info[Id].OnMenu = false;
        $('#popup_menu_div div.fsubmenu').css('display', 'none');
        
        //debug("<span style='color:red'>Hided menu for ID " + Id + "</span>");

    } else for(Id in popup_menu_info) {
        clear_timer_data(Id);
        popup_menu_info[Id].OnObj = popup_menu_info[Id].OnProgress = popup_menu_info[Id].OnSubMenu = popup_menu_info[Id].OnMenu = false;
        //debug("Cleared all menus");
    }

    $('#fmenu_loading').css('display', 'none');
    $('#popup_menu_div').hide();
}

function clear_timer_data(Id) {

    //debug("Clearing timers for ID " + Id);

    var skip_show_timer = (arguments.length >= 2) ? arguments[1] : false;
    var skip_hide_timer = (arguments.length >= 3) ? arguments[2] : false;
    var skip_show_submenu_timer = (arguments.length >= 4) ? arguments[3] : false;
    var skip_hide_submenu_timer = (arguments.length >= 5) ? arguments[4] : false;

    if(!skip_show_timer && popup_menu_info[Id].showTimer) clearTimeout(popup_menu_info[Id].showTimer);
    if(!skip_hide_timer && popup_menu_info[Id].hideTimer) clearTimeout(popup_menu_info[Id].hideTimer);
    if(!skip_show_submenu_timer && popup_menu_info[Id].showSubMenuTimer) clearTimeout(popup_menu_info[Id].showSubMenuTimer);
    if(!skip_hide_submenu_timer && popup_menu_info[Id].hideSubMenuTimer) clearTimeout(popup_menu_info[Id].hideSubMenuTimer);

    if(!skip_show_timer) popup_menu_info[Id].showTimer = 0;
    if(!skip_hide_timer) popup_menu_info[Id].hideTimer = 0;
    if(!skip_show_submenu_timer) popup_menu_info[Id].showSubMenuTimer = 0;
    if(!skip_hide_submenu_timer) popup_menu_info[Id].hideSubMenuTimer = 0;

    //debug("Finished clearing timers for ID " + Id);
}

function hide_popup_submenu(Id, target) {

    //debug("Hiding submenu for ID :" + Id + "(" + target + ")");
    popup_menu_info[Id].hideSubMenuTimer = 0;

    if((popup_menu_info[Id].OnSubMenu == target) && (Id == cur_popup_menu_id)) {
        //debug("No need to hide submenu for ID :" + Id + "(" + target + ")");
        return;
    }

    $('#'+target).css('display', 'none');
    
    //debug("Hided submenu for ID :" + Id + "(" + target + ")");
    hide_popup_menu(Id); 
}

function show_popup_submenu(Id, target, offset) {
    
    popup_menu_info[Id].showSubMenuTimer = 0;
    
    // hide all submenus
    $('#popup_menu_div div.fsubmenu').css('display', 'none');

    $('#'+target).
        css('top', offset*20+'px').
        css('left', 121+'px').
        css('display', 'block');

    //debug("Showed submenu for ID :" + Id + "(" + target + ")");
}

function hide_not_active_popup() {
    
    if((timestamp() - last_popup_menu_activity > 3) && ($('#popup_menu_div').is(':visible'))) {
        $('#fmenu_loading').css('display', 'none');
        $('#popup_menu_div').hide();
    }
}

/***************************************************/
/***************************************************/
/***************************************************/

function timestamp() {
    var timestamp = 0;
    var cur_date = new Date();

    timestamp += cur_date.getSeconds();
    timestamp += cur_date.getMinutes() * 60;
    timestamp += cur_date.getHours() * 3600;
    timestamp += cur_date.getDay() * 86400;
    
    return timestamp;
}

function update_hidden_block_stage(cookie_name, cur_visible, block_id) {

    var hidden_blocks = $.cookies.get(cookie_name);
    if(hidden_blocks == null) hidden_blocks = '';
    hidden_blocks = hidden_blocks.split('|');

    var cur_index = in_array(block_id, hidden_blocks);
    
    if(cur_visible && (cur_index != -1)) {
        do {
            hidden_blocks[cur_index] = null;
        } while(-1 != (cur_index = in_array(block_id, hidden_blocks)));

    } else if(!cur_visible && (cur_index == -1)) {
        hidden_blocks[hidden_blocks.length] = block_id;
    }

    var packed = hidden_blocks.join('|').replace(/(\|+)/g, '|').replace(/^\||\|$/g, '');
    $.cookies.set(cookie_name, packed, {hoursToLive: 720});
}

/*function debug(text) {
    var cur_date = new Date();
    var cur_hour = cur_date.getHours();
    var cur_minute = cur_date.getMinutes();
    var cur_second = cur_date.getSeconds();
    
    var ind, to_add = '';
    for(ind in popup_menu_info) if(popup_menu_info[ind].html != '')
        to_add += ind + '->' + popup_menu_info[ind].html.length+':';

    $('div.area_body_cont').append('<br />'+cur_hour+":"+cur_minute+':'+cur_second+' -> '+text+'['+to_add+']' + $('#popup_menu_div').html().length);
}*/