$(document).ready(function(){
	$('#english_content div').slideToggle();
	$('.slide .t2').mouseout(function(){
		$('#title_exposure span').html('<br />');
	});
	
	$('#list_years').find('li').find('p').find('a').click(function(){
		if($(this).parent().find('div').html() == null)
			getObras2($(this).html(),$(this));
		else
			if($(this).parent().find('div').css('display') == 'none')
				$(this).parent().find('div').show();
			else
				$(this).parent().find('div').hide();
	});
	
	$('.slide .t2').mouseover(function(){
		if($(this).attr('title') != ''){
			$('#title_exposure span').html( 'Exposição<br />' + $(this).attr('title') );
		}
	});
	$('.slide .t2').mouseout(function(){
		if($(this).attr('title') != '' || $(this).attr('title') != undefined)
			$('#title_exposure span').html('<br />');
	});
	
	var y_fixo = $("#res_img").offset().top;
	    $(window).scroll(function () {
	        $("#res_img").animate({
	            top: y_fixo+$(document).scrollTop()+"px"
	            },{duration:500,queue:false}
	        );
	    })
	
});
/*
 * funcao para editar contato
 */
function editContato(base,id){
	$('#id_contato').val(id);
	
	$.getJSON(base + 'publisher/json/contato/' + id,
	        function(ret){
				$('#contact').val(ret.contact);
				$('#misc').val(ret.misc);
				
				if(ret.misc)
					tinyMCE.get('misc').setContent(ret.misc);
				else
					tinyMCE.get('misc').setContent('');
					
				$('#enviar_contato_2').removeClass('hide');
	        });
}

/*
 * funcao para excluir contato
 */
function delContato(base,id){
	
	var c = confirm('Tem certeza que deseja continuar?\nEssa ação não pode ser desfeita');
	
	if(c == true)
	$.getJSON(base + 'publisher/json/contato/' + id + '/del',
	        function(ret){
				alert('Contato ecluido com sucesso');
	        });
}

/*
 * funcao para editar textos
 */
function editTexts(base,id){
	$('#id').val(id);
	$.getJSON(base + 'publisher/json/textos/' + id,
	        function(ret){
				$('#title').val(ret.title);
				$('#title_en').val(ret.title_en);
				$('#author').val(ret.author);
				$('#ref').val(ret.ref);
				$('#texto').val(ret.content);
				$('#texto_en').val(ret.content_en);
				$('#date').val(ret.date);
			
				if($('#description').attr('name') != undefined){
					$('#description').val(ret.description);
					if(ret.description)
						tinyMCE.get('description').setContent(ret.description);
					else
						tinyMCE.get('description').setContent('');
				}
				
				if($('#description_en').attr('name') != undefined){
					$('#description_en').val(ret.description_en);
					if(ret.description_en)
						tinyMCE.get('description_en').setContent(ret.description_en);
					else
						tinyMCE.get('description_en').setContent('');
				}
				
				if(ret.content)
					tinyMCE.get('texto').setContent(ret.content);
				else
					tinyMCE.get('texto').setContent('');

				if(ret.content_en)
					tinyMCE.get('texto_en').setContent(ret.content_en);
				else
					tinyMCE.get('texto_en').setContent('');

				if(ret.images != undefined){
					var t = ret.images.length;
					var html = '';
					var res;
					for( var i = 0; i < t ; i++ )
					{
						res = ret.images[i];
						if(res.path != "" && res.id != undefined)
						{
							html += '<div class="t3">';
							if(res.not_is_obra == undefined)
								html += '<input type="checkbox" name="obras[]" id="obra_' + res.id + '" value="' + res.id + '" texto="' + res.year + ' - ' + res.title + '" checked="checked" />';
							
	                		html += '<img src="public/uploads/small/' + res.path + res.ext + '" class="t1" style="margin-bottom: 0" />';
							html += '<div class="t2 last" style="margin: 0">';
	                 		html += res.title + ', ' + res.year + '<br />';
	                 		html += '<span class="italic">' + res.tecnic + '<br />';
	                 		if(res.height > 0 && res.width > 0){
								html += res.height + 'x' + res.width + 'cm';
							}
	                 		html += '</span>';
							html += '</div>';
	                		html += '</div>';
						}
					}
				
					$('#res_img').html(html);
				}else{
					$('#res_img').html('&nbsp;');
				}

				$('input[type=submit]').hide();
				$('.hide').show();

				if(ret.title_en != '' || ret.content_en != '')
					$('#english_content div').slideDown();
				else
					$('#english_content div').slideUp();
	        });
}

