﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="MwwObject.js"/>

var __mwwX = 0, __mwwY = 0;
var __mwwPageReady = false;
 
function redimPrgUpd() {
    setPageDimValues();
    $get('mwwImgPrgUpd').width = document.body.clientWidth;
    $get('mwwImgPrgUpd').height = document.body.clientHeight;
    $get('updPrgTitle').width = document.body.clientWidth;
    $get('updPrgLoadingImg').style.top = ((document.body.clientHeight / 2) - 30).toString() + "px";
    $get('updPrgLoadingImg').style.left = ((document.body.clientWidth / 2) - 30).toString() + "px";
}

try{ 
    $(document).ready(function() {

        //if (!$get('hMobile')) {
            try { $(document.forms[0]).submit(setPageDimValues) } catch (e) { }

            if (window.addEventListener) {
                window.addEventListener("resize", setPageLayout, false);
                window.addEventListener("resize", setPageDimValues, false);
                window.addEventListener("load", setPageLayout, false);
                window.addEventListener("load", setPageDimValues, false);
                try { document.forms[0].addEventListener("submit", setPageDimValues, false) } catch (e) { }
            } else {
                window.attachEvent("onresize", setPageLayout);
                window.attachEvent("onresize", setPageDimValues);
                window.attachEvent("onload", setPageLayout);
                window.attachEvent("onload", setPageDimValues);
                try { document.forms[0].attachEvent("onsubmit", setPageDimValues) } catch (e) { }
            }


            //            try { $("#mwwAlertBox").draggable({ handle: '#mabDragHelper', containment: '#fullPageUpd' }); } catch (e) { }
            //            try { $("#mwwConfirmBox").draggable({ handle: '#mcbDragHelper', containment: '#fullPageUpd' }); } catch (e) { }
            try {
                if (window.addEventListener) document.forms['MwwForm'].addEventListener("click", function(event) { __mwwX = event.clientX; __mwwY = event.clientY; }, false);
                else document.forms['MwwForm'].attachEvent("onclick", function(event) { __mwwX = event.clientX; __mwwY = event.clientY; })
            } catch (e) { }
        //}
    });
} catch (e) { }

function enableMwwControlState() {
    try {
        var vs = document.getElementsByName('__VIEWSTATE');
        for (var i = 0; i < vs.length; i++) if (vs[i].value == "") vs[i].parentNode.removeChild(vs[i]);
    } catch (e) { }
    __mwwPageReady = true;
}

function setPageDimValues(flgOper) {
    try {
        $get("hPageWidth").value = document.body.clientWidth;
        $get("hPageHeight").value = document.body.clientHeight;
        $get("hContentScrollWidth").value = $get("containerPanel").scrollWidth;
        $get("hContentScrollHeight").value = $get("containerPanel").scrollHeight;
        //alert("hPageWidth: " + $get("hPageWidth").value + "\n" + "hPageHeight: " + $get("hPageHeight").value + "\n" + "hContentScrollWidth: " + $get("hContentScrollWidth").value + "\n" + "hContentScrollHeight: " + $get("hContentScrollHeight").value);
    } catch (ex) { }
}
 
function setPageLayout(sender) {
    try {
        var hDelta = Number($get("hDeltaHeight").value)
        $get("containerPanel").style.width = document.body.clientWidth.toString() + "px";
        $get("containerPanel").style.height = (document.body.clientHeight - hDelta).toString() + "px";
    } catch (ex) { }
}


function onOverCellLookUp(cell) {
    try {
        if (cell.childNodes(0).disabled) return;
        cell.style.textDecoration = 'underline';
     } catch (e) { }
}

function onOutCellLookUp(cell) {
    try {
        if (cell.childNodes(0).disabled) return;
        cell.style.textDecoration = 'none';
    } catch (e) { }
}


function mwwReloadExternalControl(nome,str) {
    //debugger;
//    document.frames[nome].location.search="zsdggasgasdgasdgasd"
//    alert(document.frames[nome])
//    alert(str)
}

//function mwwLockMasterArea() {
//    var lock = document.getElementById("mwwMasterDivLock");
////    var ctrl = document.getElementById("mwwMasterArea");
//    var ctrl = $get("masterWrapper");
//    if (lock.getAttribute("relatedControlState") == "enabled") return;
//    lock.style.display = "block";
//    lock.style.top = ctrl.offsetTop;
//    lock.style.left = ctrl.offsetLeft;
//    lock.style.width = ctrl.offsetWidth;
//    lock.style.height = ctrl.offsetHeight;
//}

function mwwGoToTargetControl(roleInPage, controlId, targetTab) {
    try {
        if (roleInPage==2) {
            try {
                var ts = $find('tsDetail');
                var tab = ts.findTabByValue(targetTab);
                tab.select();
            } catch (ex) { };
        }
        var ctrl = $get(controlId)
        try{ if(ctrl)ctrl.focus() } catch(ex){};
        try{ if(ctrl)ctrl.className = "mwwInputInError" } catch(ex){};
    } catch (ex) { };
}
function showMwwBox(box, item) {
    //debugger;
    box.style.zindex = "35000";
    box.style.display = "block";
    try {
        box.style.top = ((document.body.clientHeight - box.clientHeight) / 2).toString()+"px";
        box.style.left = ((document.body.clientWidth - box.clientWidth) / 2).toString()+"px";
    } catch(ex) {
        box.style.top = "100px";
        box.style.left = "150px";
    }
    if (item!=undefined) showMwwBoxItem(item);
}
function showMwwBoxItem(item) {
    if ($get("mwwMessageItemButton2").getAttribute("enabled") == 1) $get("mwwMessageItemButton2").className = "mwwMessageBoxItemButton";
    if ($get("mwwMessageItemButton1").getAttribute("enabled") == 1) $get("mwwMessageItemButton1").className = "mwwMessageBoxItemButton";
    if ($get("mwwMessageItemButton0").getAttribute("enabled") == 1) $get("mwwMessageItemButton0").className = "mwwMessageBoxItemButton";
    $get("mwwMessageItem2").style.display = "none";
    $get("mwwMessageItem1").style.display = "none";
    $get("mwwMessageItem0").style.display = "none";
    $get("mwwMessageItemButton" + item.toString()).className = "mwwMessageBoxItemButton_s";
    $get("mwwMessageItem" + item.toString()).style.display = "block";
}
function mwwMessageBoxItemOver(btn) {
    if (btn.className=='mwwMessageBoxItemButton_s') return;
    btn.className='mwwMessageBoxItemButton_o';
}
function mwwMessageBoxItemOut(btn) {
    if (btn.className=='mwwMessageBoxItemButton_s') return;
    btn.className='mwwMessageBoxItemButton';
}
function hideMwwBox(box) {
    box.style.display = "none";
    if (document.getElementById("mwwModalPnlConfirm")) {
        document.getElementById("mwwModalPnlConfirm").style.display = 'none';
    }
}

function mwwAlert(text, title, level, width, height, Html) {
    var box = document.getElementById("mwwAlertBox");
    var tit = document.getElementById("mwwAlertBoxTitle");
    var txt = document.getElementById("mwwAlertMsgArea");
    var img = document.getElementById("mwwAlertBoxImage");
    var CellCenter = document.getElementById("mabDragHelper");
    var CellText = document.getElementById("cellBodyText");
    if (title) tit.innerHTML = title
    else tit.innerHTML = "MyWay Office"
    if (level) img.src = "alert" + level + ".fihx"
    else img.src = "alert0.fihx";
    if (text) {
        if (Html) {
            txt.innerHTML = text;
        } else {
            txt.innerHTML = text;
        }
    }
    if (height) {
        if (height > 60) CellText.style.height = (height - 58) + 'px';
    } else {
        CellText.style.height = "120px";
    }

    if (width) {
        box.style.width = width + "px";
        CellCenter.style.width = (width - 37) + 'px';
        txt.style.width = (width - 80) + 'px';
    } else {
        box.style.width = "270px";
        CellCenter.style.width = "233px";
        txt.style.width = "190px";
    }

    box.style.zIndex = "12000"

    showMwwBox(box);

    $('#mwwOkBtn').focus();
}


///////////////////////////////////////////////////////////////////////////////
//Test New mwwAlert
document.write('<div id="mwwAlertBox" style="display:none;">')
document.write('<table cellpadding="0" cellspacing="0"><tr height="28px">')
document.write('<td style="width:6px;background-image:url(TopLeft.fihx);"></td>')
document.write('<td id="mabDragHelper" style="background-image:url(TopCenter.fihx);cursor:move;" style="width:100%;"><span  id="mwwAlertBoxTitle"></span></td>')
document.write('<td style="background-image:url(TopCenter.fihx);cursor:pointer;width:25px;"><img ID="imgCloseWd" onclick="hideMwwBox($get(\'mwwAlertBox\'));" src="CloseWindow.fihx" onmouseover="this.src=\'CloseWindow_o.fihx\';" onmouseout="this.src=\'CloseWindow.fihx\';"/></td>')
document.write('<td style="width:6px;background-image:url(TopRight.fihx);"></td></tr>')
document.write('<tr><td valign="top" align="center" colspan="4" style="background-color: #ddecfe;">')
document.write('<div style="border:solid 1px #3a5a82;border-top:0px;margin:0px 0px 0px 0px;padding:0px 3px 0px 3px;text-align:center;">')
document.write('<table id="mwwAlertInfo" cellspacing="0" cellpadding="0">')
document.write('<tr><td valign="top"><img id="mwwAlertBoxImage" hspace="10" vspace="10" src=""></td>')
document.write('<td id="cellBodyText" valign="top"><div id="mwwAlertMsgArea"></div></td></tr>')
document.write('<tr><td align="center" valign="middle" height="30" colspan="2" style="background-color:#ddecfe"><input type="button" id="mwwOkBtn" class="mwwConfirmBoxButton" value="OK" onclick="hideMwwBox($get(\'mwwAlertBox\'));"/></td></tr></table>')
document.write('</div></td></tr></table></div>')
/////////////////////////////////////////////////////////////////////////////////
	

