////////////////////////////////GOOGLE//////////////////////////////////////////////////////
if (googleAnalyticsAccount && googleAnalyticsAccount != 'null' && trim(googleAnalyticsAccount).length > 0){
	if (_gat){
		var pageTracker = _gat._getTracker(googleAnalyticsAccount);
		pageTracker._initData();
		pageTracker._trackPageview();
	}
}

//DHTMLWINDOW JS START
// -------------------------------------------------------------------
// DHTML Window Widget- By Dynamic Drive, available at: http://www.dynamicdrive.com
// v1.0: Script created Feb 15th, 07'
// v1.01: Feb 21th, 07' (see changelog.txt)
// v1.02: March 26th, 07' (see changelog.txt)
// v1.03: May 5th, 07' (see changelog.txt)
// -------------------------------------------------------------------
//==================== Parameters ===================================
// 'Unique_ID'
// 'ContentAreaType' (div/iframe/ajax)
// 'src' (divId/source file for iframe / url for Ajax)
// 'Title' 
// 'Attributes'  i.e. 'width=350px,height=200px,left=350px,top=100px,resize=1,scrolling=1,center=1,drag=1,title=1,minimize=1,maximize=1,close=1,maxTop=120,maxLeft=5,maxwidth=1000,maxheight=800'
// 'recal' (Optional)
// 'className' (Optional)

var dhtmlwindow={
	ajaxbustcache: true, //Bust caching when fetching a file via Ajax?
	ajaxloadinghtml: '<b>Loading. Please wait...</b>', //HTML to show while window fetches Ajax Content?

	minimizeorder: 0,
	zIndexvalue:100,
	tobjects: [], //object to contain references to dhtml window divs, for cleanup purposes
	lastactivet: {}, //reference to last active DHTML window

	init:function(t,clsname){
		var domwindow=document.createElement("div") //create dhtml window div
		domwindow.id=t
		domwindow.className=clsname || "dhtmlwindow"
		var domwindowdata=''
		domwindowdata='<iframe FRAMEBORDER=0 class="popupbackground" id="'+t+'_background"></iframe><div class="drag-handle">'
		domwindowdata+='DHTML Window <div class="drag-controls"><span class="drag-controls-minimize" title="Minimize" >&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="drag-controls-maximize" title="Maximize" >&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="drag-controls-close" title="Close" >&nbsp;&nbsp;&nbsp;&nbsp;</span></div>'
		domwindowdata+='</div>'
		domwindowdata+='<div class="drag-contentarea"></div>'
		domwindowdata+='<div class="drag-statusarea"><div class="drag-resizearea">&nbsp;</div></div>'
		domwindowdata+='</div>'
		domwindow.innerHTML=domwindowdata
		document.getElementById("dhtmlwindowholder").appendChild(domwindow)
		var t=document.getElementById(t)
		var divs=t.getElementsByTagName("div")
		t.fb = t.getElementsByTagName("iframe")[0];
		for (var i=0; i<divs.length; i++){ //go through divs inside dhtml window and extract all those with class="drag-" prefix
			if (/drag-/.test(divs[i].className))
				t[divs[i].className.replace(/drag-/, "")]=divs[i] //take out the "drag-" prefix for shorter access by name
		}
		t.handle._parent=t //store back reference to dhtml window
		t.resizearea._parent=t //same
		t.controls._parent=t //same
		t.onclose=function(){return true} //custom event handler "onclose"
		t.onmousedown=function(){dhtmlwindow.setfocus(this)} //Increase z-index of window when focus is on it
		t.handle.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on handle div
		t.handle.ondblclick = function(){dhtmlwindow.titleDBClick(this._parent)}
		t.resizearea.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on resize div
		t.controls.onclick=dhtmlwindow.enablecontrols
		t.show=function(){dhtmlwindow.show(this)} //public function for showing dhtml window
		t.setBackground = function(){dhtmlwindow.setBackground(this)}
		t.hide=function(){dhtmlwindow.hide(this)} //public function for hiding dhtml window
		t.close=function(){dhtmlwindow.close(this)} //public function for closing dhtml window (also empties DHTML window content)
		t.setSize=function(w, h){dhtmlwindow.setSize(this, w, h)} //public function for setting window dimensions
		t.moveTo=function(x, y){dhtmlwindow.moveTo(this, x, y)} //public function for moving dhtml window (relative to viewpoint)
		t.isResize=function(bol){dhtmlwindow.isResize(this, bol)} //public function for specifying if window is resizable
		t.isScrolling=function(bol){dhtmlwindow.isScrolling(this, bol)} //public function for specifying if window content contains scrollbars
		t.load=function(contenttype, contentsource, title){dhtmlwindow.load(this, contenttype, contentsource, title)} //public function for loading content into window
		this.tobjects[this.tobjects.length]=t
		return t //return reference to dhtml window div
	},

	open:function(t, contenttype, contentsource, title, attr, recalonload,clsname){
		var d=dhtmlwindow //reference dhtml window object
		var className = clsname || "dhtmlwindow"
		function getValue(Name){
			var config=new RegExp(Name.toUpperCase()+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
			var value = (config.test(attr.toUpperCase()))? parseInt(RegExp.$1) : 0 //return value portion (int), or 0 (false) if none found
			return value;
		}
		if (document.getElementById(t)==null) //if window doesn't exist yet, create it
			t=this.init(t,className) //return reference to dhtml window div
		else
			t=document.getElementById(t)
		
		this.setfocus(t)
		t.setSize(getValue(("width")), (getValue("height"))) //Set dimensions of window
		var xpos=getValue("center")? "middle" : getValue("left") //Get x coord of window
		var ypos=getValue("center")? "middle" : getValue("top") //Get y coord of window
		if (typeof recalonload!="undefined" && recalonload=="recal" && this.scroll_top==0){ //reposition window when page fully loads with updated window viewpoints?
			if (window.attachEvent && !window.opera) //In IE, add another 400 milisecs on page load (viewpoint properties may return 0 b4 then)
				this.addEvent(window, function(){setTimeout(function(){t.moveTo(xpos, ypos)}, 400)}, "load")
			else
				this.addEvent(window, function(){t.moveTo(xpos, ypos)}, "load")
		}
		t.isResize(getValue("resize")) //Set whether window is resizable
		t.isScrolling(getValue("scrolling")) //Set whether window should contain scrollbars
		t.dragBool = getValue("drag")
		t.minimizeBool = getValue("minimize")
		t.maximizeBool = getValue("maximize")
		t.closeBool = getValue("close")
		t.maxHeight = getValue("maxheight");
		t.maxWidth = getValue("maxwidth");
		t.maxTop =  getValue("maxtop");
		t.maxLeft =  getValue("maxleft");

		t.titleBool = getValue("title")
		if (t.titleBool==0){ t.dragBool=t.minimizeBool=t.maximizeBool=t.closeBool=0;t.handle.style.display='none';}
		if(t.dragBool==0) {t.handle.style.cursor='normal'; t.handle.onmousedown=function(){}};
		if(t.minimizeBool==0 && t.maximizeBool==0 && t.closeBool==0) { t.controls.onclick=function(){}; t.controls.style.display='none';}

		if (t.minimizeBool==0){
			t.controls.childNodes[0].style.display='none';
		}else{
			t.controls.childNodes[0].style.display='';
			t.controls.childNodes[0].className = 'drag-controls-minimize'
			t.controls.childNodes[0].setAttribute("title", "Minimize")
		}
		if (t.maximizeBool==0){
			t.controls.childNodes[1].style.display='none';
		}else{
			t.controls.childNodes[1].style.display='';
			t.controls.childNodes[1].className = 'drag-controls-maximize'
			t.controls.childNodes[1].setAttribute("title", "Maximize")
		}
		if (t.closeBool==0){
			t.controls.childNodes[2].style.display='none';
		}else{
			t.controls.childNodes[2].style.display='';
			t.controls.childNodes[2].className = 'drag-controls-close'
			t.controls.childNodes[2].setAttribute("title", "Close")
		}
		t.state="fullview";
		t.style.visibility="visible"
		t.style.display="block"
		t.contentarea.style.display="block"
		t.moveTo(xpos, ypos) //Position window
		t.load(contenttype, contentsource, title)
		if (t.state=="minimized"){ //If window exists and is currently minimized?
			t.controls.firstChild.className = 'drag-controls-minimize';
			t.controls.firstChild.setAttribute("title", "Minimize")
			t.state="fullview" //indicate the state of the window as being "fullview"
		}
		t.setBackground(t)
		return t
	},

	setSize:function(t, w, h){ //set window size (min is 150px wide by 100px tall)
		t.style.width=Math.max(parseInt(w), 150)+"px"
		t.contentarea.style.height=Math.max(parseInt(h), 100)+"px"
	},

	moveTo:function(t, x, y){ //move window. Position includes current viewpoint of document
		this.getviewpoint() //Get current viewpoint numbers
		t.style.left=(x=="middle")? this.scroll_left+(this.docwidth-t.offsetWidth)/2+"px" : this.scroll_left+parseInt(x)+"px"
		t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px"
	},

	isResize:function(t, bol){ //show or hide resize inteface (part of the status bar)
		t.statusarea.style.display=(bol)? "block" : "none"
		t.resizeBool=(bol)? 1 : 0
	},
	
	isScrolling:function(t, bol){ //set whether loaded content contains scrollbars
		t.contentarea.style.overflow=(bol)? "auto" : "hidden"
	},

	load:function(t, contenttype, contentsource, title){ //loads content into window plus set its title (3 content types: "inline", "iframe", or "ajax")
		if (t.isClosed){
			alert("DHTML Window has been closed, so no window to load contents into. Open/Create the window again.")
			return
		}
		var contenttype=contenttype.toLowerCase() //convert string to lower case
		if (typeof title!="undefined")
			t.handle.firstChild.nodeValue=title
		if (contenttype=="inline")
			t.contentarea.innerHTML=contentsource
		else if (contenttype=="div"){
			var inlinedivref=document.getElementById(contentsource)
			t.contentarea.innerHTML=(inlinedivref.defaultHTML || inlinedivref.innerHTML) //Populate window with contents of inline div on page
			if (!inlinedivref.defaultHTML)
				inlinedivref.defaultHTML=inlinedivref.innerHTML //save HTML within inline DIV
			inlinedivref.innerHTML="" //then, remove HTML within inline DIV (to prevent duplicate IDs, NAME attributes etc in contents of DHTML window
			inlinedivref.style.display="none" //hide that div
		}
		else if (contenttype=="iframe"){
			t.contentarea.style.overflow="hidden" //disable window scrollbars, as iframe already contains scrollbars
			if (!t.contentarea.firstChild || t.contentarea.firstChild.tagName!="IFRAME") //If iframe tag doesn't exist already, create it first
				t.contentarea.innerHTML='<iframe src="" FRAMEBORDER=0 style="border:none; margin:0; padding:0;height:100%;width:100%;" name="_iframe-'+t.id+'"></iframe>'
			window.frames["_iframe-"+t.id].location.replace(contentsource) //set location of iframe window to specified URL
			}
		else if (contenttype=="ajax"){
			this.ajax_connect(contentsource, t) //populate window with external contents fetched via Ajax
		}
		t.contentarea.datatype=contenttype //store contenttype of current window for future reference
	},

	setupdrag:function(e){
		var d=dhtmlwindow //reference dhtml window object
		var t=this._parent //reference dhtml window div
		d.etarget=this //remember div mouse is currently held down on ("handle" or "resize" div)
		var e=window.event || e
		d.initmousex=e.clientX //store x position of mouse onmousedown
		d.initmousey=e.clientY
		d.initx=parseInt(t.offsetLeft) //store offset x of window div onmousedown
		d.inity=parseInt(t.offsetTop)
		d.width=parseInt(t.offsetWidth) //store width of window div
		d.height=parseInt(t.offsetHeight) //store width of window div
		d.contentheight=parseInt(t.contentarea.offsetHeight) //store height of window div's content div
		if (t.contentarea.datatype=="iframe"){ //if content of this window div is "iframe"
			t.style.backgroundColor="#F8F8F8" //colorize and hide content div (while window is being dragged)
			t.contentarea.style.visibility="hidden"
		}
		document.onmousemove=d.getdistance //get distance travelled by mouse as it moves
		document.onmouseup=function(){
			if (t.contentarea.datatype=="iframe"){ //restore color and visibility of content div onmouseup
				t.contentarea.style.backgroundColor="white"
				t.contentarea.style.visibility="visible"
			}
			d.stop()
		}
		return false
	},

	getdistance:function(e){
		var d=dhtmlwindow
		var etarget=d.etarget
		var e=window.event || e
		d.distancex=e.clientX-d.initmousex //horizontal distance travelled relative to starting point
		d.distancey=e.clientY-d.initmousey
		if (etarget.className=="drag-handle") //if target element is "handle" div
			d.move(etarget._parent, e)
		else if (etarget.className=="drag-resizearea") //if target element is "resize" div
			d.resize(etarget._parent, e)
		return false //cancel default dragging behavior
	},

	getviewpoint:function(){ //get window viewpoint numbers
		var ie=document.all && !window.opera
		var domclientWidth=parseInt(document.documentElement.clientWidth) || 100000 //Preliminary doc width in non IE browsers
		var domclientHeight=parseInt(document.documentElement.clientHeight) || 100000 //Preliminary doc Height in non IE browsers
		this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
		this.scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
		this.scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
		this.docwidth=(ie)? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-20)
		this.docheight=(ie)? this.standardbody.clientHeight: (/Safari/i.test(navigator.userAgent))? window.innerHeight : Math.min(domclientHeight, window.innerHeight-20)
		return;
	},

	rememberattrs:function(t){ //remember certain attributes of the window when it's minimized or closed, such as dimensions, position on page
		this.getviewpoint() //Get current window viewpoint numbers
		t.lastx=parseInt((t.style.left || t.offsetLeft))//-dhtmlwindow.scroll_left //store last known x coord of window just before minimizing
		t.lasty=parseInt((t.style.top || t.offsetTop))//-dhtmlwindow.scroll_top
		t.lastwidth=parseInt(t.style.width) //store last known width of window just before minimizing/ maximizing/ closing
		t.lastheight=parseInt(t.contentarea.style.height) //store last known height of window just before minimizing/maximizing /closing
	},

	move:function(t, e){
		t.style.left=dhtmlwindow.distancex+dhtmlwindow.initx+"px"
		t.style.top=dhtmlwindow.distancey+dhtmlwindow.inity+"px"
	},

	resize:function(t, e){
		t.style.width=Math.max(dhtmlwindow.width+dhtmlwindow.distancex, 150)+"px"
		t.contentarea.style.height=Math.max(dhtmlwindow.contentheight+dhtmlwindow.distancey, 100)+"px"
		t.setBackground(t)
	},
	titleDBClick:function(t){
		if(t.maximizeBool==1){
			var d=dhtmlwindow;
			var sourceobj = t.controls.childNodes[1]
			if(t.state =='minimized' || t.state =='maximized')
				d.restore(t.controls.childNodes[0],t)
			else if(t.state =='fullview')
				d.maximize(t.controls.childNodes[1],t)
		}		
	},

	enablecontrols:function(e){
		
		var d=dhtmlwindow
		var sourceobj=window.event? window.event.srcElement : e.target //Get element within "handle" div mouse is currently on (the controls)		
		if(!sourceobj)
			sourceobj=window.event.target;			
		if (/Minimize/i.test(sourceobj.getAttribute("title"))) //if this is the "minimize" control
			d.minimize(sourceobj, this._parent)
		else if (/Maximize/i.test(sourceobj.getAttribute("title"))) //if this is the "maximize" control
			d.maximize(sourceobj,this._parent)
		else if (/Restore/i.test(sourceobj.getAttribute("title"))) //if this is the "restore" control
			d.restore(sourceobj, this._parent)
		else if (/Close/i.test(sourceobj.getAttribute("title"))) //if this is the "close" control
			d.close(this._parent)
		return false
	},

	minimize:function(button, t){
		dhtmlwindow.rememberattrs(t)
		button.className = 'drag-controls-restore'
		button.setAttribute("title", "Restore")
		t.controls.childNodes[1].style.display='none'

		t.state="minimized" //indicate the state of the window as being "minimized"
		t.contentarea.style.display="none"
		t.statusarea.style.display="none"
		if (typeof t.minimizeorder=="undefined"){ //stack order of minmized window on screen relative to any other minimized windows
			dhtmlwindow.minimizeorder++ //increment order
			t.minimizeorder=dhtmlwindow.minimizeorder
		}
		t.style.left="10px" //left coord of minmized window
		t.style.width="200px"
		var windowspacing=t.minimizeorder*10 //spacing (gap) between each minmized window(s)
		t.style.top=dhtmlwindow.scroll_top+dhtmlwindow.docheight-(t.handle.offsetHeight*t.minimizeorder)-windowspacing+"px"
		t.setBackground(t);
	},
	maximize:function(button,t){ //set window full size 
		dhtmlwindow.rememberattrs(t)
		if (t.minimizeBool==1){
			t.controls.childNodes[0].className = 'drag-controls-minimize'
			t.controls.childNodes[0].setAttribute("title", "Minimize")
		}
		t.controls.childNodes[1].className = 'drag-controls-restore'
		t.controls.childNodes[1].setAttribute("title", "Restore")
		t.state="maximized" //indicate the state of the window as being "maximized"
		t.moveTo(t.maxLeft,(t.maxTop - this.scroll_top));
		self.scroll(0,0)
		
		var maxWidth = t.maxWidth > 0 ? t.maxWidth : this.docwidth;
		var maxHeight = t.maxHeight > 0 ? t.maxHeight : this.docheight;

		t.setSize((maxWidth - t.maxLeft),(maxHeight - t.maxTop - 20));
		t.contentarea.style.display='';

		if (typeof t.maximizeorder=="undefined"){ //stack order of minmized window on screen relative to any other minimized windows
			dhtmlwindow.maximizeorder++ //increment order
			t.maximizeorder=dhtmlwindow.maximizeorder
		}
		t.setBackground(t);
	},
	restore:function(button, t){
		dhtmlwindow.getviewpoint()
		if (t.state == 'minimized'){
			if (t.minimizeBool==1){
				t.controls.childNodes[0].className = 'drag-controls-minimize'
				t.controls.childNodes[0].setAttribute("title", "Minimize")
			}
			if (t.maximizeBool==1){
				t.controls.childNodes[1].style.display='';
				t.controls.childNodes[1].className = 'drag-controls-maximize'
				t.controls.childNodes[1].setAttribute("title", "Maximize")
			}
		}else if(t.state == 'maximized'){
			if (t.maximizeBool==1){
				t.controls.childNodes[1].style.display='';
				t.controls.childNodes[1].className = 'drag-controls-maximize'
				t.controls.childNodes[1].setAttribute("title", "Maximize")
			}
		}
		t.state="fullview" //indicate the state of the window as being "fullview"
		t.style.display="block"
		t.contentarea.style.display="block"
		if (t.resizeBool) //if this window is resizable, enable the resize icon
			t.statusarea.style.display="block"
		t.style.left=parseInt(t.lastx)+'px'//+dhtmlwindow.scroll_left+"px" //position window to last known x coord just before minimizing
		t.style.top=parseInt(t.lasty)+'px'//+dhtmlwindow.scroll_top+"px"
		t.style.width=parseInt(t.lastwidth)+"px"
		t.contentarea.style.height=parseInt(t.lastheight)+"px"
		t.setBackground(t);
	},


	close:function(t){
		try{
			var closewinbol=t.onclose()
		}
		catch(err){ //In non IE browsers, all errors are caught, so just run the below
			var closewinbol=true
	 }
		finally{ //In IE, not all errors are caught, so check if variable isn't defined in IE in those cases
			if (typeof closewinbol=="undefined"){
				alert("An error has occured somwhere inside your \"onclose\" event handler")
				var closewinbol=true
			}
		}
		if (closewinbol){ //if custom event handler function returns true
			if (t.state!="minimized") //if this window isn't currently minimized
				dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing
			if (window.frames["_iframe-"+t.id]) //if this is an IFRAME DHTML window
				window.frames["_iframe-"+t.id].location.replace("about:blank")
			else
				t.contentarea.innerHTML=""
			t.style.display="none"
			t.isClosed=true //tell script this window is closed (for detection in t.show())
		}
		return closewinbol
	},


	setopacity:function(targetobject, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
		if (!targetobject)
			return
		if (targetobject.filters && targetobject.filters[0]){ //IE syntax
			if (typeof targetobject.filters[0].opacity=="number") //IE6
				targetobject.filters[0].opacity=value*100
			else //IE 5.5
				targetobject.style.filter="alpha(opacity="+value*100+")"
			}
		else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
			targetobject.style.MozOpacity=value
		else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
			targetobject.style.opacity=value
	},

	setfocus:function(t){ //Sets focus to the currently active window
		this.zIndexvalue++
		t.style.zIndex=this.zIndexvalue
		t.isClosed=false //tell script this window isn't closed (for detection in t.show())
		this.setopacity(this.lastactivet.handle, 0.5) //unfocus last active window
		this.setopacity(t.handle, 1) //focus currently active window
		this.lastactivet=t //remember last active window
	},

	setBackground:function(t){
		t.fb.style.width = (t.offsetWidth-4)+"px";
		t.fb.style.height = (t.offsetHeight-4)+"px";
	},

	show:function(t){
		if (t.isClosed){
			alert("DHTML Window has been closed, so nothing to show. Open/Create the window again.")
			return
		}
		if (t.lastx) //If there exists previously stored information such as last x position on window attributes (meaning it's been minimized or closed)
			dhtmlwindow.restore(t.controls.firstChild, t) //restore the window using that info
		else
			t.style.display="block"
		this.setfocus(t)
		t.state="fullview" //indicate the state of the window as being "fullview"
	},

	hide:function(t){
		t.style.display="none"
	},

	ajax_connect:function(url, t){
		var page_request = false
		var bustcacheparameter=""
		if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject){ // if IE6 or below
			try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}
		else
			return false
		t.contentarea.innerHTML=this.ajaxloadinghtml
		page_request.onreadystatechange=function(){dhtmlwindow.ajax_loadpage(page_request, t)}
		if (this.ajaxbustcache) //if bust caching of external page
			bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		page_request.open('GET', url+bustcacheparameter, true)
		page_request.send(null)
	},

	ajax_loadpage:function(page_request, t){
		if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		t.contentarea.innerHTML=page_request.responseText
		}
	},


	stop:function(){
		dhtmlwindow.etarget=null //clean up
		document.onmousemove=null
		document.onmouseup=null
	},

	addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
		var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
		if (target.addEventListener)
			target.addEventListener(tasktype, functionref, false)
		else if (target.attachEvent)
			target.attachEvent(tasktype, functionref)
	},

	cleanup:function(){
		for (var i=0; i<dhtmlwindow.tobjects.length; i++){
			dhtmlwindow.tobjects[i].handle._parent=dhtmlwindow.tobjects[i].resizearea._parent=dhtmlwindow.tobjects[i].controls._parent=null
		}
		window.onload=null
	}

} //End dhtmlwindow object

document.write('<div id="dhtmlwindowholder"><span style="display:none">.</span></div>') //container that holds all dhtml window divs on page
window.onunload=dhtmlwindow.cleanup


//******************************** MODAL WINDOW FUNCTIONS ******************************************//

var dhtmlmodal={
veilstack: 0,
	open:function(t, contenttype, contentsource, title, attr, recalonload,clsname){
		var d=dhtmlwindow //reference dhtmlwindow object
		var className = clsname || "dhtmlwindow";
		this.interVeil=document.getElementById("interVeil") //Reference "veil" div
		this.veilstack++ //var to keep track of how many modal windows are open right now
		this.loadveil()
		if (typeof recalonload!="undefined" && recalonload=="recal" && d.scroll_top==0)
			d.addEvent(window, function(){dhtmlmodal.loadveil()}, "load")
			var t=d.open(t, contenttype, contentsource, title, attr, recalonload,className)
		t.controls.onclick=function(){dhtmlmodal.forceclose(this._parent)} //OVERWRITE default control action with new one
		t.show=function(){dhtmlmodal.show(this)} //OVERWRITE default t.show() method with new one
		t.hide=function(){dhtmlmodal.close(this)} //OVERWRITE default t.hide() method with new one
		return t
	},


	loadveil:function(){
		var d=dhtmlwindow
		d.getviewpoint()
		this.docheightcomplete=(d.standardbody.offsetHeight>d.standardbody.scrollHeight)? d.standardbody.offsetHeight : d.standardbody.scrollHeight
		this.interVeil.style.width=d.docwidth+"px" //set up veil over page
		this.interVeil.style.height=this.docheightcomplete+"px" //set up veil over page
		this.interVeil.style.left=0 //Position veil over page
		this.interVeil.style.top=0 //Position veil over page
		this.interVeil.style.visibility="visible" //Show veil over page
		this.interVeil.style.display="block" //Show veil over page
	},

	adjustveil:function(){ //function to adjust veil when window is resized
		if (this.interVeil && this.interVeil.style.display=="block") //If veil is currently visible on the screen
			this.loadveil() //readjust veil
	},


	close:function(t){ //user initiated function used to close modal window
		t.contentDoc=(t.contentarea.datatype=="iframe")? window.frames["_iframe-"+t.id].document : t.contentarea //return reference to modal window DIV (or document object in the case of iframe
		var closewinbol=dhtmlwindow.close(t)
		if (closewinbol){ //if var returns true
			this.veilstack--
			if (this.veilstack==0) //if this is the only modal window visible on the screen, and being closed
				this.interVeil.style.display="none"
		}
	},

	forceclose:function(t){ //function attached to default "close" icon of window to bypass "onclose" event, and just close window
		dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing
		t.style.display="none"
		this.veilstack--
			//if this is the only modal window visible on the screen, and being closed
				this.interVeil.style.display="none"
	},

	show:function(t){
		dhtmlmodal.veilstack++
		dhtmlmodal.loadveil()
		dhtmlwindow.show(t)
	}
} //END object declaration

document.write('<div id="interVeil"></div>')
dhtmlwindow.addEvent(window, function(){if (typeof dhtmlmodal!="undefined") dhtmlmodal.adjustveil()}, "resize")

//DHTMLWINDOW JS END/////////////////////////////////////////////////


//MY AJAX JS START/////////////////////////////////////////////////

function myAjax(url, mtd, retType, options) 
{ 
	this.url = url;
	this.method = mtd.toUpperCase() || 'GET';

	this.returnType = retType.toUpperCase() || 'XML';
	
	this.options = options || {};
	this.params = this.options.params || '' ;
	this.params += "&dummy=" + new Date().getTime();
	this.callBack = this.options.callBack || '';
	this.onError = this.options.onError || '';
	this.onTimeout = this.options.onTimeout || '';
	this.header = this.options.header || new Array();
//	this.userId = this.options.userid || null;
//	this.password = this.options.password || null;
	this.httpObj = null;
	this.timeout = false;
	this.timeoutStart = new Date().getTime();
	this.timeoutConstant = 300 * 1000;  // time in miliseconds
	this.config();
	this.createAjax();
};

myAjax.prototype.config = function (){
	this.httpObj = this.httpRequest();
	if (this.url.length == 0 )
	{
		alert('please send HTTP url for ajax request...')
		return false;
	}
	if (this.returnType != 'XML' && this.returnType != 'TEXT')
	{
		this.returnType = 'XML';
	}
};

myAjax.prototype.httpRequest = function (){
	var httprequest = null;
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest = new XMLHttpRequest();
	}else if (window.ActiveXObject){ // if IE
		try {
			httprequest = new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			try{
				httprequest = new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e){
				Alert('Your browser does not support HTTP request...');
				return false;
			}
		}
	}
	if (httprequest.overrideMimeType)
		httprequest.overrideMimeType('text/xml')

	return httprequest
};


myAjax.prototype.checkTimeout = function (){
	var curTime = new Date().getTime();
	if (( curTime - this.timeoutStart) > this.timeoutConstant){
		 this.timeout = true;
	}
	if (this.timeout){
		if (this.onTimeout && this.onTimeout.length > 0 ){
			eval(this.onTimeout+'(this.httpObj.readyState)')
		}else {
			alert('Ajax call time out on status :'+this.httpObj.onreadystatechange)
		}
		return true;
	}
	return false;
};


myAjax.prototype.createAjax = function (){
	if (this.method == 'POST'){
		this.httpObj.open(this.method, this.url, true); 
		// set default request header 
		this.httpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 
		this.httpObj.setRequestHeader("Content-length", this.params.length);
		this.httpObj.setRequestHeader("Connection", "close");
		for (var x=0; x < this.header.length ;x++ )	{
			if (this.header[x][0].toUpperCase() != "Content-Type".toUpperCase() && this.header[x][0].toUpperCase() != "Content-length".toUpperCase() && this.header[x][0].toUpperCase() != "Connection".toUpperCase() )
			{
				this.httpObj.setRequestHeader(this.header[x][0],this.header[x][1])
			}
			
		}
		this.httpObj.send(this.params);
	}
	if (this.method == 'GET'){
		this.url = this.url + (this.params.length > 0 ? '?'+this.params : '')
		this.httpObj.open(this.method, this.url, true); 
		this.httpObj.send(null);
	}
	var owner = this; 
	this.httpObj.onreadystatechange = function(){
		//owner.showProgress();
		if (owner.checkTimeout()) {
			owner.httpObj.abort();
			owner.httpObj = null;
			return false;
		}
		if (owner.httpObj.readyState == 4) { // done
			var ajaxResponse = null;
			owner.hideProgress();
			switch (owner.httpObj.status) {
				case 200:
					if (owner.httpObj.responseText.indexOf('ErrorOnSessionExpire') > -1 ) {
						if (owner.onError || owner.onError > 0){
							eval(owner.onError+ '(owner.httpObj.responseText)')
						}else{
							owner.handleErrFullPage('<h1>Error:</h1></p><h1>'+owner.httpObj.responseText+'</h1>');
						}
					}
					else {
						if (owner.returnType == 'XML') { 
							ajaxResponse = owner.httpObj.responseXML;
						}else{
							ajaxResponse = owner.httpObj.responseText;
						}

						if (owner.callBack || owner.callBack > 0){
							eval(owner.callBack + '(ajaxResponse)');
						}
					}
					break;
				case 404:
					alert('Error: Not Found. The requested URL ' + owner.url + ' could not be found.\n'+owner.httpObj.statusText);
					break;
				default:
					owner.handleErrFullPage(owner.httpObj.responseText);
					break;
			}
		}
	}

};


myAjax.prototype.showProgress = function(){
	var processAjax = document.getElementById('processAjax');
	if (!processAjax)
	{
		processAjax = document.createElement('div');
		processAjax.id = 'processAjax'
		processAjax.className = 'processAjax'
		processAjax.style.cssText = "position:absolute;left:0px;top:0px;width:100px;height:100px;background-color:#aaaaaa;z-index:99;filter:alpha(opacity=40);text-align:center;vertical-align:center;"
		span = document.createElement('span');
		span.innerHTML = '&nbsp;'
		span.style.cssText = 'width:100%;height:100%;background:url(../images/myloader.gif) center center no-repeat;'
		processAjax.appendChild(span);
		document.body.appendChild(processAjax);
	}
	processAjax.style.display='block';
	var ajaxPos = this.windowCenter({'width':processAjax.offsetWidth,'height':processAjax.offsetHeight})
	processAjax.style.left = ajaxPos.x
	processAjax.style.top = ajaxPos.y
};

myAjax.prototype.hideProgress = function(){
	var ajaxProcess = document.getElementById('processAjax');
	if (ajaxProcess){
		ajaxProcess.style.display='none'
	}
};

myAjax.prototype.getUrl = function(){
	return this.url;
};

myAjax.prototype.getResponse = function(){
	if (this.httpObj.readyState == 4 && this.httpObj.status == 200) {
		if (this.returnType == 'XML') { 
			return this.httpObj.responseXML;
		}else{
			return this.httpObj.responseText;
		} 
	}
	return null;
};



myAjax.prototype.handleErrFullPage = function(strIn) {
	var errorWin;
	try {
		errorWin = window.open('', 'Error');
		errorWin.document.body.innerHTML = strIn;
	}
	catch(e) {
		alert('An error occurred, but the error message cannot be displayed because of your browser\'s pop-up blocker.\n' +
		'Please allow pop-ups from this Web site.');
	}
	
};



