$(document).ready(function(){
	$("a.to_btn").mouseover(function(){
		$(this).addClass('to_over');
    }).mouseout(function(){
     	$(this).removeClass('to_over');
    });
    
    $("a.to_btn").mouseover(function(){
		$(this).addClass('to_over');
    }).mouseout(function(){
     	$(this).removeClass('to_over');
    });
	
	$(".to_dropdown a").mouseover(function(){
		$(this).css("color","#ff7000");
    }).mouseout(function(){
     	$(this).css("color","#A9A9A9");
    });
		
	$(".to_dropdown a").click(function(){
		$(this).css("color","#ff7000");
    });

	$("body").append('<table id="to_tooltip"><tr><td class="to_t_cse"></td><td class="to_t_bt"></td><td class="to_t_csd"></td></tr><tr><td class="to_t_bl"></td><td><div class="to_t_text"></div></td><td class="to_t_br"></td></tr><tr><td class="to_t_cie"></td><td class="to_t_bb"></td><td class="to_t_cid"></td></tr></table>');

	$(".to_tooltip_btn span").mouseover(function(){
		$("#to_tooltip").fadeIn("fast");
		$(".to_t_text").text($($(this).parent()).attr('title'));
	}).mouseout(function(){
		$("#to_tooltip").fadeOut("fast");
	});
	
	$(".to_tooltip_btn span").mousemove(function(e){
		$("#to_tooltip").css('top', (e.pageY-40)+"px")
						.css('left', (e.pageX+35)+"px");
	});
});



function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (var i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }


function checkNumeros(isto){
	var numero = $(isto).attr("value");
	if (numero!=null) {
		if (IsNumeric(numero)==1) {
			if (numero.split("",1)!="9") {
				$(isto).attr({value:numero.slice(0, -1)});}
		} else {
		try{
		$(isto).attr({value:numero.slice(0, -1)});
		}catch(excep){}
		}
	}
}

function checkNumerosFixoEMoveis(isto){
	var numero = $(isto).attr("value");
	if (numero!=null) {
		if (IsNumeric(numero)==1) {
			if (numero.split("",1)!="9" && numero.split("",1)!="2" ) {
				$(isto).attr({value:numero.slice(0, -1)});}
		} else {
		try{
		$(isto).attr({value:numero.slice(0, -1)});
		}catch(excep){}
		}
	}
}

function checkIfIsFullNumbers()
{
    for (var i=1;i<=($("#passo2_caixa1_d .to_cx_tit i").text());i++) {
        if($("#cx_num"+i).attr("value")==null)
		    return false;
    }
    return true;
}

function checkNumeros2(full){

	var cont = 0;
	for (var i=0;i<window.num_tels.length;i++) {
		window.num_tels[i]="";
	}

    var isRepeat = false;
    var considerFull = false;
    
    if(full != null && full != "")
        considerFull = true;
        
    
        
	for (var i=1;i<=($("#passo2_caixa1_d .to_cx_tit i").text());i++) {
		if ($("#cx_num"+i).attr("value")!=null) {
			if ($("#cx_num"+i).attr("value").length==9 && !isAlreadyInList($("#cx_num"+i).attr("value")) ) {
				cont++;
				$("#cx_num"+i).css("color","#A9A9A9");
				window.num_tels[cont]=$("#cx_num"+i).attr("value");
				window.validado = 1;
			} else {
				$("#cx_num"+i).css("color","red");
				// $(".to_dropdown_erro").css("display","block");
				window.validado = 0;
				//isRepeat = true;
			}
		}
		else if(considerFull)
		{
		   if($("#cx_num"+i).attr("value")==null)
		   {
		       $(".to_dropdown_erro").css("display","block");
		       window.validado = 0;
		    }
		}
		
	}
	if(!considerFull && !isRepeat)
	    $(".to_dropdown_erro").css("display","none");
}

function isAlreadyInList(num)
{
    for (var i=0;i<window.num_tels.length;i++) {
		if(window.num_tels[i]==num)
		    return true;
	}
	
	return false;
}

function alreadyExistsInArray(arr,num)
{
    for (var i=0;i<arr.length;i++) {
        if(arr[i] == num)
            return true;
    }
    return false;
}

function extraExceptionIsAlreadyInList()
{
    var arr = new Array();
    for (var i=1;i<=($("#passo2_caixa1_d .to_cx_tit i").text());i++) {
        
        if(alreadyExistsInArray(arr,$("#cx_num"+i).attr("value")))
            return true;
        else
           arr[i] =  $("#cx_num"+i).attr("value");
    }
    return false;
}

function haveInvalidNumbers()
{
    for (var i=1;i<=($("#passo2_caixa1_d .to_cx_tit i").text());i++) {
        if($("#cx_num"+i).attr("value").length!=9)
            return true;
    }   
    return false; 
}

function checkNumeros3(isto){
	if ($(isto).attr("value").length==9) {
		$("#to_erro_tel").css("display","none");
	} else {
		$("#to_erro_tel").css("display","block");
	}
}



function checkPost(postal,isto) {
	var numero = $(isto).attr("value");	
	if (numero!=null) {
		if (IsNumeric(numero)==1) {
			if (postal=="1") {
				if (numero.length<=4) {
				} else {$(isto).attr({value:numero.slice(0, -1)});}
			} else if (postal=="2") {
				if (numero.length<=3) {
				} else {$(isto).attr({value:numero.slice(0, -1)});}
			}
		} else {$(isto).attr({value:numero.slice(0, -1)});}
	}
}

