var _selectedMainTab = null;
var _currLinkTree = -1;

function noClickLoading(message) {
  if ((event.button == 1) || (event.button == 2)) {
    alert('Caricamento sentenze in corso, operazione non consentita.\nAttendere prego...')
  }
}
function noClickSearching(message) {
  if ((event.button == 1) || (event.button == 2)) {
    alert('Ricerca in corso, operazione non consentita.\nAttendere prego...')
  }
}

function CheckStatus() {
  if (document.getElementById('hidToolareaStatus').value == 1)
    ResizeToolArea('no');
  if (document.getElementById('hidDoclistStatus').value == 0)
    ResizeDocList('no');
}

function CheckFieldHL(fieldName) {
  if (document.getElementById(fieldName).value != '' && !document.getElementById(fieldName).readOnly)
    document.getElementById(fieldName).style.backgroundColor = '#D5E2F5';
  else
    document.getElementById(fieldName).style.backgroundColor = '#ffffff';
}

function LogOut() {
  if (window.frames["fraContent1"].frames["FraDoclist"].$('input[type="checkbox"]').length > 0) {
    fireClickEvent(document.getElementById('hrefLinklogout'));
  }
  else {
    document.forms['logoutForm'].submit();
  }
}

function DoResizeNavigate() {
  document.getElementById('divContent').style.height = GetInnerHeight() - pageHeaderHeight + 'px';
  document.getElementById('divSplashScreen').style.display = 'none';
  document.getElementById('divContent').style.display = 'block';
}

function DoResizeHP() {
  document.getElementById('divContenuti').style.height = GetInnerHeight() - pageHeaderHeight + "px";
}

function ToolAreaMouseOver() {
  document.getElementById('imgToolAreaResize').src = imgResizeOnMouseOver.src;
}

function ToolAreaMouseOut() {
  document.getElementById('imgToolAreaResize').src = imgResizeOnMouseOut.src;
}

function DocListMouseOver() {
  document.getElementById('imgDocListResize').src = imgResizeVertOnMouseOver.src;
}

function DocListMouseOut() {
  document.getElementById('imgDocListResize').src = imgResizeVertOnMouseOut.src;
}

function ResizeToolArea(doresize) {
  doresize = doresize || 'yes';

  document.frmResizeObj.hidObj.value = 'toolarea';

  if (divtoolareaPxWidth == divtoolareaClosePxWidth) {
    divtoolareaPxWidth = divtoolareaOpenPxWidth;
    searchTextPxWidth = searchTextOpenPxWidth - 5;
    imgResizeOnMouseOver = imgResizeOnMouseOverOpen;
    document.frmResizeObj.hidNewStatus.value = 1;
  }
  else {
    divtoolareaPxWidth = divtoolareaClosePxWidth;
    searchTextPxWidth = searchTextClosePxWidth;
    imgResizeOnMouseOver = imgResizeOnMouseOverClose;
    document.frmResizeObj.hidNewStatus.value = 0;
  }

  document.frmResizeObj.submit();

  if (doresize == 'yes') {
    DoResize();

    if (navigator.appVersion.indexOf('MSIE 5.0') > 0)
      window.onresize();
  }
}

