/**/
// JavaScript Document
//
// v.11
//
//	added zeropad function zeroPad(x)
//

//**********************************************************************
//http://www.phpied.com/javascript-include/     (include js and css)
//**********************************************************************


var included_files = new Array();
function include_once(script_filename) {
  if (!in_array(script_filename, included_files)) {
    included_files[included_files.length] = script_filename;
    include_dom(script_filename);
  }
}
function include_dom(script_filename) {
  var html_doc = document.getElementsByTagName('head').item(0);
  t=script_filename.substring(script_filename.lastIndexOf('.')+1);
  if (t=='js'){
    var file = document.createElement('script');
    file.setAttribute('language','javascript');
    file.setAttribute('type','text/javascript');
    file.setAttribute('src',script_filename);
  }else if (t=='css'){
    var file = document.createElement('link');
    file.setAttribute('rel','stylesheet');
    file.setAttribute('type','text/css');
    file.setAttribute('href',script_filename);
  }
  html_doc.appendChild(file);
  return false;
}
function in_array(needle, haystack) {
  for (var i = 0; i < haystack.length; i++) {
    if (haystack[i] == needle) {
      return true;
    }
  }
  return false;
}
//**********************************************************************



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



if (top != self){ 
	if (!(top.location.href.indexOf("admin")>0)){
	top.location.href = location.href;
	}
}


function getNextHighestZindex(obj){  
	var allElems = document.getElementsByTagName?document.getElementsByTagName("*"):document.all; // or test for that too
	var maxZIndex = 0;
	for(var i=0;i<allElems.length;i++) {
		var elem = allElems[i];
		var cStyle = null;
		if (elem.currentStyle) {
			cStyle = elem.currentStyle;
		}else if (document.defaultView && document.defaultView.getComputedStyle) {
			cStyle = document.defaultView.getComputedStyle(elem,"");
		}
		var sNum;
		if (cStyle) {
			sNum = Number(cStyle.zIndex);
		} else {
			sNum = Number(elem.style.zIndex);
		}
		if (!isNaN(sNum)) {
			maxZIndex = Math.max(maxZIndex,sNum);
		}
	}
	return maxZIndex;
}  

/////////////////////////////////////SCRIPTACULOUS PATCH/////////////////////////////////////////////
  Sortable.create = function(element) {
    element = $(element);
    var options = Object.extend({
      element:     element,
      tag:         'li',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'ul',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      delay:       0,
      hoverclass:  null,
      ghosting:    false,
      quiet:       false,
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      this.SERIALIZE_RULE,
/*+*/ revert:      false,
      // these take arrays of elements or ids and can be
      // used for better initialization performance
      elements:    false,
      handles:     false,

      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || { });

    // clear any old sortable with same element
    this.destroy(element);

    // build options for the draggables
    var options_for_draggable = {
      revert:      true,
      quiet:       options.quiet,
      scroll:      options.scroll,
      scrollSpeed: options.scrollSpeed,
      scrollSensitivity: options.scrollSensitivity,
      delay:       options.delay,
      ghosting:    options.ghosting,
      constraint:  options.constraint,
      handle:      options.handle };

    if(options.starteffect)
      options_for_draggable.starteffect = options.starteffect;

    if(options.reverteffect)
      options_for_draggable.reverteffect = options.reverteffect;
    else
      if(options.ghosting) options_for_draggable.reverteffect = function(element) {
        element.style.top  = 0;
        element.style.left = 0;
      };

    if(options.endeffect)
      options_for_draggable.endeffect = options.endeffect;

    if(options.zindex)
      options_for_draggable.zindex = options.zindex;

    // build options for the droppables
    var options_for_droppable = {
      overlap:     options.overlap,
      containment: options.containment,
      tree:        options.tree,
      hoverclass:  options.hoverclass,
      onHover:     Sortable.onHover
    };

    var options_for_tree = {
      onHover:      Sortable.onEmptyHover,
      overlap:      options.overlap,
      containment:  options.containment,
      hoverclass:   options.hoverclass
    };

    // fix for gecko engine
    Element.cleanWhitespace(element);

    options.draggables = [];
    options.droppables = [];

    // drop on empty handling
    if(options.dropOnEmpty || options.tree) {
      Droppables.add(element, options_for_tree);
      options.droppables.push(element);
    }

    (options.elements || this.findElements(element, options) || []).each( function(e,i) {
      var handle = options.handles ? $(options.handles[i]) :
        (options.handle ? $(e).select('.' + options.handle)[0] : e);
      options.draggables.push(
        new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
      Droppables.add(e, options_for_droppable);
      if(options.tree) e.treeNode = element;
      options.droppables.push(e);
    });

    if(options.tree) {
      (Sortable.findTreeElements(element, options) || []).each( function(e) {
        Droppables.add(e, options_for_tree);
        e.treeNode = element;
        options.droppables.push(e);
      });
    }

    // keep reference
    this.sortables[element.identify()] = options;

    // for onupdate
    Draggables.addObserver(new SortableObserver(element, options.onUpdate));

  };

Sortable.onHover= function(element, dropon, overlap) {
    if(Element.isParent(dropon, element)) return;
	
	
/*+*/	var oldParentNode = element.parentNode;
/*+*/	var oldOptions = Sortable.options(oldParentNode);
/*+*/	
/*+*/	var revert = oldOptions.revert;
/*+*/	if (revert && typeof revert == 'function') revert = revert(element, oldParentNode, dropon.parentNode);
/*+*/	if (revert) return;

    if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
      return;
    } else if(overlap>0.5) {
      Sortable.mark(dropon, 'before');
      if(dropon.previousSibling != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, dropon);
        if(dropon.parentNode!=oldParentNode)
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    } else {
      Sortable.mark(dropon, 'after');
      var nextElement = dropon.nextSibling || null;
      if(nextElement != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, nextElement);
        if(dropon.parentNode!=oldParentNode)
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    }
  },

Sortable.onEmptyHover= function(element, dropon, overlap) {
    var oldParentNode = element.parentNode;
    var droponOptions = Sortable.options(dropon);
	
/*+*/	var revert = Sortable.options(oldParentNode).revert;
/*+*/	if (revert && typeof revert == 'function') revert = revert(element, oldParentNode, dropon);
/*+*/    if (revert) return;

    if(!Element.isParent(dropon, element)) {
      var index;

      var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
      var child = null;

      if(children) {
        var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);

        for (index = 0; index < children.length; index += 1) {
          if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
            offset -= Element.offsetSize (children[index], droponOptions.overlap);
          } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
            child = index + 1 < children.length ? children[index + 1] : null;
            break;
          } else {
            child = children[index];
            break;
          }
        }
      }

      dropon.insertBefore(element, child);

      Sortable.options(oldParentNode).onChange(element);
      droponOptions.onChange(element);
    }
  },

