//para corrigir um problema de implementação do document.getElementById para o IE
if (/msie/i.test (navigator.userAgent)) //only override IE
{
    document.nativeGetElementById = document.getElementById;
    document.getElementById = function(id)
    {
        var elem = document.nativeGetElementById(id);
        if(elem)
        {
            //make sure that it is a valid match on id
            if(elem.id == id)
            {
                return elem;
            }
            else
            {
                //otherwise find the correct element
                for(var i=1;i<document.all[id].length;i++)
                {
                    if(document.all[id][i].id == id)
                    {
                        return document.all[id][i];
                    }
                }
            }
        }
        return null;
    };
}


function showEspiar(pf_id, dept_id, templatePath, attr_value,store){
	
	var espiar = document.getElementById('espiar');
	document.getElementById('sku').value = '';
	if(espiar.style.display == "none" || espiar.style.display == ""){
		carregaProdutoEspiar(pf_id, dept_id, templatePath, attr_value,store);
		
		moverEspiar();
		$(window).bind('resize scroll', function () {
			moverEspiar();
		})
	}else{
		$(window).unbind('resize scroll');
		espiar.style.display = "none";
	}
	
	
	function moverEspiar()
	{
		var scrollTop = 0, scrollLeft = 0;
		if (jQuery.browser.msie) {
			scrollTop = document.body.scrollTop;
			scrollLeft = document.body.scrollLeft;
		}
		espiar.style.display = "block";
		espiar.style.top = ((document.body.clientHeight - espiar.offsetHeight) / 2) + scrollTop + "px";
		espiar.style.left = ((document.body.clientWidth - espiar.offsetWidth) / 2) + scrollLeft + "px";
	}
	
}

function carregaProdutoEspiar(pf_id, dept_id, templatePath, attr_value,store){	
	var cAjax = new Ajax();
	//mostra tela de carregando
	loading(true);

	cAjax.onStateChange = function(classState,httpState,retornoHTML,retornoXML){		
		if(httpState == 200) {
			var jsDados = eval(retornoHTML);
			
			document.getElementById('espiar_titulo').innerHTML = "<span class='espiar_titulo'> " + jsDados[0].name + "</span>";

		
			montaImagemPreco(jsDados, templatePath.substr(3));
			
			document.getElementById('pf_id').value = pf_id;
			document.getElementById('linkProduto').href = "product.asp?pf_id=" + pf_id + "&dept_id=" + dept_id + "&store="+store;
			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 (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";
			}	

			var cboAttrValue1 = document.getElementById('cboAttrValue1');
			var cboAttrValue2 = document.getElementById('cboAttrValue2');
			
			for(var i = cboAttrValue1.length - 1; i >= 0 ; i--)
				cboAttrValue1.options[i] = null;

			for(var i = cboAttrValue2.length - 1; i >= 0 ; i--)
				cboAttrValue2.options[i] = null;

			if(jsDados[0].attr_label1 == null){
				document.getElementById('variante1').style.display = "none";
			}else{
				document.getElementById('variante1').style.display = "";
				document.getElementById('img1').alt = "Passo 1";
				document.getElementById('img1').src = templatePath.substr(3) + "/var_1.gif";
				document.getElementById('img3').alt = "Passo 2";
				document.getElementById('img3').src = templatePath.substr(3) + "/var_2.gif";
				cboAttrValue1.options[cboAttrValue1.length] = new Option("Escolha " + jsDados[0].attr_label1 , "");
			}

			if(jsDados[0].attr_label2 == null){
				document.getElementById('variante2').style.display = "none";
				document.getElementById('img2').alt = "Passo 2";
				document.getElementById('img2').src = templatePath.substr(3) + "/var_2.gif";
			}else{
				document.getElementById('variante2').style.display = "";	
				cboAttrValue2.options[cboAttrValue2.length] = new Option("Escolha " + jsDados[0].attr_label2 , "");
				if(jsDados[0].attr_label1 == null){
					document.getElementById('img2').alt = "Passo 1";
					document.getElementById('img2').src = templatePath.substr(3) + "/var_1.gif";
					document.getElementById('img3').alt = "Passo 2";
					document.getElementById('img3').src = templatePath.substr(3) + "/var_2.gif";
				}else{
					document.getElementById('img2').alt = "Passo 2";
					document.getElementById('img2').src = templatePath.substr(3) + "/var_2.gif";
					document.getElementById('img3').alt = "Passo 3";
					document.getElementById('img3').src = templatePath.substr(3) + "/var_3.gif";					
				}	
			}
				
			if(jsDados[0].attr_label1 == null && jsDados[0].attr_label2 == null){
				document.getElementById('img3').alt = "Passo 1";
				document.getElementById('img3').src = templatePath.substr(3) + "/var_1.gif";	
			}
			
			for(var 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

				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].variant[i].attr_value1 != null){				

						if (jsDados[0].variant[i].quantity <= 0){	
							if (jsDados[0].attr_label2 == null) {	
							msgForaEstoque = ' (Indisponível, avise-me quando chegar.)';
							classForaEstoque = 'indisponivel';
						}
					    }
					    if (jsDados[0].ExibeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0){
							if ((jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0 && jsDados[0].TipoControleDisp != "P") || (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0 && jsDados[0].TipoControleDisp == "P" && jsDados[0].disponibilidade != null)) {
								if (jsDados[0].attr_label2 == null) {
								msgForaEstoque = ' (Verificar prazo de disponibilidade.)';
								classForaEstoque = 'indisponivel';
							}
						}
                    }
					cboAttrValue1.options[cboAttrValue1.length] = new Option(jsDados[0].variant[i].attr_value1 + msgForaEstoque, jsDados[0].variant[i].attr_value1);
					cboAttrValue1.options[cboAttrValue1.length - 1].className  = classForaEstoque;
					if(jsDados[0].variant[i].attr_value1 == attr_value)
						cboAttrValue1.options[cboAttrValue1.length - 1].selected = true;
				}
			}
			
			var abaPrincipal = "<li><a href=\"#javascript;\" id=\"A0\" style=\"cursor: pointer;\"";
			var browser;   
			browser = navigator.appName;   
			if(browser == "Microsoft Internet Explorer") { 
				abaPrincipal += "<span></span>"
			}
			abaPrincipal += "<span>Descri&ccedil;&atilde;o ";
			abaPrincipal += "</span></a></li>";
			document.getElementById('abas_descricao').innerHTML = abaPrincipal;
			
			document.getElementById('descricao').innerHTML = jsDados[0].description;
			
			if(attr_value != null)
				changeVariant(templatePath);			

			loading(false);
		}else{
			alert(msgErro);
		}
			
	}
	cAjax.load('product_espiar.asp','dept_id=' + dept_id + '&pf_id=' + pf_id + '&store=' + store, 'POST', true);
}

