function showEspiar(pf_id, dept_id, templatePath, attr_value){
	
	var espiar = document.getElementById('espiar');
	document.getElementById('sku').value = '';
	if(espiar.style.display == "none" || espiar.style.display == ""){
		carregaProdutoEspiar(pf_id, dept_id, templatePath, true);
		espiar.style.display = "block";
		espiar.style.visibility = "visible";
	}else{
		espiar.style.display = "none";
		espiar.style.visibility = "hidden";
	}

}

function carregaProdutoEspiar(pf_id, dept_id, templatePath, pri_vez){
	var cAjax = new Ajax();
	
	//mostra tela de carregando
	//loading(true);

	cAjax.onStateChange = function (classState, httpState, retornoHTML, retornoXML) {
	    if (httpState == 200) {
	        var jsDados = eval('(' + retornoHTML.toString() + ')');
	        var temAttr1 = !(jsDados[0].attr_label2 == '' || jsDados[0].attr_label2 == null); // verifica se tem atributo 1
	        var temAttr2 = !(jsDados[0].attr_label1 == '' || jsDados[0].attr_label1 == null); // verifica se tem atributo 2 
	        var html1 = '';
	        var html2 = '';
	        var strExisteAttr1 = '';
	        var strExisteAttr2 = '';

	        // if (pri_vez) {
	        //    teste(jsDados, templatePath);
	        //    document.getElementById('attr_value1').value = "";
	        //    document.getElementById('attr_value2').value = "";
	        //}


	        document.getElementById('espiar_titulo').innerHTML = "<h1>" + jsDados[0].name + "</h1>";
	        document.getElementById('pf_id').value = pf_id;
	        document.getElementById('linkProduto').href = "product.asp?pf_id=" + pf_id + "&dept_id=" + dept_id;
	        document.getElementById('hidden_dept_id').value = dept_id;
	        document.getElementById('attr_label1').value = jsDados[0].attr_label1;
	        document.getElementById('attr_label2').value = jsDados[0].attr_label2;


	        if (temAttr1)
	            html1 = '<ul>';


	        if (temAttr2) {
	            html2 = '<ul>';
	            if (pri_vez)
	                document.getElementById('attr_value2').value = jsDados[0].variant[0].attr_value2;
	        }


	        if (jsDados[0].bonus != 0 && jsDados[0].displaybonus == "S") {
	            document.getElementById('bonus_text').style.display = "";
	            document.getElementById('bonus').innerHTML = jsDados[0].bonus;
	        } else {
	            document.getElementById('bonus_text').style.display = "none";
	        }


	        if (jsDados[0].attr_label1 == null && jsDados[0].attr_label2 == null) {
	            document.getElementById('sku').value = pf_id;
	        }

	        for (i in jsDados[0].variant) {
	            var msgForaEstoque = ""; //variável que guarda a mensagem caso a variante esteja fora de estoque
	            var classForaEstoque = ""; //variável que guarda o estilo caso a variante esteja fora de estoque
	            var classe1 = "";
	            var classe2 = "";
	            var attr2 = "";

	            if ((jsDados[0].ExibeProdForaEstoque == "S") || (jsDados[0].disponibilidade == null || jsDados[0].VendeProdForaEstoque == "N")) {
	                document.getElementById('prazo_text').style.display = "none";
	            }
	            else {
	                document.getElementById('prazo_text').style.display = "";
	                if (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp == "P" && (jsDados[0].availability != null || jsDados[0].availability != "") && jsDados[0].variant[i].quantity <= 0) {
	                    document.getElementById('prazo_disponibilidade').innerHTML = jsDados[0].availability;
	                }
	                if (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp != "P" && jsDados[0].variant[i].quantity <= 0) {
	                    document.getElementById('prazo_disponibilidade').innerHTML = jsDados[0].PrazoProdForaEstoque;
	                }
	            }

	            if (jsDados[0].attr_label1 != null) {
	                if (!existeNaLista(strExisteAttr1, jsDados[0].variant[i].attr_value1, '|') && document.getElementById('attr_value2').value == jsDados[0].variant[i].attr_value2) {
	                    strExisteAttr1 += jsDados[0].variant[i].attr_value1 + '|';

	                    if (jsDados[0].VendeProdForaEstoque == "N" && jsDados[0].variant[i].quantity <= 0 || jsDados[0].bloqueado == "P") {
	                        msgForaEstoque = ' (Indisponível, avise-me quando chegar.)';
	                        classForaEstoque = 'indisponivel';
	                        classe1 = ' class="indisponivel" ';
	                    }

	                    if (!pri_vez && jsDados[0].variant[i].attr_value1 == document.getElementById('attr_value1').value || jsDados[0].variant[i].default_var == 1 && pri_vez) {
	                        classe1 = ' class="selecionado"';
	                        if (pri_vez) {
	                            changeVariant(jsDados[0].variant[i].attr_value1, document.getElementById("attr_value2").value, templatePath, dept_id);
	                        }
	                        if ((jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp == "P" && jsDados[0].disponibilidade != "") || (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp != "P") || (jsDados[0].bloqueado != "P")) {
	                            if ((jsDados[0].bloqueado == "P")) {
	                                document.getElementById('bt_comprar').src = templatePath + "/bt_reservar.gif"
	                            }

	                            if (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp == "P" && (jsDados[0].availability != null || jsDados[0].availability != "")) {
	                                document.getElementById('prazo_disponibilidade').innerHTML = jsDados[0].availability;
	                            }
	                            if (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp != "P" && jsDados[0].quantity <= 0) {
	                                document.getElementById('prazo_disponibilidade').innerHTML = jsDados[0].PrazoProdForaEstoque;
	                            }

	                            if (jsDados[0].variant[i].quantity <= 0 && jsDados[0].ExibeProdForaEstoque == "S") {
	                                document.getElementById('link_comprar').href = "javascript:setEncomenda();";
	                                document.getElementById('bt_comprar').src = templatePath + "/bt_encomendar.gif"
	                            }
	                            else {
	                                document.getElementById('link_comprar').href = "javascript:setVenda();";
	                                document.getElementById('bt_comprar').src = templatePath + "/bt_comprar.gif"
	                            }
	                        }

	                    }
	                    html1 += '<li name="li_attr1" ' + classe1 + ' id="li_attr1_' + jsDados[0].variant[i].attr_value1 + '"><a href="javascript:changeVariant(\'' + jsDados[0].variant[i].attr_value1 + '\',\'' + document.getElementById("attr_value2").value + '\',\'' + templatePath + '\',\'' + dept_id + '\');">' + jsDados[0].variant[i].attr_value1 + '</a></li>';



	                }
	            }



	            if (jsDados[0].attr_label2 != null) {
	                if (!existeNaLista(strExisteAttr2, jsDados[0].variant[i].attr_value2, '|')) {
	                    if (!pri_vez && jsDados[0].variant[i].attr_value2 == document.getElementById('attr_value2').value)
	                        classe2 = ' class="selecionado"';
	                    strExisteAttr2 += jsDados[0].variant[i].attr_value2 + '|';
	                    html2 += '<li name="li_attr2" ' + classe2 + ' id="li_attr2_' + jsDados[0].variant[i].attr_value2 + '" ><a href="javascript:changeVariant(\'' + jsDados[0].variant[0].attr_value1 + '\',\'' + jsDados[0].variant[i].attr_value2 + '\',\'' + templatePath + '\',\'' + dept_id + '\');"><img src="../assets/attribute_images/mini/' + jsDados[0].variant[i].attr_image_file + '" border="0" vspace="3" /></a></li>';
	                }
	            }

	        }

	        if (temAttr1)
	            html1 += '</ul>';
	        if (temAttr2) {
	            html2 += '</ul>';
	            document.getElementById("variante2").innerHTML = html2;
	            if (pri_vez)
	                document.getElementById('li_attr2_' + jsDados[0].variant[0].attr_value2).className = "selecionado";
	        }

	        document.getElementById("variante1").innerHTML = html1;



	        var abaDescricao = "<li><a href=\"#javascript;\" id=\"A:1\" style=\"cursor: pointer;\"";
	        abaDescricao += " onClick=\"changeTab(':2', '" + pf_id + "'); ChangeBackground(this,'a', 1,'" + templatePath + "');\"";
	        abaDescricao += "><span id=\"S:3\" onClick=\"javascript:ChangeBackground(this,'span', 1,'" + templatePath + "');\">:4</span></a></li>";

	        var abaPrincipal = "<li><a href=\"#javascript;\" id=\"A0\" style=\"cursor: pointer;\""
	        abaPrincipal += " onClick=\"changeTab(0,'" + pf_id + "'); ChangeBackground(this,'a', 1,'" + templatePath + "');\"";
	        abaPrincipal += "><span id=\"S0\" onClick=\"javascript:ChangeBackground(this,'span', 1,'" + templatePath + "');\">Descri&ccedil;&atilde;o</span></a></li>";

	        document.getElementById('abas_descricao').innerHTML = abaPrincipal;

	        for (var i in jsDados[0].descricao_complementar) {
	            var indice = parseInt(i) + 1;
	            var tempAba = abaDescricao.replace(":1", indice);
	            tempAba = tempAba.replace(":2", jsDados[0].descricao_complementar[i].info_id);
	            tempAba = tempAba.replace(":3", indice);
	            tempAba = tempAba.replace(":4", jsDados[0].descricao_complementar[i].title);
	            document.getElementById('abas_descricao').innerHTML += tempAba;
	        }

	        document.getElementById('descricao').innerHTML = jsDados[0].description;

	        loading(false);
	    } else {
	        alert(msgErro);
	    }

	}
	cAjax.load('product_espiar.asp','dept_id=' + dept_id + '&pf_id=' + pf_id, 'GET');
}