function setarAtivo(obj)
{
	if($(obj).attr('checked') == true)
	{
		$.getJSON('index.php/publisher/json/obras/' + $(obj).val() + '/active',
		        function(ret){
					alert('Obra atualizada com sucesso');
		        });
	}else if($(obj).attr('checked') == false)
	{
		$.getJSON('index.php/publisher/json/obras/' + $(obj).val() + '/disable',
		        function(ret){
					alert('Obra atualizada com sucesso');
		        });
	}
}

/*
 * funcao para excluir textos
 */
function delTexts(base,id){
	
	var c = confirm('Tem certeza que deseja continuar?\nEssa ação não pode ser desfeita');
	
	if(c == true)
	$.getJSON(base + 'publisher/json/textos/' + id + '/del',
	        function(ret){
				alert('Texto ecluido com sucesso');
				$('#reg_'+id).slideUp();
				$('#divisor_'+id).hide();
	        });
}

/*
 * funcao para editar obras
 */
function editObras(base,id){
	$('#id').val(id);
	$('#res_img').hide();
	$.getJSON(base + 'publisher/json/obras/' + id,
	        function(ret){
				$('#titulo').val(ret.title);
				$('#title_en').val(ret.title_en);
				$('#author').val(ret.author);
				$('#tecnic').val(ret.tecnic);
				$('#tecnic_en').val(ret.tecnic_en);
				$('#width').val(ret.width);
				$('#height').val(ret.height);
				$('#exposure').val(ret.exposure);
				$('#exposure_en').val(ret.exposure_en);
				$('#author').val(ret.author);
				$('#year').val(ret.year);
				$('#res_img').html(ret.image).slideDown();
				
				$('input[type=submit]').hide();
				$('.hide').show();
	        });
}

/*
 * funcao para excluir obras
 */
function delObras(base,id){
	
	var c = confirm('Tem certeza que deseja continuar?\nEssa ação não pode ser desfeita');
	
	if(c == true)
	$.getJSON(base + 'publisher/json/obras/' + id + '/del',
	        function(ret){
				alert('Obra ecluida com sucesso');
				window.document.location.href = window.document.location.href;
	        });
}

/*
 * funcao para incluir textos em ingles/portugeus
 */
function chgLang(l){
	if(l == 'en'){
		$('#title').hide();
		$('#texto').removeClass('texts texto').addClass('hide');
		$('#title_en').show();
		$('#texto_en').addClass('texts texto').removeClass('hide');
	}else if(l == 'pt'){
		$('#title').show();
		$('#texto').addClass('texts texto').removeClass('hide');
		$('#title_en').hide();
		$('#texto_en').removeClass('texts texto').addClass('hide');
	}
	
}

/*
 * funcao para setar o titulo da apgina
 */
function setTitle(t){
	if(t != '')
		$('#title_exposure span').html('Exposição<br />'+t);
}

/*
 * funcao do slide
 */
