jQuery.getCookie = function(Name) {
	var re=new RegExp(Name+"=[^;]+", "i");
	if (document.cookie.match(re))
	return document.cookie.match(re)[0].split("=")[1];
	return null;
}

jQuery.setCookie = function(name, value) {
	document.cookie = name + "=" + value;
}

$(function() {

    /* tirando a borda do ultimo elemento do menu */
    $('#menuPrincipal ul li a').last().css('border-right', 'none');

    $('ul#menuTopo li a').last().css('border-right', 'none');

    /* tirando a borda do ultimo elemento do menu */
    $('ul#menuRodape li a').last().css('border-right', 'none');

	$('#menuKoralle li:last,#menuKoralle li:last a').css('width', '133px');
	$('#menuKoralle li a:first').css('border-left', 'none');


	/**************************************
		Percorre por todos os endereços
		e coloca borda apenas nos
		endereços centralizados.
		Caso tenha menos de 3 endereços
		em uma linha, soh tera borda
		o segundo endereço, e ainda assim
		apenas à esquerda.
		Caso tenha apenas 1 endereço,
		não haverá borda
	***************************************/
	var endBox = $(".bordaBox").length;
	for(var i = 1; i < endBox; i+= 3) {
		$(".bordaBox").eq(i).css({"borderLeft":"1px solid #ccc","borderRight":"1px solid #ccc"});
	}
	$(".bordaBox:last").css('borderRight','0');

	/***********************************
		* função para aumentar
		* ou comprimir o menu de acordo
		* com o numero de itens
	***********************************/
	var valor = $("#menuTopo li a").size();
	if(valor > 2) {
		$("#menuTopo").css({"width":"274px"})
	}
	else {
		$("#menuTopo").css("width","167px")
	}
	/********************************
		faq  animação
		esconder/ver respostas
	********************************/
	$("dl.perguntas dt").each(function(i) {
		$(this).toggle(
		function() {
			$(this).css('backgroundPosition','0 -10px')
			$(this).siblings('dd').eq(i).slideDown()
		},
		function() {
			$(this).css('backgroundPosition','0 3px')
			$(this).siblings('dd').eq(i).slideUp()
		});
	});

	/***********************************
		* função para sumir e exibir
		* mais itens do menu lateral
	***********************************/
	$("div.nav a.verTodas").toggle(
	function() {
		$(this).prev().find("li.hidden").slideDown()
		$(this).text("ver todos [-]")
	},
	function() {
		$(this).prev().find("li.hidden").slideUp()
		$(this).text("ver todos [+]")
	});


	/*******************************************
		* função external que pega todos
		* os links com o attr rel e chama a
		* sua url em uma nova janela
	*******************************************/
	$("a[rel='external']").click(function() {
		window.open($(this).attr('href'))
		return false;
	});


	try{
		$('.star, .starOpiniao, .starVotos').rating();
	}catch(e){}

	$("#primario ul.menuCategorias li:first,#rodape div.copyright ul.menuCategorias li:first").css('background','none')


	/**ativar e desativar background sobre o menu no topo**/
	try {
		$(".ativo").width("125px");
		$("a",$("#menuKoralle li")).each(function(i) {
			$(this).click(function() {
				var largura = $(this).width() + "px";
				$(".ativo").remove();
				$(this).before("<div class='ativo'>")
				$(".ativo").width(largura);
			});
		});
	}catch(e){}

	/***criando margin na primeira linha da tabela***/
	$(".historicoPedidos tbody tr:first td").css('paddingTop','20px');

	$("table.tabelaCarrinho thead th:first").css({'textAlign':'left',"padding":"0 0 0 10px"});


	/**apenas pra o ie alinhar o campo da imagem para a esquerda**/
	$("a.item-lista").parent().css("text-align","left");

	/***centralizando imagem no ie***/
	var top_margin = (70 - $('.item-lista img').height()) / 2;
	$('.item-lista img').css( 'margin-top' , top_margin);


	/***********************************
		função para exibir e esconder
		os itens do menu de categorias
	************************************/
	var menu = $(".menuLateral");
	$(".nav h4 span").each(function(index) {
		$(this).toggle(
		function() {
			// Fecha todos os demais
			$('.nav h4 span.accordion-selected').trigger('click');
			$.setCookie('menu-selected', index);
			$(this).addClass('accordion-selected');
			$(this).css('backgroundPosition','0 -24px');
			menu.eq(index).slideDown();
		},
		function() {
			$(this).css('backgroundPosition','0 0');
			$(this).removeClass('accordion-selected');
			$.setCookie('menu-selected', '');
			menu.eq(index).slideUp();
		});
	});
	var selected = $.getCookie('menu-selected');
	if (selected != null) {
		$('.nav h4 span:eq('+selected+')').trigger('click');
	}


	/***********************************
		função para
		determinar a qtd
		de colunas na listagem
		de produtos
	*************************************/
	if($("#maisvendidos").is(':visible')) {
		$(".novaCategoriaProdutos").css({
			"width":"576px",
			"margin":"0"
		});

		$(".miolo").css(
		{
			'float':'left',
			'width':'576px'
		});

		$(".listaProdutos,.navigation").css(
		{
			'width':'576px',
			'float':'none'
		});
	}
	else {
		$(".conteiner-depto").css(
		{
			'width':'434px',
			'float':'right',
			'marginRight':'7px'
		});
	}


	/***********************
		cursos e noticias
		trocar a cor do box
		caso for noticias
	************************/
	if($(".current h3:contains(\"Notícias\")").length > 0) {
		$(".detalheImagem").css('background','#ffffff');
	}

	/************************************
		Se o site n está na loja
		virtual n renderizar o carrinho
		************************************
		function visible(obj) {
		if(obj.is(':visible')) {
		$(".compras").css('visibility','visible');
		}
		}
		//visualizando o carrinho
		visible($(".boxCategorias"));
		visible($(".ultimoPedido"));
		visible($(".compra"));
		visible($(".historicoPedidos"));
		visible($("#ClienteAddForm"));
	*/

	//compartilhe com facebook ou twitter
	$("a[rel=\"facebook\"],a[rel=\"twitter\"]").click(function(e) {
		e.preventDefault();
		var rel = $(this).attr('rel');
		var url = encodeURIComponent(window.location.href);

		if(rel == 'facebook') {
			$(this).attr('href','http://www.facebook.com/sharer.php?u='+url);
			window.open('http://www.facebook.com/sharer.php?u='+url,'','width=400,height=450');
		}
		else {
			var title = $('div.current h3').html();
			url = encodeURIComponent(title) + '+' + url + encodeURIComponent(' via @korallearte');
			$(this).attr('href','http://twitter.com/home?status='+url);
			window.open('http://twitter.com/home?status='+url,'','width=400,height=450');
		}
	});

	/***verticalizando a imagem dos produtos no ie7***/
	if(navigator.userAgent.indexOf('MSIE 7.0') != -1) {
		$("a.blocoProduto").css({"display":"block"});
		$("a.blocoProduto img").each(function(i) {
			var height = (180 - $(this).height()) /2;
			$(this).css('marginTop',height);
		});


		$(".boxVerticalImage img").each(function(i) {
			var height = (203 - $(this).height()) /2;
			$(this).css('marginTop',height);
		});
	}

	/***animação menu de empresas no topo***/
	$("#menuEmpresas li a span").each(function(i) {
		var txt = $(this).text()
		$(this).css('background',txt)
	});

	if ($('#menuEmpresas').length == 0) {
		var box = $('#banner div.boxImagemarca');
		var color = $('span', box);
		box.css({'float': 'right', 'background': color.html()});
		color.remove();
	}

	// Preload de imagens
	$('#menuEmpresas li a').each(function(i, element) {
		var img = $(element).attr('rel');
		$('<img/>').attr('src', img);
	});

	$("#menuEmpresas li").each(function(i) {
		var txt = $(this).find('span').text();
		$(this).find('span').css('background',txt);

		$(this).hover(
		function() {
			var image = $(this).find('a').attr('rel');
			$(this).css('background',txt)
			$(this).find('a').css('background',txt);
			$('.boxVerticalImage').css('background',txt);
			$('.boxVerticalImage').find('img').attr('src',image)
			$('.boxVerticalImage').find('img').css('display','block')
		},
		function() {
			var image = $(this).find('a').attr('rel');
			$(this).find('a').css('background','#ededed');
			$(this).find('span').css('background',txt);
			$(this).css('background','none');
			$('.boxVerticalImage').find('img').css('display','none')
			$('.boxVerticalImage').css('background','none');
		});

	});

	$('.boxVerticalImage img').each(function(i) {
		$(this).error(function() {
			$(this).css('display','none');
		});

	});


	/*****************
		abrir modal
		ao carregar
		o site www.casadodesenho.com.br
	******************/	
	if(window.location.host.toString().match(/(www\.)?casadodesenho\.com\.br/)){
		// Abre modal
		modal();
		// Redireciona em X segundos
		setTimeout(function(){window.location=window.location.toString().replace(/(www.)?casadodesenho\.com\.br/,"www.koralle.com.br");},6000);
	}




});
var grey;
var box;