/////////////////////////////////////UI COMPONENTS///////////////////////////////////////////////////


/*
//////////////////DROP DOWN MENU


Usage : var DropDownMenu = new dropDownMenu('frm_newItem_Image_Change')


HTML:

			<div class="dDM" id="frm_newItem_Image_Change" style="width:170px;margin:170px">
				<div class="dDM_Caption">change/apply image...</div>
				<ul class="dDM_Values">
					<li><a href="http://www.apple.com" title="choose and image from the web">choose an image from the web</a></li>
					<li><a href="#">choose an image with Yahoo!</a></li>
					<li><a href="#">upload one from your computer</a></li>
				</ul>
			</div>

*/
document._ddms = [];

var dropDownMenu = Class.create();

dropDownMenu.prototype = {
/*					container : null,
	menu : null,
	caption : null,
	choises : null,
	closetimer : 0,*/
	initialize: function(id){
		_dropDownMenu = this;
		//console.log('initialize');
		/*document._ddms.push(this);
		document._ddmsClose = function(){
			if(document._ddms.length>0){
				document._ddms.each(function(dd){
					dd.mclosetime().bind(this);
				});
			}
		}*/
		//document.observe('click', document._ddmsClose,true);
		this.container = $(id);
		this.container.dDM = this;	
		this.menu = this.container.getElementsBySelector('ul.dDM_Values')[0];
		
		this.choices = this.container.getElementsBySelector('ul.dDM_Values > li');
		
		this.caption = this.container.getElementsBySelector('.dDM_Caption')[0];
		this.caption.innerHTML = this.caption.innerHTML + '<span class="dDM_Icon"></span>';

		this.menu.setAttribute('width',this.container.width);
		this.choices.each(function(e){
			e.observe('mouseover',this.mcancelclosetime);
			e.observe('mouseout',this.mclosetime);
			e.observe('click',this.mclose.bind(this));
			e.observe('mouseover',function(){
				try{
					this.down('ul').style.zIndex = getNextHighestZindex();
					this.down('ul').style.left = $(this.parentNode).getWidth()-3 + "px";
				}catch(e){}
			})
		}.bind(this));
		
		
		this.container.addClassName('allChildsVisible');
		this.menu.getElementsBySelector('ul').each(function(ul){
				//ul.ancestors()[0].innerHTML= '<span class="dDM_Icon"></span>' + ul.ancestors()[0].innerHTML;
				//ul.ancestors
				Element.identify(ul.ancestors()[0]);
				Element.insert(Element.firstDescendant(ul.ancestors()[0]), { top: '<span class="dDM_subIcon"></span>' })
				ul.style.left = $(ul.parentNode).getWidth()-3 + "px";
				ul.observe('mouseover',function(){
					//following "this" is the "ul" element
					this.style.left = $(this.parentNode).getWidth()-3 + "px"; //prevent hidden container don't calculate the right position of the submenu
					this.style.zIndex = getNextHighestZindex()+1;
				})
			}
		);
		
		this.container.removeClassName('allChildsVisible');
		
		
		this.menu.hide();
		this.menu.observe('mouseover',this.mcancelclosetime.bind(this));
		this.menu.observe('mouseout',this.mclosetime.bind(this));
		this.caption.observe('mouseover',this.mcancelclosetime.bind(this));
		this.caption.observe('mouseout',this.mclosetime.bind(this));
		
		this.caption.onclick = function(){
			if(this.menu.style.display == 'none'){
				this.caption.addClassName('open');
				this.mcancelclosetime();
				this.menu.show();
				this.menu.focus();
				this.menu.zIndex = getNextHighestZindex()+1;
			}else{
				this.mclose();
			}
		}.bind(this);
		return this;
	},
	mclose: function(){
		//console.log(this.menu+"     "+ this)
		if(this.menu)this.menu.hide();
		this.caption.removeClassName('open');
		//console.log("mclose");
	},
	mclosetime: function(){
		if(this.mclose)this.closetimer = setTimeout(this.mclose.bind(this), 500);
		//console.log("mclosetime");
	},
	mcancelclosetime: function(){
		if(this.closetimer){
			clearTimeout(this.closetimer);
			this.closetimer = null;
			//console.log("mcancelclosetime");
		}
	}
}



	var SlideShow = Class.create();
	
	SlideShow.prototype = {
		initialize: function(id,_className,_wait,_nav,_effect){ /* id = la div che contiene le pagine,
													className = la classe applicata alle pagine, 
													wait = secondi che si attende per passare alla pagina successiva*/
			this.slideShow = this;
			this.container = $(id);
			this.effect = _effect || '';
			this.container.style.position = "relative";
			//this.container.style.overflow = "hidden";
			this.containerID = id;
			this.className = _className;
			this.slides = $$("#" + this.containerID + " ." + this.className);
			this.wait = _wait;
			this.isPlaying = false;
			this.isPaused = true;
			this.selected = 0;
			this._intervalID = 0;
			this.navContainer = null;
			var navStr = "";
			this.single = false;
			this._prenav = false;
			this.navSymbol = "&nbsp;&#8226;&nbsp;";
			if(_nav){
				this.navButtons = new Array();
				this.navContainer = $(_nav);
				if(this.navContainer.down('a')){
					this.navButtons = $A(this.navContainer.getElementsBySelector('a'));
					this._prenav = true;
				}
			}
			
			
			
			
			var i;
			
			for(i=0;i<this.slides.length;i++){
				//this.slides[i].setAttribute("id","slide"+ this.containerID+ i); //aggiunge l'id alle pagine (es.:"slide1")
				this.slides[i].style.position = "absolute";
				this.slides[i].slideShow = this;
				//this.slides[i].style.top = "0px";
				//this.slides[i].style.left = "0px";
				if(this.navContainer){
					var btn;
					if(this._prenav){
						btn = this.navButtons[i];
					}else{
						btn = document.createElement("a");
						btn.setAttribute("class","SS_btn");
						var text = document.createElement("span");
						text.innerHTML = this.navSymbol + '<span class="label">' + this.slides[i].title + '</span>';
						btn.appendChild(text);
					}
					//btn.setAttribute("id","SS_btn"+this.containerID+i);
					//btn.setAttribute("href","#");
					btn.style.cursur = 'pointer'
					btn.index = i;
					btn.slideShow = this;
					btn.onclick = function(){
						this.slideShow.goto(this.index);
						try{
							return A$(document.anchors).find(
								function(value){
									return value.href;
								}
							);
						}catch(e){
							//return false;
						}
					};
					if(!this._prenav){
						this.navButtons.push(btn);
						this.navContainer.appendChild(btn);
					}
					if(i==0){
						btn.addClassName("active")
					}
				}
				if(i!=0){ //non nasconde la prima
					this.slides[i].style.display = "none"; //nasconde le pagine
				}
				Event.observe(this.slides[i],'mousedown',function(){
					this.slideShow.pause(true)
				})
			}
			Event.extend(this);
			this.goto(this.getInitialSlideIndex());
			return this;
		},
		getInitialSlideIndex : function() {
			if(document.location.href.match(/#(\w.+)/) && this.navButtons) {
				var loc = RegExp.$1;
				var slide = this.navButtons.find(function(value) { if(value.href)return value.href.match(/#(\w.+)/)[1] == loc; });
				if (slide){
					return slide.index
				}else{
					return 0
				}
			}else{
				return 0;
			}
		},
		doSlide:function(){
			Effect.Fade(this.slides[this.selected],{duration:1,from:1.0,to:0.0,afterFinish:this.onChange});
			this.selected++;
			if (this.selected==this.slides.length){
				this.selected=0;
			}
			Effect.Appear(this.slides[this.selected], { duration:1, from:0.0, to:1.0 ,afterFinish:this.onChange});
			this.checkPages();
		},
		start: function(){
			if(this.isPaused){
				this._intervalID = setInterval(this.doSlide.bind(this),this.wait);
				this.isPaused = false;
				this.isPlaying = true;
			}
			return this;
		},
		pause: function(_continue){
			if(this.isPlaying){

				clearInterval(this._intervalID);
				this.isPaused = true;
				this.isPlaying = false;
				if(_continue && this.isPaused){
					setTimeout(this.start,15000)
				}
			}
			return this
		},
		goto: function(page,_effect){
			if(this.isPlaying)this.pause(true);
			if(page!=this.selected){
				/*
				Effect.Fade(slides[selected],{duration:0.5,from:1.0,to:0.0});
				selected=page;
				//if (selected==slides.length){
				//	selected=0;
				//}
				Effect.Appear(slides[selected], { duration:0.5, from:0.0, to:1.0 });*/
	
	
				//Effect.Fade(slides[selected],{duration:0.5,from:1.0,to:0.0});
				//selected=page;
				if(this.effect.toLowerCase()=='appearfade' || (_effect && _effect.toLowerCase() == 'appearfade')){
					Effect.Fade(this.slides[this.selected],{duration:0.5,afterFinish:this.onChange});
					this.selected=page;
					Effect.Appear(this.slides[this.selected], {duration:0.5,afterFinish:this.onChange});
				}else{
					Effect.SlideUp(this.slides[this.selected],{duration:0.5,transition:Effect.Transitions.sinoidal,afterFinish:this.onChange});
					this.selected=page;
					Effect.SlideDown(this.slides[this.selected], { duration:0.5,transition: Effect.Transitions.sinoidal,afterFinish:this.onChange});
				}
			}
			this.checkPages();
		},
		next: function(){
			this.pause(false);
			this.doSlide();
		},
		checkPages: function(){
			if(this.navContainer){
				for(j=0;j<this.slides.length;j++){
					$(this.navButtons[j]).removeClassName("active");
				}
				$(this.navButtons[this.selected]).addClassName("active");
			}
		},
		onChange: function(){
			
		}
	}






var modifield = Class.create();

modifield.prototype = {
	initialize: function(id,field,_fieldIcons,_replaceText){
	
		this.fieldIcons = _fieldIcons || false;
		
		this.Content = $(id).getElementsBySelector('.modifield_Content')[0];
		this.Caption = $(id).getElementsBySelector('.modifield_Caption')[0];
		this.Field = $(field);
		this.origValue = this.Field.value;
		this.Content.hide();
		
		this.replaceText = '';
		if(_replaceText){
			this.replaceText = _replaceText;
			this.replaceTextElement = new Element('span',{'class':'opaque','title':'edit'});
			this.replaceTextElement.update(this.replaceText)
			if(this.Field.value=='')this.Caption.update(this.replaceTextElement)
		}else{
			this.replaceTextElement = null;
		}
		
		
		this.modifIcon = new Element('span', {'class':'modifield_Icon', 'title':'edit'});
		this.cancelIcon = new Element('span', {'class':'modifield_cancelIcon', 'title':'cancel'});
		this.okIcon = new Element('span', {'class':'modifield_okIcon', 'title':'ok'});
		this.Caption.insert(this.modifIcon,'bottom');
		
		
		if(this.fieldIcons==true){
			this.Field.up(0).insert(this.cancelIcon,'after');
			this.Field.up(0).insert(this.okIcon,'after');
			this.cancelIcon.observe('click',this.cancelEdit.bind(this));
			this.okIcon.observe('click',this.exitEdit.bind(this));
		}else{
			this.Field.observe('blur',this.exitEdit.bind(this));
		}
		
		this.Caption.observe('click',this.enterEdit.bind(this));
		this.Field.observe('keydown',this.checkForEscapeOrReturn.bind(this));
	},
	enterEdit:function(){
		this.origValue = this.Field.value;
		this.Content.show();
		this.Caption.hide();
		this.Field.focus();
		this.Field.select();
	},
	exitEdit:function(){
		if(this.Field.value.length>1){
			this.Caption.update(this.Field.value);
		}else{
			if(this.replaceTextElement)this.Caption.update(this.replaceTextElement)
		}
		this.origValue = this.Field.value;
		this.Content.hide();
		this.Caption.show();
		this.Caption.insert(this.modifIcon,'bottom');
	},
	cancelEdit:function(){
		this.Field.value = this.origValue;
		if(this.Field.value.length>1){
			this.Caption.update(this.Field.value);
		}else{
			if(this.replaceTextElement)this.Caption.update(this.replaceTextElement)
		}
		this.Content.hide();
		this.Caption.show();
		this.Caption.insert(this.modifIcon,'bottom');
	},
	checkForEscapeOrReturn: function(e) {
		if (e.ctrlKey || e.altKey || e.shiftKey) return;
		if (Event.KEY_ESC == e.keyCode)
		  this.cancelEdit();
		else if (Event.KEY_RETURN == e.keyCode){
		  this.exitEdit();
		  e.stop();
		}
	}
}


var typeDDM = Class.create();

typeDDM.prototype = {
	initialize: function(ddm,selectElement,captionElement,_selectedId,_enabled){
		_typeDDM = this;
		this.ddm = new dropDownMenu(ddm);
		this.selectElement = $(selectElement);
		this.selectedId = _selectedId;
		this.enabled = _enabled;
		this.selectedChoice = null;
		this.captionElement = captionElement;
		this.choices = this.ddm.container.getElementsBySelector('a');
		this.choices.each(function(el){
			el.observe('click', function(event){
				this.selectId(Event.element(event).rel);
			}.bind(this));
		}.bind(this));
		
		if(this.selectedId){
			this.selectId(this.selectedId);
		}
	},
	selectId: function(id){
		this.selectElement.getElementsBySelector('option').each(function(o){
			if(o.value==id){o.selected = true}
		}.bind(this));
		this.choices.each(function(el){
			if(el.rel==id){
				el.addClassName('selected')
				this.selectedChoice = el;
			}else{
				el.removeClassName('selected')
			}
		}.bind(this));
		this.captionElement.update(this.selectedChoice.title)
		new Effect.Pulsate(this.captionElement,{ pulses: 3,from: 0.5, duration: 0.5,transition:Effect.Transitions.sinoidal ,delay:0.4})
		this.selectedId = id;
		this.onChange(id)
	},
	onChange:function(id){
		return this.selectedId;
	}
}




var itemImageBox = Class.create();

itemImageBox.prototype = {
	initialize: function(id){
		this.element 		= $(id);
		this.field 			= $(id).getElementsBySelector('input')[0];
		this.dDM 			= $(id).getElementsBySelector('.dDM')[0];
		this.imageContainer	= $(id).getElementsBySelector('.imageContainer')[0];
		this.value			= null || this.field.value;
		this.window			= null;
		this.maxWidth		= this.imageContainer.getWidth()-10;
		this.maxHeight		= this.imageContainer.getHeight()-10;
		this.lightView		= null;
		this.cancelButtons	= $(id).getElementsBySelector('.itemImageBox_cancelButton');
		this.loadingImage	= new Image();
		if(this.cancelButtons){
			if(this.value.length>0){
				this.cancelButtons.invoke('removeClassName', 'disabled')
			}else{
				this.cancelButtons.invoke('addClassName', 'disabled')
			}
			this.cancelButtons.invoke('observe','click',function(){
				this.dDM.dDM.mclose();
				this.clear();
			}.bind(this))
		}
		this.reloadImage();
		//document.observe("dom:loaded",this.reloadImage);
		return this;
	},
	setImageByURL:function(){
		Lightview.show({
			href: '/inc/tools/img/UrlImage.asp?value='+this.value,
			rel: 'ajax',
			options: {
				autosize:true,
				radius:5,
				topclose: false,
				viewport:false,
				closeButton:false,
				ajax: {
					asynchronous:true,
					evalScripts:true,
					evalJS:'force',
					evalJSON:'force',
					onComplete: function(){
						$('img_URLAddress_URL').focus();
						$('img_URLAddress_URL').select();
					}
				}
			}
		});
		this.lightView = Lightview;
		this.lightView.itemImageBox = this;
		this.lightView.itemImageBox.urlImage = {};
		return this.lightView;
	},
	setImageByUpload:function(){
		Lightview.show({
			href: '/inc/tools/img/UploadImage.asp',
			rel: 'ajax',
			options: {
				autosize:false,
				width:500,
				height:280,
				radius:5,
				topclose: false,
				viewport:false,
				closeButton:false,
				ajax: {
					asynchronous:true,
					evalScripts:true,
					evalJS:'force',
					evalJSON:'force',
				}
			}
		});
		this.lightView = Lightview;
		this.lightView.itemImageBox = this;
		this.lightView.itemImageBox.uploadImage = {};
		return this.lightView;
	},
	setImageByYahooImage:function(title){
		//if(!title)return false;
		Lightview.show({
			href: '/inc/tools/img/chooseYahooImage.asp?title=' + encodeURIComponent(title),
			rel: 'ajax',
			options: {
				autosize:false,
				width:630,
				height:450,
				radius:5,
				topclose: false,
				closeButton:false,
				viewport:false,
				ajax: {
					asynchronous:true,
					evalScripts:true,
					evalJS:'force',
					evalJSON:'force',
					onComplete: function(){
						
					}
				}
			}
		});
		this.lightView = Lightview;
		this.lightView.itemImageBox = this;
		this.lightView.itemImageBox.yahooImage = {};
		return this.lightView;
	},
	setImageByFirstYahooImage:function(_title,_callback){
		if(!_title)return false;
		new Ajax.Updater('emptyLoading','/inc/tools/img/chooseYahooImage_results.asp?title=' + _title, {
			asynchronous:true, 
			evalScripts:true,
			evalJS:'force',
			evalJSON:'force',
			parameters: {'title':_title,'callback':_callback}
		});
	},
	setImage:function(url){
		if(url){
			this.value = url;
			this.field.value = url;
			this.cancelButtons.invoke('removeClassName', 'disabled')
			return this.reloadImage();
		}
	},
	reloadImage:function(){
		if(this.value){
			return this.loadImageFromUrl(this.value);
		}else{
			new Effect.Appear(this.imageContainer,{from:0})
			this.imageContainer.setAttribute('style','background-image:url(/inc/tools/fitimage.aspx?img=/inc/img/noimage.png&w=100&h=100)')
			return false;
		}
	},
	loadImageFromUrl:function(url){
		if(url){
			this.imageContainer.setAttribute('style','background-image:url(/inc/img/loader.gif)');
			Event.observe(this.loadingImage,'load',function(){
				this.imageContainer.setAttribute('style','background-image:url(/inc/tools/fitimage.aspx?img=' + url + '&w=' + this.maxWidth + '&h=' + this.maxHeight +')');
				this.imageContainer.hide();
				new Effect.Appear(this.imageContainer,{from:0,duration:0.5,delay:0.5});
				Event.stopObserving(this.loadingImage,'load');
			}.bind(this));
			/*
			this.loadingImage.onload = function(){
				this.imageContainer.setAttribute('style','background-image:url(/inc/tools/fitimage.aspx?img=' + url + '&w=' + this.maxWidth + '&h=' + this.maxHeight +')');
				this.imageContainer.hide();
				new Effect.Appear(this.imageContainer,{from:0,duration:0.5,delay:0.5});
			}.bind(this);*/
			this.loadingImage.hide();
			this.loadingImage.src = '/inc/tools/fitimage.aspx?img=' + url + '&w=' + this.maxWidth + '&h=' + this.maxHeight;
			return url;
		}
		return false;
	},
	clear:function(withoutConfirm){
		if(!withoutConfirm){
			withoutConfirm = confirm('Do you want to remove this image from the item?')
		}
		if(withoutConfirm){	
			this.value = null;
			this.field.value = '';
			this.cancelButtons.invoke('addClassName', 'disabled')
			this.reloadImage();
		}
	}
}




	
var itemTypesUtils = {
	items: [
		
	],
	getTypeCaption: function(typeId){
		return this.getProperty(typeId,'caption')
	},
	getTypeValidationRegExp:	function(typeId){
		return this.getProperty(typeId,'validationRegExp')
	},
	getProperty: function(typeId,property){
		for (var index = 0; index < this.items.length; ++index) {
			if(this.items[index].id==typeId){
				return eval('this.items[index].' + property);
				break;
			}
		}
	},
	_format: {
		string: function(string){
				return string.escapeHTML();
		},
		number: function(string){
			if(isNaN(string) || null){
				throw 'Not a Number'
			}else{
				return string.escapeHTML();
			}
		},
		integer: function(string){
			if(isNaN(string) || null){
				throw 'Not a Number'
			}else{
				return Number(string).toFixed(0).escapeHTML();
			}
		},
		unitNumber:	function(string,sign, plural, prefix){
			if(isNaN(string) || null){
				throw 'Not a Number'
				return 0;
			}else{
				if(plural && Math.round(string)>1)sign=sign+"s";
				if(prefix){
					return (sign + ' ' + string.escapeHTML())
				}else{
					return (string.escapeHTML() + ' ' + sign)
				}
			}
		},
		currency: function(string,valute){
			if(isNaN(string) || null){
				throw 'Not a Number'
				return 0;
			}else{
				var valuteSymbol = '$'
				switch(valute.toUpperCase()){
					case "EUR":
						valuteSymbol = "&euro;";
						decimalSymbol = ",";
						separatorSymbol = ".";
						break;
					case "USD":
						valuteSymbol = "$";
						decimalSymbol = ".";
						separatorSymbol = ",";
						break;
					default:
						valuteSymbol = "$";
						decimalSymbol = ".";
						separatorSymbol = ",";
						break;
				}
				num = string.toString().replace(/\$|\,/g,'');
				if(isNaN(num))num = "0";
				sign = (num == (num = Math.abs(num)));
				num = Math.floor(num*100+0.50000000001);
				cents = num%100;
				num = Math.floor(num/100).toString();
				if(cents<10)
				cents = "0" + cents;
				for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
				num = num.substring(0,num.length-(4*i+3))+separatorSymbol+
				num.substring(num.length-(4*i+3));
				return (((sign)?'':'-') + valuteSymbol + num + decimalSymbol + cents);
			}
		},
	},
	formatType: function(string, typeId){
		
			var _formatFunction = '';
			var ruleTypeId = typeId;
			var _value = string;
			do{
				_property = this.getProperty(ruleTypeId,'viewRule');
				if(_property){
					_formatFunction = _property;
				}else{
					ruleTypeId = this.getProperty(ruleTypeId,'parent');
				}
			}while(_formatFunction.length==0)
		try{
			var a = String(eval('itemTypesUtils._format.' + _formatFunction));
			return a;
		}catch(e){
			return 'Error: ' + e.escapeHTML() + ' (' + string.escapeHTML() + ')';
		}
	}
}





var detailsList = Class.create();
detailsList.prototype = {
	initialize: function(id){
		this.id = id;
		$(id).detailsListObject = this;
		this.element = $(id);
		this.isEditing = false;
		this.multiedit = false;
		
		this.items = [];
		this.selectedItems = [];
		this.editingItems = [];
		
		this.Sortable = null;
		
		var a = this.element.getElementsBySelector('li.detailRow');
		if(a.length>0){
			for(i=0;i<a.length;i++){
				var _label = a[i].getElementsBySelector('.editMode .detailLabel input')[0].value;
				var _value = a[i].getElementsBySelector('.editMode .detailValue input')[0].value;
				var _type  = a[i].getElementsBySelector('.editMode .detailType select')[0].value;
				this._addDetailRow(new detailRow(this,a[i],_label,_value,_type));
			}
		}
		
		this._reCreateSort();
		return this;
	},
	newItem: function(_label,_value,_type){
		//ToDo: Implement multiedit validation
		var b = this._addDetailRow(new detailRow(this,null,_label,_value,_type));
		var a = b.element;
		this.element.insert({bottom:a});
		b.edit();
		b.element.editMode.detailLabel.select();
		Effect.ScrollTo(a);
		this._reCreateSort();
		//alert(this.items.length);
		return b;
	},
	remove: function(detailRow){
		//alert('Do you really want to remove this detail?');
		this.items = this.items.without(detailRow);
		detailRow.element.fade();
		new Effect.BlindUp(detailRow.element,{afterFinish:function(fx){detailRow.element.remove()}.bind(this)})
		this._reCreateSort();
		//alert(this.items.length);
		return detailRow;
	},
	_reCreateSort: function(){
		this._destroySortable();
		this.Sortable = Sortable.create(this.element,{
			only:['detailRow','detailsList'],
			scroll: window,
			tree:true,
			hoverclass:'dragListItem',
			ghosting:true,
			handle:'.grab',
			containment:[this.id,'sortUtils'],
			delay:0.5,
			onChange: function(){
			},
			onUpdate: function(){
			}
		});
	},
	_destroySortable: function(){
		Sortable.destroy(this.element);
	},
	_updateEditing: function(){
		this.isEditing = (this.editingItems.length>0);
	},
	_addDetailRow: function(_detailRow){
		_detailRow.index = this.items.length;
		this.items.push(_detailRow);
		return _detailRow;
	}
}




















function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}



Array.prototype.clean = function(){
	for(a in this){
		if(a==null)this.splice(a);
	}
	return this;
}



function zeroPad(x){
	x = Math.round(x);
   return (x>9)?x:'0'+x;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_validateForm() { //v4.0
  	var i,p,q,nm,test,num,min,max,firstErrField,errors='',tmpErrors='',args=MM_validateForm.arguments;
	firstErrField = null;
  	for (i=0; i<(args.length-2); i+=3){
		tmpErrors = errors;
  		test=args[i+2];
		val=MM_findObj(args[i]);
		valObj = val;
    	if (val) {
			nm=val.title;
			if(!nm){nm=val.name}
			if ((val=val.value)!="" && args[i+1]!='radio') {
				if (test.indexOf('isEmail')!=-1) {
					p=val.indexOf('@');
			        if (p<1 || p==(val.length-1)){
						errors+='- Il campo "'+nm+'" deve contenere un indirizzo email valido.\n';
					}
				} else if (test!='R') {
					num = parseFloat(val);
			        if (isNaN(val)){
						errors+='- Il campo "'+nm+'" deve contenere un numero.\n';
					}
			        if (test.indexOf('inRange') != -1) {
						p=test.indexOf(':');
						min=test.substring(8,p);
						max=test.substring(p+1);
						if (num<min || max<num) errors+='- Il campo "'+nm+'" deve contenere un numero compreso tra '+min+' e '+max+'.\n';
				    }
				}
			} else if (test.charAt(0) == 'R'){
			 	if (args[i+1]=='radio'){
					if (emptyInput(valObj)){
						errors += '- Selezionare una opzione per il campo "'+valObj[0].title+'".\n'+emptyInput(valObj);
						valObj = valObj[0];
					}
				}else{
					errors += '- Il campo "'+nm+'" è obbligatorio.\n';
				}
			 }
		}
		if(tmpErrors != errors){
			valObj.className = 'error'
			if(firstErrField == null){
				firstErrField = valObj;
				firstErrField.focus();
			}
		}else{
			valObj.className = ''
		}
	} 
	if (errors) alert('Attenzione! Si sono verificati i seguenti errori:\n'+errors);
	document.MM_returnValue = (errors == '');
	return document.MM_returnValue;
}



function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){
		s+='* '+a[i+3]+'\n';
		o.className = 'error'
		err=false;
	}else{
		o.className = '';
	}
  }
  if (s!=''){alert('The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}


var clockID = 0;

function UpdateClock() {
   if(clockID) {
      clearTimeout(clockID);
      clockID  = 0;
   }
   var tDate = new Date();
   MM_findObj('placeTimeStr').innerText = "" 
                                   + (tDate.getHours()>9 ? tDate.getHours():"0"+tDate.getHours()) + ":" 
                                   + (tDate.getMinutes()>9 ? tDate.getMinutes():"0"+tDate.getMinutes()) + ":" 
                                   + (tDate.getSeconds()>9 ? tDate.getSeconds():"0"+tDate.getSeconds());
   clockID = setTimeout("UpdateClock()", 1000);
}

function StartClock() {
   clockID = setTimeout("UpdateClock()", 500);
}

function KillClock() {
   if(clockID) {
      clearTimeout(clockID);
      clockID  = 0;
   }
}

function messageWindow(title, msg)

{

  var width="300", height="125";

  var left = (screen.width/2) - width/2;

  var top = (screen.height/2) - height/2;

  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top;

  var msgWindow = window.open("","msgWindow", styleStr);

  var head = '<head><title>'+title+'</title></head>';

  var body = '<center>'+msg+'<br><p><form><input type="button" value="   Done   " onClick="self.close()"></form>';

  msgWindow.document.write(head + body);

}

var popUpWin=0;

function popUpWindow(URLStr, left, top, width, height,scrollbars,resize)

{

  if(popUpWin)

  {

    if(!popUpWin.closed) popUpWin.close();

  }
	if(!scrollbars) scrollbars = 'no';
	if(!resize) scrollbars = 'no';
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable='+ resize +',copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');

}

//corrisponde alla @replacesubstring
function ReplaceSubString(Stringa, StringaDaCercare, StringaDaSostituire) {
 temp = "" + Stringa;
 while (temp.indexOf(StringaDaCercare)>-1) {
  pos= temp.indexOf(StringaDaCercare);
  temp = "" + (temp.substring(0, pos) + StringaDaSostituire + temp.substring((pos + StringaDaCercare.length), temp.length));
 }
 return temp;
}

function getCheckBoxes(chkbxs,txtfld){
	chkbxs = MM_findObj(chkbxs);
	strcomp = '';
	for(i=0;i<chkbxs.length;i++){
		if(chkbxs[i].checked) strcomp = strcomp + chkbxs[i].value +'|';
	}
	if(strcomp){
	strcomp = strcomp + '%$£$';
	strcomp = ReplaceSubString(strcomp, '|%$£$', '');
	}
	txtfld = MM_findObj(txtfld);
	txtfld.value = strcomp;
}	
		
function addbookmark() {
	bookmarkurl= window.location.href;
	bookmarktitle=document.title;
	if (document.all) window.external.AddFavorite(bookmarkurl,bookmarktitle);
}

function setHome() {
	document.body.style.behavior='url(#default#homepage)';
	document.body.setHomePage("http://www.capodimonte.com");
}
function printPage(){
	window.print();
}


function Accetta(){
	var p = MM_findObj('Accettato');
	var e = MM_findObj('Normativa_sulla_privacy');
	if (p.checked) {
		e.value = "Accettato";
	}else{
		e.value = "";
	}
}




function toggleVis(id,focus){
	var a,b,p;
	p = id + 'Content';
	a = MM_findObj(p);
	a.style.display = ( (a.style.display=='none') ? '' : 'none');
	b = MM_findObj(id + 'Caption');
	if (a.style.display =='none')
	{
		if(b)b.className = "off";
	}else{
		if(focus){location = '#' + id;}
		if(b)b.className = "on";
	}
}
function toggleDisplay(id){
	a = MM_findObj(id);
	a.style.display = ( (a.style.display=='none') ? '' : 'none');
}



function sendPageByMail(){
	window.location.href = "/sendPageByMail.asp";
}

	function addImage(a){
		a = MM_findObj(a);
		popUpWindow('/inc/upArtImage.aspx?campo=' + a.name + '&amp;filename=' + a.value, 10, 10, 500, 275);
	}
	function urlImage(a){
		a = MM_findObj(a);
		popUpWindow('/inc/upUrlImage.aspx?campo=' + a.name + '&amp;filename=' + a.value, 10, 10, 500, 275);
	}


function loadXMLinID(url,id,hideLoading,callback){
  if(hideLoading!=true)MM_findObj(id).innerHTML = '<div class="loading"><a onclick="loadXMLinID(\''+url+'\',\''+id+'\',\'' + hideLoading + '\')"><span>Loading...</span></a></div>'+ MM_findObj(id).innerHTML;
  //new Behaviour.addLoadEvent(new Ajax.Updater(id,url));
  var ppX = new Ajax.Updater(id,url,{onComplete: callback});
  
}

function xUpdater(id,page,params)
{
    return new Ajax.Updater(id,page,params);
}

function setAjaxSubmitUpdate(formId,containerId,params){
	Event.observe(formId, 'submit', function(event) {
		new Ajax.Updater(containerId,$(formId).action,{method: $(formId).method, parameters: Form.serialize(formId),asynchronous:true, evalScripts:true,evalJS:'force',evalJSON:'force',onComplete:function(){$(containerId).removeClassName('isLoading')}})
		Event.stop(event); // stop the form from submitting
	    return false;
	});
}

function setAjaxSubmitUpdateByURL(formId,containerId,URL,params){
	Event.observe(formId, 'submit', function(event) {
		new Ajax.Updaterx(containerId,URL,{method: $(formId).method, parameters: Form.serialize(formId),asynchronous:true, evalScripts:true,evalJS:'force',evalJSON:'force',onComplete:function(){$(containerId).removeClassName('isLoading')}})
		Event.stop(event); // stop the form from submitting
	    return false;
	});
}








function updateId(id,str){
    MM_findObj(id).innerHTML = str;
}

function helpWin(url){
	try{
		w = 350;
		h = 500;
		left = 24
		left = screen.availWidth - w - 24;
		top = 24;
	}catch(ex){
	}finally{
		popUpWindow(url, left , top, w, h,'1','1');
	}
	return false;
}

function InStr(strSearch, charSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
                           was found in the string str.  (If the character is not
                           found, -1 is returned.)
                           
Requires use of:
	Mid function
	Len function
*/
{
	for (i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, 1))
	    {
			return i;
	    }
	}
	return -1;
}

function Mid(str, start, len)
        /***
                IN: str - the string we are LEFTing
                    start - our string's starting position (0 based!!)
                    len - how many characters from start we want to get

                RETVAL: The substring from start to start+len
        ***/
        {
                // Make sure start and len are within proper bounds
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }

function Right(str, n)
        /***
                IN: str - the string we are RIGHTing
                    n - the number of characters we want to return

                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }

function Left(str, n)
        /***
                IN: str - the string we are LEFTing
                    n - the number of characters we want to return

                RETVAL: n characters from the left side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                        return "";
                else if (n > String(str).length)   // Invalid bound, return
                        return str;                // entire string
                else // Valid bound, return appropriate substring
                        return String(str).substring(0,n);
        }

function Len(str)
/***
		IN: str - the string whose length we are interested in

		RETVAL: The number of characters in the string
***/
{  return String(str).length;  }

function Trim(str)
/***
		PURPOSE: Remove trailing and leading blanks from our string.
		IN: str - the string we want to Trim

		RETVAL: A Trimmed string!
***/
{
		return RTrim(LTrim(str));
}

function RTrim(str)
        /***
                PURPOSE: Remove trailing blanks from our string.
                IN: str - the string we want to RTrim

                RETVAL: An RTrimmed string!
        ***/
        {
                // We don't want to trip JUST spaces, but also tabs,
                // line feeds, etc.  Add anything else you want to
                // "trim" here in Whitespace
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
                    // We have a string with trailing blank(s)...

                    var i = s.length - 1;       // Get length of string

                    // Iterate from the far right of string until we
                    // don't have any more whitespace...
                    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                        i--;


                    // Get the substring from the front of the string to
                    // where the last non-whitespace character is...
                    s = s.substring(0, i+1);
                }

                return s;
        }


function LTrim(str)
        /***
                PURPOSE: Remove leading blanks from our string.
                IN: str - the string we want to LTrim

                RETVAL: An LTrimmed string!
        ***/
        {
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(0)) != -1) {
                    // We have a string with leading blank(s)...

                    var j=0, i = s.length;

                    // Iterate from the far left of string until we
                    // don't have any more whitespace...
                    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                        j++;


                    // Get the substring from the first non-whitespace
                    // character to the end of the string...
                    s = s.substring(j, i);
                }

                return s;
        }

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