var g_sMwwConfirmEventTarget;

function mwwConfirm(text, title, eventTarget, okButtonText, noButtonText, cancelButtonText, imgname, width, height,modal) {
    g_sMwwConfirmEventTarget = eventTarget
    var pnlModal = document.getElementById("mwwModalPnlConfirm");
    var box = document.getElementById("mwwConfirmBox");
    var tit = document.getElementById("mwwConfirmBoxTitle");
    var txt = document.getElementById("mwwConfirmMsgArea");
    var tpl = document.getElementById("mwwConfirmTemplateArea");
    var btnOk = document.getElementById("mwwConfirmOkBtn");
    var btnNo = document.getElementById("mwwConfirmNoBtn");
    var btnCancel = document.getElementById("mwwConfirmCancelBtn");
    var img = document.getElementById("mwwImgConfirm");
    var cellBodyConf = document.getElementById("cellBodyTextConf");
    var cellTitle = document.getElementById("mcbDragHelper")

    if (modal == true) {
        pnlModal.style.display = "block";
    }

    if (title) tit.innerHTML = title
    else tit.innerHTML = "MyWay Office"

    if (imgname) img.src = imgname + ".fihx"

    if (text) txt.innerHTML = text;
    
    if (okButtonText) {btnOk.style.display="block"; btnOk.value=okButtonText;}
    else btnOk.style.display = "none";

    if (noButtonText) {btnNo.style.display="block"; btnNo.value=noButtonText; }
    else btnNo.style.display = "none";

    if (cancelButtonText) {btnCancel.style.display="block"; btnCancel.value=cancelButtonText; }
    else btnCancel.style.display = "none";

    if (height) {
        cellBodyConf.style.height = (height) + 'px';
    }

    if (width) {
        box.style.width = width + "px";
        cellTitle.style.width = (width - 37) + 'px';
    } else {
        box.style.width = "300px";
        cellTitle.style.width = "263px";
    }
    showMwwBox(box);
}


function mwwConfirmResult(arg) {
    hideMwwBox(document.getElementById("mwwConfirmBox"));
    if (g_sMwwConfirmEventTarget) __doPostBack(g_sMwwConfirmEventTarget, arg);
}

function mwwConfirmResetTemplateArea() {
    $get("mwwConfirmTemplateArea").innerHTML = "";
    $get("mwwConfirmTemplateArea").style.display = "none";
    
    $('#mwwConfirmOkBtn')[0].setAttribute('onclick','');
    $('#mwwConfirmNoBtn')[0].setAttribute('onclick', '');
    $('#mwwConfirmCancelBtn')[0].setAttribute('onclick', '');
    
    $('#mwwConfirmOkBtn').unbind( 'click' );
    $('#mwwConfirmNoBtn').unbind( 'click' );
    $('#mwwConfirmCancelBtn').unbind('click');

    $('#mwwConfirmOkBtn').bind( 'click', function() { mwwConfirmResult(this.value) } );
    $('#mwwConfirmNoBtn').bind( 'click', function() { mwwConfirmResult(this.value) } );
    $('#mwwConfirmCancelBtn').bind('click', function() { hideMwwBox($get('mwwConfirmBox')) });

    $('mwwConfirmBoxButton').width = "80px";
    
    hideMwwBox($get('mwwConfirmBox'));
}


function changeConfirmClickEvent(IDButton, procedure) {
    $('#' + IDButton)[0].setAttribute('onclick', '');
    $('#' + IDButton).unbind('click');
    $('#' + IDButton).bind('click', procedure);
}

function restoreConfirmClickEvent(IDButton) {
    $('#' + IDButton)[0].setAttribute('onclick', '');
    $('#' + IDButton).unbind('click');
    if (IDButton == 'mwwConfirmCancelBtn') {
        $('#' + IDButton).bind('click', function() { hideMwwBox($get('mwwConfirmBox')); });
    } else {
        $('#' + IDButton).bind('click', function() { mwwConfirmResult(this.value); });
    }
}

///////////////////////////////////////////////////////////////////////////////
//Test New mwwConfirm
document.write('<div id="mwwModalPnlConfirm" style="display:none;"></div>')
document.write('<div id="mwwConfirmBox" style="display:none;">')
document.write('<table cellpadding="0" cellspacing="0"><tr height="28px">')
document.write('<td style="width:6px;background-image:url(TopLeft.fihx);"></td>')
document.write('<td id="mcbDragHelper" style="background-image:url(TopCenter.fihx);cursor:move;" style="width:100%;"><span id="mwwConfirmBoxTitle"></span></td>')
document.write('<td style="background-image:url(TopCenter.fihx);cursor:pointer;width:25px;"><img ID="imgCloseWdConf" src="CloseWindow.fihx" onclick="hideMwwBox($get(\'mwwConfirmBox\'));" onmouseover="this.src=\'CloseWindow_o.fihx\';" onmouseout="this.src=\'CloseWindow.fihx\';"/></td>')
document.write('<td style="background-image:url(TopRight.fihx);width:6px;"></td></tr>')
document.write('<tr><td valign="top" align="center" colspan="4" style="background-color:#ddecfe;">')
document.write('<div style="border:solid 1px #3a5a82;border-top:0px;margin:0px 0px 0px 0px;padding:0px 3px 0px 3px;">')
document.write('<table id="mwwConfirmInfo" cellspacing="0" cellpadding="0"><tr>')
document.write('<td valign="top"><img id="mwwImgConfirm" hspace="10" vspace="10" src="confirm.fihx"></td>')
document.write('<td ID="cellBodyTextConf" valign="top"><div id="mwwConfirmMsgArea"></div><div id="mwwConfirmTemplateArea"></div></td>')
document.write('<tr><td align="center" valign="middle" height="30" colspan="2" style="background-color:#ddecfe">')
document.write('<table align="center"><tr>')
document.write('<td align="center"><input type="button" id="mwwConfirmOkBtn" class="mwwConfirmBoxButton" value="OK" onclick="mwwConfirmResult(this.value) "/></td>')
document.write('<td align="center"><input type="button" id="mwwConfirmNoBtn" class="mwwConfirmBoxButton" value="NO" onclick="mwwConfirmResult(this.value); "/></td>')
document.write('<td align="center"><input type="button" id="mwwConfirmCancelBtn" class="mwwConfirmBoxButton" value="Cancel" onclick="hideMwwBox($get(\'mwwConfirmBox\'));"/></td></tr></table>')
document.write('</td></tr></table></div></td></tr></table></div>')
///////////////////////////////////////////////////////////////////////////////

function edited() {
    window.parent.g_bHasChanges = true;
    setCommandState("Save", 1)
}

function undoChanges() {
    window.parent.g_bHasChanges = false;
    setCommandState("Save", 0)
}

function onDisableToolbar() {
    setCommandState("CreateNew", 0)
    setCommandState("Save", 0)
    setCommandState("Delete", 0)
    setCommandState("Undo", 0)
    setCommandState("Print", 0)
}

function setCommandState(cmd, state) {
var obj;
    if (cmd=="CreateNew") obj = document.getElementById("mwwToolbarMain_mwwCmdNew");
    else if (cmd=="Save") obj = document.getElementById("mwwToolbarMain_mwwCmdSave");
    else if (cmd=="Delete") obj = document.getElementById("mwwToolbarMain_mwwCmdDel");
    else if (cmd=="Undo") obj = document.getElementById("mwwToolbarMain_mwwCmdUndo");
    else if (cmd=="Print") obj = document.getElementById("mwwToolbarMain_mwwCmdPrint");
    if (state == 0) {
        obj.style.filter = "alpha(opacity=30)";
        obj.style.opacity = 0.3;
        obj.style.cursor = "default";
        obj.setAttribute("disabled", "disabled")            
    } else {
        obj.style.filter = "";
        obj.style.opacity = 1;
        obj.style.cursor = "pointer";
        obj.removeAttribute("disabled")
    }
}

function deleteConfirm(confirmMsg){
    return confirm(confirmMsg)
}


