

/* ---------- /shared/js/jPrototype.js ---------- */

var jPrototype = {
	Version: '0.25',
	nightly: '20090902',
/*
	lc1:["à","á","è","é","ì","í","ò","ó","ù","ú","ç"],
	uc1:["À","Á","È","É","Ì","Í","Ò","Ó","Ù","Ú","Ç"],
	eq1:["a","a","e","e","i","i","o","o","u","u","c"],
	lc2:["š","œ" ,"ž","ÿ","â","ã","ä","å","æ" ,"ê","ë","î","ï","ð","ñ","ô","õ","ö","û","ü","ý","þ" ,"ß" ],
	uc2:["Š","Œ" ,"Ž","Ÿ","Â","Ã","Ä","Å","Æ" ,"Ê","Ë","Î","Ï","Ð","Ñ","Ô","Õ","Ö","Û","Ü","Ý","Þ" ,"ß" ],
	eq2:["s","oe","z","y","a","a","a","a","ae","e","e","i","i","d","n","o","o","o","u","u","y","th","ss"]
*/
	lc:[353,339,382,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255],
	eq:["s","oe","z","ss","a","a","a","a","a","a","ae","c","e","e","e","e","i","i","i","i","d","n","o","o","o","o","o","d","u","u","u","u","y","th","y"]
}
jPrototype.lc.each(function(v,i){jPrototype.lc[i]=String.fromCharCode(v);});

function dump(o){
	var level_current=arguments[1]||0;
	var level_next=level_current+1;
	var indent_single="    ";
	var indent_current="";
	var indent_next="";
	for(var i=0;i<level_current;i++)indent_current+=indent_single;
	var indent_next=indent_current+indent_single;
	var result = ''; 
	     if(is.Null(o))   result += '{ } null';
	else if(is.U(o)) result += '{ } undefined';
	else if(is.S(o)) result += '{s:'+o.length+'} "' + o.replace(/"/,'\\"') + '"' ;
	else if(is.B(o)) result += '{b} ' + (o?"true":"false") ;
	else if(is.N(o)) result += '{n} ' + o ;
	else if(is.F(o)) result += '{f} ' + String(o).split("\n").join("\n"+indent_current) ;
	else if(is.Date(o)) result += '{D} '+o.getFullYear().zeroFill()+'-'+(o.getMonth()+1).zeroFill()+'-'+o.getDate().zeroFill()+' '+o.getHours().zeroFill()+':'+o.getMinutes().zeroFill()+':'+o.getSeconds().zeroFill()+' '+o.getMilliseconds().zeroFill(3);
	else if(is.Array(o)){
		var l=o.length;
		result += '{a:'+l+') [';
		o.each(function(v,k){
			result += '\n'+indent_next+k+': ';
			result += dump(v,level_next) ;
			result += "," ;
		});
		if (l>0) result  = result.substr(0,result.length-1)+'\n';
		result += indent_current+']' ;
	}else if(is.Object(o)){
		if(is.Defined(o.tagName)){
			result += '{H} '+o.tagName;
		}else if(is.Defined(o.nodeName)){
			result += '{X} '+o.nodeName;
		}else{
			var l=$A(o).length;
			result += '{o:'+l+') {';
			for(k in o){
				v=o[k];
				result += '\n'+indent_next+k+': ';
				result += dump(v,level_next) ;
				result += "," ;
			}
			if (l>0) result  = result.substr(0,result.length-1)+'\n';
			result += indent_current+'}' ;
		}
	}
	return result;
}

function log(q){
	try{
		console.log(q);
	}catch(e){
		if(!$("jLog")){
			$$("BODY").first().insert({top:'<div id="jLog" style="float:right;"></div>'})
		}
		var jconsole=$("jLog"),d=new Date();
		if(jconsole){
			jconsole.insert(
				'<div>['+d.getHours().zeroFill()+':'+d.getMinutes().zeroFill()+':'+d.getSeconds().zeroFill()+']</div>'
				+'<xmp>'+dump(q)+'</xmp>'
			);
		}
	}
}

function trace(){alert($A(arguments))};

function ALLOF(check,values){
	result=true;
	values.each(function(v){if(check!=v)result=false;});
	return result;
}
function NONEOF(check,values){
	var result=true;
	values.each(function(v){if(check==v)result=false;});
	return result;
}
function ONEOF(check,values){
	var result=false;
	values.each(function(v){if(check==v)result=true;});
	return result;
}
function ONENOTOF(check,values){
	result=false;
	values.each(function(v){if(check!=v)result=true;});
	return result;
}

function wr(q){document.write(q)};
function wri(q){document.write(q)};
function xmp(q){wri("<xmp>"+q+"</xmp>")};
function div(q){wri("<div>"+q+"</div>")};
function ce(q){return document.createElement(q)};
function ac(q,p){p.appendChild(q)};
function rc(q,p){p.removeChild(q)};
function px(q){return parseInt(q)+"px"};
function ascii(q){return String.fromCharCode(q)};

function count(q){
	if(typeof q.length!="undefined")return q.length;
	var t,i=0;
	for(t in q)i++;
	return i;
};
function global(k){
	if(arguments.length>1)window[k]=arguments[1];
	return window[k];
};

// fix both IE and Opera (adjust when they implement this method properly)
// http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html
if(Prototype.Browser.IE||Prototype.Browser.Opera){
	document.nativeGetElementById = document.getElementById;
	document.getElementById = function(id){
		var elem = document.nativeGetElementById(id);
		if(elem){
			if(elem.id == id){
				return elem;
			}else{
				for(var i=1;i<document.all[id].length;i++){
					if(document.all[id][i].id == id){
						return document.all[id][i];
					}
				}
			}
		}
		return null;
	};
}

function $EX(element){
	// Extract Value
	element=$(element);
	if(is.formElement(element))					return $F(element);
	if(is.Defined(element.innerHTML))			return element.innerHTML;
	return element;
}
function $FGet(element){
	var isArrayOfFormElements=false;
	if(is.Defined(element.length)){
		if(element.length>0){
			if(is.Defined(element[0].tagName)){
				var tag=element[0].tagName.toUpperCase();
				isArrayOfFormElements=ONEOF(tag,["INPUT","TEXTAREA","SELECT"]);
			}
		}
	}
	if(isArrayOfFormElements){
		i=element;
	}else{
		q=$(element);
		// se non è l'elemento di una form: return false
		if(!is.formElement(element))return false;
		// se non ha un nome: return value
		if(is.Empty(q.name))return $F(q);
		// se invece ha un nome: recupero l'elemento tramite il suo nome
		var i=q.form.elements[q.name];
		// controllo se è un array di elementi
		if(!is.Defined(i.length)){
			// se non è un array: return value
			return $F(i);
		}else if(is.Defined(i.options)){
			// se è una select: return value
			return $F(i);
		}
	}
	if(i[0].type=="radio"){
		// se è un array di radio: return array value
		for(var j=0;j<i.length;j++){
			if(i[j].checked)return i[j].value;
		}
		return null;
	}else{
		// se è un array di input: return array value
		var r=[];
		if(i[0].type=="checkbox"){
			// array di checkbox
			for(var j=0;j<i.length;j++){
				if(i[j].checked)r.push(i[j].value);
			}
		}else{
			// array di input text o textarea
			for(var j=0;j<i.length;j++){
				r.push(i[j].value);
			}
		}
		return r;
	}
}
function $FSet(element,value){
	// build my own Array.indexOf
	// because actual Prototype version (1.6.0.2) uses "===" operator
	// instad of "==" operator
	function $FSet_indexOf(ago,pagliaio){
		var l=pagliaio.length;
		for(var i=0;i<l;i++)if(pagliaio[i]==ago)return i;
		return -1;
	}
	var isArrayOfFormElements=false;
	if(is.Defined(element.length)){
		if(element.length>0){
			if(is.Defined(element[0].tagName)){
				var tag=element[0].tagName.toUpperCase();
				isArrayOfFormElements=ONEOF(tag,["INPUT","TEXTAREA","SELECT"]);
			}
		}
	}
	if(isArrayOfFormElements){
		i=element;
	}else{
		q=$(element);
		if(!is.formElement(element))return false;
		if(!is.Empty(q.name))i=q.form.elements[q.name];
		else i=q;
	}
	if(is.Defined(i.options)){
		if(!is.Array(value))value=(function(){v=[];v[0]=value;return v;})();
		for(var j=0;j<q.options.length;j++){
			var o=q.options[j];
			o.selected=($FSet_indexOf(o.value,value)!=-1)?1:0;
		}
	}else if(!is.Defined(i.length)){
		i.value=value;
	}else if(i[0].type=="radio"){
		value=$A(value);
		for(var j=0;j<i.length;j++){
			var o=i[j];
			o.checked=($FSet_indexOf(o.value,value)!=-1)?1:0;
		}
	}else{
		value=$A(value);
		if(i[0].type=="checkbox"){
			for(var j=0;j<i.length;j++){
				var o=i[j];
				o.checked=($FSet_indexOf(o.value,value)!=-1)?1:0;
			}
		}else{
			for(var j=0;j<i.length;j++){
				var o=i[j];
				if(is.Defined(value[j]))o.value=value[j];
			}
		}
	}
	return $(element);
}

Element.addMethods({
	
	// Forms
	
	getFormElements:function(element){
		return [$(element).select("INPUT"),$(element).select("TEXTAREA"),$(element).select("SELECT")].flatten();
	},
	get:function(element){
		return $FGet(element);
	},
	set:function(element,value){
		return $FSet(element,value);
	},
	getIndex:function(element){
		// WORK IN PROGRESS: NON SOLO SELECT
		q=$(element);
		if(q.tagName!="SELECT")return -1;
		if(arguments.length==1)return q.options.selectedIndex;
		
		var value=arguments[1];
		var r=[];
		$A(q.options).each(function(o,i){
			if(o.value==value)r.push(i);
		});
		return (r.length==1)?r[0]:r;
		return q;
	},
	setIndex:function(element,index){
		// WORK IN PROGRESS: NON SOLO SELECT
		q=$(element);
		if(q.tagName!="SELECT")return -1;
		$A(index).each(function(v){
			q.options[v].selected=1;
		})
		return q;
	},
	
	// Checks
	
	is:function(element,what){
		switch(what){
			case"Num":			return is.Num($EX(element));			break;
			case"Int":			return is.Int($EX(element));			break;
			case"Float":		return is.Float($EX(element));			break;
			case"Empty":		return is.Empty($EX(element));			break;
			case"Email":		return is.Email($EX(element));			break;
			case"Url":			return is.Url($EX(element));			break;
			case"CreditCard":	return is.CreditCard($EX(element));		break;
			case"CodiceFiscale":return is.CodiceFiscale($EX(element));	break;
			case"PIVA":			return is.PIVA($EX(element));			break;
			case"Tel":			return is.Tel($EX(element));			break;
			case"formElement":	return is.formElement(element);			break;
			//	various
			case"positioned":	return is.positioned(element);			break;
		}
	},
	
	// Position
	
	setDimensions:function(element,dim){
		var d=$A(dim),element=$(element);
		$(element).style.width=px(d[0]);
		$(element).style.height=px(d[1]);
		return element;
	},
	setWidth:function(element,dim){
		$(element).style.width=parseInt(dim)+"px";
		return element;
	},
	setHeight:function(element,dim){
		$(element).style.height=parseInt(dim)+"px";
		return element;
	},
	setLeft:function(element,left){
		$(element).style.left=parseInt(left)+"px";
		return element;
	},
	setTop:function(element,top){
		$(element).style.top=parseInt(top)+"px";
		return element;
	},
	setMidLeft:function(element,left){
		$(element).style.left=(parseInt(left)-Element.getDimensions(element).width/2)+"px";
		return element;
	},
	setMidTop:function(element,top){
		$(element).style.top=(parseInt(top)-Element.getDimensions(element).height/2)+"px";
		return element;
	},
	setPos:function(element,pos){
		element=$(element);
		if(element.is("positioned")){
			pos=$A(pos);
			element.style.left=pos[0]+"px";
			element.style.top=pos[1]+"px";
		}
		return element;
	},
	setMid:function(element,pos){
		element=$(element);
		if(element.is("positioned")){
			pos=$A(pos);
			var dim=element.getDimensions();
			element.style.left=(pos[0]-dim.width/2)+"px";
			element.style.top=(pos[1]-dim.height/2)+"px";
		}
		return element;
	},
	getPos:function(element){
		element=$(element);
		if(element.is("positioned")){
			//return [parseInt(element.style.left),parseInt(element.style.top)];
			return element.cumulativeOffset();
		}else{
			return element.cumulativeOffset();
		}
	},
	getMid:function(element){
		element=$(element);
		var pos,dim=Element.getDimensions(element);
		if(element.is("positioned")){
			//pos=[parseInt(element.style.left),parseInt(element.style.top)];
			pos=element.cumulativeOffset();
		}else{
			pos=element.getOffsetParent().cumulativeOffset();
		}
		return [pos[0]+dim.width/2,pos[1]+dim.height/2];
	},
	
	// Flash
	
	swfobject:function(element,src,width,height){
		element=$(element);
		if(typeof swfobject!="undefined"){
			var o=arguments[4]||{};
			var id=element.identify();
			var version=is.Defined(o.version)?o.version:"9.0.0";
			var expressInstall=is.Defined(o.expressInstall)?o.expressInstall:false;
			var flashvars=is.Defined(o.flashvars)?o.flashvars:false;
			var params=is.Defined(o.params)?o.params:{};
			var attributes=is.Defined(o.attributes)?o.attributes:false;
			if(!is.Defined(params.wmode))params.wmode='opaque';
			swfobject.embedSWF(src,id,width,height,version,expressInstall,flashvars,params,attributes);
		}else{
			element.insert('<div><a href="http://code.google.com/p/swfobject/" target="_blank" style="color:#f00;">SWFOBJECT NOT FOUND</a></div>');
		}
	},
	
	// Miscellaneous
	
	index:function(element){
		return element.up().childElements().indexOf(element);
	}
	
}); 

var is = {
	// enviroment
	global:function(q){
		return window[q]!="undefined";
	},
	// browser
	IE: Prototype.Browser.IE,
	Opera: Prototype.Browser.Opera,
	WebKit: Prototype.Browser.WebKit,
	Gecko: Prototype.Browser.Gecko,
	Win:navigator.appVersion.toLowerCase().indexOf("win")!=-1,
	Mac:navigator.userAgent.indexOf("Mac")!=-1,
	// objects
	formElement: function(q){
		q=$(q);
		if(q)switch(q.tagName.toUpperCase()){case"TEXTAREA":case"INPUT":case"SELECT":return true;}
		return false;
	},
	// normal types
	S : function(q){ return typeof q == "string" },
	B : function(q){ return typeof q == "boolean" },
	N : function(q){ return typeof q == "number" },
	F : function(q){ return typeof q == "function" },
	O : function(q){ return typeof q == "object" },
	U : function(q){ return typeof q == "undefined" },
	// special types
	Date : function(q){
		return Object.prototype.toString.call(q) === '[object Date]'; 
	},
	Array   : function(q){
		return Object.prototype.toString.call(q) === '[object Array]'; 
	},
	Object  : function(q){ return !is.Array(q) && !is.Date(q) && is.O(q) },
	Defined : function(q){ return !is.U(q) },
	Null    : function(q){ return is.O(q) && q==undefined },
	// validation
	RealDate:function(yyyy,mm,gg){
		function y2k(q){return(q<1000)?q+1900:q;}
		var today=new Date();
		yyyy = ((!yyyy) ? y2k(today.getFullYear()):yyyy)
		mm = ((!mm) ? today.getMonth():mm-1)
		if (!gg) return false
		var test = new Date(yyyy,mm,gg)
		if ((y2k(test.getFullYear()) == yyyy) && (mm == test.getMonth()) && (gg == test.getDate()) ){
			return true
		}else{
			return false

		}
	},
	Num     : function(q){
		if(is.N(q))return true;
		var str=String(q);
		var re = /^[\-\+]{0,1}[0-9]+\.{0,1}[0-9]*$/;
		return re.test(str);
	},
	Int     : function(q){
		var str=String(q);
		var re = /^[\-]{0,1}[0-9]+$/;
		return re.test(str);
	},
	Float   : function(q){
		var str=String(q);
		var re = /^[\-]{0,1}[0-9]+\.[0-9]+$/;
		return re.test(str);
	},
	Empty	: function(q){
		var str=String(q);
		return (is.S(str)||is.N(str))?(String(str).trim()==""):false;
		
	},
	Email  : function(q){
		var str=String(q);
		var re = /^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\.\-]+$/i;
		return re.test(str);
	},
	Url    : function(q){
		var str=String(q);
		var re = /^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*\.)+([a-z]{2,6})|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&amp;]*)?)?(#[a-z][a-z0-9_]*)?$/i;
		return re.test(str);
	},
	CreditCard : function(q) {
		// Encoding only works on cards with less than 19 digits
		var str=String(q);
		if(typeof str!="string")return false;
		if (str.length > 19)return (false);
		var sum=0, mul=1, l=str.length;
		for (i = 0; i < l; i++) {
			var digit = str.substring(l-i-1,l-i);
			var tproduct = parseInt(digit ,10)*mul;
			sum += (tproduct >= 10) ? ((tproduct%10)+1) : tproduct ;
			mul += (mul == 1) ? 1 : -1 ;
		}
		return ((sum % 10)==0) ;
	},
	CodiceFiscale : function(q){
		var str=String(q);
		var re = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/i;
		return re.test(str);
	},
	PIVA : function(q){
		var str=String(q);
		var re = /^\d{11}$/;
		return re.test(str);
	},
	Tel : function(q){
		var str=String(q);
		var re = /^\+{0,1}[\d\s\-\.\(\)\[\]]+$/;
		return re.test(str);
	},
	//	various
	positioned:function(element){
		element=$(element);
		var p=element.getStyle("position");
		return p=='absolute'||p=='relative';
	}
}

