//produto_detalhe.jsp e includes
( function() {
  if (window.DetalheProduto)
    return;

  var DetalheProduto = window.DetalheProduto = {};
  DetalheProduto.marca = '';
  DetalheProduto.modelo = '';
  DetalheProduto.site = '';

  DetalheProduto.ajaxExecuted = new Object();
  
  DetalheProduto.validate_quantity = function (formQty, maxQty) {
    var value = jq(formQty).val();
    if (!value.match(/^\d+$/) || value < 1 || value > maxQty) {
      alert('Quantidade máxima ' + maxQty + (maxQty > 1 ? ' unidades' : ' unidade') + ' por produto.');
      jq(formQty).focus();
      return false;
    }
    return true;
  }
  
  DetalheProduto.clickTab = function(index, url) {
    try {
      if (url != 'null')
        this.executeAjaxTab(index, url);
    } catch (e) {
      alert("clickTab:" + url);
    }
  };

  DetalheProduto.executeAjaxTab = function(index, URL) {
    if (this.ajaxExecuted[index])
      return;

    this.ajaxExecuted[index] = true;

    var selector = jq(jq("#scrolabblepane > div")[index]);

    URL += (URL.indexOf('?') > 0) ? '&' : '?';

    jq.ajax( {
      url : URL + 'x=' + Math.random(),
      success : function(data) {
        selector.html('<div class="div">'+data+'<div>');
      }
    });
  };

  DetalheProduto.addProduto = function (promoPrices, maxQty) {
    var acrescentaProd = jq('#acrescentaProd')[0];
    
    if (!DetalheProduto.validate_quantity(acrescentaProd.qty, maxQty))
      return;
    
    if (DetalheProduto.messageNoBuy) {
      alert(DetalheProduto.messageNoBuy);
      return;
    }

    if (!acrescentaProd.selectCores || acrescentaProd.selectCores.selectedIndex == -1) {
      if (promoPrices != '1')
        alert('Produto n\ão dispon\ível na Loja Virtual. Para adquirir este produto dirija-se a uma Loja ou Agente autorizado tmn.');
      else
        alert('Produto n\ão dispon\ível na Loja Virtual. Para adquirir este produto dirija-se a uma Loja ou Agente autorizado tmn. O pre\ço apresentado na Loja Virtual \é exclusivo para compras on-line');
      return;
    }
    
    var corId = jq(acrescentaProd.selectCores).val();

    if (corId == '-') {
      alert('Por favor seleccione a cor pretendida');
      return;
    }

    var cores = this.cores;
    for ( var i = 0; i < cores.length; i++) {
      if (cores[i][0] == corId) {
        acrescentaProd.codSap.value = cores[i][1];
        acrescentaProd.codCampanha.value = cores[i][2]
        break;
      }
    }

    if (!acrescentaProd.codCampanha.value) {
      alert('Produto n\ão dispon\ível na Loja Virtual. Para adquirir este produto dirija-se a uma Loja ou Agente autorizado tmn.');
      return;
    }

    if (!acrescentaProd.codSap.value) {
      alert('Produto temporariamente indispon\ível.');
      return;
    }
    acrescentaProd.submit();
  };

  DetalheProduto.cores = new Array();
  DetalheProduto.addCor = function (index, id, codSap, codCampanha) {
    this.cores[index] = [id, codSap, codCampanha];
  };
  
  DetalheProduto.clickImagem = function (url_imagem, options, caller) {
    if(!url_imagem)
      return;
    
    if(!options) {
      jq('#imgemPrincipal').attr("src",url_imagem);
      return;
    }
    
    if(options.url.indexOf('http') === 0) {
      var width = options.width || 400;
      var height = options.height || 350;
      var key = options.url.replace(/[^a-z0-9]/gi, '_');
      var html = '<div id="' + key + '" style="display: none;">';
      
      if(options.url.indexOf('.sapo') > 0 || options.url.match(/.swf$/)) {
        html += '<embed src="' + options.url 
          + '" width="' + width
          + '" height="' + height
          + '" type="application/x-shockwave-flash" allowFullScreen="true" autoplay="true"></embed>';
      } else {
        html += '<iframe src="' + options.url 
          + '" width="' + width
          + '" height="' + height
          + '" frameborder="0" allowfullscreen></embed>';
      }
      html += '</div>';
      jq('#imgemPrincipal').after(html);
      caller.href = '#' + key;
      jq(caller).prettyPhoto({
            social_tools: '',
            default_width: width,
            default_height: height,
            deeplinking: false
          });
      caller.onclick = '';
      jq(caller).click();
    }
  };
  

  DetalheProduto.submitAcrescentaCartao = function (maxQty) {
    var quant = document.getElementById('qty');
    var acrescentaProd = jq('#acrescentaProd')[0];
    if (DetalheProduto.validate_quantity(quant, maxQty)) {

        if (acrescentaProd.codCampanha.value == '') {
            alert('Produto n\ão dispon\ível na Loja Virtual. Para adquirir este produto dirija-se a uma Loja ou Agente autorizado tmn.');
            return;
        } else if (acrescentaProd.codSap.value == '') {
            alert('Produto temporariamente indispon\ível.');
            return;
        }
        acrescentaProd.qty.value = quant.value;
        acrescentaProd.submit();
    }
  };
  
})();