function ResizeDocList(doresize, newstatus) {
  doresize = doresize || 'yes';
  newstatus = newstatus || null;

  document.frmResizeObj.hidObj.value = 'doclist';

  if (newstatus == 'close') {
    document.frmResizeObj.hidNewStatus.value = 0;
    document.getElementById('divcheckall').style.display = 'none';
    imgResizeVertOnMouseOver = imgResizeVertOnMouseOverOpen;
    if (document.getElementById('divrepository').style.display == 'block') {
      document.getElementById('divrepository').style.display = 'none';
      divDocviewMinPxHeight -= 43;
      document.frmResizeObj.submit();
    }
  }
  else if (newstatus == 'open') {
    document.frmResizeObj.hidNewStatus.value = 1;
    document.getElementById('divcheckall').style.display = 'block';
    imgResizeVertOnMouseOver = imgResizeVertOnMouseOverClose;
    if (document.getElementById('divrepository').style.display != 'block') {
      document.getElementById('divrepository').style.display = 'block';
      divDocviewMinPxHeight += 43;
      document.frmResizeObj.submit();
    }
  }
  else {
    if (document.getElementById('divrepository').style.display == 'block') {
      document.getElementById('divrepository').style.display = 'none';
      document.getElementById('divcheckall').style.display = 'none';
      imgResizeVertOnMouseOver = imgResizeVertOnMouseOverOpen;
      divDocviewMinPxHeight -= 43;
      document.frmResizeObj.hidNewStatus.value = 0;
    }
    else {
      document.getElementById('divrepository').style.display = 'block';
      document.getElementById('divcheckall').style.display = 'block';
      imgResizeVertOnMouseOver = imgResizeVertOnMouseOverClose;
      divDocviewMinPxHeight += 43;
      document.frmResizeObj.hidNewStatus.value = 1;
    }
    document.frmResizeObj.submit();
  }

  if (doresize == 'yes') {
    DoResize();

    if (navigator.appVersion.indexOf('MSIE 5.0') > 0)
      window.onresize();
  }
}

function HilightOnTab(tabname) {
  if (document.getElementById(tabname).className != 'selectedtab')
    document.getElementById(tabname).className = 'hilightedtab';
}

function HilightOffTab(tabname) {
  if (document.getElementById(tabname).className != 'selectedtab')
    document.getElementById(tabname).className = 'tab';
}


//------------------------------------------------------------------
// FUNCTION:    GetInnerHeight
// DESCRIPTION: retrieves browser window height (not including margin,
//              border, or scroll bar)
// ARGUMENTS:   none
// RETURN:      clientHeight
//------------------------------------------------------------------
function GetInnerHeight() {
  return document.body.clientHeight;
}


//------------------------------------------------------------------
// FUNCTION:    GetInnerWidth
// DESCRIPTION: retrieves browser window width (not including margin,
//              border, or scroll bar)
// ARGUMENTS:   none
// RETURN:      clientWidth
//------------------------------------------------------------------
function GetInnerWidth() {
  return document.body.clientWidth;
}

function GetBodiesHeight() {
  if ((GetInnerHeight() - pageHeaderHeight - tabHeadersHeight - toolAreaPadding) >= divbodiesMinPxHeight)
    return (GetInnerHeight() - pageHeaderHeight - tabHeadersHeight - toolAreaPadding);
  else
    return divbodiesMinPxHeight;
}

function GetViewAreaWidth() {
  if ((GetInnerWidth() - divtoolareaPxWidth) >= divviewareaMinPxWidth)
    return (GetInnerWidth() - divtoolareaPxWidth);
  else
    return divviewareaMinPxWidth;
}

function GetDocviewHeight() {
  offset = 0;

  if (document.getElementById('divrepository').style.display == 'none')
    offset = 113;

  if ((GetInnerHeight() - pageHeaderHeight - divViewAreaHeight - viewAreaPadding) >= divDocviewMinPxHeight)
    return (GetInnerHeight() - pageHeaderHeight - divViewAreaHeight - viewAreaPadding) + offset;
  else
    return divDocviewMinPxHeight + offset;
}
//------------------------------------------------------------------
// FUNCTION:    SwitchLayer
// DESCRIPTION: switch between two layers
// ARGUMENTS:   vis (div's ID  to show)
//              hid (div's ID  to hide)
// RETURN:      none
//------------------------------------------------------------------
function SwitchLayer(vis, hid) {
  document.getElementById(vis).style.display = "block";
  document.getElementById(hid).style.display = "none";
}


