
/**************** FUNCIONALIDADES DA COMPARAÇÃO DE EQUIPAMENTOS ********************/
$(function(){
//alert("DDD");			
	$.meta.setType("elem", "script");
	//Sacar dados e copiá-los como prop para o container .col_equipamento
	//esconder o SPAN que contém o script JSON com os dados
	$(".col_topo SPAN.data").each(function(){
		$(this).css("display","none");
		$(this).parent().get(0).cores = $(this).data().cores;
	}); 
	$(".inactive").each(function(){
	    $(".link_topo>.lista_equipamentos A",this).each(function(){
			$(this).bind("click",function(event){
			    var mobiles = $(".topo>H2[@sap]");
			    var saps = "";
			    for(i=0;i<mobiles.length;++i){
			        saps += (mobiles[i].attributes["sap"].value + ",");
			    }
			    saps += $(this).attr("sap");
			    
			    $("#compare INPUT[@name='compareMobiles']").val(saps);
				$("#compare").submit();
			});
		});
	});
	
	$(".col_topo").each(function(){
		if(this.cores){
			var cores = this.cores;
			var col_equipamento = $(this);
			this.cor_idx = 0;
			var now = document.getElementById('now').value;
			//adicionar imagens com idx de referência à array cores 
			var entered = false;
			for(i=0;i<this.cores.length;i++){
				//img cores
				if(cores[i] != null)
				{
				    $(".cores",this).append('<img class="cor coloursBorder" data="'+i+'" src="/img/spacer.gif" alt="cor" style="background-color:#'+cores[i].rgb_cor+'";/>');
				    if((now >= this.cores[i].inicio || "" == this.cores[i].inicio) && (now <= this.cores[i].fim || "" == this.cores[i].fim) && '1' == this.cores[i].disponivel)
			            this.cores[i].disponivel = '1';
			        else
			            this.cores[i].disponivel = '0';
    			      
    			    if(cores[i] != null && !entered)
				    { 
				        entered = true; 
			            //redefinir o html da 1 imagem para ficar correcto com a disponibilidade
	                    if( '1' == cores[i].disponivel && '0' == cores[i].descontinuado)
	                    {
	                          $(".comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar.gif");
	                           $(".comprar img",col_equipamento).attr("class","rosa laranja_empresas");
	                           $(".comprar img",col_equipamento).attr("border","0");
                              $(".comprar img",col_equipamento).attr("alt","comprar");
                              $(".comprar a",col_equipamento).attr("rel","comprar");
                        }
                        if( '0' == cores[i].disponivel && '0' == cores[i].descontinuado && '1' == cores[i].reserva)
                        {
                               $(".comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar.gif");
                               $(".comprar img",col_equipamento).attr("class","rosa laranja_empresas");
	                           $(".comprar img",col_equipamento).attr("border","0");
                               $(".comprar img",col_equipamento).attr("alt","reservar");
                               $(".comprar a",col_equipamento).attr("rel","reservar");
                        }
                        if( ('0' == cores[i].disponivel && ('1' == cores[i].descontinuado || '0' == cores[i].reserva)) || 
                            ( '1' == cores[i].disponivel && '1' == cores[i].descontinuado) || 
                            (!cores[i].preco_online && cores[i].precos_pontos.length == 0))
                        {
                               $(".comprar img",col_equipamento).removeAttr("src");
                               $(".comprar img",col_equipamento).removeAttr("alt");
                               $(".comprar img",col_equipamento).removeAttr("class");
	                           $(".comprar img",col_equipamento).removeAttr("border");

                               $(".comprar a",col_equipamento).removeAttr("rel");
                        }
                    }
                }
			}
			//Adicionar click a cada uma das cores
			$(".cores IMG[@class='cor coloursBorder']",this).each(function(){
				$(this).css("cursor","pointer");
				$(this).bind("click",function(){
					var idx = $(this).attr("data");
					col_equipamento.get(0).cor_idx = idx;
					//$("IMG.img_telemovel",col_equipamento).attr("src",cores[idx].url_equipamento);
					if( cores[idx].url_equipamento == "/")
					{
					    $("IMG.img_telemovel",col_equipamento)[0].style["visibility"] = "hidden";
					}
					else
					{
					    $("IMG.img_telemovel",col_equipamento).attr("src",cores[idx].url_equipamento);
					    $("IMG.img_telemovel",col_equipamento)[0].style["visibility"] = "visible";
					}
					if('1' == cores[idx].disponivel && (cores[idx].preco_online || cores[idx].precos_pontos.length > 0))
                    {
                      $(".col_preco img",col_equipamento).attr("src","/img/telemoveis_bot_comprar.gif");
                      $(".col_preco img",col_equipamento).attr("class","rosa laranja_empresas");
	                  $(".col_preco img",col_equipamento).attr("border","0");
                      $(".col_preco img",col_equipamento).attr("alt","comprar");
                      $(".col_preco .bot_comprar",col_equipamento).attr("rel","comprar");
                      $(".col_preco .esgotado",col_equipamento).empty();
                      $(".col_preco .bot_comprar",col_equipamento).attr("href","#");
                    }
                    else
                    {
                      $(".col_preco img",col_equipamento).attr("src","/img/bot_comparar_esgotado.gif");
                      $(".col_preco img",col_equipamento).attr("class","rosa laranja_empresas");
	                   $(".col_preco img",col_equipamento).attr("border","0");
                      $(".col_preco img",col_equipamento).attr("alt","esgotado");
                      $(".col_preco .bot_comprar",col_equipamento).attr("rel","esgotado");
                      $(".col_preco .esgotado",col_equipamento).empty();
                      $(".col_preco .esgotado",col_equipamento).append("Esgotado");
                      $(".col_preco .bot_comprar",col_equipamento).removeAttr("href");//tem de ser removido
                    }
                    
                    
					//mudar preços
					var preco_obj = $(".col_preco .preco",col_equipamento);
					preco_obj.attr("data",0);
					preco_obj.empty();
					if(cores[idx].preco_offline) preco_obj.append("<span>&euro;"+cores[idx].preco_offline+"</span>");
					if(cores[idx].preco_online)
					{ 
					    preco_obj.append("&euro;"+cores[idx].preco_online);
					}
					else
					{
					    if(cores[idx].precos_pontos.length > 0)
					        preco_obj.append(cores[idx].precos_pontos[0].descricao);
					}
						//EM 05.01.008-------start
						$(".todos_precos",col_equipamento).trigger("rebuild");
						//EM 05.01.008-------end					
				});
			});
			//Adicionar combobox ao preço e construir estrutura interactiva
			var listaPrecosOpen = 0;
			var listaPrecosTimeOut = 0;
			$(".col_preco .bloco>SPAN.preco",this).each(function(){
				$(this).css("cursor","pointer");
		 		var todos_precos = $(".todos_precos",col_equipamento);
				todos_precos.bind("rebuild",function(){
					$(this).empty();
					var cor_idx = col_equipamento.get(0).cor_idx;
					while(cores[cor_idx] == null && col_equipamento.get(0).cores.length > cor_idx)
					    ++cor_idx;
					    
					if(cores[cor_idx] != null)
					{
					    var precos_pontos = cores[cor_idx].precos_pontos;
					    todos_precos.append('<a href="#" data="0"></a>'); 
					    if(cores[cor_idx].preco_offline) $("a",todos_precos).append("<span>&euro;"+cores[cor_idx].preco_offline+"</span>");
					    $("a",todos_precos).append("&euro;"+cores[cor_idx].preco_online);
					    for(i=0;i<precos_pontos.length;i++){
						    todos_precos.append('<a href="#" data="'+precos_pontos[i].id_preco+'">'+precos_pontos[i].descricao+'</a>');
					    }
					//EM 05.01.008-----start
					spanDoPreco = $(".comprar>SPAN.preco", $(this).parent());
					spanDoPreco.attr("numerolinks",$("a", todos_precos).length);
					if($("a", todos_precos).length > 1){spanDoPreco.addClass("preco_active").removeClass("preco_inactive");}else{spanDoPreco.removeClass("preco_active").addClass("preco_inactive");};
					//EM 05.01.008-----end
					}
					$("a",todos_precos).bind("click",function(event){
						event.stopPropagation();
						event.preventDefault();
						$(".col_preco .preco",col_equipamento).empty().html($(this).html()).attr("data",$(this).attr("data"));
						todos_precos.slideToggle();
						$(".col_preco .bloco>SPAN.preco",col_equipamento).toggleClass("preco_open");
						listaPrecosOpen = 0;
					});
				});
				todos_precos.trigger("rebuild");
						/*
						$(this).bind("click",function(){
							$(this).toggleClass("preco_open");
							todos_precos.slideToggle();
							todos_precos.trigger("rebuild");

						});
						*/
			
							
				$(this).hover(function(){
			        if(listaPrecosOpen == 0){
				        todos_precos.slideDown();
				        $(this).addClass("preco_open");
				        todos_precos.trigger("rebuild");
				        listaPrecosOpen = 1;
			        } else {
				        clearTimeout(listaPrecosTimeOut);
				        listaPrecosOpen = 1;
			        }
		        },function(){
			        precoTimeOut = setTimeout(function(){
				        todos_precos.slideUp();
				        $(".comprar>SPAN.preco",this).removeClass("preco_open");
				        listaPrecosOpen = 0
			        }, 333);
		        });
			
			    //hover submenu:
			    todos_precos.hover(function(){
					clearTimeout(precoTimeOut);
				},function(){
					listaPrecosTimeOut = setTimeout(function(){
						if(listaPrecosOpen == 1){
							todos_precos.slideUp();
							$(".comprar>SPAN.preco",this).removeClass("preco_open");
							listaPrecosOpen = 0;
						}
				    }, 333);
					
			    });	
			});
					
			$(".col_preco A.bot_comprar",col_equipamento).each(function(){
				$(this).bind("click",function(event){
					event.stopPropagation();
					event.preventDefault();
					comprar_params = new Object();
					//Se o id_preco = 0 quer dizer que é o preço 'normal'
					comprar_params.id_cor = cores[$(col_equipamento).get(0).cor_idx].id_cor;
					comprar_params.id_preco = $(".col_preco .preco",col_equipamento).attr("data") || "0";
					comprar_params.action = $(this).attr("rel");
					comprar_params.id_prod = $(this).attr("idProd");
					comprar_params.marca = $(this).attr("marca");
					comprar_params.modelo = $(this).attr("modelo");
                    
			        var path = window.location.pathname;
					var pathParts = path.split("/");
					var site = pathParts[1];
				    if(comprar_params.action == "comprar")
				    {
					    if((-1 != (site.toLowerCase()).search("particulares")) &&
					       ($(this).attr("rel") != "reservar"))
					    {
				            $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
				            $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
					        if(comprar_params.id_preco != "0") {
				                $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
				                $("#form_add_prod").attr('action', $("#form_add_prod INPUT[@name='actionComprarPontos']").val());
					        } else {
					            $("#form_add_prod INPUT[@name='lms']").remove();
				                $("#form_add_prod").attr('action', $("#form_add_prod INPUT[@name='actionComprar']").val());
					        }
					        $("#form_add_prod").submit();
					    }
					    else
					    {
					        var actionUrl = '/' + site + '/ApoioAoCliente/ServiceRequest';
					        $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
				            $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
				            $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
				            $("#form_add_prod INPUT[@name='marca']").val(comprar_params.marca);
				            $("#form_add_prod INPUT[@name='modelo']").val(comprar_params.modelo);
				            $("#form_add_prod").attr('action', actionUrl);
				            $("#form_add_prod").submit();
    					 
					    }
					 }
					 else if(comprar_params.action == "reservar")
					 {
					    var actionUrl = '/' + site + '/Telemoveis/Reserva';
				        $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
			            $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
			            $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
			            $("#form_add_prod INPUT[@name='marca']").val(comprar_params.marca);
			            $("#form_add_prod INPUT[@name='modelo']").val(comprar_params.modelo);
			            $("#form_add_prod").attr('action', actionUrl);
			            $("#form_add_prod").submit();
					 }
					 
				});
			});
			
			$(".link_topo>.lista_equipamentos A",this).each(function(){
				$(this).bind("click",function(event){
				    var mobiles = $(".topo>H2[@sap]");
			        var saps = "";
			        saps += $(this).attr("sap");
			        var parentSap = $(".topo>h2",$(this).parent().parent().parent()).attr("sap");
			        
			        for(i=0;i<mobiles.length;++i){
			            if(parentSap != mobiles[i].attributes["sap"].value)
			                saps += ("," + mobiles[i].attributes["sap"].value);
			        }
			        
			        $("#compare INPUT[@name='compareMobiles']").val(saps);
				    $("#compare").submit();
				});
			});
			
		}
	});
});