function slide( d , i ){
	
	var container = $('#container_'+i);
	var margin    = $('#margin_'+i);
	var year 	  = $('#ctrl_year_'+i);
	var next	  = $('#totnext_'+i);
	var totitens  = $('#totitens_'+i);
	var max_itens  = $('#max_itens_'+i);

	if(d == 'l')
	{
		var mf = parseInt(margin.val())-840; // margin final
		var w = parseInt(container.find('.slide').width())+1010; // width novo pra caber todos os itens
		
		/*var atu_first = parseInt(next.val()+1)*5;
		var atu_last = atu_first+6;
		var j = 0;
		container.find('.slide').find('.t2').each(function(){
			if(j >= atu_first && j <= atu_last)
				$(this).css('display','inline');
		});*/
		

		container.find('.slide').animate({marginLeft: mf+'px', width: w+'px'},1000, function(){
			
			margin.val(mf);
			$('#year_'+i).css('display','none');
			container.find('.hide').css('display','block');
			
			next.val(
				parseInt(next.val())+1
			);
			
			getObras( year.val() , container.find('.slide_container').find('.slide') , i );
			
			
			setH(i);
			
			if(margin.val() < 0){
				var n = parseInt(max_itens.val()) / 5;
				var n2 = parseInt(totitens.val()) / 5;
				var nxt = parseInt(next.val())+1;
				if(nxt == n){
					$('#next_'+i).hide();
					$('#lnext_'+i).hide();
				}else{
					$('#next_'+i).show();
					$('#lnext_'+i).show();
				}
			}
			
			
			
		});

	}else{
		var mf = parseInt(margin.val())+840;//margin final

		var atu_first = parseInt(next.val())*5;
		var atu_last = atu_first+5;

		container.find('.slide').animate({marginLeft: mf+'px'},1000, function(){
			margin.val(mf);

			if(mf >= 0){
				$('#year_'+i).css('display','block');
				container.find('.hide').css('display','none');
			}

			next.val(
				parseInt(next.val())-1
			);
			
			if(margin.val() <= 0){
				$('#next_'+i).show();
				$('#lnext_'+i).show();
			}
			
			setH(i);

		});
	}
	
}

function setH( i , hpx ){
	if($('#totnext_'+i).val() > 0)
		var totn = parseInt($('#totnext_'+i).val())+1;
	else if($('#totnext_'+i).val() == 0)
		var totn = 1;

	var pimg = (totn*5)-5;
	var nimg = (totn*5)+1;

	if(pimg <= 0){
		pimg = 5;
	}

	//var ph = $("#container_"+i +" .slide_container .slide .t2 a").find('img').eq(pimg).height();
	//$('#prev_'+i).height(ph);
	var j = 1;
	$("#container_"+i+" .slide_container .slide .t2").each(function(){
		if(pimg == j){
			var h = $(this).find('img').height();
			$('#prev_'+i).height(h);
			}
		j++;
	});
	
	if(hpx != undefined){
		$('#next_'+i).height(hpx);
	}else{
		j = 1;
		$("#container_"+i).find('.slide_container').find('.slide').find('.t2').each(function(){
			if(nimg == j){
				var h = $(this).find('img').height();
				if(h > 0)
					$('#next_'+i).height(h);
				else
					setTimeout("$('#next_'+i).height(h);",5000);
				}
			j++;
		});
		//var nh = $("#container_"+i).find('.slide_container').find('.slide').find('.t2').eq(nimg).find('img').height();
		//$('#next_'+i).height(nh);
	}
	
	//alert($('#container_'+i +' .slide_container .slide .t2 a').find('img').eq(nimg).attr('src'));
	

	/*

	*/
}