function doHelp() {
    mwwAlert("Manuale utente della pagina corrente non disponibile", "Myway Office", 0);
    
//    var engine = null;
//    if (window.navigator.appName == "Microsoft Internet Explorer")
//    {
//       // This is an IE browser. What mode is the engine in?
//       if (document.documentMode) // IE8
//          engine = document.documentMode;
//       else // IE 5-7
//       {
//          engine = 5; // Assume quirks mode unless proven otherwise
//          if (document.compatMode)
//          {
//             if (document.compatMode == "CSS1Compat")
//                engine = 7; // standards mode
//          }
//       }
//       // the engine variable now contains the document compatibility mode.
//    }
//    //mwwAlert("documentMode=" + engine.toString(), "Compatibility mode test", 1)

    return false;
}

//GESTIONE MENU' TOOLBAR 
function doMenuPrint(CmdPrint,PanelMenu) {
   var Print = document.getElementById(CmdPrint)
   var Menu = document.getElementById(PanelMenu)

    //$($get(PanelMenu)).offset({ left: 130 });

   Menu.style.left = '130px'

   if (Menu.style.display == 'block'){
        Print.src='tbPrint.fihx'
        Menu.style.display='none'
   } else {
        Print.src='tbPrint_o.fihx'
        Menu.style.display='block'
   }     
   return false

}

function doMenuNote(CmdNote,PanelMenu,NameImgOut) {
    var Note = document.getElementById(CmdNote)
    var Menu = document.getElementById(PanelMenu)

    try { setVisibleMenuNote(); } catch (e) { };
    
    Menu.style.left = '170px'

   if (Menu.style.display == 'block'){
        Note.src=NameImgOut
        Menu.style.display='none'
   } else {
        Note.src='tbNote_o.fihx'
        Menu.style.display='block'
   }     
   return false

}

function mnuMouseOver(me) {
    me.style.backgroundColor='yellow'
    me.style.color = 'red'
    me.style.cursor = 'pointer'
}

function mnuMouseOut(me) {
    me.style.backgroundColor='transparent'
    me.style.color = 'black'
    me.style.cursor = 'default'
}

var g_ScrollNote;

function onSaveScroll() {
     var pnl = document.getElementById('PnlGridNote')
     g_ScrollNote = pnl.scrollTop
}

function onLoadScroll() {
    var pnl = document.getElementById('PnlGridNote')
    if (g_ScrollNote == undefined) {
        var row = document.getElementById('GridNote').childNodes[2].childNodes
        var i = 0
        var RowSel = 0
        for (i=0;i<row.length -1;i++) {
            if (row[i].getAttribute('selected') != null) {
                RowSel = i;
                break;
            }
        }
        g_ScrollNote = i * 15
    }
    pnl.scrollTop = g_ScrollNote
}

function onConfirmDeleteNota(btn) {
    //debugger;
    mwwConfirmResetTemplateArea();
    changeConfirmClickEvent('mwwConfirmOkBtn', function() { mwwConfirmResetTemplateArea(); __doPostBack(btn, "click"); });
    mwwConfirm("Vuoi eliminare la Nota selezionata?", "Gestione Note", null, "SI", "", "NO", null, null, 80, true);
    return false;
}

function onCreateHead(str) {
    //alert('creazione header')
    document.write('<div id="PnlGridNote_h_div" style="position:absolute;overflow:hidden">')
    document.write('</div>')

    //alert('top=' + document.getElementById('PnlGridNote').offsetTop +'\nleft='+document.getElementById('PnlGridNote').offsetLeft);
    document.getElementById('PnlGridNote_h_div').style.top=document.getElementById('PnlGridNote').parentElement.offsetTop;
    document.getElementById('PnlGridNote_h_div').style.left=document.getElementById('PnlGridNote').parentElement.offsetLeft;
    document.getElementById('PnlGridNote_h_div').style.width=document.getElementById('PnlGridNote').style.width;
    document.getElementById('PnlGridNote_h_div').innerHTML = str
    //alert(document.getElementById('PnlGridNote_h_div').innerHTML)
}

function onScrollTab(Master, Slave) {
    var pnlMaster = document.getElementById(Master)
    var pnlSlave = document.getElementById(Slave)
    pnlSlave.style.top = pnlMaster.scrollTop + 5

}

function setPositionFrame(master,slave) {
    var Container = document.getElementById(master)
    var Panel = document.getElementById(slave)
    if (Container != null) {
        Panel.style.top = 5 
        Panel.style.left = 280 
    }
}

function mwwOpenWindowPage(pageId, params, pageName, width, height, modal) {
    var win = window
    var targetwin = window
    while (win) {
        targetwin = win
        win = win.opener
    }
    //aggiunta gianluca per apire popup rad in popup rad (esempio finestra LayoutUsers)
    var sName;
    while (targetwin.name != '') {
        if (targetwin.name == sName) {
            targetwin = targetwin.opener
            break;
        } else {
            sName = targetwin.name
            targetwin = targetwin.parent
        }
    }
    return targetwin.mwwOpenWindow(pageId, params, pageName, width, height, GetRadWindowManager(), modal)
}


function mwwOpenFromPage(pageId, params, pageName, width, height) {
    var win = window
    var targetwin = window
    while (win) {
        targetwin = win
        win = win.opener
    }
    targetwin = targetwin.parent
    targetwin.mwwOpen(pageId, params, pageName, width, height)
}

function onOpenObj(hField) {
    var hSelObj = document.getElementById(hField)

    var val = hSelObj.split('|')

    //alert(val)

    return false;
}

var maxIndex;
var IncIndex;

function onChangeIndexPro(ID_Control, ID_hIndex, IndexBase) {
   var Control = document.getElementById(ID_Control);
   var hIndex = document.getElementById(ID_hIndex);

   if (Control.currentStyle.zIndex != maxIndex) {
        if (IncIndex == undefined) IncIndex = 0;
        IncIndex += 10;
        hIndex.value = parseInt(IndexBase) + IncIndex;
        Control.runtimeStyle.zIndex = hIndex.value
        maxIndex = hIndex.value
   }
}

function onChangeCanale(cmb, tabNoMail, tabYesMail, cmdSend) {
    var Canale = document.getElementById(cmb)
    var NoMail = document.getElementById(tabNoMail)
    var YesMail = document.getElementById(tabYesMail)
    var Send = document.getElementById(cmdSend)

    if (Canale.value == 'e-mail') {
        Send.removeAttribute('disabled')
        if (Send.style.filter) Send.style.filter = ""
        else Send.style.opacity = 1;
        NoMail.style.display = 'none'
        YesMail.style.display = 'block'
    } else {
        Send.setAttribute('disabled', 'true')
        if (Send.style.filter) Send.style.filter = "alpha(opacity=30)"
        else Send.style.opacity = 0.3;        
        NoMail.style.display = 'block'
        YesMail.style.display = 'none'
    }
}

function onLoadParamCom(hParam) {
    var ParamFrame = document.getElementById(hParam)
    var ParamParent = window.parent.document.getElementById('mwwToolbarMain_mwwComInOut_hParamCom')
    ParamFrame.value = ParamParent.value
    __doPostBack(hParam,'FirstLoad')
}

function onLoadfrm(objid) {
    var frame = document.getElementById('iFrameDlgCom')
    if (frame != null) {
        var ParamCom = document.getElementById(objid)
        frame.src = ParamCom.value
    }
}

function onLoadModelloComunication() {
    //var frame = self.frames['FrameComIn'].document
    //var divEdit = frame.getElementById("ctl04_divEdit")
    var divEdit;
    if (FrameComIn.contentDocument) divEdit = FrameComIn.contentDocument.getElementById('ctl04_divEdit');
        else divEdit = FrameComIn.document.getElementById('ctl04_divEdit');
    var hMarkup = document.getElementById('hMarkup')

    divEdit.innerHTML = divEdit.innerHTML + hMarkup.value
}

function onSaveMarkupComunication() {
    var divEdit;
    if (FrameComIn.contentDocument) divEdit = FrameComIn.contentDocument.getElementById('ctl04_divEdit');
    else divEdit = FrameComIn.document.getElementById('ctl04_divEdit');
    var hMarkup = document.getElementById('hMarkup')
    var hText = document.getElementById('hTesto')
    var File = document.getElementById('FileUpload')
    var hFile = document.getElementById('hFile')

    hFile.value = File.value
    hMarkup.value = divEdit.innerHTML
    hText.value = divEdit.innerHTML
    
    return true
}

//controllo DialogBox_Documenti
function onCloseDialogBox() {
    var box = document.getElementById('DocumentTicket_pnlSelectMatr')
    box.style.display = 'none'
}

var detSel;