//------------------------------------------------------------------
// FUNCTION:    SwitchLabel
// DESCRIPTION: switch between two labels, changing their appearance
// ARGUMENTS:   active
//              inactive
// RETURN:      none
//------------------------------------------------------------------
function SwitchLabel(active, inactive, idLayer, obj) {

  obj = obj || document;
  switch (idLayer) {
    case 'treebox':
      obj.getElementById(active).style.color = "#ffffff";
      obj.getElementById(inactive).style.color = "#000000";
      break;

    case 'viewarea':
      obj.getElementById(active).style.color = "#6c99dc";
      obj.getElementById(inactive).style.color = "#000000";
      break;

    default:
      obj.getElementById(active).style.color = "#dddddd";
      obj.getElementById(inactive).style.color = "#000000";
      break;

    case 'doclist':
      obj.getElementById(active).style.color = "#6c99dc";
      obj.getElementById(inactive).style.color = "#000000";
      break;
  }
}

//------------------------------------------------------------------
// FUNCTION:    SwapImg
// DESCRIPTION: rollover on images
// ARGUMENTS:   name = image's name
//              action (max, min) = action performed by the icon's click
//              state = identifies the image to be used (active/inactive)
// RETURN:      none
//------------------------------------------------------------------
function SwapImg(name, action, state) {
  switch (action) {
    case "max":
      {
        if (state == 1)
          eval('document.' + name + '.src="' + max_resize.src + '";');
        else
          eval('document.' + name + '.src="' + resize.src + '";');
      }
      break;
    case "min":
      {
        if (state == 1)
          eval('document.' + name + '.src="' + min_resize.src + '";');
        else
          eval('document.' + name + '.src="' + resize.src + '";');
      }
      break;
  }
}


//------------------------------------------------------------------
// FUNCTION:    CheckAllControl
// DESCRIPTION: controls the state of "checked" attribute for 
//              chekboxes in a from
// ARGUMENTS:   idIframe = iframe's ID
//              idForm = form's ID
//              state = value to set
// RETURN:      none
//------------------------------------------------------------------
function CheckAllControl(frameName, formId, state) {

  if (state == "checked")
    window.frames[frameName].$('#' + formId + ' input').attr('checked', 'checked');
  else
    window.frames[frameName].$('#' + formId + ' input').removeAttr('checked');
}

function ShowDocList() {
  ResizeDocList('yes', 'open');
  document.getElementById('divencyclopediaterm').style.display = 'none';
  document.getElementById('divdoclist').style.display = 'block';
  document.getElementById('divcheckall').style.display = 'block';
}

function ShowEncyclopedia() {
  ResizeDocList('yes', 'open');
  document.getElementById('divcheckall').style.display = 'none';
  document.getElementById('divdoclist').style.display = 'none';
  document.getElementById('divencyclopediaterm').style.display = 'block';
}

function PrintRaccoglitore() {
  if (window.frames["FraDoclist"].document.forms[0].elements[4]) {
    window.frames["FraDoclist"].document.getElementById('hidAction').value = 'print';
    window.frames["FraDoclist"].document.forms[0].target = 'newWindow';
    window.frames["FraDoclist"].document.forms[0].submit();
  }
  else
    alert('Nessun documento nel raccoglitore');
}

function CopyToClipboard() {
  if (!$.browser.msie) {
    alert('Questa funzionalita\' e\' disponibile solo per browser Microsoft Internet Explorer.');
    return;
  }

  window.frames["FraDocview"].document.getElementById('hidCopy').value =
    window.frames["FraDocview"].document.getElementById('divTitle').innerText + "\n\n" +
    window.frames["FraDocview"].document.getElementById('divParti').innerText + "\n" +
    window.frames["FraDocview"].document.getElementById('divGiudice').innerText + "\n\n" +
    window.frames["FraDocview"].document.getElementById('divText').innerText;
  window.frames["FraDocview"].document.getElementById('hidCopy').createTextRange().execCommand('Copy');
}