function changeVariant(attr1, attr2, templatePath, dept_id){
	var cAjax = new Ajax();
	var pf_id = document.getElementById('pf_id').value;
	document.getElementById('sku').value = '';
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");		
	var all_li = document.getElementsByTagName('li');
	for(i=0;i<all_li.length;i++){
		if (all_li[i].getAttribute('name') == 'li_attr1' || all_li[i].getAttribute('name') == 'li_attr2'){ 
			all_li[i].className = '';
		}
	}
	

	if (attr1 != null  || (attr1 != null && attr2 != null)) {
		document.getElementById('attr_value1').value="";
		document.getElementById('attr_value1').value=attr1;
	
		if (attr2 != null){
			document.getElementById('attr_value2').value="";			
			document.getElementById('attr_value2').value=attr2;
		}

		carregaProdutoEspiar(pf_id, dept_id, templatePath, false);

		cAjax.onStateChange = function(classState, httpState, retornoHTML, retornoXML){
			if (httpState == 200) {
				var jsDados = eval('(' + retornoHTML.toString() + ')');
				if (jsDados != null) {
					montaImagemPreco(jsDados, templatePath);
					document.getElementById('sku').value = jsDados[0].sku;					
				}			
			}
			else {
				alert(msgErro);
			}
			
		}
		cAjax.load('product_espiar_variante.asp', 'attr_value1=' + attr1 + '&attr_value2=' + attr2 + "&pf_id=" + pf_id, 'POST');
	}
}


