
var theList;
var subList;
var imageMapClicked;

var continentIndex;
var countryIndex;

$(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)
	};

	//fix para header:
	$("#header").css("zIndex", 100000);

	//listas:
	auxList = eval('(' + $("div SPAN.data #jsonArray").get(0).text + ')');
	theList = auxList.theArray;
	//subLista para ajudar a ir buscar elementos:
	subList = [];
	
	/*
	//image maps:
	imageMapClicked = 0;
	
	$("map area[@name]").bind("click", function(){
		areaName = $(this).attr("name");
		imageMapClicked = 1;
		change_continent('', areaName, '');
	});*/
	
	//limpar a primeira combo:
	select_continent = $(".combobox_container .combobox_header INPUT[@name^=continent]",$(".combobox_list").parents("div")).parents(".combobox_container");
	input_text = $("div.combobox_header INPUT[@type=text]",select_continent);
	input_text.val('Seleccione');
	
});


function change_continent(text,value,container){
	for(theID in theList) if(theList[theID].itemContinent == value) break;
	subList.continent = theID;
	
	//para image maps:
	if(imageMapClicked == 1) updateContinentCombo(theList[theID].theContinent);
	
	updateCountryCombo(theID);
	
}

function change_dp_continent(combo) {
    var continent = combo.selectedIndex;
    continentIndex = continent;
    updateDpCountryCombo(continent);
}

function selectContinent(index) {
    var combo = document.getElementById("dp_continent");
    combo.options[index].selected = true;
    
    var continent = combo.selectedIndex;
    continentIndex = continent;
    
    updateDpCountryCombo(continent);
}

function updateDpCountryCombo(continent) {
    var combo = document.getElementById("dp_country");
    
    // limpar a lista
    $(combo).html('');
    
    // limpar comparativo
    $(".infoOperador").empty();

    // preencher a lista
    var options = '';

    options += '<option value="-1">-- Seleccione --</option>';

    var continent = continentIndex-1;
    if (continent <= -1) {
        $(combo).html(options);
        return;
    }
  	for(theID in theList[continent].theCountries) {
  	    if(isValidNumber(theID)) {
  	        options += '<option value="'+theList[continent].theCountries[theID].theCountry+'">'+theList[continent].theCountries[theID].theCountry+'</option>';
  	        //combo[i] = new Option(theList[continent].theCountries[theID].theCountry, theList[continent].theCountries[theID].theCountry);
  	        //i++;
  	    }
  	}

    $(combo).html(options);
    
    combo.options[0].selected = true;
    
    var country = combo.selectedIndex;
    countryIndex = country;
    updateOperators();

}

function updateOperators() {
    var hidden = document.getElementById("MaxNrOperators");
    var nrDefaultOperators = hidden.value;

    var hidden2 = document.getElementById("URL_ROAMING_INFO");
    var urlRoamingInfo = hidden2.value;

    var tbl = document.getElementById("tblOperators");
    
    // limpar lista
    $(tbl).html('');
    
    // limpar comparativo
    $(".infoOperador").empty();
    
    var continent = continentIndex - 1;
    var country = countryIndex - 1;

    var combo = document.getElementById("dp_country");
    country = combo.selectedIndex - 1;    

    if (country <= -1) {
        return;
    }
    countryIndex = country;

    var tblLine = '';

    // preencher lista
    var nrOperators = 0;
  	for(theID in theList[continent].theCountries[country].theOperators) {
	    if(isValidNumber(theID)) {
	        var operatorName = theList[continent].theCountries[country].theOperators[theID].descOperator;
	        var operatorId = theList[continent].theCountries[country].theOperators[theID].idOperator;
	        var operatorRoaminmgAutomatico = (theList[continent].theCountries[country].theOperators[theID].RoamingAutomatico == '1' ? true : false);
	        var operatorRoaminmgContratual = (theList[continent].theCountries[country].theOperators[theID].RoamingContratual == '1' ? true : false);
	        var txtRoaming = ''
	        if (operatorRoaminmgAutomatico) {
	            if (operatorRoaminmgContratual) {
	                txtRoaming = 'Autom&aacute;tico e Contratual';
	            }
	            else {
	                txtRoaming = 'Autom&aacute;tico';
	            }
	        }
	        else {
                if (operatorRoaminmgContratual) {
	                txtRoaming = 'Contratual';
	            }
	        }
	        
	        var selected = ''
	        if (nrOperators < nrDefaultOperators) {
	            selected = 'checked';
	            nrOperators++;
	        }
	        tblLine += '<tr><td class="rowTitle"><input type="checkbox" name="Operator" value="'+operatorId+'" '+selected+' onclick="javascript:verifyOperators(this);" /><td class="key">'+formatTextFromJson(operatorName)+'</td><td class="value">' + txtRoaming + ' <a href="' + urlRoamingInfo + '" data="'+operatorId+'">[+]</a></td></tr>';
	    }
	}
    
    var tblHeader = '';
    tblHeader += '<table cellspacing="0" cellpadding="0" border="0" class="tabToptitle">';
    tblHeader += '<tr><td valign="top" class="fundolaranja btCxTabTopoCanto"><div class="btCxTabTopoEsq"></div></td><td class="titTabCaixa">Seleccione o operador do pa&iacute;s em quest&atilde;o:</td><td valign="top" class="fundolaranja btCxTabTopoCanto"><div class="btCxTabTopoDir"></div></td></tr>';
    tblHeader += '</table>';
    
    var tblSubHeader = '';
    tblSubHeader += '<tr>';
    tblSubHeader += '<td class="header operador_title" colspan="2">Operador</td>';
    tblSubHeader += '<td class="header roaming_title">Roaming</td>';
    tblSubHeader += '</tr>';

    var button = '<img id="btn_comparar" border="0" alt="comparar" src="/img/telemoveis_bot_comparar.gif" onclick="javascript:getOperatorInfo()">';
    $(tbl).html('<table cellspacing="" width="100%"><tr><td class="" colspan="3">' + tblHeader + '</td></tr>' + tblSubHeader + tblLine + '</table>' + button);
    
    $("#tblOperators input:checkbox:not(:checked)").each(function(){
        $(this).attr('disabled', true);
    });

    
    getOperatorInfo();

    
}
/*
function change_dp_continent(text,value,container){
	for(theID in theList) if(theList[theID].itemContinent == value) break;
	subList.continent = theID;
	
	//para image maps:
	if(imageMapClicked == 1) updateContinentCombo(theList[theID].theContinent);
	
	updateDpCountryCombo(theID);
	
}*/

