$(function(){
	$('select.onselect').onselect();
	
	$('.onselect').change(function(){
		window.location.href = $(this).val();
	});
	
	initFilterVid();
	
	var listBuscaProduto = new ElementoAjax();
	listBuscaProduto.init($("#jsListBuscaProduto"),{links:".lstPaginacaoPad"});
	
	listFamiliaFas = new ElementoAjax();
	listFamiliaFas.init($("#jsListFamiliaFas"),{links:".jsPaginacao"});
	
	initRelacionaFamilia();
	
	initColapseSearch();
	initCrossSelling();
});

function initFilterVid(){
	if( $('input[type="radio"][name=formato]').length > 0 ){
		
		$('input[type="radio"][name=formato]').change(function(){
			href = window.location.href;

			href = href.replace('busca', 'busca/pagina.action');
			href = href.replace('/marca/', '?marca=');
			href = href.replace('/categoria/', '?categoria=');
			href = href.replace(/_.*/, '');
			
			url = href + '&page=1&formato=' + $(this).val();
			
			$.ajax({
				url: url,
				success: function(t){ 
					$('#jsListBuscaProduto').html(t);
					
					total = $('#hdnTotalProdutos').val();
					text = ( total > 1 ) ? '<span>'+total+'</span> produtos encontrados' : 
								( total == 1 ) ? '<span>1</span> produto encontrado' : 
									'nenhum receito encontrado';

					$('p.totalProdutos').html( text );
				},
				dataType: 'html'
			});
		});
	}
}

function initColapseSearch(){
	
	$('.groupColapse .content').addClass('clearfix')
							   .hide();

	$('.groupColapse.open').children('.content').show();
	
	$(".groupColapse .title a").click(function(e){
		e.preventDefault();
		$(this).parents('.groupColapse').children('.content').slideToggle(400,function(){
			if ( $(this).is(':visible') ) {
				$(this).parents('.groupColapse').addClass("open");
			}
			else {
				$(this).parents('.groupColapse').removeClass("open");
			}
		});
	});
}

function findReceitaId(){
	path = window.location.pathname;
	start = path.search('[0-9]');
	len = path.indexOf('_')

	return path.substr(start, len-start );
}

function initCrossSelling(){	
	var dataJson = []
	
	$.ajax({
		url: '/produtos-relacionados.action',
		dataType: 'json',
		data: {id: findReceitaId()},
		async: false,
		success: function(data){
			dataJson = data;
		}
	});
	
	var pages = [],
		page = 0,
		recPerPage = 3;
		
	if( dataJson.length < 4 ) {
		$('#receitasRelContainer .bts, #receitasRelContainer .btVejaTodas').hide();
	};

	// Fetch the data for a page from the json-result object
	while( dataJson.length > 0 )
	{	
		pages.push(dataJson.splice(0, recPerPage));
	}
	
	function createItem(t){
		img = $('<img>').attr({
			src: '/'+t.path,
			width: 185,
			height: 117,
			alt: t.name,
			title: t.name
		});
		
		msk = $('<span>').addClass('mask pngfix');

		a = $('<a>').attr({
			'href': '/receitas/'+t.link,
			'title': t.name
		}).html(img);
		
		if( t.type == 'V' )
			$(a).append(msk);
		
		div = $('<div>').addClass('receita')
			  			.append('<h4>'+t.name+'</h4>')	
						.append(a);
						
		$('#receitasRelContainer .container').append(div);
	}
	
	function showPage(page){
		$('#receitasRelContainer .container .receita').each(function(){ $(this).remove(); });
		
		$(pages[page]).each(function(t){
			createItem(pages[page][t]);
		});
	}
	
	// init events
	$('.bts .btAnterior').click(function(e){
		e.preventDefault(); 
		
		page--;
		if(page < 0) return false;
		showPage(page);
	});
	
	$('.bts .btProximo').click(function(e){
		e.preventDefault();
		
		page++;
		if (page > pages.length-1) return false;
		showPage(page);
	});
	
	// start
	showPage(page);
	
}

function initRelacionaFamilia(){
	$("#jsRelFamilia,#jsRemFamilia").unbind("click").click(function(){
		if($(this).attr("rel") != 'modal') {
			modalRelFam = new Modal();
			modalRelFam.init({ajax:{type:"get",url:$(this).attr("href"),call: "responseRelacionaFamilia"},args:this});
		}
		dataMetrics({pageName:getPageName().replace(/ - Passo a passo/g,"") + " - Fazer parte da Familia",prop8:document.title,events:"event7"});
		return false;
	});
}

function responseRelacionaFamilia(elem, opt){
	if ($("#jsOkRelFamilia").size() != 0) {
		$("#jsOkRelFamilia").unbind("click").click(function(){
			modalRelFam.close();
			return false;
		});
		
		$(opt.args).hide();
		if ($(opt.args).attr("id") == "jsRelFamilia") {
			var replaceHref = ($("#lastPage").val()).replace(/0/,"1");
			$("#jsRemFamilia").show();
			pageTracker._trackPageview("/produtos/["+ document.title +"]/seja_fa");
		}else{
			var replaceHref = $("#currentPage").val();
			$("#jsRelFamilia").show();
		}
		listFamiliaFas.refresh({type: "get",url: replaceHref});
	}
}


