function txtAutocompleteFromDdl(txtId, ddlId) {

  var txt = $(txtId);
  var ddlElement = $(ddlId);

  txt
	  .autocomplete({
	      source: function(request, response) {
	          var matcher = new RegExp("^" + request.term, "i");
	          response(ddlElement.children("option").map(function() {
	              var text = $(this).text();
	              if (this.value && (!request.term || matcher.test(text))) {
	                  return {
	                      id: this.value,
	                      label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
	                      value: text
	                  };
	              }
	          }));
	      },
	      delay: 0,
	      select: function(event, ui) {
	          if (!ui.item) {
	              // remove invalid value, as it didn't match anything
	              $(this).val("");
	              return false;
	          }

	          ddlElement.val(ui.item.id);
	          //	      ddl._trigger("selected", event, {
	          //	        item: ddlElement.find("[value='" + ui.item.id + "']")
	          //	      });
	      },
	      change: function(event, ui) {
	          if (!ui.item) {
	              // remove invalid value, as it didn't match anything
	              $(this).val("");
	              return false;
	          }

	          ddlElement.val(ui.item.id);
	          //	      ddl._trigger("selected", event, {
	          //	        item: ddlElement.find("[value='" + ui.item.id + "']")
	          //	      });
	      },

	      minLength: 1,
	      autoFill: true
	  });
}
  
function txtAutocompleteComuneFromFunction(txtId, hidId, txtProvinciaId, hidProvinciaId, urlJsonService) {

  var txt = $(txtId);
  var hid = $(hidId);
  var txtProvincia = $(txtProvinciaId);
  var hidProvincia = $(hidProvinciaId);

  txt
	  .autocomplete({
	      source: function(request, response) {
	          $.ajaxSetup({
	              timeout: 5000,
	              async: false
	          });
	          var data = eval('(' + $.getJSON(urlJsonService, { service: "comuni", mode: "kvp", term: request.term }).responseText + ')');
	          data = jQuery.map(data, function(item, i) {
	              return { label: item.Value, id: item.Key }
	          });
	          $.ajaxSetup({
	              async: true
	          });
	          response(data);
	      },
	      delay: 0,
	      select: function(event, ui) {
	          txt.val(ui.item.label);
	          hid.val(ui.item.id);
	          $(this).data("uiItem", ui.item.label);

	          if (txtProvincia != null) {
	              $.getJSON(urlJsonService, { service: "provincie", mode: "kvp", codiceComune: ui.item.id }, function(data) {
	                  txtProvincia.val(data.Value);
	                  hidProvincia.val(data.Key);
	                  txtProvincia.data("uiItem", data.Value);
	              });
	          }

	          return false;
	      },
	      minLength: 2,
	      autoFill: true
	  });
}

function txtAutocompleteStatoFromFunction(txtId, hidId, divProvinciaId, divComuneId, urlJsonService) {

  var txt = $(txtId);
  var hid = $(hidId);
  var divProvincia = $(divProvinciaId);
  var divComune = $(divComuneId);

  txt
	  .autocomplete({
	      source: function(request, response) {
	          $.ajaxSetup({
	              timeout: 5000,
	              async: false
	          });
	          var data = eval('(' + $.getJSON(urlJsonService, { service: "nazioni", mode: "kvp", term: request.term }).responseText + ')');
	          data = jQuery.map(data, function(item, i) {
	              return { label: item.Value, id: item.Key }
	          });
	          $.ajaxSetup({
	              async: true
	          });
	          response(data);
	      },
	      delay: 0,
	      select: function(event, ui) {
	          txt.val(ui.item.label);
	          hid.val(ui.item.id);
	          $(this).data("uiItem", ui.item.label);

	          if (ui.item.id == '119') {
	              divProvincia.show();
	              divComune.show();
	          }
	          else {
	              divProvincia.hide();
	              divComune.hide();
	          }

	          return false;
	      },
	      minLength: 1,
	      autoFill: true
	  });
}

