// QUESTA FUNZIONE SERVE PER NON FARE RICARICARE LE IMMAGINI IN CACHE A IE6
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}
//

function isValidWebPage(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected == 'it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}

	new Ajax.Request('/ajax/isValidWebPage.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected
									}
								}
					);

	refreshDialog(myDialog);
	return false;
}

function isValidDomain(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected == 'it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}

	new Ajax.Request('/ajax/isValidDomain.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected
									}
								}
					);

	refreshDialog(myDialog);
	return false;
}
function isValidHost(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected == 'it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}

	new Ajax.Request('/ajax/isValidHost.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected
									}
								}
					);

	refreshDialog(myDialog);
	return false;
}

function isValidHostName(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected == 'it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}

	new Ajax.Request('/ajax/isValidHostName.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected
									}
								}
					);

	refreshDialog(myDialog);
	return false;
}
function isValidIp(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);
	if(args[3]=='dnsbl')
		allowDnsBl = 'true';
	else
		allowDnsBl = 'false';

	if(myObj.value==''){
		if(gLangSelected=='it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}
	new Ajax.Request('/ajax/isValidIp.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected,
										dnsbl: allowDnsBl
									}
								}
					);
	refreshDialog(myDialog);
	return false;
}
function isValidInteger(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected=='it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}
	new Ajax.Request('/ajax/isValidInteger.php',
								{
									method: 'post',
									parameters: {
										formId: myForm.id,
										objId: myObj.id,
										objValue: myObj.getValue(),
										dialogId: myDialog.id,
										lang: gLangSelected
									}
								}
					);
	refreshDialog(myDialog);
	return false;
}
function isNotEmpty(){
	args = $A(arguments)
	myForm = args[0];
	myObj = $(args[1]);
	myDialog = $(args[2]);

	if(myObj.value==''){
		if(gLangSelected=='it'){
			alert('Introdurre un valore');
		}else if(gLangSelected == 'es'){
			alert('Por favor, introduzca un valor ');
		}else{
			alert('Please enter a value');
		}
		myObj.focus()
		return false;
	}else{
		return true;
	}
}

function refreshDialog(dialog){

	dialog.removeClassName('Ko');
	dialog.removeClassName('Ok');

	dialogHtml = '<img src="/image/loading_orange.gif" border="0" />';

	if(gLangSelected == 'it'){
		dialogHtml += 'Sto verificando l\'input';
	}else if(gLangSelected == 'es'){
		dialogHtml += 'Estoy verificando...';
	}else{
		dialogHtml += 'Checking your input';
	}

	dialog.update(dialogHtml);
	dialog.show();
}

Element.collectTextNodes = function(element) {
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue :
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue :
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

AjaxSelect = Class.create({
  initialize: function(element,accept) {

  	options = {minChars:0}
  	update = 'inputAutocompleter';
  	url = '/ajax/getSelectable.php';

    this.baseInitialize(element, update, options);

    this.options.array = new Array();
    this.options.defaultParams = this.options.parameters || null;
    this.accept                = accept;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
  	if(this.options.array.length==0){
	    this.startIndicator();
	    var entry = encodeURIComponent(this.options.paramName) + '=' +
	      encodeURIComponent(this.getToken());

	    this.options.parameters = this.options.callback ?
	      this.options.callback(this.element, entry) : entry;

	    if(this.options.defaultParams)
	      this.options.parameters += '&' + this.options.defaultParams;

	    new Ajax.Request(this.url,
								{
									onComplete: this.onComplete.bind(this),
									method: 'post',
									parameters: {
										accepts: this.accept
									}
								}
		);
  	}else{
    	this.updateChoices(this.options.selector(this));
  	}
  },

  onComplete: function(request) {
  	if(request.responseText!=''){
	  	this.options.array = request.responseText.split('|')
	    this.updateChoices(this.options.selector(this));
  	}
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 0,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0; i < instance.options.array.length &&
          ret.length < instance.options.choices ; i++) {

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ?
            elem.toLowerCase().indexOf(entry.toLowerCase()) :
            elem.indexOf(entry);

          while (foundPos != -1) {
            if (foundPos == 0 && elem.length != entry.length) {
              ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
                elem.substr(entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars &&
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
                  elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
                  foundPos + entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ?
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
              elem.indexOf(entry, foundPos + 1);

          }
        }


        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))

        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  },

  baseInitialize: function(element, update, options) {
    element          = $(element)
    this.element     = element;
    this.update      = $(update);
    this.hasFocus    = false;
    this.changed     = false;
    this.active      = false;
    this.index       = 0;
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 0;
    this.options.onShow       = this.options.onShow ||
      function(element, update){
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false,
            setWidth: false,
            offsetTop: element.offsetHeight
          });
        }
        //Effect.Appear(update,{duration:0.15});
        Element.setOpacity(update, 1)
        Element.show(update)
      };
    this.options.onHide = this.options.onHide ||
      function(element, update){
      		Element.setOpacity(update, 0)
        	Element.hide(update)
      };
      //function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string')
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;

    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
    Event.observe(this.element, 'click', this.onClickMain.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix &&
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },

  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  onClickMain: function(event) {
    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex)
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },

  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },

  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
  },

  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ?
          Element.addClassName(this.getEntry(i),"selected") :
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) {
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },

  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },

  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },

  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },

  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },

  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount =
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;

      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {
    if (null != this.tokenBounds) return this.tokenBounds;
    var value = this.element.value;
    if (value.strip().empty()) return [-1, 0];
    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
    var offset = (diff == this.oldElementValue.length ? 1 : 0);
    var prevTokenPos = -1, nextTokenPos = value.length;
    var tp;
    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }
    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