function checkNIF (isto) {
	var numero = $(isto).attr("value");	
	if (numero!=null) {
		if (IsNumeric(numero)==1) {
			if (numero.length<=9) {
			} else {
			    try{
		            $(isto).attr({value:numero.slice(0, -1)});
		       }catch(excep){}
		    }
	}
	} else { try{$(isto).attr({value:numero.slice(0, -1)}); }catch(excep){}}
}

function checkNIF2(isto) {
	var numero = $(isto).attr("value");	
	if (numero!=null) {
		if (IsValidNIF(numero)==false) {
			$("#to_erro_nif").css("display","block");
		} else {
			$("#to_erro_nif").css("display","none");
		}
	}
}

function IsValidNIF(nif)
{
    var c;
    var checkDigit = 0;
    //Check if is not null, is numeric and if has 9 numbers
    if(nif != null && IsNumeric2(nif) && nif.length == 9)
    {
        //Get the first number of NIF
        c = nif.charAt(0);
        //Check firt number is (1, 2, 5, 6, 8 or 9)
        if(c == "1" || c == "2" || c == "5" || c == "6" || c == "8" || c == "9")
        {
            //Perform CheckDigit calculations
            checkDigit = c * 9;
            var i = 0;
            for(var i = 2; i <= 8; i++)
            {
                checkDigit += nif.charAt(i-1) * (10-i);
            }
            checkDigit = 11 - (checkDigit % 11);
            //if checkDigit is higher than ten set it to zero
            if(checkDigit >= 10)
                checkDigit = 0;
            //Compare checkDigit with the last number of NIF
            //If equal the NIF is Valid.           
            if(checkDigit == nif.charAt(8))
                return true;           
        }       
    }
    return false;
}

function checkEmail(isto) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(isto.value)){
		return (true)
	}
	return (false)
}

function checkMail (isto) {
	if (checkEmail(isto)==0) {
		$("#to_erro_mail").css("display","block");
	} else {
		$("#to_erro_mail").css("display","none");
	}
}


function validateFromData(){
    var nameVal = checkGeneric("to_nome","#to_erro_nome");
    var adressVal = checkGeneric("to_morada","#to_erro_morada");
    var locationVal = checkLocation();
    var nifVal = IsValidNIF(document.getElementById("to_nif").value);
    var extraInfo = true;
    checkNifValidation(nifVal)
    
    if(document.getElementById("to_email").value != "")
    {
        if(checkEmail(document.getElementById("to_email"))==0)
            extraInfo = false;
    }
    else if(document.getElementById("to_tel").value != "")
    {
        checkNumerosFixoEMoveis("to_tel")
        if($("#to_tel").attr("value").length != 9)
            extraInfo = false;
    }
    
    if(nameVal && adressVal && locationVal && nifVal && extraInfo)
        return true
    return false;
}

function checkNifValidation(flag)
{
    if(!flag)
		$("#to_erro_nif").css("display","block");
	else
		$("#to_erro_nif").css("display","none");
}

function checkLocation() {
    if (document.getElementById("to_cod_post1").value == "" || document.getElementById("to_cod_post2").value == "" || document.getElementById("to_localidade").value == "")
    {
        $("#to_erro_codp").css("display","block");
        return false;
    }
    else {
        $("#to_erro_codp").css("display","none");
        return true;
    }
}

function checkGeneric(id, errorId) {
    if (document.getElementById(id).value == ""){
        $(errorId).css("display","block");
        return false;
    }
    else {
        $(errorId).css("display","none");
        return true;
    }
}


function IsNumeric2(ObjVal) {
	return /^\d+$/.test(ObjVal);
} 


function voarActivar(tipo,val,topi,topf,isto) {
	$("#tar_"+tipo+" .to_cx_valseta").animate({ 
		top: topi+"px",
		opacity: "0"
	}, 500 , function () {
		$("#tar_"+tipo+" .to_cx_valseta").animate({ 
			top: topf+"px",
			opacity: "1"
		}, 500 );
		$("#tar_"+tipo+" .to_cx_valseta").text(""+val);
	});

}