var Cookie = {
  set: function(name, value, o) {
	var daysToExpire,path;
	if(typeof o=="undefined"){
		daysToExpire=365*2;
		path="/";
	}else{
		if(is.Num(o))daysToExpire=o;
		else if(typeof o.expire!="undefined")daysToExpire=o.expire;
		else daysToExpire=365*2;
		if(is.Num(o))path="/";
		else if(typeof o.path!="undefined")path=o.path;
		else path="/";
	}
	
 	var expire = '';
	if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
	var path = '; path='+path;
	
	
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  del: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  isEnabled: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.del('_test') === '1');
  },
  exists: function(name){
	return !(Cookie.get(name)===null);
  }
};

Object.extend(String.prototype, {
	find: function(q){return this.indexOf(q) != - 1;},
	zeroFill:function(){
		var q=arguments[0]||2;

		if(!is.Num(this))return this;
		else return (this*1).zeroFill(q);
	},
	timestamp2date:function(q){
		q=this.replace(/\D/g,"");
		return new Date(q.substr(0,4),q.substr(4,2)-1,q.substr(6,2),q.substr(8,2),q.substr(10,2),q.substr(12,2));
	},
	fileext:function(){
		var s = this;
		if(s.indexOf("?")!=-1)s=s.substr(0,s.indexOf("?"));
		if(s.indexOf("#")!=-1)s=s.substr(0,s.indexOf("#"));
		return (s.lastIndexOf(".")!=-1) ? s.substring(s.lastIndexOf(".")+1,s.length) : s ;
	},
	filename:function(){
		var s = this;
		if(s.indexOf("?")!=-1)s=s.substr(0,s.indexOf("?"));
		if(s.indexOf("#")!=-1)s=s.substr(0,s.indexOf("#"));
		return (s.lastIndexOf("/")!=-1) ? s.substring(s.lastIndexOf("/")+1,s.length) : s ;
	},
	trim:function(){
		  return this.replace(/^[\n\r\t\v\f\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+/, '').replace(/[\n\r\t\v\f\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+$/, '');
	},
	lower:function(){
		return this.toLowerCase();
/*
		var i,s=this.toLowerCase(),extended=arguments[0]||false;
		var from=(extended)?[jPrototype.uc1,jPrototype.uc2].flatten():jPrototype.uc1;
		var to=(extended)?[jPrototype.lc1,jPrototype.lc2].flatten():jPrototype.lc1;
		var q=from.lenght;
		for(i=0;i<q;i++)if(s.indexOf(from[i])!=-1)s=s.split(from[i]).join(to[i]);
		return s;
*/
	},
	upper:function(){
		return this.toUpperCase();
/*
		var i,s=this.toUpperCase(),extended=arguments[0]||false;
		var from=(extended)?[jPrototype.lc1,jPrototype.lc2].flatten():jPrototype.lc1;
		var to=(extended)?[jPrototype.uc1,jPrototype.uc2].flatten():jPrototype.uc1;
		var q=from.lenght;
		for(i=0;i<q;i++)if(s.indexOf(from[i])!=-1)s=s.split(from[i]).join(to[i]);
		return s;
*/
	},
	toPermalink:function(){
		var p=this.toLowerCase();
		var m=p.match(/[^0-9a-z]/g);
		if(!m)return p;
		m.uniq().each(function(v){
			var r=new RegExp("\\"+v,"g");
			var i=jPrototype.lc.indexOf(v);
			if(i!=-1){
				p=p.replace(r,jPrototype.eq[jPrototype.lc.indexOf(v)]);
			}else{
				p=p.replace(r,"-");
			}
		});
		
		while(p.indexOf("--")!=-1){
			p=p.replace(/--/,"-");
		}
		if(p.indexOf("-")==0)p=p.substring(1);
		if(p.lastIndexOf("-")==p.length-1)p=p.substring(0,p.length-1);
		if(p.length>255)p=p.substring(0,255);
		return p;
	},
	parseNumbers:function(){
		return this.match(/-{0,1}\d+(\.\d+)*/g);
	},
	parseIntegers:function(){
		var s=this.parseNumbers();
		var r=[]
		s.each(function(i){
			r.push(parseInt(i));
		})
		return r;
	},
	parseIDs:function(){
		var s=this.parseNumbers();
		var r=[]
		s.each(function(i){
			if( i*1>0 && i==parseInt(i) ){
				r.push(parseInt(i));
			}
		})
		return r;
	},
	parseEmails:function(){
		return this.match(/[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\.\-]+/g);
	},
	parseLinks: function(q){
		return this.match(/((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*\.)+([a-z]{2,6})|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&amp;]*)?)?(#[a-z][a-z0-9_]*)?/g);
	}
});

// navigator.version
if(is.IE){
	navigator.version=navigator.userAgent.split("MSIE ")[1].split(" ")[0].replace(";","");
}else if(is.Opera){
	navigator.version=navigator.userAgent.substring(navigator.userAgent.lastIndexOf("/")+1).split(" ")[0];
}else if(is.Gecko){
	navigator.version=navigator.userAgent.split("; rv:")[1].split(")")[0];
}else if(is.WebKit){
	navigator.version=navigator.userAgent.split("AppleWebKit/")[1].split(" ")[0];
}else{
	navigator.version=navigator.userAgent.substring(navigator.userAgent.lastIndexOf("/")+1)
}
navigator.lowerThan=function(a){
	a=String(a).split(".");b=navigator.version.split(".");
	var q=Math.max(a.length,b.length);
	for(var i=0;i<q;i++){
		var v1=1*((typeof a[i]!="undefined")?a[i]:0);
		var v2=1*((typeof b[i]!="undefined")?b[i]:0);
		if(v1>v2)return true;
	}
	return false;
}
navigator.higherThan=function(a){
	a=String(a).split(".");b=navigator.version.split(".");
	var q=Math.max(a.length,b.length);
	for(var i=0;i<q;i++){
		var v1=1*((typeof a[i]!="undefined")?a[i]:0);
		var v2=1*((typeof b[i]!="undefined")?b[i]:0);
		if(v1>v2)return false;
	}
	return true;
}
navigator.equalTo=function(a){
	a=String(a).split(".");b=navigator.version.split(".");
	var q=Math.max(a.length,b.length);
	for(var i=0;i<q;i++){
		var v1=(typeof a[i]!="undefined")?a[i]:0;
		var v2=(typeof b[i]!="undefined")?b[i]:0;
		if(v1!=v2)return false;
	}
	return true;
}

Object.extend(Number.prototype, {
	prev: function(){return this - 1;},
	next: function(){return this + 1;},
	zeroFill:function(){
		var q=arguments[0]||2;
		var s=String(this);
		var isFloat=s.indexOf(".")!=-1;
		var isNegative=s.indexOf("-")==0;
		
		if(isFloat){
			var int=s.substring(isNegative?1:0,s.lastIndexOf("."));
			var float=s.substring(s.lastIndexOf(".")+1);
		}else{
			var int=s.substring(isNegative?1:0);
			var float="";
		}
		
		if(q>=0){
			if(int.length>=q)return s;
			var r=int;
			for(var i=int.length;i<q;i++)r="0"+r;
			if(isNegative)r="-"+r;
			if(isFloat)r+="."+float;
		}else{
			q*=-1;
			if(float.length>=q)return s;
			var r=((isNegative)?"-":"")+int+"."+float;
			for(var i=float.length;i<q;i++)r+="0";
		}
		return r;
	},
	timestamp2date:function(){
		q=this.replace(/\D/g,"");
		return new Date(q.substr(0,4),q.substr(4,2)-1,q.substr(6,2),q.substr(8,2),q.substr(10,2),q.substr(12,2));
	}
});

Object.extend(Math,{
	baseConvert:function(n,b1,b2){return parseInt(String(n),b1).toString(b2).toUpperCase();},
	gra2rad:function(G){return G*Math.PI/180;},
	rad2gra:function(R){return R*180/Math.PI;}
});

Object.extend(Form,{
	submit:function(form){
		form=$(form);
		if(form.onsubmit!=null){
			switch(form.onsubmit()){
				case true:case undefined:form.submit();
			}
		}else form.submit();
	}
});

Function.prototype.name=function(q){
	// q can be a function or an "arguments.callee"
	var results = String(q).match(/function (\S+)\(/); // in Opera the regexp doesn't work if i put "^" at the beginning
	if(results)if(results.length>1)return results[1];
	return null;
}

Object.extend(window,{
	getScroll:function(){
		return document.viewport.getScrollOffsets();
	},
	getDimensions:function(){
		return document.viewport.getDimensions();
	},
	pop:function(){
		// pop ( href [,target] [,x] [,y] [,"maximized"] [,"fullscreen"] [,"noresize"] [,"nocenter"] [,"scroll"] [,"return"] )
		// eg: pop('http://www.google.com',400,300,'myTarget','scroll')
		if(arguments.length>0){
			_url=arguments[0];
			var x,y,o,_target="",_params=[],center=true,maximized=false,fullscreen=false,resizable=true,scroll=false,returnObj=false;
			if(!document.all || (document.all && navigator.userAgent.indexOf("Mac")!=-1) ){
				for(i=1;i<arguments.length;i++){
					if(arguments[i]=="fullscreen"){
						arguments[i]="maximized";
						break;
					}
				}
			}
			if(arguments.length>1){
				for(i=1;i<arguments.length;i++){
					if(isNaN(arguments[i])){
						switch(arguments[i]){
							case"nocenter":
								center=false;
							break;
							case"scroll":
								scroll=true;
							break;
							case"maximized":
								maximized=true;
								_params[_params.length]="left=0";
								_params[_params.length]="top=0";
								_params[_params.length]="width="+(screen.width-6);
								_params[_params.length]="height="+(screen.height-26);
							break;
							case"fullscreen":
								fullscreen=true;
								_params[_params.length]="fullscreen=yes";
								if(document.all)_params[_params.length]="channelmode=yes"; 
							break;
							case"noresize":
								resizable=false;
								_params[_params.length]="resizable=no";
							break;
							case"return":
								returnObj=true;
							break;
							default:
								_target=arguments[i];
							break;
						}
					}
				}
				if(!fullscreen && !window[_target])_params[_params.length]="scrollbars="+((scroll)?"yes":"no");
				if(!maximized && !fullscreen &&  !window[_target]){
					for(i=1;i<arguments.length;i++){
						if(!isNaN(arguments[i]) && !maximized){
							if(x==undefined){
								x=arguments[i];
								_params[_params.length]="width="+x;
							}else{
								y=arguments[i];
								_params[_params.length]="height="+y;
							}
						}
					}
					if(center && !window[_target]){
						_params[_params.length]="left="+((screen.width-x)/2);
						_params[_params.length]="top="+((screen.height-y)/2);
					}
				}
			}
			o=window.open(_url,_target,_params.join(","));
			if(o==undefined)alert("L'apertura della finestra è stata bloccata");
			if(returnObj)return o;
		}
	}
});

Object.extend(Date.prototype,{
	toTimestamp:function(){
		var Y=this.getFullYear();
		var m=(this.getMonth()+1).zeroFill();
		var d=(this.getDate()).zeroFill();
		var H=(this.getHours()).zeroFill();
		var i=(this.getMinutes()).zeroFill();
		var s=(this.getSeconds()).zeroFill();
		return ""+Y+m+d+H+i+s;
	}
});

$_GET=location.href.toQueryParams();
$_SERVER={
	PHP_SELF:location.pathname,
	QUERY_STRING:location.search.substring(location.search.indexOf("?")==0?1:0)
};

/* ---------- /shared/js/jDate.js ---------- */

function jDate(){
//	example: var cal=new jDate();
//	example: var cal=new jDate(2007,11);
//	example: var cal=new jDate(2006,2,29);if(cal.exists)...

	this.Version='0.24';
	this.nightly='20090714';

	this.now = new Date();
	/* GENERIC FUNCTIONS */
	this.zeroFill=function(q){
		q=String(q);
		var zeri=arguments[1]||2;
		while(q.length<zeri)q="0"+q;
		return q;
	}
	// DATE FORMAT (PHP style: http://it2.php.net/manual/it/function.date.php )
	var args = [] ;
	var opts = [] ;
	for(var i=0;i<arguments.length;i++){
		if(isNaN(arguments[i]))opts[opts.length]=arguments[i];
		else args[args.length]=arguments[i];
	}
	var startingLang=(opts.length>0)?opts[0]:"it";
	
	this.j = (args.length>2)?args[2]*1:this.now.getDate();		// day
	this.n = (args.length>1)?args[1]*1:(this.now.getMonth()+1);	// month
	this.Y = (args.length>0)?args[0]*1:this.now.getFullYear();	// year
	this.G = (args.length>3)?args[3]*1:this.now.getHours();
	this.i = this.zeroFill((args.length>4)?args[4]*1:this.now.getMinutes());
	this.s = this.zeroFill((args.length>5)?args[5]*1:this.now.getSeconds());
	this.u = (args.length>6)?zeroFill(args[6]*1,3):this.now.getMilliseconds();
	
	// check for valid date (and declaration of "checkDate" method)
	this.checkDate=function(yyyy,mm,gg){
		function y2k(q){return(q<1000)?q+1900:q;}
		var today=new Date();
		yyyy = ((!yyyy) ? y2k(today.getFullYear()):yyyy)
		mm = ((!mm) ? today.getMonth():mm-1)
		if (!gg) return false
		var test = new Date(yyyy,mm,gg)
		if ((y2k(test.getFullYear()) == yyyy) && (mm == test.getMonth()) && (gg == test.getDate()) ){
			return true
		}else{
			return false
		}
	}

	this.exists=this.checkDate(this.Y,this.n,this.j);
	this.suffix=[
		"st","nd","rd","th","th","th","th","th","th","th",
		"th","th","th","th","th","th","th","th","th","th",
		"st","nd","rd","th","th","th","th","th","th","th",
		"st"
	];
		
	/* LANGUAGE */
	this.lngStr = [];

	this.lngStr.it = {
		"dayName":["Domenica","Luned"+String.fromCharCode(236),"Marted"+String.fromCharCode(236),"Mercoled"+String.fromCharCode(236),"Gioved"+String.fromCharCode(236),"Venerd"+String.fromCharCode(236),"Sabato"],
		"monthName":["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],
		"labels":["Mostra il mese precedente","Mostra il mese successivo","Calendario eventi di"]
	};
	this.lngStr.en = {
		"dayName":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
		"monthName":["January","February","March","April","May","June","July","August","September","October","November","December"],
		"labels":["Show previous month","Show next month","Events calendar of"]
	};
	this.lngStr.es = {
		"dayName":["Domingo","Lunes","Martes","Mi"+String.fromCharCode(233)+"rcoles","Jueves","Viernes","Sabado"],
		"monthName":["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
		"labels":["Show previous month","Show next month","Events calendar of"]
	};
	this.lngStr.fr = {
		"dayName":["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"],
		"monthName":["Janvier","F"+String.fromCharCode(233)+"vrier","Mars","Avril","Mai","Juin","Juillet","Ao"+String.fromCharCode(251)+"t","Septembre","Octobre","Novembre","D"+String.fromCharCode(233)+"cembre"],
		"labels":["Show previous month","Show next month","Events calendar of"]
	};
	this.lngStr.de = {
		"dayName":["Dienstag","Mittwoch","Donnerstag","Freitag","Samstag","Sonntag","Montag"],
		"monthName":["Januar","Februar","M"+String.fromCharCode(228)+"rz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],
		"labels":["Show previous month","Show next month","Events calendar of"]
	};
	this.lngStr.us = this.lngStr.en;
	
	this.firstDay=0;
	/* METHODS (checkDate already declared) */
	this.setFirstDay=function(q){
		var i,r=[],a=this.lngStr[this.lang].dayName;
		if(q>a.length||q<=0||isNaN(q)){
			this.lngStr.current.dayName=a;
		}else{
			for(i=q;i<a.length;i++)r[r.length]=a[i];
			for(i=0;i<q;i++)r[r.length]=a[i];
			this.lngStr.current.dayName=r;
		}
	}

	this.setFirstDay = function(q){
		// 0 sunday, 1 monday, ...
		this.firstDay=q;
	}
	this.setLang = function(q){
		var i,found=false;

		if(q!=this.lang){
			if(typeof this.lngStr[q] != "undefined"){
				this.lang = q;
				this.lngStr.current={"dayName":[],"monthName":[],"labels":[]};
				for(i=0;i<this.lngStr[q].dayName.length;i++)this.lngStr.current.dayName[i]=this.lngStr[q].dayName[i];
				for(i=0;i<this.lngStr[q].monthName.length;i++)this.lngStr.current.monthName[i]=this.lngStr[q].dayName[i];
				for(i=0;i<this.lngStr[q].labels.length;i++)this.lngStr.current.labels[i]=this.lngStr[q].labels[i];
				this.setFirstDay(this.firstDay);
				this.F = this.lngStr[this.lang].monthName[this.now.getMonth()];
				this.M = this.F.substring(0,3);
				this.l = this.lngStr[this.lang].dayName[this.now.getDay()]
				this.D = this.l.substring(0,3);
			}else{
				this.setLang('en');
			}
		}
	}

	// DATE FORMAT (PHP style: http://it2.php.net/manual/it/function.date.php )
	
	this.now.setFullYear(this.Y);
	this.now.setMonth(this.n-1);
	this.now.setDate((this.exists)?this.j:0);
	
	this.setLang(startingLang); // setting lang redefines F M l and D
	
	this.isBisestile=function(Y){
		return ((Y%4==0&&Y%100!=0)||Y%400==0)?1:0;
	}
	this.daysInMonth=function(n,Y){
		var isBisestile = ((Y%4==0&&Y%100!=0)||Y%400==0)?1:0;
		if(n==4||n==6||n==9||n==11)return 30;
		else if(n==1||n==3||n==5||n==7||n==8||n==10||n==12)return 31;
		else if(n==2)return (isBisestile)?29:28;
	}
	this.getWeek = function() {
		var onejan = new Date(this.Y,0,1);
		return Math.ceil((((this.now - onejan) / 86400000) + onejan.getDay())/7);
	}
	
	// Day
	this.d = this.zeroFill(this.j);
//	this.D : already set
//	this.j : already set
//	this.l : already set
	this.N = (this.now.getDay()>0)?this.now.getDay():7;
	this.S = this.suffix[this.j-1];
	this.w = this.now.getDay();
	this.z = 0;for(var i=0;i<this.n-1;i++)this.z+=this.daysInMonth(i+1);this.z += this.j - 1;
	
	// Week
	this.W = this.getWeek();
	
	// Month
//	this.F : already set
	this.m = this.zeroFill(this.n);
//	this.M : already set
//	this.n : already set
	this.t = this.daysInMonth(this.n,this.Y);
	
	// Year
	this.L = this.isBisestile(this.Y);
	this.o = this.Y
	if(this.W==1){
		var lastDayPrevYear=new Date(this.Y-1,11,31).getDay();
		if(lastDayPrevYear!=0)this.o = this.Y - 1;
	}else if(this.n==12&&this.j>31-7){
		var firstDayNextYear=new Date(this.Y+1,0,1).getDay();
		if(firstDayNextYear!=1)this.o = this.Y + 1;
	};
//	this.Y : already set
	this.y = String(this.Y).substr(2);
	
	// Time
	this.a = (this.G>0&&this.G<13)?"am":"pm";
	this.A = this.a.toUpperCase();
	this.B=Math.floor(((this.G-1) * 3600 + (this.i *60) + this.s * 1) * 1000 / 86400);
	if(this.B>=1000)this.B-=1000;
	else if(this.B<0)this.B+=1000;
	this.g = (this.G==0)?12:((this.G>12)?(this.G-12):this.G);
//	this.G : already set
	this.h = this.zeroFill(this.g);
	this.H = this.zeroFill(this.G);
//	this.i : already set
//	this.s : already set
//	this.u : already set
	
	// Timezone	
	// Ora legale
	var date1 = new Date(this.Y, 0, 1, 0, 0, 0, 0);
	var date2 = new Date(this.Y, 6, 1, 0, 0, 0, 0);
	var temp = date1.toGMTString();
	var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var temp = date2.toGMTString();
	var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
	var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
	var TimeZone = hoursDiffStdTime; // es: GMT+100 = 1 ; es ora legale: GMT+200 = 1;
	var isDstObserved = (hoursDiffDaylightTime != hoursDiffStdTime);
	
	this.e = "*UNSUPPORTED*";
	this.O = String(this.now);
	this.O = this.O.substr(this.O.indexOf("+"),5);
	this.I = ( hoursDiffStdTime != parseInt((this.O*1)/100) && isDstObserved ) ? 1 : 0;
	this.P = this.O.substr(0,3)+":"+this.O.substr(3,2);
	this.T = "*UNSUPPORTED*";
	this.Z = this.O/100*60*60;
	
	// Full Date/Time
	this.c = this.Y+"-"+this.m+"-"+this.d+"T"+this.H+":"+this.i+":"+this.s+this.P;
	this.r = this.lngStr.en.dayName[this.w].substr(0,3)+", "+this.d+" "+this.lngStr.en.monthName[this.n-1].substr(0,3)+" "+this.Y+" "+this.H+":"+this.i+":"+this.s+" "+this.O;
	this.U = Math.floor(this.now.getTime()/1000);
	
	this.format=function(formato){
		var s="";
		for(var i=0;i<formato.length;i++){
			var letter=formato.charAt(i);
			s+=(typeof this[letter]!="undefined")?this[letter]:letter;
		}
		return s;
	}
	this.toDate=function(){
		return this.now;
	}
}

Object.extend(Date.prototype,{
	tojDate:function(){
		return new jDate(this.getFullYear(),this.getMonth()+1,this.getDate());
	},
	addDate:function(q){
		q=arguments[0]||q;
		var d=this.setDate(this.getDate()+q);
		return this;
	},
	addWeek:function(q){
		q=arguments[0]||q;
		var d=this.setDate(this.getDate()+q*7);
		return this;
	},
	addMonth:function(q){
		q=arguments[0]||q;
		this.setMonth(this.getMonth()+q);
		return this;
	},
	addYear:function(q){
		q=arguments[0]||q;
		var d=this.setFullYear(this.getFullYear()+q);
		return this;
	}
});

Object.extend(String.prototype, {
	timestamp2jDate:function(){
		var q=this.replace(/\D/g,"");
		return new jDate(q.substr(0,4),q.substr(4,2),q.substr(6,2),q.substr(8,2),q.substr(10,2),q.substr(12,2));
	}
});

/* ---------- /shared/js/jMouse.js ---------- */

var jMouse = {
	Version: '0.16',
	nightly: '20090903',
	onMove:function(f){
		var useCapture=arguments[1]||true;
		Event.observe(window,"load",f,useCapture);
		Event.observe(document,"mousemove",f,useCapture);
	},
	onWheel:function(f){
		var e=arguments[1]||document;
		var useCapture=arguments[2]||true;
		Event.observe(e,"mousewheel",f,useCapture);
		Event.observe(e,"DOMMouseScroll",f,useCapture); // Firefox
	},
	x:-1,
	y:-1,
	getCoords:function(e){
		jMouse.x=Event.pointerX(e);
		jMouse.y=Event.pointerY(e);
	},
	fromElement:function(e){
		if (!e) var e = window.event;
		var relTarg = e.relatedTarget || e.fromElement;
		return relTarg;
	},
	toElement:function(e){
		if (!e) var e = window.event;
		var relTarg = e.relatedTarget || e.toElement;
		return relTarg;
	}
};

jMouse.onMove(jMouse.getCoords);

var jTooltip = {
	show:function(){
		var t=$("jTooltip");
		if(t){
			jTooltip.move();
			if(arguments.length>0){
				t.innerHTML=arguments[0];
			}
			t.show();
		}
	},
	hide:function(){
			var t=$("jTooltip");
			if(t){
				t.hide();
			}
	},
	move:function(){
		
		                        var opt=arguments[0]||{};
		if(!is.Object(opt))     var opt={};
		                            opt.coords=[jMouse.x,jMouse.y];
		if(!is.Defined(opt.pos))    opt.pos="rT";
		var t=$("jTooltip");
		
		if(t){if(t.visible()){
			var xy = opt.coords ;
			var wh = Object.values(t.getDimensions());
			var WH = Object.values(window.getDimensions());
			
			var x = parseInt(xy[0]);
			var y = parseInt(xy[1]);
			var w = parseInt(wh[0]);
			var h = parseInt(wh[1]);
			var W = parseInt(WH[0]);
			var H = parseInt(WH[1]);
			
			var pos=String(opt.pos);
			var left = pos.charAt(0);
			var top  = pos.charAt(1);
			var margin = 6  ;
			var cursor = 16 ;
			
			switch(left){
				case"l":			x=x-w-margin;		break;
				case"c":			x=x-w/2;			break;
				case"r":default:	x=x+cursor+margin;	break;
			}
			switch(top){
				case"t":			y=y-h-margin;		break;
				case"b":			y=y+cursor+margin;	break;
				case"T":			y=y;				break;
				case"B":			y=y+cursor-h;		break;
				case"m":default:	y=y-h/2;			break;
			}
			
			var scrollAmount=window.getScroll();
			
			if(x<0)x=0;
			else if(x+w-scrollAmount[0]>W)x=W-w;
			if(y<0)y=0;
			else if(y+h-scrollAmount[1]>H)y=H-h;
			
			t.setPos([x,y]);
			
		}}
	},
	observe:function(e,txt){
		var align=arguments[2]||"rT";
		Event.observe(e,is.IE?'mouseenter':'mouseover',function(ev){
			jTooltip.show(txt);
		});
		Event.observe(e,is.IE?'mouseleave':'mouseout',function(ev){
			jTooltip.hide();
		});
		Event.observe(e,'mousemove',function(ev){
			jTooltip.move({pos:align});
		});
	},
	create:function(){
		if(!document.getElementById("jTooltip")){
			var body=$$("body")[0];
			var div=ce("div");
			div.id="jTooltip";
			div.style.display="none";
			div.style.position="absolute";
			ac(div,body);
			jTooltip.observe(div);
		}
	}
}

Event.observe(window,'load',jTooltip.create);

Object.extend(Event, {
	wheel:function (event){
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta) {
			delta = event.wheelDelta/120; 
			if (window.opera) delta = -delta;
		} else if (event.detail) { delta = -event.detail/3;	}
		if(event.preventDefault)event.preventDefault();
		return Math.round(delta); //Safari Round
	}
});

Element.addMethods({
	onWheel:function(element,f){
		jMouse.onWheel(f,element);
	},
	tooltip:function(element,txt){
		var align=arguments[2]||"rT";
		jTooltip.observe(element,txt,align);
	}
});

Object.extend(is,{
	leftClick:function(e){
		return Event.isLeftClick(e);
	},
	middleClick:function(e){
		var middleclick;
		if (!e) var e = window.event;
		if (e.which) middleclick = (e.which == 2);
		else if (e.button) middleclick = (e.button == 4);
		return 	middleclick;
	},
	rightClick:function(e){
		var rightclick;
		if (!e) var e = window.event;
		if (e.which) rightclick = (e.which == 3);
		else if (e.button) rightclick = (e.button == 2);
		return 	rightclick;
	}
});

/* ---------- /shared/js/swfobject.js ---------- */

/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		
		win = window,
		doc = document,
		nav = navigator,
		
		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;
	
	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/ 
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors 
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();
	
	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}
	
	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}
	
	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks 
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},
		
		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {}; 
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					if (att.id == replaceElemIdStr) {
						setVisibility(replaceElemIdStr, true);
					}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			} 
		}
	};
}();