function existeNaLista(strList, strValue, strSep)
{
    /*
     * Função que verifica a existencia de um atributo em uma lista de atributos.
     * Parâmetros:
     *      strList [String]   = Lista de Atributos
     *      strValue[String]   = Valor do Atributo a ser consultado
     *      strSep  [String]   = Separador da lista, que separa um atributo do outro. 
     * Retorno      [Boolean]  = true ou false
     */
    var aList = strList.split(strSep)
    for(var x=0; x<aList.length; x++)
    {
        if(aList[x] == strValue)
        {
            return true;
        }
    }
    return false;
}



function montaImagemPreco(jsDados, templatePath){
	document.getElementById('espiar_foto').src = jsDados[0].image_file;	
	
	for(var i in jsDados[0].variant){
		var quantityVariant = jsDados[0].variant[i].quantity; 
	}
	
	if ((jsDados[0].ExibeProdForaEstoque == "N")||(jsDados[0].quantity > 0)||(jsDados[0].disponibilidade == null || jsDados[0].VendeProdForaEstoque == "N")) {
		document.getElementById('prazo_text').style.display = "none";
	}
	else {
		document.getElementById('prazo_text').style.display = "";
	}	
	
	document.getElementById('espiar_preco').style.display = "";
    if (jsDados[0].on_sale && jsDados[0].template_tipo == "B2C") {
        document.getElementById('price_text1').style.display = "";
        document.getElementById('economize_text').style.display = "";
        document.getElementById('espiar_preco1').innerHTML = jsDados[0].list_price;
        document.getElementById('espiar_preco2').innerHTML = jsDados[0].sale_price;
        if (jsDados[0].DescontoAvista > 0){
			document.getElementById('desconto_avista').innerHTML = jsDados[0].Desconto_a_vista;
			}
        if (jsDados[0].parcela_semjuros > 1) {
			document.getElementById('price_text3').style.display = "";
			document.getElementById('espiar_vezes').innerHTML = jsDados[0].parcela_semjuros;
		}
		else 
			document.getElementById('price_text3').style.display = "none";
        document.getElementById('produto_preco').innerHTML = jsDados[0].preco_parcelado;
        document.getElementById('economize').innerHTML = jsDados[0].economize;

    }
    else {
        document.getElementById('price_text1').style.display = "none";
        document.getElementById('economize_text').style.display = "none";
        if (jsDados[0].template_tipo == "B2B")
			document.getElementById('espiar_preco2').innerHTML = jsDados[0].list_price_b2b;
		else
			document.getElementById('espiar_preco2').innerHTML = jsDados[0].sale_price;
				
        if (jsDados[0].DescontoAvista > 0){
			document.getElementById('desconto_avista').innerHTML = jsDados[0].Desconto_a_vista;
			}
        if (jsDados[0].parcela_semjuros > 1) {
			document.getElementById('price_text3').style.display = "";
			document.getElementById('espiar_vezes').innerHTML = jsDados[0].parcela_semjuros;
			document.getElementById('produto_preco').innerHTML = jsDados[0].preco_parcelado;
		}
		else {
		document.getElementById('price_text3').style.display = "none";
        document.getElementById('produto_preco').innerHTML = jsDados[0].preco_parcelado;
        }
        }  
   }      
 	