function changeVariant(templatePath){
	var cAjax = new Ajax();
	//mostra tela de carregando
	loading(true);	
	var pf_id = document.getElementById('pf_id').value;
	var store = document.getElementById('store').value;
	var attr_value1 = null;
	document.getElementById('sku').value = '';
	if(document.getElementById('cboAttrValue1').selectedIndex > 0)
		attr_value1 = document.getElementById('cboAttrValue1').options[document.getElementById('cboAttrValue1').selectedIndex].value ;
	var attr_value2 = null;
	if(document.getElementById('cboAttrValue2').selectedIndex > 0)
		attr_value2 = document.getElementById('cboAttrValue2').options[document.getElementById('cboAttrValue2').selectedIndex].value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");		
		
	if (attr_value1 != null  || (attr_value1 != null && attr_value2 != null)) {
		cAjax.onStateChange = function(classState, httpState, retornoHTML, retornoXML){
			if (httpState == 200) {
				var jsDados = eval('(' + retornoHTML.toString() + ')');
				if (jsDados != null) {
					if (!hasTwoVariants) {
						montaImagemPreco(jsDados, templatePath);
						document.getElementById('sku').value = jsDados[0].sku;
					}else{
						if(attr_value1 != null  && attr_value2 != null){
							montaImagemPreco(jsDados, templatePath);
							document.getElementById('sku').value = jsDados[0].sku;
						}else{
							var cboAttrValue2 = document.getElementById('cboAttrValue2');
							document.getElementById('espiar_foto').src = jsDados[0].image_file;
			
							for(var i = cboAttrValue2.length - 1; i > 0 ; i--)
								cboAttrValue2.options[i] = null;
								
							for(var 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
 
								if(jsDados[0].variant[i].attr_value2 != null){
			
									if (jsDados[0].variant[i].quantity <= 0){	
										msgForaEstoque = ' (Indisponível, avise-me quando chegar.)';
										classForaEstoque = 'indisponivel';	
									}
									
				                    if (jsDados[0].ExibeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0){
										if ((jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0 && jsDados[0].TipoControleDisp != "P") || (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].variant[i].quantity <= 0 && jsDados[0].TipoControleDisp == "P" && jsDados[0].disponibilidade != null)) {
											msgForaEstoque = ' (Verificar prazo de disponibilidade.)';
											classForaEstoque = 'indisponivel';
										}	
									}
									
									cboAttrValue2.options[cboAttrValue2.length] = new Option(jsDados[0].variant[i].attr_value2 + msgForaEstoque, jsDados[0].variant[i].attr_value2);
									cboAttrValue2.options[cboAttrValue2.length - 1].className  = classForaEstoque;
								}
							}
						}
					}
				}
				
				//mostra tela de carregando
				loading(false);
			}
			else {
				alert(msgErro);
			}
			
		}
		cAjax.load('product_espiar_variante.asp', 'attr_value1=' + attr_value1 + '&attr_value2=' + attr_value2 + "&pf_id=" + pf_id + "&store="+store, 'POST',true);
	}else{
		loading(false);
	}
}