////-------------INIZIO LOOKUP----------------
function onReturnValueLookup(IDLook, Grid, RetValue, ValueEmpty, ValueSep, AddValue,hidewindow) {
    //debugger;
    var ArrRet = RetValue.split('|')
    var i = 0
    var j = 0
    var ClienID
    var KeyField
    var RowHeader = $find(Grid).get_masterTableView().get_columns();
    var GridLookUp = $find(Grid).get_masterTableView()
    var obj;
    
    //svuoto i controlli di ritorno
    for (i = 0; i <= ArrRet.length - 1; i++) {
        ClientID = ArrRet[i].split('=')[1]
        switch (ClientID.substr(0, 4)) {
            case 'LBL_':
                ClientID = ClientID.substr(4, ClientID.length - 1)
                obj = window.parent.document.getElementById(ClientID);
                if (AddValue) {
                    if (obj.innerHTML.length > 0) obj.innerHTML = obj.innerHTML + ','
                } else {
                    obj.innerHTML = ""
                }
            case 'CHK_':
                ClientID = ClientID.substr(4, ClientID.length - 1)
                window.parent.document.getElementById(ClientID).cheched = false

            default:
                obj = window.parent.document.getElementById(ClientID)
                if (AddValue) {
                    if (obj.value.length > 0) obj.value = obj.value + ','
                } else {
                    obj.value = ""
                }
        }
    }
    
    var isSet = false;
    //ciclo su parametri di ritorno
    for (i = 0; i <= ArrRet.length - 1; i++) {
        isSet = false
        var TypeCnt = ''
        ClientID = ArrRet[i].split('=')[1]
        switch (ClientID.substr(0, 4)) {
            case 'LBL_':
                ClientID = ClientID.substr(4, ClientID.length - 1)
                TypeCnt = 'LBL'
            case 'CHK_':
                ClientID = ClientID.substr(4, ClientID.length - 1)
                TypeCnt = 'CHK'
        }
        KeyField = ArrRet[i].split('=')[0]
        //ciclo la griglia
        if (KeyField != '_') {
            for (j = 0; j <= RowHeader.length - 1; j++) {
                //alert(RowHeader[j].get_uniqueName() + ' - ' + KeyField)
                if (RowHeader[j].get_uniqueName() == KeyField) {
                    isSet = true
                    if (window.parent.document.getElementById(ClientID).value != '') window.parent.document.getElementById(ClientID).value = window.parent.document.getElementById(ClientID).value + ' '

                    var app = '';
                    var IndexSelRow = 0;
                    //CICLARE SULLE RIGHE
                    for (var k = 0; k < GridLookUp.get_selectedItems().length; k++) {
                        IndexSelRow = GridLookUp.get_selectedItems()[k]._itemIndexHierarchical
                        if (IndexSelRow == '') IndexSelRow = 0
                        app = app + $find(Grid).get_masterTableView().get_dataItems()[IndexSelRow].get_element().getElementsByTagName("TD")[j].innerHTML
                        if (k < GridLookUp.get_selectedItems().length - 1) app = app + ValueSep
                    }

                    if ((app == ' ') || (app == '&nbsp;')) app = ValueEmpty
                    app = app.replace('&amp;','&')
                    switch (TypeCnt) {
                        case 'LBL':
                            window.parent.document.getElementById(ClientID).innerHTML = window.parent.document.getElementById(ClientID).innerHTML + app
                        case 'CHK':
                            if (app == 1) window.parent.document.getElementById(ClientID).checked = true
                            else window.parent.document.getElementById(ClientID).checked = false

                        default:
                            window.parent.document.getElementById(ClientID).value = window.parent.document.getElementById(ClientID).value + app
                            if (window.parent.document.getElementById(ClientID).getAttribute('OLD_VALUE'))
                                window.parent.document.getElementById(ClientID).setAttribute('OLD_VALUE', app)
                    }
                    break;
                }
            }

            if (!isSet) {
                if ($find(Grid).get_masterTableView().get_selectedItems()[0].getDataKeyValue(KeyField)) {
                    isSet = true
                    if (window.parent.document.getElementById(ClientID).value != '') window.parent.document.getElementById(ClientID).value = window.parent.document.getElementById(ClientID).value + ' '

                    var app = '';
                    var IndexSelRow = 0;
                    //CICLARE SULLE RIGHE
                    for (var k = 0; k < GridLookUp.get_selectedItems().length; k++) {
                        IndexSelRow = GridLookUp.get_selectedItems()[k]._itemIndexHierarchical
                        if (IndexSelRow == '') IndexSelRow = 0
                        app = app + $find(Grid).get_masterTableView().get_dataItems()[IndexSelRow].getDataKeyValue(KeyField)
                        if (k < GridLookUp.get_selectedItems().length - 1) app = app + ValueSep
                    }

                    if ((app == ' ') || (app == '&nbsp;')) app = ValueEmpty
                    app = app.replace('&amp;', '&')
                    switch (TypeCnt) {
                        case 'LBL':
                            window.parent.document.getElementById(ClientID).innerHTML = window.parent.document.getElementById(ClientID).innerHTML + app
                        case 'CHK':
                            if (app == 1) window.parent.document.getElementById(ClientID).checked = true
                            else window.parent.document.getElementById(ClientID).checked = false

                        default:
                            window.parent.document.getElementById(ClientID).value = window.parent.document.getElementById(ClientID).value + app
                            if (window.parent.document.getElementById(ClientID).getAttribute('OLD_VALUE'))
                                window.parent.document.getElementById(ClientID).setAttribute('OLD_VALUE', app)
                    }
                }
            }
        } else {
            window.parent.document.getElementById(ClientID).value = ValueEmpty
        }
    }

    if (window.parent.$find(IDLook) == undefined) {
        window.parent.document.getElementById(IDLook).childNodes[3].value = '_'
        window.parent.document.getElementById(IDLook).style.display = 'none'
    } else {
        if (hidewindow) {
            window.parent.$find(IDLook).hide()
            window.parent.$find(IDLook).setUrl("about:blank");
        }
    }

}

function onPostTarget(EventTarget, EventArgument, hidewindow) {
    if (EventTarget != '') window.parent.__doPostBack(EventTarget, EventArgument + "|" + (hidewindow ? 1 : 0));
}

function rowSelected(sender, eventArgs) {
    //$get('hSelRow').value = $get('hSelRow').value + '|' + eventArgs.get_itemIndexHierarchical()

}

function rowDeselected(sender, eventArgs) {
    //$get('hSelRow').value = $get('hSelRow').value.replace('|' + eventArgs.get_itemIndexHierarchical(),'')
}

//ritorna l' array della lookup utilizzata
function getParLookUp(IDLookUp) {
    var app;
    var posStart = $("*").html().indexOf("arrLookUp_" + IDLookUp)
    var strApp = $("*").html().substr(posStart)
    var strArr = strApp.substr(0, (strApp.indexOf("]]") + 1))

    strArr = strArr.substr((IDLookUp.length + 14)).split("[")

    var i;
    var arrLookUp = new Array()
    if (strArr[0] == '') {
        for (i = 1; i < strArr.length; i++) {
            var ArrKeyValue = strArr[i].split("]")[0];
            var Key = ArrKeyValue.split(",")[0].substr(1, (ArrKeyValue.split(",")[0].length - 2));
            var Value = ArrKeyValue.split(",")[1].substr(1, (ArrKeyValue.split(",")[1].length - 2));
            arrLookUp[i - 1] = new Array(Key, Value);
        }
    }
    return arrLookUp
}

function getUnicodeFormat(str) {
    str = str.replace("#", "%23")
    str = str.replace("%", "%25")
    str = str.replace("&", "%26")
    str = str.replace("(", "%28")
    str = str.replace(")", "%29")
    str = str.replace("+", "%2B")
    str = str.replace(",", "%2C")
    str = str.replace(".", "%2E")
    str = str.replace("/", "%2F")
    str = str.replace(":", "%3A")
    str = str.replace(";", "%3B")
    str = str.replace("<", "%3C")
    str = str.replace("=", "%3D")
    str = str.replace(">", "%3E")
    str = str.replace("?", "%3F")
    str = str.replace("@", "%40")
    str = str.replace("[", "%5B")
    str = str.replace("\\", "%5C")
    str = str.replace("]", "%5D")
    str = str.replace("^", "%5E")
    str = str.replace("\"", "%27")
    str = str.replace("{", "%7B")
    str = str.replace("|", "%7C")
    str = str.replace("}", "%7D")
    str = str.replace("~", "%7E")
    return str
}