function mudaBotaoOver(botao, templatePath){
	if (botao.src.indexOf('bt_comprar', 0) != -1){
		botao.src = templatePath + '/bt_comprar_over.gif';
	}
}

function mudaBotaoOut(botao, templatePath){
	if (botao.src.indexOf('bt_comprar', 0) != -1){
		botao.src = templatePath + '/bt_comprar.gif';
	}
}


function setVenda(){
	var pf_id = document.getElementById('pf_id').value;
	attr_value1 = document.getElementById('attr_value1').value;
	attr_value2 = document.getElementById('attr_value2').value;
	var sku = document.getElementById('sku').value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");	
	if (sku == null || sku == "") {
		var HTMLErro = '<div class="erro_cor">É necessário selecionar '; //guarda o erro pelos atributos
		if (attr_value1 == null || attr_value1 == '') 
			HTMLErro += document.getElementById('attr_label1').value;
		
		if (attr_value2 == null && hasTwoVariants) 
			if (attr_value1 == null || attr_value1 == '') 
				HTMLErro += ' e ' + document.getElementById('attr_label2').value;
			else 
				HTMLErro += document.getElementById('attr_label2').value;
			
		HTMLErro += ' do seu produto</div>';
		
		document.getElementById("erro_cor").innerHTML = HTMLErro;
	}
	else {
		document.getElementById('attr_value1').value = attr_value1;
		document.getElementById('attr_value2').value = attr_value2;
		document.frm_espiar.action = document.getElementById('action_venda').value;
		document.frm_espiar.submit();
	}
	
}

