$(function(){
	var self = this;
	var s_cookie = {category:'',ids:''};
	var cookie_name = "shoppinguol_compare";
	var cookie_domain = ".uol.com.br";
	var current_page = $('#product-list');
	var current_category = $('#boxProduct').attr('class');
	var current_subcategory = current_page.attr('class');

	if(current_page.size() == 0){
		current_page = $('#product-galery');
		current_subcategory = current_page.attr('class');
	}
	
	this.init = function(){
		// leio o cookie para obter os ids
		self.get_cookie();
			
		$('input[@name=compare-check]').each(function(){
			this.checked = false;
		});
		
		if(self.check_current_cookie()){
			var cookie_data = s_cookie.ids.replace("null","").replace(/^\,+|\,+$/g,'').split(',');
			for(i = 0;i < cookie_data.length;i ++){
				var label = $('label#'+ cookie_data[i]);
				
				if(label){
					label.addClass('selected');
					$('input[@name=compare-check]:eq(0)', label).attr('checked','checked');
				}
			}
		}
		
		// açoes para os links e checkbox que fazem a seleção dos produtos para comparação
		$("a.select, input[@name=compare-check]").click(self.select_product);
		
		// selects de ordenação e itens por pagina
		$('select[@name=orderType]').change(self.order_type);
		$('select[@name=resultOffset]').change(self.result_offset);
		
		// atribui ações aos links de imagem
		$('ul li:not(.merchandise) a.image:not(.img_error)').mouseover(self.addzoom);
		
		$('#product-visualization li a').click(self.update_page_type);
		
		$('.contentNumLoja a').unbind().click(self.show_evaluation);
	
		$('span.logo-ps').mouseover(self.show_ps_info);
		$('span.logo-ps').mouseout(self.hide_ps_info);
		$('span.logo-ps').click(self.click_ps_info);
		
		self.update_compare();
		
		$('a.image span.zoom').remove();
		
		$('img','ul li:not(.merchandise) a.image:not(.img_error)').each(function(){
			$(this).attr('alt','Clique para ampliar');
			
			var tb_height = $(this).parents('a').hasClass('unavailable') ? 400 : 560;
			var param = ($(this).parents('a').attr('href').indexOf('?') > -1 ? '&' : '?' ) + 'top=true&width=460&height='+ tb_height;
			$(this).parents('a').addClass('thickbox').attr('href', $(this).parents('a').attr('href') + param);
			
		});

		
		$('ul li:not(.merchandise) a.image:not(.img_error)').mouseup(function(e){
			var left_button = $.browser.msie ? 1 : 0;
			var middle_button = $.browser.msie ? 4 : 1;
			var right_button = 2;
			
			if((e.button == middle_button && !$.browser.msie) || e.button == right_button){
				$(this).attr('href',$(this).attr('href').replace(/(top|width|height)=[a-z0-9]+&?/gim,''));
			}else{
				if($(this).attr('href').indexOf('top=true') == -1){
					var tb_height = $(this).hasClass('unavailable') ? 400 : 560;
					var param = ($(this).attr('href').indexOf('?') > -1 ? '&' : '?' ) + 'top=true&width=460&height='+ tb_height;
					$(this).attr('href', $(this).attr('href') + param);
				}
			}
		});
		
		tb_init('a.thickbox'); 
	};
	
	// método para criar cookie
	this.set_cookie = function(page_type, subcategory){ 
		var category = ($.trim(subcategory) == "" ? current_subcategory : subcategory);
		var ids = ($.trim(s_cookie.ids) == "" ? "null" : s_cookie.ids);
		var value = page_type +"|"+ category +"|"+ ids;
		var expires = "";
		document.cookie = cookie_name +"="+ escape(value) +''+ expires +"; domain="+ cookie_domain +"; path=/;";
		
		// leio o cookie novamente
		self.get_cookie();
	};
	
	// método para pegar um cookie específico
	this.get_cookie = function(){
		var start = document.cookie.indexOf(cookie_name +"=");
		var len = start + cookie_name.length + 1;
		
		if(!start && cookie_name != document.cookie.substring(0, cookie_name.length)){
			return
		}
		
		if(start == -1){
			return;
		}
		var end = document.cookie.indexOf( ";", len );
		
		if(end == -1){
			end = document.cookie.length;
		}
		
		var cookie_data = unescape(document.cookie.substring(len,end)).split('|');
		
		if(cookie_data.length >= 3 && $.trim(cookie_data[0]) != "" && $.trim(cookie_data[0]) != "undefined"){
			s_cookie = {
				page_type: cookie_data[0],
				category: cookie_data[1],
				ids: cookie_data[2]
			};
		}else{
			s_cookie = {
				page_type: "product-galery",
				category: cookie_data[0],
				ids: cookie_data[1]
			};
		}
	};
	
	// método para deletar cookie
	this.erase_cookie = function(){
		document.cookie = cookie_name +"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain="+ cookie_domain +"; path=/;";
	};
	
	// método que checa se o a categoria atual é mesma categoria do cookie
	this.check_current_cookie = function(){
		if(s_cookie && s_cookie.category == current_subcategory){
			return true;
		}else{
			return false;
		}
	};
	
	// adciona um id ao cookie
	this.cookie_add_id = function(id){
		self.get_cookie();
		
		var cookie_data = $.trim(s_cookie.ids).replace("null","").replace(/^\,+|\,+$/g,'').split(',');
		var id_exists = false;
		
		for(i = 0;i < cookie_data.length;i ++){
			if(cookie_data[i] == id){
				id_exists = true;
			}
		}
		
		if(!id_exists){
			cookie_data.push(id);
			s_cookie.ids = cookie_data.join(',').replace(/^\,+|\,+$/g,'');
			self.set_cookie(self.get_page_type(), current_subcategory);
		}
	};
	
	// remove um id do cookie
	this.cookie_rm_id = function(id){
		var cookie_data = $.trim(s_cookie.ids).replace("null","").replace(/^\,+|\,+$/g,'').split(',');
		var new_cookie_data = [];
		
		for(i = 0;i < cookie_data.length;i ++){
			if(cookie_data[i] != id){
				new_cookie_data.push(cookie_data[i]);
			}
		}
		
		s_cookie.ids = new_cookie_data.join(',').replace(/^\,+|\,+$/g,'');
		
		self.set_cookie(self.get_page_type(), current_subcategory);
	};
	
	// adiciona lupa a imagem
	this.addzoom = function(e){
		e.stopPropagation(); e.preventDefault();
		var current_zoom = $('span.zoom', this);
		
		if(current_zoom.size() == 0){
			var zoom = $('span.zoom');
			zoom.remove();
			
			var lupa = '<span class="zoom"><span></span></span>';
			$(lupa).appendTo(this);
			
			$('span.zoom').mouseout(function(){
				$(this).remove();
			});
		}
		
		return;
	};
	
	// atualiza links de compare
	this.update_compare = function(){
		var selecteds = $('label.selected');
		
		if(!s_cookie){
			set_cookie(self.get_page_type(),current_subcategory);
		}
		
		var cookie_data = s_cookie.ids.replace("null","").replace(/^\,+|\,+$/g,'').split(',');
		
		if(cookie_data.length > 1){
			selecteds.addClass('compare');
			selecteds.find('a.select').text('Comparar produtos');
		}else{
			selecteds.removeClass('compare');
			selecteds.find('a.select').text('Selecione outros produtos');
		}
	};
	
	// envia o usuário para comparação
	this.goto_compare = function(){
		$('input#comparison-form-aux-id').val(s_cookie.ids.replace("null","").replace(/^\,+|\,+$/g,''));
		$('form#comparison-form-aux').submit();
	};
	
	// checa se o usuário já selecionou 5 ids de produto
	this.check_cookie_total = function(){
		if(!s_cookie){
			set_cookie(self.get_page_type(),current_subcategory);
		}
		
		var cookie_data = s_cookie.ids.replace("null","").replace(/^\,+|\,+$/g,'').split(',');
		if(cookie_data.length < 5){
			return true;
		}else{
			alert("Você pode comparar somente 5 produtos por vez");
			return false;
		}
	};
	
	// ação para os links "selecione e compare"
	this.select_product = function(e){
		// caso a categoria atual não seja a mesma do cookie
		if(!self.check_current_cookie()){
			// deleto o cookie
			self.erase_cookie();
			s_cookie = {category:current_subcategory,ids:''};
			// crio o cookie zerado
			self.set_cookie(self.get_page_type(), current_subcategory);
		}
		
		var label = $(this).parents('label');
		var nodeName = this.nodeName.toLowerCase();
		// caso o elemento clicado seja um link
		if(nodeName == 'a'){
			e.stopPropagation(); e.preventDefault();
			
			var checkbox = label.find('input:checked');
			var product_id = label.find('input').val();
			
			if(checkbox.size() == 0 && !label.attr('class')){
				if(self.check_cookie_total()){
				// marco o alemente como selecionado
					self.cookie_add_id(product_id);
					label.find('input')[0].checked = true;
					label.removeClass().addClass('selected');
					$(this).text('Selecione outros produtos');
				}else{
					$(this).reset();
				}
			}else if(label.attr('class') && label.attr('class').indexOf('compare') == -1){
				// coloco o elemento no estagio inicial
				self.cookie_rm_id(product_id);				
				$(this).reset();
			}else{
				// mando o usuário para comparação
				self.goto_compare();
			}
		}
		
		// caso o elemento clicado seja um checkbox
		if(nodeName == 'input'){
			var product_id = $(this).val();
			
			if($(this).is(':checked')){
				if(self.check_cookie_total()){
					self.cookie_add_id(product_id);
					label.removeClass().addClass('selected');
					$('a',label).text('Selecione outros produtos');
				}else{
					$(this).reset();
				}
			}else{
				self.cookie_rm_id(product_id);
				$(this).reset();
			}
		}
		
		self.update_compare(this);
	};
	
	// ordenação
	this.order_type = function(){
		var ord = $(this).val();
		location.href = ord;
	};
	
	// ordenação
	this.result_offset = function(){
		var param = "num="+ $(this).val();
		
		if(!param) return;
		
		if(location.href.match(/num=[^&]+/gi)){
			location.href = location.href.replace(/&?start=[0-9]{1,}/,'').replace(/num=[^&]+/gi,param);
		}else {
			var href = location.href.replace(/&?start=[0-9]{1,}/,'');
			location.href = href + ((href.indexOf('?') > -1) ? (href[href.length - 1] == '?' ?  '' : '&') : '?') + param;
		}
	};
	
	// pega o tipo da página (galeria|lista)
	this.get_page_type = function(){
		return $('#storeFront').attr('class');
	};
	
	// atualiza o tipo da página no cookie
	this.update_page_type = function(e){
		e.stopPropagation(); e.preventDefault();
		
		var type = $(this).attr('class');
		if(type == "lista"){
			page_type = "product-list";
		}else if(type == "galeria"){
			page_type = "product-galery";
		}
		
		var category = "";
		if(s_cookie.category != ""){
			category = s_cookie.category;
		}
		
		self.set_cookie(page_type, category);
		
		location.href = $(this).attr('href');
	};
	
	this.hide_evaluation = function(){
		$('div#boxAvaliacao').remove();	
	}
	
	// regras para avaliação do lojista na topCategorySeach
	this.show_evaluation = function(e){
		self.hide_evaluation();
		e.preventDefault(); e.stopPropagation();
		
		var box_aval = $("#storeFront");
		var id = $(this).attr("id");
		var parent = $(this).parents("li.merchandise");
		
		var parent_pos_x = parent.offset().left;
		var parent_pos_y = parent.offset().top;
		
		var max_pos_x = box_aval.offset().left + box_aval.width();
		
		var new_pos_x = parent_pos_x;
		var new_pos_y = 0;
		
		if(!id) return;
		
		var shop_evaluted = !$(this).parents('.contentNumLoja').hasClass('not_evaluted');
		
		$.getJSON('/loja.js?id='+ id,function(data){	
			$('#avaliacaoLoader').remove();
			
			var newClass = !shop_evaluted ? "not-evaluted" : (parseInt(data.finalscore) >= 50 ? "positive" : "negative");
			var pageSize = getPageSize();
			var pageScroll = getPageScroll();
			var html = new Array();
			
			html.push("<div id='boxAvaliacao' class='"+ newClass +"' style='display: none;'>");
			html.push("<div id='top'><h2>Informações sobre a loja</h2><a href='#fechar' title='Fechar' class='close' rel='nofollow'>Fechar</a></div>");
			html.push("<div id='column1'>");
			html.push("<p class='loja'>"+ ((data.logo != "") ? "<img src='"+ data.logo +"' />" : data.name) +"</p>");
			
			if(shop_evaluted){
				html.push("<dl>");
				html.push("<dt>Cumpre os Prazos de Entrega:</dt>");
				html.push("<dd><p>"+ data.score1 +"%</p>");
				html.push("<span class='greycheck'><span class='greencheck' style='width: "+ data.score1 +"%'></span></span></dd>");
				html.push("<dt>Respeita o preço anunciado:</dt>");
				html.push("<dd><p>"+ data.score2 +"%</p>");
				html.push("<span class='greycheck'><span class='greencheck' style='width: "+ data.score2 +"%'></span></span></dd>");
				html.push("<dt>Excelência no atendimento:</dt>");
				html.push("<dd><p>"+ data.score3 +"%</p>");
				html.push("<span class='greycheck'><span class='greencheck' style='width: "+ data.score3 +"%'></span></span></dd>");
				html.push("<dt>Respeita código do consumidor:</dt>");
				html.push("<dd><p>"+ data.score4 +"%</p>");
				html.push("<span class='greycheck'><span class='greencheck' style='width: "+ data.score4 +"%'></span></span></dd></dl>");
				html.push("<a href='http://st.shopping.uol.com.br/avaliacao-de-loja.html' class='veja' rel='nofollow'>Veja como foi feita a avaliação</a>");
			}
			
			html.push("</div>");
			html.push("<div id='column2'>");
			html.push("<p class='data'>No Shopping desde:<span>"+ data.subscriptiondate +"</span></p>");
			
			if(shop_evaluted) html.push("<div class='perctotal'><h3>"+ data.finalscore +"%</h3><p class='indice'>Índice de satisfação</p></div>");
			
			html.push("</div>");
			
			if(!shop_evaluted) html.push("<p class='not-evaluted-message'>Loja não avaliada</p>");
			
			html.push("</div>");
			
			$(box_aval).prepend(html.join(''));
			
			var box_avaliacao = $('#boxAvaliacao');
			if($("#product-list").size() > 0){
				box_avaliacao.css({
					"left": "100%",
					"top": parent_pos_y - (($.browser.msie && $.browser.version == 6) ? -120 : 70),
					"margin-left": "-400px"
				});
			}else{
				var pos_x = parent_pos_x - $("#product-galery").width() - 141;
				console.debug(pos_x);
				if(pos_x > -400) pos_x = -400;
				box_avaliacao.css({
					"left": "100%",
					"top": parent_pos_y - (($.browser.msie && $.browser.version == 6) ? -120 : 70),
					"margin-left": pos_x
				});
			}
			
			box_avaliacao.fadeIn();
			
			var contentNumLojaY = box_avaliacao.offset().top;
			var positionYAval = contentNumLojaY + parseInt(box_avaliacao.height());
			var positionYPage = pageSize.windowHeight + pageScroll.yScroll;
			
			if(positionYAval > positionYPage){
				var diff = positionYAval - positionYPage;
				var currentPos = positionYPage;
				var finalPos = pageScroll.yScroll + diff + parseInt($('#boxAvaliacao').css('top'));
				window.scrollTo(0,finalPos);
			}
			
			box_avaliacao.find('a.close').click(function(e){
				e.stopPropagation(); e.preventDefault();
				self.hide_evaluation();
			});
			
			box_avaliacao.find('a.veja').click(function(e){
				e.stopPropagation(); e.preventDefault();
				window.open($(this).attr('href'));
			});
			
			box_avaliacao.mousemove(function(){
				$(document).unbind('click');
			});
			
			box_avaliacao.mouseout(function(){
				$(document).click(function(){
					self.hide_evaluation();
				});
			});
			
			$(document).keyup(function(e){
				if(box_avaliacao.size() > 0){
					if(e.keyCode == 27){
						self.hide_evaluation();
					}
				}
			});
		});
	}
	
	this.click_ps_info = function(e){
		e.stopPropagation(); e.preventDefault();
		
		if($(this).hasClass('redirpagseguro')) return;
		
		window.open('http://click.uol.com.br/?rf=shop_ps_mouseover&u=http://www.pagseguro.uol.com.br');
	}
	
	this.show_ps_info = function(e){
		var ps_info = $(this).parents('.product-info').find('var.bl');
		$('var.bl').hide();
		ps_info.show();
	}
	
	this.hide_ps_info = function(e){
		e.preventDefault();
		$('var.bl').hide();
	}
	
	
	$.fn.extend({
		reset: function(){
			$(this).parents('label').find('input').removeAttr('checked');
			$(this).parents('label').removeAttr('class');
			$(this).parents('label').find('a').text('Selecione e compare');
		}
	});
	
	this.init();
});