function FormatPercent(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num*100,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf(")") != -1) {
		// We know we have a negative number, so place '%' inside of ')'
		tmpStr = tmpStr.substring(0,tmpStr.length - 1) + "%)";
		return tmpStr;
	}
	else
		return tmpStr + "%";			// Return formatted string!
}

function FormatCurrency(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf("(") != -1 || tmpStr.indexOf("-") != -1) {
		// We know we have a negative number, so place '$' inside of '(' / after '-'
		if (tmpStr.charAt(0) == "(")
			tmpStr = "($"  + tmpStr.substring(1,tmpStr.length);
		else if (tmpStr.charAt(0) == "-")
			tmpStr = "-$" + tmpStr.substring(1,tmpStr.length);
			
		return tmpStr;
	}
	else
		return "$" + tmpStr;		// Return formatted string!
}

function FormatDateTime(datetime, FormatType)
/*
	 FomatType takes the following values
		1 - General Date = Friday, October 30, 1998
		2 - Typical Date = 10/30/98
		3 - Standard Time = 6:31 PM
		4 - Military Time = 18:31
*/
{
	var strDate = new String(datetime);

	if (strDate.toUpperCase() == "NOW") {
		var myDate = new Date();
		strDate = String(myDate);
	} else {
		var myDate = new Date(datetime);
		strDate = String(myDate);
	}


	// Get the date variable parts
	var Day = new String(strDate.substring(0,3));
	if (Day == "Sun") Day = "Sunday";
	if (Day == "Mon") Day = "Monday";
	if (Day == "Tue") Day = "Tuesday";
	if (Day == "Wed") Day = "Wednesday";
	if (Day == "Thu") Day = "Thursday";
	if (Day == "Fri") Day = "Friday";
	if (Day == "Sat") Day = "Saturday";	
	
	var Month = new String(strDate.substring(4,7)), MonthNumber = 0;
	if (Month == "Jan") { Month = "January"; MonthNumber = 1; }
	if (Month == "Feb") { Month = "February"; MonthNumber = 2; }
	if (Month == "Mar") { Month = "March"; MonthNumber = 3; }
	if (Month == "Apr") { Month = "April"; MonthNumber = 4; }
	if (Month == "May") { Month = "May"; MonthNumber = 5; }
	if (Month == "Jun") { Month = "June"; MonthNumber = 6; }
	if (Month == "Jul") { Month = "July"; MonthNumber = 7; }
	if (Month == "Aug") { Month = "August"; MonthNumber = 8; }
	if (Month == "Sep") { Month = "September"; MonthNumber = 9; }
	if (Month == "Oct") { Month = "October"; MonthNumber = 10; }
	if (Month == "Nov") { Month = "November"; MonthNumber = 11; }
	if (Month == "Dec") { Month = "December"; MonthNumber = 12; }
	
	var curPos = 11;
	var MonthDay = new String(strDate.substring(8,10));
	if (MonthDay.charAt(1) == " ") {
		MonthDay = "0" + MonthDay.charAt(0);
		curPos--;
	}	
	
	var MilitaryTime = new String(strDate.substring(curPos,curPos + 5));
	
	var Year = new String(strDate.substring(strDate.length - 4, strDate.length));	
	
	document.write(strDate + "");	

	// Format Type decision time!
	if (FormatType == 1)
		strDate = Day + ", " + Month + " " + MonthDay + ", " + Year;
	else if (FormatType == 2)
		strDate = MonthNumber + "/" + MonthDay + "/" + Year.substring(2,4);
	else if (FormatType == 3) {
		var AMPM = MilitaryTime.substring(0,2) >= 12 && MilitaryTime.substring(0,2) != "24" ? " PM" : " AM";
		if (MilitaryTime.substring(0,2) > 12)
			strDate = (MilitaryTime.substring(0,2) - 12) + ":" + MilitaryTime.substring(3,MilitaryTime.length) + AMPM;
		else {
			if (MilitaryTime.substring(0,2) < 10)
				strDate = MilitaryTime.substring(1,MilitaryTime.length) + AMPM;
			else
				strDate = MilitaryTime + AMPM;
		}
	}	
	else if (FormatType == 4)
		strDate = MilitaryTime;


	return strDate;
}