AjaxSelect.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};
/*
AutoHostName = Class.create(Autocompleter.Cox, {
  initialize: function(element, update) {
  	options = {minChars:0}
  	update = 'inputAutocompleter';
    this.baseInitialize(element, update, options);
    this.options.array = HostNames;
  },

  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 0,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0; i < instance.options.array.length &&
          ret.length < instance.options.choices ; i++) {

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ?
            elem.toLowerCase().indexOf(entry.toLowerCase()) :
            elem.indexOf(entry);

          while (foundPos != -1) {
            if (foundPos == 0 && elem.length != entry.length) {
              ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
                elem.substr(entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars &&
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
                  elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
                  foundPos + entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ?
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
              elem.indexOf(entry, foundPos + 1);

          }
        }


        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))

        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  }
});
*/
var Contextual = { }
Contextual = Class.create({
  initialize: function(element, menu) {
    this.element     = element;
    this.menu        = $(menu);
    this.hasFocus    = false;
    this.active      = false;
    this.index       = 0;
    this.spanCnt	 = element.innerHTML;

    this.options = { };
    this.options.frequency    = this.options.frequency || 0.2;
    this.options.onShow       =
      function(element, menu){
      	if(menu.style && element.style){
	        if(!menu.style.position || menu.style.position=='absolute') {
	          menu.style.position = 'absolute';
	          Position.clone(element, menu, {
	            setWidth: false,
	            setHeight: false,
	            offsetTop: element.offsetHeight
	          });
	        }
	        //Effect.Appear(update,{duration:0.15});
	        Element.setOpacity(menu, 1)
	        Element.show(menu)
      	}
      };
    this.options.onHide = this.options.onHide ||
      function(element, menu){
      		Element.setOpacity(menu, 0)
        	Element.hide(menu)
      };

    this.observer = null;

    Element.hide(this.menu);

	document.observe('mouseover', this.onDocumentClick.bindAsEventListener(this));

    Event.observe(this.element, 'mouseover', this.onElementClick.bindAsEventListener(this));
  },

  show: function() {
    this.active = true;
    Element.addClassName(this.element, 'Closer');
    if(Element.getStyle(this.menu, 'display')=='none') this.options.onShow(this.element, this.menu);
    if(!this.iefix &&
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.menu, 'position')=='absolute')) {
      new Insertion.After(this.menu,
       '<iframe id="' + this.menu.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.menu.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);

  },

  fixIEOverlapping: function() {
    Position.clone(this.menu, this.iefix, {setTop:(!this.menu.style.height)});
    this.iefix.style.zIndex = 100;
    this.menu.style.zIndex = 200;
	//alert('bidone')
    Element.show(this.iefix);
  },

  hide: function() {

    Element.removeClassName(this.element, 'Closer');

    this.active = false;
    if(Element.getStyle(this.menu, 'display')!='none') this.options.onHide(this.element, this.menu);
    if(this.iefix) Element.hide(this.iefix);
  },

  onElementClick: function(event) {

    this.hasFocus = true;
    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*2000);
    this.makeThemClickable()
    event.stop()
  },

  onDocumentClick: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
  },

  onObserverEvent: function() {

    if(!this.active) {
      this.show();
    } else {
      this.hide();
    }
  },

  makeThemClickable: function() {
      Element.cleanWhitespace(this.menu);
      Element.cleanWhitespace(this.menu.down());


      if(this.menu.firstChild && this.menu.down().childNodes) {
        entryCount = this.menu.down().childNodes.length;
        for (var i = 0; i < entryCount; i++) {
          var entry = this.menu.down().childNodes.item(i);
          //alert(entry.tagName)
          Event.observe(entry, "mouseover", this.onItemHover.bindAsEventListener(this));
          Event.observe(entry, "mouseout", this.onItemOut.bindAsEventListener(this));
		  Event.observe(entry, "click", this.onItemClick.bindAsEventListener(this));
        }
      }
  },

  onItemHover: function(event) {
    var element = Event.findElement(event, 'LI');
    element.className = 'selected';
    Event.stop(event);
  },
  onItemOut: function(event) {
    var element = Event.findElement(event, 'LI');
    element.className = '';
    Event.stop(event);
  },

  onItemClick: function(event) {
    var element = Event.findElement(event, 'LI');
    //alert(this.spanCnt)
    if(element.id!='CpyToClip'){
	    strLocation  = '/ajax/contextMenuHandler.php?action='+element.id;
	    strLocation += '&content='+this.spanCnt;
	    strLocation += '&lang='+gLangSelected;
	    strLocation += '&usrIndex='+gUsrIndex;
	    document.location = strLocation;
    }else{
    	copyToClipboard(this.spanCnt);
    }
    this.hide();
    Event.stop(event);
  }
});

