var debug = true;
var Favs = [];
var isFavoritesPage = false;
var isAboutPage = false;
var isNewsPage = false;
var cookie_params = { expires: 30,  path: "/"}; 
var cookie_name = 'Favorites';


$(function(){
   
   // assign class to top menu
   $('#nav li').eq(0).addClass('l1');
   $('#nav li').eq(1).addClass('l2');
   $('#nav li').eq(2).addClass('l3');
   $('#nav li').eq(3).addClass('l4');
   
   // add fotograph to list
   if ($('.photo-r>div>h5').size() == 1) {
        var name = $('.photo-r>div>h5').text().replace(":","");
	 var value = name.replace(" ","_");
        Log(name);
        
        $("#p_order select[name=type]").prepend("<option value='"+value+"' selected='selected'>"+name+"</option>");
   }
   
   // Fav Init
   Initfav();
   
   // Hash Init;
   InitHash();
   
   // Fav add click
   $('div.ad-image a.fav').live('click',function(){3
        
    	var currentPhoto = $('ul.ad-thumb-list a.ad-active img');
        var imgId =   currentPhoto.attr('fav');
        Log(imgId);
        
        if($.inArray(imgId,Favs) == -1) {
            AddTofav(imgId); Log('adding to fav - '+imgId);
			$(this).attr('title','Удалить из избранного')
        } else {
            DelFromFav(imgId); Log('remove from fav - '+imgId);
			$(this).attr('title','Добавить в избранное')
        }
        
        AssignGalClass(imgId);
        
        return false;
   });
   
   
   
   // remove whole photgraph
   $('.photo-r a.remove').click(function(){
        RemovePhotographFromFav($(this).attr('rel'));
   });
   
   if (isNewsPage) {
        LoadLikeButtons();
   }
   
});


function InitHash() {
    var hash = window.location.hash;
    
    // about page tabs
    if (isAboutPage) {
        var loc = hash.match(/news|articles|smi/) ? hash : '#news';
        
        $('a[href='+loc+']').parent().addClass('active');
        InitAboutTabs();
        
    }
    
    // Loads images
    if (!isFavoritesPage) {
        if (hash.match(/^\#image_\d+$/)) {
            Log('Found image Hash '+hash);
            
            
            /*$('a[rel='+hash+']').click();
            Log($('a[rel='+hash+']'));*/    
        }
    }
    
}

function LoadLikeButtons() {
    //var hostname = 'http://'+window.location.host;
    var hostname = '';
    var img_link = hostname+$('a.ad-active img').attr('src');
    Log(img_link);
    
    if (!isFavoritesPage) {
        
        var container_selector = isNewsPage ? 'div.contents' : 'div.ad-image';
        var imgContainer = $(container_selector);
        imgContainer.append('<div class="social_buttons" id="social_buttons"></div>');
         var YaShareInstance = new Ya.share({
                element: 'social_buttons',
                elementStyle: {
                'type': 'button',
                'border': false,
                'quickServices': ['twitter',  'vkontakte' , 'odnoklassniki' , 'lj' , 'facebook']
                },
                image: 'assets/galleries/6/thumbs/Jellyfish.jpg',
                
                onready: function(instance) {
                    
                }
         });   
    }
}

function Log(str) {
    if (debug && window.console) {
        
        console.log(str);
    }
}


function Initfav() {
    var str = $.cookie(cookie_name);
        
    if (str == null) {
        //create element
        $.cookie(cookie_name,'',cookie_params);    
        Log("Creating cookie");
    } else {
        if (str != '') {
             Favs = str.split(",");
        }       
    }
    
    Log('Fav is:' + Favs);
    SaveFav();
}

function AddTofav(id) {
    if ($.inArray(id,Favs) == -1) {
        Favs.push(id);
        SaveFav();
		UpdatePhotographFavCount(id);
        return true;    
    } else {
        return false;
    }
}

function DelFromFav(id) {
    var index = $.inArray(id,Favs);
    Favs.splice(index,1);
    SaveFav();
	UpdatePhotographFavCount(id);
    
    if (isFavoritesPage) {
        
        var li = $('.ad-gallery li:has(img[fav='+id+'])');
        var siblings_count = li.siblings('li').size();
        li.remove();
        
        if (siblings_count == 0) {
            var photograph_id = $('.g_wrap').attr('photograph_id');
            Log('photograph_id:'+photograph_id);
            RemovePhotographFromFav(photograph_id);
            
        } else {
            Log('Init Gallery');
            InitGallery();    
        }
    }
    
    
    return true;
}

function CountFav() {
    return Favs.length;
}

function UpdateFavLink(id) {
    
}

function SaveFav() {
//    $.cookie(cookie_name,Favs.join(','),cookie_params);
    //    
//    $("#nav .l1 a").text('Мой фотограф ('+CountFav()+')');        
}


function RemovePhotographFromFav(photograph_id) {
    $(".g_wrap[photograph_id="+photograph_id+"],.photo-r#photograph_"+photograph_id).remove();
    $.post('ajax.php',{action:'get_fav_ids',photograph_id:photograph_id},function(ids){
        if (ids) {
            for (id in ids) {
                var index = $.inArray(id,Favs);
                Favs.splice(index,1);
            }
            SaveFav();
            
            if ($('.photo-r').size() == 0) {
                location.reload();    
            }
        }
        Log(ids);
    },'json');    
}


function UpdatePhotographFavCount(image_id) {
    $.post('ajax.php',{action:'get_fav_ids',image_id:image_id},function(r){
        
		Log(r);
		var icon = $(".icon"+r.photograph_id);
		icon.html(r.html);
		
    },'json');
}

function AssignGalClass(imgId) {
    var gallery = $('div.ad-gallery');
    if ($.inArray(imgId,Favs) == -1) {
        gallery.removeClass('has_favorite');
    } else {
        gallery.addClass('has_favorite');
    }
}