/* ---------- /shared/js/lightwindow.js ---------- */

// lightwindow.js v2.0
//
// Copyright (c) 2007 stickmanlabs
// Author: Kevin P Miller | http://www.stickmanlabs.com
// 
// LightWindow is freely distributable under the terms of an MIT-style license.
//
// I don't care what you think about the file size...
//   Be a pro: 
//	    http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
//      http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
//

/*-----------------------------------------------------------------------------------------------*/

if(typeof Effect == 'undefined')
  throw("lightwindow.js requires including script.aculo.us' effects.js library!");

// This will stop image flickering in IE6 when elements with images are moved
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}

var lightwindow = Class.create();	
lightwindow.prototype = {
	//
	//	Setup Variables
	//
	element : null,
	contentToFetch : null,
	windowActive : false,
	dataEffects : [],
	dimensions : {
		cruft : null,
		container : null,
		viewport : {
			height : null,
			width : null,
			offsetTop : null,
			offsetLeft : null
		}
	},
	pagePosition : {
		x : 0,
		y : 0
	},
	pageDimensions : {
		width : null,
		height : null
	},
	preloadImage : [],
	preloadedImage : [],
	galleries : [],
	resizeTo : {
		height : null,
		heightPercent : null,
		width : null,
		widthPercent : null,
		fixedTop : null,
		fixedLeft : null
	},
	scrollbarOffset : 18,
	navigationObservers : {
		previous : null,
		next : null
	},
	containerChange : {
		height : 0,
		width : 0
	},
	activeGallery : false,
	galleryLocation : {
		current : 0,
		total : 0
	},
	//
	//	Initialize the lightwindow.
	//
	initialize : function(options) {
		this.options = Object.extend({
			resizeSpeed : 8,
			contentOffset : {
				height : 20,
				width : 20
			},
			dimensions : {
				image : {height : 250, width : 250},
				page : {height : 250, width : 250},
				inline : {height : 250, width : 250},
				media : {height : 250, width : 250},
				external : {height : 250, width : 250},
				titleHeight : 25
			},
			classNames : {	
				standard : 'lightwindow',
				action : 'lightwindow_action'
			},
			fileTypes : {
				page : ['asp', 'aspx', 'cgi', 'cfm', 'htm', 'html', 'pl', 'php4', 'php3', 'php', 'php5', 'phtml', 'rhtml', 'shtml', 'txt', 'vbs', 'rb'],
				media : ['aif', 'aiff', 'asf', 'avi', 'divx', 'm1v', 'm2a', 'm2v', 'm3u', 'mid', 'midi', 'mov', 'moov', 'movie', 'mp2', 'mp3', 'mpa', 'mpa', 'mpe', 'mpeg', 'mpg', 'mpg', 'mpga', 'pps', 'qt', 'rm', 'ram', 'swf', 'viv', 'vivo', 'wav'],
				image : ['bmp', 'gif', 'jpg', 'png', 'tiff']
			},
			mimeTypes : {
				avi : 'video/avi',
				aif : 'audio/aiff',
				aiff : 'audio/aiff',
				gif : 'image/gif',
				bmp : 'image/bmp',
				jpeg : 'image/jpeg',
				m1v : 'video/mpeg',
				m2a : 'audio/mpeg',
				m2v : 'video/mpeg',
				m3u : 'audio/x-mpequrl',
				mid : 'audio/x-midi',
				midi : 'audio/x-midi',
				mjpg : 'video/x-motion-jpeg',
				moov : 'video/quicktime',
				mov : 'video/quicktime',
				movie : 'video/x-sgi-movie',
				mp2 : 'audio/mpeg',
				mp3 : 'audio/mpeg3',
				mpa : 'audio/mpeg',
				mpa : 'video/mpeg',
				mpe : 'video/mpeg',
				mpeg : 'video/mpeg',
				mpg : 'audio/mpeg',
				mpg : 'video/mpeg',
				mpga : 'audio/mpeg',
				pdf : 'application/pdf',
				png : 'image/png',
				pps : 'application/mspowerpoint',
				qt : 'video/quicktime',
				ram : 'audio/x-pn-realaudio-plugin',
				rm : 'application/vnd.rn-realmedia',
				swf	: 'application/x-shockwave-flash',
				tiff : 'image/tiff',
				viv : 'video/vivo',
				vivo : 'video/vivo',
				wav : 'audio/wav',
				wmv : 'application/x-mplayer2'			
			},	
			classids : {
				mov : 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
				swf : 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
				wmv : 'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6'
			},
			codebases : {
				mov : 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
				swf : 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0',
				wmv : 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715'
			},	
			viewportPadding : 10,
			EOLASFix : 'swf,wmv,fla,flv',
			overlay : {
				opacity : 0.7,
				image : 'images/black.png',
				presetImage : 'images/black-70.png'
			},
			skin : 	{
				main : 	'<div id="lightwindow_container" >'+
							'<div id="lightwindow_title_bar" >'+
								'<div id="lightwindow_title_bar_inner" >'+
									'<span id="lightwindow_title_bar_title"></span>'+
									'<a id="lightwindow_title_bar_close_link" >close</a>'+
								'</div>'+
							'</div>'+
							'<div id="lightwindow_stage" >'+
								'<div id="lightwindow_contents" >'+
								'</div>'+
								'<div id="lightwindow_navigation" >'+
									'<a href="#" id="lightwindow_previous" >'+
										'<span id="lightwindow_previous_title"></span>'+
									'</a>'+
									'<a href="#" id="lightwindow_next" >'+
										'<span id="lightwindow_next_title"></span>'+
									'</a>'+
									'<iframe name="lightwindow_navigation_shim" id="lightwindow_navigation_shim" src="javascript:false;" frameBorder="0" scrolling="no"></iframe>'+
								'</div>'+								
								'<div id="lightwindow_galleries">'+
									'<div id="lightwindow_galleries_tab_container" >'+
										'<a href="#" id="lightwindow_galleries_tab" >'+
											'<span id="lightwindow_galleries_tab_span" class="up" >Galleries</span>'+
										'</a>'+
									'</div>'+
									'<div id="lightwindow_galleries_list" >'+
									'</div>'+
								'</div>'+
							'</div>'+
							'<div id="lightwindow_data_slide" >'+
								'<div id="lightwindow_data_slide_inner" >'+
									'<div id="lightwindow_data_details" >'+
										'<div id="lightwindow_data_gallery_container" >'+
											'<span id="lightwindow_data_gallery_current"></span>'+
											' of '+
											'<span id="lightwindow_data_gallery_total"></span>'+
										'</div>'+
										'<div id="lightwindow_data_author_container" >'+
											'by <span id="lightwindow_data_author"></span>'+
										'</div>'+
									'</div>'+
									'<div id="lightwindow_data_caption" >'+
									'</div>'+
								'</div>'+
							'</div>'+
						'</div>',	
				loading : 	'<div id="lightwindow_loading" >'+
								'<img src="/shared/images/ajax-loading.gif" alt="loading" />'+
								'<span>Loading or <a href="javascript: myLightWindow.deactivate();">Cancel</a></span>'+
								'<iframe name="lightwindow_loading_shim" id="lightwindow_loading_shim" src="javascript:false;" frameBorder="0" scrolling="no"></iframe>'+
							'</div>',
				iframe : 	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
							'<html xmlns="http://www.w3.org/1999/xhtml">'+
								'<body>'+
									'{body_replace}'+
								'</body>'+
							'</html>',
				gallery : {
					top :		'<div class="lightwindow_galleries_list">'+
									'<h1>{gallery_title_replace}</h1>'+
									'<ul>',
					middle : 			'<li>'+
											'{gallery_link_replace}'+
										'</li>',
					bottom : 		'</ul>'+
								'</div>'
				}
			},
			formMethod : 'get',
			hideFlash : false,
			hideGalleryTab : false,
			showTitleBar : true,
			animationHandler : false,
			navigationHandler : false,
			transitionHandler : false,
			finalAnimationHandler : false,
			formHandler : false,
			galleryAnimationHandler : false,
			showGalleryCount : true
		}, options || {});
		this.duration = ((11-this.options.resizeSpeed)*0.15);
		this._setupLinks();
		this._getScroll();
		this._getPageDimensions();
		this._browserDimensions();
		this._addLightWindowMarkup(false);
		this._setupDimensions(); 
		this.buildGalleryList();
	},
	//
	//	Activate the lightwindow.
	//
	activate : function(e, link){		
		// Clear out the window Contents
		this._clearWindowContents(true);
			
		// Add back in out loading panel
		this._addLoadingWindowMarkup();

		// Setup the element properties
		this._setupWindowElements(link);
		
		// Setup everything
		this._getScroll();
		this._browserDimensions();
		this._setupDimensions();
		this._toggleTroubleElements('hidden', false);
		this._displayLightWindow('block', 'hidden');
		this._setStatus(true);
		this._monitorKeyboard(true);
		this._prepareIE(true);
		this._loadWindow();
	},
	//
	//	Turn off the window
	//
	deactivate : function(){
		// The window is not active
		this.windowActive = false;
		
		// There is no longer a gallery active
		this.activeGallery = false;
		if (!this.options.hideGalleryTab) {
			this._handleGalleryAnimation(false);
		}
		
		// Kill the animation
		this.animating = false;
		
		// Clear our element
		this.element = null;
		
		// hide the window.
		this._displayLightWindow('none', 'visible');
		
		// Clear out the window Contents
		this._clearWindowContents(false);
		
		// Stop all animation
		var queue = Effect.Queues.get('lightwindowAnimation').each(function(e){e.cancel();});
		
		// Undo the setup
		this._prepareIE(false);
		this._setupDimensions();
		this._toggleTroubleElements('visible', false);	
		this._monitorKeyboard(false);	
	},
	//
	//  Initialize specific window
	//
	createWindow : function(element, attributes) {
		this._processLink($(element));
	},
	//
	//  Open a Window from a hash of attributes
	//
	activateWindow : function(options) {
		this.element = Object.extend({
			href : null,
			title : null,
			author : null,
			caption : null,
			rel : null,
			top : null,
			left : null,
			type : null,
			showImages : null,
			height : null,
			width : null,
			loadingAnimation : null,
			iframeEmbed : null,
			form : null
		}, options || {});
		
		// Set the window type
		this.contentToFetch = this.element.href;
		this.windowType = this.element.type ? this.element.type : this._fileType(this.element.href);	
		
		// Clear out the window Contents
		this._clearWindowContents(true);
			
		// Add back in out loading panel
		this._addLoadingWindowMarkup();
		
		// Setup everything
		this._getScroll();
		this._browserDimensions();
		this._setupDimensions();
		this._toggleTroubleElements('hidden', false);
		this._displayLightWindow('block', 'hidden');
		this._setStatus(true);
		this._monitorKeyboard(true);
		this._prepareIE(true);
		this._loadWindow();
	},
	//
	//  Fire off our Form handler
	//
	submitForm : function(e) {
		if (this.options.formHandler) {
			this.options.formHandler(e);
		} else {
			this._defaultFormHandler(e);
		}
	},
	//
	//	Reload the window with another location
	//
	openWindow : function(element) {
		var element = $(element);

		// The window is active
		this.windowActive = true;
		
		// Clear out the window Contents
		this._clearWindowContents(true);
		
		// Add back in out loading panel
		this._addLoadingWindowMarkup();
		
		// Setup the element properties
		this._setupWindowElements(element);

		this._setStatus(true);
		this._handleTransition();
	},
	//
	//  Navigate the window
	//
	navigateWindow : function(direction) {
		this._handleNavigation(false);
		if (direction == 'previous') {
			this.openWindow(this.navigationObservers.previous);
		} else if (direction == 'next'){ 
			this.openWindow(this.navigationObservers.next);
		}
	},
	//
	//  Build the Gallery List and Load it
	//
	buildGalleryList : function() {
		var output = '';
		var galleryLink;
		for (i in this.galleries) {
			if (typeof this.galleries[i] == 'object') {
				output += (this.options.skin.gallery.top).replace('{gallery_title_replace}', unescape(i));
				for (j in this.galleries[i]) {
					if (typeof this.galleries[i][j] == 'object') {						
						galleryLink = '<a href="#" id="lightwindow_gallery_'+i+'_'+j+'" >'+unescape(j)+'</a>';
						output += (this.options.skin.gallery.middle).replace('{gallery_link_replace}', galleryLink);
					}
				}
				output += this.options.skin.gallery.bottom;
			}
		}
		new Insertion.Top('lightwindow_galleries_list', output);
		
		// Attach Events
		for (i in this.galleries) {
			if (typeof this.galleries[i] == 'object') {
				for (j in this.galleries[i]) {
					if (typeof this.galleries[i][j] == 'object') {
						Event.observe($('lightwindow_gallery_'+i+'_'+j), 'click', this.openWindow.bind(this, this.galleries[i][j][0]), false);
						$('lightwindow_gallery_'+i+'_'+j).onclick = function() {return false;};	
					}
				}
			}
		}
	},
	// 
	//  Set Links Up
	//
	_setupLinks : function() {
		var links = $$('.'+this.options.classNames.standard);
		links.each(function(link) {
			this._processLink(link);
		}.bind(this));	
	},
	//
	//  Process a Link
	//
	_processLink : function(link) {
		if ((this._fileType(link.getAttribute('href')) == 'image' || this._fileType(link.getAttribute('href')) == 'media')) {
			if (gallery = this._getGalleryInfo(link.rel)) {
				if (!this.galleries[gallery[0]]) {
					this.galleries[gallery[0]] = new Array();
				}
				if (!this.galleries[gallery[0]][gallery[1]]) {
					this.galleries[gallery[0]][gallery[1]] = new Array();
				}
				this.galleries[gallery[0]][gallery[1]].push(link);
			}
		}
		
		// Take care of our inline content
		var url = link.getAttribute('href');
		if (url.indexOf('?') > -1) {
			url = url.substring(0, url.indexOf('?'));
		}
		
		var container = url.substring(url.indexOf('#')+1);
		if($(container)) {
			$(container).setStyle({
				display : 'none'
			});
		}
		
		Event.observe(link, 'click', this.activate.bindAsEventListener(this, link), false);
		link.onclick = function() {return false;};		
	},
	//
	//	Setup our actions
	//
	_setupActions : function() {
		var links = $$('#lightwindow_container .'+this.options.classNames.action);
		links.each(function(link) {
			Event.observe(link, 'click', this[link.getAttribute('rel')].bindAsEventListener(this, link), false);
			link.onclick = function() {return false;};
		}.bind(this));
	},
	//
	//	Add the markup to the page.
	//
	_addLightWindowMarkup : function(rebuild) {
		var overlay = Element.extend(document.createElement('div'));
		overlay.setAttribute('id', 'lightwindow_overlay');		
		// FF Mac has a problem with putting Flash above a layer without a 100% opacity background, so we need to use a pre-made
		if (Prototype.Browser.Gecko) {
			overlay.setStyle({
				backgroundImage: 'url('+this.options.overlay.presetImage+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height+'px'
			});			
		} else {
			overlay.setStyle({
				opacity: this.options.overlay.opacity,
				backgroundImage: 'url('+this.options.overlay.image+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height+'px'
			});
		}
		
		var lw = document.createElement('div');
		lw.setAttribute('id', 'lightwindow');
		lw.innerHTML = this.options.skin.main;
		
		var body = document.getElementsByTagName('body')[0];
		body.appendChild(overlay);
		body.appendChild(lw);	
				
		if ($('lightwindow_title_bar_close_link')) {
			Event.observe('lightwindow_title_bar_close_link', 'click', this.deactivate.bindAsEventListener(this));
			$('lightwindow_title_bar_close_link').onclick = function() {return false;};
		}
			
		Event.observe($('lightwindow_previous'), 'click', this.navigateWindow.bind(this, 'previous'), false);
		$('lightwindow_previous').onclick = function() {return false;};		
		Event.observe($('lightwindow_next'), 'click', this.navigateWindow.bind(this, 'next'), false);
		$('lightwindow_next').onclick = function() {return false;};

		if (!this.options.hideGalleryTab) {
			Event.observe($('lightwindow_galleries_tab'), 'click', this._handleGalleryAnimation.bind(this, true), false);
			$('lightwindow_galleries_tab').onclick = function() {return false;};
		}
		
		// Because we use position absolute, kill the scroll Wheel on animations
		if (Prototype.Browser.IE) {
			Event.observe(document, 'mousewheel', this._stopScrolling.bindAsEventListener(this), false);
		} else {
			Event.observe(window, 'DOMMouseScroll', this._stopScrolling.bindAsEventListener(this), false);
		}
				
		Event.observe(overlay, 'click', this.deactivate.bindAsEventListener(this), false);
		overlay.onclick = function() {return false;};
	},
	//
	//  Add loading window markup
	//
	_addLoadingWindowMarkup : function() {
		$('lightwindow_contents').innerHTML += this.options.skin.loading;
	},
	//
	//  Setup the window elements
	//
	_setupWindowElements : function(link) {
		this.element = link;
		this.element.title = null ? '' : link.getAttribute('title');
		this.element.author = null ? '' : link.getAttribute('author');
		this.element.caption = null ? '' : link.getAttribute('caption');
		this.element.rel = null ? '' : link.getAttribute('rel');
		this.element.params = null ? '' : link.getAttribute('params');

		// Set the window type
		this.contentToFetch = this.element.href;
		this.windowType = this._getParameter('lightwindow_type') ? this._getParameter('lightwindow_type') : this._fileType(this.contentToFetch);	
	},
	//
	//  Clear the window contents out
	//
	_clearWindowContents : function(contents) {
		// If there is an iframe, its got to go
		if ($('lightwindow_iframe')) {
			Element.remove($('lightwindow_iframe'));
		}

		// Stop playing an object if its still around
		if ($('lightwindow_media_primary')) {
			try {
				$('lightwindow_media_primary').Stop();
			} catch(e) {}
			Element.remove($('lightwindow_media_primary'));
		}

		// Stop playing an object if its still around		
		if ($('lightwindow_media_secondary')) {
			try {
				$('lightwindow_media_secondary').Stop();
			} catch(e) {}
			Element.remove($('lightwindow_media_secondary'));
		}
		
		this.activeGallery = false;
		this._handleNavigation(this.activeGallery);
		
		if (contents) {
			// Empty the contents
			$('lightwindow_contents').innerHTML = '';
			
			// Reset the scroll bars
			$('lightwindow_contents').setStyle({
				overflow: 'hidden'
			});		
			
			if (!this.windowActive) {
				$('lightwindow_data_slide_inner').setStyle({
					display: 'none'
				});

				$('lightwindow_title_bar_title').innerHTML = '';
			}

			// Because of browser differences and to maintain flexible captions we need to reset this height at close
			$('lightwindow_data_slide').setStyle({
				height: 'auto'
			});
		}
		
		this.resizeTo.height = null;
		this.resizeTo.width = null;
	},
	//
	//	Set the status of our animation to keep things from getting clunky
	//
	_setStatus : function(status) {
		this.animating = status;
		if (status) {
			Element.show('lightwindow_loading');
		}
		if (!(/MSIE 6./i.test(navigator.userAgent))) {
			this._fixedWindow(status);
		}
	},
	//
	//  Make this window Fixed
	//
	_fixedWindow : function(status) {
		if (status) {
			if (this.windowActive) {
				this._getScroll();
				$('lightwindow').setStyle({
					position: 'absolute',
					top: parseFloat($('lightwindow').getStyle('top'))+this.pagePosition.y+'px',
					left: parseFloat($('lightwindow').getStyle('left'))+this.pagePosition.x+'px'
				});		
			} else {
				$('lightwindow').setStyle({
					position: 'absolute'
				});						
			}
		} else {
			if (this.windowActive) {
				this._getScroll();
				$('lightwindow').setStyle({
					position: 'fixed',
					top: parseFloat($('lightwindow').getStyle('top'))-this.pagePosition.y+'px',
					left: parseFloat($('lightwindow').getStyle('left'))-this.pagePosition.x+'px'
				});		
			} else {
				if ($('lightwindow_iframe')) {
					// Ideally here we would set a 50% value for top and left, but Safari rears it ugly head again and we need to do it by pixels
					this._browserDimensions();
				}
				$('lightwindow').setStyle({
					position: 'fixed',
					top: (parseFloat(this._getParameter('lightwindow_top')) ? parseFloat(this._getParameter('lightwindow_top'))+'px' : this.dimensions.viewport.height/2+'px'),
					left: (parseFloat(this._getParameter('lightwindow_left')) ? parseFloat(this._getParameter('lightwindow_left'))+'px' : this.dimensions.viewport.width/2+'px')
				});
			}
		}
	},
	//
	//	Prepare the window for IE.
	//
	_prepareIE : function(setup) {
		if (Prototype.Browser.IE) {
			var height, overflowX, overflowY;
			if (setup) { 
				var height = '100%';
			} else {
				var height = 'auto';
			}
			var body = document.getElementsByTagName('body')[0];
			var html = document.getElementsByTagName('html')[0];
			html.style.height = body.style.height = height;
		}
	},
	_stopScrolling : function(e) {
		if (this.animating) {
			if (e.preventDefault) {
				e.preventDefault();
			}
			e.returnValue = false;		
		}
	},
	//
	//	Get the scroll for the page.
	//
	_getScroll : function(){
      	if(typeof(window.pageYOffset) == 'number') {
        	this.pagePosition.x = window.pageXOffset;
        	this.pagePosition.y = window.pageYOffset;
      	} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
	       	this.pagePosition.x = document.body.scrollLeft;
        	this.pagePosition.y = document.body.scrollTop;
		} else if(document.documentElement) {
        	this.pagePosition.x = document.documentElement.scrollLeft;
        	this.pagePosition.y = document.documentElement.scrollTop;
      	}
	},
	//
	//	Reset the scroll.
	//
	_setScroll : function(x, y) {
		document.documentElement.scrollLeft = x; 
		document.documentElement.scrollTop = y; 
	},
	//
	//	Hide Selects from the page because of IE.
	//     We could use iframe shims instead here but why add all the extra markup for one browser when this is much easier and cleaner
	//
	_toggleTroubleElements : function(visibility, content){
		
		if (content) {
			var selects = $('lightwindow_contents').getElementsByTagName('select');
		} else {
			var selects = document.getElementsByTagName('select');
		}
		
		for(var i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
		
		if (!content) {
			if (this.options.hideFlash){
				var objects = document.getElementsByTagName('object');
				for (i = 0; i != objects.length; i++) {
					objects[i].style.visibility = visibility;
				}
				var embeds = document.getElementsByTagName('embed');
				for (i = 0; i != embeds.length; i++) {
					embeds[i].style.visibility = visibility;
				}
			}
			var iframes = document.getElementsByTagName('iframe');
			for (i = 0; i != iframes.length; i++) {
				iframes[i].style.visibility = visibility;
			}
		}
	},
	// 
	//  Get the actual page size
	//
	_getPageDimensions : function() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ 
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { 
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {	
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { 
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { 
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	

		if(yScroll < windowHeight){
			this.pageDimensions.height = windowHeight;
		} else { 
			this.pageDimensions.height = yScroll;
		}

		if(xScroll < windowWidth){	
			this.pageDimensions.width = windowWidth;
		} else {
			this.pageDimensions.width = xScroll;
		}
	},
	//
	//	Display the lightWindow.
	//
	_displayLightWindow : function(display, visibility) {
		$('lightwindow_overlay').style.display = $('lightwindow').style.display = $('lightwindow_container').style.display = display;	
		$('lightwindow_overlay').style.visibility = $('lightwindow').style.visibility = $('lightwindow_container').style.visibility = visibility;
	},
	//
	//	Setup Dimensions of lightwindow.

	//
	_setupDimensions : function() {

		var originalHeight, originalWidth;
		switch (this.windowType) {
			case 'page' :
				originalHeight = this.options.dimensions.page.height;
				originalWidth = this.options.dimensions.page.width;
				break;

			case 'image' :
				originalHeight = this.options.dimensions.image.height;
				originalWidth = this.options.dimensions.image.width;
				break;
				
			case 'media' :
				originalHeight = this.options.dimensions.media.height;
				originalWidth = this.options.dimensions.media.width;
				break;
			
			case 'external' : 
				originalHeight = this.options.dimensions.external.height;
				originalWidth = this.options.dimensions.external.width;
				break;
				
			case 'inline' :
				originalHeight = this.options.dimensions.inline.height;
				originalWidth = this.options.dimensions.inline.width;
				break;
				
			default :
				originalHeight = this.options.dimensions.page.height;
				originalWidth = this.options.dimensions.page.width;
				break;
				
		}

		var offsetHeight = this._getParameter('lightwindow_top') ? parseFloat(this._getParameter('lightwindow_top'))+this.pagePosition.y : this.dimensions.viewport.height/2+this.pagePosition.y;
		var offsetWidth = this._getParameter('lightwindow_left') ? parseFloat(this._getParameter('lightwindow_left'))+this.pagePosition.x : this.dimensions.viewport.width/2+this.pagePosition.x;
		
		// So if a theme has say shadowed edges, they should be consistant and take care of in the contentOffset
		$('lightwindow').setStyle({
			top: offsetHeight+'px',
			left: offsetWidth+'px'
		});
		
		$('lightwindow_container').setStyle({
			height: originalHeight+'px',
			width: originalWidth+'px',
			left: -(originalWidth/2)+'px',
			top: -(originalHeight/2)+'px'
		});

		$('lightwindow_contents').setStyle({
			height: originalHeight+'px',
			width: originalWidth+'px'
		});
	},
	//
	//	Get the type of file.
	//
	_fileType : function(url) {
		var image = new RegExp("[^\.]\.("+this.options.fileTypes.image.join('|')+")\s*$", "i");
		if (image.test(url)) return 'image';
		if (url.indexOf('#') > -1 && (document.domain == this._getDomain(url))) return 'inline';		
		if (url.indexOf('?') > -1) url = url.substring(0, url.indexOf('?'));
		var type = 'unknown';
		var page = new RegExp("[^\.]\.("+this.options.fileTypes.page.join('|')+")\s*$", "i");
		var media = new RegExp("[^\.]\.("+this.options.fileTypes.media.join('|')+")\s*$", "i");
		if (document.domain != this._getDomain(url)) type = 'external';
	  	if (media.test(url)) type = 'media';
		if (type == 'external' || type == 'media') return type;
	  	if (page.test(url) || url.substr((url.length-1), url.length) == '/') type = 'page';
		return type;
	},
	//
	//  Get file Extension
	//
	_fileExtension : function(url) {
		if (url.indexOf('?') > -1) {
			url = url.substring(0, url.indexOf('?'));
		}
		var extenstion = '';
		for (var x = (url.length-1); x > -1; x--) {
			if (url.charAt(x) == '.') {
				return extenstion;
			}
			extenstion = url.charAt(x)+extenstion;
		}
	},
	//
	//	Monitor the keyboard while this lightwindow is up
	//
	_monitorKeyboard : function(status) {
		if (status) document.onkeydown = this._eventKeypress.bind(this); 
		else document.onkeydown = '';
	},
	//
	//  Perform keyboard actions
	//
	_eventKeypress : function(e) {
		if (e == null) {
			var keycode = event.keyCode;
		} else {
			var keycode = e.which;
		}
		
		switch (keycode) { 
			case 27: 
				this.deactivate(); 
				break;
			
			case 13:
				return;
				
			default:
				break;
		}
	
		// Gotta stop those quick fingers
		if (this.animating) {
			return false;
		}
		
		switch (String.fromCharCode(keycode).toLowerCase()) {
			case 'p':
				if (this.navigationObservers.previous) {
					this.navigateWindow('previous');
				}
				break;
				
			case 'n':
				if (this.navigationObservers.next) {
					this.navigateWindow('next');
				}
				break;
				
			default:
				break;
		}
	},
	//
	//	Get Gallery Information
	//
	_getGalleryInfo : function(rel) {
		if (!rel) return false;
		if (rel.indexOf('[') > -1) {
			return new Array(escape(rel.substring(0, rel.indexOf('['))), escape(rel.substring(rel.indexOf('[')+1, rel.indexOf(']'))));
		} else {
			return false;
		}
	},
	//
	//	Get the domain from a string.
	//
	_getDomain : function(url) {    
        var leadSlashes = url.indexOf('//');
        var domainStart = leadSlashes+2;
        var withoutResource = url.substring(domainStart, url.length);
        var nextSlash = withoutResource.indexOf('/');
        var domain = withoutResource.substring(0, nextSlash);
		if (domain.indexOf(':') > -1){
			var portColon = domain.indexOf(':');
			domain = domain.substring(0, portColon);
       	}
		return domain;
    },
	//
	//	Get the value from the params attribute string.
	//
	_getParameter : function(parameter, parameters) {
		if (!this.element) return false;
		if (parameter == 'lightwindow_top' && this.element.top) {
			return unescape(this.element.top);
		} else if (parameter == 'lightwindow_left' && this.element.left) {
			return unescape(this.element.left);
		} else if (parameter == 'lightwindow_type' && this.element.type) {
			return unescape(this.element.type);
		} else if (parameter == 'lightwindow_show_images' && this.element.showImages) {
			return unescape(this.element.showImages);
		} else if (parameter == 'lightwindow_height' && this.element.height) {
			return unescape(this.element.height);
		} else if (parameter == 'lightwindow_width' && this.element.width) {
			return unescape(this.element.width);
		} else if (parameter == 'lightwindow_loading_animation' && this.element.loadingAnimation) {
			return unescape(this.element.loadingAnimation);
		} else if (parameter == 'lightwindow_iframe_embed' && this.element.iframeEmbed) {
			return unescape(this.element.iframeEmbed);
		} else if (parameter == 'lightwindow_form' && this.element.form) {
			return unescape(this.element.form);
		} else {
			if (!parameters) {
				if (this.element.params) parameters = this.element.params;
				else return;
			}
			var value;
			var parameterArray = parameters.split(',');
			var compareString = parameter+'=';
			var compareLength = compareString.length;
			for (var i = 0; i < parameterArray.length; i++) {
				if (parameterArray[i].substr(0, compareLength) == compareString) {
					var currentParameter = parameterArray[i].split('=');
					value = currentParameter[1];
					break;
				}
			}
			if (!value) return false;
			else return unescape(value);
		}
	},
	//
	//  Get the Browser Viewport Dimensions
	//
	_browserDimensions : function() {
		if (Prototype.Browser.IE) {
            this.dimensions.viewport.height = document.documentElement.clientHeight;
            this.dimensions.viewport.width = document.documentElement.clientWidth;   
        } else {
            this.dimensions.viewport.height = window.innerHeight;
            this.dimensions.viewport.width = document.width || document.body.offsetWidth;
        }
	},
	//
	//  Get the scrollbar offset, I don't like this method but there is really no other way I can find.
	//
	_getScrollerWidth : function() {
	    var scrollDiv = Element.extend(document.createElement('div'));
		scrollDiv.setAttribute('id', 'lightwindow_scroll_div');
		scrollDiv.setStyle({
			position: 'absolute',
			top: '-10000px',
			left: '-10000px',
			width: '100px',
			height: '100px',
			overflow: 'hidden'
		});



	    var contentDiv = Element.extend(document.createElement('div'));
		contentDiv.setAttribute('id', 'lightwindow_content_scroll_div');
		contentDiv.setStyle({
			width: '100%',
			height: '200px'
		});

	    scrollDiv.appendChild(contentDiv);

		var body = document.getElementsByTagName('body')[0];
		body.appendChild(scrollDiv);

	    var noScroll = $('lightwindow_content_scroll_div').offsetWidth;
	    scrollDiv.style.overflow = 'auto';
    	var withScroll = $('lightwindow_content_scroll_div').offsetWidth;

	   	Element.remove($('lightwindow_scroll_div'));

	    this.scrollbarOffset = noScroll-withScroll;
	},
	

	//
	//  Add a param to an object dynamically created
	//
	_addParamToObject : function(name, value, object, id) {
		var param = document.createElement('param');
		param.setAttribute('value', value);
		param.setAttribute('name', name);
		if (id) {
			param.setAttribute('id', id);
		}
		object.appendChild(param);
		return object;
	},
	//
	//  Get the outer HTML of an object CROSS BROWSER
	//
	_outerHTML : function(object) {
 		if (Prototype.Browser.IE) {
			return object.outerHTML;
		} else {
			var clone = object.cloneNode(true);
			var cloneDiv = document.createElement('div');
			cloneDiv.appendChild(clone);
			return cloneDiv.innerHTML;
		}
	},
	//
	//  Convert an object to markup
	//
	_convertToMarkup : function(object, closeTag) {
		var markup = this._outerHTML(object).replace('</'+closeTag+'>', '');
		if (Prototype.Browser.IE) {
			for (var i = 0; i < object.childNodes.length; i++){
				markup += this._outerHTML(object.childNodes[i]);
			}
			markup += '</'+closeTag+'>';
		}
		return markup;
	},
	//
	//  Depending what type of browser it is we have to append the object differently... DAMN YOU IE!!
	//
	_appendObject : function(object, closeTag, appendTo) {
		if (Prototype.Browser.IE) {
			appendTo.innerHTML += this._convertToMarkup(object, closeTag);
			
			// Fix the Eolas activate thing but only for specified media, for example doing this to a quicktime film breaks it.
			if (this.options.EOLASFix.indexOf(this._fileType(this.element.href)) > -1) {
				var objectElements = document.getElementsByTagName('object');
				for (var i = 0; i < objectElements.length; i++) {
					if (objectElements[i].getAttribute("data")) objectElements[i].removeAttribute('data');
					objectElements[i].outerHTML = objectElements[i].outerHTML;
					objectElements[i].style.visibility = "visible";
				}
			}
		} else {
			appendTo.appendChild(object);	
		}	
	},
	//
	//  Add in iframe
	//
	_appendIframe : function(scroll) {
		var iframe = document.createElement('iframe');
		iframe.setAttribute('id', 'lightwindow_iframe');
		iframe.setAttribute('name', 'lightwindow_iframe');
		iframe.setAttribute('src', 'about:blank');
		iframe.setAttribute('height', '100%');
		iframe.setAttribute('width', '100%');
		iframe.setAttribute('frameborder', '0');
		iframe.setAttribute('marginwidth', '0');
		iframe.setAttribute('marginheight', '0');
		iframe.setAttribute('scrolling', scroll);	
		
		this._appendObject(iframe, 'iframe', $('lightwindow_contents'));
	},
	//
	//  Write Content to the iframe using the skin
	//
	_writeToIframe : function(content) {
		var template = this.options.skin.iframe;
		template = template.replace('{body_replace}', content); 
		if ($('lightwindow_iframe').contentWindow){
			$('lightwindow_iframe').contentWindow.document.open();
			$('lightwindow_iframe').contentWindow.document.write(template);
			$('lightwindow_iframe').contentWindow.document.close();
		} else {
			$('lightwindow_iframe').contentDocument.open();
			$('lightwindow_iframe').contentDocument.write(template);
			$('lightwindow_iframe').contentDocument.close();
		}
	},
	//
	//  Load the window Information
	//  
	_loadWindow : function() {
		switch (this.windowType) {
			case 'image' :

				var current = 0;
				var images = [];
				this.checkImage = [];
				this.resizeTo.height = this.resizeTo.width = 0;
				this.imageCount = this._getParameter('lightwindow_show_images') ? parseInt(this._getParameter('lightwindow_show_images')) : 1;

				// If there is a gallery get it
				if (gallery = this._getGalleryInfo(this.element.rel)) {	
					for (current = 0; current < this.galleries[gallery[0]][gallery[1]].length; current++) {
						if (this.contentToFetch.indexOf(this.galleries[gallery[0]][gallery[1]][current].href) > -1) {
							break;
						}
					}
					if (this.galleries[gallery[0]][gallery[1]][current-this.imageCount]) {
						this.navigationObservers.previous = this.galleries[gallery[0]][gallery[1]][current-this.imageCount];
					} else {
						this.navigationObservers.previous = false;
					}
					if (this.galleries[gallery[0]][gallery[1]][current+this.imageCount]) {
						this.navigationObservers.next = this.galleries[gallery[0]][gallery[1]][current+this.imageCount];
					} else {
						this.navigationObservers.next = false;
					}
					
					this.activeGallery = true;
				} else {
					this.navigationObservers.previous = false;
					this.navigationObservers.next = false;					

					this.activeGallery = false;
				}
				
				for (var i = current; i < (current+this.imageCount); i++) {
		
					if (gallery && this.galleries[gallery[0]][gallery[1]][i]) {
						this.contentToFetch = this.galleries[gallery[0]][gallery[1]][i].href;
						
						this.galleryLocation = {current: (i+1)/this.imageCount, total: (this.galleries[gallery[0]][gallery[1]].length)/this.imageCount};
											
						if (!this.galleries[gallery[0]][gallery[1]][i+this.imageCount]) {
							$('lightwindow_next').setStyle({
								display: 'none'
							});
						} else {
							$('lightwindow_next').setStyle({
								display: 'block'
							});
							$('lightwindow_next_title').innerHTML = this.galleries[gallery[0]][gallery[1]][i+this.imageCount].title;
						}
						
						if (!this.galleries[gallery[0]][gallery[1]][i-this.imageCount]) {
							$('lightwindow_previous').setStyle({
								display: 'none'
							});
						} else {
							$('lightwindow_previous').setStyle({
								display: 'block'
							});
							$('lightwindow_previous_title').innerHTML = this.galleries[gallery[0]][gallery[1]][i-this.imageCount].title;
						}
					}

					images[i] = document.createElement('img');
					images[i].setAttribute('id', 'lightwindow_image_'+i);
					images[i].setAttribute('border', '0');
					images[i].setAttribute('src', this.contentToFetch);
					$('lightwindow_contents').appendChild(images[i]);

					// We have to do this instead of .onload 
					this.checkImage[i] = new PeriodicalExecuter(function(i) {
						if (!(typeof $('lightwindow_image_'+i).naturalWidth != "undefined" && $('lightwindow_image_'+i).naturalWidth == 0)) {
	
							this.checkImage[i].stop();
	
							var imageHeight = $('lightwindow_image_'+i).getHeight();
							if (imageHeight > this.resizeTo.height) {
								this.resizeTo.height = imageHeight;
							}
							this.resizeTo.width += $('lightwindow_image_'+i).getWidth();
							this.imageCount--;
	
							$('lightwindow_image_'+i).setStyle({
								height: '100%'
							});
	
						 	if (this.imageCount == 0) {
								this._processWindow();
						 	}
						}
					
					}.bind(this, i), 1);			
				}


			break;
		
		case 'media' :			
		
			var current = 0;
			this.resizeTo.height = this.resizeTo.width = 0;

			// If there is a gallery get it
			if (gallery = this._getGalleryInfo(this.element.rel)) {	
				for (current = 0; current < this.galleries[gallery[0]][gallery[1]].length; current++) {
					if (this.contentToFetch.indexOf(this.galleries[gallery[0]][gallery[1]][current].href) > -1) {
						break;
					}
				}
				
				if (this.galleries[gallery[0]][gallery[1]][current-1]) {
					this.navigationObservers.previous = this.galleries[gallery[0]][gallery[1]][current-1];
				} else {
					this.navigationObservers.previous = false;
				}
				if (this.galleries[gallery[0]][gallery[1]][current+1]) {
					this.navigationObservers.next = this.galleries[gallery[0]][gallery[1]][current+1];
				} else {
					this.navigationObservers.next = false;
				}
		
				this.activeGallery = true;
			} else {
				this.navigationObservers.previous = false;
				this.navigationObservers.next = false;
				
				this.activeGallery = false;
			}
		

			if (gallery && this.galleries[gallery[0]][gallery[1]][current]) {
				this.contentToFetch = this.galleries[gallery[0]][gallery[1]][current].href;

				this.galleryLocation = {current: current+1, total: this.galleries[gallery[0]][gallery[1]].length};
				
				if (!this.galleries[gallery[0]][gallery[1]][current+1]) {
					$('lightwindow_next').setStyle({
						display: 'none'
					});
				} else {
					$('lightwindow_next').setStyle({
						display: 'block'
					});
					$('lightwindow_next_title').innerHTML = this.galleries[gallery[0]][gallery[1]][current+1].title;
				}
				
				if (!this.galleries[gallery[0]][gallery[1]][current-1]) {
					$('lightwindow_previous').setStyle({
						display: 'none'
					});
				} else {
					$('lightwindow_previous').setStyle({
						display: 'block'
					});
					$('lightwindow_previous_title').innerHTML = this.galleries[gallery[0]][gallery[1]][current-1].title;
				}
			}
			
			if (this._getParameter('lightwindow_iframe_embed')) {
				this.resizeTo.height = this.dimensions.viewport.height;
				this.resizeTo.width = this.dimensions.viewport.width;	
			} else {
				this.resizeTo.height = this._getParameter('lightwindow_height');
				this.resizeTo.width = this._getParameter('lightwindow_width');				
			}
			
			this._processWindow();
			
			break;

		case 'external' :		

			this._appendIframe('auto');

			this.resizeTo.height = this.dimensions.viewport.height;
			this.resizeTo.width = this.dimensions.viewport.width;
						
			this._processWindow();

			break;
				
		case 'page' :	
			
			var newAJAX = new Ajax.Request(
				this.contentToFetch, {
					method: 'get', 
					parameters: '', 
					onComplete: function(response) {
						$('lightwindow_contents').innerHTML += response.responseText;
						this.resizeTo.height = $('lightwindow_contents').scrollHeight+(this.options.contentOffset.height);
						this.resizeTo.width = $('lightwindow_contents').scrollWidth+(this.options.contentOffset.width);
						this._processWindow();
					}.bind(this)
				}
			);
			
			break;
			
		case 'inline' : 
		
			var content = this.contentToFetch;
			if (content.indexOf('?') > -1) {
				content = content.substring(0, content.indexOf('?'));
			}
			content = content.substring(content.indexOf('#')+1);
			
			new Insertion.Top($('lightwindow_contents'), $(content).innerHTML);
			
			this.resizeTo.height = $('lightwindow_contents').scrollHeight+(this.options.contentOffset.height);
			this.resizeTo.width = $('lightwindow_contents').scrollWidth+(this.options.contentOffset.width);
			
			this._toggleTroubleElements('hidden', true); 			
			this._processWindow();
			
			break;
			
		default : 
			throw("Page Type could not be determined, please amend this lightwindow URL "+this.contentToFetch);
			break;
		}
	},
	//
	//  Resize the Window to fit the viewport if necessary
	//
	_resizeWindowToFit : function() {
		if (this.resizeTo.height+this.dimensions.cruft.height > this.dimensions.viewport.height) {
			var heightRatio = this.resizeTo.height/this.resizeTo.width;
			this.resizeTo.height = this.dimensions.viewport.height-this.dimensions.cruft.height-(2*this.options.viewportPadding);
			// We only care about ratio's with this window type			
			if (this.windowType == 'image' || (this.windowType == 'media' && !this._getParameter('lightwindow_iframe_embed'))) {
				this.resizeTo.width = this.resizeTo.height/heightRatio;
				$('lightwindow_data_slide_inner').setStyle({
					width: this.resizeTo.width+'px'
				});			
			}
		} 
		if (this.resizeTo.width+this.dimensions.cruft.width > this.dimensions.viewport.width) {
			var widthRatio = this.resizeTo.width/this.resizeTo.height;
			this.resizeTo.width = this.dimensions.viewport.width-2*this.dimensions.cruft.width-(2*this.options.viewportPadding);
			// We only care about ratio's with this window type
			if (this.windowType == 'image' || (this.windowType == 'media' && !this._getParameter('lightwindow_iframe_embed'))) {
				this.resizeTo.height = this.resizeTo.width/widthRatio;
				$('lightwindow_data_slide_inner').setStyle({
					height: this.resizeTo.height+'px'
				});
			}
		}
			
	},
	//
	//  Set the Window to a preset size
	//
	_presetWindowSize : function() {
		if (this._getParameter('lightwindow_height')) {
			this.resizeTo.height = parseFloat(this._getParameter('lightwindow_height'));
		}
		if (this._getParameter('lightwindow_width')) {
			this.resizeTo.width = parseFloat(this._getParameter('lightwindow_width'));
		}
	},
	//
	//  Process the Window
	//
	_processWindow : function() {
		// Clean out our effects
		this.dimensions.dataEffects = [];

		// Set up the data-slide if we have caption information
		if (this.element.caption || this.element.author || (this.activeGallery && this.options.showGalleryCount)) {
			if (this.element.caption) {
				$('lightwindow_data_caption').innerHTML = this.element.caption;
				$('lightwindow_data_caption').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_caption').setStyle({
					display: 'none'
				});				
			}
			if (this.element.author) {
				$('lightwindow_data_author').innerHTML = this.element.author;
				$('lightwindow_data_author_container').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_author_container').setStyle({
					display: 'none'
				});				
			}
			if (this.activeGallery && this.options.showGalleryCount) {
				$('lightwindow_data_gallery_current').innerHTML = this.galleryLocation.current;
				$('lightwindow_data_gallery_total').innerHTML = this.galleryLocation.total;
				$('lightwindow_data_gallery_container').setStyle({
					display: 'block'
				});
			} else {
				$('lightwindow_data_gallery_container').setStyle({
					display: 'none'
				});				
			}

			$('lightwindow_data_slide_inner').setStyle({
				width: this.resizeTo.width+'px',
				height: 'auto',
				visibility: 'visible',
				display: 'block'
			});
			$('lightwindow_data_slide').setStyle({
				height: $('lightwindow_data_slide').getHeight()+'px',
				width: '1px',
				overflow: 'hidden',
				display: 'block'
			});
		} else {
			$('lightwindow_data_slide').setStyle({
				display: 'none',
				width: 'auto'
			});
			$('lightwindow_data_slide_inner').setStyle({
				display: 'none',
				visibility: 'hidden',
				width: this.resizeTo.width+'px',
				height: '0px'
			});
		}
				
		if (this.element.title != 'null') {		
			$('lightwindow_title_bar_title').innerHTML = this.element.title;
		} else {
			$('lightwindow_title_bar_title').innerHTML = '';
		}
		
		var originalContainerDimensions = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
		// Position the window
    	$('lightwindow_container').setStyle({
			height: 'auto',
			// We need to set the width to a px not auto as opera has problems with it
			width: $('lightwindow_container').getWidth()+this.options.contentOffset.width-(this.windowActive ? this.options.contentOffset.width : 0)+'px'
		});
		var newContainerDimensions = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
 		
		// We need to record the container dimension changes
		this.containerChange = {height: originalContainerDimensions.height-newContainerDimensions.height, width: originalContainerDimensions.width-newContainerDimensions.width};

		// Get out general dimensions
		this.dimensions.container = {height: $('lightwindow_container').getHeight(), width: $('lightwindow_container').getWidth()};
		this.dimensions.cruft = {height: this.dimensions.container.height-$('lightwindow_contents').getHeight()+this.options.contentOffset.height, width: this.dimensions.container.width-$('lightwindow_contents').getWidth()+this.options.contentOffset.width};
		
		// Set Sizes if we need too
		this._presetWindowSize();
		this._resizeWindowToFit(); // Even if the window is preset we still don't want it to go outside of the viewport

		if (!this.windowActive) {
			// Position the window
		   	$('lightwindow_container').setStyle({
				left: -(this.dimensions.container.width/2)+'px',
				top: -(this.dimensions.container.height/2)+'px'
			});
		}
	   	$('lightwindow_container').setStyle({
			height: this.dimensions.container.height+'px',
			width: this.dimensions.container.width+'px'
		});
		
		// We are ready, lets show this puppy off!
		this._displayLightWindow('block', 'visible');
		this._animateLightWindow();
	},
	//
	//  Fire off our animation handler
	//
	_animateLightWindow : function() {
		if (this.options.animationHandler) {
			this.options.animationHandler().bind(this);
		} else {
			this._defaultAnimationHandler();
		}
	},
	//
	//  Fire off our transition handler
	//
	_handleNavigation : function(display) {
		if (this.options.navigationHandler) {
			this.options.navigationHandler().bind(this, display);
		} else {
			this._defaultDisplayNavigation(display);
		}
	},
	//
	//  Fire off our transition handler
	//
	_handleTransition : function() {
		if (this.options.transitionHandler) {
			this.options.transitionHandler().bind(this);
		} else {
			this._defaultTransitionHandler();
		}
	},
	//
	//  Handle the finish of the window animation
	// 
	_handleFinalWindowAnimation : function(delay) {
		if (this.options.finalAnimationHandler) {
			this.options.finalAnimationHandler().bind(this, delay);
		} else {
			this._defaultfinalWindowAnimationHandler(delay);
		}		
	},
	//
	//  Handle the gallery Animation
	// 
	_handleGalleryAnimation : function(list) {
		if (this.options.galleryAnimationHandler) {
			this.options.galleryAnimationHandler().bind(this, list);
		} else {
			this._defaultGalleryAnimationHandler(list);
		}		
	},
	//
	//  Display the navigation 
	//
	_defaultDisplayNavigation : function(display) {
		if (display) {
			$('lightwindow_navigation').setStyle({
				display: 'block',
				height: $('lightwindow_contents').getHeight()+'px',
				width: '100%',
				marginTop: this.options.dimensions.titleHeight+'px'
			});			
		} else {
			$('lightwindow_navigation').setStyle({
				display: 'none',
				height: 'auto',
				width: 'auto'
			});			
		}
	},
	//
	//  This is the default animation handler for LightWindow
	//
	_defaultAnimationHandler : function() {	
		// Now that we have figures out the cruft lets make the caption go away and add its effects
		if (this.element.caption || this.element.author || (this.activeGallery && this.options.showGalleryCount)) {
			$('lightwindow_data_slide').setStyle({
				display: 'none',
				width: 'auto'
			});
			this.dimensions.dataEffects.push(
				new Effect.SlideDown('lightwindow_data_slide', {sync: true}),
				new Effect.Appear('lightwindow_data_slide', {sync: true, from: 0.0, to: 1.0})
			);
		}

		// Set up the Title if we have one
		$('lightwindow_title_bar_inner').setStyle({
			height: '0px',
			marginTop: this.options.dimensions.titleHeight+'px'
		});
		
		// We always want the title bar as well
		this.dimensions.dataEffects.push(
			new Effect.Morph('lightwindow_title_bar_inner', {sync: true, style: {height: this.options.dimensions.titleHeight+'px', marginTop: '0px'}}),
		 	new Effect.Appear('lightwindow_title_bar_inner', {sync: true, from: 0.0, to: 1.0})
		);		
		
		if (!this.options.hideGalleryTab) {
			this._handleGalleryAnimation(false);
			if ($('lightwindow_galleries_tab_container').getHeight() == 0) {
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_tab_container', {sync: true, style: {height: '20px', marginTop: '0px'}})
				);
				$('lightwindow_galleries').setStyle({
					width: '0px'
				});
			}
		}
		
		var resized = false;
		var ratio = this.dimensions.container.width-$('lightwindow_contents').getWidth()+this.resizeTo.width+this.options.contentOffset.width;
		if (ratio != $('lightwindow_container').getWidth()) {
			new Effect.Parallel([
					new Effect.Scale('lightwindow_contents', 100*(this.resizeTo.width/$('lightwindow_contents').getWidth()), {scaleFrom: 100*($('lightwindow_contents').getWidth()/($('lightwindow_contents').getWidth()+(this.options.contentOffset.width))), sync: true,  scaleY: false, scaleContent: false}),
					new Effect.Scale('lightwindow_container', 100*(ratio/(this.dimensions.container.width)), {sync: true, scaleY: false, scaleFromCenter: true, scaleContent: false})
				], {
					duration: this.duration, 
					delay: 0.25,
					queue: {position: 'end', scope: 'lightwindowAnimation'}
				}
			);		
		}
		
		ratio = this.dimensions.container.height-$('lightwindow_contents').getHeight()+this.resizeTo.height+this.options.contentOffset.height;
		if (ratio != $('lightwindow_container').getHeight()) {
			new Effect.Parallel([
					new Effect.Scale('lightwindow_contents', 100*(this.resizeTo.height/$('lightwindow_contents').getHeight()), {scaleFrom: 100*($('lightwindow_contents').getHeight()/($('lightwindow_contents').getHeight()+(this.options.contentOffset.height))), sync: true, scaleX: false, scaleContent: false}),
					new Effect.Scale('lightwindow_container', 100*(ratio/(this.dimensions.container.height)), {sync: true, scaleX: false, scaleFromCenter: true, scaleContent: false})
				], {
					duration: this.duration, 
					afterFinish: function() {				
						if (this.dimensions.dataEffects.length > 0) {
							if (!this.options.hideGalleryTab) {
								$('lightwindow_galleries').setStyle({
									width: this.resizeTo.width+'px'
								});
							}
							new Effect.Parallel(this.dimensions.dataEffects, {
									duration: this.duration,
									afterFinish: function() {
										this._finishWindow();
									}.bind(this),
									queue: {position: 'end', scope: 'lightwindowAnimation'} 
								}
							);
						}
					}.bind(this), 
					queue: {position: 'end', scope: 'lightwindowAnimation'} 
				}
			);
			resized = true;
		}
		
		// We need to do our data effect since there was no resizing
		if (!resized && this.dimensions.dataEffects.length > 0) {	
			new Effect.Parallel(this.dimensions.dataEffects, {
					duration: this.duration,
					beforeStart: function() {
						if (!this.options.hideGalleryTab) {
							$('lightwindow_galleries').setStyle({
								width: this.resizeTo.width+'px'
							});
						}
						if (this.containerChange.height != 0 || this.containerChange.width != 0) {
							new Effect.MoveBy('lightwindow_container', this.containerChange.height, this.containerChange.width, {transition: Effect.Transitions.sinoidal});
						}
					}.bind(this),			
					afterFinish: function() {
						this._finishWindow();
					}.bind(this),
					queue: {position: 'end', scope: 'lightwindowAnimation'} 
				}
			);
		}			
		
	},
	//
	//  Finish up Window Animation
	//
	_defaultfinalWindowAnimationHandler : function(delay) {
		if (this.windowType == 'media' || this._getParameter('lightwindow_loading_animation')) {	
			// Because of major flickering with the overlay we just hide it in this case
			Element.hide('lightwindow_loading');
			this._handleNavigation(this.activeGallery);
			this._setStatus(false);
		} else {
			Effect.Fade('lightwindow_loading', {
				duration: 0.75,
				delay: 1.0, 
				afterFinish: function() {
					// Just in case we need some scroll goodness (this also avoids the swiss cheese effect)
					if (this.windowType != 'image' && this.windowType != 'media' && this.windowType != 'external') {
						$('lightwindow_contents').setStyle({
							overflow: 'auto'
						});
					}
					this._handleNavigation(this.activeGallery);
					this._defaultGalleryAnimationHandler();
					this._setStatus(false);
				}.bind(this),
				queue: {position: 'end', scope: 'lightwindowAnimation'}
			});
		}
	},
	//
	//  Handle the gallery Animation
	//
	_defaultGalleryAnimationHandler : function(list) {
		if (this.activeGallery) {
			$('lightwindow_galleries').setStyle({
				display: 'block',
				marginBottom: $('lightwindow_data_slide').getHeight()+this.options.contentOffset.height/2+'px'
			});
			$('lightwindow_navigation').setStyle({
				height: $('lightwindow_contents').getHeight()-20+'px'
			});
		} else {
			$('lightwindow_galleries').setStyle({
				display: 'none'
			});	
			$('lightwindow_galleries_tab_container').setStyle({
				height: '0px',
				marginTop: '20px'
			});
			$('lightwindow_galleries_list').setStyle({
				height: '0px'
			});
			return false;
		}
		
		if (list) {
			if ($('lightwindow_galleries_list').getHeight() == 0) {
				var height = $('lightwindow_contents').getHeight()*0.80;
				$('lightwindow_galleries_tab_span').className = 'down';
			} else {
				var height = 0;
				$('lightwindow_galleries_tab_span').className = 'up';
			}

			new Effect.Morph('lightwindow_galleries_list', {
				duration: this.duration,
				transition: Effect.Transitions.sinoidal,
				style: {height: height+'px'},
				beforeStart: function() {
					$('lightwindow_galleries_list').setStyle({
						overflow: 'hidden'
					});					
				},
				afterFinish: function() {
					$('lightwindow_galleries_list').setStyle({
						overflow: 'auto'
					});
				},
				queue: {position: 'end', scope: 'lightwindowAnimation'}
			});	
		}
		
		
	},
	//
	//  Default Transition Handler
	//
	_defaultTransitionHandler : function() {
		// Clean out our effects
		this.dimensions.dataEffects = [];

		// Now that we have figures out the cruft lets make the caption go away and add its effects
		if ($('lightwindow_data_slide').getStyle('display') != 'none') {
			this.dimensions.dataEffects.push(
				new Effect.SlideUp('lightwindow_data_slide', {sync: true}),
				new Effect.Fade('lightwindow_data_slide', {sync: true, from: 1.0, to: 0.0})
			);
		}
		
		if (!this.options.hideGalleryTab) {
			if ($('lightwindow_galleries').getHeight() != 0 && !this.options.hideGalleryTab) {
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_tab_container', {sync: true, style: {height: '0px', marginTop: '20px'}})
				);
			}
			
			if ($('lightwindow_galleries_list').getHeight() != 0) {
				$('lightwindow_galleries_tab_span').className = 'up';
				this.dimensions.dataEffects.push(
					new Effect.Morph('lightwindow_galleries_list', {
						sync: true, 
						style: {height: '0px'},
						transition: Effect.Transitions.sinoidal,
						beforeStart: function() {
							$('lightwindow_galleries_list').setStyle({
								overflow: 'hidden'
							});					
						},
						afterFinish: function() {
							$('lightwindow_galleries_list').setStyle({
								overflow: 'auto'
							});
						}
					})
				);
			}
		}
		
		// We always want the title bar as well
		this.dimensions.dataEffects.push(
			new Effect.Morph('lightwindow_title_bar_inner', {sync: true, style: {height: '0px', marginTop: this.options.dimensions.titleHeight+'px'}}),
		 	new Effect.Fade('lightwindow_title_bar_inner', {sync: true, from: 1.0, to: 0.0})
		);

		new Effect.Parallel(this.dimensions.dataEffects, {
				duration: this.duration,
				afterFinish: function() {
					this._loadWindow();
				}.bind(this),
				queue: {position: 'end', scope: 'lightwindowAnimation'} 
			}
		);	
	},
	//
	//	Default Form handler for LightWindow
	//
	_defaultFormHandler : function(e) {
		var element = Event.element(e).parentNode;
		var parameterString = Form.serialize(this._getParameter('lightwindow_form', element.getAttribute('params')));
		if (this.options.formMethod == 'post') {
			var newAJAX = new Ajax.Request(element.href, { 
				method: 'post', 
				postBody: parameterString, 
				onComplete: this.openWindow.bind(this, element)
			});
		} else if (this.options.formMethod == 'get') {
			var newAJAX = new Ajax.Request(element.href, { 
				method: 'get', 
				parameters: parameterString, 
				onComplete: this.openWindow.bind(this, element)
			});
		}
	},
	// 
	//  Wrap everything up
	//
	_finishWindow : function() {
		if (this.windowType == 'external') {
			// We set the externals source here because it allows for a much smoother animation
			$('lightwindow_iframe').setAttribute('src', this.element.href);
			this._handleFinalWindowAnimation(1);	
		} else if (this.windowType == 'media') {

			var outerObject = document.createElement('object');
			outerObject.setAttribute('classid', this.options.classids[this._fileExtension(this.contentToFetch)]);
			outerObject.setAttribute('codebase', this.options.codebases[this._fileExtension(this.contentToFetch)]);
			outerObject.setAttribute('id', 'lightwindow_media_primary');
			outerObject.setAttribute('name', 'lightwindow_media_primary');
			outerObject.setAttribute('width', this.resizeTo.width);
			outerObject.setAttribute('height', this.resizeTo.height);
			outerObject = this._addParamToObject('movie', this.contentToFetch, outerObject);
			outerObject = this._addParamToObject('src', this.contentToFetch, outerObject);
			outerObject = this._addParamToObject('controller', 'true', outerObject);
			outerObject = this._addParamToObject('wmode', 'transparent', outerObject);
			outerObject = this._addParamToObject('cache', 'false', outerObject);
			outerObject = this._addParamToObject('quality', 'high', outerObject);

			if (!Prototype.Browser.IE) {
				var innerObject = document.createElement('object');
				innerObject.setAttribute('type', this.options.mimeTypes[this._fileExtension(this.contentToFetch)]);
				innerObject.setAttribute('data', this.contentToFetch);
				innerObject.setAttribute('id', 'lightwindow_media_secondary');
				innerObject.setAttribute('name', 'lightwindow_media_secondary');
				innerObject.setAttribute('width', this.resizeTo.width);
				innerObject.setAttribute('height', this.resizeTo.height);
				innerObject = this._addParamToObject('controller', 'true', innerObject);
				innerObject = this._addParamToObject('wmode', 'transparent', innerObject);
				innerObject = this._addParamToObject('cache', 'false', innerObject);
				innerObject = this._addParamToObject('quality', 'high', innerObject);
			
				outerObject.appendChild(innerObject);
			}	
			
			if (this._getParameter('lightwindow_iframe_embed')) {
				this._appendIframe('no');
				this._writeToIframe(this._convertToMarkup(outerObject, 'object'));
			} else {
				this._appendObject(outerObject, 'object', $('lightwindow_contents'));
			}

			this._handleFinalWindowAnimation(0);
		} else {
			this._handleFinalWindowAnimation(0);
		}

		// Initialize any actions
		this._setupActions();
	}
}