var GoogleMap = { }
GoogleMap  = Class.create({
  initialize: function(element, latitude, longitude, zoom) {

    this.element      = $(element);
    this.latitude     = latitude;
    this.longitude    = longitude;
    this.zoom         = zoom;
    this.libraryName  = "http://maps.google.com/maps?file=api&v=2&key=" + gGoogleApiKey

	this.alreadyCalled = false;
	this.loadGMapScript();

  },
  loadGMapScript: function(){

    if(!this.alreadyCalled && typeof this.alreadyCalled!='undefined'){
        var script = new Element("script", {  type: "text/javascript", src: this.libraryName });
	    $$("head")[0].insert(script);
	    this.alreadyCalled = true;
    }
	this.loadMap();

  },

  loadMap: function(){
    if (typeof GMap2=='undefined')
        setTimeout(this.loadGMapScript.bind(this), 100)
    else{

	    map = new GMap2(this.element);

	    map.addControl(new GOverviewMapControl ());
	    map.addControl(new GMapTypeControl());
	    map.addControl(new GLargeMapControl());
	    map.addControl(new GScaleControl());

		var icon = new GIcon();
		icon.image = "/image/google_map_here.gif";
		icon.shadow = "/image/google_map_icon.png";
		icon.iconSize = new GSize(37, 34);
		icon.shadowSize = new GSize(37, 34);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(20, 0);

		point = new GLatLng(this.latitude, this.longitude);
		map.setCenter(point, this.zoom);

		var marker = new GMarker(point, icon);
        map.addOverlay(marker);

    }
  }
});