function onLoadRadLookUp(IDLookUp, LookUpType) {
    //debugger
    var sParams;
    var sProperty;
    var arrLookUpChild;
    var ArrApp;
    var sTitleWindow = "";
    var i;
    
    //parametri
    ArrApp = eval($get(IDLookUp + "_HField").value)
    for (i = 0; i <= ArrApp.length - 1; i++) {
        if (ArrApp[i][0] == LookUpType) {
            sParams = ArrApp[i][1];
            sProperty = ArrApp[i][2];
            sTitleWindow = ArrApp[i][3];
            break;
        }
    }

    //controlli da cui prendere i valori aggiornati
    ArrApp = eval($('#' + IDLookUp + '_HParams')[0].value);
    for (i = 0; i <= ArrApp.length - 1; i++) {
        if (ArrApp[i][0] == LookUpType) {
            arrLookUpChild = ArrApp[i][1];
            break;
        }
    }

    var arrPar = sParams.split("&");
    var arrProp = $get(IDLookUp + '_HURlCont').value + sProperty

    var i = 0;
    var newSrc = "";
    var app;
    for (i = 0; i < arrPar.length; i++) {
        app = arrPar[i];
        if ((app.split("=")[0] == "height")) app = "height=" + (parseInt(app.split("=")[1].split("px")[0]) - 20) + "px";
        for (j = 0; j < arrLookUpChild.length; j++) {
            if ((arrPar[i].split("=")[0] == arrLookUpChild[j][0]) && (arrLookUpChild[j][1] != '')) {
                if ($("#" + arrLookUpChild[j][1])[0] == undefined) break; //se il controllo non viene trovato viene caricato il valore inserito come default lato server
                var val = getRealValue($("#" + arrLookUpChild[j][1])[0]);

                if (arrPar[i].split("=")[1].indexOf("|") != -1) {
                    app = arrPar[i].split("=")[0] + "=" + val + "|" + arrPar[i].split("=")[1].split("|")[1] + "|" + arrPar[i].split("=")[1].split("|")[2] + "|" + arrPar[i].split("=")[1].split("|")[3] + "|" + arrPar[i].split("=")[1].split("|")[4];
                } else {
                    app = arrPar[i].split("=")[0] + "=" + val;
                }
                break;
            }
        }

        if (i == arrPar.length - 1) {
            newSrc = newSrc + app;
        } else {
            newSrc = newSrc + app + "&";
        }
    }

    var frmLookUp = document.forms['frmLookUpParams']

    frmLookUp.hPropertyLookUp.value = arrProp
    frmLookUp.hParamsLookUp.value = newSrc

    $find(IDLookUp).set_width(arrProp.split("&")[2].replace('width=', '').replace('px', ''));
    $find(IDLookUp).set_height(arrProp.split("&")[3].replace('height=', '').replace('px', ''));
    $find(IDLookUp).set_title(sTitleWindow);
    $find(IDLookUp).setUrl("about:blank");
    $find(IDLookUp).show()

    $find(IDLookUp).add_close(setAboutBlank)

    frmLookUp.action = "MwwLookUp.mwwx";
    frmLookUp.target = $find(IDLookUp).get_name();
    frmLookUp.method = "POST";
    frmLookUp.submit();

    frmLookUp.hPropertyLookUp.value = ""
    frmLookUp.hParamsLookUp.value = ""
}

function setAboutBlank(sender,args) {
    sender.setUrl("about:blank");
}

function getRealValue(ctr) {
    if (ctr.value == "---") return ""
    if (!ctr.getAttribute("OLD_VALUE")) return getUnicodeFormat(ctr.value)
    if (ctr.value == ctr.getAttribute("OLD_VALUE")) {
        return ""
    } else {
        return getUnicodeFormat(ctr.value)
    }
}

function onResizeLookUp(sender, eventArgs) {
    var frm = window.frames[sender._name]
    var nFilter = (27 * frm.$get("NFilter").value)
    if (window.navigator.appName != "Microsoft Internet Explorer") nFilter += 6;

    frm.$find("GridFiltro").get_element().style.width = (sender.getWindowBounds().width - 20) + 'px';
    frm.$get("pnlContGrid").style.width = (sender.getWindowBounds().width - 18) + 'px';
    frm.$find("GridFiltro").get_element().style.height = (sender.getWindowBounds().height - (72 + nFilter)) + 'px';
    frm.$get("pnlContGrid").style.height = (sender.getWindowBounds().height - (62 + nFilter)) + 'px';
    frm.$find("GridFiltro").repaint()
}

var m_IDLookUp;
function setSizeLookUp(IDLookUp) {
    if ((m_IDLookUp == undefined) && (IDLookUp)) m_IDLookUp = IDLookUp;
    if ($find("GridFiltro")) {
        var nFilter = (27 * $get("NFilter").value)
        if (window.navigator.appName != "Microsoft Internet Explorer") nFilter += 6;
        
        $find("GridFiltro").get_element().style.width = (window.parent.$find(m_IDLookUp).getWindowBounds().width - 20) + 'px';;
        $get("pnlContGrid").style.width = (window.parent.$find(m_IDLookUp).getWindowBounds().width - 18) + 'px';;
        $find("GridFiltro").get_element().style.height = (window.parent.$find(m_IDLookUp).getWindowBounds().height - (72 + nFilter)) + 'px'; ;
        $get("pnlContGrid").style.height = (window.parent.$find(m_IDLookUp).getWindowBounds().height - (62 + nFilter)) + 'px';;
        $find("GridFiltro").repaint()
    } else setTimeout(setSizeLookUp, 100);
}

function onClearValueLookUp(txt, ArrCtrClear) {
    if (txt.value.length == 0) {
        var Arr = ArrCtrClear
        for (var i = 0; i <= Arr.length - 1; i++) {
            $get(Arr[i]).value = '';
        }
    }
    return txt.value.length == 0 ? true : false;
}

//-------------FINE LOOKUP------------------
var appval = null;

function onEnable(val) {
    var ajaxPanel = $find("UpdRad");
    if (appval==null) appval = val;
    if (!ajaxPanel) {
        setTimeout(onEnable, 10);
    } else {
        ajaxPanel.set_enableAJAX(appval);
        appval=null
    }
}

function resizeGridAgenda() {
    try {
        $("#TodoList_wGridTodo")[0].runtimeStyle.overflow = "hidden"
        $("#TodoList_wGridTodo")[0].style.width = (document.body.offsetWidth - 13).toString() + "px";
        $("#TodoList_wGridTodo")[0].style.height = (document.body.offsetHeight - 180).toString() + "px";
    } catch (e) { }
}

//----------Cronologia---------------
function onSelectNodeCrono(otr) {
    try {
        var i = 0;
        for (i = 0; i <= otr.getElementsByTagName("TABLE").length - 1; i++) {
            otr.document.getElementById("TrvCronot" + i).runtimeStyle.color = "gray";
            otr.document.getElementById("TrvCronot" + i).runtimeStyle.fontWeight = "normal";
        }
        if (event.srcElement.tagName != "IMG") {
            try {
                otr.document.getElementById(event.srcElement.id).runtimeStyle.color = "Maroon";
                otr.document.getElementById(event.srcElement.id).runtimeStyle.fontWeight = "bold";
            } catch (e) {
                event.srcElement.runtimeStyle.color = "Maroon";
                event.srcElement.runtimeStyle.fontWeight = "bold";
            }
        } else {
            event.srcElement.parentElement.parentElement.nextSibling.childNodes(0).runtimeStyle.color = "Maroon";
            event.srcElement.parentElement.parentElement.nextSibling.childNodes(0).runtimeStyle.fontWeight = "bold";
        }
    } catch (e) {}
}

function onTreeView(val) {
    try {
        var treeview = $('#TrvCrono')[0]

        if (val == 0) {
            treeview.childNodes[0].getElementsByTagName("IMG")[0].src = "arrowOpen.fihx"
            treeview.childNodes[1].style.display = 'none'
        } else {
            treeview.childNodes[0].getElementsByTagName("IMG")[0].src = "arrowClose.fihx"
            treeview.childNodes[1].style.display = 'block'
        }
    } catch (e) {}
}
//----------------------------------------


//----------------NOTE----------------------
var gCodTipoNota = '', gNotaKeyField = '', gNotaCodWinMW = '', gNoteNotLoad;

function onLoadNotaOpenWin(Cod_TipoNota, KeyField, CodWinMW, strTipiNotLoad) {
    //debugger;
    if (KeyField) {
        gCodTipoNota = Cod_TipoNota;
        gNotaKeyField = KeyField;
        gNotaCodWinMW = CodWinMW;
        gNoteNotLoad = strTipiNotLoad;
    }
    if (GetRadWindowManager()) {
            if (GetRadWindowManager().get_windows()) {
                var sArrCodTipi = gCodTipoNota.split('|')
                var sArrKeyField = gNotaKeyField.split('|')
                var sArrCodWin = gNotaCodWinMW.split('|')
                var sArrNotLoad = gNoteNotLoad.split('|')

                for (var i = 0; i < sArrCodTipi.length; i++) {
                    if (sArrCodTipi[i] != '') onOpenNota(sArrCodTipi[i], sArrKeyField[i], sArrCodWin[i], sArrNotLoad[i]);
                }
               
            } else {
                setTimeout(onLoadNotaOpenWin,10)
            }
    } else {
        setTimeout(onLoadNotaOpenWin,10)
    }
}