/*-----------------------------------------------------------------------------------------------*/

//jure:
//Event.observe(window, 'load', lightwindowInit, false);
document.observe('dom:loaded', lightwindowInit, false);
//:jure

//
//	Set up all of our links
//
var myLightWindow = null;
function lightwindowInit() {
	myLightWindow = new lightwindow();
}

/* ---------- /shared/js/menu.js ---------- */

var menu={
	playing:0,
	liv_1:[],
	queue:[],
	cursor:{isOver:false},
	delay:{
		start:function(){
			setTimeout("(function(){if(!menu.cursor.isOver){menu.hide()}})()",1);
		}
	},
	hide:function(){
		menu.liv_1.each(function(li){
			var element_loop = li.select(".fix-B").first() ;
			if(element_loop)if(element_loop.visible())element_loop.hide();
		});
		$("overlapIEfix").hide();
	},
	fixIEoverlap:function(){},
	transition:function(DIV){
		Effect.SlideDown(DIV,{
			duration:(is.IE&navigator.version<7)?0:0.5,
			beforeStart:function(e){
				menu.playing=1;
				var element = e.element ;
				menu.hide();
			},
			afterUpdate:function(e){
				menu.fixIEoverlap(e);
			},
			afterFinish:function(){
				menu.playing=0;
				if(menu.queue.length>0){
					var q=menu.queue[0];
					menu.queue=[];
					var DIV=$(q).up().select(".fix-B").first();
					if(DIV){
						if(!DIV.visible()){
							menu.show(q);
						}
					}else{
						menu.show(q);
					}
				}
				/*
				if(!menu.cursor.isOver){
					menu.hide();
				}
				*/
			}
		});		
	},
	select:function(){
		var liv1=$("menu-header").down("UL").childElements();
		var found=liv1.length-1;
		for(var i=0;i<liv1.length;i++){
			var LI=liv1[i],A=liv1[i].down("A");
			var p=location.pathname;
			var h=A.readAttribute("href");
			if(p.charAt(0         )!="/")p="/"+p;
			if(h.charAt(0         )!="/")h="/"+h;
			if(p.charAt(p.length-1)!="/")p=p+"/";
			if(h.charAt(h.length-1)!="/")h=h+"/";
			if(p.indexOf(h)!=-1){
				found=i;
				break;
			}
		}
		liv1[found].addClassName("nodo");
		liv1[found].down("A").addClassName("sel");
		var fb=liv1[found].down(".fix-B");
		if(fb)fb.show();
	},
	show:function(){
		var q=arguments[0]||-1;
		if(q==-1){
			playing=0;
			menu.hide();
			return;
		}else{
			menu.hide();
		}
		var IFRAME=$("overlapIEfix");
		IFRAME.hide();
		var DIV = $(q).up().select(".fix-B").first() ;
		if(DIV){
			menu.transition(DIV)
		}else{
			menu.hide();
		}
	}
}

