function toolTipShowMosaico(obj){
    obj.children('.info-item').stop().show();
    obj.children('input[name=in-table]').show();
    obj.css('z-index', 1);
}
function toolTipShowTabla(obj){
    var e = obj.attr('rel');
    var x = obj.offset();
    $("#"+e).css('display', 'block').css({top: x.top+15, left: x.left+135});
}
                


var timeoutShowMosaico;//variable que almacena la referencia al timeout
var timeoutShowTabla;//variable que almacena la referencia al timeout
$(document).ready(function()
{
	
	function tooltip (event) 
	{
		wTam = 0;
		hTam = 0;
		xCoor = 0;
		yCoor = 0;
		$('.design-grid').mousemove(
		//tamanos de la reticula y posicion del mouse en ella
		function(e){
			wTam = $(this).width();
			hTam = $(this).height();
			xCoor = e.pageX - this.offsetLeft;
			yCoor = e.pageY - this.offsetTop;
		});
		//mouseover sobre un elemento [mouseover es mejor que mouseenter]
		if (event.type == 'mouseover') {
			//$(this).children('.info-item').stop().show();
			//$(this).children('input[name=in-table]').show();
			//$(this).css('z-index', 1);
		}
		//mouseleave 
		else {
                        if(timeoutShowMosaico!=null && timeoutShowMosaico!=undefined){
                            clearTimeout(timeoutShowMosaico);
                        }
			$('.info-item').hide();
			$(this).children('input:checkbox').hide();
			$(this).children('input:checked').show();
			$(this).css('z-index', 0);
                };
                 var i=0;
		//posicion del tooltip al mover sobre un elemento que depende de la posicion del mouse en la reticula y del tamano de esta
		$(this).mousemove(
			function(e){
                                var obj=$(this);
				xCoorThis = e.pageX;
				yCoorThis = e.pageY;
				$(this).children('.info-item').css({'top': yCoorThis - this.offsetTop + 20});
                                
                                if(obj.children('.info-item').css('display')=="none" && i==0){
                                    if(timeoutShowMosaico!=null && timeoutShowMosaico!=undefined){
                                       clearTimeout(timeoutShowMosaico);
                                    }
                                    timeoutShowMosaico=setTimeout(function(){toolTipShowMosaico(obj)},1000);
                                    i++;
                                }
                                
				
				//Verticalmente se presenta siempre en la misma posicion porque se pierde foco del checkbox de otra form
				/*if ((hTam/2) < yCoor) {
					$(this).children('.info-item').css({'top': yCoorThis - this.offsetTop - 120});
				}*/
				if ((wTam/2) > xCoor) {
					$(this).children('.info-item').css({'left': xCoorThis - this.offsetLeft + 20});
				}
				if (xCoor > 216 && xCoor < 432) {
					$(this).children('.info-item').css({'left': xCoorThis - this.offsetLeft - 200});
				}
				if (xCoor > 432) {
					$(this).children('.info-item').css({'left': xCoorThis - this.offsetLeft - 400});
				}
			}
		);
	};
	
	controla = true;
	
	/*$('#nav .drop-down a').click(
		function () {
			if (controla == true) {
				$(this).parent('li').addClass('active');
				$('.drop-down-menu').show(200);
				controla = false;	
			}
			else {
				$(this).parent('li').removeClass('active');
				$('.drop-down-menu').hide(200);
				controla = true;
			}	
		}
	);
	
	$('#nav .drop-down').mouseleave(
		function () {
			$('#nav .drop-down').removeClass('active');
			$('.drop-down-menu').hide();
			controla = true;	
		}
	);*/
	
	switch($('input[name=vista]').val())
	{
		case 'mosaic':
			$('#my-table').css('display', 'none');
			$('#my-mosaic').css('display', 'block');
			
			$('.design-grid li').live('mouseenter mouseleave', tooltip);
		break;
		default:
			$('#my-table').css('display', 'block');
			$('#my-mosaic').css('display', 'none');
	}
	
	$('li.view-serp > a.view-mosaic').click(function()
	{
		$('#my-table').fadeOut(300);
		$('#my-mosaic').fadeIn(300);
		$('#my-table').css('display', 'none');
		$('#my-mosaic').css('display', 'block');
		
		$('.serp li').live('mouseenter mouseleave', tooltip);
		
		$('.paginator p a').each(function() { $(this).attr('href', $(this).attr('href').replace(/table/, "mosaic")); });
		$('#sidebar .item .categories li a').each(function() { $(this).attr('href', $(this).attr('href').replace(/table/, "mosaic")); });
		$('input[name=vista]').val('mosaic');
	});
	
	$('li.view-serp > a.view-table').click(function()
	{
		$('#my-table').fadeIn(300);
		$('#my-mosaic').fadeOut(300);
		$('#my-table').css('display', 'block');
		$('#my-mosaic').css('display', 'none');
		
		$('.paginator p a').each(function() { $(this).attr('href', $(this).attr('href').replace(/mosaic/, "table")); });
		$('#sidebar .item .categories li a').each(function() { $(this).attr('href', $(this).attr('href').replace(/mosaic/, "table")); });
		$('input[name=vista]').val('table');
	});
	
	$('.design-tabla h2 a').mouseover(function (){
		var obj=$(this);
                if(timeoutShowTabla!=null && timeoutShowTabla!=undefined){
                    clearTimeout(timeoutShowTabla)
                }
                 timeoutShowTabla=setTimeout(function(){toolTipShowTabla(obj)},1000);
	});
	
	$('.design-tabla h2 a').mouseout(function (){
		if(timeoutShowTabla!=null && timeoutShowTabla!=undefined){
                    clearTimeout(timeoutShowTabla)
                }
                var e = $(this).attr('rel');
                $("#"+e).css('display', 'none');
	});
	
	$('input[name=chk-all]').bind('click', function()
	{
		var checked_status = this.checked;
		$('input[name=chk-all]').each(function() { this.checked = checked_status; });
		$('input[name=in-table]').each(function() { this.checked = checked_status; });
		$('#my-mosaic input[name=in-table]').each(function()
		{
			if($(this).is(':checked')) $(this).show();
			else $(this).hide();
		});
	});

	$('input[name=in-table]').bind('click', function() 
	{
		var checked_status = this.checked;
		var element = this.value;

		$('#my-table .' + element).prop('checked', checked_status);
		$('#my-mosaic .' + element).prop('checked', checked_status);
		if(checked_status) $('#my-mosaic .' + element).show();
		else $('#my-mosaic .' + element).hide();
	});
	
	$('a.edit').bind('click', function()
	{
		var item = '',
			counter = 0;
		
		switch($('input[name=vista]').val())
		{
			case 'mosaic':
				$('#my-mosaic input[name=in-table]').each(function() 
				{
					if($(this).is(':checked'))
					{
						item = $(this).val();
						counter++;
					} 
				});
			break;
			default:
				$('#my-table input[name=in-table]').each(function()
				{
					if($(this).is(':checked')) 
					{
						item = $(this).val();
						counter++;
					} 
				});
		}
		
		if(counter == 1)
		{
			$('#edit').modal();
		
			var year = $('.year-' + item).text(),
				month = $('.month-' + item).text(),
				day = $('.day-' + item).text(),
				condition = $('.condition-' + item).text(),
				price = ($('.price-' + item).text()=="-")?"":$('.price-' + item).text(),
				currency = $('.currency-' + item).text(),
				note = ($('.note-' + item).text()!="-")?$('.note-' + item).text():"";
			
			dates_set('year_acqui', 'month_acqui', 'day_acqui', year, month, day);
			$("#condition option[value='" + condition + "']").prop('selected', 'selected');
			$('#price').val(price);
			$("#currency option[value='" + currency + "']").prop('selected', 'selected');
			$('#note').val(note);
			$('#id-item').val(item);
		}
		else
			$('#edit-alert').modal();
		
		return false;
	});
	
	$('#save-modify').click(function()
	{
		if(($('#price').val() != '' && isNaN($('#price').val())) || $('#price').val() < 0)
		{
			$('#price').addClass('error');
			$('#price').val('');
			$('#price').focus();
			$('div.error').show();
		}
		else
		{
			var item = $('#id-item').val(),
				year = $('#year_acqui').val(),
				month = $('#month_acqui').val(),
				day = $('#day_acqui').val(),
				condition = $('#condition').val(),
				price = $('#price').val(),
				currency = $('#currency').val(),
				note = $('#note').val();
			
			$.modal.close();
			
			$.post(CI_ROOT + "index.php/collection/modify", 
				{id: item, year: year, month: month, day: day, condition: condition, price: price, currency: currency, note: note},
				function()
				{
					$("#filter").submit();
					//window.open(CI_ROOT+'/collection/show/'+$("#txtIdCollection").val(),"_self");
					//$('tr#' + item).load(CI_ROOT + "index.php/collection/refresh_item/" + item);
					return false;
				});
		}
		return false;
	});
	
	$('#price').keypress(function() 
	{
		$('#price').removeClass('error');
		$('div.error').hide();
	});
	
	$('.copy').bind('click', function()
	{
		var items = '',
			counter = 0;
		
		switch($('input[name=vista]').val())
		{
			case 'mosaic':
				$('#my-mosaic input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
			break;
			default:
				$('#my-table input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
		}
		
		if(counter > 0)
		{
			$('#copy').modal();
			
			$('#ids-items').val(items);
		}	
		else
			$('#copy-alert').modal();
		
		return false;
	});
	
	$('#save-copy').click(function() 
	{
		var items = $('#ids-items').val(),
			id_collection = $('#copyCollection').val();
		
		$.modal.close();
		
		$.post(CI_ROOT + "index.php/collection/copy_items", {ids: items, id_collection: id_collection},
			function(data)
			{
				if(data.isRegister){
					//location.reload(true);
					if(data.state == 1){
						window.open(CI_ROOT+'collection/show/'+id_collection+"/name/1/"+$('input[name=vista]').val(),"_self")
					}
				}
			}
		,'json');
	});	
	
	$('.move').bind('click', function()
	{
		var items = '',
			counter = 0;
		
		switch($('input[name=vista]').val())
		{
			case 'mosaic':
				$('#my-mosaic input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked')) 
					{
						items += $(this).val() + ',';
						counter++;
					} 
				});
			break;
			default:
				$('#my-table input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					} 
				});
		}
		
		if(counter > 0)
		{
			$('#move').modal();
			$('#move-items').val(items);
		}
		else
			$('#move-alert').modal();
		
		return false;
		
	});
	
	$('#save-move').click(function() 
	{
		var items = $('#move-items').val(),
			id_collection = $('#cbCutColeccion').val();
		
		$.modal.close();
		
		$.post(CI_ROOT + "index.php/collection/move_items", 
			{ids: items, id_collection: id_collection},
			function(data)
			{
				if(data.isRegister){
					//location.reload(true);
					if(data.state == 1){
					
						window.open(CI_ROOT+'collection/show/'+id_collection+"/name/1/"+$('input[name=vista]').val(),"_self")
					}
				}
			}
		,'json');
	});
	
	$('.del').bind('click', function() 
	{
		var items = '',
		counter = 0;
	
		switch($('input[name=vista]').val())
		{
			case 'mosaic':
				$('#my-mosaic input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
			break;
			default:
				$('#my-table input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
		}
		
		if(counter > 0){
			$('#delete-confirm').modal();
		}else{
			$('#delete-alert').modal();
		}
		
		
			
		
		return false;
	});
	
	$('.closeThis').bind('click', function() { $.modal.close();	return false;});
	
	//Evento de Seguir coleccion btn sidebar
	$("#confirmDeleteItemCollection").live("click",function(){
		var items = '',
		counter = 0;
	
		switch($('input[name=vista]').val())
		{
			case 'mosaic':
				$('#my-mosaic input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
			break;
			default:
				$('#my-table input[name=in-table]').each(function() 
				{ 
					if($(this).is(':checked'))
					{
						items += $(this).val() + ',';
						counter++;
					}  
				});
		}
		
		if(counter > 0)
			
			$.post(CI_ROOT + "index.php/collection/delete_items", 
					{ids: items},
					function()
					{
						//location.reload(true);
						$("#filter").submit();
					});
		else
			$('#delete-alert').modal();
		
		return false;
		
		
		
	});
	
	
	$("#btnSideFollowCollection").live("click",function(e){
		var that= eval('(' + $(this).prop("rel") + ')');
		var selLink = $(this);
		var count = parseInt($("#followCount").html());
		//$("#followCount").html("<img src='"+CI_ROOT+"images/ajax-loader.gif'/>");
		$("#loader_follow").html("<img src='"+CI_ROOT+"images/ajax-loader.gif'/>");
		
		var url= CI_ROOT+'collection/following/'+that.id+"/"+that.state;
		//selLink.html("<img src='"+CI_ROOT+"images/ajax-loader.gif'/>");
		$.getJSON(url, function(data) {
			if(data.isRegister){
				if(data.code){
					selLink.html("<strong>"+data.textLink+"</strong>");
					selLink.prop("rel" , "{'id':"+that.id+", 'state': '"+data.state+"'}");
					//var newCountText = (that.state == 1)?parseInt($("#followCount").text())+1:parseInt($("#followCount").text())-1;
					var newCountText = (that.state == 1)?count+1:count-1;
					$("#followCount").html(newCountText);
					$("#loader_follow").html("");
					/*var a= ($("#f-"+that.id).text()).split(" ");
					var newText =(data.state==0)?(parseInt(a[0])+1)+" "+a[1]:(parseInt(a[0])-1)+" "+a[1];
					$("#f-"+that.id).text(newText);*/
				}else{
					//Error raro
					window.open(CI_ROOT+'login/index/collection/index',"_self");
					//window.open(CI_ROOT+'login/index/gallery/image/'+$('#id_item').val()+'/12/'+$('#id_image').val()+'/1',"_self");
				}
			}else{
				//llevar a pagina principal;
				//alert("Sin registro");
				window.open(CI_ROOT+'login/index/collection/index',"_self");
			}
			
		});
		
		return false;
	});
	
	
	
	
});