function passo2(tipo,activo,under,isto) {
	if (!$(isto).is(".to_active")) { //se o butão tiver activo
		var to_active=1;
		$("#tarifas_"+tipo+"_"+under+" a").removeClass('to_active'); //desactiva todos do grupo
		$(isto).addClass('to_active'); //activa somente o clicado
	} else {
		if (under==1) {	//se o butão for do primeiro grupo
			$("#tarifas_"+tipo+"_"+under+" a").removeClass('to_active'); //desactiva todos do grupo
		}
	}

	if (under==1) { //se for do primeiro grupo
			if ((to_active!=1)||(activo=="desactivar")) {
				if (to_active!=1) {
					valores(tipo,"_1",0,0,0,0);
					valores(tipo,"_2",0,0,0,0);
				} 
				if (activo=="desactivar") {
					valores(tipo,"_2",0,0,0,0);
				} 
				$("#tarifas_"+tipo+"_2 a").removeClass('to_active');
				if ("#passo2_"+tipo+" .to_tapa_branco"=="#passo2_caixa1 .to_tapa_branco") {
					$(".to_dropdown").css('zIndex',"" );
					$("#passo2_caixa1 .to_tapa_branco").css('zIndex', "");
					$("#dropdown_numeros").css('zIndex', "");
					$("#dropdown_numeros").css("backgroundPosition","0 bottom");
					$("#dropdown_numeros .to_dropdown_n").css("display","none");
					$("#passo2_caixa1_2 .to_dropdown .to_dropdown_cont").animate({ 
						height: "0px",
						opacity: "0"
					 }, 500 );
				}
				$("#passo2_"+tipo+" .to_tapa_branco").css('display', "block");
				$("#passo2_"+tipo+" .to_tapa_branco").animate({
					opacity: "0.6"
				  }, 500);
				$("#passo2_"+tipo+"_d .to_tapa_branco").css("display","block");
				$("#passo2_"+tipo+"_d .to_tapa_branco").animate({ 
					opacity: "1"
				  }, 500);
			} else {
				$("#passo2_"+tipo+" .to_tapa_branco").animate({ 
					opacity: "0"
				  }, 500, function () {
					  $("#passo2_"+tipo+" .to_tapa_branco").css('display', "none");
				  });
				if ("#passo2_"+tipo+" .to_tapa_branco"=="#passo2_caixa1 .to_tapa_branco") {
					$(".to_dropdown").css('zIndex', 10);
					$("#passo2_caixa1 .to_tapa_branco").css('zIndex', 1000);
				}
			}
		} else if (under==2) {
			$("#passo2_"+tipo+"_d .to_tapa_branco").animate({ 
				opacity: "0"
			  }, 500, function () {
				  $("#passo2_"+tipo+"_d .to_tapa_branco").css("display","none");
			});
		}
}

function dropDownMenu(val) {
    
	if (val=="menos") {
		$("#dropdown_menos").css('display', "block");
		$("#dropdown_mais").css('display', "none");
		//$("#tarifas_caixa1_2").css('zIndex', 0);
	} else { 
		$("#dropdown_menos").css('display', "none");
		$("#dropdown_mais").css('display', "block");
		//$("#dropdown_mais").css('zIndex', 2000);
		//$("#tarifas_caixa1_2").css('zIndex', 2000);
	}
}

function especial(tipo,activo,val,isto) {
	if (!$(isto).is(".to_active")) {
		var to_active=1;
		$("#tarifas_"+tipo+" a").removeClass('to_active');
		$(isto).addClass('to_active');
	} else {
		$("#tarifas_"+tipo+" a").removeClass('to_active');
	}
	
	$("#tar_"+tipo+" .to_cx_valseta").animate({ 
		opacity: "0"
	}, 500 , function () {
		if ((to_active!=1)||(activo=="desactivar")) {
		} else {
			$("#tar_"+tipo+" .to_cx_valseta").animate({ 
				opacity: "1"
			}, 500 );
			$("#tar_"+tipo+" .to_cx_valseta").text(""+val);
		}
	});

	if ((to_active!=1)||(activo=="desactivar")) {
		valores(tipo,'',0,0,0,0);
		$("#passo2_"+tipo+"_d .to_tapa_branco").css("display","block");
		$("#passo2_"+tipo+"_d .to_tapa_branco").animate({ 
			opacity: "1"
		}, 500);
	} else {
		$("#passo2_"+tipo+"_d .to_tapa_branco").animate({ 
			opacity: "0"
		}, 500, function () {
			$("#passo2_"+tipo+"_d .to_tapa_branco").css("display","none");
		});
	}
}


window.aberto =0;

function passo3(tipo,div,isto) {
	$("#passo3_caixa1 a").removeClass('to_active');
	$(isto).addClass('to_active');

	if (window.aberto == 0) {
		$("#"+div).css('display', "block");
		//$("#passo3_caixa1 .to_cx_img_e").css('backgroundImage','url(../img/caixa_111px_e_desce.png)'); 
		//$("#passo3_caixa1 .to_cx_img_d").css('backgroundImage','url(../img/caixa_111px_d_desce.png)');
		$(".to_p3_d_f").css('display', "block");
        $(".to_p3_d").slideDown("slow");
		window.to_ul_dp = div;
		window.aberto = 1;
    } else {
        $(".to_p3_d").slideUp("slow", function () {
			$(".to_dp").css('display', "none");
			//$("#passo3_caixa1 .to_cx_img_e").css('backgroundImage','url(../img/caixa_111px_e.png)'); 
			//$("#passo3_caixa1 .to_cx_img_d").css('backgroundImage','url(../img/caixa_111px_d.png)');
			$(".to_p3_d_f").css('display', "none");
			if (window.to_ul_dp!=div) {
				$("#"+div).css('display', "block");
				$(".to_p3_d").slideDown("slow");
				//$("#passo3_caixa1 .to_cx_img_e").css('backgroundImage','url(../img/caixa_111px_e_desce.png)'); 
				//$("#passo3_caixa1 .to_cx_img_d").css('backgroundImage','url(../img/caixa_111px_d_desce.png)');
				$(".to_p3_d_f").css('display', "block");
				window.to_ul_dp = div;
				window.aberto = 1;
			} else {
				$(isto).removeClass('to_active');	
				window.aberto = 0;
			}
			$(".to_p3_d").css('display', "block");
		});
    }
	
}