( function() {
      if(DetalheProduto.Tabs)
        return;
      
      var windowsInterval;
      var mover = 0;
      var maxscroll = 0;
      var slider;
      
      DetalheProduto.Tabs = {};
      
      DetalheProduto.Tabs.init = function () {
        slider = document.getElementById('scrolabbleslider');
        if(!slider) return;
        var container = document.getElementById('slidercontainer');
        if(!container) return;
        var scrolldir = document.getElementById('deta_vartab_dir');
        if(!scrolldir) return;
        var scrollesq = document.getElementById('deta_vartab_esq');
        if(!scrollesq) return;

        slider.style.marginLeft = '-10000px';
        slider.style.width = "auto";
        var larguracontainer = slider.offsetWidth;
        slider.style.marginLeft = '0px';
        slider.style.width = "10000px";
        
        maxscroll = larguracontainer - container.offsetWidth;
        if(maxscroll < scrolldir.offsetWidth - scrollesq.offsetWidth) {
            container.style.width = (scrolldir.offsetWidth + scrollesq.offsetWidth + container.offsetWidth) + "px" ;
            scrolldir.style.display = "none";
            scrollesq.style.display = "none";
        }
        
        jq(".tabs").tabs("div.pane > div", {
        	initialIndex: 	0
        });
        var api =  jq(".tabs").data("tabs");
        api.onClick(function(index) {
        	scrollTo(0, parseInt(jq(".w_568_dest").position().top+jq(".w_568_dest").height()/2));
        });
      };

      DetalheProduto.Tabs.startMove = function (velocidade) {
        windowsInterval = window.setInterval(
            function startMoving(){
              mover = mover + 10*velocidade;
              if (mover > maxscroll) {
                DetalheProduto.Tabs.stopMove();
                mover = maxscroll;
              }
              if (mover < 1) {
                DetalheProduto.Tabs.stopMove();
                mover = 0;
              }
              slider.style.marginLeft = -(mover) +'px';
            },
            10);
          };
      DetalheProduto.Tabs.stopMove = function () {
          window.clearInterval(windowsInterval);
        };
      
      DetalheProduto.Tabs.clickByName = function (name) {
          if(!name)
            return;
          var tabs = jq('#scrolabbleslider li a');
         
          var totalWitdh =0;
          var medidaL=519;
          for(var i = 0; i < tabs.length; ++i) {
        	totalWitdh = totalWitdh + tabs[i].offsetWidth;
            if(jq.trim(jq(tabs[i]).html()) == name) {
            	try{
	              if(totalWitdh>medidaL) {
	            	  mover = totalWitdh-medidaL;
	            	  slider.style.marginLeft = -mover +'px';
	              } else if(totalWitdh<medidaL && i==0) {
	            	  mover = '0px';
	            	  slider.style.marginLeft = mover+'px';
	              }else if(totalWitdh<medidaL && (mover ==0 || mover == '0px')){
	            	  mover = mover = '0px';
	            	  slider.style.marginLeft = -mover +'px';
	              }else if(totalWitdh<medidaL){
		          	  mover = tabs[i-1].offsetWidth;
		          	  slider.style.marginLeft = -mover +'px';
		          }
            	} catch(error){}
              jq(tabs[i]).click();
              return;
            }
          }
        };
    }
)();