var g_nNextMwwWindowIdNote = 0
function onOpenNota(Cod_TipoNota, KeyField, CodWinMW,strTipiNotLoad) {
    //debugger;
    var matrKeyNota = new Array();
    matrKeyNota[0] = new Array("CodTipoNota",Cod_TipoNota);
    matrKeyNota[1] = new Array("NomeChiave",KeyField);
    matrKeyNota[2] = new Array("ValoreChiave","");
    matrKeyNota[3] = new Array("CodiceRisorsa", $("#HField_CodiceRisorsa")[0].value);
    matrKeyNota[4] = new Array("IDUtenteMW", $("#HField_IDUtenteMW")[0].value);
    matrKeyNota[5] = new Array("CodWinMW",CodWinMW);
    matrKeyNota[6] = new Array("CodNotaSincro", "");
    matrKeyNota[7] = new Array("TipiNotLoad", strTipiNotLoad)
    matrKeyNota[8] = new Array("IDPage", $("#HField_IDPage")[0].value)

    //questa funzione viene chiamata nel file javascript della pagina;
    //in diverse pagine avremo la stessa funzione che tornera valori diversi
    //ATTENZIONE!!! a non includere nella pagina due file jScript con lo stessa funzione

    var matrKeyConfirm = valueParamNoteInMwwFw(matrKeyNota);
    
    var strQuery = "";
    for (var i = 0; i <= matrKeyConfirm.length - 1; i++) {
        strQuery += matrKeyConfirm[i][0] + "=" + matrKeyConfirm[i][1] + "&";
    }

    var sExcludeNote = '';

    try { sExcludeNote = exsTipiNota() } catch (e) { };

    g_nNextMwwWindowIdNote++;

    var dat = new Date()
    wndNoteName = "MwwWindow" + dat.getHours() + '' + dat.getMinutes() + '' + dat.getSeconds() + g_nNextMwwWindowIdNote;
    
    var winNote = GetRadWindowManager().open("about:blank", wndNoteName);
    
    //var winNote = $find("mwwToolbarMain_mwwRadNote");
    winNote.set_width(576)
    winNote.set_height(500)
    winNote.set_title('Note')
    winNote.setUrl("MwwNote.mwwx?" + strQuery + "height=" + winNote.get_height() + "&width=" + winNote.get_width() + "&exscludenote=" + sExcludeNote)
    winNote.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close)
    winNote.show()
}

function onChangeNota(value) {
    //debugger;
    var matrKeyNota = new Array();
    matrKeyNota[0] = new Array("CodTipoNota", value.split("|")[0]);
    matrKeyNota[1] = new Array("NomeChiave", value.split("|")[1]);
    matrKeyNota[2] = new Array("ValoreChiave","");
    matrKeyNota[3] = new Array("CodiceRisorsa", "");
    matrKeyNota[4] = new Array("IDUtenteMW", "");
    matrKeyNota[5] = new Array("CodWinMW","");
    matrKeyNota[6] = new Array("CodNotaSincro", "");
    matrKeyNota[7] = new Array("TipiNotLoad", "");
    
    var matrKeyConfirm = valueParamNoteInMwwFw(matrKeyNota);

    return matrKeyNota[2][1];
}

function onSelectNota(sender, args) {
    __doPostBack("hNoteUser", sender.get_masterTableView().get_selectedItems()[0].get_element().rowIndex)
}

function onSelectNewUser(sender, args) {
    __doPostBack("hNewUser", sender.get_masterTableView().get_selectedItems()[0].get_element().rowIndex)
}

function EnabledButtonDelete(sender,args) {
    var UtenteSel = sender.get_masterTableView().get_selectedItems()[0].get_element().cells(0).innerHTML
    var UtenteLogg = IDUtenteMW
    var DelUser = document.getElementById('UserDel')
    if (UtenteSel == UtenteLogg) {
        if (DelUser.style.filter) DelUser.style.filter = "alpha(opacity=30)"
        else DelUser.style.opacity = 0.3;
        DelUser.setAttribute("disabled", "disabled");
    } else {
        if (DelUser.style.filter) DelUser.style.filter = ""
        else DelUser.style.opacity = 1;
        DelUser.setAttribute("disabled", "");
    }
}

function onChangePermessi(Index) {
    //debugger;
    var Pos = Index;

    var chkWrite = $find("GridCond").get_masterTableView().get_dataItems()[Index].get_element().childNodes[4].childNodes[0]
    var chkDelete = $find("GridCond").get_masterTableView().get_dataItems()[Index].get_element().childNodes[5].childNodes[0]
    var txtPermessi = document.getElementById('txtPermessi')

    var Permessi
    if (chkDelete.checked == true) {
        Permessi = 'D'
        chkWrite.checked = true
    } else {
        if (chkWrite.checked == true) {
            Permessi = 'W'
        } else {
            Permessi = 'R'
        }
    }

    var Array = txtPermessi.value.split("|")
    var LocalArr
    var NewValue = ''
    var i = 1
    for (i = 1; i < Array.length; i++) {
        LocalArr = Array[i].split(":")
        if (LocalArr[0] == Pos) {
            LocalArr[1] = Permessi
            Array[i] = LocalArr[0] + ':' + LocalArr[1]
        }
        NewValue = NewValue + '|' + Array[i]
    }
    txtPermessi.value = NewValue
}

function onClickNote() {
    //debugger;
    document.getElementById('CelNota').style.borderBottomWidth = '0px';
    document.getElementById('CelPer').style.borderBottomWidth = '1px';
    document.getElementById('CelPer').style.borderBottomColor = 'gray';
    document.getElementById('CelPer').style.borderBottomStyle = 'solid';
    document.getElementById('pnlNote').style.display = 'block';
    document.getElementById('pnlCond').style.display = 'none';
    document.getElementById('CelNota').style.backgroundColor = 'e6e6fa';
    document.getElementById('CelPer').style.backgroundColor = 'c8c8d9';
    document.getElementById('TabSel').value = '0';
}

function onClickPermessi() {
    //debugger;
    document.getElementById('CelNota').style.borderBottomWidth = '1px';
    document.getElementById('CelNota').style.borderBottomColor = 'gray';
    document.getElementById('CelNota').style.borderBottomStyle = 'solid';
    document.getElementById('CelPer').style.borderBottomWidth = '0px';
    document.getElementById('pnlNote').style.display = 'none';
    document.getElementById('pnlCond').style.display = 'block';
    document.getElementById('CelNota').style.backgroundColor = 'c8c8d9';
    document.getElementById('CelPer').style.backgroundColor = 'e6e6fa';
    document.getElementById('TabSel').value = '1';
}

function EnableUndoButton() {
    var UndoButton = document.getElementById('UndoBtn');
    UndoButton.style.filter = "";
    UndoButton.setAttribute("disabled", "");

    var NewButton = document.getElementById('NewBtn');
    if (NewButton.style.filter) NewButton.style.filter = "alpha(opacity=30)"
    else NewButton.style.opacity = 0.3;
    NewButton.setAttribute("disabled", "disabled");

    var DelButton = document.getElementById('DelBtn');
    if (DelButton.style.filter) DelButton.style.filter = "alpha(opacity=30)"
    else DelButton.style.opacity = 0.3;
    DelButton.setAttribute("disabled", "disabled")
}
//------------------------------------------------------------------

//-----------------------------Comunicazioni-------------------------
function TypeCom() {
    this.Log = 0;
    this.Attivita = 1;
    this.Cliente = 2;
}

//carica il controllo delle comunicazioni
function doComInOut() {
    //debugger;
    var matrKeyCom = new Array();
    matrKeyCom[0] = new Array("Codice", "");
    matrKeyCom[1] = new Array("TipoCod", "");
    matrKeyCom[2] = new Array("RagSoc", $("#HField_RagSoc")[0].value);
    matrKeyCom[3] = new Array("IDUtente", $("#HField_IDUtente")[0].value);
    matrKeyCom[4] = new Array("IDAreaCom", "");
    matrKeyCom[5] = new Array("CodComInOut", "");

    //questa funzione viene chiamata nel file javascript della pagina;
    //in diverse pagine avremo la stessa funzione che tornera valori diversi
    //ATTENZIONE!!! a non includere nella pagina due file jScript con lo stessa funzione
    var matrKeyConfirm = valueParamComInMwwFw(matrKeyCom);

    var strQuery = "";
    for (var i = 0; i <= matrKeyConfirm.length - 1; i++) {
        strQuery += matrKeyConfirm[i][0] + "=" + matrKeyConfirm[i][1] + "&";
    }

    var winCom = $find("mwwToolbarMain_mwwRadCom");
    winCom.setUrl("MwwComInOut.mwwx?" + strQuery + "height=" + winCom.get_height() + "&width=" + winCom.get_width())
    winCom.show()

    return false;
}

//questa funzione apre un popup contenente la preview del modello di comunicazione passato come parametro.
//i parametri saranno valorizzati andano a interrogare dal file js associato allo specifico controllo che richiama la
//preview la funzione getValueParamsPreview() (personalizzata a secondo del controllo)
var gIDArea;
var g_ArrParamsMod;

function OpenPreviewComunication(IDMod,IDArea) {
    //debugger;
    gIDArea = IDArea
    var Prs = new MwwObject.JsRequest('SP_WEB_GetModelli_Com')
    Prs.resultType(2,'<<*>>')
    Prs.addParams('ID_Modello', IDMod, 0)
    Prs.addParams('All',0,0) //carico solo il markup del modello
    Prs.onResultService(onLoadModPreview)
}

function onLoadModPreview(executor, eventArgs) {
    if (executor.get_responseAvailable()) {
        var result = executor.get_responseData();
        if (result != "") {
            result = result.substring(1, result.length - 1)
            var Pos = result.indexOf('<<*>>')
            var Oggetto = result.substring(0, Pos)
            var Modello = result.substring(Pos + 5)
            
            onPreviewOpen(Oggetto, Modello);
        }
    }
}

function onPreviewOpen(Oggetto, Modello) {
    var ds = new Date()
    var sDate = ds.getDay().toString() + '/' + ds.getMonth().toString() + '/' + ds.getFullYear().toString()

    Modello = onCreatePreview(Modello,Oggetto, g_ArrParamsMod)

    var popup = window.open("about:blank", "Anteprima", "width=600,height=400,location=0,menubar=0,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0")
    popup.document.write(Modello)
}