/**************** FUNCIONALIDADES DO DETALHE DE EQUIPAMENTOS ********************/
jQuery(document).ready(function() {
    /*$(".data").each(function(){
        alert("aaa");
    });*/
	//get data from server
	$.meta.setType("elem", "script");
	$(".equipamento SPAN.data").each(function(){
		$(this).css("display","none");
		$(this).parent().get(0).cores = $(this).data().cores;
	});

	$(".equipamento").each(function(){
	    
		if(this.cores){
			var cores = this.cores;
			var col_equipamento = $(this);
		}
		var now = document.getElementById('now').value;
		this.cor_idx = 0;		
		
		//adicionar imagens com idx de referência à array cores
		for(i=0;i<this.cores.length;i++){
			//img cores
			if(cores[i] != null)
			{
			    $(".cores",this).append('<img class="cor coloursBorder" data="'+i+'" src="/img/spacer.gif" alt="cor" style="background-color:#'+cores[i].rgb_cor+'";/>');
			    //colocar a flag de disponibilidade correctamente
			    if((now >= this.cores[i].inicio || "" == this.cores[i].inicio) && (now <= this.cores[i].fim || "" == this.cores[i].fim) && '1' == this.cores[i].disponivel)
			        this.cores[i].disponivel = '1';
			    else
			        this.cores[i].disponivel = '0';
			}
		}			
		
		//redefinir o html da 1 imagem para ficar correcto com a disponibilidade
	    if( '1' == cores[0].disponivel && '0' == cores[0].descontinuado)
	    {
	          $(".comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar.gif");
              $(".comprar img",col_equipamento).attr("alt","comprar");
              $(".comprar a",col_equipamento).attr("rel","comprar");
        }
        if( '0' == cores[0].disponivel && '0' == cores[0].descontinuado && '1' == cores[0].reserva)
        {
               $(".comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar.gif");
               $(".comprar img",col_equipamento).attr("alt","reservar");
               $(".comprar a",col_equipamento).attr("rel","reservar");
        }
        if( ('0' == cores[0].disponivel && ('1' == cores[0].descontinuado || '0' == cores[0].reserva)) || 
            ( '1' == cores[0].disponivel && '1' == cores[0].descontinuado))
        {
               //$("comprar a",col_equipamento).empty();
        }
        
        //EM 1909007 selos onLoad:
			    arraySelos = cores[0].selos;
			    for(i=0;i<arraySelos.length;i++){
			      if(arraySelos[i] != undefined)
			      {
                    $(".texto .selos", col_equipamento).append("<p class='selo_generico'></p>");
                    //EM 1902008 novos selos com src:
                    //URL preenchido:
                    if((arraySelos[i].url).length > 0){
                        $(".texto .selos p:eq("+i+")", col_equipamento).html("<a href='"+arraySelos[i].url+"'><img src='"+arraySelos[i].src+"' alt='"+ arraySelos[i].descricao+"' title='"+ arraySelos[i].descricao+"' /></a>");
                    } else {
                        $(".texto .selos p:eq("+i+")", col_equipamento).html("<img src='"+arraySelos[i].src+"' alt='"+ arraySelos[i].descricao+"' title='"+ arraySelos[i].descricao+"' />");
                    }
				  }
			    }
        $("UL[@class='precos'] INPUT[@name='radiobutton']").click(function(){
           var idx = $(".cores IMG[@class='cor coloursBorder']").attr("data");
            if ($(this).attr("local") == "pontos"){	
                if($("a.bot_comprar img").length){
                    $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                    $("a.bot_comprar img",col_equipamento).attr("class","rosa laranja_empresas");
                    $("a.bot_comprar img",col_equipamento).attr("border","0");
                    $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                    $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                }
                else {
                    $("a.bot_comprar",col_equipamento).append("<img border='0' class='rosa laranja_empresas' alt='comprar' src='/img/telemoveis_bot_comprar_.gif'/>");
                }
            }
			else{
		        if('1' == cores[idx].disponivel && '0' == cores[idx].descontinuado){
                    if($("a.bot_comprar img",col_equipamento).length == 0){
                        $("a.bot_comprar",col_equipamento).append('<img/>');
                    }
                    $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                    $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                    $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                    $("a.bot_comprar",col_equipamento).attr("href","#");
                }
                if( '0' == cores[idx].disponivel && '0' == cores[idx].descontinuado && '1' == cores[idx].reserva){
                    if($("a.bot_comprar img",col_equipamento).length == 0){
                        $("a.bot_comprar",col_equipamento).append('<img/>');
                    }
                    $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar_.gif");
                    $("a.bot_comprar img",col_equipamento).attr("alt","reservar");
                    $("a.bot_comprar",col_equipamento).attr("rel","reservar");
                    $("a.bot_comprar",col_equipamento).attr("href","#");
                }
                if( ('0' == cores[idx].disponivel && ('1' == cores[idx].descontinuado || '0' == cores[idx].reserva)) || ( '1' == cores[idx].disponivel && '1' == cores[idx].descontinuado) || (!cores[idx].preco_online && cores[idx].precos_pontos.length == 0))
                {
                    $("a.bot_comprar img",col_equipamento).remove();	
                }
            }

        });
      
		//Adicionar click a cada uma das cores
		$(".cores IMG[@class='cor coloursBorder']",this).each(function(){
			$(this).css("cursor","pointer");
			$(this).bind("click",function(){
				var idx = $(this).attr("data");
				col_equipamento.get(0).cor_idx = idx;
				
				//tsousa - Apagar o elemento img se não houver imagem definida no BO
				$("IMG.img_telemovel",col_equipamento).remove();
				if(cores[idx].url_equipamento != '')
				{ 
				    $("DIV.imageContainer",col_equipamento).append('<img class="img_telemovel" width="157" height="245" src="'+cores[idx].url_equipamento+'"></img>');
				}
				else
				{
					$("DIV.imageContainer",col_equipamento).append('<img class="img_telemovel" width="157" height="245" src="/" style="visibility:hidden"></img>');

				}
				if ($(this).attr("local") == "pontos"){	
                    if($("a.bot_comprar img").length){
                        $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                        $("a.bot_comprar img",col_equipamento).attr("class","rosa laranja_empresas");
                        $("a.bot_comprar img",col_equipamento).attr("border","0");
                        $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                        $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                    }
                    else {
                        $("a.bot_comprar",col_equipamento).append("<img border='0' class='rosa laranja_empresas' alt='comprar' src='/img/telemoveis_bot_comprar_.gif'/>");
                    }
                }
			    else{

		            if('1' == cores[idx].disponivel && '0' == cores[0].descontinuado){
                        if($("a.bot_comprar img",col_equipamento).length == 0){
                            $("a.bot_comprar",col_equipamento).append('<img/>');
                        }
                        $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                        $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                        $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                        $("a.bot_comprar",col_equipamento).attr("href","#");
                    }
                    if( '0' == cores[idx].disponivel && '0' == cores[idx].descontinuado && '1' == cores[idx].reserva){
                        if($("a.bot_comprar img",col_equipamento).length == 0){
                            $("a.bot_comprar",col_equipamento).append('<img/>');
                        }
                        $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar_.gif");
                        $("a.bot_comprar img",col_equipamento).attr("alt","reservar");
                        $("a.bot_comprar",col_equipamento).attr("rel","reservar");
                        $("a.bot_comprar",col_equipamento).attr("href","#");
                    }
                    if( ('0' == cores[idx].disponivel && ('1' == cores[idx].descontinuado || '0' == cores[idx].reserva)) || ( '1' == cores[idx].disponivel && '1' == cores[idx].descontinuado) || (!cores[idx].preco_online && cores[idx].precos_pontos.length == 0))
                    {
                        $("a.bot_comprar img",col_equipamento).remove();	
                    }
             }
		
                
          //EM 1909007 selos ao clicar:
					arraySelos = cores[idx].selos;
					$(".selos", col_equipamento).html('');
					for(i=0;i<arraySelos.length;i++){
					    if(arraySelos[i] != undefined)
			            {
                            $(".texto .selos", col_equipamento).append("<p class='selo_generico'></p>");
                            //EM 1902008 novos selos com src:
                            //URL preenchido:
                            if((arraySelos[i].url).length > 0){
                                $(".texto .selos p:eq("+i+")", col_equipamento).html("<a href='"+arraySelos[i].url+"'><img src='"+arraySelos[i].src+"' alt='"+ arraySelos[i].descricao+"' title='"+ arraySelos[i].descricao+"' /></a>");
                            } else {
                                $(".texto .selos p:eq("+i+")", col_equipamento).html("<img src='"+arraySelos[i].src+"' alt='"+ arraySelos[i].descricao+"' title='"+ arraySelos[i].descricao+"' />");
                            }
                        }
					}
					
				//mudar preços
				var preco_obj = $("UL.precos",col_equipamento);
				preco_obj.attr("data",0);
				preco_obj.empty();
				
				if(cores[idx].preco_offline) {
					preco_obj.append('<li><label><input local="loja" name="radiobutton" type="radio" value="0" checked/><span>&euro;'+cores[idx].preco_offline+'</span>&euro;'+cores[idx].preco_online+'</label></li>');
				} else {
				    if(cores[idx].preco_online != '' && cores[idx].preco_online != '0')
					    preco_obj.append('<li><label><input local="loja" name="radiobutton" type="radio" value="0" checked/>&euro;'+cores[idx].preco_online+'</label></li>');
				}
				for(i=0;i<cores[idx].precos_pontos.length;i++){
				    if((cores[idx].precos_pontos[i].id_preco != '' && cores[idx].precos_pontos[i].id_preco != '0') || cores[idx].precos_pontos[i].descricao != '')
				    {
					    preco_obj.append('<li><label><input local="pontos" name="radiobutton" type="radio" value="'+cores[idx].precos_pontos[i].id_preco+'"/>'+cores[idx].precos_pontos[i].descricao+'</label></li>');
				    }
				}		
				$("INPUT[@name='radiobutton']").click(function(){
                    
                    if ($(this).attr("local") == "pontos"){	
                        if($("a.bot_comprar img").length){
                            $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                            $("a.bot_comprar img",col_equipamento).attr("class","rosa laranja_empresas");
                            $("a.bot_comprar img",col_equipamento).attr("border","0");
                            $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                            $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                        }
                        else {
                            $("a.bot_comprar",col_equipamento).append("<img border='0' class='rosa laranja_empresas' alt='comprar' src='/img/telemoveis_bot_comprar_.gif'/>");
                        }
                    }
			        else{
		                if('1' == cores[idx].disponivel && '0' == cores[idx].descontinuado){
                            if($("a.bot_comprar img",col_equipamento).length == 0){
                                $("a.bot_comprar",col_equipamento).append('<img/>');
                            }
                            $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                            $("a.bot_comprar img",col_equipamento).attr("alt","comprar");
                            $("a.bot_comprar",col_equipamento).attr("rel","comprar");
                            $("a.bot_comprar",col_equipamento).attr("href","#");
                        }
                        if( '0' == cores[idx].disponivel && '0' == cores[idx].descontinuado && '1' == cores[idx].reserva){
                            if($("a.bot_comprar img",col_equipamento).length == 0){
                                $("a.bot_comprar",col_equipamento).append('<img/>');
                            }
                            $("a.bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar_.gif");
                            $("a.bot_comprar img",col_equipamento).attr("alt","reservar");
                            $("a.bot_comprar",col_equipamento).attr("rel","reservar");
                            $("a.bot_comprar",col_equipamento).attr("href","#");
                        }
                        if( ('0' == cores[idx].disponivel && ('1' == cores[idx].descontinuado || '0' == cores[idx].reserva)) || ( '1' == cores[idx].disponivel && '1' == cores[idx].descontinuado) || (!cores[idx].preco_online && cores[idx].precos_pontos.length == 0))
                        {
                            $("a.bot_comprar img",col_equipamento).remove();	
                        }
                    }                
            });
			    InitializeReservaPontosBehavior(col_equipamento,cores);
			});
		});
		
		InitializeReservaPontosBehavior(col_equipamento,cores);
		
		$("A.bot_comprar",col_equipamento).each(function(){
			$(this).bind("click",function(event){
				event.stopPropagation();
				event.preventDefault();
				comprar_params = new Object();
				//Se o id_preco = 0 quer dizer que é o preço 'normal'
				comprar_params.id_cor = cores[$(col_equipamento).get(0).cor_idx].id_cor;
				comprar_params.id_preco = $("UL.precos INPUT:checked",col_equipamento).val() || "*";
				comprar_params.action = $(this).attr("rel");
				comprar_params.id_prod = $(this).attr("idProd");
				comprar_params.marca = $(this).attr("marca");
				comprar_params.modelo = $(this).attr("modelo");

                
				if(comprar_params.action == "comprar")
				{
				    if((-1 != (window.location.href.toLowerCase()).search("particulares")) &&
				       ($(this).attr("rel") != "reservar"))
					{
				        $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
				        $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
        		        
			            if(comprar_params.id_preco != "0") {
		                    $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
				            $("#form_add_prod").attr('action', $("#form_add_prod INPUT[@name='actionComprarPontos']").val());
			            } else {
			                $("#form_add_prod INPUT[@name='lms']").remove();
				            $("#form_add_prod").attr('action', $("#form_add_prod INPUT[@name='actionComprar']").val());
			            }
			            $("#form_add_prod").submit();
			        }
			        else
				    {
				        $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
			            $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
			            $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
			            $("#form_add_prod INPUT[@name='marca']").val(comprar_params.marca);
			            $("#form_add_prod INPUT[@name='modelo']").val(comprar_params.modelo);
			            $("#form_add_prod").attr('action', '../../../ApoioAoCliente/ServiceRequest');
			            $("#form_add_prod").submit();
				    }				
			    }
			    else if (comprar_params.action == "reservar")
			    {
			        $("#form_add_prod INPUT[@name='prodid']").val(comprar_params.id_prod);
		            $("#form_add_prod INPUT[@name='sap']").val(comprar_params.id_cor);
		            $("#form_add_prod INPUT[@name='lms']").val(comprar_params.id_preco);
		            $("#form_add_prod INPUT[@name='marca']").val(comprar_params.marca);
		            $("#form_add_prod INPUT[@name='modelo']").val(comprar_params.modelo);
		            $("#form_add_prod").attr('action', '../../../Telemoveis/Reserva');
		            $("#form_add_prod").submit();
			    }
			});
		});
		
	});
});

