var nList = {87: [], 88 : [], 89 : [] , 113: [] , 114 : []};
var debug = true;
var cookie_params = { expires: 1,  path: "/"}; 

$(function(){
	
	$("table tbody td.last a,a.add,a.remove").click(function(event){
		var $target = $(event.target);
        
        var params = $target.attr('rel').split(":");
        var id = params[1]
        var list = params[0];
		
        if ($target.hasClass('add')){
		    Log("Add "+id+ " to "+ list);
            addToList(list,id);    
			$target.removeClass('add').addClass('remove').html('- убрать из Моего списка');
		}
		else if ($target.hasClass('remove')){
		    Log("Remove "+id+ " from "+ list);   
            removeFromList(list,id); 
            
			$target.removeClass('remove').addClass('add').html('+ добавить в Мой список');
		};
        
        // refresh sum
        var sum = GetListCount();
        $(".my_list").html('<a href="/mylist/">Мой список</a> ('+sum+')');
        
        if (sum>0) {
           $(".my_list").show(); 
        } else {
           $(".my_list").hide(); 
        }
        
		return false;
	});
    
    InitList();
    
    
    // print IF class exists
    if ($("#wrapper.print").size()>0) {
        $("div.options.buttons,div.buttons,ul.options").remove();
        window.print();
    }
    
    
    // hide buttons
    $(".leftmenu>li:has(ul)").each(function(){
       var name = $(this).children('a').text();
       $(this).children('a').replaceWith($('<span>'+name+'</span>'));
        
    });
    
});


function InitList() {
    
    $.each(nList,function(index , value){
        var str = $.cookie(index);
        
        if (str == null) {
            //create element
            $.cookie(index,'',cookie_params);    
            Log("Creating cookie vals for "+index);
        } else {
            if (str != '') {
                 nList[index] = str.split(",");
            }   else {
                nList[index] = [];
            }         
        }
    });
    
    Log("List is:");    
    Log(nList);
}

function addToList(list,id) {    
    if ($.inArray(id,nList[list]) == -1) {
        nList[list].push(id); 
        SaveList();   
    }
}

function removeFromList(list,id) {
    var index = $.inArray(id,nList[list]);
    nList[list].splice(index,1);
    SaveList();
}

function SaveList() {
    Log("Save object");
    
    $.each(nList,function(index , value){
        Log("Save "+index+" value "+value.join(","));
        $.cookie(index,value.join(','),cookie_params);    
    });
    
    Log(nList);
}

function GetListCount() {
    var sum = 0;
    $.each(nList,function(index,value){
        sum += value.length;
    });
    return sum;
}

function Log(text) {
    if (debug) {
        if (window.console) {
            console.log(text);    
        }
    }
}