function txtAutocompleteComuneDiProvinciaFromFunction(txtId, hidId, hidProvinciaId, urlJsonService) {

    var txt = $(txtId);
    var hid = $(hidId);
    var hidProvincia = $(hidProvinciaId);

    txt
	  .autocomplete({
	      source: function(request, response) {
	          $.ajaxSetup({
	              timeout: 5000,
	              async: false
	          });
	          var data = eval('(' + $.getJSON(urlJsonService, { service: "comuni", mode: "kvp", term: request.term, codiceProvincia: hidProvincia.val() }).responseText + ')');
	          data = jQuery.map(data, function(item, i) {
	              return { label: item.Value, id: item.Key }
	          });
	          $.ajaxSetup({
	              async: true
	          });
	          response(data);
	      },
	      delay: 0,
	      select: function(event, ui) {
	          txt.val(ui.item.label);
	          hid.val(ui.item.id);
	          $(this).data("uiItem", ui.item.label);

	          return false;
	      },
	      minLength: 1,
	      autoFill: true
	  })
	  .addClass("ui-widget ui-widget-content ui-corner-left");
}


// Numeric input filter

  /*
  *  Dev One (http://www.dev-one.com)
  *  Input filters jQuery plug-in
  *
  */

(function($) {
  $.fn.numeric = function(options) {
    settings = jQuery.extend({
      allowDecimal: true,
      allowNegative: false,
      decimalSeparator: ",",
      maxDecimals: -1
    }, options);

    $(this).keypress(function(e) {
      var key = (e.which) ? e.which : e.keyCode;
      var text = $(this).val();
      var caretPos = getCaretPos($(this)[0]);

      // Allow system keys
      if ((e.which == 0) || (e.which == 8)) {
        return true;
      }

      // Allow digits
      if ((e.which >= 48) && (e.which <= 57)) {
        if ((settings.allowDecimal) && (settings.maxDecimals > -1)) {
          var decimalSeparatorPos = text.indexOf(settings.decimalSeparator);

          if ((decimalSeparatorPos > -1) && (caretPos > decimalSeparatorPos) && (text.substr(decimalSeparatorPos + 1).length >= settings.maxDecimals)) {
            return false;
          }
        }

        return true;
      }

      // Allow negative
      if ((settings.allowNegative) && (e.which == 45) && (caretPos == 0) && (text.indexOf("-") == -1)) {
        return true;
      }


      // Allow decimal
      if ((settings.allowDecimal) && (e.which == getSeparatorCode(settings.decimalSeparator)) && (caretPos > 0) && (text.indexOf(settings.decimalSeparator) == -1) && (text.substr(caretPos).length <= settings.maxDecimals)) {
        return true;
      }

      return false;
    });

    $(this).blur(function() {
      var text = $(this).val();
      var pos = text.length - 1

      // Remove the decimal separator if it ends the string
      $(this).filter(function() {
        return text.charAt(pos) == settings.decimalSeparator;
      }).val(text.substr(0, pos));

    });
  };
})(jQuery);

function getCaretPos(element) {
  var pos = -1;

  if (document.selection) {
    element.focus();
    var oSel = document.selection.createRange();
    oSel.moveStart('character', -element.value.length);
    pos = oSel.text.length;
  }
  else if (element.selectionStart || element.selectionStart == "0") {
    pos = element.selectionStart;
  }

  return pos;
}

function getSeparatorCode(character) {
  switch (character) {
    case ".":
      return 46;
    case ",":
      return 44;
    default:
      return -1;
  }
}