var GooglePolyMap = { }
GooglePolyMap  = Class.create({
  initialize: function(element, polypoints) {

    this.element      = $(element);
    this.libraryName  = "http://maps.google.com/maps?file=api&v=2.x&key=" + gGoogleApiKey

    this.polypoints   = polypoints;

	this.alreadyCalled = false;
	this.loadGMapScript();

  },
  loadGMapScript: function(){

    if(!this.alreadyCalled && typeof this.alreadyCalled!='undefined'){
        var script = new Element("script", {  type: "text/javascript", src: this.libraryName });
	    $$("head")[0].insert(script);
	    this.alreadyCalled = true;
    }
	this.loadMap();

  },

  loadMap: function(){
    if (typeof GMap2=='undefined')
        setTimeout(this.loadGMapScript.bind(this), 100)
    else{

	    map = new GMap2(this.element);

	    map.addControl(new GOverviewMapControl ());
	    map.addControl(new GMapTypeControl());
	    map.addControl(new GLargeMapControl());
	    map.addControl(new GScaleControl());
	    map.setCenter(new GLatLng(37.4419, -122.1419), 13);


        baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);

        mypolypoints = new Array();
        bounds = new GLatLngBounds();
        for(i=0;i<this.polypoints.length;i++){
        	var letteredIcon = new GIcon(baseIcon);
            idx = this.polypoints[i][0];
            letteredIcon.image = "/image/google_marker_"+idx+".png";
            var mypolypoint = new GLatLng(parseFloat(this.polypoints[i][1]), parseFloat(this.polypoints[i][2]));
        	markerOptions = { icon:letteredIcon };
            var marker = new GMarker(mypolypoint,markerOptions);
            map.addOverlay(marker);
            mypolypoints.push(mypolypoint)
            bounds.extend(mypolypoint);
        }

        polyline = new GPolyline(mypolypoints,"#FF0000", 5);
	    map.addOverlay(polyline);
	    map.setZoom(map.getBoundsZoomLevel(bounds));
      	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
      	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
      	map.setCenter(new GLatLng(clat,clng));

    }
  }
});
function resizeMap( map, points ) {
  var minLong = 999;
  var minLat = 999;
  var maxLong = -999;
  var maxLat = -999;

  // Get the current map width/height
  var size = map.getSpanLatLng();
  var mapWidth = size.width;
  var mapHeight = size.height;
  var baseWidth = mapWidth;
  var baseHeight = mapHeight;

  // Figure out the elemental unit (depends on the size of the map)
  // You will need to re-run resizeMap() if the size of the map changes.
  if ( map.getZoomLevel() > 0 ) {
    baseWidth /= Math.pow( 2, map.getZoomLevel() );
    baseHeight /= Math.pow( 2, map.getZoomLevel() );
  }

  // Find the max/min points
  for ( var i = 0; i < points.length; i++ ) {
    if ( points[i].x < minLong ) minLong = points[i].x;
    if ( points[i].x > maxLong ) maxLong = points[i].x;
    if ( points[i].y < minLat ) minLat = points[i].y;
    if ( points[i].y > maxLat ) maxLat = points[i].y;
  }

  // Find the optimal Width Zoom
  var wZoom = 0;
  var w = Math.abs( maxLong - minLong );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseWidth > w ) break;
    baseWidth *= 2;
    wZoom = i;
  }

  // Find the optimal Height Zoom
  var hZoom = 0;
  var h = Math.abs( maxLat - minLat );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseHeight > h ) break;
    baseHeight *= 2;
    hZoom = i;
  }

  // Reposition
  map.centerAndZoom(
    new GPoint( ( minLong + maxLong ) / 2, ( minLat + maxLat ) / 2 ),
    ( wZoom > hZoom ? wZoom : hZoom )
  );
}