function dropDownNum(numTel,custo) {
	
	$("#dropdown_menos .to_dropdown_av b").text(""+numTel);
	$("#dropdown_menos .to_dropdown_av i").text(""+custo);
	$("#dropdown_mais .to_dropdown_av b").text(""+numTel);
	$("#dropdown_mais .to_dropdown_av i").text(""+custo);
	
	$("#passo2_caixa1_d .to_cx_tit i").text(""+numTel);
	$("#passo2_caixa1_d .to_cx_valseta i").text(""+custo);

	$("#passo2_caixa1_d .to_tapa_branco").animate({ 
		opacity: "0"
		}, 500, function () {
			$("#passo2_caixa1_d .to_tapa_branco").css("display","none");
	});
	$(".dropdown_numeros").css('zIndex', 10);
	
	$(".to_dropdown_n input").remove();
	for (var i=numTel;i>0;i--) {
		$("#passo2_caixa1_d .to_dropdown_n").prepend("<input onkeydown='checkNumerosFixoEMoveis(this)' onkeyup='checkNumerosFixoEMoveis(this)' maxlength='9' onchange='checkNumeros2(false)' type='text' id='cx_num"+i+"' value='"+window.num_tels[i]+"' />");
	}

}

function toolTip_on(texto) {
	$("#to_tooltip").css('display', "block");
	$("#to_tooltip").css('left', "1px");
	$("#to_tooltip").css('top', pageY+"px");
	$(".to_t_text").text("texto");
}

function toolTip_off() {
	$("#to_tooltip").css('display', "none");
}

var aidis=new Array();
aidis["optimus"]=new Array(0,0,0,0);
aidis["outras"]=new Array(0,0,0,0);
aidis["caixa1_1"]=new Array(0,0,0,0);
aidis["caixa1_2"]=new Array(0,0,0,0);
aidis["caixa2_1"]=new Array(0,0,0,0);
aidis["caixa2_2"]=new Array(0,0,0,0);
aidis["caixa3_1"]=new Array(0,0,0,0);
aidis["caixa3_2"]=new Array(0,0,0,0);
aidis["caixa4_1"]=new Array(0,0,0,0);
aidis["caixa4_2"]=new Array(0,0,0,0);
aidis["caixa5_1"]=new Array(0,0,0,0);
aidis["caixa5_2"]=new Array(0,0,0,0);
aidis["caixa6"]=new Array(0,0,0,0);