( function() {
		if(DetalheProduto.Pontos)
	        return;
		
		DetalheProduto.Pontos = {};
		DetalheProduto.Pontos.ArrayTrocas = [];
		DetalheProduto.Pontos.ArrayInfoStock = [];
		DetalheProduto.Pontos.cores = new Array();
		
		DetalheProduto.Pontos.init = function (tipoProd, prodOID, chanOID, format, tipoProd) {
			this.tipoProd=tipoProd;
			this.prodOID=prodOID;
			this.chanOID=chanOID;
			this.format=format;
			this.tipoProd=tipoProd;
	    };

		DetalheProduto.Pontos.submitForm = function(euros, pontos) {
			for(var i = 0; i!= DetalheProduto.Pontos.ArrayTrocas.length; ++i) {
				if(DetalheProduto.Pontos.ArrayTrocas[i].euros == euros && DetalheProduto.Pontos.ArrayTrocas[i].numeroPontos == pontos) {
					if(DetalheProduto.Pontos.ArrayTrocas[i].msgNoStock && DetalheProduto.Pontos.ArrayTrocas[i].msgNoStock!='') {
						alert(DetalheProduto.Pontos.ArrayTrocas[i].msgNoStock);
						return;
					} 
					if(typeof DetalheProduto.Pontos.ArrayTrocas[i].infoStock != "undefined"){
						var info =DetalheProduto.Pontos.ArrayTrocas[i].infoStock;
						if(DetalheProduto.Pontos.isEsgotado(info)) {			
							alert(DetalheProduto.Pontos.getMsgInfoStock(info));
							return;
						}
					}
						 
					/*Trocas com cores*/
					var corId = jq("#selectCores").find("option:selected").attr("value");
					if(typeof corId != "undefined" && corId=='-'){
						alert("Por favor seleccione a cor pretendida");
						return;
					}
					if(typeof DetalheProduto.Pontos.ArrayTrocas[i].cor != "undefined" && DetalheProduto.Pontos.cores.length>1 && corId==DetalheProduto.Pontos.ArrayTrocas[i].cor.id) {
						for(var t = 0; t!= DetalheProduto.Pontos.cores.length; ++t) {
							if(DetalheProduto.Pontos.cores[t].id == corId) {
								jq("#corId").attr("value", DetalheProduto.Pontos.ArrayTrocas[i].cor.id);
								jq("#nome").attr("value", DetalheProduto.Pontos.ArrayTrocas[i].cor.codNome);
								break;
							}	
						}
					}else if(typeof DetalheProduto.Pontos.ArrayTrocas[i].cor != "undefined" && corId!=DetalheProduto.Pontos.ArrayTrocas[i].cor.id)
						continue;
					/*FIM*/  
					jq("#ref").attr("value", DetalheProduto.Pontos.ArrayTrocas[i].referencia);
					jq("#codMov").attr("value", DetalheProduto.Pontos.ArrayTrocas[i].codMovimento);
					
					jq("#prod_oid").attr("value", DetalheProduto.Pontos.Troca.prodOID);
					jq("#chn_oid").attr("value", DetalheProduto.Pontos.Troca.chanOID);
					jq("#format").attr("value", DetalheProduto.Pontos.Troca.format);
					jq("#tipoProd").attr("value", DetalheProduto.Pontos.Troca.tipoProd);	
					break;
				}
			}
			jq("#rebaterPontosForm").submit();
		};
		
		DetalheProduto.Pontos.AddTroca = function(troca) {
			DetalheProduto.Pontos.ArrayTrocas.push(troca);
	    };
	    
	    DetalheProduto.Pontos.AddInfoStock = function(infoStock) {
			DetalheProduto.Pontos.ArrayInfoStock.push(infoStock);
	    };
	    
		DetalheProduto.Pontos.Troca = function(referencia, codMovimento, corId, numeroPontos, euros, id, msgNoStock, infoStock) {
	        this.referencia = referencia;
	        this.codMovimento = codMovimento;
	        for(var i = 0; i!= DetalheProduto.Pontos.cores.length; ++i) {
				if(DetalheProduto.Pontos.cores[i] && DetalheProduto.Pontos.cores[i].id == corId) 
					this.cor = DetalheProduto.Pontos.cores[i];
			}
	        this.numeroPontos = numeroPontos;
	        this.euros = euros;
	        this.id = id;
	        if(typeof msgNoStock != "undefined" && msgNoStock!='')
	        	this.msgNoStock = msgNoStock;
	        else
	        	this.msgNoStock = '';
	        if(typeof infoStock != "undefined")
	        	this.infoStock = infoStock;
	    };
		
		DetalheProduto.Pontos.addCor = function (id, nome, codNome) {
			for(var i = 0; i!= DetalheProduto.Pontos.cores.length; ++i) {
				if(DetalheProduto.Pontos.cores[i] && DetalheProduto.Pontos.cores[i].id == id) 
					return;
			}
			DetalheProduto.Pontos.cores.push({"id": id, "nome":nome, "codNome":codNome});
		};
		
		DetalheProduto.Pontos.InfoStock = function (stock, seloStock, mensagemNoStock, msgDefault) {
			this.stock=stock;
			this.seloStock=seloStock;
			this.mensagemNoStock=mensagemNoStock;
			this.msgDefault=msgDefault;
		};
		
		DetalheProduto.Pontos.isEsgotado = function (info) {
			if (typeof info != "undefined")
	            return ( info.stock == 0 || info.seloStock == 1 )
	        else
	            return false;
		};
		
		DetalheProduto.Pontos.getMsgInfoStock = function (info) {
			if (info.mensagemNoStock != '')
	            return info.mensagemNoStock
	        else
	            return info.msgDefault;
		};
	}
)();