function montaImagemPreco(jsDados, templatePath){
	document.getElementById('espiar_foto').src = jsDados[0].image_file;	
	document.getElementById('espiar_preco').style.display = "";
	document.getElementById('price_text1').style.display = "none";
	document.getElementById('economize_text').style.display = "none";
	if (jsDados[0].hidePrice == "N") {	
		for(var i in jsDados[0].variant){
			var quantityVariant = jsDados[0].variant[i].quantity; 
		}
	}
	if ((jsDados[0].hidePrice == "N") && ((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 = "";
	}	
	
	if ((jsDados[0].hidePrice == "N") && ((jsDados[0].quantity <= 0 && jsDados[0].VendeProdForaEstoque == "N") || (jsDados[0].quantity <= 0 && jsDados[0].VendeProdForaEstoque == "N") || ((jsDados[0].quantity <= 0) && jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp == "P" && jsDados[0].disponibilidade == null) || (quantityVariant <= 0 && jsDados[0].VendeProdForaEstoque == "N" && jsDados[0].disponibilidade == null))){
		if (jsDados[0].quantity > 0 && jsDados[0].ExibeProdForaEstoque == "S" && jsDados[0].VendeProdForaEstoque == "N"){
			document.getElementById('link_comprar').href = "javascript:setVenda();";
			if ((jsDados[0].bloqueado == "P")){	
				document.getElementById('bt_comprar').src = templatePath + "/bt_reservar.png"
			}else{
			document.getElementById('bt_comprar').src = templatePath + "/bt_comprar.png"
			}
			document.getElementById('espiar_preco').style.display = "none";
		}else{
			document.getElementById('link_comprar').href = "javascript:setEncomenda();";
			document.getElementById('bt_comprar').src = templatePath + "/bt_encomendar.png"
			document.getElementById('espiar_preco').style.display = "none";
		}	
	}	
	else {
		if ((jsDados[0].hidePrice == "N") && ((jsDados[0].quantity > 0) || (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp == "P" && jsDados[0].disponibilidade != "") || (jsDados[0].VendeProdForaEstoque == "S" && jsDados[0].TipoControleDisp != "P") || (jsDados[0].bloqueado != "P"))) {
			document.getElementById('link_comprar').href = "javascript:setVenda();";
			
			if ((jsDados[0].bloqueado == "P")){	
				document.getElementById('bt_comprar').src = templatePath + "/bt_reservar.png"
			}else{
				document.getElementById('bt_comprar').src = templatePath + "/bt_comprar.png"
			}
			
			if (jsDados[0].quantity <= 0 && jsDados[0].ExibeProdForaEstoque == "N"){
				document.getElementById('link_comprar').href = "javascript:setEncomenda();";
				document.getElementById('bt_comprar').src = templatePath + "/bt_encomendar.png"
				document.getElementById('espiar_preco').style.display = "none";	
			}	
			
			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;
			}	
		}
		else{
			if (jsDados[0].hidePrice == "N") {
			document.getElementById('link_comprar').href = "javascript:setEncomenda();";
			document.getElementById('bt_comprar').src = templatePath + "/bt_encomendar.png"
			}
		} 
		if (jsDados[0].hidePrice == "N") {
			document.getElementById('espiar_preco2').innerHTML = jsDados[0].sale_price;
		}	
		if ((jsDados[0].DescontoAvista > 0) && (jsDados[0].hidePrice == "N")) {
			document.getElementById('desconto_avista').innerHTML = jsDados[0].Desconto_a_vista;
			}
		if ((jsDados[0].parcela_semjuros > 1) && (jsDados[0].hidePrice == "N")) {
			document.getElementById('price_text3').style.display = "";
			document.getElementById('espiar_vezes').innerHTML = jsDados[0].parcela_semjuros;
		}
		else 
			document.getElementById('price_text3').style.display = "none";
		if (jsDados[0].hidePrice == "N") {	
			document.getElementById('produto_preco').innerHTML = jsDados[0].preco_parcelado;
		}
		if (jsDados[0].hidePrice == "S") {
			document.getElementById('link_comprar').href = "javascript:setOrcamento();";
			document.getElementById('bt_comprar').src = templatePath + "/bt_orcamento.gif";		
			document.getElementById('espiar_preco').style.display = "none";
		}

	}	
}

function setVenda(){
	var pf_id = document.getElementById('pf_id').value;
	var attr_value1 = "";
	if(document.getElementById('cboAttrValue1').selectedIndex > 0)
		attr_value1 = document.getElementById('cboAttrValue1').options[document.getElementById('cboAttrValue1').selectedIndex].value ;
	var attr_value2 = "";
	if(document.getElementById('cboAttrValue2').selectedIndex > 0)
		attr_value2 = document.getElementById('cboAttrValue2').options[document.getElementById('cboAttrValue2').selectedIndex].value;
	var sku = document.getElementById('sku').value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");	
	
	var hasOneVariant = !(document.getElementById('variante1').style.display == "none");
    if (attr_value1== "" && hasOneVariant) {
		var HTMLErro = '<div class="erro_cor">É necessário selecionar '; //guarda o erro pelos atributos
		if (attr_value1 == "") 
			HTMLErro += document.getElementById('attr_label1').value;
		
		if (attr_value2 == "" && hasTwoVariants) 
			if (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;
	var attr_value1 = "";
	if(document.getElementById('cboAttrValue1').selectedIndex > 0)
		attr_value1 = document.getElementById('cboAttrValue1').options[document.getElementById('cboAttrValue1').selectedIndex].value ;
	var attr_value2 = "";
	if(document.getElementById('cboAttrValue2').selectedIndex > 0)
		attr_value2 = document.getElementById('cboAttrValue2').options[document.getElementById('cboAttrValue2').selectedIndex].value;
	var sku = document.getElementById('sku').value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");	
	var hasOneVariant = !(document.getElementById('variante1').style.display == "none");
    if (attr_value1== "" && hasOneVariant) {
		var HTMLErro = '<div class="erro_cor">É necessário selecionar '; //guarda o erro pelos atributos
		if (attr_value1 == "") 
			HTMLErro += document.getElementById('attr_label1').value;
		
		if (attr_value2 == "" && hasTwoVariants) 
			if (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_encomendar').value;
		document.frm_espiar.submit();
	}
}


function setOrcamento(){
	var pf_id = document.getElementById('pf_id').value;
	var attr_value1 = "";
	if(document.getElementById('cboAttrValue1').selectedIndex > 0)
		attr_value1 = document.getElementById('cboAttrValue1').options[document.getElementById('cboAttrValue1').selectedIndex].value ;
	var attr_value2 = "";
	if(document.getElementById('cboAttrValue2').selectedIndex > 0)
		attr_value2 = document.getElementById('cboAttrValue2').options[document.getElementById('cboAttrValue2').selectedIndex].value;
	var sku = document.getElementById('sku').value;
	var hasTwoVariants = ! (document.getElementById('variante2').style.display == "none");	
	var hasOneVariant = !(document.getElementById('variante1').style.display == "none");
    if (attr_value1== "" && hasOneVariant) {
		var HTMLErro = '<div class="erro_cor">É necessário selecionar '; //guarda o erro pelos atributos
		if (attr_value1 == "") 
			HTMLErro += document.getElementById('attr_label1').value;
		
		if (attr_value2 == "" && hasTwoVariants) 
			if (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_orcamento').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";  
        }
    }
}
