var prm;
var postbackElement;

function init()
{
  prm = Sys.WebForms.PageRequestManager.getInstance(); 
  prm.add_initializeRequest(initializeRequest);
  prm.add_endRequest(endRequest);
}

function initializeRequest(sender, args) 
  { 
  if (prm.get_isInAsyncPostBack()) 
  {
    //debugger
    args.set_cancel(true); 
  }
}

function endRequest(sender, args) 
{ }

// --------------------
// ECOL DCLEAO 20091111
var Sis = {};

(function($)
{
    $.Get = function(o, p, dv)
    {
        var v;
        return (o && (v = o[p]) != null) ? v : dv;
    };

    $.Eval = function(sEval)
    {
        return eval('(function(){ return ' + sEval + '; })()');
    };
    
    $.ShowPopup = function(url, options)
    {
        var width  = $.Get(options, 'Width', 670),
            height = $.Get(options, 'Height', 620),
            name   = $.Get(options, 'Name', 'popupPage'),
            style  = 'width=' + width + ',height=' + height + ',resizable=yes,scrollbars=no,toolbar=no,status=no',
            win    = window.open(url, name, style);

        if (window.focus)
        {
            win.focus();
        }

        return win;
    };

    $.GetUrlAsyncUsingIFrame = function(url)
    {
        // This method of asynchronous "remote scripting" (the base of Ajax)
        //  is important because it allows the response to be processed by the client-agent (whichever the content-type in the response).
        // As an example, the save as dialog is presented for file downloads,
        //  if that is waht is implied in the response.

        var frame = document.createElement("iframe");
        frame.style.width = "1px";
        frame.style.height = "1px";
        frame.frameBorder = "0";
        frame.style.position = "absolute";
        frame.style.top = "-100px"
        frame.style.left = "-100px";
        
        document.body.appendChild(frame);

        frame.src = url;

        // There is no general way to know when an iframe is loaded!
        // Depending on the content-type, that url refers to, and on the browser, 
        //  there are specific ways to detect loading.
        return { // Signature-Compatible with Ajax.Net's IDisposable
            dispose: function()
            {
                document.body.removeChild(frame);
            }
        };
    };

    $.GetUrlAsync = function(url, funCompleted)
    {
        var request = new Sys.Net.WebRequest();
        request.set_url(url);
        request.set_httpVerb("GET");
        request.add_completed(function(executor/*, eventArgs*/)
        {
            funCompleted(executor);
        });

        // Invoke the request
        request.invoke();
    };

    $.LaunchCallCompletedSentinel = function(callStatusUrl, funCompleted)
    {
        function Invoke()
        {
            $.GetUrlAsync(callStatusUrl, function(executor)
            {
                var callActive = executor.get_responseAvailable() && !!$.Eval(executor.get_responseData());
                if (!callActive)
                {
                    funCompleted();
                }
                else
                {
                    // try again in...
                    window.setTimeout(Invoke, 100);
                }
            });
        }

        // 1st invoke
        Invoke();
    };

})(Sis);

//  -------------------

function clickButton(e, buttonid){ 
     var bt = document.getElementById(buttonid); 
     if (typeof bt == 'object'){
        if (e.keyCode == 13){
            bt.click();
            return false;
        }
     }
}

function Change_Arrow(id)
{
  var img = document.getElementById(id);
  index = img.src.lastIndexOf('/')+1;
  file = img.src.substring(index,img.src.length);
    
  if(file == "seta_selected.gif")
      img.src = img.src.substring(0,index)+"seta_notSelected.gif";
  else
      img.src = img.src.substring(0,index)+"seta_selected.gif";
        
  CloseAll(id);
}

function CloseAll(id)
{    
    var allElements = document.getElementsByTagName("*");
    for (var i = 0; i < allElements.length; i++) {
        var elem = allElements[i];
        if(elem.id != id && IsOnSameControl(id, elem.id))
        {
          index = elem.id.lastIndexOf('_')+1;
          if(elem.id.substring(index,elem.id.length) == "Arrow")
          {
            index = elem.src.lastIndexOf('/')+1;
            elem.src = elem.src.substring(0,index)+"seta_notSelected.gif";
          }
        }
    }
}