//clicar nos image maps:
function updateContinentCombo(whichContinent){

select_continent = $(".combobox_container .combobox_header INPUT[@name^=continent]",$(".combobox_list").parents("div")).parents(".combobox_container");

input_text = $("div.combobox_header INPUT[@type=text]",select_continent);
input_value = $("div.combobox_header INPUT[@type=hidden]",select_continent);

input_text.val(whichContinent);
input_value.val(0);
//select_continent.get(0).rebuild();

imageMapClicked = 0;
}

function formatTextFromJson(text)
{
    if ("" != text)
        //return text.replace("&apos;", "'");
        return $("<div/>").html(unescape(text)).text().replace("<", "&lt;").replace(">", "&gt;");
    return text;
}

function updateCountryCombo(whichID){
	//cria a combo dependendo do item escolhido na combo Nº1:
	select_country = $(".combobox_container .combobox_header INPUT[@name^=country]",$(".combobox_list").parents("div")).parents(".combobox_container");

	lista = $(".combobox_list", select_country);
	input_text = $("div.combobox_header INPUT[@type=text]",select_country);
	input_value = $("div.combobox_header INPUT[@type=hidden]",select_country);

	input_value.val('');
	input_text.val(''); 
	lista.empty();

	for(theID in theList[whichID].theCountries) if(isValidNumber(theID)) lista.append('<a href="#" data="'+theList[whichID].theCountries[theID].theCountry+'">'+theList[whichID].theCountries[theID].theCountry+'</a><br/>');

	//input_text.val(theList[whichID].theCountries[0].theCountry);
	input_text.val("Seleccione");
	input_value.val(0);
	select_country.get(0).rebuild();

	//------EM 17.01.008 start-------
	//corrigir altura da combo países se maior do que x items:
	if($("a", lista).length > 12){lista.css({height: "168px", overflow: "auto"})} else {lista.css({height: "auto", overflow: "visible"})}
	//------EM 17.01.008 end-------

	//limpa combo dos operadores
	select_operador = $(".combobox_container .combobox_header INPUT[@name^=operator]",$(".combobox_list").parents("div")).parents(".combobox_container");
	listaOperator = $(".combobox_list", select_operador);
	input_text_operador = $("div.combobox_header INPUT[@type=text]",select_operador);

	input_text_operador.val("");
	listaOperator.empty();
	//listaOperator.append('<a data="1" href="#"></a><br/>');
	select_operador.get(0).rebuild();

	limpaContentoresInfo();
}


function limpaContentoresInfo(){
	//limpa os dois containers:
	$(".infoOperador").html('');
	$(".infoOptimus").html('');
}


function change_country(text,value,container){
	for(theID in theList[subList.continent].theCountries) if(theList[subList.continent].theCountries[theID].theCountry == value) break;
	subList.country = theID;
	
	updateOperatorCombo(theID);
}