if(is.IE && navigator.version<7){
	menu.fixIEoverlap=function(e){
		var IFRAME=$("overlapIEfix");
		var element=e.element;
		var dim=element.getDimensions();
		var pos=element.cumulativeOffset();
		IFRAME.style.width=px(dim.width);
		IFRAME.style.height=px(dim.height);
		IFRAME.style.left=px(pos.left);
		IFRAME.style.top=px(pos.top);
		IFRAME.show();
	}
}


var MenuID="menu-header";
// SCARPA:
function liv2position(){
	var m=$(MenuID);
	var P=m.getOffsetParent().cumulativeOffset();
	$(MenuID).select(".fix-A").each(function(DIV){
		DIV.setStyle({left:0});
	})

}
// :SCARPA
function initMenu(){
	var m=$(MenuID);
	var mu=$(MenuID).select("UL");
	var muu=$(MenuID).select("UL UL");
	
	// prepare for Scriptaculous bugs
	var ULs=muu.each(function(ul){
		var divA=new Element("div",{className:"fix-A"});
		var divB=new Element("div",{className:"fix-B",style:"display:none;"});
		var divC=new Element("div",{className:"fix-C"});
		ul.up("li").insert(
			divA.insert(divB.insert(divC.insert(ul.remove())))
		);
	});
	
	// animate
	var UL=mu.first();
	menu.liv_1=UL.childElements();
	/* if i have a second row or a second menu under the first:
	var liv_1_amp=UL.next("UL").childElements();
	liv_1_amp.each(function(li){menu.liv_1.push(li);});
	*/
	
	var whichSelected=-1;
	menu.liv_1.each(function(li){
		a=li.down("a");
		Event.observe(a,"mouseover",function(event){
			if(!menu.playing){
				menu.show(this);
			}else{
				menu.queue[0]=this;
			}
			var ov=m.down(".liv-1-over");
			if(ov)ov.removeClassName("liv-1-over");
			if(!this.hasClassName("sel"))this.addClassName("liv-1-over");
		});
	});
	
	mu.each(function(ul){
		Event.observe(ul,"mouseover",function(){
			menu.cursor.isOver=true;
		});
		Event.observe(ul,"mouseout",function(){
			menu.cursor.isOver=false;
			//menu.delay.start();
		});
	});
	
/*	
	var d=ce("div");d.id="ddd";
	$("menu-header").up().appendChild(d);
	new PeriodicalExecuter(function(){$("ddd").innerHTML=menu.cursor.isOver},0.001)
*/
	// SCARPA:
	liv2position();
	Event.observe(window,'resize',liv2position);
	// :SCARPA
	menu.select();
	m.select(".clickable-0").each(function(A){
		A.writeAttribute({
			href:'javascript:;'
		}).setStyle({
			cursor:'default'
		});
	});	
	
	$(MenuID).show();
}