function getObras(y,obj,j)
{
	if($('#totret_'+y).val() != 'ok' && $('#totitens_' + j).val()%5 == 0){
		var urlimg  = $('base').attr('href');
		var urlbase = $('base').attr('href') + 'index.php/';
		var currurl = window.document.location.href;
		var offset  = $('#totitens_' + j).val();
		var child   = $('#child').val();
		
		if($('#escala').val() == 1)
		{
			offset += '/1';
		}
		
		$.getJSON(urlbase + 'json/obras/' + y + '/' + child + '/' + offset,
			function(ret){
			
				if(ret.row && ret.row.length > 0){
					var t = ret.row.length;
					var html = '';
					var res;
					for( var i = 0; i < t ; i++ )
					{
						res = ret.row[i];
						if(res.id != undefined)
						{
							if(res.exposure != undefined)
								var exposure = res.exposure;
							else
								var exposure = "<br />";

							html += '<div class="t2" title="' + exposure + '">';
							if($('#escala').val() == 1)
								html += '<a href="' + urlbase + 'obra/' + $('#defaulturl').val() + res.id + '"><img src="' + urlimg + 'public/uploads/tmp/' + res.path + res.ext + '"></a>';
							else
								html += '<a href="' + urlbase + 'obra/' + $('#defaulturl').val() + res.id + '"><img src="' + urlimg + 'public/uploads/small/' + res.path + res.ext + '"></a>';
							
							if(i == 0)
								var hpx = res.height_px;

	                		html += '<p class="leg">';
	                 		html += '<a href="' + urlbase + 'obra/' + $('#defaulturl').val() + res.id + '">' + res.title + ',' + res.year + '</a><br />';
	                 		html += '<span class="italic">' + res.tecnic + '<br />';
	                 		if(res.height > 0 && res.width > 0){
								html += res.height + 'x' + res.width + 'cm';
							}
	                 		html += '</span>';
	                 		html +=	'</p>';
	                		html += '</div>';
						}
					}

					obj.append(html);
					$('.slide .t2').mouseover(function(){
						if($(this).attr('title') != '')
							$('#title_exposure span').html( 'Exposição<br />' + $(this).attr('title') );
					});
					$('.slide .t2').mouseout(function(){
						$('#title_exposure span').html('<br />');
					});

					var totalItens = parseInt($('#totitens_'+j).val())+t;
					$('#totitens_'+j).val(totalItens);
						
					if(t < 5)
						$('#totret_'+y).val('ok');
					else
						$('#totret_'+y).val(t);
					
					if(hpx)
						setH(j,hpx);
				
				}else{
					$('#totret_'+y).val('ok');
				}
			}
		);
	}
}

// funcao para setar a exposicao
function setExposure(str)
{
	if(str != '' || str != false)
		$('#title_exposure span').html('Exposição<br />'+str);
	else
		$('#title_exposure span').html('&nbsp;<br />');
}

// funcao para pegar as obra sde acordo com o ano
function getObras2(y,obj)
{
	var urlbase = $('base').attr('href') + 'index.php/';

	$.getJSON(urlbase + 'json/obras/' + y,
		function(ret){
		
			if(ret.row && ret.row.length > 0){
				var t = ret.row.length;
				var html = '';
				var res;
				for( var i = 0; i < t ; i++ )
				{
					res = ret.row[i];
					if(res.id != undefined)
					{	
						//onmouseover="setTitle(' + res.exposure + ')"
						html += '<div class="t3">';
						html += '<input type="checkbox" name="obras[]" id="obra_' + res.id + '" value="' + res.id + '" texto="' + res.year + ' - ' + res.title + '" onclick="chkview(\'#obra_' + res.id + '\')" />';
                		html += '<img src="public/uploads/small/' + res.path + res.ext + '" class="t1" style="margin-bottom: 0" />';
						html += '<div class="t2 last" style="margin: 0">';
                 		html += res.title + ', ' + res.year + '<br />';
                 		html += '<span class="italic">' + res.tecnic + '<br />';
						if(res.height > 0 && res.width > 0){
							html += res.height + 'x' + res.width + 'cm';
						}
                 		html += '</span>';
						html += '</div>';
                		html += '</div>';
					}
				}

				obj.after(html);

			}else{
				alert('Nenhum resultado encontrado')
			}
		}
	);
}

// funcao para checar o checkbox e mostrar na lista os checados
function chkview(obj)
{
	if($(obj).attr('checked') == true){

		$(obj).parent().addClass('selected');
		
		var html  = '<p class="t3 last" style="margin: 0" id="' + $(obj).attr('id') + '_item">';
		 	html += $(obj).attr('texto');
			html += '</p>';
		
		//input .t3     a       li       
		$(obj).parent().parent().parent().parent().before(html);
		
	}else{
		
		var item = $(obj).attr('id') + '_item';
		$(obj).parent().removeClass('selected');
		$('#' + item).remove();

	}
}