function modal() {
	var screenW = $(window).width();
	var screenH = $(window).height();

   	grey = $("<div>",{
   		css:({
			"position":'absolute',
			"top":'0px',
			"left":'0px',
			"zIndex":2,
			"opacity":0.9,
			"background":'#000',
			"width":$(document).width(),
			"height":$(document).height()
		})
   	}).appendTo("body");

	box = $("<div>",{
		css:({
			"position":'absolute',
			"width":'400px',
			"height":'250px',
			"top":screenH/2 - 250 / 2,
			"left":screenW/2 - 400 / 2,
			"border":'3px solid #000',
			"background":"#fff",
			"zIndex":3,
			"padding":'10px'
		}),
		html:$("<a>",{
			text:'X',
			css:({
				"color":"#333",
				"font":'bold 22px Trebuchet MS',
				"float":'right'
			}),
			click:fechar
		})

	}).appendTo("body");

	content = $("<div>",{
		css:({"clear":'both'})

	}).appendTo(box);

	$(content).addClass('boxModal');



	$('.boxModal').append('<p>www.casadodesenho.com.br<span>agora é</span></p>');
	$('.boxModal').append("<a href='http://www.koralle.com.br'><big>www.koralle.com.br</big></a>");
}
function fechar(){
	$(grey).next().andSelf().remove();

}