$(window).load(function(){
	$('.zoom').remove();
});

// erro nas imagens
function image_error(img){
	$(img).parents('a.image').removeClass('thickbox').addClass('img_error');
	if($(img).parents('a.image').size() > 0){
		$(img).parents('a.image').attr('href').replace(/(top|width|height)=[a-z0-9]+&?/gim,'');
	}
	
	// atribui ações aos links de imagem
	$('.image span.zoom').remove();
	
	if($("#titleTopCategory").size() > 0){
		$('.product .image:not(.img_error)').mouseover(self.addzoom);
	}else{
		$('.image:not(.img_error)').mouseover(self.addzoom);
	}
	
	var new_url = $(img).parents('a.image').next('h3').find('a').attr('href');
	$(img).parents('a.image').attr('href',new_url);
	
	var cDepto = $('#boxProduct').attr('class') || $(img).parents('div').attr('class').replace(/.*cat-([^\s"]+)/gim,"$1");
	var reg_test = /(.*(\-|\/))?nao(_|\-)disponivel\d+\.gif/gi;
	var imageNotFoundUrl = "http://shopp.img.uol.com.br/v2006/nao_disponivel/" + cDepto + "-nao-disponivel100.gif";
	
    if(!reg_test.test(img.src)){
		img.src = imageNotFoundUrl;
    }else{
		imageNotFoundUrl = "http://shopp.img.uol.com.br/v2006/nao_disponivel/nao-disponivel100.gif";
		if(!reg_test.test(img.src)){
		    img.src = imageNotFoundUrl;
		}else{
		    img.src = '';
		}
		img.onerror = null;
    }
	
    return;
}




