function IsOnSameControl(id, targetId)
{
    var idSource = id.split('_');
    var targetIdSource = targetId.split('_');
    return idSource[3] == targetIdSource[3];
}

function GetInfoCallback(result,context)
{
    var values = result.split('|');
    var x = document.getElementById("Pesquisa_HelpBox");
    var y = document.getElementById("Pesquisa_NomeCampo");
    if(x != null && y != null)
    {
        y.innerHTML = values[0];
        x.innerHTML = values[1];
    }
    else
        alert("Não existe nenhum objecto com o id dado.");
}

function isNotIE()
{
	var browser = navigator.appName;

	if(browser == "Microsoft Internet Explorer")
		return 0;
	else
		return 1;
}

function adjustPopSizeMore(width, height)
{
	if(isNotIE() == 1)
	{
		width = width + 50;
		height = height + 50;
	}
	
	adjustPopSize(width, height);
}
function Maximize() 
{
window.innerWidth = screen.width;
window.innerHeight = screen.height;
window.screenX = 0;
window.screenY = 0;
alwaysLowered = false;
}
function CheckAccordionClearText()
{
    var check = setTimeout('CheckFont()', 10000);
}

function CheckFont()
{
    var element = document.getElementByClass("gridview_accordion_content");
    if(element.style.font != "normal normal normal 11px \"Trebuchet MS\",Verdana")
        element.style.font = "normal normal normal 11px \"Trebuchet MS\",Verdana";
    else
        window.clearTimeout(win);
}


function ChangeCollapsedPanel(img, panel)
{
  var panelControl = document.getElementById(panel);
  if(panelControl == null) return;
  
  var extended = (panelControl.className.indexOf('Extended') != -1);
  if(extended)
    CollapsePanel(img, panel)
  else
    ExpandPanel(img, panel);   
}

function ExpandPanel(img, panel)
{
  var imgControl = document.getElementById(img);
  if(imgControl == null) return;
  var panelControl = document.getElementById(panel);
  if(panelControl == null) return;

  panelControl.className = 'collapsePanelExtended';
  imgControl.src = 'images/menos.gif';  
}

function CollapsePanel(img, panel)
{
  var imgControl = document.getElementById(img);
  if(imgControl == null) return;
  var panelControl = document.getElementById(panel);
  if(panelControl == null) return;
  
  panelControl.className = 'collapsePanelCollapsed';
  imgControl.src = 'images/mais.gif';
}

function LimparSelect(id)
{
  var c = document.getElementById(id);
  if(c != null) c.selectedIndex = 0;
}
function LimparAdvancedSelectPai(id)
{
  var c = document.getElementById(id);
  if(c != null) c.selectedIndex = 0;

  var cs = document.getElementById(id.replace('dropdown', 'cascading_ClientState'));
  cs.value = ':::';
}
function LimparAdvancedSelect(id)
{
  var c = document.getElementById(id);
  if(c == null) return;
  c.options.length = 0;
  c.options.add(new Option('-','-'));
  c.disabled = true;
  c.selectedIndex = 0;
  
  var cs = document.getElementById(id.replace('dropdown', 'cascading_ClientState'));
  cs.value = ':::';
}
function LimparInputText(id) {
    var c = $('#' + id);
  var c = document.getElementById(id);
  if(c != null) c.value = '';
}
function LimparAreaAdministracao()
{
  var c1 = document.getElementById('Pesquisa_areaAdministracao_ctl00_ctl00');
  var c2 = document.getElementById('Pesquisa_areaAdministracao_ctl01_ctl00');
  var c3 = document.getElementById('Pesquisa_areaAdministracao_ctl02_ctl00');
  var c4 = document.getElementById('Pesquisa_areaAdministracao_ctl03_ctl00');
  var c5 = document.getElementById('Pesquisa_areaAdministracao_ctl04_ctl00');
  c1.checked = false;
  c2.checked = false;
  c3.checked = false;
  c4.checked = false;
  c5.checked = false;
  
  LimparAdvancedSelectPai('Pesquisa_addAmbito_addAmbito_dropdown');
  c2.click();
}