function countDownFormatDate(Time_Left,format){
	var output;
	output='';
	 switch(format)
	   {
	   case 0:
			//The simplest way to display the time left.
			output = Time_Left + ' seconds';
			break;
	   case 1,2:
			//More datailed.
			weeks = Math.floor(Time_Left / (60 * 60 * 24 * 7));
			Time_Left %= (60 * 60 * 24 * 7);
			days = Math.floor(Time_Left / (60 *60 * 24));
			Time_Left %= (60 * 60 * 24);
			hours = Math.floor(Time_Left / (60 * 60));
			Time_Left %= (60 * 60);
			minutes = Math.floor(Time_Left / 60);
			Time_Left %= 60;
			seconds = Time_Left;
			
			if(format==1){
				ws = ' week'; ds = ' day'; hs = ' hour'; ms = ' minute'; ss = ' second'
				wps = 's'; dps = 's'; hps = 's'; mps = 's'; sps = 's';
			}else{
				ws = '<abbr title="week">w</abbr>'; ds = '<abbr title="day">d</abbr>'; hs = '<abbr title="hour">h</abbr>'; ms = '<abbr title="minute">m</abbr>'; ss = '<abbr title="second">s</abbr>'
				wps = ''; dps = ''; hps = ''; mps = ''; sps = '';
			}
			//ps is short for plural suffix.
			if(weeks == 1) wps ='';
			if(days == 1) dps ='';
			if(hours == 1) hps ='';
			if(minutes == 1) mps ='';
			if(seconds == 1) sps ='';
			
			if(weeks>=1)output = weeks + ws + wps + ' ';
			if(days >=1 || weeks>=1)output += days + ds + dps + ' ';
			if((days >=1 && hours<=0)||hours>=1)output += hours + hs + hps + ':';
			if((days >=1 && hours>=1 && minutes<=0) ||minutes>=1)output += minutes + ms + mps + ':';
			output += seconds + ss + sps;
			 
			break;
	   default: 
			output = Time_Left + ' seconds';
	   }
	return output
}