var _isSearchEngineMainWide = false;
function expandCollapseSearchEngineNoAmin() {

  // elemento(i) da nascondere
  var hideElements = $('.searchEngineVisibilityToggle:visible');

  // elemento(i) da visualizzare
  var showElements = $('.searchEngineVisibilityToggle:hidden');

  // tabella main di cui va adattatala dimensione
  var main = $('#main');

  // var di utilità
  var mainAnimated = false;

  // nascondo gli elementi da nascondere e contemporaneamente (vedi sotto) ridimensiono il main
  hideElements.hide();

  if (_isSearchEngineMainWide && !mainAnimated) {
    mainAnimated = true;
    _isSearchEngineMainWide = !_isSearchEngineMainWide;
    main.css("width", 670);
  }
  showElements.show();

  if (!_isSearchEngineMainWide && !mainAnimated) {
    mainAnimated = true;
    _isSearchEngineMainWide = !_isSearchEngineMainWide;
    main.css("width", 845 );
  } 
}

function expandCollapseSearchEngine() {

  // elemento(i) da nascondere
  var hideElements = $('.searchEngineVisibilityToggle:visible');

  // elemento(i) da visualizzare
  var showElements = $('.searchEngineVisibilityToggle:hidden');
  
  // tabella main di cui va adattatala dimensione
  var main = $('#main');
  
  // var di utilità
  var mainAnimated = false;

  // nascondo gli elementi da nascondere e contemporaneamente (vedi sotto) ridimensiono il main
  hideElements.animate({ width: 'hide' }, "slow", "swing", function() {
    if (_isSearchEngineMainWide && !mainAnimated) {
      mainAnimated = true;
      _isSearchEngineMainWide = !_isSearchEngineMainWide;
      main.animate({ width: 670 }, "slow", "swing", function() {
    });
    }
    showElements.animate({ width: 'show' }, "slow", "swing", function() {
    });
  });

  if (!_isSearchEngineMainWide && !mainAnimated) {
    mainAnimated = true;
    _isSearchEngineMainWide = !_isSearchEngineMainWide;
    main.animate({ width: 845 }, "slow", "swing", function() { //939
    });
  }
}




function fillBox(id, defaultText) {
    if (document.getElementById(id).value == "") {
        document.getElementById(id).value = defaultText;
        document.getElementById(id).className = "";
    }
    else if (document.getElementById(id).value == defaultText) {
        document.getElementById(id).value = "";
        document.getElementById(id).className = "on";
    }

}

/*open/close column menu*/
function opClMenu() {
    $(this).next().toggle('fast');
    if (this.className == 'tlClose') { this.className = 'tlOpen'; }
    else { this.className = 'tlClose'; }
}

$(document).ready(function() {
  $('.tlClose').next().css('display', 'none').end().click(opClMenu);
  $('.tlOpen').next().css('display', 'block').end().click(opClMenu);
});

var toPrintHead = null;
var toPrintBody = null;

function printPage() {
    
    var htmlStartTag = function() {
        var attrs = $('html')[0].attributes;
        var result = '<html';
        $.each(attrs, function() {
            result += ' ' + this.name + '="' + this.value + '"';
        });
        result += '>';
        
        return result;
    }

    toPrintHead = $('head').html() + '<link rel="stylesheet" href="./css/print.css" type="text/css" media="all" />';

    toPrintBody = $('body').html().replace('//<plh_remove_alert_start>', '/*').replace('//<plh_remove_alert_end>', '*/')+ '<script type="text/javascript" src="./js/print.js"></script>';
  
  var printWindow = window.open($('base').attr('href') + 'printPopUp.html', '', 'width=1010,height=450,scrollbars=yes', true);
}

function printPage_MM() {

    var htmlStartTag = function() {
        var attrs = $('html')[0].attributes;
        var result = '<html';
        $.each(attrs, function() {
            result += ' ' + this.name + '="' + this.value + '"';
        });
        result += '>';

        return result;
    }

    toPrintHead = $('head').html() + '<link rel="stylesheet" href="css/print_MM.css" type="text/css" media="all" />';

    toPrintBody = $('body').html().replace('//<plh_remove_alert_start>', '/*').replace('//<plh_remove_alert_end>', '*/') + '<script type="text/javascript" src="../js/print.js"></script>';

    var printWindow = window.open( 'printPopUp_MM.html', '', 'width=850,height=450,scrollbars=yes', true);
}