myAjax.prototype.getPageScroll =function () {
	if(!window.pageYOffset)	{
		//strict mode
		if(!(document.documentElement.scrollTop == 0))	{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}
  return { 'x': offsetX, 'y': offsetY };
};



//-----------------------------------------------------------------------------
myAjax.prototype.windowCenter= function ()	{
	var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
	var _x = 0;
	var _y = 0;
	_pgScroll = this.getPageScroll();
	_winSize = this.getWindowSize();
	_x = ((_winSize.width - hWnd.width)/2)+_pgScroll.x;
	_y = ((_winSize.height - hWnd.height)/2)+_pgScroll.y;

	return{x:_x,y:_y};
};
//-----------------------------------------------------------------------------
myAjax.prototype.getWindowSize= function (){
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth){
		//strict mode
		if(!(document.documentElement.clientWidth == 0)){
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
};


//MY AJAX JS END/////////////////////////////////////////////////

//MY AUTOSUGGEST JS START/////////////////////////////////////////////////

var autoSuggestElementObj;
var autoSuggestRows;
var autoListMouseOut;
var autoSuggestXMLTagName;
var servletDataListName;
var servletRootPath;
var autoListContainer = 'auto_suggest_list';
var dummyContainer = 'dummy_auto_suggest_list';
var autoListClassName = 'suggest_list';
var autoListLinkClassName = 'suggest_link';
var autoListLinkOverClassName = 'suggest_link_over';
var autoListContextPath = getContextPath();

function fillAutoSuggest(event,obj){
	var key = keygetter(event);
	switch(key){
		case 9: setAutoSuggestValue(obj); break; /* tab key */
	}
}

function autoSuggestFocus(obj){
	obj.select();
	autoListMouseOut = false;
	autoSuggestElementObj = obj;
	if(obj$(dummyContainer)!=null)
		hide$(dummyContainer);
	
	if(obj$(autoListContainer)!=null)
		hide$(autoListContainer);
}


function searchAutoSuggest(event,obj,dataList,tagName,keyLen,idLen,rows,width,root){
	servletDataListName = dataList ? dataList : 'airportList';
	autoSuggestXMLTagName = tagName ? tagName : 'airport';
	servletRootPath = root ? root : null;
	autoListMouseOut = false;
	autoSuggestElementObj = obj;
	autoSuggestRows = rows || 10;
	autoSuggestListWidth = width || obj.offsetWidth;
	codeWidth = idLen || 3;
	autoKeyLen = keyLen || 3;

	var key = keygetter(event);
	var objSuggestList = getAutoSuggestListContainer();
	var objDummy = obj$(dummyContainer);

	var oPos = getObjectPos$(obj);

	obj.setAttribute('autocomplete','off');
	obj.onblur = function(){ fireBlur(this);};

	objSuggestList.style.top = oPos.y+obj.offsetHeight+'px';
	objSuggestList.style.left = (oPos.x+1)+'px';
	objSuggestList.style.width = autoSuggestListWidth+"px";

	objDummy.style.top = oPos.y+obj.offsetHeight+'px';
	objDummy.style.left = (oPos.x+1)+'px';
	objDummy.style.width = autoSuggestListWidth+"px";
	objDummy.style.border = 'none';

	
	objSuggestList.onmouseout = function(){autoListMouseOut = false; };
	objSuggestList.onmouseover = function(){autoListMouseOut = true; };
	objSuggestList.onblur = function() {fireBlur(obj);};
	objSuggestList.onkeyup = function() { keyHandler(event,this); };
	
	if (obj.value.length < autoKeyLen || key == 27){
		hide$(objSuggestList);
		hide$(dummyContainer);

		if ( key == 27){
			obj.value="";
		}
		return false;
	}
	switch(key){
		case 37: break; /* left arrow */
		case 39: break; /* right arrow */
		case 33: break; /* page up  */
		case 34: break; /* page down  */
		case 36: break; /* home  */
		case 35: break; /* end     */             
		case 9:  break; /* tab  */
		case 27: break; /* esc  */
		case 16: break; /* shift  */
		case 17: break; /* ctrl  */
		case 18: break; /* alt  */
		case 20: break; /* caps lock */
		case 38: doScrollUp(objSuggestList); break; /* up arrow */
		case 40: doScrollDown(objSuggestList); break; /* down arrow */
		case 13: setAutoSuggestValue(obj); break; /* Enter key */
		default: getDataByAjax(obj.value);	break;
	}
}

function getDataByAjax(value){
	var root = servletRootPath ? servletRootPath : autoListContextPath+"/DataListServlet";
	var url = root;
	var params="";
	if(servletDataListName !="hotelList" && servletDataListName !="stationList"){
		params = "name="+servletDataListName+"&key="+value;
	}else{
		params = "name="+servletDataListName+"&cityCode="+cityCOdeForGtaServlet+"&key="+value;
	}

		var suggestAjax = new myAjax(url, 'get', 'xml', {'params':params,'callBack':'autoSuggestData'});
}

function autoSuggestData(xmlResponse){
	var xmlDataList = xmlResponse.getElementsByTagName(autoSuggestXMLTagName);
	createAutoSuggestList(xmlDataList);
}

function createAutoSuggestList(xmlList){
	var objSuggestList = obj$(autoListContainer);
	var objDummy = obj$(dummyContainer);
	var listLength = xmlList.length;
	var ifHeight = 0;
	if ( listLength > autoSuggestRows){
		objSuggestList.style.height = (autoSuggestRows * 18)+"px";
		ifHeight = autoSuggestRows * 18;
	}else{
		objSuggestList.style.height = "auto";
		ifHeight = listLength * 18;
	}
	objDummy.innerHTML='<iframe src="" FRAMEBORDER=0 style=";z-index:-1;position:relative;border:none; left:0px;top:0px;margin:0; padding:0;height:'+ifHeight+'px;width:100%;" id="_iframe_'+autoListContainer+'"></iframe>'
	objSuggestList.innerHTML='';

	hide$(objDummy);
	hide$(objSuggestList);

	if (xmlList.length > 0){
		for (var x=0;x<xmlList.length ;x++ ){
			var listItem = document.createElement('div');
			listItem.id = x;
			listItem.className = autoListLinkClassName;
			listItem.onmouseover = function() { autoListMouseOut = true; autoSuggestOver(objSuggestList);this.className = autoListLinkOverClassName};
			listItem.onclick = function() { setAutoSuggestValue(autoSuggestElementObj);};
			listItem.onmouseout = function(){autoListMouseOut = false;};
			listItem.innerHTML = xmlList[x].getAttribute('display');

			objSuggestList.appendChild(listItem);
		}
		objSuggestList.scrollTop = 0;
		objSuggestList.firstChild.className = autoListLinkOverClassName;
		show$(objDummy);
		show$(objSuggestList);

	}
}

function autoSuggestOver(listObj){
	var obj = listObj.childNodes;
	for (var x =0; x < obj.length ;x++ ){
		if (obj[x].className == autoListLinkOverClassName){
			obj[x].className = autoListLinkClassName;
		}
	}
}

function setAutoSuggestValue(obj){
	var pathName=window.location.pathname;
	if(obj$(autoListContainer)!=null){
		
	var objList = obj$(autoListContainer).childNodes;
	if (objList && objList.length > 0){
		var elNo = getCurrentElement(objList);
		obj.value = objList[elNo].innerHTML;
	}
	hide$(dummyContainer);
	hide$(autoListContainer);
	if(pathName!=autoListContextPath+"/oueb2c/jsp/transfersReview.jsp"){
	if (servletDataListName.indexOf('irport') != -1){ //as index of is case sensitive so Airport and airport is different. add by afsar
		setPresetValue(obj) // set value in to sector for multicity
		fillDropOffloc(obj) // for car dropoff value setting
	}
	}
	}
}

function doScrollUp(objList){
	var obj = objList.childNodes;
	var elNo = getCurrentElement(obj);
	if (elNo > 0){
		obj[elNo].className = autoListLinkClassName;
		obj[elNo-1].className = autoListLinkOverClassName;

		if (elNo+1 > autoSuggestRows -1 ){
			objList.scrollTop -= 18;
		}
	}
}

function doScrollDown(objList){
	var obj = objList.childNodes;
	var elNo = getCurrentElement(obj);
	if (elNo < obj.length -1){
		obj[elNo].className = autoListLinkClassName;
		obj[elNo+1].className = autoListLinkOverClassName;
		if (elNo+1 >= autoSuggestRows - 1 ){
			objList.scrollTop += 18;
		}
	}
}

function getCurrentElement(objList){
	var elNo=0;
	for (var x= 0;x < objList.length ;x++ ){
		if (objList[x].className==autoListLinkOverClassName){
			elNo = x;
			break;
		}
	}
	return elNo;
}

function keygetter(e){
	var key=27;
	var evt = e ? e :window.Event;
	key = evt.keyCode ? evt.keyCode : e.which;
	return key;
}


function fireBlur(obj){
	if (!autoListMouseOut){
		hide$(dummyContainer);
		hide$(autoListContainer); 
		if (obj.value=="" )	{
			// set your function
		}
	}
}

function keyHandler(event, obj){
	var key = keygetter(event); 
	switch (key){
		case 38: doScrollUp(obj);break; // up arrow
		case 40: doScrollDown(obj);break; // down arrow
		case 13: setAutoSuggestValue(autoSuggestElementObj); break; /* Enter key */
	}
}

function getAutoSuggestListContainer(){		
	var objSuggestList = obj$(autoListContainer);
	if (!objSuggestList){
		var objDummy = document.createElement('div');
		objDummy.style.display='none';
		objDummy.id = dummyContainer;
		objDummy.className = autoListClassName;

		objSuggestList = document.createElement('div');
		objSuggestList.style.display='none';
		objSuggestList.id = autoListContainer;
		objSuggestList.className = autoListClassName;

		document.body.appendChild(objDummy);
		document.body.appendChild(objSuggestList);
	}
	return objSuggestList;
}

function getCodeFromValue(id,token,len){
	var retValue = "";
	var fToken = new Array('(','[','{');
	var lToken = new Array(')',']','}');
	var tPos = 0;
	for (x=0;x<fToken.length ;x++ ){
		if (token == fToken[x] || token == lToken[x]){
			tPos = x;
			break;
		}
	}
	var v = obj$(id).value;
	var tokenFPos = v.indexOf(fToken[tPos]);
	var tokenLPos = v.indexOf(lToken[tPos],tokenFPos);
	if (tokenFPos >= 0 && tokenLPos > tokenFPos){
		len = tokenLPos - tokenFPos;
		retValue = v.substr(tokenFPos+1,len-1);
	}else {
		retValue = v.substr(0,len);
	}
	return retValue;
}
/*
//added by beall
function hotelAutoSuggestTour(xmlResponse) {

	var cityList = xmlResponse.getElementsByTagName('hotel')
	createAutoSuggestListForTour(cityList);
}

//addded by belal
function getHotelCodeForTour(value) {
	// var url = getContextPath()+"/SuggestAjaxServlet";
	var url = getContextPath() + "/DataListServlet";
	 var params = "name=hotelList&cityCode="+cityCOdeForGtaServlet+"&key="+value;
	//var params = "name=airportList&key=" + value;
	var suggestAjax = new myAjax(url, 'get', 'xml', {
		'params' :params,
		'callBack' :'hotelAutoSuggestTour'
	});
}*/

//MY AUTOSUGGEST JS END/////////////////////////////////////////////////


//NEW_TABLE JS START/////////////////////////////////////////////////
//------------------------------------------------------------------
function myTable(_cid,_header,_rows,_footer,options){
	this.container = document.getElementById(_cid);
	if (! this.container || typeof(this.container) == 'undefined'){
		alert('Invalid table container...')
		return false;
	}

	function getHTMLTable(_rows){
		var t = document.getElementById(_rows)
		var rows = t.rows
		var tData= new Array()
		for(x=0 ;x<rows.length;x++){
			var cells = rows[x].cells;
			var tRow = new Array()
			if(cells[0].tagName != "TH"){
				for(y=0;y<cells.length;y++){
					tRow[y] = cells[y].innerHTML
				}
				tData[tData.length] = tRow;
			}
		}
		t.style.display='none';
		return tData;
	}

	function getXMLData(_rows){
		var rows = _rows
		var tData= new Array()
		for(x=0 ;x<rows.length;x++){
			var cells = rows[x].getElementsByTagName('Cell');
			var tRow = new Array()
			for(y=0;y<cells.length;y++){
				tRow[y] = cells[y].firstChild.nodeValue;
			}
			tData[tData.length] = tRow;
		}
		return tData;
	}

	this.container.innerHTML='';
	this.cId = _cid;
	this.tHeader = _header || {};
	this.tRows = _rows || new Array();
	this.tFooter = _footer || new Array();
	this.options = options || { };
	this.input = this.options.input || 'A';
	if(this.input.toUpperCase().substr(0,1) == 'T'){
		this.tRows = getHTMLTable(_rows)
	} else if(this.input.toUpperCase().substr(0,1) == 'X'){
		this.tRows = getXMLData(_rows)
	}
	this.title = this.options.title || null;
	this.title = (this.title && this.title.length > 0 ? this.title : null);
	this.tClass = this.options.className || 'mytables';
	this.tType = this.options.type || 'P';
	this.tType = this.tType.toUpperCase().substr(0,1);
	this.tHeight = this.options.height || (this.tType == 'P' ? 10 : 200);
	this.tLang = this.options.lang || {};
	this.filterInput="";
	this.dataArray = this.tRows;
	this.noOfCols = this.tHeader.length || 0;
	this.displayableCols = 0;
	this.tWidth = 0 ;
	this.rHeight = 18;
	this.tHeadHeight = 22;
	this.dataRowsHeight = 0;
	this.scrollbarWidth = 0 ;
	this.noOfRowsPerPage = (this.tType == 'P' ? this.tHeight : 0);
	this.noOfRows = 0;
	this.noOfFilteredRows = 0;
	this.noOfPages = 1;
	this.browser = this.getBrowser(); 
	for (var x=0;x<_header.length ;x++ ){
		if (typeof(_header[x].width) == 'undefined' || _header[x].width == null) this.tHeader[x].width = 50 ; else this.tHeader[x].width = parseInt(this.tHeader[x].width);
		if (typeof(_header[x].filter) == 'undefined' || _header[x].sortable == null) this.tHeader[x].filter = false;
		if (typeof(_header[x].sortable) == 'undefined' || _header[x].sortable == null) this.tHeader[x].sortable = false;
		if (typeof(_header[x].sort_type) == 'undefined' || _header[x].sort_type == null) this.tHeader[x].sort_type = 'TEXT';
		if (typeof(_header[x].display) == 'undefined' || _header[x].display == null) this.tHeader[x].display = true;
		if (typeof(_header[x].toolTip) == 'undefined' || _header[x].toolTip == null) this.tHeader[x].toolTip = false;
		if (typeof(_header[x].toolTipText) == 'undefined' || _header[x].toolTipText == null) this.tHeader[x].toolTipText = "";
		if (typeof(_header[x].align) == 'undefined' || _header[x].align == null) this.tHeader[x].align = 'left';
	}
	this.dataTable;
	this.tableHeading;
	this.tableRows;
	this.divRows;
	this.tableFooter;
	this.tableFooterPagination;
	this.config();
	this.createMyTable();
	this.visible ? this.show() : this.hide();
	if (this.tType =='S' ) { this.divRows.style.width = this.tableHeading.offsetWidth + (this.browser.ns ? -1:0); }
};
//-----------------------------------------------------------------------------
myTable.prototype.config = function (){
	this.setTableHeight();
	this.setTableWidth();
	this.setLang();
	this.visible = true;
};
//-----------------------------------------------------------------------------
myTable.prototype.setTableHeight = function (){
	this.dataRowsHeight =  this.tHeight - this.tHeadHeight;
	this.noOfRows = this.tRows.length;
	this.noOfFilteredRows = this.tRows.length;
	if (this.tType == 'S'){
		if (this.tHeight < 100)	{ this.tHeight = 100; }
		this.scrollbarWidth =  18 + (this.browser.ns ? -5:0); 
		this.tableHeight = this.tHeight
	}
	if (this.tType == 'P'){
		this.noOfPages =Math.ceil(this.noOfRows / this.noOfRowsPerPage);
		this.tableHeight = this.noOfRowsPerPage * this.rHeight;
	}
};
//-----------------------------------------------------------------------------
myTable.prototype.setTableWidth = function (){
	for (var x=0;x<this.tHeader.length ;x++ ){
		if (this.tHeader[x].display){
			this.displayableCols++;
			if (this.tHeader[x].filter)	
				this.tHeader[x].width += 12;
			this.tWidth += parseInt(this.tHeader[x].width) ; 
		}
	}
	this.tWidth += this.scrollbarWidth;
};
//-----------------------------------------------------------------------------
myTable.prototype.show = function () {
	this.dataTable.style.display = 'block';
	this.visible = true;
};
//-----------------------------------------------------------------------------
myTable.prototype.hide = function () {
	this.dataTable.style.display = 'none';
	this.visible = false;
};
//-----------------------------------------------------------------------------
myTable.prototype.toggle = function () {
	if(this.visible) { this.hide(); }
	else { this.show();}
};
//-----------------------------------------------------------------------------
myTable.prototype.setLang = function() {
	this.sortText = this.tLang.sortText || "click to sort on ";
	this.ofText = this.tLang.ofText || "of";
	this.pageText = this.tLang.pageText || "page(s)";
	this.totalText = this.tLang.totalText || "Total:";
	this.rowText = this.tLang.rowText || "row(s)";
	this.firstPageText = this.tLang.firstPageText || "first page";
	this.prevPageText = this.tLang.prevPageText || "previous page";
	this.nextPageText = this.tLang.nextPageText || "next page";
	this.lastPageText = this.tLang.lastPageText || "last page";
	this.sRowsPerPageText = this.tLang.rowsPerPageText || "Rows/Page:";
	this.months = this.tLang.months || ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
	myTableMonths = this.months;
};
//-----------------------------------------------------------------------------
function toDate(s,months){
	if(months == null) months = myTableMonths;
	var _date = s;
	if (typeof(s)=='string'){
		var _sDate=s.split("-");
		var _month=0;
		if(_sDate.length > 2){
			for (var x = 0; x < months.length ;x++ ){
				if(_sDate[1].toUpperCase()== months[x].toUpperCase()) {
					_month=x;
					break;
				}
			}
			_date = new Date(_sDate[2],_month,_sDate[0]);
		}
	}
	return _date;
};
//-----------------------------------------------------------------------------
myTable.prototype.createLoader = function () {
	this.loader = document.createElement('div')
	this.setClass(this.loader,'loader')
	this.loader.style.display = 'none';
	this.loader.style.width = this.tWidth;
	this.loader.style.height = this.tableHeight ;
	return this.loader;
};
//-----------------------------------------------------------------------------
myTable.prototype.showLoader = function () {
	this.loader.style.width = (this.dataTable.offsetWidth ? this.dataTable.offsetWidth : this.tWidth );
	this.loader.style.height = (this.dataTable.offsetHeight ? this.dataTable.offsetHeight : this.tableHeight );
	this.loader.style.display = 'block';
	this.loader.style.zIndex = 1000;
};
//-----------------------------------------------------------------------------
myTable.prototype.hideLoader = function () {
	this.loader.style.display = 'none';
};
//-----------------------------------------------------------------------------
myTable.prototype.createMyTable = function () {
	var tbody, thead,tfoot, tr, td;
	this.container.appendChild(this.createLoader());
	this.tableId = this.cId+'_table';
	this.headerId = this.cId+'_table_head';
	this.bodyId = this.cId+'_table_body';
	this.footerId = this.cId+'_table_foot';
	this.dataTable = this.createTable(this.tableId,this.tClass,0,0,this.tWidth,null,0);
	this.showLoader();
	this.dataTable.onselectstart = function() {return false;};
	this.dataTable.ondrag = function() {return false;};

	tbody = document.createElement('tbody');
	if(this.title) {
		tr = document.createElement('tr')
		td = document.createElement('td');
		this.setClass( td,'title');
		td.appendChild(this.tableCaption());
		tr.appendChild(td);
		tbody.appendChild(tr);
	}
	
	tr = document.createElement('tr')
	td = document.createElement('td');
	td.setAttribute('id',this.headerId);
	td.appendChild(this.createHeadingTable(this.headerId));
	tr.appendChild(td);
	tbody.appendChild(tr);

	tr = document.createElement('tr')
	td = document.createElement('td');
	td.setAttribute('id',this.bodyId);
	td.appendChild(this.createDataTable(this.bodyId));
	tr.appendChild(td);
	tbody.appendChild(tr);
	
	tr = document.createElement('tr')
	td = document.createElement('td');
	td.setAttribute('id',this.footerId);
	td.appendChild(this.createFooterTable(this.footerId));
	tr.appendChild(td);
	tbody.appendChild(tr);

	this.loader.style.display = 'none'
	this.dataTable.appendChild(tbody);
	this.dataTable.owner = this;
	this.container.appendChild(this.dataTable);
	this.hideLoader();
	
	this.filterPopup = document.createElement('div');
	this.setClass( this.filterPopup,'filterpopup');
	this.filterPopup.innerHTML = '<label id="1">1</label>&nbsp;<select><option value="S">Start with</option><option value="E">End with</option><option value="C">Contain</option></select>&nbsp;<input type="text" value=""><div><div class="filterButton" id="reset" >Reset</div><div class="filterButton" id="cancel">Cancel</div><div class="filterButton" id="apply">Apply</div></div>'

	this.container.appendChild(this.filterPopup);
};
//-----------------------------------------------------------------------------
myTable.prototype.tableCaption = function () {
	var lable = document.createElement('lable')
	lable.innerHTML = this.title
	return lable;
};
//-----------------------------------------------------------------------------
myTable.prototype.createHeadingTable = function (hId) {
	var tableHeadingId = hId +'_table';
	var tbody,tr;
	this.tableHeading = this.createTable(tableHeadingId,'heading',2,0,this.tWidth,null,0);
	thead = document.createElement('thead');
	tr = document.createElement('tr');
	for( var x = 0; x < this.noOfCols; x++) {
		if (this.tHeader[x].display){
			var th = document.createElement('th');
			var hLabel = document.createElement('div');
			th.setAttribute('id',x);
			th.onmouseover = function(){this.owner.setClass(this,'mouseover');};
			th.onmouseout = function(){this.owner.setClass(this,'');};

			th.style.width = this.tHeader[x].width - 1
			hLabel.setAttribute('id',x);			
			hLabel.style.width = this.tHeader[x].filter ? this.tHeader[x].width - 12 -1 : this.tHeader[x].width - 1
			hLabel.innerHTML = this.tHeader[x].title;
			hLabel.style.textAlign = this.tHeader[x].align;
			hLabel.owner = th.owner = this;
			if (this.tHeader[x].sortable) {
				hLabel.scope = this.tHeader[x].sort_type;
				hLabel.className= 'sortable';
				hLabel.title = this.sortText +'<'+ this.tHeader[x].title +'>'
				hLabel.onclick = function() {this.owner.showLoader(); this.owner.sortData(this);this.owner.hideLoader()}; 
			}
			th.appendChild(hLabel);
			if (this.tHeader[x].filter)	{
				var hFilter = document.createElement('div');
				hFilter.owner = this;
				hFilter.setAttribute('id',x);
				hFilter.scope = this.tHeader[x].sort_type+";"+this.tHeader[x].title;
				this.setClass(hFilter,'filter')
				hFilter.title = 'click to filter on <'+this.tHeader[x].title+'>';
				hFilter.onclick = function() {this.owner.showFilterPopup(this)}; 
				th.appendChild(hFilter);
			}
			tr.appendChild(th);
		}
	}
	if (this.tType == 'S'){
		th = document.createElement('th');
		th.style.width = this.scrollbarWidth
		tr.appendChild(th);
	}
	thead.appendChild(tr);
	this.tableHeading.appendChild(thead);
	return this.tableHeading;
};

//------------------------------------------------------------------------------

myTable.prototype.createDataTable = function(bId) {
	var tableRowsId = bId +'_table';
	var tbody;
	this.tableRows = this.createTable(tableRowsId,'datarow',2,0,this.tWidth,null,0);
	tbody = this.createDataRows(0);
	this.tableRows.appendChild(tbody);
	if (this.tType == 'S'){
		this.tableRows.style.width = this.tWidth - this.scrollbarWidth;
		this.divRows = document.createElement('div')
		this.divRows.style.height = this.dataRowsHeight;
		this.divRows.style.width = this.tWidth + (this.browser.ns ? 1 : 0);
		this.setClass(this.divRows,'datascroll');
		this.divRows.style.overflow = 'auto'
		this.divRows.appendChild(this.tableRows);
		return this.divRows
	}
	return this.tableRows;
};
//------------------------------------------------------------------------------
myTable.prototype.createDataRows = function(rowPos){
	var tbody = document.createElement('tbody');
	var dataRow;
	var c=0;
	for (var x=rowPos;x<this.noOfRows ; x++){
		tbody.appendChild(this.createRow(this.tRows[x], c++));
		if (this.tType == 'P' && c >= this.noOfRowsPerPage) { break; }
	}
	if ( this.tType == 'P' && c < this.noOfRowsPerPage && this.noOfPages > 1){
		for (x=c; x < this.noOfRowsPerPage ;x++ ) { tbody.appendChild(this.createRow(this.createEmptyRow(),c++)); }
	}
	if (this.tType == 'S' && c * this.rHeight < this.dataRowsHeight){
		for (x=c; c * this.rHeight < this.dataRowsHeight; x++){ tbody.appendChild(this.createRow(this.createEmptyRow(),c++)); }
	}
	return tbody;
};
//------------------------------------------------------------------------------
myTable.prototype.createRow = function (row , r) {
	var tr =document.createElement('tr');
	tr.id = r;
	for (var c=0;c < this.noOfCols ; c++){
		if (this.tHeader[c].display){
			td =document.createElement('td');
			span =document.createElement('span');
			td.className = (r%2 ? 'odd':'even')
			td.style.width = this.tHeader[c].width - 1; 
			td.scope=r+'~'+c
			td.style.textAlign = this.tHeader[c].align;
			if(this.tHeader[c].toolTip && (this.tHeader[c].toolTipText.length > 0))	{
				if (this.tHeader[c].toolTipText.toUpperCase() == 'DATA') {	td.title = row[c]; }
				else {	td.title = this.tHeader[c].toolTipText;}
			}
			span.innerHTML = row[c] || ' ';
			td.appendChild(span);
			tr.appendChild(td);
		}
	}
	return tr;
};
//------------------------------------------------------------------------------

myTable.prototype.createFooterTable = function(fId){
	var tableFooterId = fId +'_table'
	var tbody,tr,td,span;
	var trc,tdc,spanc;
	this.tableFooter = this.createTable(tableFooterId,'footer',2,0,'100%',null,0);
	tbody = document.createElement('tbody');
	tr =document.createElement('tr');
	if (this.tFooter.length >  0){
		for (var x=0;x<this.tHeader.length ; x++){
			if (this.tHeader[x].display){
				td =document.createElement('td');
				span =document.createElement('span');
				td.style.width = this.tHeader[x].width - 1;
				td.style.textAlign = this.tHeader[x].align;
				if ( typeof(this.tFooter[x]) != 'undefined' && this.tFooter[x] != null )
					span.innerHTML = (this.tFooter[x].length==0 ? '&nbsp;':this.tFooter[x])
				else 
					span.innerHTML = '&nbsp';
				td.appendChild(span);
				tr.appendChild(td);
			}
		}
		if (this.tType == 'S'){
			td =document.createElement('td');
			span =document.createElement('span');
			td.style.width = this.scrollbarWidth;
			td.className = 'data';
			span.innerHTML = '&nbsp;';
			td.appendChild(span);
			tr.appendChild(td);
		}
		tbody.appendChild(tr);
	}
	if (this.noOfPages > 1){ tbody.appendChild(this.createFooterPagination()); }
	this.tableFooter.appendChild(tbody);
	return this.tableFooter;
};
//------------------------------------------------------------------------------
myTable.prototype.createFooterPagination = function (){
	if (this.noOfPages <= 1)
		return null;
	var pagingTr =document.createElement('tr');
	var pagingTd =document.createElement('td');
	pagingTd.colSpan = this.displayableCols;
	pagingTd.setAttribute('width','100%');
	this.tableFooterPagination = this.createTable(null,'pagination',0,0,'100%',null,0);
	var tbody = document.createElement('tbody')
	var tr =document.createElement('tr');
	var td =document.createElement('td');
	var span =document.createElement('span');
	var img =document.createElement('img');
	var spanc,sPageText,sRowsText,sFiller;
	
	var pages = new Array();
	for (var x=0;x<this.noOfPages-1 && x < 5 ; x++){
		pages[x] = new Array((x+1)*10,(x+1)*10)
	}
	pages[x] = new Array('All',this.noOfRows)
	this.sRowsList = this.createSelect('selectrows',pages)
	sRowsListText = span.cloneNode(true);
	sRowsListText.innerHTML = '&nbsp;'+this.sRowsPerPageText;

	sFiller = span.cloneNode(true);
	sFiller.innerHTML = ''
	sRowsText = span.cloneNode(true);
	sRowsText.innerHTML = this.totalText +'&nbsp;<span id="nooffilteredrows">'+this.noOfFilteredRows+'</span>&nbsp;of&nbsp;<span>'+this.noOfRows+'</span>&nbsp;'+ this.rowText

	this.sRowsList.owner = this; 

	this.sRowsList.onchange = function() { this.owner.pageNavigation(this);}; 

	tdc = document.createElement('td')
	tdc.appendChild(sRowsListText);
	tdc.appendChild(this.sRowsList);
	tr.appendChild(tdc);

	tdc = document.createElement('td')
	tdc.appendChild(sRowsText);
	tr.appendChild(tdc);

	tdc = document.createElement('td')
	
	tdc.appendChild(this.createFooterPageNavigation());

	tr.appendChild(tdc);

	tbody.appendChild(tr);
	this.tableFooterPagination.appendChild(tbody);
	pagingTd.appendChild(this.tableFooterPagination)
	pagingTr.appendChild(pagingTd);

	return pagingTr;
};
//------------------------------------------------------------------------------
myTable.prototype.createPageNavigationSelect = function(){
	var pages = new Array();
	for (var x=0;x<this.noOfPages ; x++){
		pages[x] = new Array(x+1,x+1)
	}
	return this.createSelect('selectpage',pages)
};
//------------------------------------------------------------------------------
myTable.prototype.createFooterPageNavigation = function(){
	var paginationSpan =document.createElement('span');

	this.iFirst = this.createSpan('firstpage','myfirstpage','15',this.firstPageText,'&nbsp;&nbsp;&nbsp;&nbsp;');
	this.iPrev = this.createSpan('prevpage','myprevpage','15',this.prevPageText,'&nbsp;&nbsp;&nbsp;&nbsp;');
	this.iNext = this.createSpan('nextpage','mynextpage','15',this.nextPageText,'&nbsp;&nbsp;&nbsp;&nbsp;');
	this.iLast = this.createSpan('lastpage','mylastpage','15',this.lastPageText,'&nbsp;&nbsp;&nbsp;&nbsp;');

	this.sPageList = this.createPageNavigationSelect();
	this.sPageText = span.cloneNode(true);
	this.sPageText.innerHTML = '&nbsp;'+this.ofText +'&nbsp;<span id="noofpages">'+this.noOfPages+'</span>&nbsp;'+ this.pageText

	this.iFirst.owner = this.iPrev.owner = this.iNext.owner = this.iLast.owner = this.sPageList.owner = this; 

	this.iFirst.onclick = function() { this.owner.pageNavigation(this);}; 
	this.iPrev.onclick = function() { this.owner.pageNavigation(this);}; 
	this.iNext.onclick = function() { this.owner.pageNavigation(this);}; 
	this.iLast.onclick = function() { this.owner.pageNavigation(this);}; 
	this.sPageList.onchange = function() { this.owner.pageNavigation(this);}; 

	paginationSpan.appendChild(this.iFirst);
	paginationSpan.appendChild(this.iPrev);
	paginationSpan.appendChild(this.sPageList);
	paginationSpan.appendChild(this.sPageText);
	paginationSpan.appendChild(this.iNext);
	paginationSpan.appendChild(this.iLast);
	return paginationSpan;
};
//------------------------------------------------------------------------------
myTable.prototype.createSpan = function(id,className,width,title,text){
	var span = document.createElement('span');
	this.setClass(span,className);
	span.id = id;
	span.width = width;
	span.title = title;
	span.innerHTML=text;
	return span;
};
//------------------------------------------------------------------------------
myTable.prototype.createImage = function(src,id,width,title){
	var img = document.createElement('img');
	
	img.src = src
	img.id = id;
	img.width = width
	img.title = title;
	return img;
};

//------------------------------------------------------------------------------
myTable.prototype.createSelect = function(id,data){
	var select = document.createElement('select');
	select.id=id;
	for (var x=0; x<data.length ; x++){ select.options[x] = new Option(data[x][0],data[x][1]); }
	return select;
};

//------------------------------------------------------------------------------
myTable.prototype.createTable = function(id,className,cellPadding,cellSpacing,width,height,border){
	var table = document.createElement('table');
	if (id != 'undefined' || id != null) table.id = id;
	if (className != 'undefined' || className != null) table.className = className;
	if (border != 'undefined' || border != null) table.border = border;
	if (cellSpacing != 'undefined' || cellSpacing != null) table.cellSpacing = cellSpacing;
	if (cellPadding != 'undefined' || cellPadding != null) table.cellPadding = cellPadding;
	if (width != 'undefined' || width != null) table.width = width;
	if (height != 'undefined' || height != null) table.height = height;
	return table;
};

//------------------------------------------------------------------------------
myTable.prototype.setPaginationElementText = function(tag,id,value){
	var spanList = this.tableFooterPagination.getElementsByTagName(tag);
	for (var x=0;x<spanList.length ; x++){
		if (spanList[x].id == id){
			spanList[x].innerHTML = value;
			break;
		}
	}
};

//------------------------------------------------------------------------------
myTable.prototype.showFilterPopup = function (el){
	var elPos = getPos(el.offsetParent);
	var lbs = this.filterPopup.getElementsByTagName('label');
	var ip = this.filterPopup.getElementsByTagName('input')[0];
	var divTag = this.filterPopup.getElementsByTagName('div');
	for (x=0;x<divTag.length ;x++ ){
		if(divTag[x].id=='reset') btReset = divTag[x]; 
		if(divTag[x].id=='cancel') btCancel = divTag[x]; 
		if(divTag[x].id=='apply') btApply = divTag[x]; 
	}

	btReset.onmouseover = function(){this.owner.setClass(this,'filterButtonover')} 
	btReset.onmouseout = function(){this.owner.setClass(this,'filterButton')} 
	btCancel.onmouseover = function(){this.owner.setClass(this,'filterButtonover')} 
	btCancel.onmouseout = function(){this.owner.setClass(this,'filterButton')} 
	btApply.onmouseover = function(){this.owner.setClass(this,'filterButtonover')} 
	btApply.onmouseout = function(){this.owner.setClass(this,'filterButton')} 
	
	var fld = el.scope.split(';')
	var inputType = fld[0].substr(0,1);

	ip.style.width = el.offsetParent.offsetWidth * .7;
	lbs[0].innerHTML = fld[1] ;
	var selTag = this.filterPopup.getElementsByTagName('select')[0];

	if(inputType=='T'){
		selTag.options[0] = new Option('Starting','S');
		selTag.options[1] = new Option('Ending','E');
		selTag.options[2] = new Option('Contain','C');
	} else {
		selTag.options[0] = new Option('Greater than','G');
		selTag.options[1] = new Option('Less than','L');
		selTag.options[2] = new Option('Equals','Q');
	}	

	this.filterPopup.style.display='block';
	this.filterPopup.style.top = elPos.y+25; 
	this.filterPopup.style.left = elPos.x;
	this.filterPopup.style.width = lbs[0].offsetWidth + 20 + selTag.offsetWidth + 20 + ip.offsetWidth  ; 

	ip.value = this.filterInput;
	ip.focus();
	btReset.owner = btCancel.owner = btApply.owner = this;

	btReset.onclick = function(){ ip.value="";this.owner.resetFilter(el)};
	btCancel.onclick = function(){ ip.value="";this.owner.cancelFilter()};
	btApply.onclick = function(){ this.owner.filterData(el,ip.value,selTag.value)};

};
//------------------------------------------------------------------------------

myTable.prototype.filterData = function(flterIcon,value,chkType){
	var fldType = flterIcon.scope.split(';')[0].substr(0,1)
	this.filterInput = value;
	this.noOfRows = this.dataArray.length;
	this.noOfFilteredRows=0;
	this.hideFilterPopup();
	this.tRows = new Array()
	value = fldType == 'T' ? value.toUpperCase():value;
	if (value.length > 0){
		this.resetFilterIcons(flterIcon);
		flterIcon.className = 'filterActive'
		for (x=0;x<this.noOfRows ;x++ )	{
			var colData = this.dataArray[x][parseInt(flterIcon.id)]
			if(colData.indexOf("href")!=-1)//add for a href condition while filtering on that data
             colData =colData.substring(colData.indexOf(">")+1, colData.lastIndexOf("<"))
			if (fldType=='T')	{
			    colData = colData.toUpperCase();
				if ((chkType=='C' && colData.indexOf(value) >= 0 ) || (chkType=='S' && colData.left(value.length)== value ) || (chkType=='E' && colData.right(value.length)== value )){
					this.tRows[this.tRows.length] = this.dataArray[x]
				}
			}else if(fldType=='N'){
				if ((chkType =='G' && colData > value) || (chkType =='L' && colData < value) || (chkType =='Q' && colData == value)){
					this.tRows[this.tRows.length] = this.dataArray[x]
				}
			}else if(fldType=='D'){
				if ((chkType =='G' && toDate(colData) > toDate(value)) || (chkType =='L' && toDate(colData) < toDate(value)) || (chkType =='Q' && toDate(colData) == toDate(value))){
					this.tRows[this.tRows.length] = this.dataArray[x]
				}
			}
		}
		this.updateControlForFilters()
		this.updateDataTable(0);
	}else {
		this.resetFilter(flterIcon);
	}
	if (this.tType == 'P'){ this.setCurrentPageNo(1); }
};
//------------------------------------------------------------------------------
myTable.prototype.updateControlForFilters = function(){
	this.noOfFilteredRows = this.tRows.length;
	this.setTableHeight() 
	if(this.tType == 'P' && this.noOfPages > 1){
		this.sPageList.length = this.noOfPages
		for (var x=0; x<this.noOfPages ; x++){ this.sPageList.options[x] = new Option(x+1,x+1); }
		this.setCurrentPageNo(1);
		this.sPageText.innerHTML = '&nbsp;'+this.ofText +'&nbsp;<span id="noofpages">'+this.noOfPages+'</span>&nbsp;'+ this.pageText
	}	
};
//------------------------------------------------------------------------------
myTable.prototype.resetFilterIcons = function(el){
	var heading = el.offsetParent.offsetParent;
	var filters = heading.getElementsByTagName('div');
	for (x=0;x<filters.length ;x++ ){
		if (filters[x].className.indexOf('filter') >= 0){ filters[x].className = 'filter'; }
	}
};
//------------------------------------------------------------------------------
myTable.prototype.resetFilter = function(cancelIcon){
	this.filterInput="";
	this.resetFilterIcons(cancelIcon);
	this.hideFilterPopup();
	this.noOfFilteredRows=this.dataArray.length;
	this.tRows = this.dataArray;
	this.updateControlForFilters()
	if (this.tType == 'P'){ this.setCurrentPageNo(1); }
	this.updateDataTable(0);
};
//------------------------------------------------------------------------------
myTable.prototype.cancelFilter = function(){
	this.hideFilterPopup();
};
//------------------------------------------------------------------------------
myTable.prototype.hideFilterPopup = function(){
	this.filterPopup.style.display='none';
};
//------------------------------------------------------------------------------
myTable.prototype.sortData = function(el){
	this.hideFilterPopup();
	if(el.className  == 'sortable-asc'){
		this.tRows.reverse() ;
		el.className  = 'sortable-desc'
	}else if (el.className  == 'sortable-desc'){
		this.tRows.reverse() ;
		el.className  = 'sortable-asc';
	}else {
		this.tRows.sort(function (a,b){
				if ( el.scope.toUpperCase() =='NUMERIC' ){
					var v1 = parseFloat(a[el.id]);
					var v2 = parseFloat(b[el.id])
				}else if(el.scope.toUpperCase() =='TEXT'){
					var v1 = a[el.id];
					var v2 = b[el.id];
				}else if (el.scope.toUpperCase() == 'DATE'){
					var v1 = toDate(a[el.id],myTableMonths);
					var v2 = toDate(b[el.id],myTableMonths);
				}
				if ( v1 < v2 ) return -1;
				else if (v1 > v2 ) return 1;
				else return 0;
			}
		);
		el.className  = 'sortable-asc'
	}
	var pNode = this.tableHeading.getElementsByTagName('div');
	for (j=0;j<pNode.length ;j++ ){
		if (pNode[j].id != el.id && pNode[j].className.indexOf('sortable-') >= 0) {	pNode[j].className = 'sortable' ;}
	}
	this.updateDataTable(0);
	if (this.tType == 'P'){
		this.setCurrentPageNo(1);
	}
};
//------------------------------------------------------------------------------
myTable.prototype.updateDataTable = function(rowPos){
	this.showLoader()
	this.hideFilterPopup();
	if (this.tType == 'P' && this.noOfPages > 1) { this.setPaginationElementText('span',"nooffilteredrows",this.noOfFilteredRows);}
	var obody = this.tableRows.tBodies[0];
	var tbody = this.createDataRows(rowPos)
	this.tableRows.removeChild(obody);
	this.tableRows.appendChild(tbody);
	this.hideLoader()
};

//------------------------------------------------------------------------------
myTable.prototype.setPageOptionList = function(){
	var currPage = this.tableFooterPagination.getElementsByTagName('select')[1];
	currPage.length = 0;
	for (var x=0;x<this.noOfPages ; x++) {currPage.options[x] = new Option(x+1,x+1);}
};
//------------------------------------------------------------------------------
myTable.prototype.getCurrentPageNo = function(){
	var currPage = this.tableFooterPagination.getElementsByTagName('select')[1];
	return parseInt(currPage.value);
};
//------------------------------------------------------------------------------
myTable.prototype.setCurrentPageNo = function(n){
	if (this.noOfPages > 1){
		var currPage = this.tableFooterPagination.getElementsByTagName('select')[1];
		currPage.value = n;
	}
};
//------------------------------------------------------------------------------
myTable.prototype.pageNavigation = function (el){
	var cPageNo = this.getCurrentPageNo();
	switch(el.id)
		{
			case 'firstpage':   if (cPageNo == 1) return; cPageNo = 1;	break;
			case 'prevpage':    if (cPageNo == 1) return; cPageNo --; 	break;
			case 'nextpage':    if (cPageNo == this.noOfPages) return; cPageNo ++; break;
			case 'lastpage':    if (cPageNo == this.noOfPages) return; cPageNo = this.noOfPages; break;
			case 'selectrows':  this.noOfRowsPerPage = (parseInt(el.value)) 
								this.setTableHeight();
								this.setPageOptionList();
								this.setPaginationElementText('span',"noofpages",this.noOfPages);
								cPageNo = 1;
								break;
		}
	this.setCurrentPageNo(cPageNo);
	var firstRow = (cPageNo * this.noOfRowsPerPage ) - this.noOfRowsPerPage;
	this.updateDataTable(firstRow)
};
//------------------------------------------------------------------------------
myTable.prototype.createEmptyRow = function(){
	var _emptyROw = new Array();
	for (var m=0;m<this.noOfCols ;m++ ) {_emptyROw[m] = "&nbsp;";}
	return _emptyROw;
};
//------------------------------------------------------------------------------
myTable.prototype.setClass = function (element,className){
	element.setAttribute('class',className);
	element.setAttribute('className',className); //<iehack>
};
//------------------------------------------------------------------------------
myTable.prototype.getBrowser = function(){
	var browser=navigator.appName;
	var ns=false;
	var ms=false;
	if (browser == 'Microsoft Internet Explorer') {ms=true;}
	if (browser == 'Netscape') {ns=true;}
	return {'ms':ms,'ns':ns}
};
//------------------------------------------------------------------------------
function allTrim(s){
	if (typeof(s)=='string') {s = s.replace(/^\s*/, "").replace(/\s*$/, "");}
	return s;
}
//------------------------------------------------------------------------------
function getPos(obj)
 {
   var pos = {x: obj.offsetLeft||0, y: obj.offsetTop||0};
    while(obj = obj.offsetParent) {
       pos.x += obj.offsetLeft||0;
       pos.y += obj.offsetTop||0;
    }
    return pos;
}
//------------------------------------------------------------------------------
// to get left side string as per length
String.prototype.left = function (x){
	return this.substr(0,x);
}
//------------------------------------------------------------------------------
// to get right side string as per length
String.prototype.right = function (x){
	return this.substr(this.length-x,x);
}

//NEW_TABLE JS END/////////////////////////////////////////////////

//PROTOTYPE JS START///////////////////////////////////////////////////

/*  Prototype JavaScript framework, version 1.5.0
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },

  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
String.interpret = function(value){
  return value == null ? '' : String(value);
}

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;

        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if(window.opera){
  Array.prototype.concat = function(){
    var array = [];
    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for(var i = 0, length = arguments.length; i < length; i++) {
      if(arguments[i].constructor == Array) {
        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(obj) {
  Object.extend(this, obj || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];

	  this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;

      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
        	key = encodeURIComponent(pair.key);
          values.each(function(value) {
            value = value != undefined ? encodeURIComponent(value) : '';
            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
	  });

    return parts.join('&');
  }
});

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
});

function $H(object) {
  if (object && object.constructor == Hash) return object;
  return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = this.options.parameters;

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    params = Hash.toQueryString(params);
    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='

    // when GET, append parameters to URL
    if (this.method == 'get' && params)
      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;

    try {
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      var body = this.method == 'post' ? (this.options.postBody || params) : null;

      this.transport.send(body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.getHeader('Content-type') || 'text/javascript').strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? eval('(' + json + ')') : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(query.snapshotItem(i));
    return results;
  };
}

document.getElementsByClassName = function(className, parentElement) {
  if (Prototype.BrowserFeatures.XPath) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  } else {
    var children = ($(parentElement) || document.body).getElementsByTagName('*');
    var elements = [], child;
    for (var i = 0, length = children.length; i < length; i++) {
      child = children[i];
      if (Element.hasClassName(child, className))
        elements.push(Element.extend(child));
    }
    return elements;
  }
};

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element || _nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    Object.extend(methods, Element.Methods.Simulated);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function' && !(property in element))
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*'));
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (document.all && !window.opera) {
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      if(attribute) return attribute.nodeValue;
    }
    return element.getAttribute(name);
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    if (['float','cssFloat'].include(style))
      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
    style = style.camelize();
    var value = element.style[style];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css[style] : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style];
      }
    }

    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
      value = element['offset'+style.capitalize()] + 'px';

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    if(style == 'opacity') {
      if(value) return parseFloat(value);
      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if(value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }
    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style) {
      var value = style[name];
      if(name == 'opacity') {
        if (value == 1) {
          value = (/Gecko/.test(navigator.userAgent) &&
            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else if(value === '') {
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else {
          if(value < 0.00001) value = 0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
              'alpha(opacity='+value*100+')';
        }
      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
      element.style[name.camelize()] = value;
    }
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
};

Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});

Element._attributeTranslations = {};

Element._attributeTranslations.names = {
  colspan:   "colSpan",
  rowspan:   "rowSpan",
  valign:    "vAlign",
  datetime:  "dateTime",
  accesskey: "accessKey",
  tabindex:  "tabIndex",
  enctype:   "encType",
  maxlength: "maxLength",
  readonly:  "readOnly",
  longdesc:  "longDesc"
};

Element._attributeTranslations.values = {
  _getAttr: function(element, attribute) {
    return element.getAttribute(attribute, 2);
  },

  _flag: function(element, attribute) {
    return $(element).hasAttribute(attribute) ? attribute : null;
  },

  style: function(element) {
    return element.style.cssText.toLowerCase();
  },

  title: function(element) {
    var node = element.getAttributeNode('title');
    return node.specified ? node.nodeValue : null;
  }
};

Object.extend(Element._attributeTranslations.values, {
  href: Element._attributeTranslations.values._getAttr,
  src:  Element._attributeTranslations.values._getAttr,
  disabled: Element._attributeTranslations.values._flag,
  checked:  Element._attributeTranslations.values._flag,
  readonly: Element._attributeTranslations.values._flag,
  multiple: Element._attributeTranslations.values._flag
});

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations;
    attribute = t.names[attribute] || attribute;
    return $(element).getAttributeNode(attribute).specified;
  }
};

// IE is missing .innerHTML support for TABLE-related elements
if (document.all && !window.opera){
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
};

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var className = 'HTML' + tag + 'Element';
    if(window[className]) return;
    var klass = window[className] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0, length = clause.length; i < length; i++)
        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      element = $(element); \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0, length = scope.length; i < length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector)).map(Element.extend);
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != undefined) {
          if (result[key]) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.blur();
      element.disabled = 'true';
    });
    return form;
  },

  enable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.disabled = '';
    });
    return form;
  },

  findFirstElement: function(form) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  }
}

Object.extend(Form, Form.Methods);

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = {};
        pair[element.name] = value;
        return Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
      !['button', 'reset', 'submit'].include(element.type) ) )
      element.select();
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = false;
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback.bind(this));
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();


//PROTOTYPE JS END///////////////////////////////////////////////////


//SLIDER JS START///////////////////////////////////////////////////

// script.aculo.us slider.js v1.7.0, Fri Jan 19 19:16:36 CET 2007

// Copyright (c) 2005, 2006 Marty Haught, Thomas Fuchs 
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if(!Control) var Control = {};
Control.Slider = Class.create();

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider.prototype = {
  initialize: function(handle, track, options) {
    var slider = this;
    
    if(handle instanceof Array) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || {};

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if(this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if(this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (slider.options.sliderValue instanceof Array ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      Element.makePositioned(h); // fix IE
      Event.observe(h, "mousedown", slider.eventMouseDown);
    });
    
    Event.observe(this.track, "mousedown", this.eventMouseDown);
    Event.observe(document, "mouseup", this.eventMouseUp);
    Event.observe(document, "mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if(this.allowedValues){
      if(value >= this.allowedValues.max()) return(this.allowedValues.max());
      if(value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if(currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if(value > this.range.end) return this.range.end;
    if(value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if(!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if(this.initialized && this.restricted) {
      if((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    //alert(" "+sliderValue+" "+handleIdx);
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = this.translateToPx(sliderValue, handleIdx);
	
    this.drawSpans();
    if(!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value, handleIdx) {
    // Hack GR to allow two sliders show the same value without overlapping
    /*if (this.handles.length == 2 && handleIdx != null) {
      var offset = (value - this.range.start) / (this.range.end-this.range.start) * (this.trackLength - 2 * this.handleLength);
	  if (handleIdx > 0) {
	    return Math.round(offset + this.handleLength) + 'px';
	  }
	  else {
	    return Math.round(offset) + 'px';
	  }
	}
    else {*/
	//alert(this.trackLength+" "+this.handleLength+" "+this.range.end+" "+this.range.start);
	  
	  // Written for bug in IE 
	  if(this.range.end-this.range.start ==0){
	   return "1px";
	  }

      return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
   // }
  },
  translateToValue: function(offset) {
    // Hack GR to allow two sliders show the same value without overlapping
    var percent = 0;
    if (this.handles.length == 2) {
	  if (this.activeHandleIdx > 0) {
	  	percent = (offset - 1.5 * this.handleLength)/(this.trackLength - 2 * this.handleLength)
	  }
	  else {
    	percent = (offset + 0.5 * this.handleLength)/(this.trackLength - 2 * this.handleLength)
	  }
	  var value = percent * (this.range.end-this.range.start) + this.range.start; 
	  if (value < this.range.start) {
	    value = this.range.start;
	  }
	  else if (value > this.range.end) {
	    value = this.range.end;
	  }
	  return value;
	}
    else {
      return ((offset/(this.trackLength-this.handleLength) * 
        (this.range.end-this.range.start)) + this.range.start);
    }
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignY);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if(this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if(this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if(this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if(this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if(Event.isLeftClick(event)) {
      if(!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if(track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if(this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if(this.active) {
      if(!this.dragging) this.dragging = true;
      this.draw(event);
      // fix AppleWebKit rendering
      if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if(this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if(this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if(this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
}

//SLIDER JS END////////////////////////////////////////////////////////////

//ZAPATEC JS START//////////////////////////////////////////////////////////

/*
 *
 * Copyright (c) 2004-2005 by Zapatec, Inc.
 * http://www.zapatec.com
 * 1700 MLK Way, Berkeley, California,
 * 94709, U.S.A.
 * All rights reserved.
 *
 *
 */


if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.version='07-01';if(typeof Zapatec.zapatecPath=='undefined'){Zapatec.zapatecPath=function(){if(document.documentElement){var aTokens=document.documentElement.innerHTML.match(/<script[^>]+src="([^"]*zapatec(-core|-src)?.js[^"]*)"/i);if(aTokens&&aTokens.length>=2){aTokens=aTokens[1].split('?');aTokens=aTokens[0].split('/');if(Array.prototype.pop){aTokens.pop();}else{aTokens.length-=1;}
return aTokens.length?aTokens.join('/')+'/':'';}}
return'';}();}
if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.Utils={};Zapatec.Utils.getAbsolutePos=function(el,scrollOff){var SL=0,ST=0;if(!scrollOff){var is_div=/^div$/i.test(el.tagName);if(is_div&&el.scrollLeft)
SL=el.scrollLeft;if(is_div&&el.scrollTop)
ST=el.scrollTop;}
var r={x:el.offsetLeft-SL,y:el.offsetTop-ST};if(el.offsetParent){var tmp=this.getAbsolutePos(el.offsetParent);r.x+=tmp.x;r.y+=tmp.y;}
return r;};Zapatec.Utils.getElementOffset=function(oEl){var iLeft=iTop=iWidth=iHeight=0;if(oEl.getBoundingClientRect){var oRect=oEl.getBoundingClientRect();iLeft=oRect.left;iTop=oRect.top;iWidth=oRect.right-iLeft;iHeight=oRect.bottom-iTop;iLeft+=Zapatec.Utils.getPageScrollX()-2;iTop+=Zapatec.Utils.getPageScrollY()-2;}else{iWidth=oEl.offsetWidth;iHeight=oEl.offsetHeight;var sPos=Zapatec.Utils.getStyleProperty(oEl,'position');if(sPos=='fixed'){iLeft=oEl.offsetLeft+Zapatec.Utils.getPageScrollX();iTop=oEl.offsetTop+Zapatec.Utils.getPageScrollY();}else if(sPos=='absolute'){while(oEl){var sTag=oEl.tagName;if(sTag){sTag=sTag.toLowerCase();if(sTag!='body'&&sTag!='html'){iLeft+=parseInt(oEl.offsetLeft,10)||0;iTop+=parseInt(oEl.offsetTop,10)||0;}}
oEl=oEl.offsetParent;var sTag=oEl?oEl.tagName:null;if(sTag){sTag=sTag.toLowerCase();if(sTag!='body'&&sTag!='html'){iLeft-=oEl.scrollLeft;iTop-=oEl.scrollTop;}}}}else{var oP=oEl;while(oP){iLeft+=parseInt(oP.offsetLeft,10)||0;iTop+=parseInt(oP.offsetTop,10)||0;oP=oP.offsetParent;}
oP=oEl;while(oP.parentNode){oP=oP.parentNode;var sTag=oP.tagName;if(sTag){sTag=sTag.toLowerCase();if(sTag!='body'&&sTag!='html'&&sTag!='tr'){iLeft-=oP.scrollLeft;iTop-=oP.scrollTop;}}}}}
return{left:iLeft,top:iTop,x:iLeft,y:iTop,width:iWidth,height:iHeight};};Zapatec.Utils.getElementOffsetScrollable=function(oEl){var oPos=Zapatec.Utils.getElementOffset(oEl);if(oEl.scrollLeft){oPos.left-=oEl.scrollLeft;oPos.x=oPos.left;}
if(oEl.scrollTop){oPos.top-=oEl.scrollTop;oPos.y=oPos.top;}
return oPos;};Zapatec.Utils.fixBoxPosition=function(box,leave){var screenX=Zapatec.Utils.getPageScrollX();var screenY=Zapatec.Utils.getPageScrollY();var sizes=Zapatec.Utils.getWindowSize();leave=parseInt(leave,10)||0;if(box.x<screenX){box.x=screenX+leave;}
if(box.y<screenY){box.y=screenY+leave;}
if(box.x+box.width>screenX+sizes.width){box.x=screenX+sizes.width-box.width-leave;}
if(box.y+box.height>screenY+sizes.height){box.y=screenY+sizes.height-box.height-leave;}};Zapatec.Utils.isRelated=function(el,evt){evt||(evt=window.event);var related=evt.relatedTarget;if(!related){var type=evt.type;if(type=="mouseover"){related=evt.fromElement;}else if(type=="mouseout"){related=evt.toElement;}}
try{while(related){if(related==el){return true;}
related=related.parentNode;}}catch(e){};return false;};Zapatec.Utils.removeClass=function(el,className){if(!(el&&el.className)){return;}
var cls=el.className.split(" ");var ar=[];for(var i=cls.length;i>0;){if(cls[--i]!=className){ar[ar.length]=cls[i];}}
el.className=ar.join(" ");};Zapatec.Utils.addClass=function(el,className){Zapatec.Utils.removeClass(el,className);el.className+=" "+className;};Zapatec.Utils.getElement=function(ev){if(Zapatec.is_ie){return window.event.srcElement;}else{return ev.currentTarget;}};Zapatec.Utils.getTargetElement=function(ev){if(Zapatec.is_ie){return window.event.srcElement;}else{return ev.target;}};Zapatec.Utils.getMousePos=function(oEv){oEv||(oEv=window.event);var oPos={pageX:0,pageY:0,clientX:0,clientY:0};if(oEv){var bIsPageX=(typeof oEv.pageX!='undefined');var bIsClientX=(typeof oEv.clientX!='undefined');if(bIsPageX||bIsClientX){if(bIsPageX){oPos.pageX=oEv.pageX;oPos.pageY=oEv.pageY;}else{oPos.pageX=oEv.clientX+Zapatec.Utils.getPageScrollX();oPos.pageY=oEv.clientY+Zapatec.Utils.getPageScrollY();}
if(bIsClientX){oPos.clientX=oEv.clientX;oPos.clientY=oEv.clientY;}else{oPos.clientX=oEv.pageX-Zapatec.Utils.getPageScrollX();oPos.clientY=oEv.pageY-Zapatec.Utils.getPageScrollY();}}}
return oPos;};Zapatec.Utils.stopEvent=function(ev){ev||(ev=window.event);if(ev){if(Zapatec.is_ie){ev.cancelBubble=true;ev.returnValue=false;}else{ev.preventDefault();ev.stopPropagation();}}
return false;};Zapatec.Utils.removeOnUnload=[];Zapatec.Utils.addEvent=function(oElement,sEvent,fListener,bUseCapture){if(oElement.addEventListener){if(!bUseCapture){bUseCapture=false;}
oElement.addEventListener(sEvent,fListener,bUseCapture);}else if(oElement.attachEvent){oElement.detachEvent('on'+sEvent,fListener);oElement.attachEvent('on'+sEvent,fListener);if(bUseCapture){oElement.setCapture(false);}}
Zapatec.Utils.removeOnUnload.push({'element':oElement,'event':sEvent,'listener':fListener,'capture':bUseCapture});};Zapatec.Utils.removeEvent=function(oElement,sEvent,fListener,bUseCapture){if(oElement.removeEventListener){oElement.removeEventListener(sEvent,fListener,bUseCapture);}else if(oElement.detachEvent){oElement.detachEvent('on'+sEvent,fListener);}
for(var iLis=Zapatec.Utils.removeOnUnload.length-1;iLis>=0;iLis--){var oParams=Zapatec.Utils.removeOnUnload[iLis];if(!oParams){continue;}
if(oElement==oParams['element']&&sEvent==oParams['event']&&fListener==oParams['listener']&&bUseCapture==oParams['capture']){Zapatec.Utils.removeOnUnload[iLis]=null;Zapatec.Utils.removeEvent(oParams['element'],oParams['event'],oParams['listener'],oParams['capture']);}}};Zapatec.Utils.createElement=function(type,parent,selectable){var el=null;if(window.self.document.createElementNS)
el=window.self.document.createElementNS("http://www.w3.org/1999/xhtml",type);else
el=document.createElement(type);if(typeof parent!="undefined"&&parent!=null)
parent.appendChild(el);if(!selectable){if(Zapatec.is_ie)
el.setAttribute("unselectable",true);if(Zapatec.is_gecko)
el.style.setProperty("-moz-user-select","none","");}
return el;};Zapatec.Utils.writeCookie=function(name,value,domain,path,exp_days){value=escape(value);var ck=name+"="+value,exp;if(domain)
ck+=";domain="+domain;if(path)
ck+=";path="+path;if(exp_days){exp=new Date();exp.setTime(exp_days*86400000+exp.getTime());ck+=";expires="+exp.toGMTString();}
document.cookie=ck;};Zapatec.Utils.getCookie=function(name){var pattern=name+"=";var tokenPos=0;while(tokenPos<document.cookie.length){var valuePos=tokenPos+pattern.length;if(document.cookie.substring(tokenPos,valuePos)==pattern){var endValuePos=document.cookie.indexOf(";",valuePos);if(endValuePos==-1){endValuePos=document.cookie.length;}
return unescape(document.cookie.substring(valuePos,endValuePos));}
tokenPos=document.cookie.indexOf(" ",tokenPos)+1;if(tokenPos==0){break;}}
return null;};Zapatec.Utils.makePref=function(obj){function stringify(val){if(typeof val=="object"&&!val)
return"null";else if(typeof val=="number"||typeof val=="boolean")
return val;else if(typeof val=="string")
return'"'+val.replace(/\x22/,"\\22")+'"';else return null;};var txt="",i;for(i in obj)
txt+=(txt?",'":"'")+i+"':"+stringify(obj[i]);return txt;};Zapatec.Utils.loadPref=function(txt){var obj=null;try{eval("obj={"+txt+"}");}catch(e){}
return obj;};Zapatec.Utils.mergeObjects=function(dest,src){for(var i in src)
dest[i]=src[i];};Zapatec.Utils.__wch_id=0;Zapatec.Utils.createWCH=function(element){var f=null;element=element||document.body;if(Zapatec.is_ie&&!Zapatec.is_ie5){var filter='filter:progid:DXImageTransform.Microsoft.alpha(style=0,opacity=0);';var id="WCH"+(++Zapatec.Utils.__wch_id);element.insertAdjacentHTML
('beforeEnd','<iframe id="'+id+'" scrolling="no" frameborder="0" '+'style="z-index:0;position:absolute;visibility:hidden;'+filter+'border:0;top:0;left:0;width:0;height:0" '+'src="javascript:false"></iframe>');f=document.getElementById(id);}
return f;};Zapatec.Utils.setupWCH_el=function(f,el,el2){if(f){var pos=Zapatec.Utils.getAbsolutePos(el),X1=pos.x,Y1=pos.y,X2=X1+el.offsetWidth,Y2=Y1+el.offsetHeight;if(el2){var p2=Zapatec.Utils.getAbsolutePos(el2),XX1=p2.x,YY1=p2.y,XX2=XX1+el2.offsetWidth,YY2=YY1+el2.offsetHeight;if(X1>XX1)
X1=XX1;if(Y1>YY1)
Y1=YY1;if(X2<XX2)
X2=XX2;if(Y2<YY2)
Y2=YY2;}
Zapatec.Utils.setupWCH(f,X1,Y1,X2-X1,Y2-Y1);}};Zapatec.Utils.setupWCH=function(f,x,y,w,h){if(f){var s=f.style;(typeof x!="undefined")&&(s.left=x+"px");(typeof y!="undefined")&&(s.top=y+"px");(typeof w!="undefined")&&(s.width=w+"px");(typeof h!="undefined")&&(s.height=h+"px");s.visibility="inherit";}};Zapatec.Utils.hideWCH=function(f){if(f)
f.style.visibility="hidden";};Zapatec.Utils.getPageScrollY=function(){if(window.pageYOffset){return window.pageYOffset;}else if(document.body&&document.body.scrollTop){return document.body.scrollTop;}else if(document.documentElement&&document.documentElement.scrollTop){return document.documentElement.scrollTop;}
return 0;};Zapatec.Utils.getPageScrollX=function(){if(window.pageXOffset){return window.pageXOffset;}else if(document.body&&document.body.scrollLeft){return document.body.scrollLeft;}else if(document.documentElement&&document.documentElement.scrollLeft){return document.documentElement.scrollLeft;}
return 0;};Zapatec.ScrollWithWindow={};Zapatec.ScrollWithWindow.list=[];Zapatec.ScrollWithWindow.stickiness=0.25;Zapatec.ScrollWithWindow.register=function(oElement){var iTop=oElement.offsetTop||0;var iLeft=oElement.offsetLeft||0;Zapatec.ScrollWithWindow.list.push({node:oElement,origTop:iTop,origLeft:iLeft});if(!Zapatec.ScrollWithWindow.interval){Zapatec.ScrollWithWindow.on();}};Zapatec.ScrollWithWindow.unregister=function(oElement){for(var iItem=0;iItem<Zapatec.ScrollWithWindow.list.length;iItem++){var oItem=Zapatec.ScrollWithWindow.list[iItem];if(oElement==oItem.node){Zapatec.ScrollWithWindow.list.splice(iItem,1);if(!Zapatec.ScrollWithWindow.list.length){Zapatec.ScrollWithWindow.off();}
return;}}};Zapatec.ScrollWithWindow.moveTop=function(iTop){Zapatec.ScrollWithWindow.top+=(iTop-Zapatec.ScrollWithWindow.top)*Zapatec.ScrollWithWindow.stickiness;if(Math.abs(Zapatec.ScrollWithWindow.top-iTop)<=1){Zapatec.ScrollWithWindow.top=iTop;}
for(var iItem=0;iItem<Zapatec.ScrollWithWindow.list.length;iItem++){var oItem=Zapatec.ScrollWithWindow.list[iItem];var oElement=oItem.node;oElement.style.position='absolute';if(!oItem.origTop&&oItem.origTop!==0){oItem.origTop=parseInt(oElement.style.top)||0;}
oElement.style.top=oItem.origTop+
parseInt(Zapatec.ScrollWithWindow.top)+'px';}};Zapatec.ScrollWithWindow.moveLeft=function(iLeft){Zapatec.ScrollWithWindow.left+=(iLeft-Zapatec.ScrollWithWindow.left)*Zapatec.ScrollWithWindow.stickiness;if(Math.abs(Zapatec.ScrollWithWindow.left-iLeft)<=1){Zapatec.ScrollWithWindow.left=iLeft;}
for(var iItem=0;iItem<Zapatec.ScrollWithWindow.list.length;iItem++){var oItem=Zapatec.ScrollWithWindow.list[iItem];var oElement=oItem.node;oElement.style.position='absolute';if(!oItem.origLeft&&oItem.origLeft!==0){oItem.origLeft=parseInt(oElement.style.left)||0;}
oElement.style.left=oItem.origLeft+
parseInt(Zapatec.ScrollWithWindow.left)+'px';}};Zapatec.ScrollWithWindow.cycle=function(){var iTop=Zapatec.Utils.getPageScrollY();var iLeft=Zapatec.Utils.getPageScrollX();if(iTop!=Zapatec.ScrollWithWindow.top){Zapatec.ScrollWithWindow.moveTop(iTop);}
if(iLeft!=Zapatec.ScrollWithWindow.left){Zapatec.ScrollWithWindow.moveLeft(iLeft);}};Zapatec.ScrollWithWindow.on=function(){if(Zapatec.ScrollWithWindow.interval){return;}
Zapatec.ScrollWithWindow.top=Zapatec.Utils.getPageScrollY();Zapatec.ScrollWithWindow.left=Zapatec.Utils.getPageScrollX();Zapatec.ScrollWithWindow.interval=setInterval(Zapatec.ScrollWithWindow.cycle,50);};Zapatec.ScrollWithWindow.off=function(){if(!Zapatec.ScrollWithWindow.interval){return;}
clearInterval(Zapatec.ScrollWithWindow.interval);Zapatec.ScrollWithWindow.interval=null;};Zapatec.FixateOnScreen={};Zapatec.FixateOnScreen.getExpression=function(coord,direction){return"Zapatec.Utils.getPageScroll"+direction.toUpperCase()+"() + "+coord;};Zapatec.FixateOnScreen.parseCoordinates=function(element){if(!this.isRegistered(element)){return false;}
var x=0;var y=0;var style=element.style;if(Zapatec.is_ie&&!Zapatec.is_ie7){x=style.getExpression("left").split(" ");x=parseInt(x[x.length-1],10);y=style.getExpression("top").split(" ");y=parseInt(y[y.length-1],10);}else{x=parseInt(style.left,10);y=parseInt(style.top,10);}
x+=Zapatec.Utils.getPageScrollX();y+=Zapatec.Utils.getPageScrollY();return{x:x,y:y};};Zapatec.FixateOnScreen.correctCoordinates=function(x,y){position={x:x,y:y};if(position.x||position.x===0){position.x-=Zapatec.Utils.getPageScrollX();if(Zapatec.is_ie&&!Zapatec.is_ie7){position.x=this.getExpression(position.x,"X");;}else{position.x+="px";}}
if(position.y||position.y===0){position.y-=Zapatec.Utils.getPageScrollY();if(Zapatec.is_ie&&!Zapatec.is_ie7){position.y=this.getExpression(position.y,"Y");;}else{position.y+="px";}}
return position;};Zapatec.FixateOnScreen.register=function(element){if(!Zapatec.isHtmlElement(element)){return false;}
if(this.isRegistered(element)){return true;}
var pos=Zapatec.Utils.getElementOffset(element);pos={x:parseInt(element.style.left,10)||pos.x,y:parseInt(element.style.top,10)||pos.y}
pos=this.correctCoordinates(pos.x,pos.y);if(!Zapatec.is_ie||Zapatec.is_ie7){var restorer=element.restorer;if(!restorer||!restorer.getObject||restorer.getObject()!=element){restorer=element.restorer=new Zapatec.SRProp(element);}
restorer.saveProp("style.position");element.style.position="fixed";element.style.left=pos.x;element.style.top=pos.y;}else{element.style.setExpression("left",pos.x);element.style.setExpression("top",pos.y);}
element.zpFixed=true;return true;};Zapatec.FixateOnScreen.unregister=function(element){if(!Zapatec.isHtmlElement(element)){return false;}
var pos=this.parseCoordinates(element);if(pos===false){return true;}
if(Zapatec.is_ie&&!Zapatec.is_ie7){element.style.removeExpression("left");element.style.removeExpression("top");}
element.style.left=pos.x+"px";element.style.top=pos.y+"px";if(!Zapatec.is_ie||Zapatec.is_ie7){element.restorer.restoreProp("style.position",true);}
element.zpFixed=false;return true;};Zapatec.FixateOnScreen.isRegistered=function(element){if(element.zpFixed){return true;}
return false;};Zapatec.Utils.destroy=function(el){if(el&&el.parentNode)
el.parentNode.removeChild(el);};Zapatec.Utils.newCenteredWindow=function(url,windowName,width,height,scrollbars){var leftPosition=0;var topPosition=0;if(screen.width)
leftPosition=(screen.width-width)/2;if(screen.height)
topPosition=(screen.height-height)/2;var winArgs='height='+height+',width='+width+',top='+topPosition+',left='+leftPosition+',scrollbars='+scrollbars+',resizable';var win=window.open(url,windowName,winArgs);return win;};Zapatec.Utils.getWindowSize=function(){var iWidth=0;var iHeight=0;if(Zapatec.is_opera){iWidth=document.body.clientWidth||0;iHeight=document.body.clientHeight||0;}else if(Zapatec.is_khtml){iWidth=window.innerWidth||0;iHeight=window.innerHeight||0;}else if(document.compatMode&&document.compatMode=='CSS1Compat'){iWidth=document.documentElement.clientWidth||0;iHeight=document.documentElement.clientHeight||0;}else{iWidth=document.body.clientWidth||0;iHeight=document.body.clientHeight||0;}
return{width:iWidth,height:iHeight};};Zapatec.Utils.selectOption=function(sel,val,call_default){var a=sel.options,i,o;for(i=a.length;--i>=0;){o=a[i];o.selected=(o.value==val);}
sel.value=val;if(call_default){if(typeof sel.onchange=="function")
sel.onchange();else if(typeof sel.onchange=="string")
eval(sel.onchange);}};Zapatec.Utils.getNextSibling=function(el,tag,alternateTag){el=el.nextSibling;if(!tag){return el;}
tag=tag.toLowerCase();if(alternateTag)alternateTag=alternateTag.toLowerCase();while(el){if(el.nodeType==1&&(el.tagName.toLowerCase()==tag||(alternateTag&&el.tagName.toLowerCase()==alternateTag))){return el;}
el=el.nextSibling;}
return el;};Zapatec.Utils.getPreviousSibling=function(el,tag,alternateTag){el=el.previousSibling;if(!tag){return el;}
tag=tag.toLowerCase();if(alternateTag)alternateTag=alternateTag.toLowerCase();while(el){if(el.nodeType==1&&(el.tagName.toLowerCase()==tag||(alternateTag&&el.tagName.toLowerCase()==alternateTag))){return el;}
el=el.previousSibling;}
return el;};Zapatec.Utils.getFirstChild=function(el,tag,alternateTag){if(!el){return null;}
el=el.firstChild;if(!el){return null;}
if(!tag){return el;}
tag=tag.toLowerCase();if(el.nodeType==1){if(el.tagName.toLowerCase()==tag){return el;}else if(alternateTag){alternateTag=alternateTag.toLowerCase();if(el.tagName.toLowerCase()==alternateTag){return el;}}}
return Zapatec.Utils.getNextSibling(el,tag,alternateTag);};Zapatec.Utils.getLastChild=function(el,tag,alternateTag){if(!el){return null;}
el=el.lastChild;if(!el){return null;}
if(!tag){return el;}
tag=tag.toLowerCase();if(el.nodeType==1){if(el.tagName.toLowerCase()==tag){return el;}else if(alternateTag){alternateTag=alternateTag.toLowerCase();if(el.tagName.toLowerCase()==alternateTag){return el;}}}
return Zapatec.Utils.getPreviousSibling(el,tag,alternateTag);};Zapatec.Utils.getChildText=function(objNode){if(objNode==null){return'';}
var arrText=[];var objChild=objNode.firstChild;while(objChild!=null){if(objChild.nodeType==3){arrText.push(objChild.data);}
objChild=objChild.nextSibling;}
return arrText.join(' ');};Zapatec.Utils.insertAfter=function(oldNode,newNode){if(oldNode.nextSibling){oldNode.parentNode.insertBefore(newNode,oldNode.nextSibling);}else{oldNode.parentNode.appendChild(newNode);}}
Zapatec.Utils._ids={};Zapatec.Utils.generateID=function(code,id){if(typeof id=="undefined"){if(typeof this._ids[code]=="undefined")
this._ids[code]=0;id=++this._ids[code];}
return"zapatec-"+code+"-"+id;};Zapatec.Utils.addTooltip=function(target,tooltip){return new Zapatec.Tooltip({target:target,tooltip:tooltip});};Zapatec.isLite=true;Zapatec.Utils.checkLinks=function(){var anchors=document.getElementsByTagName('A');for(var ii=0;ii<anchors.length;ii++){if(Zapatec.Utils.checkLink(anchors[ii])){return true;}}
return false;}
Zapatec.Utils.checkLink=function(lnk){if(!lnk){return false;}
if(!/^https?:\/\/((dev|www)\.)?zapatec\.com/i.test(lnk.href)){return false;}
var textContent=""
for(var ii=0;ii<lnk.childNodes.length;ii++){if(lnk.childNodes[ii].nodeType==3){textContent+=lnk.childNodes[ii].nodeValue;}}
if(textContent.length<4){return false;}
var parent=lnk;while(parent&&parent.nodeName.toLowerCase()!="html"){if(Zapatec.Utils.getStyleProperty(parent,"display")=="none"||Zapatec.Utils.getStyleProperty(parent,"visibility")=="hidden"||Zapatec.Utils.getStyleProperty(parent,"opacity")=="0"||Zapatec.Utils.getStyleProperty(parent,"-moz-opacity")=="0"||/alpha\(opacity=0\)/i.test(Zapatec.Utils.getStyleProperty(parent,"filter"))){return false;}
parent=parent.parentNode;}
var coords=Zapatec.Utils.getElementOffset(lnk);if(coords.left<0||coords.top<0){return false;}
return true;}
Zapatec.Utils.checkActivation=function(){if(!Zapatec.isLite)return true;var arrProducts=[]
add_product=function(script,webdir_in,name_in)
{arrProducts[script]={webdir:webdir_in,name:name_in,bActive:false}}
add_product('calendar.js','prod1','Calendar')
add_product('zpmenu.js','menu','Menu')
add_product('tree.js','prod3','Tree')
add_product('form.js','forms','Forms')
add_product('effects.js','effects','Effects')
add_product('hoverer.js','effects','Effects - Hoverer')
add_product('slideshow.js','effects','Effects - Slideshow')
add_product('zpgrid.js','grid','Grid')
add_product('slider.js','slider','Slider')
add_product('zptabs.js','tabs','Tabs')
add_product('zptime.js','time','Time')
add_product('window.js','windows','Window')
var strName,arrName,i
var bProduct=false
var scripts=document.getElementsByTagName('script');for(i=0;i<scripts.length;i++)
{if(/wizard.js/i.test(scripts[i].src))
return true
arrName=scripts[i].src.split('/')
if(arrName.length==0)
strName=scripts[i]
else
strName=arrName[arrName.length-1]
strName=strName.toLowerCase()
if(typeof arrProducts[strName]!='undefined')
{bProduct=true
arrProducts[strName].bActive=true}}
if(!bProduct||Zapatec.Utils.checkLinks()){return true;}
var strMsg='You are using the Free version of the Zapatec Software.\n'+'While using the Free version, a link to www.zapatec.com in this page is required.'
for(i in arrProducts)
if(arrProducts[i].bActive==true)
strMsg+='\nTo purchase the Zapatec '+arrProducts[i].name+' visit www.zapatec.com/website/main/products/'+arrProducts[i].webdir+'/'
//alert(strMsg)
return false;}
Zapatec.Utils.clone=function(oSource){var oClone;if(!oSource&&typeof oSource=='object'){return null;}else if(typeof oSource=='undefined'){return oClone;}
if((oSource instanceof String)||(oSource instanceof Number)||(oSource instanceof Boolean)){oClone=new oSource.constructor(oSource.valueOf());}else{oClone=new oSource.constructor();}
for(var sProperty in oSource){if(typeof oSource[sProperty]=='object'){oClone[sProperty]=Zapatec.Utils.clone(oSource[sProperty],true);}else{oClone[sProperty]=oSource[sProperty];}}
return oClone;};Zapatec.is_opera=/opera/i.test(navigator.userAgent);Zapatec.is_ie=(/msie/i.test(navigator.userAgent)&&!Zapatec.is_opera);Zapatec.is_ie5=(Zapatec.is_ie&&/msie 5\.0/i.test(navigator.userAgent));Zapatec.is_ie7=(Zapatec.is_ie&&/msie 7\.0/i.test(navigator.userAgent));Zapatec.is_mac_ie=(/msie.*mac/i.test(navigator.userAgent)&&!Zapatec.is_opera);Zapatec.is_khtml=/Konqueror|Safari|KHTML/i.test(navigator.userAgent);Zapatec.is_konqueror=/Konqueror/i.test(navigator.userAgent);Zapatec.is_gecko=/Gecko/i.test(navigator.userAgent);Zapatec.is_webkit=/WebKit/i.test(navigator.userAgent);Zapatec.webkitVersion=Zapatec.is_webkit?parseInt(navigator.userAgent.replace(/.+WebKit\/([0-9]+)\..+/,"$1")):-1;if(!Object.prototype.hasOwnProperty){Object.prototype.hasOwnProperty=function(strProperty){try{var objPrototype=this.constructor.prototype;while(objPrototype){if(objPrototype[strProperty]==this[strProperty]){return false;}
objPrototype=objPrototype.prototype;}}catch(objException){}
return true;};}
if(!Function.prototype.call){Function.prototype.call=function(){var objThis=arguments[0];objThis._this_func=this;var arrArgs=[];for(var iArg=1;iArg<arguments.length;iArg++){arrArgs[arrArgs.length]='arguments['+iArg+']';}
var ret=eval('objThis._this_func('+arrArgs.join(',')+')');objThis._this_func=null;return ret;};}
if(!Function.prototype.apply){Function.prototype.apply=function(){var objThis=arguments[0];var objArgs=arguments[1];objThis._this_func=this;var arrArgs=[];if(objArgs){for(var iArg=0;iArg<objArgs.length;iArg++){arrArgs[arrArgs.length]='objArgs['+iArg+']';}}
var ret=eval('objThis._this_func('+arrArgs.join(',')+')');objThis._this_func=null;return ret;};}
if(!Array.prototype.pop){Array.prototype.pop=function(){var last;if(this.length){last=this[this.length-1];this.length-=1;}
return last;};}
if(!Array.prototype.push){Array.prototype.push=function(){for(var i=0;i<arguments.length;i++){this[this.length]=arguments[i];}
return this.length;};}
if(!Array.prototype.shift){Array.prototype.shift=function(){var first;if(this.length){first=this[0];for(var i=0;i<this.length-1;i++){this[i]=this[i+1];}
this.length-=1;}
return first;};}
if(!Array.prototype.unshift){Array.prototype.unshift=function(){if(arguments.length){var i,len=arguments.length;for(i=this.length+len-1;i>=len;i--){this[i]=this[i-len];}
for(i=0;i<len;i++){this[i]=arguments[i];}}
return this.length;};}
if(!Array.prototype.splice){Array.prototype.splice=function(index,howMany){var elements=[],removed=[],i;for(i=2;i<arguments.length;i++){elements.push(arguments[i]);}
for(i=index;(i<index+howMany)&&(i<this.length);i++){removed.push(this[i]);}
for(i=index+howMany;i<this.length;i++){this[i-howMany]=this[i];}
this.length-=removed.length;for(i=this.length+elements.length-1;i>=index+elements.length;i--){this[i]=this[i-elements.length];}
for(i=0;i<elements.length;i++){this[index+i]=elements[i];}
return removed;};}
Zapatec.Utils.arrIndexOf=function(arr,searchElement,fromIndex){if(Array.prototype.indexOf){return arr.indexOf(searchElement,fromIndex);}
if(!fromIndex){fromIndex=0;}
for(var iElement=fromIndex;iElement<arr.length;iElement++){if(arr[iElement]==searchElement){return iElement;}}
return-1;};Zapatec.Log=function(objArgs){if(!objArgs){return;}
var strMessage=objArgs.description;if(objArgs.severity){strMessage=objArgs.severity+':\n'+strMessage;}
if(objArgs.type!="warning"){alert(strMessage);}};Zapatec.Utils.Array={};Zapatec.Utils.Array.insertBefore=function(arr,el,key,nextKey){var tmp=new Array();for(var i in arr){if(i==nextKey){if(key){tmp[key]=el;}else{tmp.push(el);}}
tmp[i]=arr[i];}
return tmp;}
Zapatec.inherit=function(oSubClass,oSuperClass,oArg){var Inheritance=function(){};Inheritance.prototype=oSuperClass.prototype;oSubClass.prototype=new Inheritance();oSubClass.prototype.constructor=oSubClass;oSubClass.SUPERconstructor=oSuperClass;oSubClass.SUPERclass=oSuperClass.prototype;if(typeof oSuperClass.path!='undefined'){if(oArg&&oArg.keepPath){oSubClass.path=oSuperClass.path;}else{oSubClass.path=Zapatec.getPath(oSubClass.id);}}};Zapatec.getPath=function(sId){var sSrc;if(typeof sId=='string'){var oScript=document.getElementById(sId);if(oScript){sSrc=oScript.getAttribute('src');}}
if(!sSrc){if(typeof Zapatec.lastLoadedModule=='string'){return Zapatec.lastLoadedModule;}
if(document.documentElement){var sHtml=document.documentElement.innerHTML;var aMatch=sHtml.match(/<script[^>]+src=[^>]+>/gi);if(aMatch&&aMatch.length){sHtml=aMatch[aMatch.length-1];aMatch=sHtml.match(/src="([^"]+)/i);if(aMatch&&aMatch.length==2){sSrc=aMatch[1];}}}
if(!sSrc){return'';}}
sSrc=sSrc.replace(/\\/g,'/');var aTokens=sSrc.split('?');aTokens=aTokens[0].split('/');aTokens=aTokens.slice(0,-1);if(!aTokens.length){return'';}
return aTokens.join('/')+'/';};Zapatec.Utils.setWindowEvent=function(oEvent){if(oEvent){window.event=oEvent;}};Zapatec.Utils.emulateWindowEvent=function(aEventNames){if(document.addEventListener){for(var iEvent=0;iEvent<aEventNames.length;iEvent++){document.addEventListener(aEventNames[iEvent],Zapatec.Utils.setWindowEvent,true);}}};Zapatec.windowLoaded=typeof(document.readyState)!='undefined'?(document.readyState=='loaded'||document.readyState=='complete'):document.getElementsByTagName!=null&&typeof(document.getElementsByTagName('body')[0])!='undefined';Zapatec.Utils.addEvent(window,"load",function(){Zapatec.windowLoaded=true;});Zapatec.Utils.warnUnload=function(msg,win){Zapatec.Utils.warnUnloadFlag=true;if(typeof(msg)!="string"){msg="All your changes will be lost.";}
if(typeof(win)=='undefined'){win=window;}
Zapatec.Utils.addEvent(win,'beforeunload',function(ev){if(Zapatec.Utils.warnUnloadFlag!=true){return true;}
if(typeof(ev)=='undefined'){ev=window.event;}
ev.returnValue=msg;return false;});}
Zapatec.Utils.unwarnUnload=function(msg,win){Zapatec.Utils.warnUnloadFlag=false;}
Zapatec.Utils.warnUnloadFlag=false;Zapatec.Utils.getMaxZindex=function(){if(window.opera||Zapatec.is_khtml){return 2147483583;}else if(Zapatec.is_ie){return 2147483647;}else{return 10737418239;}};Zapatec.Utils.correctCssLength=function(val){if(typeof val=='undefined'||(typeof val=='object'&&!val)){return'auto';}
val+='';if(!val.length){return'auto';}
if(/\d$/.test(val)){val+='px';}
return val;};Zapatec.Utils.destroyOnUnload=[];Zapatec.Utils.addDestroyOnUnload=function(objElement,strProperty){Zapatec.Utils.destroyOnUnload.push([objElement,strProperty]);};Zapatec.Utils.createProperty=function(objElement,strProperty,val){objElement[strProperty]=val;Zapatec.Utils.addDestroyOnUnload(objElement,strProperty);};Zapatec.Utils.addEvent(window,'unload',function(){for(var iObj=Zapatec.Utils.destroyOnUnload.length-1;iObj>=0;iObj--){var objDestroy=Zapatec.Utils.destroyOnUnload[iObj];objDestroy[0][objDestroy[1]]=null;objDestroy[0]=null;}
for(var iLis=Zapatec.Utils.removeOnUnload.length-1;iLis>=0;iLis--){var oParams=Zapatec.Utils.removeOnUnload[iLis];if(!oParams){continue;}
Zapatec.Utils.removeOnUnload[iLis]=null;Zapatec.Utils.removeEvent(oParams['element'],oParams['event'],oParams['listener'],oParams['capture']);}});Zapatec.Utils.htmlEncode=function(str){str=str.replace(/&/ig,"&amp;");str=str.replace(/</ig,"&lt;");str=str.replace(/>/ig,"&gt;");str=str.replace(/\x22/ig,"&quot;");return str;};Zapatec.Utils.applyStyle=function(elRef,style){if(typeof(elRef)=='string'){elRef=document.getElementById(elRef);}
if(elRef==null||style==null||elRef.style==null){return null;}
if(Zapatec.is_opera){var pairs=style.split(";");for(var ii=0;ii<pairs.length;ii++){var kv=pairs[ii].split(":");if(!kv[1]){continue;}
var value=kv[1].replace(/^\s*/,'').replace(/\s*$/,'');var key="";for(var jj=0;jj<kv[0].length;jj++){if(kv[0].charAt(jj)=="-"){jj++;if(jj<kv[0].length){key+=kv[0].charAt(jj).toUpperCase();}
continue;}
key+=kv[0].charAt(jj);}
switch(key){case"float":key="cssFloat";break;}
try{elRef.style[key]=value;}catch(e){}}}else{elRef.style.cssText=style;}
return true;}
Zapatec.Utils.getStyleProperty=function(objElement,strProperty){if(document.defaultView&&document.defaultView.getComputedStyle){strProperty=strProperty.replace(/([A-Z])/g,'-$1').toLowerCase();var computedStyle=document.defaultView.getComputedStyle(objElement,'');if(computedStyle){return computedStyle.getPropertyValue(strProperty);}}else if(objElement.currentStyle){return objElement.currentStyle[strProperty];}
return objElement.style[strProperty];};Zapatec.Utils.getPrecision=function(dFloat){return(dFloat+'').replace(/^\d*\.*/,'').length;};Zapatec.Utils.setPrecision=function(dFloat,iPrecision){dFloat*=1;if(dFloat.toFixed){return(dFloat*1).toFixed(iPrecision)*1;}
var iPow=Math.pow(10,iPrecision);return parseInt(dFloat*iPow,10)/iPow;};Zapatec.Utils.setPrecisionString=function(dFloat,iPrecision){var sFloat=Zapatec.Utils.setPrecision(dFloat,iPrecision)+'';var iZeros=iPrecision-Zapatec.Utils.getPrecision(sFloat);for(var iZero=0;iZero<iZeros;iZero++){sFloat+='0';}
return sFloat;};Zapatec.Utils.createNestedHash=function(parent,keys,value){if(parent==null||keys==null){return null;}
var tmp=parent;for(var ii=0;ii<keys.length;ii++){if(typeof(tmp[keys[ii]])=='undefined'){tmp[keys[ii]]={};}
if(ii==keys.length-1&&typeof(value)!='undefined'){tmp[keys[ii]]=value;}
tmp=tmp[keys[ii]];}}
Zapatec.implement=function(classOrObject,interfaceStr){if(typeof interfaceStr!="string"){return false;}
if(typeof classOrObject=="function"){classOrObject=classOrObject.prototype;}
if(!classOrObject||typeof classOrObject!="object"){return false;}
var interfaceObj=window;var objs=interfaceStr.split(".");try{for(var i=0;i<objs.length;++i){interfaceObj=interfaceObj[objs[i]];}}catch(e){return false;}
if(typeof classOrObject.interfaces!="object"){classOrObject.interfaces={};classOrObject.interfaces[interfaceStr]=true;}else if(classOrObject.interfaces[interfaceStr]!==true){classOrObject.interfaces=Zapatec.Utils.clone(classOrObject.interfaces);classOrObject.interfaces[interfaceStr]=true;}else{return true;}
for(var iProp in interfaceObj){classOrObject[iProp]=interfaceObj[iProp];}
classOrObject.hasInterface=function(interfaceStr){if(this.interfaces[interfaceStr]===true){return true;}
return false;}
return true;};Zapatec.Utils.getCharFromEvent=function(evt){if(!evt){evt=window.event;}
var response={};if(Zapatec.is_gecko&&!Zapatec.is_khtml&&evt.type!="keydown"&&evt.type!="keyup"){if(evt.charCode){response.chr=String.fromCharCode(evt.charCode);}else{response.charCode=evt.keyCode;}}else{response.charCode=evt.keyCode||evt.which;response.chr=String.fromCharCode(response.charCode);}
if(Zapatec.is_opera&&response.charCode==0){response.charCode=null;response.chr=null;}
if(Zapatec.is_khtml&&response.charCode==63272){response.charCode=46;response.chr=null;}
return response;}
if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.Transport=function(){};if(typeof ActiveXObject!='undefined'){Zapatec.Transport.XMLDOM=null;Zapatec.Transport.XMLHTTP=null;Zapatec.Transport.pickActiveXVersion=function(aVersions){for(var iVn=0;iVn<aVersions.length;iVn++){try{var oDoc=new ActiveXObject(aVersions[iVn]);if(oDoc){return aVersions[iVn];}}catch(oExpn){};}
return null;};Zapatec.Transport.XMLDOM=Zapatec.Transport.pickActiveXVersion(['Msxml2.DOMDocument.4.0','Msxml2.DOMDocument.3.0','MSXML2.DOMDocument','MSXML.DOMDocument','Microsoft.XMLDOM']);Zapatec.Transport.XMLHTTP=Zapatec.Transport.pickActiveXVersion(['Msxml2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP']);Zapatec.Transport.pickActiveXVersion=null;}
Zapatec.Transport.createXmlHttpRequest=function(){if(typeof ActiveXObject!='undefined'){try{return new ActiveXObject(Zapatec.Transport.XMLHTTP);}catch(oExpn){};}
if(typeof XMLHttpRequest!='undefined'){return new XMLHttpRequest();}
return null;};Zapatec.Transport.isBusy=function(oArg){var oContr=oArg.busyContainer;if(typeof oContr=='string'){oContr=document.getElementById(oContr);}
if(!oContr){return;}
var sImage=oArg.busyImage;if(typeof sImage!='string'){sImage='';}
sImage=sImage.split('/').pop();if(!sImage.length){sImage='zpbusy.gif';}
var oFC=oContr.firstChild;if(oFC){oFC=oFC.firstChild;if(oFC){oFC=oFC.firstChild;if(oFC&&oFC.tagName&&oFC.tagName.toLowerCase()=='img'){var sSrc=oFC.getAttribute('src');if(typeof sSrc=='string'&&sSrc.length){sSrc=sSrc.split('/').pop();if(sSrc==sImage){return true;}}}}}
return false;};Zapatec.Transport.showBusy=function(oArg){if(Zapatec.Transport.isBusy(oArg)){return;}
var oContr=oArg.busyContainer;if(typeof oContr=='string'){oContr=document.getElementById(oContr);}
if(!oContr){return;}
var sImage=oArg.busyImage;var sImageWidth=oArg.busyImageWidth;var sImageHeight=oArg.busyImageHeight;if(typeof sImage!='string'||!sImage.length){sImage='zpbusy.gif';}else{if(typeof sImageWidth=='number'||(typeof sImageWidth=='string'&&/\d$/.test(sImageWidth))){sImageWidth+='px';}
if(typeof sImageHeight=='number'||(typeof sImageHeight=='string'&&/\d$/.test(sImageHeight))){sImageHeight+='px';}}
if(!sImageWidth){sImageWidth='65px';}
if(!sImageHeight){sImageHeight='35px';}
var sPath='';if(sImage.indexOf('/')<0){if(Zapatec.zapatecPath){sPath=Zapatec.zapatecPath;}else{sPath=Zapatec.Transport.getPath('transport.js');}}
var aImg=[];aImg.push('<img src="');aImg.push(sPath);aImg.push(sImage);aImg.push('"');if(sImageWidth||sImageHeight){aImg.push(' style="');if(sImageWidth){aImg.push('width:');aImg.push(sImageWidth);aImg.push(';');}
if(sImageHeight){aImg.push('height:');aImg.push(sImageHeight);}
aImg.push('"');}
aImg.push(' />');var iContainerWidth=oContr.offsetWidth;var iContainerHeight=oContr.offsetHeight;var oBusyContr=Zapatec.Utils.createElement('div');oBusyContr.style.position='relative';oBusyContr.style.zIndex=2147483583;var oBusy=Zapatec.Utils.createElement('div',oBusyContr);oBusy.style.position='absolute';oBusy.innerHTML=aImg.join('');if(oContr.firstChild){oContr.insertBefore(oBusyContr,oContr.firstChild);}else{oContr.appendChild(oBusyContr);}
var iBusyWidth=oBusy.offsetWidth;var iBusyHeight=oBusy.offsetHeight;if(iContainerWidth>iBusyWidth){oBusy.style.left=oContr.scrollLeft+
(iContainerWidth-iBusyWidth)/2+'px';}
if(iContainerHeight>iBusyHeight){oBusy.style.top=oContr.scrollTop+
(iContainerHeight-iBusyHeight)/2+'px';}};Zapatec.Transport.removeBusy=function(oArg){var oContr=oArg.busyContainer;if(typeof oContr=='string'){oContr=document.getElementById(oContr);}
if(!oContr){return;}
if(Zapatec.Transport.isBusy(oArg)){oContr.removeChild(oContr.firstChild);}};Zapatec.Transport.fetch=function(oArg){if(oArg==null||typeof oArg!='object'){return null;}
if(!oArg.url){return null;}
if(!oArg.method){oArg.method='GET';}
if(typeof oArg.async=='undefined'){oArg.async=true;}
if(!oArg.contentType&&oArg.method.toUpperCase()=='POST'){oArg.contentType='application/x-www-form-urlencoded';}
if(!oArg.content){oArg.content=null;}
if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
var oRequest=Zapatec.Transport.createXmlHttpRequest();if(oRequest==null){return null;}
Zapatec.Transport.showBusy(oArg);var bErrorDisplayed=false;var funcOnReady=function(){Zapatec.Transport.removeBusy(oArg);try{if(oRequest.status==200||oRequest.status==304||(location.protocol=='file:'&&!oRequest.status)){if(typeof oArg.onLoad=='function'){oArg.onLoad(oRequest);}}else if(!bErrorDisplayed){bErrorDisplayed=true;Zapatec.Transport.displayError(oRequest.status,"Error: Can't fetch "+oArg.url+'.\n'+
(oRequest.statusText||''),oArg.onError);}}catch(oExpn){if(!bErrorDisplayed){bErrorDisplayed=true;if(oExpn.name&&oExpn.name=='NS_ERROR_NOT_AVAILABLE'){Zapatec.Transport.displayError(0,"Error: Can't fetch "+oArg.url+'.\nFile not found.',oArg.onError);}else{Zapatec.Transport.displayError(0,"Error: Can't fetch "+oArg.url+'.\n'+
(oExpn.message||''),oArg.onError);}}};};try{if(typeof oArg.username!='undefined'&&typeof oArg.password!='undefined'){oRequest.open(oArg.method,oArg.url,oArg.async,oArg.username,oArg.password);}else{oRequest.open(oArg.method,oArg.url,oArg.async);}
if(oArg.async){oRequest.onreadystatechange=function(){if(oRequest.readyState==4){funcOnReady();oRequest.onreadystatechange={};}};}
if(oArg.contentType){oRequest.setRequestHeader('Content-Type',oArg.contentType);}
oRequest.send(oArg.content);if(!oArg.async){funcOnReady();return oRequest;}}catch(oExpn){Zapatec.Transport.removeBusy(oArg);if(!bErrorDisplayed){bErrorDisplayed=true;if(oExpn.name&&oExpn.name=='NS_ERROR_FILE_NOT_FOUND'){Zapatec.Transport.displayError(0,"Error: Can't fetch "+oArg.url+'.\nFile not found.',oArg.onError);}else{Zapatec.Transport.displayError(0,"Error: Can't fetch "+oArg.url+'.\n'+
(oExpn.message||''),oArg.onError);}}};return null;};Zapatec.Transport.parseHtml=function(sHtml){sHtml+='';sHtml=sHtml.replace(/^\s+/g,'');var oTmpContr;if(document.createElementNS){oTmpContr=document.createElementNS('http://www.w3.org/1999/xhtml','div');}else{oTmpContr=document.createElement('div');}
oTmpContr.innerHTML=sHtml;return oTmpContr;};Zapatec.Transport.evalGlobalScope=function(sScript){if(typeof sScript!='string'||!sScript.match(/\S/)){return;}
if(window.execScript){window.execScript(sScript,'javascript');}else if(window.eval){window.eval(sScript);}};Zapatec.Transport.setInnerHtml=function(oArg){if(!oArg||typeof oArg.html!='string'){return;}
var sHtml=oArg.html;var oContr=null;if(typeof oArg.container=='string'){oContr=document.getElementById(oArg.container);}else if(typeof oArg.container=='object'){oContr=oArg.container;}
var aScripts=[];if(sHtml.match(/<\s*\/\s*script\s*>/i)){var aTokens=sHtml.split(/<\s*\/\s*script\s*>/i);var aHtml=[];for(var iToken=aTokens.length-1;iToken>=0;iToken--){var sToken=aTokens[iToken];if(sToken.match(/\S/)){var aMatch=sToken.match(/<\s*script([^>]*)>/i);if(aMatch){var aCouple=sToken.split(/<\s*script[^>]*>/i);while(aCouple.length<2){if(sToken.match(/^<\s*script[^>]*>/i)){aCouple.unshift('');}else{aCouple.push('');}}
aHtml.unshift(aCouple[0]);var sAttrs=aMatch[1];var srtScript=aCouple[1];if(sAttrs.match(/\s+src\s*=/i)){srtScript='';}else{srtScript=srtScript.replace(/function\s+([^(]+)/g,'$1=function');}
aScripts.push([sAttrs,srtScript]);}else if(iToken<aTokens.length-1){aTokens[iToken-1]+='</script>'+sToken;}else{aHtml.unshift(sToken);}}else{aHtml.unshift(sToken);}}
sHtml=aHtml.join('');}
if(oContr){if(window.opera){oContr.innerHTML='<form></form>';}
oContr.innerHTML=sHtml;}
for(var iScript=0;iScript<aScripts.length;iScript++){if(aScripts[iScript][1].length){Zapatec.Transport.evalGlobalScope(aScripts[iScript][1]);}
var sAttrs=aScripts[iScript][0];sAttrs=sAttrs.replace(/\s+/g,' ').replace(/^\s/,'').replace(/\s$/,'').replace(/ = /g,'=');if(sAttrs.indexOf('src=')>=0){var oContr=document.body;if(!oContr){oContr=document.getElementsByTagName('head')[0];if(!oContr){oContr=document;}}
var aAttrs=sAttrs.split(' ');var oScript=Zapatec.Utils.createElement('script');for(var iAttr=0;iAttr<aAttrs.length;iAttr++){var aAttr=aAttrs[iAttr].split('=');if(aAttr.length>1){oScript.setAttribute(aAttr[0],aAttr[1].match(/^[\s|"|']*([\s|\S]*[^'|"])[\s|"|']*$/)[1]);}else{oScript.setAttribute(aAttr[0],aAttr[0]);}}
oContr.appendChild(oScript);}}};Zapatec.Transport.fetchXmlDoc=function(oArg){if(oArg==null||typeof oArg!='object'){return null;}
if(!oArg.url){return null;}
if(typeof oArg.async=='undefined'){oArg.async=true;}
if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
if(!oArg.method&&typeof oArg.username=='undefined'&&typeof oArg.password=='undefined'){if(document.implementation&&document.implementation.createDocument){var oDoc=null;if(!oArg.reliable){oArg.reliable=false;}
var oFetchArg={};for(var sKey in oArg){oFetchArg[sKey]=oArg[sKey];}
if(oArg.async){oFetchArg.onLoad=function(oRequest){oFetchArg.onLoad=null;var parser=new DOMParser();oDoc=parser.parseFromString(oRequest.responseText,"text/xml");Zapatec.Transport.removeBusy(oArg);Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);};}else{oFetchArg.onLoad=null;}
var oRequest=Zapatec.Transport.fetch(oFetchArg);if(!oArg.async&&oRequest){var parser=new DOMParser();oDoc=parser.parseFromString(oRequest.responseText,"text/xml");Zapatec.Transport.removeBusy(oArg);Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);return oDoc;}
return null;}
if(typeof ActiveXObject!='undefined'){Zapatec.Transport.showBusy(oArg);try{var oDoc=new ActiveXObject(Zapatec.Transport.XMLDOM);oDoc.async=oArg.async;if(oArg.async){oDoc.onreadystatechange=function(){if(oDoc.readyState==4){Zapatec.Transport.removeBusy(oArg);Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);oDoc.onreadystatechange={};}};}
oDoc.load(oArg.url);if(!oArg.async){Zapatec.Transport.removeBusy(oArg);Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);return oDoc;}
return null;}catch(oExpn){Zapatec.Transport.removeBusy(oArg);};}}
var oFetchArg={};for(var sKey in oArg){oFetchArg[sKey]=oArg[sKey];}
if(oArg.async){oFetchArg.onLoad=function(oRequest){Zapatec.Transport.parseXml({strXml:oRequest.responseText,onLoad:oArg.onLoad,onError:oArg.onError});};}else{oFetchArg.onLoad=null;}
var oRequest=Zapatec.Transport.fetch(oFetchArg);if(!oArg.async&&oRequest){return Zapatec.Transport.parseXml({strXml:oRequest.responseText,onLoad:oArg.onLoad,onError:oArg.onError});}
return null;};Zapatec.Transport.parseXml=function(oArg){if(oArg==null||typeof oArg!='object'){return null;}
if(!oArg.strXml){return null;}
if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
if(window.DOMParser){try{var oDoc=(new DOMParser()).parseFromString(oArg.strXml,'text/xml');Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);return oDoc;}catch(oExpn){Zapatec.Transport.displayError(0,"Error: Can't parse.\n"+'String does not appear to be a valid XML fragment.',oArg.onError);};return null;}
if(typeof ActiveXObject!='undefined'){try{var oDoc=new ActiveXObject(Zapatec.Transport.XMLDOM);oDoc.loadXML(oArg.strXml);Zapatec.Transport.onXmlDocLoad(oDoc,oArg.onLoad,oArg.onError);return oDoc;}catch(oExpn){};}
return null;};Zapatec.Transport.onXmlDocLoad=function(oDoc,onLoad,onError){var sError=null;if(oDoc.parseError){sError=oDoc.parseError.reason;if(oDoc.parseError.srcText){sError+='Location: '+oDoc.parseError.url+'\nLine number '+oDoc.parseError.line+', column '+
oDoc.parseError.linepos+':\n'+
oDoc.parseError.srcText+'\n';}}else if(oDoc.documentElement&&oDoc.documentElement.tagName=='parsererror'){sError=oDoc.documentElement.firstChild.data+'\n'+
oDoc.documentElement.firstChild.nextSibling.firstChild.data;}else if(!oDoc.documentElement){sError='String does not appear to be a valid XML fragment.';}
if(sError){Zapatec.Transport.displayError(0,"Error: Can't parse.\n"+sError,onError);}else{if(typeof onLoad=='function'){onLoad(oDoc);}}};Zapatec.Transport.serializeXmlDoc=function(oDoc){if(window.XMLSerializer){return(new XMLSerializer).serializeToString(oDoc);}
if(oDoc.xml){return oDoc.xml;}};Zapatec.Transport.fetchJsonObj=function(oArg){if(oArg==null||typeof oArg!='object'){return null;}
if(!oArg.url){return null;}
if(typeof oArg.async=='undefined'){oArg.async=true;}
if(!oArg.reliable){oArg.reliable=false;}
var oFetchArg={};for(var sKey in oArg){oFetchArg[sKey]=oArg[sKey];}
if(oArg.async){oFetchArg.onLoad=function(oRequest){Zapatec.Transport.parseJson({strJson:oRequest.responseText,reliable:oArg.reliable,onLoad:oArg.onLoad,onError:oArg.onError});};}else{oFetchArg.onLoad=null;}
var oRequest=Zapatec.Transport.fetch(oFetchArg);if(!oArg.async&&oRequest){return Zapatec.Transport.parseJson({strJson:oRequest.responseText,reliable:oArg.reliable,onLoad:oArg.onLoad,onError:oArg.onError});}
return null;};Zapatec.Transport.parseJson=function(oArg){if(oArg==null||typeof oArg!='object'){return null;}
if(!oArg.reliable){oArg.reliable=false;}
if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
var oJson=null;try{if(oArg.reliable){if(oArg.strJson){oJson=eval('('+oArg.strJson+')');}}else{oJson=Zapatec.Transport.parseJsonStr(oArg.strJson);}}catch(oExpn){var sError="Error: Can't parse.\nString doesn't appear to be a valid JSON fragment: ";sError+=oExpn.message;if(typeof oExpn.text!='undefined'&&oExpn.text.length){sError+='\n'+oExpn.text;}
sError+='\n'+oArg.strJson;Zapatec.Transport.displayError(0,sError,oArg.onError);return null;};if(typeof oArg.onLoad=='function'){oArg.onLoad(oJson);}
return oJson;};Zapatec.Transport.parseJsonStr=function(text){var p=/^\s*(([,:{}\[\]])|"(\\.|[^\x00-\x1f"\\])*"|-?\d+(\.\d*)?([eE][+-]?\d+)?|true|false|null)\s*/,token,operator;function error(m,t){throw{name:'JSONError',message:m,text:t||operator||token};}
function next(b){if(b&&b!=operator){error("Expected '"+b+"'");}
if(text){var t=p.exec(text);if(t){if(t[2]){token=null;operator=t[2];}else{operator=null;try{token=eval(t[1]);}catch(e){error("Bad token",t[1]);}}
text=text.substring(t[0].length);}else{error("Unrecognized token",text);}}else{token=operator=null;}}
function val(){var k,o;switch(operator){case'{':next('{');o={};if(operator!='}'){for(;;){if(operator||typeof token!='string'){error("Missing key");}
k=token;next();next(':');o[k]=val();if(operator!=','){break;}
next(',');}}
next('}');return o;case'[':next('[');o=[];if(operator!=']'){for(;;){o.push(val());if(operator!=','){break;}
next(',');}}
next(']');return o;default:if(operator!==null){error("Missing value");}
k=token;next();return k;}}
next();return val();};Zapatec.Transport.serializeJsonObj=function(v){var a=[];function e(s){a[a.length]=s;}
function g(x){var c,i,l,v;switch(typeof x){case'object':if(x){if(x instanceof Array){e('[');l=a.length;for(i=0;i<x.length;i+=1){v=x[i];if(typeof v!='undefined'&&typeof v!='function'){if(l<a.length){e(',');}
g(v);}}
e(']');return;}else if(typeof x.toString!='undefined'){e('{');l=a.length;for(i in x){v=x[i];if(x.hasOwnProperty(i)&&typeof v!='undefined'&&typeof v!='function'){if(l<a.length){e(',');}
g(i);e(':');g(v);}}
return e('}');}}
e('null');return;case'number':e(isFinite(x)?+x:'null');return;case'string':l=x.length;e('"');for(i=0;i<l;i+=1){c=x.charAt(i);if(c>=' '){if(c=='\\'||c=='"'){e('\\');}
e(c);}else{switch(c){case'\b':e('\\b');break;case'\f':e('\\f');break;case'\n':e('\\n');break;case'\r':e('\\r');break;case'\t':e('\\t');break;default:c=c.charCodeAt();e('\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16));}}}
e('"');return;case'boolean':e(String(x));return;default:e('null');return;}}
g(v);return a.join('');};Zapatec.Transport.displayError=function(iErrCode,sError,onError){if(typeof onError=='function'){onError({errorCode:iErrCode,errorDescription:sError});}else{alert(sError);}};Zapatec.Transport.translateUrl=function(oArg){if(!oArg||!oArg.url){return null;}
var aFullUrl=oArg.url.split('?',2);var sUrl=aFullUrl[0];if(sUrl.charAt(0)=='/'||sUrl.indexOf(':')>=0){return oArg.url;}
var sRelativeTo;if(typeof oArg.relativeTo!='string'){sRelativeTo=document.location.toString().split('?',2)[0];}else{sRelativeTo=oArg.relativeTo.split('?',2)[0];if(sRelativeTo.indexOf('/')<0){sRelativeTo=document.location.toString().split('?',2)[0];}else if(sRelativeTo.charAt(0)!='/'&&sRelativeTo.indexOf(':')<0){sRelativeTo=Zapatec.Transport.translateUrl({url:sRelativeTo});}}
var aUrl=sUrl.split('/');var aRelativeTo=sRelativeTo.split('/');aRelativeTo.pop();for(var iToken=0;iToken<aUrl.length;iToken++){var sToken=aUrl[iToken];if(sToken=='..'){aRelativeTo.pop();}else if(sToken!='.'){aRelativeTo.push(sToken);}}
aFullUrl[0]=aRelativeTo.join('/');return aFullUrl.join('?');};Zapatec.Transport.loading={};Zapatec.Transport.setupEvents=function(oArg){if(!oArg){return{};}
if(oArg.force||!Zapatec.EventDriven||!oArg.url){return{onLoad:oArg.onLoad,onError:oArg.onError};}
var sUrl=oArg.url;if(typeof oArg.onLoad=='function'){Zapatec.EventDriven.addEventListener('zpTransportOnLoad'+sUrl,oArg.onLoad);}
if(typeof oArg.onError=='function'){Zapatec.EventDriven.addEventListener('zpTransportOnError'+sUrl,oArg.onError);}
if(Zapatec.Transport.loading[sUrl]){return{loading:true};}else{Zapatec.Transport.loading[sUrl]=true;return{onLoad:new Function("Zapatec.EventDriven.fireEvent('zpTransportOnLoad"+
sUrl+"');Zapatec.EventDriven.removeEvent('zpTransportOnLoad"+
sUrl+"');Zapatec.EventDriven.removeEvent('zpTransportOnError"+
sUrl+"');Zapatec.Transport.loading['"+sUrl+"'] = false;"),onError:new Function('oError',"Zapatec.EventDriven.fireEvent('zpTransportOnError"+
sUrl+"',oError);Zapatec.EventDriven.removeEvent('zpTransportOnLoad"+
sUrl+"');Zapatec.EventDriven.removeEvent('zpTransportOnError"+
sUrl+"');Zapatec.Transport.loading['"+sUrl+"'] = false;")};}};Zapatec.Transport.loadedJS={};Zapatec.Transport.isLoadedJS=function(sUrl,sAbsUrl){if(typeof sAbsUrl=='undefined'){sAbsUrl=Zapatec.Transport.translateUrl({url:sUrl});}
if(Zapatec.Transport.loadedJS[sAbsUrl]){return true;}
var aScripts=document.getElementsByTagName('script');for(var iScript=0;iScript<aScripts.length;iScript++){var sSrc=aScripts[iScript].getAttribute('src')||'';if(sSrc==sUrl){Zapatec.Transport.loadedJS[sAbsUrl]=true;return true;}}
return false;};Zapatec.Transport.getPath=function(sScriptFileName){var aScripts=document.getElementsByTagName('script');for(var iScript=aScripts.length-1;iScript>=0;iScript--){var sSrc=aScripts[iScript].getAttribute('src')||'';var aTokens=sSrc.split('/');var sLastToken=aTokens.pop();if(sLastToken==sScriptFileName){return aTokens.length?aTokens.join('/')+'/':'';}}
for(var sSrc in Zapatec.Transport.loadedJS){var aTokens=sSrc.split('/');var sLastToken=aTokens.pop();if(sLastToken==sScriptFileName){return aTokens.length?aTokens.join('/')+'/':'';}}
return'';};Zapatec.Transport.include=function(sSrc,sId,bForce){if(Zapatec.doNotInclude){return;}
var sAbsUrl=Zapatec.Transport.translateUrl({url:sSrc});if(!bForce&&Zapatec.Transport.isLoadedJS(sSrc,sAbsUrl)){return;}
document.write('<script type="text/javascript" src="'+sSrc+
(typeof sId=='string'?'" id="'+sId:'')+'"></script>');Zapatec.Transport.loadedJS[sAbsUrl]=true;};Zapatec.include=Zapatec.Transport.include;Zapatec.Transport.includeJS=function(sSrc,sId){setTimeout(function(){var oContr=document.body;if(!oContr){oContr=document.getElementsByTagName('head')[0];if(!oContr){oContr=document;}}
var oScript=document.createElement('script');oScript.type='text/javascript';oScript.src=sSrc;if(typeof sId=='string'){oScript.id=sId;}
oContr.appendChild(oScript);},0);};Zapatec.Transport.loadJS=function(oArg){if(!(oArg instanceof Object)){return;}
if(typeof oArg.async=='undefined'){oArg.async=true;}
var sUrl=null;if(oArg.url){sUrl=oArg.url;}else if(oArg.module){var sPath='';if(typeof oArg.path!='undefined'){sPath=oArg.path;}else if(typeof Zapatec.zapatecPath!='undefined'){sPath=Zapatec.zapatecPath;}
sUrl=sPath+oArg.module+'.js';}else{return;}
var sAbsUrl=Zapatec.Transport.translateUrl({url:sUrl});if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
if(Zapatec.doNotInclude||(!oArg.force&&Zapatec.Transport.isLoadedJS(sUrl,sAbsUrl))){if(typeof oArg.onLoad=='function'){oArg.onLoad();}
return;}
var oHandlers=Zapatec.Transport.setupEvents({url:sAbsUrl,force:oArg.force,onLoad:oArg.onLoad,onError:oArg.onError});if(oHandlers.loading){return;}
Zapatec.Transport.fetch({url:sUrl,async:oArg.async,onLoad:function(oRequest){if(oArg.force||!Zapatec.Transport.loadedJS[sAbsUrl]){var aTokens=sUrl.split('/');var sLastToken=aTokens.pop();Zapatec.lastLoadedModule=aTokens.join('/')+'/';Zapatec.Transport.evalGlobalScope(oRequest.responseText);Zapatec.lastLoadedModule=null;Zapatec.Transport.loadedJS[sAbsUrl]=true;}
if(typeof oHandlers.onLoad=='function'){oHandlers.onLoad();}},onError:oHandlers.onError});};Zapatec.Transport.includeCSS=function(sHref){var oContr=document.getElementsByTagName('head')[0];if(!oContr){return;}
var oLink=document.createElement('link');oLink.setAttribute('rel','stylesheet');oLink.setAttribute('type','text/css');oLink.setAttribute('href',sHref);oContr.appendChild(oLink);};Zapatec.Transport.loadedCss={};Zapatec.Transport.loadCss=function(oArg){if(Zapatec.StyleSheet){Zapatec.Transport.loadCssWithStyleSheet(oArg);}else{Zapatec.Transport.loadJS({module:'stylesheet',async:oArg.async,onLoad:function(){Zapatec.Transport.loadCssWithStyleSheet(oArg);}});}};Zapatec.Transport.loadCssWithStyleSheet=function(oArg){if(!(oArg instanceof Object)){return;}
if(!oArg.url){return;}
if(typeof oArg.async=='undefined'){oArg.async=true;}
var sAbsUrl=Zapatec.Transport.translateUrl({url:oArg.url});if(!oArg.force){if(Zapatec.Transport.loadedCss[sAbsUrl]){if(typeof oArg.onLoad=='function'){oArg.onLoad();}
return;}
var aLinks=document.getElementsByTagName('link');for(var iLnk=0;iLnk<aLinks.length;iLnk++){var sHref=aLinks[iLnk].getAttribute('href')||'';sHref=Zapatec.Transport.translateUrl({url:sHref});if(sHref==sAbsUrl){Zapatec.Transport.loadedCss[sAbsUrl]=true;if(typeof oArg.onLoad=='function'){oArg.onLoad();}
return;}}}
var oHandlers=Zapatec.Transport.setupEvents({url:sAbsUrl,force:oArg.force,onLoad:oArg.onLoad,onError:oArg.onError});if(oHandlers.loading){return;}
Zapatec.Transport.fetch({url:oArg.url,async:oArg.async,onLoad:function(oRequest){var sCss=oRequest.responseText;var aResultCss=[];var aImgUrls=[];var aCssUrls=[];var iPos=0;var iNextPos=sCss.indexOf('url(',iPos);while(iNextPos>=0){iNextPos+=4;var sToken=sCss.substring(iPos,iNextPos);var bIsImport=/@import\s+url\($/.test(sToken);aResultCss.push(sToken);iPos=iNextPos;iNextPos=sCss.indexOf(')',iPos);if(iNextPos>=0){var sImgUrl=sCss.substring(iPos,iNextPos);sImgUrl=sImgUrl.replace(/['"]/g,'');sImgUrl=Zapatec.Transport.translateUrl({url:sImgUrl,relativeTo:oArg.url});sImgUrl=Zapatec.Transport.translateUrl({url:sImgUrl});aResultCss.push(sImgUrl);if(bIsImport){aCssUrls.push(sImgUrl);}else{aImgUrls.push(sImgUrl);}
iPos=iNextPos;iNextPos=sCss.indexOf('url(',iPos);}}
aResultCss.push(sCss.substr(iPos));sCss=aResultCss.join('');Zapatec.Transport.loadCssList({urls:aCssUrls,async:oArg.async,onLoad:function(){(new Zapatec.StyleSheet()).addParse(sCss);if(typeof oHandlers.onLoad=='function'){oHandlers.onLoad();}}});Zapatec.Transport.loadedCss[sAbsUrl]=true;Zapatec.Transport.preloadImages({urls:aImgUrls,timeout:60000});},onError:oHandlers.onError});};Zapatec.Transport.loadCssList=function(oArg){if(!(oArg instanceof Object)){return;}
if(typeof oArg.async=='undefined'){oArg.async=true;}
if(!oArg.onLoad){oArg.onLoad=null;}
if(!oArg.onError){oArg.onError=null;}
if(!oArg.urls||!oArg.urls.length){if(typeof oArg.onLoad=='function'){oArg.onLoad();}
return;}
var sUrl=oArg.urls.shift();var funcOnLoad=function(){Zapatec.Transport.loadCssList({urls:oArg.urls,async:oArg.async,force:oArg.force,onLoad:oArg.onLoad,onError:oArg.onError});};Zapatec.Transport.loadCss({url:sUrl,async:oArg.async,force:oArg.force,onLoad:funcOnLoad,onError:function(oError){Zapatec.Transport.displayError(oError.errorCode,oError.errorDescription,oArg.onError);funcOnLoad();}});};Zapatec.Transport.imagePreloads=[];Zapatec.Transport.preloadImages=function(oArg){if(Zapatec.PreloadImages){Zapatec.Transport.imagePreloads.push(new Zapatec.PreloadImages(oArg));}else{Zapatec.Transport.loadJS({module:'preloadimages',onLoad:function(){Zapatec.Transport.imagePreloads.push(new Zapatec.PreloadImages(oArg));}});}};if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.StyleSheet=function(bUseLast){if(bUseLast){if(document.createStyleSheet){if(document.styleSheets.length){this.styleSheet=document.styleSheets[document.styleSheets.length-1];}}else{var aStyleSheets=document.getElementsByTagName('style');if(aStyleSheets.length){this.styleSheet=aStyleSheets[aStyleSheets.length-1];}}}
if(!this.styleSheet){if(document.createStyleSheet){try{this.styleSheet=document.createStyleSheet();}catch(oException){this.styleSheet=document.styleSheets[document.styleSheets.length-1];};}else{this.styleSheet=document.createElement('style');this.styleSheet.type='text/css';var oHead=document.getElementsByTagName('head')[0];if(!oHead){oHead=document.documentElement;}
if(oHead){oHead.appendChild(this.styleSheet);}}}};Zapatec.StyleSheet.prototype.addRule=function(strSelector,strDeclarations){if(!this.styleSheet){return;}
if(document.createStyleSheet){this.styleSheet.cssText+=strSelector+' { '+strDeclarations+' }';}else{this.styleSheet.appendChild(document.createTextNode(strSelector+' { '+strDeclarations+' }'));}};Zapatec.StyleSheet.prototype.removeRules=function(){if(!this.styleSheet){return;}
if(document.createStyleSheet){var iRules=this.styleSheet.rules.length;for(var iRule=0;iRule<iRules;iRule++){this.styleSheet.removeRule();}}else{while(this.styleSheet.firstChild){this.styleSheet.removeChild(this.styleSheet.firstChild);}}};Zapatec.StyleSheet.prototype.addParse=function(strStyleSheet){var arrClean=[];var arrTokens=strStyleSheet.split('/*');for(var iTok=0;iTok<arrTokens.length;iTok++){var arrTails=arrTokens[iTok].split('*/');arrClean.push(arrTails[arrTails.length-1]);}
strStyleSheet=arrClean.join('');strStyleSheet=strStyleSheet.replace(/@[^{]*;/g,'');var arrStyles=strStyleSheet.split('}');for(var iStl=0;iStl<arrStyles.length;iStl++){var arrRules=arrStyles[iStl].split('{');if(arrRules[0]&&arrRules[1]){var arrSelectors=arrRules[0].split(',');for(var iSel=0;iSel<arrSelectors.length;iSel++){this.addRule(arrSelectors[iSel],arrRules[1]);}}}};Zapatec.ImagePreloader=function(objArgs){this.job=null;this.image=null;if(arguments.length>0)this.init(objArgs);};Zapatec.ImagePreloader.prototype.init=function(objArgs){if(!objArgs||!objArgs.job){return;}
this.job=objArgs.job;this.image=new Image();this.job.images.push(this.image);var objPreloader=this;this.image.onload=function(){objPreloader.job.loadedUrls.push(objArgs.url);setTimeout(function(){objPreloader.onLoad();},0);};this.image.onerror=function(){objPreloader.job.invalidUrls.push(objArgs.url);objPreloader.onLoad();};this.image.onabort=function(){objPreloader.job.abortedUrls.push(objArgs.url);objPreloader.onLoad();};this.image.src=objArgs.url;if(typeof objArgs.timeout=='number'){setTimeout(function(){if(objPreloader.job){if(objPreloader.image.complete){objPreloader.job.loadedUrls.push(objArgs.url);}else{objPreloader.job.abortedUrls.push(objArgs.url);}
objPreloader.onLoad();}},objArgs.timeout);}};Zapatec.ImagePreloader.prototype.onLoad=function(){if(!this.job){return;}
this.image.onload=null;this.image.onerror=null;this.image.onabort=null;var objJob=this.job;this.job=null;objJob.leftToLoad--;if(objJob.leftToLoad==0&&typeof objJob.onLoad=='function'){var funcOnLoad=objJob.onLoad;objJob.onLoad=null;funcOnLoad(objJob);}};Zapatec.PreloadImages=function(objArgs){this.images=[];this.leftToLoad=0;this.loadedUrls=[];this.invalidUrls=[];this.abortedUrls=[];this.onLoad=null;if(arguments.length>0)this.init(objArgs);};Zapatec.PreloadImages.prototype.init=function(objArgs){if(!objArgs){return;}
if(!objArgs.urls||!objArgs.urls.length){if(typeof objArgs.onLoad=='function'){objArgs.onLoad(this);}
return;}
this.images=[];this.leftToLoad=objArgs.urls.length;this.loadedUrls=[];this.invalidUrls=[];this.abortedUrls=[];this.onLoad=objArgs.onLoad;for(var iUrl=0;iUrl<objArgs.urls.length;iUrl++){new Zapatec.ImagePreloader({job:this,url:objArgs.urls[iUrl],timeout:objArgs.timeout});}};if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.EventDriven=function(){};Zapatec.EventDriven.prototype.init=function(){this.events={};};Zapatec.EventDriven.prototype.addEventListener=function(sEvent,fListener){if(typeof fListener!="function"){return false;}
if(!this.events[sEvent]){this.events[sEvent]={listeners:[]};}else{this.removeEventListener(sEvent,fListener);}
this.events[sEvent].listeners.push(fListener);};Zapatec.EventDriven.prototype.unshiftEventListener=function(sEvent,fListener){if(typeof fListener!="function"){return false;}
if(!this.events[sEvent]){this.events[sEvent]={listeners:[]};}else{this.removeEventListener(sEvent,fListener);}
this.events[sEvent].listeners.unshift(fListener);};Zapatec.EventDriven.prototype.removeEventListener=function(sEvent,fListener){if(!this.events[sEvent]){return 0;}
var aListeners=this.events[sEvent].listeners;var iRemoved=0;for(var iListener=aListeners.length-1;iListener>=0;iListener--){if(aListeners[iListener]==fListener){aListeners.splice(iListener,1);iRemoved++;}}
return iRemoved;};Zapatec.EventDriven.prototype.getEventListeners=function(sEvent){if(!this.events[sEvent]){return[];}
return this.events[sEvent].listeners;};Zapatec.EventDriven.prototype.isEventListener=function(sEvent,fListener){if(!this.events[sEvent]){return false;}
var aListeners=this.events[sEvent].listeners;for(var iListener=aListeners.length-1;iListener>=0;iListener--){if(aListeners[iListener]==fListener){return true;}}
return false;};Zapatec.EventDriven.prototype.isEvent=function(sEvent){if(this.events[sEvent]){return true;}
return false;};Zapatec.EventDriven.prototype.removeEvent=function(sEvent){if(this.events[sEvent]){var undef;this.events[sEvent]=undef;}};Zapatec.EventDriven.prototype.fireEvent=function(sEvent){if(!this.events[sEvent]){return;}
var aListeners=this.events[sEvent].listeners.slice();for(var iListener=0;iListener<aListeners.length;iListener++){var aArgs=[].slice.call(arguments,1);aListeners[iListener].apply(this,aArgs);}};Zapatec.EventDriven.events={};Zapatec.EventDriven.addEventListener=function(sEvent,fListener){if(typeof fListener!="function"){return false;}
if(!Zapatec.EventDriven.events[sEvent]){Zapatec.EventDriven.events[sEvent]={listeners:[]};}else{Zapatec.EventDriven.removeEventListener(sEvent,fListener);}
Zapatec.EventDriven.events[sEvent].listeners.push(fListener);};Zapatec.EventDriven.unshiftEventListener=function(sEvent,fListener){if(typeof fListener!="function"){return false;}
if(!Zapatec.EventDriven.events[sEvent]){Zapatec.EventDriven.events[sEvent]={listeners:[]};}else{Zapatec.EventDriven.removeEventListener(sEvent,fListener);}
Zapatec.EventDriven.events[sEvent].listeners.unshift(fListener);};Zapatec.EventDriven.removeEventListener=function(sEvent,fListener){if(!Zapatec.EventDriven.events[sEvent]){return 0;}
var aListeners=Zapatec.EventDriven.events[sEvent].listeners;var iRemoved=0;for(var iListener=aListeners.length-1;iListener>=0;iListener--){if(aListeners[iListener]==fListener){aListeners.splice(iListener,1);iRemoved++;}}
return iRemoved;};Zapatec.EventDriven.getEventListeners=function(sEvent){if(!Zapatec.EventDriven.events[sEvent]){return[];}
return Zapatec.EventDriven.events[sEvent].listeners;};Zapatec.EventDriven.isEventListener=function(sEvent,fListener){if(!Zapatec.EventDriven.events[sEvent]){return false;}
var aListeners=Zapatec.EventDriven.events[sEvent].listeners;for(var iListener=aListeners.length-1;iListener>=0;iListener--){if(aListeners[iListener]==fListener){return true;}}
return false;};Zapatec.EventDriven.isEvent=function(sEvent){if(Zapatec.EventDriven.events[sEvent]){return true;}
return false;};Zapatec.EventDriven.removeEvent=function(sEvent){if(Zapatec.EventDriven.events[sEvent]){var undef;Zapatec.EventDriven.events[sEvent]=undef;}};Zapatec.EventDriven.fireEvent=function(sEvent){if(!Zapatec.EventDriven.events[sEvent]){return;}
var aListeners=Zapatec.EventDriven.events[sEvent].listeners.slice();for(var iListener=0;iListener<aListeners.length;iListener++){var aArgs=[].slice.call(arguments,1);aListeners[iListener].apply(aListeners[iListener],aArgs);}};if(typeof Zapatec=='undefined'){Zapatec=function(){};}
Zapatec.Widget=function(oArg){this.config={};Zapatec.Widget.SUPERconstructor.call(this);this.init(oArg);};Zapatec.inherit(Zapatec.Widget,Zapatec.EventDriven);Zapatec.Widget.path=Zapatec.getPath('Zapatec.Widget');Zapatec.Widget.prototype.init=function(oArg){Zapatec.Widget.SUPERclass.init.call(this);if(typeof this.id=='undefined'){var iId=0;while(Zapatec.Widget.all[iId]){iId++;}
this.id=iId;Zapatec.Widget.all[iId]=this;}
this.configure(oArg);this.addUserEventListeners();this.addStandardEventListeners();this.loadTheme();};Zapatec.Widget.prototype.reconfigure=function(oArg){this.configure(oArg);this.loadTheme();};Zapatec.Widget.prototype.configure=function(oArg){this.defineConfigOption('theme','default');if(typeof this.constructor.path!='undefined'){this.defineConfigOption('themePath',this.constructor.path+'../themes/');}else{this.defineConfigOption('themePath','../themes/');}
this.defineConfigOption('asyncTheme',false);this.defineConfigOption('source');this.defineConfigOption('sourceType');this.defineConfigOption('callbackSource');this.defineConfigOption('asyncSource',true);this.defineConfigOption('reliableSource',true);this.defineConfigOption('eventListeners',{});if(oArg){for(var sOption in oArg){if(typeof this.config[sOption]!='undefined'){this.config[sOption]=oArg[sOption];}else{Zapatec.Log({description:"Unknown config option: "+sOption});}}}};Zapatec.Widget.prototype.getConfiguration=function(){return this.config;};Zapatec.Widget.all=[];Zapatec.Widget.getWidgetById=function(iId){return Zapatec.Widget.all[iId];};Zapatec.Widget.prototype.addCircularRef=function(oElement,sProperty){if(!this.widgetCircularRefs){this.widgetCircularRefs=[];}
this.widgetCircularRefs.push([oElement,sProperty]);};Zapatec.Widget.prototype.createProperty=function(oElement,sProperty,val){oElement[sProperty]=val;this.addCircularRef(oElement,sProperty);};Zapatec.Widget.prototype.removeCircularRefs=function(){if(!this.widgetCircularRefs){return;}
for(var iRef=this.widgetCircularRefs.length-1;iRef>=0;iRef--){var oRef=this.widgetCircularRefs[iRef];oRef[0][oRef[1]]=null;oRef[0]=null;}};Zapatec.Widget.prototype.discard=function(){Zapatec.Widget.all[this.id]=null;this.removeCircularRefs();};Zapatec.Widget.removeCircularRefs=function(){for(var iWidget=Zapatec.Widget.all.length-1;iWidget>=0;iWidget--){var oWidget=Zapatec.Widget.all[iWidget];if(oWidget){oWidget.removeCircularRefs();}}};Zapatec.Utils.addEvent(window,'unload',Zapatec.Widget.removeCircularRefs);Zapatec.Widget.prototype.defineConfigOption=function(sOption,val){if(typeof this.config[sOption]=='undefined'){if(typeof val=='undefined'){this.config[sOption]=null;}else{this.config[sOption]=val;}}};Zapatec.Widget.prototype.addUserEventListeners=function(){for(var sEvent in this.config.eventListeners){if(this.config.eventListeners.hasOwnProperty(sEvent)){this.addEventListener(sEvent,this.config.eventListeners[sEvent]);}}};Zapatec.Widget.prototype.addStandardEventListeners=function(){this.addEventListener('loadThemeError',Zapatec.Widget.loadThemeError);};Zapatec.Widget.loadThemeError=function(oError){var sDescription="Can't load theme.";if(oError&&oError.errorDescription){sDescription+=' '+oError.errorDescription;}
Zapatec.Log({description:sDescription});};Zapatec.Widget.prototype.loadTheme=function(){if(typeof this.config.theme=='string'&&this.config.theme.length){var iPos=this.config.theme.lastIndexOf('/');if(iPos>=0){iPos++;this.config.themePath=this.config.theme.substring(0,iPos);this.config.theme=this.config.theme.substring(iPos);}
iPos=this.config.theme.lastIndexOf('.');if(iPos>=0){this.config.theme=this.config.theme.substring(0,iPos);}
this.config.theme=this.config.theme.toLowerCase();}else{this.config.theme='';}
if(this.config.theme){this.fireEvent('loadThemeStart');this.themeLoaded=false;var oWidget=this;var sUrl=this.config.themePath+this.config.theme+'.css';Zapatec.Transport.loadCss({url:sUrl,async:this.config.asyncTheme,onLoad:function(){oWidget.fireEvent('loadThemeEnd');oWidget.themeLoaded=true;oWidget.hideLoader();},onError:function(oError){oWidget.fireEvent('loadThemeEnd');oWidget.fireEvent('loadThemeError',oError);oWidget.themeLoaded=true;oWidget.hideLoader();}});}}
Zapatec.Widget.prototype.getClassName=function(oArg){var aClassName=[];if(oArg&&oArg.prefix){aClassName.push(oArg.prefix);}
if(this.config.theme!=''){aClassName.push(this.config.theme.charAt(0).toUpperCase());aClassName.push(this.config.theme.substr(1));}
if(oArg&&oArg.suffix){aClassName.push(oArg.suffix);}
return aClassName.join('');};Zapatec.Widget.prototype.formElementId=function(oArg){var aId=[];if(oArg&&oArg.prefix){aId.push(oArg.prefix);}else{aId.push('zpWidget');}
aId.push(this.id);if(oArg&&oArg.suffix){aId.push(oArg.suffix);}else{aId.push('-');}
if(typeof this.widgetUniqueIdCounter=='undefined'){this.widgetUniqueIdCounter=0;}else{this.widgetUniqueIdCounter++;}
aId.push(this.widgetUniqueIdCounter);return aId.join('');};Zapatec.Widget.prototype.showLoader=function(message){if(this.container!=null&&this.config.theme&&!this.themeLoaded){if(!Zapatec.windowLoaded){var self=this;Zapatec.Utils.addEvent(window,"load",function(){self.showLoader(message)});return null;}
if(typeof(Zapatec.Indicator)=='undefined'){var self=this;Zapatec.Transport.loadJS({module:'indicator',onLoad:function(){if(self.themeLoaded){return null;}
self.showLoader(message);}});return null;}
this.loader=new Zapatec.Indicator({container:this.container,themePath:Zapatec.zapatecPath+"../zpextra/themes/indicator/"});this.loader.start(message||'loading');this.container.style.visibility='hidden';}}
Zapatec.Widget.prototype.hideLoader=function(){if(this.loader&&this.loader.isActive()){this.container.style.visibility='';this.loader.stop();}}
Zapatec.Widget.prototype.showContainer=function(effects,animSpeed,onFinish){return this.showHideContainer(effects,animSpeed,onFinish,true);}
Zapatec.Widget.prototype.hideContainer=function(effects,animSpeed,onFinish){return this.showHideContainer(effects,animSpeed,onFinish,false);}
Zapatec.Widget.prototype.showHideContainer=function(effects,animSpeed,onFinish,show){if(this.container==null){return null;}
if(effects&&effects.length>0&&typeof(Zapatec.Effects)=='undefined'){var self=this;Zapatec.Transport.loadJS({url:Zapatec.zapatecPath+'../zpeffects/src/effects.js',onLoad:function(){self.showHideContainer(effects,animSpeed,onFinish,show);}});return false;}
if(animSpeed==null&&isNaN(parseInt(animSpeed))){animSpeed=5;}
if(!effects||effects.length==0){if(show){this.container.style.display=this.originalContainerDisplay;this.originalContainerDisplay=null;}else{this.originalContainerDisplay=this.container.style.display;this.container.style.display='none';}
if(onFinish){onFinish();}}else{if(show){Zapatec.Effects.show(this.container,animSpeed,effects,onFinish);}else{Zapatec.Effects.hide(this.container,animSpeed,effects,onFinish);}}
return true;}
Zapatec.Widget.prototype.loadData=function(oArg){if(typeof this.config.callbackSource=='function'){var oSource=this.config.callbackSource(oArg);if(oSource){if(typeof oSource.source!='undefined'){this.config.source=oSource.source;}
if(typeof oSource.sourceType!='undefined'){this.config.sourceType=oSource.sourceType;}}}
if(this.config.source!=null&&this.config.sourceType!=null){var sSourceType=this.config.sourceType.toLowerCase();if(sSourceType=='html'){this.fireEvent('loadDataStart');this.loadDataHtml(Zapatec.Widget.getElementById(this.config.source));this.fireEvent('loadDataEnd');}else if(sSourceType=='html/text'){this.fireEvent('loadDataStart');this.loadDataHtmlText(this.config.source);this.fireEvent('loadDataEnd');}else if(sSourceType=='html/url'){this.fireEvent('fetchSourceStart');var oWidget=this;Zapatec.Transport.fetch({url:this.config.source,async:this.config.asyncSource,onLoad:function(oRequest){oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataStart');oWidget.loadDataHtmlText(oRequest.responseText);oWidget.fireEvent('loadDataEnd');},onError:function(oError){oWidget.fireEvent('fetchSourceError',oError);oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataEnd');}});}else if(sSourceType=='json'){this.fireEvent('loadDataStart');if(typeof this.config.source=='object'){this.loadDataJson(this.config.source);}else if(this.config.reliableSource){this.loadDataJson(eval('('+this.config.source+')'));}else{this.loadDataJson(Zapatec.Transport.parseJson({strJson:this.config.source}));}
this.fireEvent('loadDataEnd');}else if(sSourceType=='json/url'){this.fireEvent('fetchSourceStart');var oWidget=this;Zapatec.Transport.fetchJsonObj({url:this.config.source,async:this.config.asyncSource,reliable:this.config.reliableSource,onLoad:function(oResult){oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataStart');oWidget.loadDataJson(oResult);oWidget.fireEvent('loadDataEnd');},onError:function(oError){oWidget.fireEvent('fetchSourceError',oError);oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataEnd');}});}else if(sSourceType=='xml'){this.fireEvent('loadDataStart');if(typeof this.config.source=='object'){this.loadDataXml(this.config.source);}else{this.loadDataXml(Zapatec.Transport.parseXml({strXml:this.config.source}));}
this.fireEvent('loadDataEnd');}else if(sSourceType=='xml/url'){this.fireEvent('fetchSourceStart');var oWidget=this;Zapatec.Transport.fetchXmlDoc({url:this.config.source,async:this.config.asyncSource,onLoad:function(oResult){oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataStart');oWidget.loadDataXml(oResult);oWidget.fireEvent('loadDataEnd');},onError:function(oError){oWidget.fireEvent('fetchSourceError',oError);oWidget.fireEvent('fetchSourceEnd');oWidget.fireEvent('loadDataEnd');}});}}else{this.fireEvent('loadDataStart');this.loadDataHtml(Zapatec.Widget.getElementById(this.config.source));this.fireEvent('loadDataEnd');}};Zapatec.Widget.prototype.loadDataHtml=function(oSource){};Zapatec.Widget.prototype.loadDataHtmlText=function(sSource){var oTempContainer=Zapatec.Transport.parseHtml(sSource);this.loadDataHtml(oTempContainer.firstChild);};Zapatec.Widget.prototype.loadDataJson=function(oSource){};Zapatec.Widget.prototype.loadDataXml=function(oSource){};Zapatec.Widget.prototype.editData=function(oArg){this.fireEvent('editData',oArg);};Zapatec.Widget.prototype.editDataGet=function(){return null;};Zapatec.Widget.prototype.editDataCancel=function(){this.fireEvent('editDataCancel');if(typeof this.hide=='function'){this.hide();}};Zapatec.Widget.prototype.editDataReturn=function(oArg){this.fireEvent('editDataReturn',oArg);if(!oArg.widget||typeof oArg.widget.editDataReceive!='function'){return;}
oArg.widget.editDataReceive({data:this.editDataGet()});this.editDataCancel();};Zapatec.Widget.prototype.editDataReceive=function(oArg){this.fireEvent('editDataReceive',oArg);};Zapatec.Widget.callMethod=function(iWidgetId,sMethod){var oWidget=Zapatec.Widget.getWidgetById(iWidgetId);if(oWidget&&typeof oWidget[sMethod]=='function'){var aArgs=[].slice.call(arguments,2);return oWidget[sMethod].apply(oWidget,aArgs);}};Zapatec.Widget.getElementById=function(element){if(typeof element=='string'){return document.getElementById(element);}
return element;};Zapatec.Widget.getStyle=function(element){var style=element.getAttribute('style')||'';if(typeof style=='string'){return style;}
return style.cssText;};Zapatec.Drag={};Zapatec.Utils.emulateWindowEvent(['mousedown','mousemove','mouseup']);Zapatec.Drag.currentId=null;Zapatec.Drag.start=function(oEv,sId,oArg){if(Zapatec.Drag.currentId){return true;}
var oEl=document.getElementById(sId);if(!oEl||oEl.zpDrag){return true;}
if(!oArg){oArg={};}
var oPos=Zapatec.Utils.getMousePos(oEv||window.event);Zapatec.EventDriven.fireEvent('dragStart',{id:sId});oEl.zpDrag=true;oEl.zpDragPageX=oPos.pageX;oEl.zpDragPageY=oPos.pageY;if(oEl.offsetParent){var oPos=Zapatec.Utils.getElementOffset(oEl);var oPosParent=Zapatec.Utils.getElementOffset(oEl.offsetParent);oEl.zpDragLeft=oPos.left-oPosParent.left;oEl.zpDragTop=oPos.top-oPosParent.top;}else{oEl.zpDragLeft=oEl.offsetLeft;oEl.zpDragTop=oEl.offsetTop;}
oEl.zpDragPrevLeft=oEl.zpDragLeft;oEl.zpDragPrevTop=oEl.zpDragTop;oEl.zpDragV=oArg.vertical;oEl.zpDragH=oArg.horizontal;oEl.zpDragLimTop=typeof oArg.limitTop=='number'?oArg.limitTop:-Infinity;oEl.zpDragLimBot=typeof oArg.limitBottom=='number'?oArg.limitBottom:Infinity;oEl.zpDragLimLft=typeof oArg.limitLeft=='number'?oArg.limitLeft:-Infinity;oEl.zpDragLimRgh=typeof oArg.limitRight=='number'?oArg.limitRight:Infinity;Zapatec.Drag.currentId=sId;Zapatec.Utils.addEvent(document,'mousemove',Zapatec.Drag.move);Zapatec.Utils.addEvent(document,'mouseup',Zapatec.Drag.end);return true;};Zapatec.Drag.move=function(oEv){oEv||(oEv=window.event);if(!Zapatec.Drag.currentId){return Zapatec.Utils.stopEvent(oEv);}
var oEl=document.getElementById(Zapatec.Drag.currentId);if(!(oEl&&oEl.zpDrag)){return Zapatec.Utils.stopEvent(oEv);}
var oPos=Zapatec.Utils.getMousePos(oEv);var oOffset={id:Zapatec.Drag.currentId,startLeft:oEl.zpDragLeft,startTop:oEl.zpDragTop,prevLeft:oEl.zpDragPrevLeft,prevTop:oEl.zpDragPrevTop,left:0,top:0};if(!oEl.zpDragV){var iLeft=oEl.zpDragLeft+oPos.pageX-oEl.zpDragPageX;if(oEl.zpDragLimLft<=iLeft&&oEl.zpDragLimRgh>=iLeft){oEl.style.right='';oEl.style.left=iLeft+'px';oOffset.left=iLeft;oEl.zpDragPrevLeft=iLeft;}else{oOffset.left=oOffset.prevLeft;}}
if(!oEl.zpDragH){var iTop=oEl.zpDragTop+oPos.pageY-oEl.zpDragPageY;if(oEl.zpDragLimTop<=iTop&&oEl.zpDragLimBot>=iTop){oEl.style.bottom='';oEl.style.top=iTop+'px';oOffset.top=iTop;oEl.zpDragPrevTop=iTop;}else{oOffset.top=oOffset.prevTop;}}
Zapatec.EventDriven.fireEvent('dragMove',oOffset);return Zapatec.Utils.stopEvent(oEv);};Zapatec.Drag.end=function(oEv){oEv||(oEv=window.event);if(!Zapatec.Drag.currentId){return Zapatec.Utils.stopEvent(oEv);}
var oEl=document.getElementById(Zapatec.Drag.currentId);if(!(oEl&&oEl.zpDrag)){return Zapatec.Utils.stopEvent(oEv);}
Zapatec.Utils.removeEvent(document,'mousemove',Zapatec.Drag.move);Zapatec.Utils.removeEvent(document,'mouseup',Zapatec.Drag.end);var oOffset={id:Zapatec.Drag.currentId,startLeft:oEl.zpDragLeft,startTop:oEl.zpDragTop,left:oEl.zpDragPrevLeft,top:oEl.zpDragPrevTop};Zapatec.Drag.currentId=null;oEl.zpDrag=null;oEl.zpDragPageX=null;oEl.zpDragPageY=null;oEl.zpDragLeft=null;oEl.zpDragTop=null;oEl.zpDragPrevLeft=null;oEl.zpDragPrevTop=null;oEl.zpDragV=null;oEl.zpDragH=null;oEl.zpDragLimTop=null;oEl.zpDragLimBot=null;oEl.zpDragLimLft=null;oEl.zpDragLimRgh=null;Zapatec.EventDriven.fireEvent('dragEnd',oOffset);return Zapatec.Utils.stopEvent(oEv);};


//ZAPATEC JS END////////////////////////////////////////////////////////////////////////


 ////ZAPATEC CALENDER's CALENDER JS START///////////////////////////////////////////////////////////////////////


    if (!window.Zapatec || (Zapatec && !Zapatec.include)) {
        alert("You need to include zapatec.js file!");
    } else {
        Zapatec.calendarPath = Zapatec.getPath("Zapatec.CalendarWidget");
    }
    window.calendar = null;
    Zapatec.Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {this.bShowHistoryEvent = false;this.activeDiv = null;this.currentDateEl = null;this.getDateStatus = null;this.getDateToolTip = null;this.getDateText = null;this.timeout = null;this.onSelected = onSelected || null;this.onClose = onClose || null;this.onFDOW = null;this.dragging = false;this.hidden = false;this.minYear = 1970;this.maxYear = 2050;this.minMonth = 0;this.maxMonth = 11;this.dateFormat = Zapatec.Calendar.i18n("DEF_DATE_FORMAT");this.ttDateFormat = Zapatec.Calendar.i18n("TT_DATE_FORMAT");this.historyDateFormat = "%B %d, %Y";this.isPopup = true;this.weekNumbers = true;this.noGrab = false;if (Zapatec.Calendar.prefs.fdow || (Zapatec.Calendar.prefs.fdow == 0)) {this.firstDayOfWeek = parseInt(Zapatec.Calendar.prefs.fdow, 10);} else {var fd = 0;if (typeof firstDayOfWeek == "number") {fd = firstDayOfWeek;} else if (typeof Zapatec.Calendar._FD == "number") {fd = Zapatec.Calendar._FD;}this.firstDayOfWeek = fd;}this.showsOtherMonths = false;this.dateStr = dateStr;this.showsTime = false;this.sortOrder = "asc";this.time24 = true;this.timeInterval = null;this.yearStep = 2;this.hiliteToday = true;this.multiple = null;this.table = null;this.element = null;this.tbody = new Array;this.firstdayname = null;this.monthsCombo = null;this.hilitedMonth = null;this.activeMonth = null;this.yearsCombo = null;this.hilitedYear = null;this.activeYear = null;this.histCombo = null;this.hilitedHist = null;this.dateClicked = false;this.numberMonths = 1;this.controlMonth = 1;this.vertical = false;this.monthsInRow = 1;this.titles = new Array;this.rowsOfDayNames = new Array;this.helpButton = true;this.disableFdowClick = true;this.disableDrag = false;this.yearNav = true;this.closeButton = true;Zapatec.Calendar._initSDN();};
    Zapatec.Calendar._initSDN = function () {if (typeof Zapatec.Calendar._TT._SDN == "undefined") {if (typeof Zapatec.Calendar._TT._SDN_len == "undefined") {Zapatec.Calendar._TT._SDN_len = 3;}var ar = [];for (var i = 8; i > 0;) {ar[--i] = Zapatec.Calendar._TT._DN[i].substr(0, Zapatec.Calendar._TT._SDN_len);}Zapatec.Calendar._TT._SDN = ar;if (typeof Zapatec.Calendar._TT._SMN_len == "undefined") {Zapatec.Calendar._TT._SMN_len = 3;}ar = [];for (var i = 12; i > 0;) {ar[--i] = Zapatec.Calendar._TT._MN[i].substr(0, Zapatec.Calendar._TT._SMN_len);}Zapatec.Calendar._TT._SMN = ar;}if (typeof Zapatec.Calendar._TT._AMPM == "undefined") {Zapatec.Calendar._TT._AMPM = {am: "am", pm: "pm"};}};
    Zapatec.Calendar.i18n = function (str, type) {var tr = "";if (!type) {if (Zapatec.Calendar._TT) {tr = Zapatec.Calendar._TT[str];}if (!tr && Zapatec.Calendar._TT_en) {tr = Zapatec.Calendar._TT_en[str];}} else {switch (type) {case "dn":tr = Zapatec.Calendar._TT._DN[str];break;case "sdn":tr = Zapatec.Calendar._TT._SDN[str];break;case "mn":tr = Zapatec.Calendar._TT._MN[str];break;case "smn":tr = Zapatec.Calendar._TT._SMN[str];break;case "ampm":tr = Zapatec.Calendar._TT._AMPM[str];break;default:;}}if (!tr) {tr = "" + str;}return tr;};
    Zapatec.Calendar._C = null;
    Zapatec.Calendar.prefs = {fdow: null, history: "", sortOrder: "asc", hsize: 9};
    Zapatec.Calendar.savePrefs = function () {Zapatec.Utils.writeCookie("ZP_CAL", Zapatec.Utils.makePref(this.prefs), null, "/", 30);};
    Zapatec.Calendar.loadPrefs = function () {var txt = Zapatec.Utils.getCookie("ZP_CAL"), tmp;if (txt) {tmp = Zapatec.Utils.loadPref(txt);if (tmp) {Zapatec.Utils.mergeObjects(this.prefs, tmp);}}};
    Zapatec.Calendar._add_evs = function (el) {var C = Zapatec.Calendar;Zapatec.Utils.addEvent(el, "mouseover", C.dayMouseOver);Zapatec.Utils.addEvent(el, "mousedown", C.dayMouseDown);Zapatec.Utils.addEvent(el, "mouseout", C.dayMouseOut);if (Zapatec.is_ie) {Zapatec.Utils.addEvent(el, "dblclick", C.dayMouseDblClick);}};
    Zapatec.Calendar._del_evs = function (el) {var C = this;Zapatec.Utils.removeEvent(el, "mouseover", C.dayMouseOver);Zapatec.Utils.removeEvent(el, "mousedown", C.dayMouseDown);Zapatec.Utils.removeEvent(el, "mouseout", C.dayMouseOut);if (Zapatec.is_ie) {Zapatec.Utils.removeEvent(el, "dblclick", C.dayMouseDblClick);}};
    Zapatec.Calendar.findMonth = function (el) {if (typeof el.month != "undefined") {return el;} else if (el.parentNode && typeof el.parentNode.month != "undefined") {return el.parentNode;}return null;};
    Zapatec.Calendar.findHist = function (el) {if (typeof el.histDate != "undefined") {return el;} else if (el.parentNode && typeof el.parentNode.histDate != "undefined") {return el.parentNode;}return null;};
    Zapatec.Calendar.findYear = function (el) {if (typeof el.year != "undefined") {return el;} else if (el.parentNode && typeof el.parentNode.year != "undefined") {return el.parentNode;}return null;};
    Zapatec.Calendar.showMonthsCombo = function () {var cal = Zapatec.Calendar._C;if (!cal) {return false;}var cd = cal.activeDiv;var mc = cal.monthsCombo;var date = cal.date, MM = cal.date.getMonth(), YY = cal.date.getFullYear(), min = YY == cal.minYear, max = YY == cal.maxYear;for (var i = mc.firstChild; i; i = i.nextSibling) {var m = i.month;Zapatec.Utils.removeClass(i, "hilite");Zapatec.Utils.removeClass(i, "active");Zapatec.Utils.removeClass(i, "disabled");i.disabled = false;if (min && m < cal.minMonth || (max && m > cal.maxMonth)) {Zapatec.Utils.addClass(i, "disabled");i.disabled = true;}if (m == MM) {Zapatec.Utils.addClass(cal.activeMonth = i, "active");}}var s = mc.style;s.display = "block";if (cd.navtype < 0) {s.left = cd.offsetLeft + "px";} else {var mcw = mc.offsetWidth;if (typeof mcw == "undefined") {mcw = 50;}s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";cal.updateWCH(mc);};
    Zapatec.Calendar.showHistoryCombo = function () {var cal = Zapatec.Calendar._C, a, h, i, cd, hc, s, tmp, div;if (!cal) {return false;}hc = cal.histCombo;while (hc.firstChild) {hc.removeChild(hc.lastChild);}if (Zapatec.Calendar.prefs.history) {a = Zapatec.Calendar.prefs.history.split(/,/);i = 0;while (tmp = a[i++]) {tmp = tmp.split(/\//);h = Zapatec.Utils.createElement("div");h.className = Zapatec.is_ie ? "label-IEfix" : "label";h.histDate = new Date(parseInt(tmp[0], 10), parseInt(tmp[1], 10) - 1, parseInt(tmp[2], 10), tmp[3] ? parseInt(tmp[3], 10) : 0, tmp[4] ? parseInt(tmp[4], 10) : 0);h.appendChild(window.document.createTextNode(h.histDate.print(cal.historyDateFormat)));hc.appendChild(h);if (h.histDate.dateEqualsTo(cal.date)) {Zapatec.Utils.addClass(h, "active");}}}cd = cal.activeDiv;s = hc.style;s.display = "block";s.left = Math.floor(cd.offsetLeft + (cd.offsetWidth - hc.offsetWidth) / 2) + "px";s.top = (cd.offsetTop + cd.offsetHeight) + "px";cal.updateWCH(hc);cal.bEventShowHistory = true;};
    Zapatec.Calendar.showYearsCombo = function (fwd) {var cal = Zapatec.Calendar._C;if (!cal) {return false;}var cd = cal.activeDiv;var yc = cal.yearsCombo;if (cal.hilitedYear) {Zapatec.Utils.removeClass(cal.hilitedYear, "hilite");}if (cal.activeYear) {Zapatec.Utils.removeClass(cal.activeYear, "active");}cal.activeYear = null;var Y = cal.date.getFullYear() + (fwd ? 1 : -1);var yr = yc.firstChild;var show = false;for (var i = 12; i > 0; --i) {if (Y >= cal.minYear && Y <= cal.maxYear) {yr.firstChild.data = Y;yr.year = Y;yr.style.display = "block";show = true;} else {yr.style.display = "none";}yr = yr.nextSibling;Y += fwd ? cal.yearStep : - cal.yearStep;}if (show) {var s = yc.style;s.display = "block";if (cd.navtype < 0) {s.left = cd.offsetLeft + "px";} else {var ycw = yc.offsetWidth;if (typeof ycw == "undefined") {ycw = 50;}s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";}cal.updateWCH(yc);};
    Zapatec.Calendar.tableMouseUp = function (ev) {var cal = Zapatec.Calendar._C;if (!cal) {return false;}if (cal.timeout) {clearTimeout(cal.timeout);}var el = cal.activeDiv;if (!el) {return false;}var target = Zapatec.Utils.getTargetElement(ev);if (typeof el.navtype == "undefined") {while (target && !target.calendar) {target = target.parentNode;}}ev || (ev = window.event);Zapatec.Utils.removeClass(el, "active");if (target == el || target.parentNode == el) {Zapatec.Calendar.cellClick(el, ev);}var mon = Zapatec.Calendar.findMonth(target);var date = null;if (mon) {if (!mon.disabled) {date = new Date(cal.date);if (mon.month != date.getMonth()) {date.setMonth(mon.month);cal.setDate(date, true);cal.dateClicked = false;cal.callHandler();}}} else {var year = Zapatec.Calendar.findYear(target);if (year) {date = new Date(cal.date);if (year.year != date.getFullYear()) {date.setFullYear(year.year);cal.setDate(date, true);cal.dateClicked = false;cal.callHandler();}} else {var hist = Zapatec.Calendar.findHist(target);if (hist && !hist.histDate.dateEqualsTo(cal.date)) {date = new Date(hist.histDate);cal._init(cal.firstDayOfWeek, cal.date = date);cal.dateClicked = false;cal.callHandler();cal.updateHistory();}}}Zapatec.Utils.removeEvent(window.document, "mouseup", Zapatec.Calendar.tableMouseUp);Zapatec.Utils.removeEvent(window.document, "mouseover", Zapatec.Calendar.tableMouseOver);Zapatec.Utils.removeEvent(window.document, "mousemove", Zapatec.Calendar.tableMouseOver);cal._hideCombos();Zapatec.Calendar._C = null;return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.tableMouseOver = function (ev) {var cal = Zapatec.Calendar._C;if (!cal) {return;}var el = cal.activeDiv;var target = Zapatec.Utils.getTargetElement(ev);if (target == el || target.parentNode == el) {Zapatec.Utils.addClass(el, "hilite active");Zapatec.Utils.addClass(el.parentNode, "rowhilite");} else {if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 && !cal.histCombo || Math.abs(el.navtype) > 2))) {Zapatec.Utils.removeClass(el, "active");}Zapatec.Utils.removeClass(el, "hilite");Zapatec.Utils.removeClass(el.parentNode, "rowhilite");}ev || (ev = window.event);if (el.navtype == 50 && target != el) {var pos = Zapatec.Utils.getAbsolutePos(el);var w = el.offsetWidth;var x = ev.clientX;var dx;var decrease = true;if (x > pos.x + w) {dx = x - pos.x - w;decrease = false;} else {dx = pos.x - x;}if (dx < 0) {dx = 0;}var range = el._range;var current = el._current;var date = cal.currentDate;var pm = date.getHours() >= 12;var old = el.firstChild.data;var count = Math.floor(dx / 10) % range.length;for (var i = range.length; --i >= 0;) {if (range[i] == current) {break;}}while (count-- > 0) {if (decrease) {if (--i < 0) {i = range.length - 1;}} else if (++i >= range.length) {i = 0;}}if (cal.getDateStatus) {var minute = null;var hour = null;var new_date = new Date(date);if (el.className.indexOf("ampm", 0) != -1) {minute = date.getMinutes();if (old != range[i]) {hour = (range[i] == Zapatec.Calendar.i18n("pm", "ampm")) ? (date.getHours() == 0) ? 12 : date.getHours() + 12 : date.getHours() - 12;} else {hour = date.getHours();}new_date.setHours(hour);}if (el.className.indexOf("hour", 0) != -1) {minute = date.getMinutes();hour = (!cal.time24) ? pm ? (range[i] != 12) ? parseInt(range[i], 10) + 12 : 12 : (range[i] != 12) ? range[i] : 0 : range[i];new_date.setHours(hour);}if (el.className.indexOf("minute", 0) != -1) {hour = date.getHours();minute = range[i];new_date.setMinutes(minute);}}var status = false;if (cal.getDateStatus) {status = cal.getDateStatus(new_date, date.getFullYear(), date.getMonth(), date.getDate(), parseInt(hour, 10), parseInt(minute, 10));}if (status == false) {if (!(!cal.time24 && range[i] == Zapatec.Calendar.i18n("pm", "ampm") && hour > 23)) {el.firstChild.data = range[i];}}cal.onUpdateTime();}var mon = Zapatec.Calendar.findMonth(target);if (mon) {if (!mon.disabled) {if (mon.month != cal.date.getMonth()) {if (cal.hilitedMonth) {Zapatec.Utils.removeClass(cal.hilitedMonth, "hilite");}Zapatec.Utils.addClass(mon, "hilite");cal.hilitedMonth = mon;} else if (cal.hilitedMonth) {Zapatec.Utils.removeClass(cal.hilitedMonth, "hilite");}}} else {if (cal.hilitedMonth) {Zapatec.Utils.removeClass(cal.hilitedMonth, "hilite");}var year = Zapatec.Calendar.findYear(target);if (year) {if (year.year != cal.date.getFullYear()) {if (cal.hilitedYear) {Zapatec.Utils.removeClass(cal.hilitedYear, "hilite");}Zapatec.Utils.addClass(year, "hilite");cal.hilitedYear = year;} else if (cal.hilitedYear) {Zapatec.Utils.removeClass(cal.hilitedYear, "hilite");}} else {if (cal.hilitedYear) {Zapatec.Utils.removeClass(cal.hilitedYear, "hilite");}var hist = Zapatec.Calendar.findHist(target);if (hist) {if (!hist.histDate.dateEqualsTo(cal.date)) {if (cal.hilitedHist) {Zapatec.Utils.removeClass(cal.hilitedHist, "hilite");}Zapatec.Utils.addClass(hist, "hilite");cal.hilitedHist = hist;} else if (cal.hilitedHist) {Zapatec.Utils.removeClass(cal.hilitedHist, "hilite");}} else if (cal.hilitedHist) {Zapatec.Utils.removeClass(cal.hilitedHist, "hilite");}}}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.tableMouseDown = function (ev) {if (Zapatec.Utils.getTargetElement(ev) == Zapatec.Utils.getElement(ev)) {return Zapatec.Utils.stopEvent(ev);}};
    Zapatec.Calendar.calDragIt = function (ev) {ev || (ev = window.event);var cal = Zapatec.Calendar._C;if (!cal) {Zapatec.Calendar.calDragEnd();}if (!cal.disableDrag) {if (!(cal && cal.dragging)) {return false;}var posX = ev.clientX + window.document.body.scrollLeft;var posY = ev.clientY + window.document.body.scrollTop;cal.hideShowCovered();var st = cal.element.style, L = posX - cal.xOffs, T = posY - cal.yOffs;st.left = L + "px";st.top = T + "px";Zapatec.Utils.setupWCH(cal.WCH, L, T);}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.calDragEnd = function (ev) {var cal = Zapatec.Calendar._C;Zapatec.Utils.removeEvent(window.document, "mousemove", Zapatec.Calendar.calDragIt);Zapatec.Utils.removeEvent(window.document, "mouseover", Zapatec.Calendar.calDragIt);Zapatec.Utils.removeEvent(window.document, "mouseup", Zapatec.Calendar.calDragEnd);if (!cal) {return false;}cal.dragging = false;Zapatec.Calendar.tableMouseUp(ev);cal.hideShowCovered();};
    Zapatec.Calendar.dayMouseDown = function (ev) {var canDrag = true;var el = Zapatec.Utils.getElement(ev);if (el.className.indexOf("disabled") != -1 || el.className.indexOf("true") != -1) {return false;}var cal = el.calendar;while (!cal) {el = el.parentNode;cal = el.calendar;}cal.bEventShowHistory = false;cal.activeDiv = el;Zapatec.Calendar._C = cal;if (el.navtype != 300) {if (el.navtype == 50) {if (!(cal.timeInterval == null || cal.timeInterval < 60 && el.className.indexOf("hour", 0) != -1)) {canDrag = false;}el._current = el.firstChild.data;if (canDrag) {Zapatec.Utils.addEvent(window.document, "mousemove", Zapatec.Calendar.tableMouseOver);}} else {if ((el.navtype == 201 || el.navtype == 202) && cal.timeInterval > 30 && (el.timePart.className.indexOf("minute", 0) != -1)) {canDrag = false;}if (canDrag) {Zapatec.Utils.addEvent(window.document, Zapatec.is_ie5 ? "mousemove" : "mouseover", Zapatec.Calendar.tableMouseOver);}}if (canDrag) {Zapatec.Utils.addClass(el, "hilite active");}Zapatec.Utils.addEvent(window.document, "mouseup", Zapatec.Calendar.tableMouseUp);} else if (cal.isPopup) {cal._dragStart(ev);} else {Zapatec.Calendar._C = null;}if (el.navtype == -1 || el.navtype == 1) {if (cal.timeout) {clearTimeout(cal.timeout);}cal.timeout = setTimeout("Zapatec.Calendar.showMonthsCombo()", 250);} else if (el.navtype == -2 || el.navtype == 2) {if (cal.timeout) {clearTimeout(cal.timeout);}cal.timeout = setTimeout((el.navtype > 0) ? "Zapatec.Calendar.showYearsCombo(true)" : "Zapatec.Calendar.showYearsCombo(false)", 250);} else if (el.navtype == 0 && Zapatec.Calendar.prefs.history) {if (cal.timeout) {clearTimeout(cal.timeout);}cal.timeout = setTimeout("Zapatec.Calendar.showHistoryCombo()", 250);} else {cal.timeout = null;}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.dayMouseDblClick = function (ev) {Zapatec.Calendar.cellClick(Zapatec.Utils.getElement(ev), ev || window.event);if (Zapatec.is_ie) {window.document.selection.empty();}};
    Zapatec.Calendar.dayMouseOver = function (ev) {var el = Zapatec.Utils.getElement(ev), caldate = el.caldate;while (!el.calendar) {el = el.parentNode;caldate = el.caldate;}var cal = el.calendar;var cel = el.timePart;if (caldate) {caldate = new Date(caldate[0], caldate[1], caldate[2]);if (caldate.getDate() != el.caldate[2]) {caldate.setDate(el.caldate[2]);}}if (Zapatec.Utils.isRelated(el, ev) || Zapatec.Calendar._C || el.className.indexOf("disabled") != -1 || el.className.indexOf("true") != -1) {return false;}if (el.ttip) {if (el.ttip.substr(0, 1) == "_") {el.ttip = caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);}el.calendar.showHint(el.ttip);}if (el.navtype != 300) {if (!(cal.timeInterval == null || el.className.indexOf("ampm", 0) != -1 || cal.timeInterval < 60 && el.className.indexOf("hour", 0) != -1) && (el.navtype == 50)) {return Zapatec.Utils.stopEvent(ev);}if ((el.navtype == 201 || el.navtype == 202) && cal.timeInterval > 30 && (cel.className.indexOf("minute", 0) != -1)) {return Zapatec.Utils.stopEvent(ev);}Zapatec.Utils.addClass(el, "hilite");if (caldate) {Zapatec.Utils.addClass(el.parentNode, "rowhilite");}}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.dayMouseOut = function (ev) {var el = Zapatec.Utils.getElement(ev);while (!el.calendar) {el = el.parentNode;caldate = el.caldate;}if (Zapatec.Utils.isRelated(el, ev) || Zapatec.Calendar._C || el.className.indexOf("disabled") != -1 || el.className.indexOf("true") != -1) {return false;}Zapatec.Utils.removeClass(el, "hilite");if (el.caldate) {Zapatec.Utils.removeClass(el.parentNode, "rowhilite");}if (el.calendar) {el.calendar.showHint(Zapatec.Calendar.i18n("SEL_DATE"));}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.cellClick = function (el, ev) {var cal = el.calendar;var closing = false;var newdate = false;var date = null;while (!cal) {el = el.parentNode;cal = el.calendar;}if (el.className.indexOf("disabled") != -1 || el.className.indexOf("true") != -1) {return false;}if (typeof el.navtype == "undefined") {if (cal.currentDateEl) {Zapatec.Utils.removeClass(cal.currentDateEl, "selected");Zapatec.Utils.addClass(el, "selected");closing = cal.currentDateEl == el;if (!closing) {cal.currentDateEl = el;}}var tmpDate = new Date(el.caldate[0], el.caldate[1], el.caldate[2]);if (tmpDate.getDate() != el.caldate[2]) {tmpDate.setDate(el.caldate[2]);}cal.date.setDateOnly(tmpDate);cal.currentDate.setDateOnly(tmpDate);date = cal.date;cal.dateClicked = true;if (cal.multiple) {cal._toggleMultipleDate(new Date(date));}newdate = true;if (el.otherMonth) {cal._init(cal.firstDayOfWeek, date);}cal.onSetTime();} else {if (el.navtype == 200) {Zapatec.Utils.removeClass(el, "hilite");cal.callCloseHandler();return;}date = new Date(cal.date);if (el.navtype == 0 && !cal.bEventShowHistory) {date.setDateOnly(new Date);}cal.dateClicked = false;var year = date.getFullYear();var mon = date.getMonth();
function setMonth(m) {var day = date.getDate();var max = date.getMonthDays(m);if (day > max) {date.setDate(max);}date.setMonth(m);}

switch (el.navtype) {case 400:Zapatec.Utils.removeClass(el, "hilite");var text = Zapatec.Calendar.i18n("ABOUT");if (typeof text != "undefined") {text += cal.showsTime ? Zapatec.Calendar.i18n("ABOUT_TIME") : "";} else {text = "Help and about box text is not translated into this language.\nIf you know this language and you feel generous please update\nthe corresponding file in \"lang\" subdir to match calendar-en.js\nand send it back to <support@zapatec.com> to get it into the distribution  ;-)\n\nThank you!\nhttp://www.zapatec.com\n";}alert(text);return;case -2:if (year > cal.minYear) {date.setFullYear(year - 1);}break;case -1:if (mon > 0) {setMonth(mon - 1);} else if (year-- > cal.minYear) {date.setFullYear(year);setMonth(11);}break;case 1:if (mon < 11) {setMonth(mon + 1);} else if (year < cal.maxYear) {date.setFullYear(year + 1);setMonth(0);}break;case 2:if (year < cal.maxYear) {date.setFullYear(year + 1);}break;case 100:cal.setFirstDayOfWeek(el.fdow);Zapatec.Calendar.prefs.fdow = cal.firstDayOfWeek;Zapatec.Calendar.savePrefs();if (cal.onFDOW) {cal.onFDOW(cal.firstDayOfWeek);}return;case 50:var date = cal.currentDate;if (el.className.indexOf("ampm", 0) >= 0) {} else if (!(cal.timeInterval == null || cal.timeInterval < 60 && el.className.indexOf("hour", 0) != -1)) {break;}var range = el._range;var current = el.firstChild.data;var pm = date.getHours() >= 12;for (var i = range.length; --i >= 0;) {if (range[i] == current) {break;}}if (ev && ev.shiftKey) {if (--i < 0) {i = range.length - 1;}} else if (++i >= range.length) {i = 0;}if (cal.getDateStatus) {var minute = null;var hour = null;var new_date = new Date(date);if (el.className.indexOf("ampm", 0) != -1) {minute = date.getMinutes();hour = (range[i] == Zapatec.Calendar.i18n("pm", "ampm")) ? (date.getHours() == 12) ? date.getHours() : date.getHours() + 12 : date.getHours() - 12;if (cal.getDateStatus && cal.getDateStatus(new_date, date.getFullYear(), date.getMonth(), date.getDate(), parseInt(hour, 10), parseInt(minute, 10))) {var dirrect;if (range[i] == Zapatec.Calendar.i18n("pm", "ampm")) {dirrect = -5;} else {dirrect = 5;}hours = hour;minutes = minute;do {minutes += dirrect;if (minutes >= 60) {minutes -= 60;++hours;if (hours >= 24) {hours -= 24;}new_date.setHours(hours);}if (minutes < 0) {minutes += 60;--hours;if (hours < 0) {hours += 24;}new_date.setHours(hours);}new_date.setMinutes(minutes);if (!cal.getDateStatus(new_date, date.getFullYear(), date.getMonth(), date.getDate(), parseInt(hours, 10), parseInt(minutes, 10))) {hour = hours;minute = minutes;if (hour > 12) {i = 1;} else {i = 0;}cal.date.setHours(hour);cal.date.setMinutes(minute);cal.onSetTime();}} while (hour != hours || (minute != minutes));}new_date.setHours(hour);}if (el.className.indexOf("hour", 0) != -1) {minute = date.getMinutes();hour = (!cal.time24) ? pm ? (range[i] != 12) ? parseInt(range[i], 10) + 12 : 12 : (range[i] != 12) ? range[i] : 0 : range[i];new_date.setHours(hour);}if (el.className.indexOf("minute", 0) != -1) {hour = date.getHours();minute = range[i];new_date.setMinutes(minute);}}var status = false;if (cal.getDateStatus) {status = cal.getDateStatus(new_date, date.getFullYear(), date.getMonth(), date.getDate(), parseInt(hour, 10), parseInt(minute, 10));}if (!status) {el.firstChild.data = range[i];}cal.onUpdateTime();return;case 201:case 202:var cel = el.timePart;var date = cal.currentDate;if (cel.className.indexOf("minute", 0) != -1 && (cal.timeInterval > 30)) {break;}var val = parseInt(cel.firstChild.data, 10);var pm = date.getHours() >= 12;var range = cel._range;for (var i = range.length; --i >= 0;) {if (val == range[i]) {val = i;break;}}var step = cel._step;if (el.navtype == 201) {val = step * Math.floor(val / step);val += step;if (val >= range.length) {val = 0;}} else {val = step * Math.ceil(val / step);val -= step;if (val < 0) {val = range.length - step;}}if (cal.getDateStatus) {var minute = null;var hour = null;var new_date = new Date(date);if (cel.className == "hour") {minute = date.getMinutes();hour = (!cal.time24) ? pm ? (range[val] != 12) ? parseInt(range[val], 10) + 12 : 12 : (range[val] != 12) ? range[val] : 0 : range[val];new_date.setHours(hour);}if (cel.className == "minute") {hour = date.getHours();minute = val;new_date.setMinutes(range[val]);}}var status = false;if (cal.getDateStatus) {status = cal.getDateStatus(new_date, date.getFullYear(), date.getMonth(), date.getDate(), parseInt(hour, 10), parseInt(minute, 10));}if (!status) {cel.firstChild.data = range[val];}cal.onUpdateTime();return;case 0:if (cal.getDateStatus && (cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate()) == true || cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate()) == "disabled")) {return false;}break;default:;}if (!date.equalsTo(cal.date)) {if ((el.navtype >= -2 && el.navtype <= 2) && (el.navtype != 0)) {cal._init(cal.firstDayOfWeek, date, true);return;}cal.setDate(date);newdate = !(el.navtype && (el.navtype >= -2 && el.navtype <= 2));}}if (newdate) {cal.callHandler();}if (closing) {Zapatec.Utils.removeClass(el, "hilite");cal.callCloseHandler();}};
    Zapatec.Calendar.prototype.create = function (_par) {var parent = null;if (!_par) {parent = window.document.getElementsByTagName("body")[0];this.isPopup = true;this.WCH = Zapatec.Utils.createWCH();} else {parent = _par;this.isPopup = false;}this.currentDate = this.date = this.dateStr ? new Date(this.dateStr) : new Date;var table = Zapatec.Utils.createElement("table");this.table = table;table.cellSpacing = 0;table.cellPadding = 0;Zapatec.Utils.createProperty(table, "calendar", this);Zapatec.Utils.addEvent(table, "mousedown", Zapatec.Calendar.tableMouseDown);var div = Zapatec.Utils.createElement("div");this.element = div;div.className = "calendar";if (Zapatec.is_opera) {table.style.width = (this.monthsInRow * (this.weekNumbers ? 8 : 7) * 2 + 4.4 * this.monthsInRow) + "em";}if (this.isPopup) {div.style.position = "absolute";div.style.display = "none";}div.appendChild(table);var cell = null;var row = null;var cal = this;var hh = function (text, cs, navtype) {cell = Zapatec.Utils.createElement("td", row);cell.colSpan = cs;cell.className = "button";if (Math.abs(navtype) <= 2) {cell.className += " nav";}Zapatec.Calendar._add_evs(cell);Zapatec.Utils.createProperty(cell, "calendar", cal);cell.navtype = navtype;if (text.substr(0, 1) != "&") {cell.appendChild(document.createTextNode(text));} else {cell.innerHTML = text;}return cell;};var hd = function (par, colspan) {cell = Zapatec.Utils.createElement("td", par);cell.colSpan = colspan;cell.className = "button";cell.innerHTML = "<div>&nbsp</div>";return cell;};var title_length = (this.weekNumbers ? 8 : 7) * this.monthsInRow - 2;var thead = Zapatec.Utils.createElement("thead", table);if (this.numberMonths == 1) {this.title = thead;}row = Zapatec.Utils.createElement("tr", thead);if (this.helpButton) {hh("?", 1, 400).ttip = Zapatec.Calendar.i18n("INFO");} else {hd(row, 1);}this.title = hh("&nbsp;", title_length, 300);this.title.className = "title";if (this.isPopup) {if (!this.disableDrag) {this.title.ttip = Zapatec.Calendar.i18n("DRAG_TO_MOVE");this.title.style.cursor = "move";}if (this.closeButton) {hh("&#x00d7;", 1, 200).ttip = Zapatec.Calendar.i18n("CLOSE");} else {hd(row, 1);}} else {hd(row, 1);}row = Zapatec.Utils.createElement("tr", thead);this._nav_py = hh("&#x00ab;", 1, -2);this._nav_py.ttip = Zapatec.Calendar.i18n("PREV_YEAR");this._nav_pm = hh("&#x2039;", 1, -1);this._nav_pm.ttip = Zapatec.Calendar.i18n("PREV_MONTH");this._nav_now = hh(Zapatec.Calendar.i18n("TODAY"), title_length - 2, 0);this._nav_now.ttip = Zapatec.Calendar.i18n("GO_TODAY");this._nav_nm = hh("&#x203a;", 1, 1);this._nav_nm.ttip = Zapatec.Calendar.i18n("NEXT_MONTH");this._nav_ny = hh("&#x00bb;", 1, 2);this._nav_ny.ttip = Zapatec.Calendar.i18n("NEXT_YEAR");var rowsOfMonths = Math.floor(this.numberMonths / this.monthsInRow);if (this.numberMonths % this.monthsInRow > 0) {++rowsOfMonths;}for (var l = 1; l <= rowsOfMonths; ++l) {var thead = Zapatec.Utils.createElement("thead", table);if (Zapatec.is_opera) {thead.style.display = "table-row-group";}if (this.numberMonths != 1) {row = Zapatec.Utils.createElement("tr", thead);var title_length = 5;this.weekNumbers && ++title_length;this.titles[l] = new Array;for (var k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {hd(row, 1);this.titles[l][k] = hh("&nbsp;", title_length, 300);this.titles[l][k].className = "title";hd(row, 1);}}row = Zapatec.Utils.createElement("tr", thead);row.className = "daynames";for (k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {if (this.weekNumbers) {cell = Zapatec.Utils.createElement("td", row);cell.className = "name wn";cell.appendChild(window.document.createTextNode(Zapatec.Calendar.i18n("WK")));if (k > 1) {Zapatec.Utils.addClass(cell, "month-left-border");}var cal_wk = Zapatec.Calendar.i18n("WK");if (cal_wk == null) {cal_wk = "";}}for (var i = 7; i > 0; --i) {cell = Zapatec.Utils.createElement("td", row);cell.appendChild(document.createTextNode("&nbsp;"));}}this.firstdayname = row.childNodes[this.weekNumbers ? 1 : 0];this.rowsOfDayNames[l] = this.firstdayname;this._displayWeekdays();var tbody = Zapatec.Utils.createElement("tbody", table);this.tbody[l] = tbody;for (i = 6; i > 0; --i) {row = Zapatec.Utils.createElement("tr", tbody);for (k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {if (this.weekNumbers) {cell = Zapatec.Utils.createElement("td", row);cell.appendChild(document.createTextNode("&nbsp;"));}for (var j = 7; j > 0; --j) {cell = Zapatec.Utils.createElement("td", row);cell.appendChild(document.createTextNode("&nbsp;"));Zapatec.Utils.createProperty(cell, "calendar", this);Zapatec.Calendar._add_evs(cell);}}}}var tfoot = Zapatec.Utils.createElement("tfoot", table);if (this.showsTime) {row = Zapatec.Utils.createElement("tr", tfoot);row.className = "time";var emptyColspan;if (this.monthsInRow != 1) {cell = Zapatec.Utils.createElement("td", row);emptyColspan = cell.colSpan = Math.ceil(((this.weekNumbers ? 8 : 7) * (this.monthsInRow - 1)) / 2);cell.className = "timetext";cell.innerHTML = "&nbsp";}cell = Zapatec.Utils.createElement("td", row);cell.className = "timetext";cell.colSpan = this.weekNumbers ? 2 : 1;cell.innerHTML = Zapatec.Calendar.i18n("TIME") || "&nbsp;";(function () {
function makeTimePart(className, init, range_start, range_end) {var table, tbody, tr, tr2, part;if (range_end) {cell = Zapatec.Utils.createElement("td", row);cell.colSpan = 1;if (cal.showsTime != "seconds") {++cell.colSpan;}cell.className = "parent-" + className;table = Zapatec.Utils.createElement("table", cell);table.cellSpacing = table.cellPadding = 0;if (className == "hour") {table.align = "right";}table.className = "calendar-time-scroller";tbody = Zapatec.Utils.createElement("tbody", table);tr = Zapatec.Utils.createElement("tr", tbody);tr2 = Zapatec.Utils.createElement("tr", tbody);} else {tr = row;}part = Zapatec.Utils.createElement("td", tr);part.className = className;part.appendChild(window.document.createTextNode(init));Zapatec.Utils.createProperty(part, "calendar", cal);part.ttip = Zapatec.Calendar.i18n("TIME_PART");part.navtype = 50;part._range = [];if (!range_end) {part._range = range_start;} else {part.rowSpan = 2;for (var i = range_start; i <= range_end; ++i) {var txt;if (i < 10 && range_end >= 10) {txt = "0" + i;} else {txt = "" + i;}part._range[part._range.length] = txt;}var up = Zapatec.Utils.createElement("td", tr);up.className = "up";up.navtype = 201;Zapatec.Utils.createProperty(up, "calendar", cal);up.timePart = part;if (Zapatec.is_khtml) {up.innerHTML = "&nbsp;";}Zapatec.Calendar._add_evs(up);var down = Zapatec.Utils.createElement("td", tr2);down.className = "down";down.navtype = 202;Zapatec.Utils.createProperty(down, "calendar", cal);down.timePart = part;if (Zapatec.is_khtml) {down.innerHTML = "&nbsp;";}Zapatec.Calendar._add_evs(down);}Zapatec.Calendar._add_evs(part);return part;}

var hrs = cal.currentDate.getHours();var mins = cal.currentDate.getMinutes();if (cal.showsTime == "seconds") {var secs = cal.currentDate.getSeconds();}var t12 = !cal.time24;var pm = hrs > 12;if (t12 && pm) {hrs -= 12;}var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);H._step = (cal.timeInterval > 30) ? cal.timeInterval / 60 : 1;cell = Zapatec.Utils.createElement("td", row);cell.innerHTML = ":";cell.className = "colon";var M = makeTimePart("minute", mins, 0, 59);M._step = (cal.timeInterval && cal.timeInterval < 60) ? cal.timeInterval : 5;if (cal.showsTime == "seconds") {cell = Zapatec.Utils.createElement("td", row);cell.innerHTML = ":";cell.className = "colon";var S = makeTimePart("minute", secs, 0, 59);S._step = 5;}var AP = null;if (t12) {AP = makeTimePart("ampm", pm ? Zapatec.Calendar.i18n("pm", "ampm") : Zapatec.Calendar.i18n("am", "ampm"), [Zapatec.Calendar.i18n("am", "ampm"), Zapatec.Calendar.i18n("pm", "ampm")]);AP.className += " button";} else {Zapatec.Utils.createElement("td", row).innerHTML = "&nbsp;";}cal.onSetTime = function () {var hrs = this.currentDate.getHours();var mins = this.currentDate.getMinutes();if (this.showsTime == "seconds") {var secs = cal.currentDate.getSeconds();}if (this.timeInterval) {mins += this.timeInterval - (mins - 1 + this.timeInterval) % this.timeInterval - 1;}while (mins >= 60) {mins -= 60;++hrs;}if (this.timeInterval > 60) {var interval = this.timeInterval / 60;if (hrs % interval != 0) {hrs += interval - (hrs - 1 + interval) % interval - 1;}if (hrs >= 24) {hrs -= 24;}}var new_date = new Date(this.currentDate);if (this.getDateStatus && this.getDateStatus(this.currentDate, this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate(), hrs, mins)) {hours = hrs;minutes = mins;do {if (this.timeInterval) {if (this.timeInterval < 60) {minutes += this.timeInterval;} else {hrs += this.timeInterval / 60;}} else {minutes += 5;}if (minutes >= 60) {minutes -= 60;hours += 1;}if (hours >= 24) {hours -= 24;}new_date.setMinutes(minutes);new_date.setHours(hours);if (!this.getDateStatus(new_date, this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate(), hours, minutes)) {hrs = hours;mins = minutes;}} while (hrs != hours || (mins != minutes));}this.currentDate.setMinutes(mins);this.currentDate.setHours(hrs);var pm = hrs >= 12;if (pm && t12 && hrs != 12) {hrs -= 12;}if (!pm && t12 && hrs == 0) {hrs = 12;}H.firstChild.data = (hrs < 10) ? "0" + hrs : hrs;M.firstChild.data = (mins < 10) ? "0" + mins : mins;if (this.showsTime == "seconds") {S.firstChild.data = (secs < 10) ? "0" + secs : secs;}if (t12) {AP.firstChild.data = pm ? Zapatec.Calendar.i18n("pm", "ampm") : Zapatec.Calendar.i18n("am", "ampm");}};cal.onUpdateTime = function () {var date = this.currentDate;var h = parseInt(H.firstChild.data, 10);if (t12) {if (/pm/i.test(AP.firstChild.data) && h < 12) {h += 12;} else if (/am/i.test(AP.firstChild.data) && h == 12) {h = 0;}}var d = date.getDate();var m = date.getMonth();var y = date.getFullYear();date.setHours(h);date.setMinutes(parseInt(M.firstChild.data, 10));if (this.showsTime == "seconds") {date.setSeconds(parseInt(S.firstChild.data, 10));}date.setFullYear(y);date.setMonth(m);date.setDate(d);this.dateClicked = false;this.callHandler();};}());if (this.monthsInRow != 1) {cell = Zapatec.Utils.createElement("td", row);cell.colSpan = (this.weekNumbers ? 8 : 7) * (this.monthsInRow - 1) - Math.ceil(emptyColspan);cell.className = "timetext";cell.innerHTML = "&nbsp";}} else {this.onSetTime = this.onUpdateTime = function () {};}row = Zapatec.Utils.createElement("tr", tfoot);row.className = "footrow";cell = hh(Zapatec.Calendar.i18n("SEL_DATE"), this.weekNumbers ? 8 * this.numberMonths : 7 * this.numberMonths, 300);cell.className = "ttip";if (this.isPopup && !this.disableDrag) {cell.ttip = Zapatec.Calendar.i18n("DRAG_TO_MOVE");cell.style.cursor = "move";}this.tooltips = cell;div = this.monthsCombo = Zapatec.Utils.createElement("div", this.element);div.className = "combo";for (i = 0; i < 12; ++i) {var mn = Zapatec.Utils.createElement("div");mn.className = Zapatec.is_ie ? "label-IEfix" : "label";mn.month = i;mn.appendChild(window.document.createTextNode(Zapatec.Calendar.i18n(i, "smn")));div.appendChild(mn);}div = this.yearsCombo = Zapatec.Utils.createElement("div", this.element);div.className = "combo";for (i = 12; i > 0; --i) {var yr = Zapatec.Utils.createElement("div");yr.className = Zapatec.is_ie ? "label-IEfix" : "label";yr.appendChild(window.document.createTextNode("&nbsp;"));div.appendChild(yr);}div = this.histCombo = Zapatec.Utils.createElement("div", this.element);div.className = "combo history";this._init(this.firstDayOfWeek, this.date);parent.appendChild(this.element);};
    Zapatec.Calendar._keyEvent = function (ev) {if (!window.calendar) {return false;}Zapatec.is_ie && (ev = window.event);var cal = window.calendar;var act = Zapatec.is_ie || ev.type == "keypress";var K = ev.keyCode;var date = new Date(cal.date);if (ev.ctrlKey) {switch (K) {case 37:act && Zapatec.Calendar.cellClick(cal._nav_pm);break;case 38:act && Zapatec.Calendar.cellClick(cal._nav_py);break;case 39:act && Zapatec.Calendar.cellClick(cal._nav_nm);break;case 40:act && Zapatec.Calendar.cellClick(cal._nav_ny);break;default:return false;}} else {switch (K) {case 32:Zapatec.Calendar.cellClick(cal._nav_now);break;case 27:act && cal.callCloseHandler();break;case 37:if (act && !cal.multiple) {date.setTime(date.getTime() - 86400000);cal.setDate(date);}break;case 38:if (act && !cal.multiple) {date.setTime(date.getTime() - 604800000);cal.setDate(date);}break;case 39:if (act && !cal.multiple) {date.setTime(date.getTime() + 86400000);cal.setDate(date);}break;case 40:if (act && !cal.multiple) {date.setTime(date.getTime() + 604800000);cal.setDate(date);}break;case 13:if (act) {Zapatec.Calendar.cellClick(cal.currentDateEl);}break;default:return false;}}return Zapatec.Utils.stopEvent(ev);};
    Zapatec.Calendar.prototype._init = function (firstDayOfWeek, date, last) {var today = new Date, TD = today.getDate(), TY = today.getFullYear(), TM = today.getMonth();if (this.getDateStatus && !last) {var status = this.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate());var backupDate = new Date(date);while ((status == true || status == "disabled") && (backupDate.getMonth() == date.getMonth())) {date.setTime(date.getTime() + 86400000);var status = this.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate());}if (backupDate.getMonth() != date.getMonth()) {date = new Date(backupDate);while ((status == true || status == "disabled") && (backupDate.getMonth() == date.getMonth())) {date.setTime(date.getTime() - 86400000);var status = this.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate());}}if (backupDate.getMonth() != date.getMonth()) {last = true;date = new Date(backupDate);}}var year = date.getFullYear();var month = date.getMonth();var rowsOfMonths = Math.floor(this.numberMonths / this.monthsInRow);var minMonth;var diffMonth, last_row, before_control;if (!this.vertical) {diffMonth = this.controlMonth - 1;minMonth = month - diffMonth;} else {last_row = ((this.numberMonths - 1) % this.monthsInRow) + 1;before_control = (this.controlMonth - 1) % this.monthsInRow;bottom = before_control >= last_row ? last_row : before_control;diffMonth = before_control * (rowsOfMonths - 1) + Math.floor((this.controlMonth - 1) / this.monthsInRow) + bottom;minMonth = month - diffMonth;}var minYear = year;if (minMonth < 0) {minMonth += 12;--minYear;}var maxMonth = minMonth + this.numberMonths - 1;var maxYear = minYear;if (maxMonth > 11) {maxMonth -= 12;++maxYear;}
function disableControl(ctrl) {Zapatec.Calendar._del_evs(ctrl);ctrl.disabled = true;ctrl.className = "button";ctrl.innerHTML = "<div>&nbsp</div>";}


function enableControl(ctrl, sign) {Zapatec.Calendar._add_evs(ctrl);ctrl.disabled = false;ctrl.className = "button nav";ctrl.innerHTML = sign;}

if (minYear <= this.minYear || !this.yearNav) {if (!this._nav_py.disabled) {disableControl(this._nav_py);}} else {if (this._nav_py.disabled) {enableControl(this._nav_py, "&#x00ab;");}}if (maxYear >= this.maxYear || !this.yearNav) {if (!this._nav_ny.disabled) {disableControl(this._nav_ny);}} else {if (this._nav_ny.disabled) {enableControl(this._nav_ny, "&#x00bb;");}}if (minYear == this.minYear && minMonth <= this.minMonth || (minYear < this.minYear)) {if (!this._nav_pm.disabled) {disableControl(this._nav_pm);}} else {if (this._nav_pm.disabled) {enableControl(this._nav_pm, "&#x2039;");}}if (maxYear == this.maxYear && maxMonth >= this.maxMonth || (maxYear > this.maxYear)) {if (!this._nav_nm.disabled) {disableControl(this._nav_nm);}} else {if (this._nav_nm.disabled) {enableControl(this._nav_nm, "&#x203a;");}}upperMonth = this.maxMonth + 1;upperYear = this.maxYear;if (upperMonth > 11) {upperMonth -= 12;++upperYear;}bottomMonth = this.minMonth - 1;bottomYear = this.minYear;if (bottomMonth < 0) {bottomMonth += 12;--bottomYear;}maxDate1 = new Date(maxYear, maxMonth, date.getMonthDays(maxMonth), 23, 59, 59, 999);maxDate2 = new Date(upperYear, upperMonth, 1, 0, 0, 0, 0);minDate1 = new Date(minYear, minMonth, 1, 0, 0, 0, 0);minDate2 = new Date(bottomYear, bottomMonth, date.getMonthDays(bottomMonth), 23, 59, 59, 999);if (maxDate1.getTime() > maxDate2.getTime()) {date.setTime(date.getTime() - (maxDate1.getTime() - maxDate2.getTime()));}if (minDate1.getTime() < minDate2.getTime()) {date.setTime(date.getTime() + (minDate2.getTime() - minDate1.getTime()) + 1);}delete maxDate1;delete maxDate2;delete minDate1;delete minDate2;this.firstDayOfWeek = firstDayOfWeek;if (!last) {this.currentDate = date;}this.date = date;(this.date = new Date(this.date)).setDateOnly(date);year = this.date.getFullYear();month = this.date.getMonth();var initMonth = date.getMonth();var mday = this.date.getDate();var no_days = date.getMonthDays();var months = new Array;if (this.numberMonths % this.monthsInRow > 0) {++rowsOfMonths;}for (var l = 1; l <= rowsOfMonths; ++l) {months[l] = new Array;for (var k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {var tmpDate = new Date(date);if (this.vertical) {var validMonth = date.getMonth() - diffMonth + ((k - 1) * (rowsOfMonths - 1) + (l - 1) + ((last_row < k) ? last_row : k - 1));} else {var validMonth = date.getMonth() - diffMonth + (l - 1) * this.monthsInRow + k - 1;}if (validMonth < 0) {tmpDate.setFullYear(tmpDate.getFullYear() - 1);validMonth = 12 + validMonth;}if (validMonth > 11) {tmpDate.setFullYear(tmpDate.getFullYear() + 1);validMonth = validMonth - 12;}tmpDate.setDate(1);tmpDate.setMonth(validMonth);var day1 = (tmpDate.getDay() - this.firstDayOfWeek) % 7;if (day1 < 0) {day1 += 7;}var hrs = tmpDate.getHours();tmpDate.setDate(- day1);tmpDate.setDate(tmpDate.getDate() + 1);if (hrs != tmpDate.getHours()) {tmpDate.setDate(1);tmpDate.setMonth(validMonth);tmpDate.setDate(- day1);tmpDate.setDate(tmpDate.getDate() + 1);}months[l][k] = tmpDate;}}var MN = Zapatec.Calendar.i18n(month, "smn");var weekend = Zapatec.Calendar.i18n("WEEKEND");var dates = this.multiple ? (this.datesCells = {}) : null;var DATETXT = this.getDateText;for (var l = 1; l <= rowsOfMonths; ++l) {var row = this.tbody[l].firstChild;for (var i = 7; --i > 0; row = row.nextSibling) {var cell = row.firstChild;var hasdays = false;for (var k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {date = months[l][k];if (this.weekNumbers) {cell.className = " day wn";cell.innerHTML = date.getWeekNumber();if (k > 1) {Zapatec.Utils.addClass(cell, "month-left-border");}cell = cell.nextSibling;}row.className = "daysrow";var iday;for (j = 7; cell && (iday = date.getDate()) && (j > 0); date.setDate(iday + 1), (date.getDate() == iday) ? date.setHours(1) && date.setDate(iday + 1) : false, cell = cell.nextSibling, --j) {var wday = date.getDay(), dmonth = date.getMonth(), dyear = date.getFullYear();cell.className = " day";if (!this.weekNumbers && j == 7 && (k != 1)) {Zapatec.Utils.addClass(cell, "month-left-border");}if (j == 1 && (k != this.monthsInRow)) {Zapatec.Utils.addClass(cell, "month-right-border");}if (this.vertical) {validMonth = initMonth - diffMonth + ((k - 1) * (rowsOfMonths - 1) + (l - 1) + ((last_row < k) ? last_row : k - 1));} else {validMonth = initMonth - diffMonth + ((l - 1) * this.monthsInRow + k - 1);}if (validMonth < 0) {validMonth = 12 + validMonth;}if (validMonth > 11) {validMonth = validMonth - 12;}var current_month = !(cell.otherMonth = !(dmonth == validMonth));if (!current_month) {if (this.showsOtherMonths) {cell.className += " othermonth";} else {cell.className += " true";cell.innerHTML = "<div>&nbsp;</div>";continue;}} else {hasdays = true;}cell.innerHTML = DATETXT ? DATETXT(date, dyear, dmonth, iday) : iday;dates && (dates[date.print("%Y%m%d")] = cell);if (this.getDateStatus) {var status = this.getDateStatus(date, dyear, dmonth, iday);if (this.getDateToolTip) {var toolTip = this.getDateToolTip(date, dyear, dmonth, iday);if (toolTip) {cell.title = toolTip;}}if (status == true) {cell.className += " disabled";} else {cell.className += " " + status;}}if (!cell.disabled) {cell.caldate = [dyear, dmonth, iday];cell.ttip = "_";if (!this.multiple && current_month && iday == this.currentDate.getDate() && this.hiliteToday && dmonth == this.currentDate.getMonth() && (dyear == this.currentDate.getFullYear())) {cell.className += " selected";this.currentDateEl = cell;}if (dyear == TY && dmonth == TM && iday == TD) {cell.className += " today";cell.ttip += Zapatec.Calendar.i18n("PART_TODAY");}if (weekend != null && (weekend.indexOf(wday.toString()) != -1)) {cell.className += cell.otherMonth ? " oweekend" : " weekend";}}}if (!(hasdays || this.showsOtherMonths)) {row.className = "emptyrow";}}if (i == 1 && (l < rowsOfMonths)) {if (row.className == "emptyrow") {row = row.previousSibling;}cell = row.firstChild;while (cell != null) {Zapatec.Utils.addClass(cell, "month-bottom-border");cell = cell.nextSibling;}}}}if (this.numberMonths == 1) {this.title.innerHTML = Zapatec.Calendar.i18n(month, "mn") + ", " + year;if (this.params && this.params.titleHtml) {if (typeof this.params.titleHtml == "function") {this.title.innerHTML = this.params.titleHtml(this.title.innerHTML, month, year);} else {this.title.innerHTML += this.params.titleHtml;}}} else {if (this.params && this.params.titleHtml) {if (typeof this.params.titleHtml == "function") {this.title.innerHTML = this.params.titleHtml(Zapatec.Calendar.i18n(month, "mn") + ", " + year, month, year);} else {this.title.innerHTML = this.params.titleHtml;}}for (var l = 1; l <= rowsOfMonths; ++l) {for (var k = 1; k <= this.monthsInRow && ((l - 1) * this.monthsInRow + k <= this.numberMonths); ++k) {if (this.vertical) {validMonth = month - diffMonth + ((k - 1) * (rowsOfMonths - 1) + (l - 1) + ((last_row < k) ? last_row : k - 1));} else {validMonth = month - diffMonth + (l - 1) * this.monthsInRow + k - 1;}validYear = year;if (validMonth < 0) {--validYear;validMonth = 12 + validMonth;}if (validMonth > 11) {++validYear;validMonth = validMonth - 12;}this.titles[l][k].innerHTML = Zapatec.Calendar.i18n(validMonth, "mn") + ", " + validYear;}}}this.onSetTime();this._initMultipleDates();this.updateWCH();};
    Zapatec.Calendar.prototype._initMultipleDates = function () {if (this.multiple) {for (var i in this.multiple) {var cell = this.datesCells[i];var d = this.multiple[i];if (!d) {continue;}if (cell) {cell.className += " selected";}}}};
    Zapatec.Calendar.prototype._toggleMultipleDate = function (date) {if (this.multiple) {var ds = date.print("%Y%m%d");var cell = this.datesCells[ds];if (cell) {var d = this.multiple[ds];if (!d) {Zapatec.Utils.addClass(cell, "selected");this.multiple[ds] = date;} else {Zapatec.Utils.removeClass(cell, "selected");delete this.multiple[ds];}}}};
    Zapatec.Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {this.getDateToolTip = unaryFunction;};
    Zapatec.Calendar.prototype.setDate = function (date, justInit) {if (!date) {date = new Date;}if (!date.equalsTo(this.date)) {var year = date.getFullYear(), m = date.getMonth();if (year < this.minYear || (year == this.minYear && m < this.minMonth)) {this.showHint("<div class='error'>" + Zapatec.Calendar.i18n("E_RANGE") + " \xBB\xBB\xBB</div>");} else if (year > this.maxYear || (year == this.maxYear && m > this.maxMonth)) {this.showHint("<div class='error'>\xAB\xAB\xAB " + Zapatec.Calendar.i18n("E_RANGE") + "</div>");}this._init(this.firstDayOfWeek, date, justInit);}};
    Zapatec.Calendar.prototype.showHint = function (text) {this.tooltips.innerHTML = text;};
    Zapatec.Calendar.prototype.reinit = function () {this._init(this.firstDayOfWeek, this.date);};
    Zapatec.Calendar.prototype.refresh = function () {var p = this.isPopup ? null : this.element.parentNode;var x = parseInt(this.element.style.left);var y = parseInt(this.element.style.top);this.destroy();this.dateStr = this.date;this.create(p);if (this.isPopup) {this.showAt(x, y);} else {this.show();}};
    Zapatec.Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {if (this.firstDayOfWeek != firstDayOfWeek) {this._init(firstDayOfWeek, this.date);var rowsOfMonths = Math.floor(this.numberMonths / this.monthsInRow);if (this.numberMonths % this.monthsInRow > 0) {++rowsOfMonths;}for (var l = 1; l <= rowsOfMonths; ++l) {this.firstdayname = this.rowsOfDayNames[l];this._displayWeekdays();}}};
    Zapatec.Calendar.prototype.setDateStatusHandler = Zapatec.Calendar.prototype.setDisabledHandler = function (unaryFunction) {this.getDateStatus = unaryFunction;};
    Zapatec.Calendar.prototype.setRange = function (A, Z) {var m, a = Math.min(A, Z), z = Math.max(A, Z);this.minYear = m = Math.floor(a);this.minMonth = (m == a) ? 0 : Math.ceil((a - m) * 100 - 1);this.maxYear = m = Math.floor(z);this.maxMonth = (m == z) ? 11 : Math.ceil((z - m) * 100 - 1);};
    Zapatec.Calendar.prototype.setMultipleDates = function (multiple) {if (!multiple || typeof multiple == "undefined") {return;}this.multiple = {};for (var i = multiple.length; --i >= 0;) {var d = multiple[i];var ds = d.print("%Y%m%d");this.multiple[ds] = d;}};
    Zapatec.Calendar.prototype.submitFlatDates = function () {if (typeof this.params.flatCallback == "function") {Zapatec.Utils.sortOrder = (this.sortOrder != "asc" && this.sortOrder != "desc" && this.sortOrder != "none") ? "none" : this.sortOrder;if (this.multiple && (Zapatec.Utils.sortOrder != "none")) {var dateArray = new Array;for (var i in this.multiple) {var currentDate = this.multiple[i];if (currentDate) {dateArray[dateArray.length] = currentDate;}dateArray.sort(Zapatec.Utils.compareDates);}this.multiple = {};for (var i = 0; i < dateArray.length; i++) {var d = dateArray[i];var ds = d.print("%Y%m%d");this.multiple[ds] = d;}}this.params.flatCallback(this);}};
    Zapatec.Calendar.prototype.callHandler = function () {if (this.onSelected) {this.onSelected(this, this.date.print(this.dateFormat));}};
    Zapatec.Calendar.prototype.updateHistory = function () {var a, i, d, tmp, s, str = "", len = Zapatec.Calendar.prefs.hsize - 1;if (Zapatec.Calendar.prefs.history) {a = Zapatec.Calendar.prefs.history.split(/,/);i = 0;while (i < len && (tmp = a[i++])) {s = tmp.split(/\//);d = new Date(parseInt(s[0], 10), parseInt(s[1], 10) - 1, parseInt(s[2], 10), parseInt(s[3], 10), parseInt(s[4], 10));if (!d.dateEqualsTo(this.date)) {str += "," + tmp;}}}Zapatec.Calendar.prefs.history = this.date.print("%Y/%m/%d/%H/%M") + str;Zapatec.Calendar.savePrefs();};
    Zapatec.Calendar.prototype.callCloseHandler = function () {if (this.dateClicked) {this.updateHistory();}if (this.onClose) {this.onClose(this);}this.hideShowCovered();};
    Zapatec.Calendar.prototype.destroy = function () {this.hide();Zapatec.Utils.destroy(this.element);Zapatec.Utils.destroy(this.WCH);Zapatec.Calendar._C = null;window.calendar = null;};
    Zapatec.Calendar.prototype.reparent = function (new_parent) {var el = this.element;el.parentNode.removeChild(el);new_parent.appendChild(el);};
    Zapatec.Calendar._checkCalendar = function (ev) {if (!window.calendar) {return false;}var el = Zapatec.is_ie ? Zapatec.Utils.getElement(ev) : Zapatec.Utils.getTargetElement(ev);for (; el != null && el != calendar.element; el = el.parentNode) {}if (el == null) {window.calendar.callCloseHandler();}};
    Zapatec.Calendar.prototype.updateWCH = function (other_el) {Zapatec.Utils.setupWCH_el(this.WCH, this.element, other_el);};
    Zapatec.Calendar.prototype.show = function () {var rows = this.table.getElementsByTagName("tr");for (var i = rows.length; i > 0;) {var row = rows[--i];Zapatec.Utils.removeClass(row, "rowhilite");var cells = row.getElementsByTagName("td");for (var j = cells.length; j > 0;) {var cell = cells[--j];Zapatec.Utils.removeClass(cell, "hilite");Zapatec.Utils.removeClass(cell, "active");}}if (this.element.style.display != "block") {this.element.style.display = "block";}this.hidden = false;if (this.isPopup) {this.updateWCH();window.calendar = this;if (!this.noGrab) {Zapatec.Utils.addEvent(window.document, "keydown", Zapatec.Calendar._keyEvent);Zapatec.Utils.addEvent(window.document, "keypress", Zapatec.Calendar._keyEvent);Zapatec.Utils.addEvent(window.document, "mousedown", Zapatec.Calendar._checkCalendar);}}this.hideShowCovered();};
    Zapatec.Calendar.prototype.hide = function () {if (this.isPopup) {Zapatec.Utils.removeEvent(window.document, "keydown", Zapatec.Calendar._keyEvent);Zapatec.Utils.removeEvent(window.document, "keypress", Zapatec.Calendar._keyEvent);Zapatec.Utils.removeEvent(window.document, "mousedown", Zapatec.Calendar._checkCalendar);}this.element.style.display = "none";Zapatec.Utils.hideWCH(this.WCH);this.hidden = true;this.hideShowCovered();};
    Zapatec.Calendar.prototype.showAt = function (x, y) {var s = this.element.style;s.left = x + "px";s.top = y + "px";this.show();};
    Zapatec.Calendar.prototype.showAtElement = function (el, opts) {var self = this;var p = Zapatec.Utils.getElementOffset(el);if (!opts || typeof opts != "string") {this.showAt(p.x, p.y + el.offsetHeight);return true;}this.element.style.display = "block";var w = self.element.offsetWidth;var h = self.element.offsetHeight;self.element.style.display = "none";var valign = opts.substr(0, 1);var halign = "l";if (opts.length > 1) {halign = opts.substr(1, 1);}switch (valign) {case "T":p.y -= h;break;case "B":p.y += el.offsetHeight;break;case "C":p.y += (el.offsetHeight - h) / 2;break;case "t":p.y += el.offsetHeight - h;break;case "b":break;default:;}switch (halign) {case "L":p.x -= w;break;case "R":p.x += el.offsetWidth;break;case "C":p.x += (el.offsetWidth - w) / 2;break;case "l":p.x += el.offsetWidth - w;break;case "r":break;default:;}p.width = w;p.height = h;self.monthsCombo.style.display = "none";Zapatec.Utils.fixBoxPosition(p, 10);self.showAt(p.x, p.y);};
    Zapatec.Calendar.prototype.setDateFormat = function (str) {this.dateFormat = str;};
    Zapatec.Calendar.prototype.setTtDateFormat = function (str) {this.ttDateFormat = str;};
    Zapatec.Calendar.prototype.parseDate = function (str, fmt) {if (!str) {return this.setDate(this.date);}if (!fmt) {fmt = this.dateFormat;}var date = Date.parseDate(str, fmt);return this.setDate(date);};
    Zapatec.Calendar.prototype.hideShowCovered = function () {if (!Zapatec.is_ie5) {return;}var self = this;
function getVisib(obj) {var value = obj.style.visibility;if (!value) {if (window.document.defaultView && typeof window.document.defaultView.getComputedStyle == "function") {if (!Zapatec.is_khtml) {value = window.document.defaultView.getComputedStyle(obj, "").getPropertyValue("visibility");} else {value = "";}} else if (obj.currentStyle) {value = obj.currentStyle.visibility;} else {value = "";}}return value;}

var tags = ["applet", "iframe", "select"];var el = self.element;var p = Zapatec.Utils.getAbsolutePos(el);var EX1 = p.x;var EX2 = el.offsetWidth + EX1;var EY1 = p.y;var EY2 = el.offsetHeight + EY1;for (var k = tags.length; k > 0;) {var ar = window.document.getElementsByTagName(tags[--k]);var cc = null;for (var i = ar.length; i > 0;) {cc = ar[--i];p = Zapatec.Utils.getAbsolutePos(cc);var CX1 = p.x;var CX2 = cc.offsetWidth + CX1;var CY1 = p.y;var CY2 = cc.offsetHeight + CY1;if (self.hidden || CX1 > EX2 || CX2 < EX1 || CY1 > EY2 || (CY2 < EY1)) {if (!cc.__msh_save_visibility) {cc.__msh_save_visibility = getVisib(cc);}cc.style.visibility = cc.__msh_save_visibility;} else {if (!cc.__msh_save_visibility) {cc.__msh_save_visibility = getVisib(cc);}cc.style.visibility = "hidden";}}}};
    Zapatec.Calendar.prototype._displayWeekdays = function () {var fdow = this.firstDayOfWeek;var cell = this.firstdayname;var weekend = Zapatec.Calendar.i18n("WEEKEND");for (k = 1; k <= this.monthsInRow && cell; ++k) {for (var i = 0; i < 7; ++i) {cell.className = " day name";if (!this.weekNumbers && i == 0 && (k != 1)) {Zapatec.Utils.addClass(cell, "month-left-border");}if (i == 6 && (k != this.monthsInRow)) {Zapatec.Utils.addClass(cell, "month-right-border");}var realday = (i + fdow) % 7;if (!this.disableFdowClick && (this.params && this.params.fdowClick || i)) {if (Zapatec.Calendar.i18n("DAY_FIRST") != null) {cell.ttip = Zapatec.Calendar.i18n("DAY_FIRST").replace("%s", Zapatec.Calendar.i18n(realday, "dn"));}cell.navtype = 100;cell.calendar = this;cell.fdow = realday;Zapatec.Calendar._add_evs(cell);}if (weekend != null && (weekend.indexOf(realday.toString()) != -1)) {Zapatec.Utils.addClass(cell, "weekend");}cell.innerHTML = Zapatec.Calendar.i18n((i + fdow) % 7, "sdn");cell = cell.nextSibling;}if (this.weekNumbers && cell) {cell = cell.nextSibling;}}};
    Zapatec.Utils.compareDates = function (date1, date2) {if (Zapatec.Calendar.prefs.sortOrder == "asc") {return date1 - date2;} else {return date2 - date1;}};
    Zapatec.Calendar.prototype._hideCombos = function () {this.monthsCombo.style.display = "none";this.yearsCombo.style.display = "none";this.histCombo.style.display = "none";this.updateWCH();};
    Zapatec.Calendar.prototype._dragStart = function (ev) {ev || (ev = window.event);if (this.dragging) {return;}this.dragging = true;var posX = ev.clientX + window.document.body.scrollLeft;var posY = ev.clientY + window.document.body.scrollTop;var st = this.element.style;this.xOffs = posX - parseInt(st.left);this.yOffs = posY - parseInt(st.top);Zapatec.Utils.addEvent(window.document, "mousemove", Zapatec.Calendar.calDragIt);Zapatec.Utils.addEvent(window.document, "mouseover", Zapatec.Calendar.calDragIt);Zapatec.Utils.addEvent(window.document, "mouseup", Zapatec.Calendar.calDragEnd);};
    Date._MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    Date.SECOND = 1000;
    Date.MINUTE = 60 * Date.SECOND;
    Date.HOUR = 60 * Date.MINUTE;
    Date.DAY = 24 * Date.HOUR;
    Date.WEEK = 7 * Date.DAY;
    Date.prototype.getMonthDays = function (month) {var year = this.getFullYear();if (typeof month == "undefined") {month = this.getMonth();}if ((0 == year % 4 && (0 != year % 100 || 0 == year % 400)) && month == 1) {return 29;} else {return Date._MD[month];}};
    Date.prototype.getDayOfYear = function () {var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);var time = now - then;return Math.round(time / Date.DAY);};
    Date.prototype.getWeekNumber = function () {var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);var DoW = d.getDay();d.setDate(d.getDate() - (DoW + 6) % 7 + 3);var ms = d.valueOf();d.setMonth(0);d.setDate(4);return Math.round((ms - d.valueOf()) / 604800000) + 1;};
    Date.prototype.equalsTo = function (date) {return this.getFullYear() == date.getFullYear() && this.getMonth() == date.getMonth() && this.getDate() == date.getDate() && this.getHours() == date.getHours() && this.getMinutes() == date.getMinutes();};
    Date.prototype.dateEqualsTo = function (date) {return this.getFullYear() == date.getFullYear() && this.getMonth() == date.getMonth() && this.getDate() == date.getDate();};
    Date.prototype.setDateOnly = function (date) {var tmp = new Date(date);this.setDate(1);this.setFullYear(tmp.getFullYear());this.setMonth(tmp.getMonth());this.setDate(tmp.getDate());};
    Date.prototype.print = function (str) {var m = this.getMonth();var d = this.getDate();var y = this.getFullYear();var wn = this.getWeekNumber();var w = this.getDay();var s = {};var hr = this.getHours();var pm = hr >= 12;var ir = pm ? hr - 12 : hr;var dy = this.getDayOfYear();if (ir == 0) {ir = 12;}var min = this.getMinutes();var sec = this.getSeconds();s['%a'] = Zapatec.Calendar.i18n(w, "sdn");s['%A'] = Zapatec.Calendar.i18n(w, "dn");s['%b'] = Zapatec.Calendar.i18n(m, "smn");s['%B'] = Zapatec.Calendar.i18n(m, "mn");s['%C'] = 1 + Math.floor(y / 100);s['%d'] = (d < 10) ? "0" + d : d;s['%e'] = d;s['%H'] = (hr < 10) ? "0" + hr : hr;s['%I'] = (ir < 10) ? "0" + ir : ir;s['%j'] = (dy < 100) ? (dy < 10) ? "00" + dy : "0" + dy : dy;s['%k'] = hr ? hr : "0";s['%l'] = ir;s['%m'] = (m < 9) ? "0" + (1 + m) : 1 + m;s['%M'] = (min < 10) ? "0" + min : min;s['%n'] = "\n";s['%p'] = pm ? "PM" : "AM";s['%P'] = pm ? "pm" : "am";s['%s'] = Math.floor(this.getTime() / 1000);s['%S'] = (sec < 10) ? "0" + sec : sec;s['%t'] = "\t";s['%U'] = s['%W'] = s['%V'] = (wn < 10) ? "0" + wn : wn;s['%u'] = (w == 0) ? 7 : w;s['%w'] = w ? w : "0";s['%y'] = "" + y % 100;if (s['%y'] < 10) {s['%y'] = "0" + s['%y'];}s['%Y'] = y;s['%%'] = "%";var re = /%./g;var a = str.match(re) || [];for (var i = 0; i < a.length; i++) {var tmp = s[a[i]];if (tmp) {re = new RegExp(a[i], "g");str = str.replace(re, tmp);}}return str;};
    Date.parseDate = function (str, format) {var fmt = format, strPointer = 0, token = null, parseFunc = null, valueLength = null, valueRange = null, valueType = null, date = new Date, values = {};var numberRules = ["%d", "%H", "%I", "%m", "%M", "%S", "%s", "%W", "%u", "%w", "%y", "%e", "%k", "%l", "%s", "%Y", "%C"];
function isNumberRule(rule) {if (Zapatec.Utils.arrIndexOf(numberRules, rule) != -1) {return true;}return false;}


function parseString() {for (var iString = valueRange[0]; iString < valueRange[1]; ++iString) {var value = Zapatec.Calendar.i18n(iString, valueType);if (!value) {return null;}if (value == str.substr(strPointer, value.length)) {valueLength = value.length;return iString;}}return null;}


function parseNumber() {var val = str.substr(strPointer, valueLength);if (val.length != valueLength || /$\d+^/.test(val)) {return null;}return parseInt(val, 10);}


function parseAMPM() {var result = (str.substr(strPointer, valueLength).toLowerCase() == Zapatec.Calendar.i18n("pm", "ampm")) ? true : false;return result || ((str.substr(strPointer, valueLength).toLowerCase() == Zapatec.Calendar.i18n("am", "ampm")) ? false : null);}


function parseCharacter() {return "";}


function parseRule(rule) {return values[rule] = parseFunc();}


function wasParsed(rule) {if (typeof rule == "undefined" || rule === null) {return false;}return true;}


function getValue() {for (var i = 0; i < arguments.length; ++i) {if (arguments[i] !== null && typeof arguments[i] != "undefined" && !isNaN(arguments[i])) {return arguments[i];}}return null;}

if (typeof fmt != "string" || typeof str != "string" || str == "" || fmt == "") {return null;}while (fmt) {parseFunc = parseNumber;valueLength = fmt.indexOf("%");valueLength = (valueLength == -1) ? fmt.length : valueLength;token = fmt.slice(0, valueLength);if (token != str.substr(strPointer, valueLength)) {return null;}strPointer += valueLength;fmt = fmt.slice(valueLength);if (fmt == "") {break;}token = fmt.slice(0, 2);valueLength = 2;switch (token) {case "%A":case "%a":valueType = (token == "%A") ? "dn" : "sdn";valueRange = [0, 7];parseFunc = parseString;break;case "%B":case "%b":valueType = (token == "%B") ? "mn" : "smn";valueRange = [0, 12];parseFunc = parseString;break;case "%p":case "%P":parseFunc = parseAMPM;break;case "%Y":valueLength = 4;if (isNumberRule(fmt.substr(2, 2))) {return null;}while (isNaN(parseInt(str.charAt(strPointer + valueLength - 1))) && valueLength > 0) {--valueLength;}if (valueLength == 0) {break;}break;case "%C":case "%s":valueLength = 1;if (isNumberRule(fmt.substr(2, 2))) {return null;}while (!isNaN(parseInt(str.charAt(strPointer + valueLength)))) {++valueLength;}break;case "%k":case "%l":case "%e":valueLength = 1;if (isNumberRule(fmt.substr(2, 2))) {return null;}if (!isNaN(parseInt(str.charAt(strPointer + 1)))) {++valueLength;}break;case "%j":valueLength = 3;break;case "%u":case "%w":valueLength = 1;case "%y":case "%m":case "%d":case "%W":case "%H":case "%I":case "%M":case "%S":break;default:;}if (parseRule(token) === null) {return null;}strPointer += valueLength;fmt = fmt.slice(2);}if (wasParsed(values['%s'])) {date.setTime(values['%s'] * 1000);} else {var year = getValue(values['%Y'], values['%y'] + --values['%C'] * 100, values['%y'] + (date.getFullYear() - date.getFullYear() % 100), values['%C'] * 100 + date.getFullYear() % 100);var month = getValue(values['%m'] - 1, values['%b'], values['%B']);var day = getValue(values['%d'] || values['%e']);if (day === null || month === null) {var dayOfWeek = getValue(values['%a'], values['%A'], values['%u'] == 7 ? 0 : values['%u'], values['%w']);}var hour = getValue(values['%H'], values['%k']);if (hour === null && (wasParsed(values['%p']) || wasParsed(values['%P']))) {var pm = getValue(values['%p'], values['%P']);hour = getValue(values['%I'], values['%l']);hour = pm ? (hour == 12) ? 12 : hour + 12 : (hour == 12) ? 0 : hour;}if (year || year === 0) {date.setFullYear(year);}if (month || month === 0) {date.setMonth(month);}if (day || day === 0) {date.setDate(day);}if (wasParsed(values['%j'])) {date.setMonth(0);date.setDate(1);date.setDate(values['%j']);}if (wasParsed(dayOfWeek)) {date.setDate(date.getDate() + (dayOfWeek - date.getDay()));}if (wasParsed(values['%W'])) {var weekNumber = date.getWeekNumber();if (weekNumber != values['%W']) {date.setDate(date.getDate() + (values['%W'] - weekNumber) * 7);}}if (hour !== null) {date.setHours(hour);}if (wasParsed(values['%M'])) {date.setMinutes(values['%M']);}if (wasParsed(values['%S'])) {date.setSeconds(values['%S']);}}if (date.print(format) != str) {return null;}return date;};
    Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
    Date.prototype.setFullYear = function (y) {var d = new Date(this);d.__msh_oldSetFullYear(y);if (d.getMonth() != this.getMonth()) {this.setDate(28);}this.__msh_oldSetFullYear(y);};
    Date.prototype.compareDatesOnly = function (date1, date2) {var year1 = date1.getYear();var year2 = date2.getYear();var month1 = date1.getMonth();var month2 = date2.getMonth();var day1 = date1.getDate();var day2 = date2.getDate();if (year1 > year2) {return -1;}if (year2 > year1) {return 1;}if (month1 > month2) {return -1;}if (month2 > month1) {return 1;}if (day1 > day2) {return -1;}if (day2 > day1) {return 1;}return 0;};
    Zapatec.Setup = function () {};
    Zapatec.Setup.test = true;
    Zapatec.Calendar.setup = function (params) {paramsList = ["id"];
function param_default(pname, def) {if (typeof params[pname] == "undefined") {params[pname] = def;}paramsList.push(pname);}

params.id = Zapatec.Utils.generateID("calendar");param_default("inputField", null);param_default("displayArea", null);param_default("button", null);param_default("eventName", "click");param_default("closeEventName", null);param_default("ifFormat", "%Y/%m/%d");param_default("daFormat", "%Y/%m/%d");param_default("singleClick", true);param_default("disableFunc", null);param_default("dateStatusFunc", params.disableFunc);param_default("dateText", null);param_default("firstDay", null);param_default("align", "Br");param_default("range", [1900, 2999]);param_default("weekNumbers", true);param_default("flat", null);param_default("flatCallback", null);param_default("onSelect", null);param_default("onClose", null);param_default("onUpdate", null);param_default("date", null);param_default("showsTime", false);param_default("sortOrder", "asc");param_default("timeFormat", "24");param_default("timeInterval", null);param_default("electric", true);param_default("step", 2);param_default("position", null);param_default("cache", false);param_default("showOthers", false);param_default("multiple", null);param_default("saveDate", null);param_default("fdowClick", false);param_default("titleHtml", null);param_default("noHelp", false);param_default("noCloseButton", false);param_default("disableYearNav", false);param_default("disableFdowChange", false);if (params.weekNumbers) {params.disableFdowChange = true;params.firstDay = 1;}param_default("disableDrag", false);param_default("numberMonths", 1);if (params.numberMonths > 12 || (params.numberMonths < 1)) {params.numberMonths = 1;}if (params.numberMonths > 1) {params.showOthers = false;}params.numberMonths = parseInt(params.numberMonths, 10);param_default("controlMonth", 1);if (params.controlMonth > params.numberMonths || (params.controlMonth < 1)) {params.controlMonth = 1;}params.controlMonth = parseInt(params.controlMonth, 10);param_default("vertical", false);if (params.monthsInRow > params.numberMonths) {params.monthsInRow = params.numberMonths;}param_default("monthsInRow", params.numberMonths);params.monthsInRow = parseInt(params.monthsInRow, 10);param_default("multiple", false);if (params.multiple) {params.singleClick = false;}param_default("canType", false);var tmp = ["inputField", "displayArea", "button"];for (var i in tmp) {if (typeof params[tmp[i]] == "string") {params[tmp[i]] = document.getElementById(params[tmp[i]]);}}if (!params.inputField) {params.canType = false;} else {params.inputField.setAttribute("autocomplete", "off");}if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {alert("Calendar.setup '" + params.id + "':\n  Nothing to setup (no fields found).  Please check your code");return false;}if (params.timeInterval && (params.timeInterval !== Math.floor(params.timeInterval) || 60 % params.timeInterval !== 0 && params.timeInterval % 60 !== 0) || (params.timeInterval > 360)) {alert("'" + params.id + "': timeInterval option can only have the following number of minutes:\n1, 2, 3, 4, 5, 6, 10, 15, 30,  60, 120, 180, 240, 300, 360 ");params.timeInterval = null;}if (params.date && !Date.parse(params.date)) {alert("'" + params.id + "' Start Date Invalid: " + params.date + ".\nSee date option.\nDefaulting to today.");params.date = null;}if (params.saveDate) {param_default("cookiePrefix", window.location.href + "--" + params.button.id);var cookieName = params.cookiePrefix;var newdate = Zapatec.Utils.getCookie(cookieName);if (newdate != null) {document.getElementById(params.inputField.id).value = newdate;}}for (var ii in params) {if (typeof params.constructor.prototype[ii] != "undefined") {continue;}if (Zapatec.Utils.arrIndexOf(paramsList, ii) == -1) {alert("Wrong config option: " + ii);}}
function onSelect(cal) {var p = cal.params;var update = cal.dateClicked || p.electric;if (update && p.flat) {if (typeof p.flatCallback == "function") {if (!p.multiple) {p.flatCallback(cal);}} else {alert("'" + cal.id + "': No flatCallback given -- doing nothing.");}return false;}if (update && p.inputField) {p.inputField.value = cal.currentDate.print(p.ifFormat);if (typeof p.inputField.onchange == "function") {p.inputField.onchange();}}if (update && p.displayArea) {p.displayArea.innerHTML = cal.currentDate.print(p.daFormat);}if (update && p.singleClick && cal.dateClicked) {cal.callCloseHandler();}if (update && typeof p.onUpdate == "function") {p.onUpdate(cal);}if (p.saveDate) {var cookieName = p.cookiePrefix;Zapatec.Utils.writeCookie(cookieName, p.inputField.value, null, "/", p.saveDate);}}

if (params.flat != null) {if (typeof params.flat == "string") {params.flat = document.getElementById(params.flat);}if (!params.flat) {alert("Calendar.setup '" + params.id + "':\n  Flat specified but can't find parent.");return false;}var cal = new (Zapatec.Calendar)(params.firstDay, params.date, params.onSelect || onSelect);cal.id = params.id;cal.disableFdowClick = params.disableFdowChange;cal.showsOtherMonths = params.showOthers;cal.showsTime = params.showsTime;cal.time24 = params.timeFormat == "24";cal.timeInterval = params.timeInterval;cal.params = params;cal.weekNumbers = params.weekNumbers;cal.sortOrder = params.sortOrder.toLowerCase();cal.setRange(params.range[0], params.range[1]);cal.setDateStatusHandler(params.dateStatusFunc);cal.getDateText = params.dateText;cal.numberMonths = params.numberMonths;cal.controlMonth = params.controlMonth;cal.vertical = params.vertical;cal.yearStep = params.step;cal.monthsInRow = params.monthsInRow;cal.helpButton = !params.noHelp;cal.closeButton = !params.noCloseButton;cal.yearNav = !params.disableYearNav;if (params.ifFormat) {cal.setDateFormat(params.ifFormat);}if (params.inputField && params.inputField.type == "text" && typeof params.inputField.value == "string") {cal.parseDate(params.inputField.value);}if (params.multiple) {cal.setMultipleDates(params.multiple);}cal.create(params.flat);cal.show();return cal;}var triggerEl = params.button || params.displayArea || params.inputField;if (params.canType) {
function cancelBubble(ev) {ev = ev || window.event;if (Zapatec.is_ie) {ev.cancelBubble = true;} else {ev.stopPropagation();}}

Zapatec.Utils.addEvent(params.inputField, "mousedown", cancelBubble);
Zapatec.Utils.addEvent(params.inputField, "keydown", cancelBubble);
Zapatec.Utils.addEvent(params.inputField, "keypress", cancelBubble);
Zapatec.Utils.addEvent(params.inputField, "keyup", function (ev) {var format = params.inputField ? params.ifFormat : params.daFormat;
var parsedDate = Date.parseDate(params.inputField.value, format);
var cal = window.calendar;
if (cal && parsedDate && !cal.hidden) {
cal.setDate(parsedDate);
}
});
}
triggerEl["on" + params.eventName] = function () {
			var dateEl = params.inputField || params.displayArea;
			if ((!params.canType || params.inputField != triggerEl) && triggerEl.blur) {
				triggerEl.blur();
				}
				var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
				var mustCreate = false;
				var cal = window.calendar;
				if (params.canType && params.inputField == triggerEl && cal && !cal.hidden) {
					return;
					}
			if (!(cal && params.cache)) {
				window.calendar = cal = new (Zapatec.Calendar)(params.firstDay, params.date, params.onSelect || onSelect, params.onClose || function (cal) {
					if (params.cache) {
						cal.hide();
						} else {
							cal.destroy();
							}
							}
							);
							cal.id = params.id;
							cal.disableFdowClick = params.disableFdowChange;
							cal.showsTime = params.showsTime;
							cal.time24 = params.timeFormat == "24";
							cal.timeInterval = params.timeInterval;
							cal.weekNumbers = params.weekNumbers;
							cal.numberMonths = params.numberMonths;
							cal.controlMonth = params.controlMonth;
							cal.vertical = params.vertical;
							cal.monthsInRow = params.monthsInRow;
							cal.historyDateFormat = params.ifFormat || params.daFormat;
							cal.helpButton = !params.noHelp;
							cal.disableDrag = params.disableDrag;
							cal.closeButton = !params.noCloseButton;
							cal.yearNav = !params.disableYearNav;
							cal.sortOrder = params.sortOrder.toLowerCase();
							mustCreate = true;
							} else {
								if (params.date) {
									cal.setDate(params.date);
									}
									cal.hide();
									}
									if (params.multiple) {
										cal.setMultipleDates(params.multiple);
										}
										cal.showsOtherMonths = params.showOthers;
										cal.yearStep = params.step;
										cal.setRange(params.range[0], params.range[1]);
										cal.params = params;
										cal.setDateStatusHandler(params.dateStatusFunc);
										cal.getDateText = params.dateText;
										cal.setDateFormat(dateFmt);
										if (mustCreate) {
					cal.create();
					}
					
					if (dateEl) {
						var dateValue;
						var value ;
						var html;
						var returnElemId=new String(dateEl.id);
						var subString1= returnElemId.slice(15,34);
						var subString2= returnElemId.slice(33,34);
					
						if(subString1=="returnFlight0" || subString1=="departFlight1"){	
							if(dateEl.value!="")
							value = dateEl.value;
							else
								value =document.getElementById("frm:searchForm:departFlight0").value;									
							}else 	if(subString1=="departFlight2"){			
								if(dateEl.value!="")
									value = dateEl.value;
								else
									value =document.getElementById("frm:searchForm:departFlight1").value;											
							}else 	if(subString1=="departFlight3"){			
								if(dateEl.value!="")
									value = dateEl.value;
								else
									value =document.getElementById("frm:searchForm:departFlight2").value;											
							}else 	if(subString1=="departFlight4"){		
								if(dateEl.value!="")
									value = dateEl.value;
								else
									value =document.getElementById("frm:searchForm:departFlight3").value;											
							}else 	if(subString1=="departFlight5"){		
								if(dateEl.value!="")
									value = dateEl.value;
								else
									value =document.getElementById("frm:searchForm:departFlight4").value;											
							}else {
								value = dateEl.value;
								}
							// added for hotel search page
							if(subString1==":toDate"){		
								if(dateEl.value!="")
									value = dateEl.value;
								else
									value =document.getElementById("frm:hotelSearch:fromDate").value;											
							}



						if(subString1=="returnFlight0" || subString1=="departFlight1"){		
							if(dateEl.innerHTML!="")
								html = dateEl.innerHTML;
							else
								html =document.getElementById("frm:searchForm:departFlight0").innerHTML;											
							}else 	if(subString1=="departFlight2"){	
								if(dateEl.innerHTML!="")
									html = dateEl.innerHTML;
								else
									html =document.getElementById("frm:searchForm:departFlight1").innerHTML;											
							}else 	if(subString1=="departFlight3"){		
								if(dateEl.innerHTML!="")
									html = dateEl.innerHTML;
								else
									html =document.getElementById("frm:searchForm:departFlight2").innerHTML;											
							}else 	if(subString1=="departFlight4"){	
								if(dateEl.innerHTML!="")
									html = dateEl.innerHTML;
								else
									html =document.getElementById("frm:searchForm:departFlight3").innerHTML;											
							}else 	if(subString1=="departFlight5"){		
								if(dateEl.innerHTML!="")
									html = dateEl.innerHTML;
								else
									html =document.getElementById("frm:searchForm:departFlight4").innerHTML;											
							}else {
								html = dateEl.innerHTML;
								}


						if (value) {					
								dateValue = value;
							} else {							
									dateValue=html;							
								}if (dateValue != "") {
									var parsedDate = Date.parseDate(value || html, dateFmt);
									if (parsedDate != null) {
										cal.setDate(parsedDate);
										}
										}
										}if (!params.position) {
											cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);} else {cal.showAt(params.position[0], params.position[1]);}return false;};if (params.closeEventName) {triggerEl["on" + params.closeEventName] = function () {if (window.calendar) {window.calendar.callCloseHandler();}};}return cal;};
    Zapatec.Utils.addEvent(window, "load", Zapatec.Utils.checkActivation);

 ////ZAPATEC CALENDER's CALENDER JS END//////////////////////////////////////////////////////////
 
 
 //ZAPATEC CALENDAR's CALENDAR-EN JS START//////////////////////////////////////////////////////////////////////
 
 
 // $Id: commonTools.js,v 1.4 2011/03/31 10:09:33 aashishkumar.singh Exp $
// ** I18N

// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: any
// Distributed under the same terms as the calendar itself.

// For translators: please use UTF-8 if possible.  We strongly believe that
// Unicode is the answer to a real internationalized world.  Also please
// include your contact information in the header, as can be seen above.

// full day names
Zapatec.Calendar._DN = new Array
("Sunday",
 "Monday",
 "Tuesday",
 "Wednesday",
 "Thursday",
 "Friday",
 "Saturday",
 "Sunday");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Zapatec.Calendar._SDN_len = N; // short day name length
//   Zapatec.Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Zapatec.Calendar._SDN = new Array
("Sun",
 "Mon",
 "Tue",
 "Wed",
 "Thu",
 "Fri",
 "Sat",
 "Sun");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Zapatec.Calendar._FD = 0;

// full month names
Zapatec.Calendar._MN = new Array
("January",
 "February",
 "March",
 "April",
 "May",
 "June",
 "July",
 "August",
 "September",
 "October",
 "November",
 "December");

// short month names
Zapatec.Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "May",
 "Jun",
 "Jul",
 "Aug",
 "Sep",
 "Oct",
 "Nov",
 "Dec");

// tooltips
Zapatec.Calendar._TT_en = Zapatec.Calendar._TT = {};
Zapatec.Calendar._TT["INFO"] = "About the calendar";

Zapatec.Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) zapatec.com 2002-2007\n" + // don't translate this this ;-)
"For latest version visit: http://www.zapatec.com/\n" +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Zapatec.Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Zapatec.Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Zapatec.Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Zapatec.Calendar._TT["GO_TODAY"] = "Go Today (hold for history)";
Zapatec.Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Zapatec.Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Zapatec.Calendar._TT["SEL_DATE"] = "Select date";
Zapatec.Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Zapatec.Calendar._TT["PART_TODAY"] = " (today)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Zapatec.Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Zapatec.Calendar._TT["WEEKEND"] = "0,6";

Zapatec.Calendar._TT["CLOSE"] = "Close";
Zapatec.Calendar._TT["TODAY"] = "Today";
Zapatec.Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Zapatec.Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Zapatec.Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Zapatec.Calendar._TT["WK"] = "wk";
Zapatec.Calendar._TT["TIME"] = "Time:";

Zapatec.Calendar._TT["E_RANGE"] = "Outside the range";

Zapatec.Calendar._TT._AMPM = {am : "am", pm : "pm"};

/* Preserve data */
	if(Zapatec.Calendar._DN) Zapatec.Calendar._TT._DN = Zapatec.Calendar._DN;
	if(Zapatec.Calendar._SDN) Zapatec.Calendar._TT._SDN = Zapatec.Calendar._SDN;
	if(Zapatec.Calendar._SDN_len) Zapatec.Calendar._TT._SDN_len = Zapatec.Calendar._SDN_len;
	if(Zapatec.Calendar._MN) Zapatec.Calendar._TT._MN = Zapatec.Calendar._MN;
	if(Zapatec.Calendar._SMN) Zapatec.Calendar._TT._SMN = Zapatec.Calendar._SMN;
	if(Zapatec.Calendar._SMN_len) Zapatec.Calendar._TT._SMN_len = Zapatec.Calendar._SMN_len;
	Zapatec.Calendar._DN = Zapatec.Calendar._SDN = Zapatec.Calendar._SDN_len = Zapatec.Calendar._MN = Zapatec.Calendar._SMN = Zapatec.Calendar._SMN_len = null


//ZAPATEC CALENDAR's CALENDAR-EN JS END////////////////////////////////////////////////////////////////////// 

//ZAPATEC CALENDAR's CALENDAR-API JS START////////////////////////////////////////////////////////////////
var calStartDate; 
var calEndDate;

/*  Description : to be called on the 'onfocus' event of a textbox
 *                to whom the Zapatec Calendar is to be assigned.
 *  Input 1     : sElId -> Date object or textbox id (Defines valid start date before which dates will be disabled) 
 *  Input 2     : eElId -> Date object or textbox id (Defines valid end date after which dates are disabled)  
 *  
 *  Usage       :eg. <input  id="calendar" name="calendar" type="text" onfocus="setCalStarEndtDate(new Date(),null)">
 *	                 <input  id="calendar_1" name="calendar_1" type="text" onfocus="javascript:setCalStarEndtDate('calendar',null)"> (Create Dependancy On Other Textbox with id 'calendar')
 *					 <input  id="calendar_1" name="calendar_1" type="text" onfocus="javascript:setCalStarEndtDate(null,null)">
 *					 <input  id="calendar_1" name="calendar_1" type="text" onfocus="javascript:setCalStarEndtDate(null,new Date())">
 *
 */
function setCalStarEndtDate(sElId,eElId){
	calStartDate = getElementDateValue(sElId);
	calEndDate = getElementDateValue(eElId);
}

/*  Description : ASSIGNS a Zapatec Calendar Instance to one textbox.
 *                
 *  Input 1     : elId      -> Textbox id 
 *  Input 2     : imgStatus -> true/false, weather calendar image with associated calendar is required
 *   
 *  Usage       : eg. createZapatecCalender('calendar_1')
 *                 OR  createZapatecCalender('calendar_1',true); 
 *  
 *  Note        : The textbox component preferrably with its onfocus event defined, must be available in the page before firing this method 
 */
function createZapatecCalender(elId,imgStatus,months){
	if(imgStatus){
		var lCalObj = document.getElementById(elId);
		var spanObj = document.createElement('span');
		spanObj.innerHTML = "<img src='/ontramercury/faces/js/zapatecCalendar/images/calendar2.gif' align='absmiddle' style='margin-left:2px;' onclick=\"triggerElementFocus(this,'"+elId+"')\">"
		insertAfter(spanObj,lCalObj);
	}
	attachCalendarToObject(elId,elId,months)
}

/*  Description : ASSIGNS Zapatec Calendar Instances to multiple textboxes.
 *                
 *  Input 1     : elIdArray      -> Textbox id Array 
 *                                  
 *	Usage       : eg.createZapatecCalenderArray(['myCal','myCal_1','myCal_2',['myCal_3',true],'myCal_4'])
 *	               OR createZapatecCalenderArray([['myCal',false],['myCal_3',true]])
 *				   OR createZapatecCalenderArray([['calendar']])
 * 
 *  Note        : The textbox components preferrably with their onfocus event defined, must be available in the page before firing this method 
 */
function createZapatecCalenderArray(elIdArray){
	for(x=0;x <elIdArray.length;x++){
		var elAry = elIdArray[x];
		if(typeof(elAry)=='object'){
			createZapatecCalender(elAry[0],elAry[1])
		} else {
			createZapatecCalender(elAry,false)
		}
	}
}

function getElementDateValue(el){
	if(el == null || el == '')
		return null;

	if(typeof(el)=='object'){
		el.setHours(0,0,0,0);
		return el;
	}
	var elObj = document.getElementById(el)
	elValue = (elObj.value).split('-');
	if (elValue.length > 1)
		var elDate = new Date(elValue[2],(parseInt(elValue[1],10)-1),elValue[0])
	else
		var elDate = new Date();

	elDate.setHours(0,0,0,0);
	return elDate;
}

function insertAfter(new_node, existing_node) {  
   if (existing_node.nextSibling){  
		if(existing_node.nextSibling.nodeName!='SPAN'){ //Append Image Only After A TextBox
		  existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
	    }
	}else
		existing_node.parentNode.appendChild(new_node);
 
} 

function disallowedCalenderDates(dateCheckOut) { 
	dateCheckOut.setHours(0,0,0,0) 
	if (calStartDate != null && calStartDate > dateCheckOut) return true
	if (calStartDate != null && calEndDate != null && calEndDate < dateCheckOut) return true

	if (calEndDate   != null && calEndDate < dateCheckOut) return true
	if (calStartDate == null && calEndDate != null && calEndDate < dateCheckOut) return true

	return false; 
} 

function triggerElementFocus(obj,elId){
	calIpObj = document.getElementById(elId);
	if(calIpObj.focus){
		calIpObj.focus()
	}
	setTimeout('calIpObj.onclick()',10);
}

function attachCalendarToObject(elId,btId,months){
	if(!months){
	  months =2;
	}
	Zapatec.Calendar.setup({
		showOthers        : false,
		singleClick       : true,
		inputField        : elId,
		button            : btId,
		dateStatusFunc    : disallowedCalenderDates,
		ifFormat          : "%d-%m-%Y",
		daFormat          : "%Y/%m/%d",
		numberMonths      : months,
		monthsInRow       : 1,
		vertical          : false,
		noHelp            : true
	});
}

//ZAPATEC CALENDAR's CALENDAR-API JS END////////////////////////////////////////////////////////////////


///MYMASK JS Start//////////////////////////////////////////////////////////////////  
  /*
   * For Testing Just call this method
   */
  function testMask() {
	  if(arguments.length==1){
		    showMask(arguments[0]);
		}else{
			showMask();
		}
	  setTimeout("hideMask()",3000);
	}

	/*
	 * Call this to Show the Loading/Processing Mask
	 * can accept one argument , i.e. the div id of the div to be displayed over the mask. 
	 */
	function showMask() {
		if(arguments.length==1){
		 document.getElementById('mask_content').innerHTML = document.getElementById(arguments[0]).innerHTML;
		}

	   var tDiv = document.getElementById('mask_holder');
	   var bgDiv = document.getElementById('mask_bg');
	   var ifr = document.getElementById('IFrmHelper');	
		 
	   var mie=document.all && !window.opera;
	   var mdomclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth) || 100000; //Preliminary doc width in non IE browsers
	   var mstandardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body; //create reference to common "body" across doctypesthis.scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
	   var mscroll_top=(mie)? mstandardbody.scrollTop : window.pageYOffset;
	   var mscroll_left=(mie)? mstandardbody.scrollLeft : window.pageXOffset;
	   var mdocwidth=(mie)? mstandardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(mdomclientWidth, window.innerWidth-16);
	   var mdocheight=(mie)? mstandardbody.clientHeight: window.innerHeight;
       var mdocCompleteHeight = (mstandardbody.offsetHeight>mstandardbody.scrollHeight)? mstandardbody.offsetHeight : mstandardbody.scrollHeight;
	   
	    //alert(mdocheight+" "+mdocCompleteHeight);
        tDiv.style.width = bgDiv.style.width = ifr.style.width = mdocwidth+"px";
		tDiv.style.height = bgDiv.style.height = ifr.style.height= mdocCompleteHeight+"px";
		
		tDiv.style.display = 'block';
		tDiv.style.visibility = 'visible';
		//switchingDisability(false);

	}

	/*
	 * Call this to Hide the Loading/Processing Mask
	 */
	function hideMask() {
		var divComponent = null;
	    if(arguments.length==1){
	        divComponent = document.getElementById(arguments[0]);
		}else{
			divComponent =document.getElementById('mask_holder');
		}
		divComponent.style.display = 'none';
		divComponent.style.visibility = 'hidden';
		//switchingDisability(true);
	}
    
	/**
	* Used to Disable/Enable Select-One components 
	* (Select-one component is always rendered over div, so they have to be 
	*  disabled)
	**/
	function switchingDisability(booleanVal){
	 var allForms =  document.forms;
        for(i=0;i<allForms.length;i++){
		    var elements = document.forms[i].elements;
			for(k=0;k<elements.length;k++){
			   if(elements[k].type=="select-one"){
				   if(booleanVal){
						elements[k].disabled = !booleanVal;
				   }else{
						elements[k].disabled = !booleanVal;
				   }
			   }
			}
		}
	}

	function getIframeDoc(IFrame){
	
	 var doc;
      if( IFrame.contentDocument )
            // For NS6
            doc = IFrame.contentDocument; 
      else if(IFrame.contentWindow ) 
            // For IE5.5 and IE6
            doc = IFrame.contentWindow.document;
      else if( IFrame.document )
            // For IE5
            doc = IFrame.document;
      else //other browser
            doc = IFrame.document;      

      return doc;


	}

///MYMASK JS END//////////////////////////////////////////////////////////////////