function valores(tipo,under,per1,per2,per3,val) {
	aidis[tipo+""+under][0]=per1;
	aidis[tipo+""+under][1]=per2;
	aidis[tipo+""+under][2]=per3;
	aidis[tipo+""+under][3]=val;
	
	
	var poupa1 = aidis["optimus"][0]+aidis["outras"][0]+aidis["caixa1_1"][0]+aidis["caixa1_2"][0]+aidis["caixa2_1"][0]+aidis["caixa2_2"][0]+aidis["caixa3_1"][0]+aidis["caixa3_2"][0]+aidis["caixa4_1"][0]+aidis["caixa4_2"][0]+aidis["caixa5_1"][0]+aidis["caixa5_2"][0]+aidis["caixa6"][0];
	var poupa2 = aidis["optimus"][1]+aidis["outras"][1]+aidis["caixa1_1"][1]+aidis["caixa1_2"][1]+aidis["caixa2_1"][1]+aidis["caixa2_2"][1]+aidis["caixa3_1"][1]+aidis["caixa3_2"][1]+aidis["caixa4_1"][1]+aidis["caixa4_2"][1]+aidis["caixa5_1"][1]+aidis["caixa5_2"][1]+aidis["caixa6"][1];
	var poupa3 = aidis["optimus"][2]+aidis["outras"][2]+aidis["caixa1_1"][2]+aidis["caixa1_2"][2]+aidis["caixa2_1"][2]+aidis["caixa2_2"][2]+aidis["caixa3_1"][2]+aidis["caixa3_2"][2]+aidis["caixa4_1"][2]+aidis["caixa4_2"][2]+aidis["caixa5_1"][2]+aidis["caixa5_2"][2]+aidis["caixa6"][2];
	var poupa4 = aidis["optimus"][3]+aidis["outras"][3]+aidis["caixa1_1"][3]+aidis["caixa1_2"][3]+aidis["caixa2_1"][3]+aidis["caixa2_2"][3]+aidis["caixa3_1"][3]+aidis["caixa3_2"][3]+aidis["caixa4_1"][3]+aidis["caixa4_2"][3]+aidis["caixa5_1"][3]+aidis["caixa5_2"][3]+aidis["caixa6"][3];
	
	$("#to_barra_1 .to_barra").animate({ 
		marginLeft: "-"+(100-poupa1)+"px"
		}, 500);
	$("#to_barra_1 .to_barra_perc div").animate({ 
		width: poupa1+"px"
		}, 500);
	$("#to_barra_1 .to_barra_perc span").text(""+poupa1);

	$("#to_barra_2 .to_barra").animate({ 
		marginLeft: "-"+(100-poupa2)+"px"
		}, 500);
	$("#to_barra_2 .to_barra_perc div").animate({ 
		width: poupa2+"px"
		}, 500);
	$("#to_barra_2 .to_barra_perc span").text(""+poupa2);

	$("#to_barra_3 .to_barra").animate({ 
		marginLeft: "-"+(100-poupa3)+"px"
		}, 500);
	$("#to_barra_3 .to_barra_perc div").animate({ 
		width: poupa3+"px"
		}, 500);
	$("#to_barra_3 .to_barra_perc span").text(""+poupa3);
	
	$(".to_carr_mens span").text(""+poupa4);
}

    function blabla(){alert();}

    /***
    *	Javascript Tarifário Online Passo2
    ****/
    var withCombinations = new Boolean(false);

    //matriz das combinacoes
    var combinationsMatrix;
    //hashtable com os resultados das combinacoes
    var combinationsHT = new jQuery.Hashtable();


    //key typeName, value index
    var typesHT = new jQuery.Hashtable();
    var codesHT = new jQuery.Hashtable();
    var inverseTypesCodesHT = new jQuery.Hashtable();


    //valores ja seleccionados
    var selectedValues = new Array();

    //criado quando se preenche as HT de types e codes
    var selectedButtons;


    /***
    *	Objecto Assoc para associar os nomes de um type e um code
    ****/
    function Assoc(typeName,codeName)
    {
        this._typeName = typeName;
        this._codeName = codeName;
    }

    Assoc.prototype.getTypeName = function(){return this._typeName;}
    Assoc.prototype.getCodeName = function(){return this._codeName;}


    /***
    * Objecto WSResult obtem os valores vindos por JSON e e' guardado na hashtable combinationsHT
    ****/
    function WSResult(ro,percentGroup,percentOffNet,percentSaveSMS)
    {
        this._ro = ro;
        this._percentGroup = percentGroup;
        this._percentOffNet = percentOffNet;
        this._percentSaveSMS = percentSaveSMS;
    }

    WSResult.prototype.getRo = function(){return this._ro;}
    WSResult.prototype.getPercentGroup = function(){return this._percentGroup;}
    WSResult.prototype.getPercentOffNet = function(){return this._percentOffNet;}
    WSResult.prototype.getPercentSaveSMS = function(){return this._percentSaveSMS;}



			/***
			*	Javascript Tarifário Online Passo2
			****/
			var withCombinations = new Boolean(false);

			//matriz das combinacoes
			var combinationsMatrix;
			//hashtable com os resultados das combinacoes
			var combinationsHT = new jQuery.Hashtable();


			//key typeName, value index
			var typesHT = new jQuery.Hashtable();
			var codesHT = new jQuery.Hashtable();
			var inverseTypesCodesHT = new jQuery.Hashtable();


			//valores ja seleccionados
			var selectedValues = new Array();

			//criado quando se preenche as HT de types e codes
			var selectedButtons;


			/***
			*	Objecto Assoc para associar os nomes de um type e um code
			****/
			function Assoc(typeName,codeName)
			{
			this._typeName = typeName;
			this._codeName = codeName;
			}

			Assoc.prototype.getTypeName = function(){return this._typeName;}
			Assoc.prototype.getCodeName = function(){return this._codeName;}


			/***
			* Objecto WSResult obtem os valores vindos por JSON e e' guardado na hashtable combinationsHT
			****/
			function WSResult(ro,percentGroup,percentOffNet,percentSaveSMS)
			{
			this._ro = ro;
			this._percentGroup = percentGroup;
			this._percentOffNet = percentOffNet;
			this._percentSaveSMS = percentSaveSMS;
			}

			WSResult.prototype.getRo = function(){return this._ro;}
			WSResult.prototype.getPercentGroup = function(){return this._percentGroup;}
			WSResult.prototype.getPercentOffNet = function(){return this._percentOffNet;}
			WSResult.prototype.getPercentSaveSMS = function(){return this._percentSaveSMS;}

		   

    /***
    * Campos de submissão
    ****/

    var hfId = null;
    var currRo = null
    var tarifOptimusValue = null;
    var tarifOthersValue = null;
    var tarifSMSValue = null;
    var tarifOptimusCode = null;
    var tarifOthersCode = null;
    var tarifSMSCode = null;

    var tarifEspecialVozGrupoCode = null;
    var nrChoosen = null;
    var tarifEspecialVozOffNetCode = null;
    var tarifEspecialSMSOnNetCode = null;
    var tarifEspecialVozInternacionalCode = null;
    var tarifEspecialVozRoamingCode = null;
    var tarifEspecialInternetCode = null;

    var tarifEspecialVozGrupoVal = null;
    var tarifEspecialVozOffNetVal = null;
    var tarifEspecialSMSOnNetVal = null;
    var tarifEspecialVozInternacionalVal = null;
    var tarifEspecialVozRoamingVal = null;
    var tarifEspecialInternetVal = null;

    var poupancaGrupo = null;
    var poupancaOutras = null;
    var poupancaSMS = null;
    
    var clientName = null;
    var clientAdress = null;
    var clientCP4 = null;
    var clientCP3 = null;
    var clientCity = null;
    var clientNTel = null;
    var clientEmail = null;
    var clientNIF = null;
    
    var nonActiveBtns = null;
    
    var isDataFromCookie = false;
    
    var enableStep4FinalizeBtn = null;

    function setHfId(id,ro,top,tou,tsms,topc,touc,tsmsc, tevgc, nc, tevonc, tesmsc, tevic, tevrc, teic,pg,po,psms,tevgv, tevonv, tesmsv, teviv, tevrv, teiv,nab, es4fb){
        hfId = id;
        currRo = ro;
        tarifOptimusValue = top;
        tarifOthersValue = tou;
        tarifSMSValue = tsms;
        tarifOptimusCode = topc;
        tarifOthersCode = touc;
        tarifSMSCode = tsmsc;
        
        tarifEspecialVozGrupoCode = tevgc;
        nrChoosen = nc;
        tarifEspecialVozOffNetCode = tevonc;
        tarifEspecialSMSOnNetCode = tesmsc;
        tarifEspecialVozInternacionalCode = tevic;
        tarifEspecialVozRoamingCode = tevrc;
        tarifEspecialInternetCode = teic;
        
        tarifEspecialVozGrupoVal = tevgv;
        tarifEspecialVozOffNetVal = tevonv;
        tarifEspecialSMSOnNetVal = tesmsv;
        tarifEspecialVozInternacionalVal = teviv;
        tarifEspecialVozRoamingVal = tevrv;
        tarifEspecialInternetVal = teiv;
        
        poupancaGrupo = pg;
        poupancaOutras = po;
        poupancaSMS = psms;
        
        nonActiveBtns = nab;
        
        enableStep4FinalizeBtn = es4fb;
        
        if(!isIE())
        {
            hfId = hfId.replace(/\$/gi, "_");    
            currRo = currRo.replace(/\$/gi, "_");
            tarifOptimusValue = tarifOptimusValue.replace(/\$/gi, "_");
            tarifOthersValue = tarifOthersValue.replace(/\$/gi, "_");    
            tarifSMSValue = tarifSMSValue.replace(/\$/gi, "_");    
            tarifOptimusCode = tarifOptimusCode.replace(/\$/gi, "_");    
            tarifOthersCode = tarifOthersCode.replace(/\$/gi, "_");    
            tarifSMSCode = tarifSMSCode.replace(/\$/gi, "_");    
            
            tarifEspecialVozGrupoCode = tarifEspecialVozGrupoCode.replace(/\$/gi, "_");
            nrChoosen = nrChoosen.replace(/\$/gi, "_");
            tarifEspecialVozOffNetCode = tarifEspecialVozOffNetCode.replace(/\$/gi, "_");
            tarifEspecialSMSOnNetCode = tarifEspecialSMSOnNetCode.replace(/\$/gi, "_");
            tarifEspecialVozInternacionalCode = tarifEspecialVozInternacionalCode.replace(/\$/gi, "_");
            tarifEspecialVozRoamingCode = tarifEspecialVozRoamingCode.replace(/\$/gi, "_");
            tarifEspecialInternetCode = tarifEspecialInternetCode.replace(/\$/gi, "_");
            
            poupancaGrupo = poupancaGrupo.replace(/\$/gi, "_");
            poupancaOutras = poupancaOutras.replace(/\$/gi, "_");
            poupancaSMS = poupancaSMS.replace(/\$/gi, "_");
            
            tarifEspecialVozGrupoVal = tarifEspecialVozGrupoVal.replace(/\$/gi, "_");
            tarifEspecialVozOffNetVal = tarifEspecialVozOffNetVal.replace(/\$/gi, "_");
            tarifEspecialSMSOnNetVal = tarifEspecialSMSOnNetVal.replace(/\$/gi, "_");
            tarifEspecialVozInternacionalVal = tarifEspecialVozInternacionalVal.replace(/\$/gi, "_");
            tarifEspecialVozRoamingVal = tarifEspecialVozRoamingVal.replace(/\$/gi, "_");
            tarifEspecialInternetVal = tarifEspecialInternetVal.replace(/\$/gi, "_");
            
            nonActiveBtns = nonActiveBtns.replace(/\$/gi, "_");
            
            enableStep4FinalizeBtn = enableStep4FinalizeBtn.replace(/\$/gi, "_");
        }
    }
    
    function setHfIdStep4(cn,ca,cp4,cp3,cc,cnt,ce,cnif)
    {
        
        clientName = cn;
        clientAdress = ca;
        clientCP4 = cp4;
        clientCP3 = cp3;
        clientCity = cc;
        clientNTel = cnt;
        clientEmail = ce;
        clientNIF = cnif;
    }


    function isIE() 
    {
	    var ua = navigator.userAgent;
	    if (ua.indexOf("MSIE 6") > -1 || ua.indexOf("MSIE 7") > -1)
	    { 
		    return true;
		}
    return false;
    }

    function submitStep(n){
        if(document.getElementById(hfId) != null)
           document.getElementById(hfId).value = n;

        if(!isDataFromCookie)
        {
        if(document.getElementById("ro_value") != null && document.getElementById(currRo) != null)
           document.getElementById(currRo).value = document.getElementById("ro_value").innerHTML;     
           
        if(document.getElementById("vox_optimus_value") != null && document.getElementById(tarifOptimusValue) != null)
        {
           var val = document.getElementById("vox_optimus_value").innerHTML;
           document.getElementById(tarifOptimusValue).value = val.split(" ")[1];
        }
        if(document.getElementById("vox_others_value") != null && document.getElementById(tarifOthersValue) != null)
        {
           var val = document.getElementById("vox_others_value").innerHTML;
           document.getElementById(tarifOthersValue).value = val.split(" ")[1];
        }
        if(document.getElementById("sms_value") != null && document.getElementById(tarifSMSValue) != null)
           document.getElementById(tarifSMSValue).value = document.getElementById("sms_value").innerHTML;    
        
        if(document.getElementById("optimusCode") != null && document.getElementById(tarifOptimusCode) != null && document.getElementById("optimusCode").value != "")
           document.getElementById(tarifOptimusCode).value = document.getElementById("optimusCode").value;
        
        if(document.getElementById("othersCode") != null && document.getElementById(tarifOthersCode) != null && document.getElementById("othersCode").value != "")
           document.getElementById(tarifOthersCode).value = document.getElementById("othersCode").value;

        if(document.getElementById("SmsCode") != null && document.getElementById(tarifSMSCode) != null && document.getElementById("SmsCode").value != "")
           document.getElementById(tarifSMSCode).value = document.getElementById("SmsCode").value;

        if(selectedValues.length != 0)
        {

                document.getElementById(tarifEspecialVozGrupoCode).value = "";
                document.getElementById(tarifEspecialVozGrupoCode).value = "";
                document.getElementById(tarifEspecialVozOffNetCode).value = "";
                document.getElementById(tarifEspecialSMSOnNetCode).value = "";
                document.getElementById(tarifEspecialVozInternacionalCode).value = "";
                document.getElementById(tarifEspecialVozRoamingCode).value = "";
                document.getElementById(tarifEspecialInternetCode).value = "";
            
                document.getElementById(poupancaGrupo).value = $("#to_barra_1 .to_barra_perc span")[0].outerText;
                document.getElementById(poupancaOutras).value = $("#to_barra_2 .to_barra_perc span")[0].outerText;
                document.getElementById(poupancaSMS).value = $("#to_barra_3 .to_barra_perc span")[0].outerText;
            
            if(nonActiveButtons != null)
            {
                var nonActiveStr = "";
                for(var m=0;m<nonActiveButtons.length;m++)
                {
                    if(nonActiveButtons[m] != "")
                        nonActiveStr = nonActiveStr + nonActiveButtons[m] + ";";
                }
                document.getElementById(nonActiveBtns).value = nonActiveStr;
            }
        
            for(var j=0;j<selectedButtons.length;j++)
            {          
                if(selectedButtons[j] != -1)
                {
                    var currKey = j+"+"+ selectedButtons[j];
                    var currType = inverseTypesCodesHT.get(currKey).getTypeName();
                    var currCode = inverseTypesCodesHT.get(currKey).getCodeName();
                
                    if(currType == "EspecialVozGrupo")
                    {
                        if(document.getElementById(tarifEspecialVozGrupoCode) != null)
                            document.getElementById(tarifEspecialVozGrupoCode).value = currCode;
                            
                        
                        if(document.getElementById("VozGrupoVal") != null && document.getElementById(tarifEspecialVozGrupoVal) != null && document.getElementById("VozGrupoVal").value != "")
                            document.getElementById(tarifEspecialVozGrupoVal).value = document.getElementById("VozGrupoVal").value;
                            
                            
                     }else if(currType == "EspecialVozOffNet")
                     {
                        if(document.getElementById(tarifEspecialVozOffNetCode) != null)
                            document.getElementById(tarifEspecialVozOffNetCode).value = currCode;
                        
                        if(document.getElementById("VozOffNetVal") != null && document.getElementById(tarifEspecialVozOffNetVal) != null && document.getElementById("VozOffNetVal").value != "")
                            document.getElementById(tarifEspecialVozOffNetVal).value = document.getElementById("VozOffNetVal").value;
                     }
                     else if(currType == "EspecialSMSOnNet")
                     {
                        if(document.getElementById(tarifEspecialSMSOnNetCode) != null)
                            document.getElementById(tarifEspecialSMSOnNetCode).value = currCode;
                        
                        if(document.getElementById("SMSOnNetVal") != null && document.getElementById(tarifEspecialSMSOnNetVal) != null && document.getElementById("SMSOnNetVal").value != "")
                            document.getElementById(tarifEspecialSMSOnNetVal).value = document.getElementById("SMSOnNetVal").value;
                     }
                     else if(currType == "EspecialVozInternacional")
                     {
                        if(document.getElementById(tarifEspecialVozInternacionalCode) != null)
                            document.getElementById(tarifEspecialVozInternacionalCode).value = currCode;
                            
                        if(document.getElementById("VozInternacionalVal") != null && document.getElementById(tarifEspecialVozInternacionalVal) != null && document.getElementById("VozInternacionalVal").value != "")
                            document.getElementById(tarifEspecialVozInternacionalVal).value = document.getElementById("VozInternacionalVal").value;
                            
                     }else if(currType == "EspecialVozRoaming")
                     {
                        if(document.getElementById(tarifEspecialVozRoamingCode) != null)
                            document.getElementById(tarifEspecialVozRoamingCode).value = currCode;
                            
                        if(document.getElementById("VozRoamingVal") != null && document.getElementById(tarifEspecialVozRoamingVal) != null && document.getElementById("VozRoamingVal").value != "")
                            document.getElementById(tarifEspecialVozRoamingVal).value = document.getElementById("VozRoamingVal").value;
                            
                     }else if(currType == "EspecialInternet")
                     {
                        if(document.getElementById(tarifEspecialInternetCode) != null)
                            document.getElementById(tarifEspecialInternetCode).value = currCode;
                            
                        if(document.getElementById("InternetVal") != null && document.getElementById(tarifEspecialInternetVal) != null && document.getElementById("InternetVal").value != "")
                            document.getElementById(tarifEspecialInternetVal).value = document.getElementById("InternetVal").value;
                     }
                 }
            }
            
            
            
        }
           
        if(document.getElementById("dropdown_numeros") != null)
        {
          if(document.getElementById(nrChoosen) != null)
          {                  
                var nrs = "";
                var currId = "";
                for (var i=1;i<=window.num_tels.length;i++) {
                    currId = "cx_num"+i;
                    if(document.getElementById(currId) != null && document.getElementById(currId).value != "")
                        nrs = nrs + document.getElementById(currId).value + ";";
                }
                document.getElementById(nrChoosen).value = nrs;
          }
        }
        
        
           
        if(n == 5)
        {
            if(document.getElementById(clientName) != null && document.getElementById("to_nome") != null)
                document.getElementById(clientName).value = document.getElementById("to_nome").value;
            if(document.getElementById(clientAdress) != null && document.getElementById("to_morada") != null)
                document.getElementById(clientAdress).value = document.getElementById("to_morada").value;
            if(document.getElementById(clientCP4) != null && document.getElementById("to_cod_post1") != null)
                document.getElementById(clientCP4).value = document.getElementById("to_cod_post1").value;
            if(document.getElementById(clientCP3) != null && document.getElementById("to_cod_post2") != null)
                document.getElementById(clientCP3).value = document.getElementById("to_cod_post2").value;
            if(document.getElementById(clientCity) != null && document.getElementById("to_localidade") != null)
                document.getElementById(clientCity).value = document.getElementById("to_localidade").value;
            if(document.getElementById(clientNTel) != null && document.getElementById("to_tel") != null)
                document.getElementById(clientNTel).value = document.getElementById("to_tel").value;
            if(document.getElementById(clientEmail) != null && document.getElementById("to_email") != null)
                document.getElementById(clientEmail).value = document.getElementById("to_email").value;
            if(document.getElementById(clientNIF) != null && document.getElementById("to_nif") != null)
                document.getElementById(clientNIF).value = document.getElementById("to_nif").value;
        }
        }
        else
            isDataFromCookie = false;
        
        document.getElementById('aspnetForm').action = "";
        document.getElementById('aspnetForm').submit();
    }

    function insertCookieSingleValue(val,id)
    {
        var result = val;
        if(document.getElementById(id) != null)
            result = val + "|" + id + "@" + document.getElementById(id).value.replace(/^\s*/, "").replace(/\s*$/, "");
        return result;
    }

    function makeCookieValue(step) //key:value|key:value|key:value|...
    {
        var cookieValue = "";
        if(document.getElementById(hfId) != null)
           cookieValue = cookieValue + "|" + hfId + "@" +step;

        cookieValue = insertCookieSingleValue(cookieValue,currRo);
        cookieValue = insertCookieSingleValue(cookieValue,tarifOptimusValue);
        cookieValue = insertCookieSingleValue(cookieValue,tarifOthersValue);
        cookieValue = insertCookieSingleValue(cookieValue,tarifSMSValue);
        cookieValue = insertCookieSingleValue(cookieValue,tarifOptimusCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifOthersCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifSMSCode);
        
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozGrupoCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozGrupoVal);
                
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozOffNetCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozOffNetVal);
        
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialSMSOnNetCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialSMSOnNetVal);
        
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozInternacionalCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozInternacionalVal);
        
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozRoamingCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialVozRoamingVal);
        
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialInternetCode);
        cookieValue = insertCookieSingleValue(cookieValue,tarifEspecialInternetVal);
        
        if(document.getElementById(nrChoosen) != null)
            cookieValue = cookieValue + "|" + nrChoosen + "@" +document.getElementById(nrChoosen).value.replace(/;/gi, "#");   
                
        cookieValue = insertCookieSingleValue(cookieValue,poupancaGrupo);
        cookieValue = insertCookieSingleValue(cookieValue,poupancaOutras);
        cookieValue = insertCookieSingleValue(cookieValue,poupancaSMS);
        
        if(document.getElementById(nonActiveBtns) != null)
            cookieValue = cookieValue + "|" + nonActiveBtns + "@" +document.getElementById(nonActiveBtns).value.replace(/;/gi, "#");              
        
        return cookieValue;
    }


    function createTOnlineCookie(step,name,days) {
        eraseCookie(name);
	    if (days) {
		    var date = new Date();
		    date.setTime(date.getTime()+(days*24*60*60*1000));
		    var expires = "; expires="+date.toGMTString();
	    }
	    else var expires = "";
	    
	    var value = makeCookieValue(step);
	    document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function eraseCookie(name)
    {
        document.cookie = name+"="+""+"; path=/";
    }
  
