/*<RMJSDep>SharedServices\ClientScripts\BrowserUtils;SharedServices\ClientScripts\WindowUtils;SharedServices\ClientScripts\DisableEnterSubmit; SharedServices\ClientScripts\Mozilla;SharedServices\ClientScripts\RMWJSResource.js.aspx;SharedServices\ClientScripts\TextBox;SharedServices\ClientScripts\AsyncServices;</RMJSDep>*/

var DialogWidth = 788;
var DialogHeight = 505;

var RMWLoadingCaption;
var RMWLoadingImage;
var RMWResizeWindowCallBack;
var RMWMainFormSubmitCallBack;
var RMWHasTextBoxWithEmptyText = false;

var RMWShowMessageInModalPopup = false;

function OnLoad(Event)
{
}

function CallClientHostNameFunction()
{
  if(ClientHostNameFunction)
    ClientHostNameFunction();
}
function pageLoad(e){



  if (!e) var e = window.event;
	DoDisableEnterSubmit(e);	
	ConfigureMainFormSubmit();
	if(RMWHasTextBoxWithEmptyText)	 
	    EnsureEmptyTextFeatures();
	eval(OnLoadFunctions);
		
	WorkAroundForAspNetAjax();
  // if (Sys.Browser.name != 'Microsoft Internet Explorer')//donotlocalize
  //	ConfigureFirefoxResizeWorkAround();
	
	var loadingMessage = RM.Lib.WebForms.ModalLoading.ShowLoading(document.body, '');
	loadingMessage.dispose();

    /***** Adiciona função para redimencionar elementos 100% de altura da pagina  ****/
	FixHeightGetItens();
	FixHeight();

	$addHandler(window, 'resize', function () {
	    window.clearTimeout(fixHeightTimeout);
	    fixHeightTimeout = window.setTimeout(FixHeight, 100)
	});
}

function pageUnload(){
  if (Sys.Browser.name != 'Microsoft Internet Explorer')//donotlocalize
  	$removeHandler(window, 'resize', RMWResizeWindowCallBack);//donotlocalize
}

function ChangeLocation(href, loadingMessage){
  ShowLoadingCaption(loadingMessage);
  window.location.href = href;
}

function ConfigureFirefoxResizeWorkAround(){
	var mainContainer = $get('MainContainer');//donotlocalize
	if (mainContainer)
	  RM.Lib.WebForms.DivOverflowUtils._mainContainerDiv = {overflowMode : RM.Lib.WebForms.DivOverflowMode.Both, element : mainContainer};

  RMWResizeWindowCallBack = Function.createCallback(RM.Lib.WebForms.DivOverflowUtils.EnsureManagedDivsSize, null);
  
  RM.Lib.WebForms.DivOverflowUtils._enableResizeWorkAround = true;

	window.resizeBy(1,1);
	$addHandler(window, 'resize', RMWResizeWindowCallBack);//donotlocalize
	window.resizeBy(-1,-1);
}

/* No dia 3/10/2007 foi detectado que o script da microsoft que gerencia as chamdas ajax
    gerava um Bug caso ocorresse uma chamada ao servidor dentro de um resultado de uma outra chamada ao servidor(Ajax)
    segue abaixo o código que substitui parte do script da microsoft corrigindo este problema.
 **********************************************************************************************/    
function WorkAroundForAspNetAjax()
{
    if( typeof(WebForm_CallbackComplete) == "function" )//donotlocalize
    {    
        WebForm_CallbackComplete = Override_WebForm_CallbackComplete;   
    }
}

function Override_WebForm_CallbackComplete() {
    for (i = 0; i < __pendingCallbacks.length; i++) {
        callbackObject = __pendingCallbacks[i];
        if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
            if (!__pendingCallbacks[i].async) {
                __synchronousCallBackIndex = -1;
            }
            __pendingCallbacks[i] = null;            
            var callbackFrameID = "__CALLBACKFRAME" + i;
            var xmlRequestFrame = document.getElementById(callbackFrameID);
            if (xmlRequestFrame) {
                xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
            }
            WebForm_ExecuteCallback(callbackObject);
        }
    }
}
/*********************************************************************************************/


function EnsureEmptyTextFeatures()
{
    if ((ServerLoadedControllerId != null) && (ServerLoadedControllerId != ''))
    {
        var _serverLoadedController = document.getElementById(ServerLoadedControllerId);
        
        if (_serverLoadedController != null)
        {
            if (_serverLoadedController.value.toString().toUpperCase() == 'FALSE')
            {
                RestoreInputEmptyTextFeatures();
                RestoreTextAreaEmptyTextFeatures();
            }
            else
            {
                _serverLoadedController.value = 'FALSE';
            }
        }
    }
}