/**************** FUNCIONALIDADES DA EXPLORAÇÃO DE EQUIPAMENTOS ********************/
jQuery(document).ready(function() {
    var numPag = document.getElementById('MobilePageCount');
    var currPag = document.getElementById('currentPage');
    //alert('página currente='+ currPag + ' ; número de páginas='+numPag);
    
    var link_esq = document.getElementById('link_esq');
    var link_dir = document.getElementById('link_dir');
    var link_dir_prev = document.getElementById('link_dir_prev');
    
    
    
    if(null != numPag && null != currPag && null != link_esq && null != link_dir)
    {
        if(numPag.value > 1)
        {
            var i;
            var paginas = "P&aacute;g:  ";
            var inumPag = parseInt(numPag.value);
            var icurrPag = parseInt(currPag.value);
            var maxPages = 10;
            var hMaxPages = Math.floor(maxPages / 2);
            var start = icurrPag - hMaxPages;
            var end = icurrPag + hMaxPages - 1;
            if (start < 1) {
                start = 1;
                end = maxPages;
                if (end > inumPag)
                    end = inumPag;
            } else {
                if (end > inumPag) {
                    end = inumPag;
                    start = end - maxPages + 1;
                    if(start < 1)
                        start = 1;
                }
            }
            for(i = start; i <= end; i++) {
                if (i > 1)
                    paginas = paginas + " : ";
                if (i == currPag.value)
                    paginas = paginas + '<span class="actual">' + i + '</span>';
                else
                    paginas = paginas + '<a href="javascript:NavigationShowPage(' + i + ');">' + i + '</a>';
            }
            //window.alert(paginas);
            $(link_esq).html(paginas);
            
            if(1 == currPag.value)
            {
                link_dir_prev.href = "javascript:NavigationShowPage("+numPag.value + ");";
            }
            else
            {
                link_dir_prev.href = "javascript:NavigationShowPage("+ (currPag.value-1) + ");";
            }
            
            if(numPag.value == currPag.value)
            {
                link_dir.href = "javascript:NavigationShowPage(1);";
            }
            else
            {
                link_dir.href = "javascript:NavigationShowPage("+ (currPag.value-(-1)) + ");";
            }

        }
        else
        {
            $("#navegacaoPaginas").empty();
        }
    }
});