function countDown(endDate,id){
	var now = new Date(); 
	Todays_Date = (new Date(now.getFullYear(),now.getMonth()+1,now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds())).getTime();
	Time_Left = Math.round((endDate - Todays_Date)/1000);
	if(Time_Left > 0){
		updateId(id,countDownFormatDate(Time_Left,2));
			return setTimeout('countDown(' + endDate + ',\'' + id + '\');', 100);
	}else{
		updateId(id,'Finished');
	}
}

function toggleAttribute(obj,attr,value1,value2){
	a = $(obj);
	a.setAttribute(attr,a.getAttribute(attr) == value1 ? value2 : value1)
}

Control.DatePicker.Locale['it_IT'] = {
	dateTimeFormat: 'dd/MM/yyyy HH:mm',
	dateFormat: 'dd/MM/yyyy',
	firstWeekDay: 1,
	weekend: [0,6],
	language: 'it'};
	
Control.DatePicker.Language['it'] = {
	months: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
		'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre',
		'Dicembre'],
	days: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'],
	strings: {
		'Now': 'Adesso',
		'Today': 'Oggi',
		'Time': 'Ora',
		'Exact minutes': 'Minuti esatti',
		'Select Date and Time': 'Seleziona date e ora',
		'Open calendar': 'Apri calendario'
		}
	};