var Tooltip = Class.create();
Tooltip.prototype = {
  initialize: function(element, tool_tip) {
    var options = Object.extend({
	  delta_x: 10,
	  delta_y: 10,
      zindex: 1000
    }, arguments[1] || {});

    this.element      = $(element);
    this.tool_tip     = $(tool_tip);

    this.options      = options;

  	this.hiddenSelects = new Array();

    // hide the tool-tip by default
    this.tool_tip.hide();

    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);

    this.registerEvents();
  },

  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
  },

  registerEvents: function() {
    Event.observe(this.element, "mouseover", this.eventMouseOver);
    Event.observe(this.element, "mouseout", this.eventMouseOut);
  },

  showTooltip: function(event){
	Event.stop(event);
	Position.clone(this.tool_tip, this.element, {
            setHeight: false,
            setWidth: false,
            offsetLeft: this.options.delta_x,
            offsetTop: this.options.delta_y
          });

	// now set the right styles
	this.setStyles();

	// finally show the Tooltip
	//new Effect.Appear(this.tool_tip);
	new Element.show(this.tool_tip);
	this.hideSelects();
  },

  hideSelects: function(){
  	this.hiddenSelects = new Array();
  	selectArray = $$('select');
  	for(i=0;i<selectArray.length;i++){
	  	selectObj = selectArray[i];
	  	if( this.intersect(this.tool_tip, selectObj ) ){
	  		this.hiddenSelects[this.hiddenSelects.length] = selectObj;
	  		selectObj.hide();
	  	}
  	}
  },

  showSelects: function(){
  	for(i=0;i<this.hiddenSelects.length;i++){
  		this.hiddenSelects[i].show();
  	}
  	this.hiddenSelects = new Array();
  },

  intersect: function(r1, r2){
	posR1 = r1.viewportOffset();
	posR2 = r2.viewportOffset();

  	r1Left    = posR1[0];
    r1Right   = r1Left + r1.getWidth();
    r1Top     = posR1[1];
    r1Bottom  = r1Top + r1.getHeight();
    r2Left    = posR2[0];
    r2Right   = r2Left + r2.getWidth();
    r2Top     = posR2[1];
    r2Bottom  = r2Top + r2.getHeight();
    if (
	       (
	          /* seeing if it overlaps horizontally */
	          (r1Left >= r2Left && r1Left <= r2Right)
	             ||
	          (r1Right <= r2Right && r1Right >= r2Left)
	             ||
	          (r1Left <= r2Left && r1Right >= r2Right)
	       )
	          &&
	       (
	          /* seeing if it overlaps vertically */
	          (r1Top >= r2Top && r1Top <= r2Bottom)
	             ||
	          (r1Bottom <= r2Bottom && r1Bottom >= r2Top)
	             ||
	          (r1Top <= r2Top && r1Bottom >= r2Bottom)
	       )
    ){
    	//alert('true '+r1Left+" "+r1Right+" "+r2Left+" "+r2Right)
		return true;
    }else{
    	//alert('false '+r1Left+" "+r1Right+" "+r2Left+" "+r2Right)
    	return false;
    }

  },
  setStyles: function(){
    // set the right styles to position the tool tip
	Element.setStyle(this.tool_tip, { position:'absolute',
									  zindex:this.options.zindex
	 								});
  },

  hideTooltip: function(event){
	//new Effect.Fade(this.tool_tip);
	new Element.hide(this.tool_tip);
	this.showSelects();
  },

  getWindowHeight: function(){
    var innerHeight;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerHeight = document.body.clientHeight;
    } else {
		innerHeight = window.innerHeight;
    }
    return innerHeight;
  },

  getWindowWidth: function(){
    var innerWidth;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerWidth = document.body.clientWidth;
    } else {
		innerWidth = window.innerWidth;
    }
    return innerWidth;
  }
}

function initUmanBox(content){
    box = document.createElement('div');
    box.id = 'umanbox';
    // this is very important since IE6 was triggering an error!
    try{
        box.update('<img id="umanclose" src="/image/umanclose.gif" onclick="hideUmanBox()" alt="Close" title="Close this window" />'+content);
    } catch(e) {
    	box.innerHTML = '<img id="umanclose" src="/image/umanclose.gif" onclick="hideUmanBox()" alt="Close" title="Close this window" />'+content;
    }
    document.body.insertBefore(box, document.body.childNodes[0]);

    overlay = document.createElement('div');
    overlay.id = 'umanoverlay';
    document.body.insertBefore(overlay, document.body.childNodes[0]);
}

function showUmanBox(){
    $('umanoverlay').show();
    umanCenter('umanbox');
    return false;
}

function hideUmanBox(){
    $('umanbox').hide();
    $('umanoverlay').hide();
    return false;
}

function umanCenter(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement &&
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body &&
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 106;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2 - 100;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY -100;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";

    element.style.display  = 'block';
}
function copyToClipboard(text){
	if(window.clipboardData){
		window.clipboardData.setData('text',text);
	}else{
		var clipboarddiv=document.getElementById('divclipboardswf');
		if(clipboarddiv==null){
			clipboarddiv=document.createElement('div');
			clipboarddiv.setAttribute("name", "divclipboardswf");
			clipboarddiv.setAttribute("id", "divclipboardswf");
			document.body.appendChild(clipboarddiv);
		}
		clipboarddiv.innerHTML='<embed src="/swf/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    }
    return false;
}

function showDomCheckLegend(aHrefObj){
    Element.setStyle($('domainCheckLegend'), {  position:'absolute' });
    Position.clone(aHrefObj, $('domainCheckLegend'), {
            setHeight: false,
            setWidth: false,
            offsetLeft: 25,
            offsetTop: 25
          });
    new Element.show($('domainCheckLegend'));

}
function hideDomCheckLegend(){
    $('domainCheckLegend').hide();

}