$(function(){

/**************** FUNCIONALIDADES DA ADESÃO A PONTOS ********************/
/* DEPRECATED ***************************	
	var validator = $("#form_adesao_pontos").validate({
		rules: {
			nome: "required",
			morada: "required",
			num: "required",
			cp1: "required",
			cp2: "required",
			localidade: "required",
			email: {
				required: true,
				email: true
			},
			nif: "required"
		},
		messages: {
			nome: "O campo nome é obrigatório!",
			morada: "O campo Morada é obrigatório!",
			num: "O campo Nº é obrigatório!",
			cp1: "O primeiro campo do código postal é obrigatório!",
			cp2: "O segundo campo do código postal é obrigatório!",
			localidade: "O campo Localidade é obrigatório!",
			email: {
				required: "O campo E-mail é obrigatório!",
				email: "O E-mail que inseriu não é válido!"
			},
			nif: "O campo Nº de Contribuinte é obrigatório!"
		},
		errorPlacement: function(error, element){
			nextSibling(element,"BR").after(error);
		}
	});
*/	
/**************** FUNCIONALIDADES DA GESTÃO DE CONTACTOS ********************/
    //alert("rrrrrrrrrrrr");
    //adicionar ringback tones à combo de adição
    /*
    $("input[@name=tone]").each(function(){
        $("#ringTonesChooser>.combobox_list").append('<a href="#" data="'+
                                                     $(this).attr("toneId")+
                                                     '">'+
                                                     $(this).attr("toneName")+
                                                     '</a><br>');                                                 
    });
    */
    
    if ($("#form_contactos").length > 0)
	    $.meta.setType("attr", "test");
    var createdId = -1;
    
    
    //Adicionar contacto
    $("#addImage").bind("click",function(){
    
        if($("#auth").val() != "False")
        {            
            if (validatorAddContact != null) {
                var res = validatorAddContact.form();
		        if (!res) {
		            return res;
		        }
		    }
            var name = $("#form_adicionar>.nome").val();
            var mobile = $("#form_adicionar>.telem").val();
            var mail = $("#form_adicionar>input.email").val();
            var toneId = "";
            if($("#ringTonesChooser>div>input[@name=opcao_ringtones]").attr("value") != "starter")
                toneId = $("#ringTonesChooser>div>input[@name=opcao_ringtones]").attr("value");
            var toneName = $("#ringTonesChooser>div>A[@data="+toneId+"]").text();//[0].textContent;
            //alert($("#ringTonesChooser>div>A[@data="+toneId+"]")[0].textContent);
            var groupId = $("#form_adicionar>.menu_grupo>div>div>input[@name=opcao_grupo]").attr("value");
            var groupName = $("#form_adicionar>.menu_grupo>div>div>A[@data="+groupId+"]").text();//[0].textContent;
            //alert($("#form_adicionar>.menu_grupo>div>div>A[@data="+groupId+"]")[0].textContent);
            var count = $("#form_contactos>.form_row").length + 1;
            
            //validações regex nome contacto e email
            tooltipNome = (name.length>0?name:titleContactsNome);

            tooltipTelem = "";
            expressionTelemNacional = $("#regexptelemnacional").val();      
            expressionTelemInternacional = $("#regexpteleminternacional").val();      
            regxTelemNacional = new RegExp(expressionTelemNacional);
            regxTelemInternacional = new RegExp(expressionTelemInternacional);
            tooltipTelem = ( (regxTelemNacional.test(mobile) || regxTelemInternacional.test(mobile)) ?mobile:titleContactsTelem);
            
            tooltipEmail = "";
            expressionEmail = $("#regexpemail").val();      
            regxEmail = new RegExp(expressionEmail);
            tooltipEmail = (regxEmail.test(mail)?mail:titleContactsEmail);        
                         
            $("#form_contactos>span").append(
                '<div style="visibility:hidden; display:none;" class="form_row" dataId=\"' +
                 createdId +
                 '" toneToDelete="" wasCreated="true">' + 
                    '<input class="checkbox" name="selecionar" value="" type="checkbox">' + 
                    '<input class="nome" name="nome' + count + '" title="' + tooltipNome + '" test="required:true" value="' + name + '"type="text" size="50">' + 
                    '<input class="telem" name="telem' + count + '" title="' + tooltipTelem + '" test="digits: true,required: true" value="' + mobile + '" type="text">' +
                    '<input class="email" name="email' + count + '" title="' + tooltipEmail + '" test="email:true" value="' + mail + '" type="text" size="50">' + 
                    '<div class="menu_grupo">' + 
                        '<select class="combobox" name="opcao_grupo" rel="">' + 
                            '<option value="' + groupId + '">' +
                                groupName +
                            '</option>'+
                            GetGroups(groupId)+
                        '</select>' + 
                    '</div>' + 
                    '<div class="menu_ringtones">' + 
                        '<select class="combobox" name="opcao_ringtones" rel="">' + 
                            '<option value="' + toneId + '">' +
                                 toneName +
                            '</option>' +
                            GetRingTones(toneId) +
                         '</select>' + 
                    '</div><br/>' + 
                    '<div class="errorGeneral errorDadosGestaoContactos2"/>' + 
                '</div>');
                           
            validatorUpdateContacts.refresh();
            //combobox($("SELECT.combobox")); 
            /*if("" == $("#dataInfo INPUT[@name='createdItems']").val())
            {
                $("#dataInfo INPUT[@name='createdItems']").val("[id="+ createdId +"; name=" + name + "; mobileNumber=" + mobile + "; email=" + mail + "; toneId=" + toneId + "; groupId=" + groupId +"]");
            }
            else
            {
                var created =  $("#dataInfo INPUT[@name='createdItems']").val()
                $("#dataInfo INPUT[@name='createdItems']").val(created + "|[id="+ createdId +"; name=" + name + " ; mobileNumber=" + mobile + " ; email=" + mail + " ; toneId=" + toneId + " ; groupId=" + groupId +"]");
            }
            */
            createdId = createdId - 1;     
            //$(".form_row>INPUT[@type='text']").keypress( function() { $(this).parent().attr("wasChanged","true"); } );
            $(".form_row>.menu_grupo>.combobox_container>.combobox_list>a").click( function() { 
                //$(this).parent().parent().parent().parent().attr("wasChanged", "true");
                if($("#auth").val() == "False")
                {
                    document.getElementById("notLogged").style.visibility = 'visible';
                }
            });
            $(".form_row>.menu_ringtones>.combobox_container>.combobox_list>a").click( function() { 
                //$(this).parent().attr("wasChanged","true"); 
                //$(this).parent().attr("toneChanged","true"); 
                if($("#auth").val() == "False")
                {
                    document.getElementById("notLogged").style.visibility = 'visible';
                }
            });       

            // no fim, guardamos as alterações sem confirmação
            GravarContactos("criar", false);  
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
    });
    
    function GravarContactos(operacao, confirma)
    {
        if (validatorUpdateContacts != null)
        {
            var res = validatorUpdateContacts.form();
            if (!res)
            {
                return false;
            }
        }		    
	    $("#form_contactos>span .form_row").each(function()
	    {
            if ($(this).attr("wasCreated") == "true")
            {
                var id = $(this).attr("dataid");
                var contName = $(".nome",this).val();
                var mobile = $(".telem",this).val();
                var mail = $(".email",this).val();
                var groupId = $("div>select[@name='opcao_grupo']>option",this).val(); 
                var toneId = "";
                var toneChanged = "false";

                if($("div>select[@name='opcao_ringtones']>option", this).val() != "starter")
                    toneId = $("div>select[@name='opcao_ringtones']>option", this).val();
                if($(this).attr("tonechanged") == "true")
                    toneChanged = "true";
		            
                var info ="[id="+ id +"; name=" + contName + "; mobileNumber=" + mobile + "; email=" + mail + "; toneId=" + toneId + "; groupId=" + groupId + "; toneChanged = " + toneChanged + "]";

                var created = $("#dataInfo INPUT[@name='createdItems']").val();
                if("" != created)
                    created = created + "|" + info;
                else
                    created = info;
                $("#dataInfo INPUT[@name='createdItems']").val(created);
            }
            else if($(this).attr("wasChanged") == "true")
            {
                var id = $(this).attr("dataid");
                var contName = $(".nome",this).val();
                var mobile = $(".telem",this).val();
                var mail = $(".email",this).val();
                var groupId = $("div>div>div>input[@name='opcao_grupo']",this).val(); 
                var toneId = "";
                var toneChanged = "false";

                if($("div>div>div>input[@name='opcao_ringtones']",this).val() != "starter")
                    toneId = $("div>div>div>input[@name='opcao_ringtones']",this).val();
                if($(this).attr("tonechanged") == "true")
                    toneChanged = "true";
		            
                var info ="[id="+ id +"; name=" + contName + "; mobileNumber=" + mobile + "; email=" + mail + "; toneId=" + toneId + "; groupId=" + groupId + "; toneChanged = " + toneChanged + "]";

                var changed = $("#dataInfo INPUT[@name='changedItems']").val();
                if("" != changed)
                    changed = changed + "|" + info;
                else
                    changed = info;
                    
                $("#dataInfo INPUT[@name='changedItems']").val(changed);	    
            }
        });
        
        // vamos garantir que não apagamos contactos não confirmados
        $("#dataInfo INPUT[@name='deletedItems']").val("");
        
        if(confirma == true)
        {
            // vamos pedir confirmação antes de gravar as alterações        
	        window.open("/OMeuOptimus/Contactos/GestaoContactosConfirmacao.aspx"
	                    + "?UrlRedirect=" + $("input[@jQueryId=urlRedirectConfirmacao]").val()
	                    + "&operacao=" + operacao,
                "wConfirmacao",
                "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");	                            
        }
        else
        {
            // vamos gravar alterações sem pedir confirmação
            document.getElementById("dataInfo").submit();            
        }
    }
    
    //Detectar alterações a contactos
    $(".form_row>INPUT[@type='text']").keypress( function() { $(this).parent().attr("wasChanged","true"); } );
    $(".form_row>.menu_grupo>.combobox_container>.combobox_list>a").click( function() { 
        $(this).parent().parent().parent().parent().attr("wasChanged", "true");
        if($("#auth").val() == "False")
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
    });
    $(".form_row>.menu_ringtones>.combobox_container>.combobox_list>a").click( function() { 
        $(this).parent().parent().parent().parent().attr("wasChanged","true"); 
        $(this).parent().parent().parent().parent().attr("toneChanged","true"); 
        if($("#auth").val() == "False")
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
    });
     
    
    //Remover contactos   
    $("#removeContact").bind("click",function()
    {
        $("#dataInfo INPUT[@name='deletedItems']").val("");
        if($("#auth").val() != "False")
        {            
            $("input.checkbox").each(function()
            {
                if(true == this.checked)
                {
                    if ("true" != $(this).parent().attr("wasCreated"))
                    {
                        var id = $(this).parent().attr("dataId");
                        var toneId = $(this).parent().attr("toneToDelete");
                        if(undefined == toneId) toneId = "";
                        //var toneId = $("input[@name='opcao_ringtones']", $(this).parent()).val();
                    
                        if("" == $("#dataInfo INPUT[@name='deletedItems']").val())
                        {
                            $("#dataInfo INPUT[@name='deletedItems']").val("[id=" + id + "; toneId=" + toneId + "]");
                        }
                        else
                        {
                            var deleted =  $("#dataInfo INPUT[@name='deletedItems']").val();
                            $("#dataInfo INPUT[@name='deletedItems']").val(deleted + "|[id=" + id + "; toneId=" + toneId + "]");
                        }
                    }
                    //$(this).parent().remove();
                }
            });

            // vamos pedir confirmação antes de apagar os contactos seleccionados     
	        window.open("/OMeuOptimus/Contactos/GestaoContactosConfirmacao.aspx"
	                    + "?UrlRedirect=" + $("input[@jQueryId=urlRedirectConfirmacao]").val()
	                    + "&operacao=apagar",
                "wConfirmacao",
                "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");

            // vamos gravar alterações sem pedir confirmação
            // document.getElementById("dataInfo").submit();
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
    });
    
    
    //Enviar mails   
    $("#sendSms").bind("click",function(){
        var numbers = '';
        $("input.checkbox").each(function(){
            if(true == this.checked)
            {
                var phone = $("input[@name^='telem']", $(this).parent()).val();
                
                if('' == numbers)
                {
                    numbers = phone;
                }
                else
                {
                    numbers = numbers + ';' + phone;
                }
            }
        });
        $('#phones').val(numbers);
        var loc = window.location.href.toLowerCase();
        var idx = loc.lastIndexOf('contactos');
        var url = '';
        if(idx > 1)
            url = window.location.href.substring(0, idx-1) + "/EnviarSMS";
        if('' != numbers)
            url += "?numbers=" + numbers;
            
        $("#goToSms").attr('action', url);  
        $("#goToSms").submit();
    });
    
    
	// Guardar Alterações
	$("#saveChanges").bind("click", function()
	{
	    if($("#auth").val() != "False")
        {	
            GravarContactos("alterar", true);
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
    });
});

function CallParent()
{
    window.close();
    if (window.opener && !window.opener.closed)
    {
        window.opener.document.getElementById("dataInfo").submit();
    }
}

function GetRingTones(exceptTone)
{
    var toReturn = '';
    for(var i = 0; i < $("input.tones").length; ++i)
    {
        if($("input.tones")[i].attributes["toneId"].value != exceptTone)
        {
            toReturn += '<option value="';
            toReturn += $("input.tones")[i].attributes["toneId"].value;
            toReturn += '">';
            toReturn += $("input.tones")[i].attributes["toneName"].value;
            toReturn += '</option>';
        } 
    }
    return toReturn;
}

function GetGroups(exceptGroup)
{
    var toReturn = '';
    for(var i = 0; i < $("input.groups").length; ++i)
    {
        if($("input.groups")[i].attributes["groupId"].value != exceptGroup)
        {
            toReturn += '<option value="';
            toReturn += $("input.groups")[i].attributes["groupId"].value;
            toReturn += '">';
            toReturn += $("input.groups")[i].attributes["groupName"].value;
            toReturn += '</option>';
        } 
    }
    return toReturn;
}

/**************** FUNCIONALIDADES DA GESTÃO DE GRUPOS DE CONTACTOS ********************/
$(function(){
	
	/*
	if($.browser.msie != true){
		$("#maincol .row_container").css({overflow: "visible", width: "508px"});
		$("#container").css({overflow: "visible"});
		$("#maincol").css({overflow: "visible"});
		//^ #container #principal #maincol (line 554 global.css)
	};
	*/
	//$(".combobox_list", $(".blocoContactos .combobox_container")).css("width", "134px");
	
	
	//---------fix para um bug no IE6 (se tiver display: none numa div com um select, dá erro;
	//a solução é colocar height: 0px; overflow: hidden; e depois retirar essas props ao carregar a página...
		
	//1º esconder; 2º mudar as props dos CSS:
	//quando se clica
	$(".blocoContactos").hide().addClass("blocoContactos1");
		
	//3º corrigir um bug do IE: (a div dos contactos tem que ter position: relative)
	//$(".blocoContactos .divContactos").addClass("posRelative");



	$(".blocoGrupoEContactos").each(function(){
		var cgroup_row = $(this);
		//correr cada input e colocar o nome do grupo.
		//neste exemplo, uso o mesmo nome para todos:
		//$(".row_grupo input", cgroup_row).val("Nome do Grupo");
		
		//colocar o primeiro item das combos como "Seleccionar":
		$(".combobox_header input", cgroup_row).val("Seleccionar");
		
		//mostrar/esconder os contactos ao clicar na seta do grupo:
		var cgroup_elements_to_toggle = $(".blocoContactos",cgroup_row);
		var cgroup_headers = $(".bullet",cgroup_row);
	
		cgroup_headers.css("cursor","pointer").bind("click",function(){
			cgroup_elements_to_toggle.slideToggle();
			cgroup_headers.toggleClass("open");
		});
		
	});
	
	
	/*-------------------------*/
	//adicionar novo grupo:
	//$("div [@name^=adicionarGrupo]").hide();
	$(".adicionar img").css("cursor", "pointer").click(function(){
		$(this).parent().hide();
		$(this).parent().siblings('div').show();
	});
	
	$("#addGroup").click(function(){
	    if($("#auth").val() != "False")
        {
	        var groupName = $(this).parent().siblings("#groupNameValue").val();
	        $("#submitInfo INPUT[@name='action']").val("addGroup");
	        $("#submitInfo INPUT[@name='groupName']").val(groupName);
	        window.open("/OMeuOptimus/Contactos/GestaoContactosGruposConfirmacao.aspx",
            "wConfirmacao", "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }

	});
	
	$("[@name=deleteGroup]").click(function(){

        if($("#auth").val() != "False")
        {
	        var groupId = $(this).parent().parent().parent().parent().attr("groupId");
	        $("#submitInfo INPUT[@name='action']").val("deleteGroup");
	        $("#submitInfo INPUT[@name='groupId']").val(groupId);
	        window.open("/OMeuOptimus/Contactos/GestaoContactosGruposConfirmacao.aspx",
            "wConfirmacao", "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }

	});
	
	$("[@name=changeGroup]").click(function(){

        if($("#auth").val() != "False")
        {
	        var groupId = $(this).parent().parent().parent().attr("groupId");
	        var groupName = $(this).parent().siblings("INPUT [@name=textfield]").val();
	        $("#submitInfo INPUT[@name='action']").val("changeGroup");
	        $("#submitInfo INPUT[@name='groupId']").val(groupId);
	        $("#submitInfo INPUT[@name='groupName']").val(groupName);
	        window.open("/OMeuOptimus/Contactos/GestaoContactosGruposConfirmacao.aspx",
            "wConfirmacao", "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }

	});
	
	$("[@name=sendGroupMessage]").click(function(){
	    var numbers = '';
	    var data = $(".telm",$(this).parent().parent().parent().siblings("div"));
	    
	    for(var i = 0; i < data.length; ++i)
        {
            if('' == numbers)
            {
                numbers = data[i].innerHTML;
            }
            else
            {
                numbers = numbers + ';' + data[i].innerHTML;
            }
	    }

	    $('#phones').val(numbers);
        var loc = window.location.href.toLowerCase();
        var idx = loc.lastIndexOf('contactos/');
        var url = '';
        if(idx > 1)
            url = window.location.href.substring(0, idx-1) + "/EnviarSMS";
        if(numbers != '')
            url += "?numbers=" + numbers;       
                 
        $("#goToSms").attr('action', url);  
        $("#goToSms").submit();
        //$("#submitInfo INPUT[@name='action']").val("sendMessage");
	    //alert('Enviar mensagem.');

	});
	
	$("[@name=addContact]").click(function(){
	    if($("#auth").val() != "False")
        {
	        //var info = $(this).parent().siblings("#groupNameValue").val();
	        var groupId = $(this).parent().parent().parent().parent().attr("groupId");
	        var aux = $(this).parent().siblings(".menu_contactos");
	        var contactId = $("INPUT[@name='opcao_contactos']" , aux).val();
	        if("Seleccionar" == contactId)
	            return;
	        $("#submitInfo INPUT[@name='action']").val("addContact");
	        $("#submitInfo INPUT[@name='groupId']").val(groupId);
	        $("#submitInfo INPUT[@name='contactId']").val(contactId);
	        window.open("/OMeuOptimus/GestaoContactosGruposConfirmacao.aspx",
            "wConfirmacao", "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
	});
	
	$("[@name=deleteContact]").click(function(){
        if($("#auth").val() != "False")
        {
	        var groupId = $(this).parent().parent().parent().parent().parent().parent().attr("groupId");
	        var contactId = $(this).parent().parent().parent().parent().attr("contactId");
	        $("#submitInfo INPUT[@name='action']").val("deleteContact");
	        window.open("/OMeuOptimus/GestaoContactosGruposConfirmacao.aspx",
            "wConfirmacao", "width=520,height=270,resizable=yes,srollbars=no,toolbar=no,location=no,menubar=no");
        }
        else
        {
            document.getElementById("notLogged").style.visibility = 'visible';
        }
	});
});

function InitializeReservaPontosBehavior(col_equipamento,cores)
{
	$(".precos INPUT",col_equipamento).each(function(){
	    $(this).bind("click",function(event){
		    event.stopPropagation();
		    //só entra nesta situação, caso seja um telemóvel que esteja em modo reserva
            if( '0' == cores[$(col_equipamento).get(0).cor_idx].disponivel && '0' == cores[$(col_equipamento).get(0).cor_idx].descontinuado && '1' == cores[$(col_equipamento).get(0).cor_idx].reserva)
            {			    
		        //se o value é "0" é porque o preço é "normal" aparece o botão reservar
		        if ($(this).attr("value") == "0")
		        {
                    $(".bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_reservar_.gif");
                    $(".bot_comprar img",col_equipamento).attr("alt","reservar");
                    $(".bot_comprar img",col_equipamento).attr("style","");
                    $("a.bot_comprar",col_equipamento).attr("rel","reservar");			    
		        }
		        //caso contrário é com pontos e mostra o botão comprar
		        else
		        {
                    $(".bot_comprar img",col_equipamento).attr("src","/img/telemoveis_bot_comprar_.gif");
                    $(".bot_comprar img",col_equipamento).attr("style","padding-right: 8px; padding-left: 9px");
                    $(".bot_comprar img",col_equipamento).attr("alt","comprar");
                    $("a.bot_comprar",col_equipamento).attr("rel","comprar");				    
		        }				
		    }
	    });		
	});	
}


var validatorAddContact;
var validatorUpdateContacts;
var titleContactsNome;
var titleContactsTelem;
var titleContactsEmail;

function SubmitContactGroup()
{
    window.close();
    if (window.opener && !window.opener.closed)
    {
        window.opener.document.getElementById("submitInfo").submit();
    }

}

var submitSource = 0;
function VerifySubmit()
{
    var toReturn = submitSource;
    submitSource = 0;
    if(1 == toReturn)
        return false;
    else
        return true;
}

function ShowDemoFlash(canal, conteudo, width, height, urlText)
{
    window.open('/Repositorio/PopupFlash.aspx?ChannelId=' + escape(canal) + '&ContentId=' + escape(conteudo), '', 'height=' + height + ',width=' + width + ',scrollbars=yes,resizable=yes');
}

function ShowDemoHtml(canal, conteudo, width, height, urlText)
{
    window.open('/Repositorio/PopupHtml.aspx?ChannelId=' + escape(canal) + '&ContentId=' + escape(conteudo), '', 'height=' + height + ',width=' + width + ',scrollbars=yes,resizable=yes');
}
function ShowStreaming(canal, conteudo, width, height)
{
    window.open('/Repositorio/PopupStreaming.aspx?ChannelId=' + escape(canal) + '&ContentId=' + escape(conteudo), '', 'height=' + height + ',width=' + width + ',scrollbars=yes,resizable=yes');
}