function onCreatePreview(sModello,sOggetto, ArrParams) {
    var sHtml = "";
    var NameParam = "";
    var ValueParam = "";
    var sAnt = sModello
    var sObj = sOggetto
    for (var i = 0; i <= ArrParams.length - 1; i++) {
        NameParam = ArrParams[i][0].replace('[#', '|!').replace('#]', '!|')
        ValueParam = ArrParams[i][1]
        while (sAnt.indexOf(NameParam)!=-1) {
            sAnt = sAnt.replace(NameParam, ValueParam)
        }
        while (sObj.indexOf(NameParam)!=-1) {
            sObj = sObj.replace(NameParam, ValueParam)
        }
    }
   
    sHtml = "<html><head><title>" + sObj + "</title><style>BODY{font-family:Tahoma;font-size:11px;}TABLE{font-family:Tahoma;font-size:11px;}</style></head><body>"
    sHtml += sAnt
    sHtml += "</body></html>"
    return sHtml
}

//---------------------------------------------------------------------

//---------------------------Report------------------------------------
document.write('<div ID="pnlParams" style="width:300px;position:absolute;top:200px;left:200px;z-index:110;display:none;background-color:#aad5ff;filter:alpha(opacity=95);opacity:0.95;border:solid 1px navy">');
document.write('<div style="background-color:gray;width:100%;height:20px;cursor:move;" ondragstart="mwwMessageBoxStartMove();" ondrag="mwwMessageBoxMove(this.parentElement);" onmousedown="this.dragDrop();"><span ID="mwwMessageBoxTitle" style="width:300px">Parametri Report</span></div>');
document.write('</div>');

var parMatrReport; //contiene tutti i parametri del report
var ArrParamDialog; //contiene i parametri che verranno modificati dall' utente

function onOpenReport(IDReport) {
    //debugger;
    $("#pnlMenuReport")[0].style.display = "none";
    $("#mwwToolbarMain_mwwCmdPrint")[0].src = "tbPrint.fihx";
    
    //filtro i parametri del report selezionato
    var j = 0;
    parMatrReport = new Array();
    var parHeadParam = arrReportPage[0];
    for (var i = 1; i <= arrReportPage.length - 1; i++) {
        if (arrReportPage[i][14] == IDReport) {
            parMatrReport[j] = arrReportPage[i];
            j++;
        }
    }

    //questa funzione viene chiamata nel file javascript della pagina;
    //in diverse pagine avremo la stessa funzione che tornera valori diversi
    //ATTENZIONE!!! a non includere nella pagina due file jScript con lo stessa funzione
    var matrParConf = valueParamReportInMwwFw(parMatrReport);

    if (matrParConf == undefined) return false;

    j=0;
    ArrParamDialog = new Array(); //array contenente i parametri che verranno chiesti all' utente
    for (var i = 0; i <= matrParConf.length - 1; i++) {
        //if (matrParConf[i][10] == 0) { //Flg_TypeParam
            //verifico se esiste un valore di default altrimenti lo chiedo all' utente
            if ((matrParConf[i][9] == '') && (matrParConf[i][9] != 0) && (matrParConf[i][12] != 1)) {
                ArrParamDialog[j] = new Array(matrParConf[i][5],matrParConf[i][6],matrParConf[i][8]) //ID_Param,Parametro,Etichetta
                j++;
            }
//        } else {
//            //lo chiedo sempre all utente    
//            ArrParamDialog[j] = new Array(matrParConf[i][5],matrParConf[i][6],matrParConf[i][8]) //ID_Param,Parametro,Etichetta
//            j++;
//        }
    }

    //se ci sono parametri da valorizzare da parte dell' utente...
    if (ArrParamDialog.length > 0) {
        //costruisco la dialog
        onBuildDialogReport();
    } else {
        OpenPopUpReport();
    }
    return false
}


function onBuildDialogReport() {
    var PnlParam = $("#pnlParams")[0];
    PnlParam.style.top = (screen.height / 2) - 100;
    PnlParam.style.left = (screen.width / 2) - 100;
        
    var strMark = '<table>';
    for (var i = 0; i <= ArrParamDialog.length - 1; i++) {
        strMark+='<tr><td align="right" style="background-color:white" >';
        strMark += '<label id="lbl' + ArrParamDialog[i][1] + '" style="width:130px;font:normal bold 11px tahoma" visible="true">' + ArrParamDialog[i][2] + '</label>';
        strMark+='</td><td align="left">';
        strMark += '<input type="text" name="txtPar_' + ArrParamDialog[i][1] + '"  style="width:180px" visible="true"/>';
        strMark += '<input type="hidden" name="HIDParam_' + ArrParamDialog[i][1] + '" value="' + ArrParamDialog[i][0] + '" />';
        strMark += '</td></tr>';
    }
    strMark += '</table>';
    strMark += '<table style="width:300px"><tr><td align="center">';
    strMark += '<input name="cmdElaboraReport" type="button" value="OK" style="width:80px" onclick="OpenPopUpReport();" />';
    strMark += '<input name="cmdCloseReport" type="button" value="Annulla" style="width:80px" onclick="onParamClose();" />';
    strMark += '</td></tr></table>';

    var div = document.createElement("DIV");
    div.innerHTML = strMark;
    PnlParam.appendChild(div)

    PnlParam.style.display = "block";
}

var g_bOpenPopUp = false;
function OpenPopUpReport() {
    //debugger;
    var hParams = $("#hRepParams")[0];  //campo imput che conterra i parametri del report da caricare
    var KeyParam;
    var ValueParam;

    //se ci sono parametri modificati dall' utente
    if (ArrParamDialog.length > 0) {
        var ArrTextInput = $("#pnlParams INPUT[type='text']"); //array contenente i campi hidden (key parametri)
        var ArrHiddenInput = $("#pnlParams INPUT[type='hidden']"); //array contenente i campi text (value parametri)
        for (var k = 0; k <= ArrHiddenInput.length - 1; k++) {
            KeyParam = ArrHiddenInput[k].value; //chiave del k-esimo parametro
            ValueParam = ArrTextInput[k].value; //valore del k-esimo parametro
            for (var j = 0; j <= parMatrReport.length - 1; j++) { //scorro la matrice dei parametri
                if (parMatrReport[j][5] == KeyParam) { //se nella matrice trovo un parametro che ha la stessa chiave del del k-esimo parametro... 
                    parMatrReport[j][9] = ValueParam; //aggiorno il valore della matrice
                    break; //passo al parametro k successivo
                }
            }            
        }
    }
    
    hParams.value = getStrParam()

    var frm = document.forms[0];

    var NameFile = parMatrReport[0][2].replace(/ /gi, "_")
    
    var OldAction = frm.getAttribute('action');
    frm.setAttribute("action", "MwwDocument.mwwx?CodReport=" + parMatrReport[0][0] + "&CodAzienda=" + parMatrReport[0][1] + "&NomeReport=" + parMatrReport[0][4] + "&NameFile=" + NameFile + "");


    g_bOpenPopUp = true;
    
    var OldTarget = frm.target;
    //frm.target = "OpenReportPopUp";
    frm.target = "";
    frm.submit();

    g_bOpenPopUp = false
    

    frm.target = OldTarget;
    frm.setAttribute("action", OldAction);

    onParamClose()
}

//creo una stringa contenente i parametri da splittare, di ogni parametro , carico solo:
//indici: 6=nome parametro, 9=valore, 11=flg_sql, 12=datatype, 13=rif sql,
function getStrParam() {
    var arrParam;
    var strQuery="";
    for (var i = 0; i <= parMatrReport.length - 1; i++) {
        arrParam = parMatrReport[i];
        for (var y = 0; y <= arrParam.length - 1; y++) {
            if ((y == 6) || (y == 9) || (y == 11) || (y == 12) || (y == 13)) {
            strQuery += arrParam[y] + "|";
            }
        }
        if (i != parMatrReport.length-1) strQuery += "^"
    }
    return strQuery;
}

function onParamClose() {
    if (ArrParamDialog.length > 0) {
        $("#pnlParams")[0].removeChild($("#pnlParams")[0].childNodes[1]);
        $("#pnlParams")[0].style.display = "none";
    }
}

//-----------------------------------------------------------------------


//--------------------------GRIGLIE TELERIK-------------------------------
var gridPage; //array contenente gli ID delle Griglie
var lastWidth; //array contenente l' ultima dimensione della TitleBar (usata come riferimento per ridimenionare la griglia)
var resolutionApply; //indica se il ridimensionamento per la risoluzione e stato applicato;