function slideLarge(d)
{
	var atual = parseInt($('#tot_next').val())-1;
	if(d == 'l') // left
	{
		var mf = parseInt($('#tot_margin').val())+(-816);
		var next = atual+1;
		$('#obra_'+next+' img').removeClass('hide');
		setExposure($('#exposure_'+next).val());

		$('.slide').animate({marginLeft: mf+'px'},900,function(){
			$('#tot_next').val(
				parseInt($('#tot_next').val())+1
			);

			$('#tot_margin').val(mf);

			
			if($('#tot_next').val() == $('#tot_itens').val())
				$('.next_img').hide();
			else
				$('.next_img').show();

			if(mf < 0 || $('#tot_next').val() > 1)
				$('.pre_img').css('visibility','visible');

			setHeightLarge();
			
			$('#obra_'+atual+' img').addClass('hide');
			
			var id_atual = $('#id_atual_'+(atual+1))
			var url = $('base').attr('href') + 'index.php/';
			
			if(id_atual.val() > 0){
				$('#texts_rel').show().attr('href', url+'textos/'+id_atual.val());
				$('#sep').show();
			}else{
				$('#texts_rel').hide();
				$('#sep').hide();
			}
			
			var id = $('#id_' + next).val();
			var nhref = $('#amp_red').attr('href').split('/');
			//alert(id);
			$('#amp_red').attr('href',$('#amp_red').attr('href').replace(nhref[nhref.length-2],id));
		});

	}else // right
	{
		var mf = parseInt($('#tot_margin').val())+816;
		var prev = atual-1;
		$('#obra_'+prev+' img').removeClass('hide');
		setExposure($('#exposure_'+prev).val());

		$('.slide').animate({marginLeft: mf+'px'},900,function(){
			$('#tot_next').val(
				parseInt($('#tot_next').val())-1
			);
			
			$('#tot_margin').val(mf);
			
			
			if(mf <= 0)
				$('.next_img').show();
			else
				$('.next_img').hide();
			
			if(mf == 0 || $('#tot_next').val() == 1)
				$('.pre_img').css('visibility','hidden');
			
			setHeightLarge();
			
			$('#obra_'+atual+' img').addClass('hide');
			
			var id_atual = $('#id_atual_'+(atual-1))
			var url = $('base').attr('href') + 'index.php/';
			
			if(id_atual.val() > 0){
				$('#texts_rel').show().attr('href', url+'textos/'+id_atual.val());
				$('#sep').show();
			}else{
				$('#texts_rel').hide();
				$('#sep').hide();
			}
			
			var id = $('#id_' + prev).val();
			var nhref = $('#amp_red').attr('href').split('/');
			//alert(id);
			$('#amp_red').attr('href',$('#amp_red').attr('href').replace(nhref[nhref.length-2],id));
			
		});
	}
}

function setHeightLarge()
{
	var tot_next = $('#tot_next');
	var tot_itens = $('#tot_itens');
	var o_next = tot_next.val();
	var o_prev = parseInt(tot_next.val())-2;

	if(o_next < tot_itens.val()){
		var h_next = $('#obra_'+o_next+' img').height();
		$('.next_img').height(h_next);
	}

	if(o_prev >= 0){
		var h_prev = $('#obra_'+o_prev+' img').height();
		$('.pre_img').height(h_prev);
	}

}


// funcao para setar a imagem em bibliografia
function setImg(img)
{
	$('#res_img').html('<img src="'+img+'" />');
	$('#res_img_original').hide();
}

//funcao para mostrar as obras referentes ao ano desejado
function showObras(y)
{
	if(y == 'all'){
		$('#content .t12').show();
		$('#show_all').addClass('hide');
		$('.ativo').removeClass('ativo');
	}else{
		$('#content .t12').hide();
		$('#content .y_' + y).show();
		$('#show_all').removeClass('hide');
		$('.year_'+y).addClass('ativo');
	}
}