function CopyToClipboardEnciclopedia() {
  if (!$.browser.msie) {
    alert('Questa funzionalita\' e\' disponibile solo per browser Microsoft Internet Explorer.');
    return;
  }

  window.frames["FraDocview"].document.getElementById('hidCopy').value =
    window.frames["FraDocview"].document.getElementById('divText').innerText;
  window.frames["FraDocview"].document.getElementById('hidCopy').createTextRange().execCommand('Copy');
}

function CheckEnterStartSearch(e) {
  if (e == null) {
    alert('CheckEnterStartSearch con "e" null');
    return;
  }

  if (e.which == 13) {
    e.preventDefault();
    DoSearch();
    return false;
  }
}

function SearchPubblicazioni(searchText, mainWindow) {
  mainWindow.switchCont('skin2', 'm2');
  SelectMainTab(2, mainWindow);
  mainWindow.frames['fraContent2'].document.getElementById('searchText').value = searchText;
  mainWindow.frames['fraContent2'].DoSearch();
}

function SearchGiurisprudenza(searchText, mainWindow) {
  mainWindow.switchCont('skin1', 'm1');
  SelectMainTab(1, mainWindow);
  mainWindow.frames['fraContent1'].document.getElementById('searchText').value = searchText;
  mainWindow.frames['fraContent1'].DoSearch();
}

function OpenDocumentsSearchWindowBig(searchTerms, sezione) {
  h = window.open('../aspx/FrmSearchPopUp.aspx?sezione=' + sezione + '&search=' + escape(searchTerms), 'documentSearchWindow', 'width=500,height=250,left=20,top=20,location=no,menubar=no,resizable=no,status=yes,toolbar=no,scrollbars=no');
  h.focus();
}


function CurrLink(n) {

  n = n || '-1';

  if (
    _currLink != null &&
    _currLink != -1 &&
    document.getElementById('lnk_' + _currLink) != null
    ) {
    document.getElementById('lnk_' + _currLink).style.backgroundColor = '#ffffff';
  }

  if (n != '-1' && document.getElementById('lnk_' + n) != null) {
    document.getElementById('lnk_' + n).style.backgroundColor = '#c2d4f0';
  }

  if (_currLink != null)
    _currLink = n;
}

function CurrLinkTree(n) {
  n = n || '-1';

  if (
    _currLinkTree != null &&
    _currLinkTree != -1 &&
    document.getElementById('a_' + _currLinkTree) != null
    ) {
    document.getElementById('a_' + _currLinkTree).style.backgroundColor = '#ffffff';
  }

  if (n != '-1' && document.getElementById('a_' + n) != null) {
    document.getElementById('a_' + n).style.backgroundColor = '#c2d4f0';
  }

  if (_currLinkTree != null)
    _currLinkTree = n;
}

function LoadMainTabContent(n, oWindow) {
  if (oWindow == null)
    oWindow = window;

  oFrame = oWindow.document.getElementById('fraContent' + n);

  if (oFrame.src == '' || oFrame.src.indexOf('FrmNavigate') > -1) {
    if (n == 1)
      oFrame.src = 'FrmGiurisprudenza.aspx?' + Math.round(Math.random() * 1000);
    if (n == 2)
      oFrame.src = 'FrmPubblicazioni.aspx?' + Math.round(Math.random() * 1000);
    else if (n == 3)
      oFrame.src = 'FrmEnciclopedia.aspx?' + Math.round(Math.random() * 1000);
    else if (n == 4)
      oFrame.src = 'FrmFormulario.aspx?' + Math.round(Math.random() * 1000);
  }
}


function SelectMainTab(n, oWindow) {
  if (oWindow == null)
    oWindow = window;

  if (oWindow._selectedMainTab != null) {
    if (oWindow._selectedMainTab == n)
      return;
    else
      oWindow.UnSelectMainTab(oWindow._selectedMainTab);
  }

  oWindow._selectedMainTab = n;

  oDiv = oWindow.document.getElementById('divContent' + n);
  oTabCaption = oWindow.document.getElementById('hrefMainTab' + n);

  // refresh raccoglitore
  if (oWindow.frames['fraContent' + n].frames['FraDoclist'] != null)
    oWindow.frames['fraContent' + n].frames['FraDoclist'].location = 'FrmDoclist.aspx?param=' + Math.floor(Math.random() * 1001);

  oDiv.style.display = 'block';
  oTabCaption.className = 'sel';

  oWindow.switchCont('skin' + n, 'm' + n);
}