function LimparCamposPesquisa() {  
  LimparAreaAdministracao();
  LimparInputText('Pesquisa_SIGLA');
  LimparInputText('Pesquisa_NOME');
  LimparInputText('Pesquisa_URL');
  LimparInputText('Pesquisa_CONTACTO');
  LimparSelect('Pesquisa_SEARCH_ORGANICA_GOVERNO_NOME_HISTORY');
  LimparSelect('Pesquisa_TH_ENTIDADE');
  LimparSelect('Pesquisa_AMBITO_TERRITORIAL');
  LimparAdvancedSelectPai('Pesquisa_addAreaActividade_addAreaActividade_dropdown');
  LimparAdvancedSelect('Pesquisa_addActividadePrincipal_addActividadePrincipal_dropdown');
  LimparInputText('Pesquisa_MISSAO');
}

function LimparCamposPesquisaAvancada()
{
  LimparInputText('Pesquisa_DATA');
  LimparInputText('Pesquisa_MORADA');
  LimparAdvancedSelectPai('Pesquisa_addDistrito_addDistrito_dropdown');
  LimparAdvancedSelect('Pesquisa_addConcelho_addConcelho_dropdown');
  LimparAdvancedSelect('Pesquisa_addFreguesia_addFreguesia_dropdown');
  LimparSelect('Pesquisa_PAIS');
  LimparInputText('Pesquisa_LEGISLACAO');
  LimparSelect('Pesquisa_TH_AUTONOMIA');
  LimparSelect('Pesquisa_TH_DEPENDENCIA');
  LimparSelect('Pesquisa_TH_ESTRUTURA_INTERNA');
  LimparSelect('Pesquisa_TH_TIPO_ORGAO');
  LimparSelect('Pesquisa_TH_REGIME_PESSOAL');
  LimparInputText('Pesquisa_ORIGEM');
}

function LimparCamposPesquisaTodos() {

    window.location.href = "default.aspx";

    $.each($('input[id*="Pesquisa_"][id!="Pesquisa_btnOK"]'), function () {
        $(this).val("");
    });
    $.each($('select[id*="Pesquisa_"]'), function () {
        $(this).val("");
    });
    $.each($('input:checkbox:checked[id*="Pesquisa_"]'), function () {
        $(this).removeAttr('checked');
    });
    $.each($('input:radio:checked[id*="Pesquisa_"]'), function () {
        $(this).removeAttr('checked');
    });

    $('#Pesquisa_cbSubEntidades').attr('checked', 'checked');

//  LimparCamposPesquisa();
//  LimparCamposPesquisaAvancada();
    CollapsePanel('collapseImage1', 'collapsePanel1');
    //$('#Pesquisa_pesquisarEmRadioButtonList_0').trigger('click');
    //__doPostBack('Pesquisa$pesquisarEmRadioButtonList$0','0');

    //theForm.__EVENTTARGET.value = 'Pesquisa$pesquisarEmRadioButtonList$0';
//    theForm.__EVENTARGUMENT.value = '0';
    //theForm.submit();
}

function simplePopUp(url)
{
	var newwindow;
	newwindow = window.open(url,'newPopupPage');
	if (window.focus) { newwindow.focus() }
}

function PopUp(url)
{
	var newwindow;
	newwindow = window.open(url,'popupPage','width=670,height=620,resizable=yes,scrollbars=yes,toolbar=no,status=no');
	if (window.focus) { newwindow.focus() }
}

function adjustPopSize(width, height)
{
	var winWidth = width;
	var winHeight = height;

	window.resizeTo(winWidth, winHeight);
}

function Popup(ddlControlID)
{
   var ddl = document.getElementById(ddlControlID);
   var url = ddl.options[ddl.selectedIndex].value;
   ddl.selectedIndex = 0;
   if(url != "")
      PopupGo(url);
}