function setEncomenda(){
	var pf_id = document.getElementById('pf_id').value;
	attr_value1 = document.getElementById('attr_value1').value;
	attr_value2 = document.getElementById('attr_value2').value;
	var sku = document.getElementById('sku').value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");	
   if (sku == null || sku == "") {
		var HTMLErro = '<div class="erro_cor">É necessário selecionar '; //guarda o erro pelos atributos
		if (attr_value1 == null || attr_value1 == '') 
			HTMLErro += document.getElementById('attr_label1').value;
		
		if (attr_value2 == null && hasTwoVariants) 
			if (attr_value1 == null || attr_value2 == '') 
				HTMLErro += ' e ' + document.getElementById('attr_label2').value;
			else 
				HTMLErro += document.getElementById('attr_label2').value;
		
		HTMLErro += ' do seu produto</div>';
		
		document.getElementById("erro_cor").innerHTML = HTMLErro;
	}
	else {
		document.frm_espiar.action = document.getElementById('action_encomendar').value;
		document.frm_espiar.submit();
	}
}


function loading(loading){
	if(loading){
		document.getElementById("loading").style.display = "";
		document.getElementById("loading").style.visibility = "visible";
	}else{
		document.getElementById("loading").style.display = "none";
		document.getElementById("loading").style.visibility = "hidden";
	}
}


function getPosicaoElemento(elemID){
    var offsetTrail = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    var offsetWidth = offsetTrail.offsetWidth;
    var offsetHeight = offsetTrail.offsetHeight; 
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop, height:offsetHeight, width:offsetWidth};
}

function capmouse(e){
    // captures the mouse position
    var espiar = document.getElementById('espiar');
    if (espiar.style.display == "block"){
		posx = 0; posy = 0;
		if (!e){var e = window.event;}
			if (e.pageX || e.pageY){
				posx = e.pageX + document.body.scrollLeft;
				posy = e.pageY + document.body.scrollTop;
			}
			else if (e.clientX || e.clientY){
				posx = e.clientX + document.body.scrollLeft;
				posy = e.clientY + document.body.scrollTop;
			}
	}	
}

function escondeEspiar(){
    if (document.getElementById("espiar").style.display == "block"){
        var minX = parseInt(getPosicaoElemento("espiar").left);
        var minY = parseInt(getPosicaoElemento("espiar").top);
        var maxX = parseInt(getPosicaoElemento("espiar").left + getPosicaoElemento("espiar").width);
        var maxY = parseInt(getPosicaoElemento("espiar").top + getPosicaoElemento("espiar").height);
   		var isIE = !!document.all && !!window.attachEvent && !window.opera;
        var posDivTop = 0;
        var posDivFoot = 0;

        posx = parseInt(posx);
        posy = parseInt(posy);
        if (isIE) {
            posDivTop = minY;
            posDivFoot = maxY;
        }else{
            posDivTop = minY + parseInt(document.body.scrollTop);
            posDivFoot = maxY + parseInt(document.body.scrollTop);    
        }
        if (posx < minX || posy < posDivTop || posx > maxX || posy > posDivFoot){
            document.getElementById("espiar").style.display = "none";  
        }
    }
}