function UnSelectMainTab(n) {
  _selectedMainTab = null;

  oDiv = document.getElementById('divContent' + n);
  oTabCaption = document.getElementById('hrefMainTab' + n);

  oDiv.style.display = 'none';
  oTabCaption.className = '';
}

function DoIASearch() {

  parent.document.getElementById("hidIASearchIDFolders").value = '';
  parent.document.getElementById("hidIASearchTextFolders").value = '';

  chks = document.getElementsByName("chkfolders");

  for (i = 0; i < chks.length; i++) {
    if (chks[i].checked) {
      parent.document.getElementById("hidIASearchIDFolders").value = parent.document.getElementById("hidIASearchIDFolders").value + chks[i].id + ',';
      parent.document.getElementById("hidIASearchTextFolders").value = parent.document.getElementById("hidIASearchTextFolders").value + '"' + document.getElementById("span_" + chks[i].id).innerText + '",';
    }
  }

  if (parent.document.getElementById("hidIASearchIDFolders").value == '') {
    alert("Attenzione: nessun termine selezionato!");
    return;
  }

  parent.document.getElementById("hidIASearchText").value = document.getElementById("searchText").value;
  parent.document.getElementById("hidIASearch").value = "1";
  parent.document.getElementById('tdSearch').innerHTML = '<img alt="Ricerca in corso..." src="../images/searching2.gif" border="0" >';
  parent.document.getElementById('spnSearch').innerHTML = '<img style="margin-top: -2px;" alt="Ricerca in corso..." src="../images/searching2.gif" border="0">&nbsp;&nbsp;<img style="margin-top: -2px;" alt="Ricerca in corso..." src="../images/cancel.gif" border="0">';
  parent.document.getElementById('divfraresults').style.display = 'none';
  parent.document.getElementById('divfraresultsloading').style.display = 'block';

  parent.contColManage('resultFocus');
  parent.document.onmousedown = noClickSearching;
  parent.document.searchForm.submit();
  parent.$.fancybox.close();
}

var _id1;
var _mv1;
var _path1;

function GoToDocumento(id, mainWindow) {
  _id1 = id;
  _mv1 = mainWindow;
  mainWindow.SelectMainTab(1, mainWindow);
  setTimeout("_mv1.frames[ 'fraContent1' ].frames['FraDocview'].location='../aspx/FrmDocview.aspx?IDDocument=' + _id1;", 2000);
  //mainWindow.frames[ 'fraContent1' ].frames['FraDocview'].location='../aspx/FrmDocview.aspx?IDDocument=' + id;
}

function GoToPubblicazione(path, mainWindow) {
  _path1 = path;
  _mv1 = mainWindow;
  mainWindow.SelectMainTab(2, mainWindow);
  //mainWindow.frames['fraContent2'].frames['FraDocview'].location = path;
  setTimeout("_mv1.frames['fraContent2'].frames['FraDocview'].location = _path1;", 2000);
  mainWindow.frames['fraContent2'].document.getElementById('divToolBar').style.visibility = 'visible'
}

function RemoveFromRaccoglitore() {
  if (window.frames["FraDoclist"].document.forms[0].elements[4]) {
    if (confirm('Eliminare dal raccoglitore gli oggetti selezionati?')) {
      window.frames["FraDoclist"].document.getElementById('hidAction').value = 'remove';
      window.frames["FraDoclist"].document.forms[0].target = '';
      window.frames["FraDoclist"].document.forms[0].submit();
    }
  }
  else
    alert('Nessun documento nel raccoglitore');
}