function printPage_CH() {

    var htmlStartTag = function() {
        var attrs = $('html')[0].attributes;
        var result = '<html';
        $.each(attrs, function() {
            result += ' ' + this.name + '="' + this.value + '"';
        });
        result += '>';

        return result;
    }

    toPrintHead = $('head').html() + '<link rel="stylesheet" href="css/print_CH.css" type="text/css" media="all" />';

    toPrintBody = $('body').html().replace('//<plh_remove_alert_start>', '/*').replace('//<plh_remove_alert_end>', '*/') + '<script type="text/javascript" src="../js/print.js"></script>';

    var printWindow = window.open('printPopUp_CH.html', '', 'width=850,height=450,scrollbars=yes', true);
}


function refreshPageByLocationHref() {
  location.href = location.href;
}

function getCalendarDate() {
  var months = new Array(13);
  months[0] = "Gennaio";
  months[1] = "Febbraio";
  months[2] = "Marzo";
  months[3] = "Aprile";
  months[4] = "Maggio";
  months[5] = "Giugno";
  months[6] = "Luglio";
  months[7] = "Agosto";
  months[8] = "Settembre";
  months[9] = "Ottobre";
  months[10] = "Novembre";
  months[11] = "Dicembre";
  var now = new Date();
  var monthnumber = now.getMonth();
  var monthname = months[monthnumber];
  var monthday = now.getDate();
  var year = now.getYear();
  if (year < 2000) { year = year + 1900; }
  var dateString = monthday +
                    ' ' +
                    monthname +
                    ' ' +
                    year;
  return dateString;
}

function checkEmail(inputvalue) {
  var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
  if (pattern.test(inputvalue)) {
    return true;
  } else {
    return false;
  }
}

function showPageLink(divToolsId) {
    var $relativeTo = $('#' + divToolsId);
    var $linkPlh;
    var linkInput;

    if ($('.linkplh').length > 0) {
        $linkPlh = $($('.linkplh')[0]);
        if ($linkPlh.is(':visible')) {
            $linkPlh.hide();
        }
        else {
            $linkPlh.show();
        }

        $linkPlh.css('left', $relativeTo.position().left + $relativeTo.width() - $linkPlh.width());
        $linkPlh.css('top', $relativeTo.position().top + 5);
        linkInput = $linkPlh.find('input')[0];
        linkInput.select();
        return;
    }

    $linkPlh = $('<div class="linkplh"><div><a class="toolBoxClsBtn" onclick="showPageLink(\'divTools\')" href="javascript:void(0)">x</a><label for="nwsLnk">Incolla il link in e-mail, chat, nel tuo sito o blog</label><input id="nwsLnk" type="text"/></div></div>');
    $('body').append($linkPlh);

    linkInput = $linkPlh.find('input')[0];
    var $linkInput = $(linkInput);
    $linkInput.val(window.location.href);
    $linkPlh.css('left', $relativeTo.position().left + $relativeTo.width() - $linkPlh.width());
    $linkPlh.css('top', $relativeTo.position().top + 5);

    $linkInput.click(function() { $('.linkplh').find('input')[0].select() });

    // quando fa la select(), IE scrolla fino a fondo pagina...quindi facciamo un piccolo workaround
    var oldScrollTop = $(document).scrollTop();
    linkInput.select();
    $(document).scrollTop(oldScrollTop);

    $linkPlh.show();
}

function insertWucImageLink($originalLinkJQueryElement, $wucImgElement) {
    $itemTmp1 = $('<a />');
    $itemTmp1.attr('href', $originalLinkJQueryElement.first().attr('href'));
    $itemTmp1.click(function() { $originalLinkJQueryElement.first().click() });
    $itemTmp2 = $wucImgElement;
    $itemTmp2.parent().append($itemTmp1);
    $itemTmp2.parent().remove($itemTmp2);
    $itemTmp1.append($itemTmp2);
  }
/*
  function hideUserMessage() {
    $('#divUserMessage').slideUp();
  }
  */