function updateOperatorCombo(whichID){
	//cria a combo dependendo do item escolhido na combo Nº2:
	select_operator = $(".combobox_container .combobox_header INPUT[@name^=operator]",$(".combobox_list").parents("div")).parents(".combobox_container");

	lista = $(".combobox_list", select_operator);
	input_text = $("div.combobox_header INPUT[@type=text]",select_operator);
	input_value = $("div.combobox_header INPUT[@type=hidden]",select_operator);

	input_value.val('');
	input_text.val(''); 
	lista.empty();

	for(theID in theList[subList.continent].theCountries[subList.country].theOperators) 
	    if(isValidNumber(theID))
	        lista.append('<a href="#" data="'+theList[subList.continent].theCountries[subList.country].theOperators[theID].idOperator+'">'+formatTextFromJson(theList[subList.continent].theCountries[subList.country].theOperators[theID].descOperator)+'</a><br/>');

	//input_text.val(theList[subList.continent].theCountries[subList.country].theOperators[0]);
	input_text.val('Seleccione');
	input_value.val(0);
	select_operator.get(0).rebuild();

	limpaContentoresInfo();
}


function change_info(text,value,container){		
    var oper = $("INPUT[@name=operator]");
    var area = 'particulares';
    
    if(window.location.href.toLowerCase().indexOf($("#urlSiteEmpresas").val()) != -1)
    {
        area = $("#urlSiteEmpresas").val();
    }
    
    if(window.location.href.toLowerCase().indexOf('corporate') != -1)
    {
        area = 'corporate';
    }
    
    if(-1 != oper.attr('value'))
    {
	    $.ajax({url:"/Servicos/RomRequest.aspx", 
				    type:"POST",
				    dataType:"html",
				    data:{operator: oper.attr('value'), site: area, refreshcache: IsRefreshCache()},
				    success:function(html){ $(".infoOptimus").empty();
				                            $(".infoOptimus").append(unescape(html.substring(html.indexOf('<part1>')+7, html.indexOf('</part1>'))));
				                            $(".infoOperador").empty();
				                            $(".infoOperador").append(html.substring(html.indexOf('<part2>')+7, html.indexOf('</part2>')));
									       },
				    error:function(req,error,ex){$(".infoOptimus").empty();
											    $(".infoOptimus").append("Ocorreu um erro: ErrorCode-"+req.status);}
	    });
    }
}

function getOperatorInfo() {
    var boxes = document.getElementsByName("Operator");
    var operatorIds = '';
    for (var i = 0; i < boxes.length; i++) {
        if (boxes[i].checked) {
            operatorIds += '\'' + boxes[i].value + '\',';
        }
    }
    
    if (operatorIds == '') {
        alert("Seleccione pelo menos um operador.");
    }
    
    var oper = operatorIds;
    var area = 'particulares';
    
    if(window.location.href.toLowerCase().indexOf($("#urlSiteEmpresas").val()) != -1)
    {
        area = $("#urlSiteEmpresas").val();
    }
    
    if(window.location.href.toLowerCase().indexOf('corporate') != -1)
    {
        area = 'corporate';
    }
    
    
    if(oper != '')
    {
	    $.ajax({url:"/Servicos/RomRequest.aspx", 
				    type:"POST",
				    dataType:"html",
				    data:{operator: oper, site: area, refreshcache: IsRefreshCache()},
				    success:function(html){ //$(".infoOptimus").empty();
				                            //$(".infoOptimus").append(unescape(html.substring(html.indexOf('<part1>')+7, html.indexOf('</part1>'))));
				                            $(".infoOperador").empty();
				                            $(".infoOperador").append(html.substring(html.indexOf('<part2>')+7, html.indexOf('</part2>')));
									       },
				    error:function(req,error,ex){$(".infoOperador").empty();
											    $(".infoOperador").append("Ocorreu um erro: ErrorCode-"+req.status);}
	    });
    }

}

function verifyOperators(lastBox) {
    var hidden = document.getElementById("MaxNrOperators");
    var nrDefaultOperators = hidden.value;
    
    var boxes = document.getElementsByName("Operator");
    var count = 0;
    for (var i = 0; i < boxes.length; i++) {
        if (boxes[i].checked) {
            count++;
        }
    }
    
    if (count >= nrDefaultOperators) {
         $("#tblOperators input:checkbox:not(:checked)").each(function(){
           $(this).attr('disabled', true);
         });
    }else{
         $("#tblOperators input:checkbox:not(:checked)").each(function(){
           $(this).removeAttr('disabled');
         });
    }
}