function HideEmbeddedDocuments() {
  var win1;
  var win2;

  if (document.getElementById('docview') != null) {
    win1 = window;
    win2 = window;
  }
  else if (window.frames['fraContent1'] != null) {
    win1 = window.frames['fraContent2'];
    win2 = window.frames['fraContent4'];
  }

  if (
    win1.document.getElementById('docview') != null &&
    (
      win1.frames['FraDocview'].location.href.toLowerCase().indexOf('.pdf') > 0 ||
      win1.frames['FraDocview'].location.href.toLowerCase().indexOf('.doc') > 0
     ))
    win1.document.getElementById('docview').style.visibility = 'hidden';

  if (
    win2.document.getElementById('docview') != null &&
    (
      win2.frames['FraDocview'].location.href.toLowerCase().indexOf('.pdf') > 0 ||
      win2.frames['FraDocview'].location.href.toLowerCase().indexOf('.doc') > 0
     ))
    win2.document.getElementById('docview').style.visibility = 'hidden';
}

function ShowEmbeddedDocuments() {
  var win1;
  var win2;

  if (document.getElementById('docview') != null) {
    win1 = window;
    win2 = window;
  }
  else if (window.frames['fraContent1'] != null) {
    win1 = window.frames['fraContent2'];
    win2 = window.frames['fraContent4'];
  }

  if (win1.document.getElementById('docview') != null)
    win1.document.getElementById('docview').style.visibility = 'visible';

  if (win2.document.getElementById('docview') != null)
    win2.document.getElementById('docview').style.visibility = 'visible';
}

function fireClickEvent(mailLink) {

  //$(mailLink).click();

  // *********************************
  // FF/NN accept programmed events,
  // but default action will be taken only
  // from hardvare device input:

  if (document.createEvent) { // FF model
    var customClick = document.createEvent('MouseEvents');
    customClick.initEvent('click', 0, 0);
    mailLink.dispatchEvent(customClick);
    // The old good click() is removed from link methods:
    //try {mailLink.click();} catch(e){alert(e.toString());}
  }
  // *********************************
  // IE accepts programmed events,
  // but default action will be taken only
  // from hardvare device input (like FF/NN):
  else if (document.createEventObject) { // IE model


    var customClick = document.createEventObject();
    mailLink.fireEvent('onclick', customClick);

    // The old good click() was simply forgotten
    // by the brave IE team and allows to bypass security:

    mailLink.click(); // equals to a hardware click


  }
  else {
    // NOP
  }
  // In your case you can use a unofficial sidewalk:
  //document.location.href = document.links[1].href;

  // If W3 comes to kill you, don't blame on me though :-)
  // Also over the last 12 years people tried to put all
  // kind of nasty crap via mailto, so it's very secured.
  // In a *secure browser* you can add nothing but a
  // subject line and *one* line of plain text into body.
}

function getParam(param) {
  param = param.replace(/[[]/, '\[').replace(/[]]/, '\]');
  var regexS = '[\?&]' + param + '=([^&#]*)',
  regex = new RegExp(regexS),
  results = regex.exec(window.location.href);
  if (results === null)
    return null;
  else
    return results[1];
}

function UserTrace(url, title, section) {
  $.post("../aspx/AjaxProvider.aspx", { mode: "UserTrace", destUrl: url, title: title, section: section });
}

function UserTracePubblicazioni(url, title) {
  UserTrace(url, title, 'Pubblicazioni');
}

function UserTraceFormulario(url, title) {
  UserTrace(url, title, 'Formulario');
}

function UserTraceGiurispredenzaFolder(url, title, hrefEl) {
  if ( hrefEl.className == 'off' )
    UserTrace(url, title, 'Cartella Giurisprudenza');
}

function UserTracePubblicazioniFolder(url, title, hrefEl) {
  if (hrefEl.className == 'off')
    UserTrace(url, title, 'Cartella Pubblicazioni');
}