function RestoreTextAreaEmptyTextFeatures()
{
    var textAreas = document.getElementsByTagName('textarea');
    for(i=0;i<textAreas.length;i++)
    {
        var textAreaId = textAreas[i].id;
        
        if ((textAreaId != null) && (textAreaId != ''))
        {
            RestoreRMWTextBoxEmptyTextFeatures(textAreaId);
        }
    }
}

function RestoreInputEmptyTextFeatures()
{
    var inputs = document.getElementsByTagName('input');
    for(i=0;i<inputs.length;i++)
    {
        var currentInput = inputs[i];
        
        if (currentInput.type.toString().toUpperCase() == 'TEXT')
        {
            var inputId = currentInput.id;
            
            if ((inputId != null) && (inputId != ''))
            {
                RestoreRMWTextBoxEmptyTextFeatures(inputId);
            }
        }
    }
}

function RestoreRMWTextBoxEmptyTextFeatures(controlId)
{
    var _rmwTextBox = new RMWTextBox(controlId);
    if (_rmwTextBox != null) 
        if(!_rmwTextBox.getShowingEmptyText())
            _rmwTextBox.clearEmptyTextStyle(true);
        else
            _rmwTextBox.restoreEmptyTextStyle(true);
}

//Método específico para o FireFox
//Quando faz history.back, o OnLoad não é disparado e sim este método
function OnPageShow(persisted)
{
    if (persisted)
        HideLoadingCaption();
}

function ConfigureMainFormSubmit()
{
  $addOnsubmitHanlder(MainFormSubmit);
}

window.detailsWindowByTransactionId = [];

function ClearDetailTransaction(TransactionId){
  if (window.detailsWindowByTransactionId &&
      window.detailsWindowByTransactionId[TransactionId] &&
      window.detailsWindowByTransactionId[TransactionId].closed)
  {
    tc_submiting = false;
    var xmlHttp = GetXmlHttp();
    var asyncResponsePageUrl = GetAsyncResponserPageUrl();

    xmlHttp.open("GET",asyncResponsePageUrl + "?ServiceId=ClearTransaction&TransactionId=" + TransactionId, true);
    xmlHttp.send(null);
  }
}

function SetupLicenceTimer() {
    window.setInterval("RenewLicence('" + LoginId + "');", TimerInterval);
}

function RenewLicence(LoginId) {
  var xmlHttp = GetXmlHttp();
  var asyncResponsePageUrl = GetAsyncResponserPageUrl();

  xmlHttp.open("GET", asyncResponsePageUrl + "?ServiceId=RenewLicence&LoginId=" + LoginId + "&RandomId=" + Math.random(), true);
  xmlHttp.send(null);
}

var ShowLoadingMessageOnSubmit = true;
function MainFormSubmit()
{
    var internalPageIsValid = true;
    if ((typeof(Page_IsValid) != null) && (typeof(Page_IsValid) != "undefined"))//donotlocalize
        eval("internalPageIsValid = Page_IsValid;")//donotlocalize
    
    if (internalPageIsValid && ShowLoadingMessageOnSubmit)
	    ShowLoadingCaption(SUBMIT_LOADING_MESSAGE);

	if (OnSubmitFunctions!=null)
		eval(OnSubmitFunctions);
}

var $LoadingPanel = null;
function ShowLoadingCaption(loadingMessage)
{
    $LoadingPanel = RM.Lib.WebForms.ModalLoading.ShowLoading(document.body, loadingMessage);
}

function HasPreviousPage()
{
    var noHistoryLength = (isIE()) ? 0 : 1;
    
    return (history.length > noHistoryLength);        
}

function HideLoadingCaption()
{
}

function SetBrowserCSS()
{
	if (isIE())
	{
		var NSCSSConst = "NS.CSS";
		var IECSSConst = "IE.CSS";
		
		for(var i=0; i<document.styleSheets.length; i++)
		{
			var styleSheet = document.styleSheets[i];
			if ((styleSheet.href!=null) &&
				(styleSheet.href.toUpperCase().indexOf(NSCSSConst)!=-1))
				styleSheet.href = styleSheet.href.toUpperCase().replace(NSCSSConst,IECSSConst);
		}
	}
}

function ConfigureWindowOnLoad()
{
}

function OpenEditPageWindow(ShowingDetail, Url) {
    //GetCenterPositionLeft
    var Features = 'height=' + DialogHeight + ', width=' + DialogWidth + ', left=' + GetCenterPositionLeft(DialogWidth + 8) + ' , top=' + GetCenterPositionTop(DialogHeight + 100) + ', resizable=yes, status=yes'; //donotlocalize
    if (ShowingDetail == "TRUE")
        ShowModalWindow(Url, '', Features, false);
    else
        OpenWindow(Url, '', Features);
}