//carica e aggiorna l'array contenente i nomi delle Griglie che verranno ridimensionate
function onLoadGrid(sender, args) {
    //debugger;
    var IDGrid = sender.get_element().id;
    var gridExsist = false;
    //verifico se l' array è stato inizializzato
    if (gridPage == null) {
        gridPage = new Array();
    } else {
       //se l' array e gia inizializzato, verifico se l' id della griglia e gia caricato
        for (var i = 0; i <= gridPage.length - 1; i++) {
            if (gridPage[i][0] == IDGrid) {
                gridExsist = true;
                break;
            }
        }
    }
    //carico l' ID della griglia nell' array se non è presente
    if (!gridExsist) {
        gridPage[gridPage.length] = new Array(IDGrid , sender.get_element().style.width, sender.get_element().parentElement.style.width);
    }
    if (lastWidth == null) lastWidth = window.parent.frames["frameApp"].frameElement.offsetWidth;
}

//ridimensiona tutte le griglie presenti nell' array gridPage
//viene richiamato dal click sul pulsante di scomparsa del frame menu
function onResizeGrid() {
    //debugger;
    if (window.parent.frames["frameApp"] == undefined) return;
    if (window.parent.frames["frameApp"].gridPage == null) return;
    var Grid; //Griglia
    var Panel; //Pannello che contiene la griglia
    var currentWidth = window.parent.frames["frameApp"].frameElement.offsetWidth; //prendo la dimensione corrente della title bar

    //se la dimensione attuale del frame non e variata esco
    if (currentWidth != window.parent.frames["frameApp"].lastWidth) {
        for (var i = 0; i <= window.parent.frames["frameApp"].gridPage.length - 1; i++) {
            Grid = window.parent.frames["frameApp"].$("#" + window.parent.frames["frameApp"].gridPage[i][0])[0] //prendo la prima griglia
            Panel = Grid.parentElement
            if (currentWidth > window.parent.frames["frameApp"].lastWidth) {
                Grid.style.width = Grid.offsetWidth + (currentWidth - window.parent.frames["frameApp"].lastWidth);
                Panel.style.width = parseInt(Panel.currentStyle.width.split("px")[0]) + (currentWidth - window.parent.frames["frameApp"].lastWidth);
            } else {
            Grid.style.width = Grid.offsetWidth - (window.parent.frames["frameApp"].lastWidth - currentWidth);
            Panel.style.width = parseInt(Panel.currentStyle.width.split("px")[0]) - (window.parent.frames["frameApp"].lastWidth - currentWidth);
            }
            gridPage[i][1] = Grid.style.width; //memorizzo l' attuale larghezza della griglia
            gridPage[i][2] = Panel.style.width; //memorizzo l' attuale largehezza del pannello contenitore
        }
        window.parent.frames["frameApp"].lastWidth = currentWidth;
    }
}

function getInfoGrid(idGriglia) {
   for(var i=0;i<=gridPage.length-1;i++) {
    if (gridPage[i][0]==idGriglia) {
        return gridPage[i]
    }
   }
}

function onSetResolutionGrid(sender, args) {
    //debugger;
    var InfoGrid = getInfoGrid(sender.get_element().id);
    if (!resolutionApply) {
        switch (screen.width) {
            case 800:
                sender.get_element().style.width = parseInt(InfoGrid[1].split("px")[0]) - 480;
                sender.get_element().parentElement.style.width = parseInt(InfoGrid[2].split("px")[0]) - 480;
                break;
            case 1024:
                sender.get_element().style.width = parseInt(InfoGrid[1].split("px")[0]) - 256;
                sender.get_element().parentElement.style.width = parseInt(InfoGrid[2].split("px")[0]) - 256;
                break;
            case 1280:
                sender.get_element().style.width = parseInt(InfoGrid[1].split("px")[0]);
                sender.get_element().parentElement.style.width = parseInt(InfoGrid[2].split("px")[0]);
                break;
        }
        resolutionApply = true;
    } else {
        sender.get_element().style.width = parseInt(InfoGrid[1].split("px")[0])
        sender.get_element().parentElement.style.width = parseInt(InfoGrid[2].split("px")[0])
    }
}
//------------------------------------------------------------------------

function onCharValid() {
    if ((event.keyCode < 48) || (event.keyCode > 57)) { //numeri
        if ((event.keyCode < 65) || (event.keyCode > 90)) { //caratteri maiuscoli
            if ((event.keyCode < 97) || (event.keyCode > 122)) { //caratteri minuscoli
                if ((event.keyCode != 46) && (event.keyCode != 45) && (event.keyCode != 95) && (event.keyCode != 231) && (event.keyCode != 36)) { //caratteri speciali . _ @ $ -
                    event.returnValue = false;
                }
            }
        }
    }
}


//---------------------------permessi sulla pagina attivita -- SOLUZIONE MOMENTANEA -------------------
var g_CliIDEnableAtt;
function getPermissionPageAtt(IDUser, UserType, CliContValue) {
    //alert('IN MWWFW.JS')
    g_CliIDEnableAtt = CliContValue
    var AttPer = new MwwObject.JsRequest('SP_WEB_GetPermissionAtt')
    AttPer.resultType(2, '|')
    AttPer.addParams('ID_User', IDUser, 0)
    AttPer.addParams('UserType', UserType, 0)
    AttPer.onResultService(onLoadPermAtt)
}

function onLoadPermAtt(executor, eventArgs) {
    if (executor.get_responseAvailable()) {
        var result = executor.get_responseData();
        if (result != "") {
            $get(g_CliIDEnableAtt).value = result.substring(1,2)
        }
    }
}

//------------------------------------------------------------------------------------------------------


//----------------------------valore configurazione ------ WEB_FW_Configuration -------------------------
var g_ValueConf;
function getConfiguration(ID_Config) {
    //debugger;
    var Conf = new MwwObject.JsRequest('SP_WEB_FW_GetConfiguration')
    Conf.resultType(2, '|')
    Conf.addParams('ID_Config', ID_Config, 0)
    Conf.onResultService(onLoadConfSys)
}

function onLoadConfSys(executor, eventArgs) {
    //debugger;
    if (executor.get_responseAvailable()) {
        var result = executor.get_responseData();
        if (result != "") {
            g_ValueConf = '';
            result = result.substring(1, result.length - 1)
            var Value = result.split('|')[0]
            var DefValue = result.split('|')[1]
            if (Value == '') {
                g_ValueConf = DefValue
            } else {
                g_ValueConf = Value
            }
        }
    }
}
//-----------------------------------------------------------------------------------------------



//---------------------------- Esecuzione comandi layout mwwGrid -------------------------
function mwwGridCommand(sender, gridId, pageId, exp) {
    var grid = $find(gridId);
    var val = grid.get_masterTableView().get_selectedItems()[0].getDataKeyValue(exp);
    //alert(sender.getAttribute("img") + "\n" + "pageId=" + pageId + "\n" + "exp=" + exp);

    var typeCom = new TypeCom()
    var windowCom = mwwOpenWindowPage(54, 'cod_com=|codice=' + val + '|type_com=' + typeCom.Attivita + '|id_areacom=6|cod_cli=|cod_rich=|cod_inter=|txt_inter=|', '', 0, 0, false);

    windowCom.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize + Telerik.Web.UI.WindowBehaviors.Maximize)
}
function mwwOpenGridLayoutManager(parms) {
    //debugger;
    //mwwOpenWindowPage(53, parms, '', 865, 548, true)       
    mwwOpenWindowPage(53, parms, '', 882, 560, true)
}
function mwwGridCtxMenuItemClicked(sender, args) {
    var item = args.get_item();
    if (item.get_items().get_count() == 0) sender.hide();
    if (sender.get_attributes().getAttribute("OnClientItemClickedEvent")) eval(sender.get_attributes().getAttribute("OnClientItemClickedEvent") + "(sender, args)");
}
function mwwGridReloadLay(gridId, args) {
   // debugger;
    __doPostBack(gridId + "CustomCmd", args);
}
function mwwGridOpenInfo(src, gridId, objCode, objType) {
    var mtv = $find(gridId).get_masterTableView();
    mtv.selectItem(src.parentNode.parentNode);
    //var di = mtv.get_dataItems();
    //window.parent.mwwOpenInfo(di[mtv.get_selectedItems()[0]._itemIndexHierarchical].getDataKeyValue(keyField) + "|" + objType, 1020, 700);
    var win = window, targetWin;
    while (win) { targetWin = win; win = targetWin.opener; }
    targetWin.parent.mwwOpenInfo(objCode + "|" + objType, 1020, 700);
}


function mwwGridColumnResized(sender, eventArgs) {
    //debugger;

}

////----------------------------------------------------------------------------------------

//controllo inserimento caratteri decimali
function ctlSepDec(ctr, e) {
    var keynum;
    var ev;
    if (window.event) {
        ev = window.event
        keynum = event.keyCode;
    } else {
        ev = e
        keynum = e.keyCode;
        if (keynum == 0) keynum = e.which;
    }

    var KeySep = 46; // il punto
    if (Global_chSepDec == ',') KeySep = 44
    
    if (((keynum < 48) || (keynum > 57)) && (keynum != KeySep)) {
        try {
            ev.returnValue = false;
            ev.preventDefault();
        } catch (e) { }
    }

    if ((ctr.value.indexOf(Global_chSepDec) != -1) && (keynum == KeySep)) {
        try {
            ev.returnValue = false;
            ev.preventDefault();
        } catch (e) { }
    }
}

////----------------------TEST GIANLUCA COMET----------------------


////---------------------------------------------------------------