/* ---------- /shared/js/default.js ---------- */

function lang(q){
	if(typeof _LANG[q] != "undefined"){
		if(arguments.length==1)return _LANG[q];
		else{
			var r=_LANG[q],re;
			for(var i=1;i<arguments.length;i++){
				re=new RegExp("%"+i,"g");
				r=r.replace(re,arguments[i]);
			}
			return r;
		}
	}
}

function cambiaLingua(l,p){
	new Ajax.Request(wwwroot+"/shared/php/cambiaLingua.php",{
		parameters:{l:l,p:p},
		onFailure:function(transport){alert(transport);},
		onSuccess:function(transport){
			var o = transport.responseText.evalJSON();
			if(o.error!=false){alert(o.error);return false;}
			location.href="http://"+location.hostname.replace(/-+\w{2}\./,"-"+l+".")+"/"+o.p+"/"+location.search;
		}
	});
}

function detailTab(q){
	$$("#detailTabs .sel").first().removeClassName("sel");
	$("tab-"+q).addClassName("sel");
	$$("#detailTabContents .sel").first().removeClassName("sel");
	$("tabContent-"+q).addClassName("sel");
}

var jCache={
	images:[],
	preloads:[],
	queue:function(q){
		this.images.push(q);
	},
	preloadImages:function(){
		for(var i=0;i<this.images.length;i++){
			this.preloads[i]=new Image();
			this.preloads[i].src=this.images[i];
		}
	}
}
jCache.queue("m_contact_0.gif");
jCache.queue("m_contact_1.gif");
jCache.queue("m_curriculumVitae_0.gif");
jCache.queue("m_curriculumVitae_1.gif");
jCache.queue("m_djSet_0.gif");
jCache.queue("m_djSet_1.gif");
jCache.queue("m_home_0.gif");
jCache.queue("m_home_1.gif");
jCache.queue("m_logo_0.gif");
jCache.queue("m_logo_1.gif");
jCache.queue("m_music_0.gif");
jCache.queue("m_music_1.gif");
jCache.queue("m_portfolio_0.gif");
jCache.queue("m_portfolio_1.gif");
jCache.queue("m_print_0.gif");
jCache.queue("m_print_1.gif");
jCache.queue("m_web_0.gif");
jCache.queue("m_web_1.gif");
jCache.preloadImages();