function OpenWindowTargetBlank(Url) {
    var Features = 'height=' + DialogHeight + ', width=' + DialogWidth + ', left=' +
        GetCenterPositionLeft(DialogWidth + 8) + ' , top=' + GetCenterPositionTop(DialogHeight + 100) +
        ', resizable=yes, status=yes, scrollbars=yes'; //donotlocalize
    OpenWindow(Url, '', Features);
}

function ShowAlertMessage(Message)
{
    if(RMWShowMessageInModalPopup)
        return $ShowModalMessageBox(RM.Lib.WebForms.ModalPanelWindowType.Alert, Message)
    else
    {
        alert(Message);
        return null;
    }
}

function HasTextBoxWithEmptyText()
{
  RMWHasTextBoxWithEmptyText = true;
}


var fixHeightTimeout = null,
    leftTdMenu = null,
    accordionItens = null,
    containers = null,
    dataContainerTD = null,
    mainContainer = null,
    pnlGrid = null,
    leftMenuTable = null,
    headerHeight = 0;

function getOffsetSum(elem) {
  var top=0, left=0
  while(elem) {
    top = top + parseInt(elem.offsetTop)
    left = left + parseInt(elem.offsetLeft)
    elem = elem.offsetParent        
  }
   
  return {top: top, left: left}
}

function getOffsetRect(elem) {
    var box = elem.getBoundingClientRect()
    
    var body = document.body
    var docElem = document.documentElement
    
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
    
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0
    
    var top  = box.top +  scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft
    
    return { top: Math.round(top), left: Math.round(left) }
}

function getOffset(elem) {
    if (elem.getBoundingClientRect) {
        return getOffsetRect(elem)
    } else {
        return getOffsetSum(elem)
    }
}

function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function FixHeightGetItens() {

    leftTdMenu = $get("tdLeftOptions");
    accordionItens = getElementsByClass('AccodionHeaderMainTable', leftTdMenu, "TABLE");
    containers = getElementsByClass('AccordionItemChildControlsDiv', leftTdMenu, "DIV");
    dataContainerTD = $get("DataContainerTD");
    mainContainer = $get("MainContainer");
    pnlGrid = $get("ViewControl_pnGrid");
    leftMenuTable = $get("LeftMenuTable");

    var header = $get("HeaderTD");
    if(header)
        headerHeight = header.offsetHeight;
}

function getWindowDimension() {
    var theWidth, theHeight;
    // Window dimensions: 
    if (window.innerWidth) {
        theWidth = window.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        theWidth = document.documentElement.clientWidth;
    }
    else if (document.body) {
        theWidth = document.body.clientWidth;
    }
    if (window.innerHeight) {
        theHeight = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight = document.documentElement.clientHeight;
    }
    else if (document.body) {
        theHeight = document.body.clientHeight;
    }
    return { width: theWidth, height: theHeight };
}

function FixHeight() {

    var footerHeight = 26;

    /*** VERIFICA SE EXISTE O FOOTER ABERTO */
    if (typeof (GetColapsableContainer) != "undefined") {
        var SelectedPanel = GetColapsableContainer('TabSheetHint');
        var windowHeight = getWindowDimension().height;

        if (SelectedPanel)
            if (SelectedPanel.style.display != 'none')
                footerHeight = 85;
    }

    /******* ALTURA DO TD CONTAINER *********/
    if (mainContainer) {
        var top = getOffset(dataContainerTD).top
        var height = dataContainerTD.offsetHeight
        var rest = windowHeight - (top + height) - footerHeight;

        mainContainer.style.height = height + rest + "px";
        dataContainerTD.style.height = mainContainer.style.height;
    }

    /****** ALTURA DO MENU CONTAINER *******/
    if (accordionItens) {
        if (accordionItens.length > 0) {
            var sumAccordionHeight = 0;
            var accordionHeight = accordionItens[0].offsetHeight;

            for (var i = 0; i < accordionItens.length; i++) {
                sumAccordionHeight += accordionItens[i].offsetHeight;
            };

            /**** ALTURA DE TODOS CONTAINERS DO MENU ***/
            var containerHeight = windowHeight - sumAccordionHeight - accordionHeight - headerHeight;
            for (var i = 0; i < containers.length; i++) {
                containers[i].style.height = containerHeight + "px";
            };

            leftMenuTable.style.height = containerHeight + "px";
        }
    }

    /**** ALTURA DA DIV DO GRID PRINCIPAL ****/
    if (pnlGrid) {
        var top = getOffset(pnlGrid).top;
        var height = pnlGrid.offsetHeight
        var rest = windowHeight - (top + height) - footerHeight;
        pnlGrid.style.height = height + rest + "px";
    }
}


