﻿/*
    Elan Web Javascript  
*/
var Elan = {};
Elan.Version = "1.0";

/* 系统安装目录，请手工修改，以 / 开始和结束 */
Elan.InstallDir = "/";
document.write("<iframe id=\"ElanWebCalender\" name=\"ElanWebCalender\" src=\""+ Elan.InstallDir +"calendar/calendar.html\" style=\"width:300px; height:182px; display:none; position:absolute; z-index:999999\" frameborder=\"0\" scrolling=\"no\"></iframe>");

Elan.Resources = {
	City : [],
	FlightCity : [],
	Week : ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
	Loading : {
		small : "<div class='loading'><img src='" + Elan.InstallDir + "Images/loading_16x16.gif' border='0' /></div>",
		big: "<div class='loading'><img src='" + Elan.InstallDir + "Images/loading.gif' border='0' /></div>"
	}
};

/****************************** 以下为程序开始  *******************************/
Elan.Travel = {
	/*
	   功能：读取指定日期的产品价格
	   参数：json对象
	       TravelId    - 度假产品ID
		   Date       - 查询日期，格式：2010-5-1
		   DataType    - 数据类型，取值： json : xml
		   CallBack    - 回调函数
	*/
	ReadPriceInfo : function(){
		var defaults = {
			TravelId: 0,
			Date: null,
			DataType: "json",
			CallBack: null
		};		
		var params = Object.extend(defaults, arguments[0] || {});
		var url = Elan.InstallDir + "Modules/Travel/GetPriceInfoByDate.aspx";
		var parameters = "TravelId=" + params.TravelId +"&Date=" + params.Date + "&DataType=" + params.DataType;
		new Ajax.Request(
				url, {
					method: "get",
					parameters: parameters,
					onComplete: params.CallBack
				}
		);
	},
	
	/*
	   功能：读取度假月份列表价格信息
	   参数：json对象
	       TravelId    - 度假产品ID
		   Month       - 查询日期，格式：2010-5，默认查询当前月
		   DataType    - 数据类型，取值： json : xml
		   CallBack    - 回调函数
	*/
	ReadPriceList : function(){
		var defaults = {
			TravelId: 0,
			Month: null,
			DataType: "json",
			CallBack: null
		};
		var params = Object.extend(defaults, arguments[0] || {});
		var url = Elan.InstallDir + "Modules/Travel/GetPriceListByMonth.aspx";
		var parameters = "TravelId=" + params.TravelId +"&Date=" + params.Month + "&DataType=" + params.DataType;
		new Ajax.Request(
				url, {
					method: "get",
					parameters: parameters,
					onComplete: params.CallBack
				}
		);
	},
	
	GetPriceCalendar : function(data, para){
		if(!data.length) return;
		var me = this;
		var html = "";
		var events = { onItemClick: null, onItemOver: null, onItemOut: null };
		var startDayWeek = data[0].PriceDate.getDay();
		var params = Object.extend(events, para || {});
		var now = new Date();
		
		var div = Builder.node("div", { id: "ElanWeb_TravelPriceCalendar", "class": "price_calendar"});
		var table = Builder.node("table", { "class": "m"+ (data[0].PriceDate.getMonth() + 1).toString() });
		var tbody = Builder.node("tbody");
		var tr = Builder.node("tr");
		
		for(var i = 0;i < Elan.Resources.Week.length; i++){
			var w = Builder.node("td", { "class": "week"});
			w.innerHTML = Elan.Resources.Week[i];
			tr.appendChild(w);
		}
		tbody.appendChild(tr);
		
		tr = Builder.node("tr");
		for(var i = 0; i < startDayWeek; i++){
			tr.appendChild(Builder.node("td", { "class": "null"}));
		}
		
		for(var i = 0; i < data.length; i++){
			var td = Builder.node("td");
			var date = Builder.node("b");
			var price = Builder.node("em")
			date.innerHTML = data[i].PriceDate.getDate();
			if(data[i].IsNull || data[i].PriceDate < now){
				td.className = "null";
				price.innerHTML = "&nbsp;";
			}else{
				price.innerHTML = "&yen;"+ data[i].Price;
				td.title = "成人价：¥"+ data[i].Price +"\n儿童价：¥"+ data[i].ChildPrice;
				(function(){
					var index = i;
					td.onmouseover = function(){
						this.className = 'over'; 
						if(params.onItemOver) params.onItemOver.call(this, data[index]); 
					}
					td.onmouseout = function(){
						this.className = '';
						if(params.onItemOut) params.onItemOut.call(this, data[index]); 
					}
					td.onclick = function(){
						if(params.onItemClick) params.onItemClick.call(this, data[index]); 
					}
				})();
				
			}
			td.appendChild(date);
			td.appendChild(price);
			tr.appendChild(td);
			if ((i + 1 + startDayWeek) % 7 == 0){
				tbody.appendChild(tr);
				tr = Builder.node("tr");
			}
		}
		
		var count = data.length + startDayWeek;
		if (count % 7 != 0){
			var temp = 7 - count % 7;
			for (var k = 0; k < temp; k++){
				tr.appendChild(Builder.node("td", { "class": "null"}));
			}
			tbody.appendChild(tr);
		}
		table.appendChild(tbody)			
		div.appendChild(table);
		return div;
	}
};

Elan.Hotel = {
	SearchDay: 30, //酒店搜索最大搜索时间间隔，天数
	
	/*
	   功能：读取客房每日详细价格（Ajax异步方式 ）
	   参数：json对象
	       RoomId     - 客房ID
	       BeginDate  - 查询开始日期
	       EndDate    - 查询结束日期
	       DataType   - 数据类型，取值： json : xml
		   CallBack   - 回调函数
	*/
	ReadRoomPriceInfo : function(){
		var defaults = {
			RooomId: 0,
			BeginDate: null,
			EndDate: null,
			DataType: "json",
			CallBack: null
		}
		var params = Object.extend(defaults, arguments[0] || {});
		var url = Elan.InstallDir + "Modules/Hotel/GetRoomPriceInfo.aspx";		
		var parameters = "RoomId=" + params.RoomId + "&BeginDate=" + params.BeginDate + "&EndDate=" + params.EndDate + "&DataType=" + params.DataType;
		new Ajax.Request(
				url, {
					method: "get",
					parameters: parameters,
					onComplete: params.CallBack
				}
			);
	},
	
	GetPriceInfoData : function(data, CheckInDate, CheckOutDate){
		var html = "";
		var status = true, price = 0;
		var start, end;
		html += "<div class='room_price_info'>";
		html += "<table width='100%' border='0' cellpadding='0' cellspacing='1'>";
		html += "<tr>";
		for(var i = 0;i < Elan.Resources.Week.length; i++)  html += "<td class='week'>"+ Elan.Resources.Week[i] +"</td>"
		html += "</tr>";	
		
		start = CheckInDate.getDay() == 0 ? CheckInDate : DateAdd("d", 0 - CheckInDate.getDay(), CheckInDate);
		end = CheckOutDate.getDay() == 0 ? DateAdd("d", -1, CheckOutDate) : DateAdd("d", 6 - CheckOutDate.getDay(), CheckOutDate);	
		html += "<tr>";
		while(start <= end){
			html += "<td>";
			html += "<i>"+ (start.getMonth() + 1) +"月"+ start.getDate() +"日</i>";			
			if(start < CheckOutDate && start >= CheckInDate){
				var p = null;
				for(var i = 0; i < data.length; i++){
					if(data[i]["Date"] == start.AsString()) p = data[i]["Price"];
				}
				if(p == null){
					html += "<s>×</s>";
					status = false;
				}else{
					html += "<em>&yen;" + p + "</em>";
					price += p.toString().ToNumber();
				}
			}
			html += "</td>";
			if(start.getDay() == 6 && start < end) html += "</tr><tr>";
			start = DateAdd("d", 1, start);
		}
		html += "</tr>";
		html += "</table></div>";
		return { Html : html, Status: status, UnitPrice: price };
	}
};

Elan.User = {
	LoginUrl        : Elan.InstallDir + "User/Login.aspx",
	LogoutUrl       : Elan.InstallDir + "User/Logout.aspx",
	RegisterUrl     : Elan.InstallDir + "User/Register.aspx",
	MemberCenterUrl : Elan.InstallDir + "User/",
	
	Login : function(userInfo, CallBack){
		var defaults = { UserName: "", Password: "", ValidateCode: "", DataType: "json" };
		var params = Object.extend(defaults, userInfo || { });
		var th = this;
		new Ajax.Request(
				Elan.InstallDir + "User/AjaxLogin.aspx",
				{
					method: "get",
					parameters: "UserName=" + params.UserName + "&Password="+ params.Password +"&ValidateCode=" + params.ValidateCode +"&DataType=" + params.DataType,
					onComplete: function(response){
						var result = Elan.GetJson(response.responseText);
						if(result != null){
							if(!result.Error){
								if(result.ApiLogin && result.ApiLogin.Trim() != ""){
									var div = Builder.node("div", { "class": "display:none" });
									div.innerHTML = result.ApiLogin.Trim();									
									$$("body")[0].appendChild(div);
								}
							}
						}
						CallBack.call(th, response);
					},
					onError: function(response){ alert("server error.") }
				}
			);
	},
	
	GetCurrent : function(DataType, CallBack){
		new Ajax.Request(
				Elan.InstallDir + "User/GetCurrentUser.aspx",
				{
					method: "get",
					parameters: "DataType=" + DataType,
					onComplete: CallBack
				}
			);
	},
	
	GetLoginStatus : function(CallBack){
		new Ajax.Request(
				Elan.InstallDir + "User/GetUserLoginStatus.aspx",
				{
					method: "get",
					onComplete: CallBack
				}
			);
	},
	
	LoginForm : {
		defaults : {
			showSuccessMsg: true,
			onComplete: null,
			onSuccess: null
		},
		Show : function(){
			this.params = Object.extend(this.defaults, arguments[0] || { });
			this.html = "";
			this.html += "<table width='100%' border='0' cellspacing='0' cellpadding='0'>";
			this.html += "<tr><td class='caption'>用户名：</td>";
			this.html += "<td colspan='2' class='input'><input type='text' id='__AjaxUserName' name='__AjaxUserName' class='textbox' size='20'></td>";
			this.html += "</tr><tr>";
			this.html += "<td class='caption'>密 码：</td>";
			this.html += "<td colspan='2' class='input'><input type='password' id='__AjaxPassword' name='__AjaxPassword' class='textbox' size='20'></td>";
			this.html += "</tr><tr>";
			this.html += "<td class='caption'>验证码：</td>";
			this.html += "<td class='input' width='90'><input type='text' id='__AjaxValidateCode' name='__AjaxValidateCode' size='10' class='textbox'></td>";
			this.html += "<td class='code'><img id='__AjaxImgValidateCode' title='看不清楚换个图片' onclick=this.src='"+ Elan.InstallDir +"Controls/ValidateCode.aspx?id='+Math.random() src='"+ Elan.InstallDir +"Controls/ValidateCode.aspx' style='border-width:0px;cursor:pointer;' /></td>";			
			this.html += "</tr><tr>";
			this.html += "<td class='button' colspan='3'><input type='button' id='__AjaxLoginBtn' name='__AjaxLoginBtn' value='登录' class='btn5' onclick='Elan.User.LoginForm.Post()'></td>";
			this.html += "</tr></table>";	
			this.win = Elan.UI.Window.Show({
					title: "会员登录",
					width: 400,
					showBtnClosed: false,
					content: "<div id='__AjaxForm' class='ajax_login_form'>"+ this.html + "</div>",
					onClosed: this.params.onComplete
			}).Resize();
			return this;
		},
		
		Post : function(){
			var userName = $F("__AjaxUserName");
			var password = $F("__AjaxPassword");
			var validateCode = $F("__AjaxValidateCode");
			if(userName.Trim() == ""){
				alert("用户名不能为空");
				$("__AjaxUserName").focus();
				return;
			}
			if(password.Trim() == ""){
				alert("密码不能为空");
				$("__AjaxPassword").focus();
				return;
			}
			if(validateCode.Trim() == ""){
				alert("验证码不能为空");
				$("__AjaxValidateCode").focus();
				return;
			}
			$("__AjaxForm").update(Elan.Resources.Loading.big);
			var me = this;
			Elan.User.Login({ UserName: userName, Password: password, ValidateCode: validateCode}, function(response){ me.Result(response) });
		},
		
		Result : function(response){
			var data = Elan.GetJson(response.responseText);
			if(data == null){
				alert("请求连接失败");
				$("__AjaxForm").update(this.html);
			}else{
				if(data.Error){
					alert(data.Error);
					$("__AjaxForm").update(this.html);
					$("__AjaxImgValidateCode").click();
					$("__AjaxValidateCode").value = "";
					$("__AjaxPassword").value = "";
				}else{
					if(this.params.showSuccessMsg) alert("登录成功");
					if(this.params.onSuccess) this.params.onSuccess.call(this, data);
					this.win.Hide();
					this.win.Update("");
					this.win = null;
				}
			}
		}
	}
};

Elan.Label = Class.create({
	Url : Elan.InstallDir + "AjaxLabel.aspx",
	InitCompleted : false,
	
	initialize : function(){
		this.labelParams = arguments[0];
		if(!this.labelParams) return;
		this.urlParams = this.GetUrlParams(this.labelParams);
		this.InitCompleted = true;
	},
	
	/*
	   功能：获取内容标签数据，同时更新指定窗体元素
	   参数：
	       1. element  - 元素ID
		   2. { }      - json对象，指定标签参数，如：{ChannelId: 1, ClassId: 2, IncludeChild: true ...... }
		                 特殊json元素：CallBack 回调函数
	*/
	Update : function(){
		if(!this.InitCompleted) return this;
		this.handle = $(arguments[0]);
		if(!this.handle) return this;
		
		new Ajax.Updater(
						 this.handle, 
						 this.Url,
						 {
							 method: "get",
							 parameters: this.GetUrlParams(this.labelParams),
							 evalScript: true,
							 onComplete: this.labelParams.CallBack
						 }
					);
		return this;
	},
	
	Loading : function(){
		if(this.handle) this.handle.update(arguments[0] ? arguments[0] : Elan.Resources.Loading.big);
		return this;
	},
	
	/*
	   功能：请求并获取内容标签数据
	   参数：
		   1. { }  - json对象，指定标签参数，如：{ChannelId: 1, ClassId: 2, IncludeChild: true ...... }
		             特殊json元素：CallBack 回调函数
	*/
	Request : function(){
		new Ajax.Request(
						 this.Url,
						 {
							 method: "get",
							 parameters: this.GetUrlParams(this.labelParams),
							 evalScript: true,
							 onComplete: this.labelParams.CallBack
						 }
					);
		return this;
	},
	
	GetUrlParams : function(labelParams){
		var params = "rnd=" + Math.random();
		for(i in labelParams){
			if(i.toLowerCase().Trim() != "callback"){
				params += "&" + i + "=" + labelParams[i];
			}
		}	
		return params;
	}
});

Elan.GetHits = function(element, channeId, infoId){
	var span = $(element);
	if(!span) return;
	new Ajax.Updater(
			span, 
			Elan.InstallDir + "Hits.aspx?ChannelId=" + channeId + "&Id=" + infoId,
			{
				method: "get"
			}
		);
};

Elan.Event = {
	BindCalendar : function(element, eventName, calendarParams, call){
		if(!element || !eventName || !calendarParams) return;
		var control = $(element);
		if(!control) return;
		var eventCalendar = (
			function(e){
				if(e) Event.stop(e);
				Elan.UI.Calendar.Show(calendarParams);
				if(call) try{ call.call() } catch(e){};
			}
		);
		this.Bind(control, eventName, eventCalendar);
	},
	
	BindCityDropDown : function(element, eventName, dropdownParams, call){
		if(!element || !eventName || !dropdownParams) return;
		var control = $(element);
		if(!control) return;
		
		var eventDropCity = (
			function(e){
				if(e) Event.stop(e);
				if(!Elan.UI.DropDown.IsShow){
					Elan.UI.DropDown.Show(dropdownParams);
					if(call) try{ call.call() } catch(e){};
				}
			}
		);
		this.Bind(control, eventName, eventDropCity);
	},
	
	Bind : function(control, eventName, eventHandle){
		if((typeof(eventName)).toLowerCase() != "object"){
			eventName = [ eventName.toString() ];
		}
		for(var i = 0; i < eventName.length; i++){
			Event.stopObserving(control, eventName[i]);
			Event.observe(control, eventName[i], eventHandle);
		}
	}
};

Elan.UI = {	
	Map : function(){
		var handle = $(arguments[0]);
		if(!handle) return;
		var defaults = {point: "39.9081726,116.3979471", zoom: 15, mapControl: 0}
		var params = Object.extend(defaults, arguments[1] || { });
		var url = Elan.InstallDir + "Map.aspx?point=" + params.point + "&zoom=" + params.zoom + "&mapcontrol=" + params.mapControl;
		var map = Builder.node("div", { id: "ElanWebMap" },[
							Builder.node("div", { id: "ElanWebMap_loading_" + handle.id }),
							Builder.node("iframe", { id: "ElanWebMap_iframe_" + handle.id, frameborder: "0",scrolling: "no", height: handle.offsetHeight +"px", width: "100%" })
					]);
		handle.update(map);
		var loading = $("ElanWebMap_loading_"+ handle.id);
		var iframe = $("ElanWebMap_iframe_"+ handle.id);
		iframe.src = url;
		IframeLoading(iframe, loading);
	},
	
	FlashSlide : function(){
		var defaults = {width: 200, height: 200, textHeight: 18, pics: "", links: "", texts: ""}
		var params = Object.extend(defaults, arguments[0] || { });
		
		var html = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='"+ params.width +"' height='"+ (params.height + params.textHeight) +"'>";
		html += "<param name='quality' value='high'>";
		html += "<param name='bgcolor' value='#EFEFEF'>";
		html += "<param name='menu' value='false'>";
		html += "<param name=wmode value='opaque'>";
		html += "<param name='FlashVars' value='pics="+ params.pics +"&amp;links="+ params.links +"&amp;texts="+ params.texts +"&amp;borderwidth="+ params.width +"&amp;borderheight="+ params.height +"&amp;textheight="+ params.textHeight +"'>";
		html += "<param name='movie' value='"+ Elan.InstallDir +"Images/flash.swf'>";
		html += "<embed width='"+ params.width +"' height='"+ params.height +"' src='"+ Elan.InstallDir +"Images/flash.swf?pics="+ params.pics +"&amp;links="+ params.links +"&amp;texts="+ params.texts +"&amp;borderwidth="+ params.width +"&amp;borderheight="+ params.height +"&amp;textheight="+ params.textHeight +"' type='application/x-shockwave-flash'>";
		html += "</object>";
		document.write(html);
	},
	
	Make : {
		div : null,
		Show : function(){
			if(!this.div){
				var documentBody = $$('body')[0];
				documentBody.appendChild(
						Builder.node('div', { id: "ElanWebMake" })
					);
				this.div = $("ElanWebMake");
				this.div.setStyle({left: "0px", top: "0px", position: "absolute", width: "100%", background: "#333", zIndex: 550});
			}
			var pageSize = Elan.UI.GetPageSize();
			this.div.setStyle({height: pageSize.height + "px", opacity: .5}).show();
			Elan.UI.HideSelects();
		},
		
		Hide : function(){
			if(this.div){
				try{
					new Effect.Fade(this.div, { duration: 0.2 });
				}catch(ex){
					this.div.hide();
				}
			}
			Elan.UI.ShowSelects();
		}
	},
	
	GetPageSize : function(){
		var pageScroll = Elan.UI.GetPageScroll();
		var windowWidth, windowHeight;
		if (self.innerHeight) {
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		
		if(pageScroll.top < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = pageScroll.top;
		}
		
		if(pageScroll.left < windowWidth){
			pageWidth = pageScroll.left;
		} else {
			pageWidth = windowWidth;
		}
		return {width:pageWidth, height:pageHeight};
	},
	
	GetPageScroll : function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else {
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		return {left: xScroll, top: yScroll}
	},
	
	CreateElement : function(){
		var params = arguments[0];
		if(!params.element) params.element = "div";
		var element = document.createElement(params.element);
		if(params.id) { element.id = params.id; element.name = params.id; }
		if(params.className) element.className = params.className;
		if(params.text) element.innerHTML = params.text;
		return element;
	},
	
	RemoveElement : function(node){
		for(var i = node.childNodes.length - 1; i >= 0; i--){
			node.removeChild(node.childNodes[i]);
		}
	},
	
	GetElementOffsets : function(element){
		var top = element.offsetTop;  
		var left = element.offsetLeft;
		while(element = element.offsetParent){
			top += element.offsetTop + (Prototype.Browser.IE ? element.clientTop : 0);
			left += element.offsetLeft + (Prototype.Browser.IE ? element.clientLeft : 0);
		} 
		return {top: top, left: left};	
	},
	
	HideSelects : function(){
		if(this.IE6() == true){
			var selects = document.getElementsByTagName("select");
			for(var i = 0; i < selects.length; i++){
				selects[i].style.display = "none";
			}
		}
	},
	
	ShowSelects : function(){
		if(this.IE6() == true){
			var selects = document.getElementsByTagName("select");
			for(var i = 0; i < selects.length; i++){
				selects[i].style.display = "";
			}
		}
	},
	
	IE6 : function(){
		if(Prototype.Browser.IE && (window.navigator.appVersion.indexOf("MSIE 6.0") > -1 || window.navigator.appVersion.indexOf("MSIE 5.0") > -1)){
			return true;
		}else{
		    return false;
		}
	},
	
	IsIE : Prototype.Browser.IE
}

Elan.UI.Slider = Class.create({
	initialize : function(){
		var defaults = {
			element: null,
			images: [],
			effect: true,
			speed : 5000,
			showTitle: true,
			showbutton: true,
			autoSize: true
		};
		this.params = Object.extend(defaults, arguments[0] || {});
		this.handle = $(this.params.element);
		if(!this.handle) return;	
		
		this.links = [];
		this.titles = [];
		this.buttons = [];
		this.step = Elan.UI.IsIE ? 25 : 5;
		
		this.handle.appendChild(Builder.node("div", { id: "ElanWebSlider_text", "class" : "webslider_text" }));
		this.handle.appendChild(Builder.node("div", { id: "ElanWebSlider", "class" : "webslider" }));		
		this.handle.appendChild(Builder.node("div", { id: "ElanWebSlider_btn", "class" : "webslider_buttons" }));		
		this.slider = $("ElanWebSlider");
		this.btn = $("ElanWebSlider_btn");		
		
		this.text = $("ElanWebSlider_text");
		this.text.setStyle({ opacity: .5, width: this.slider.offsetWidth + "px", marginTop: (this.slider.offsetHeight - this.text.offsetHeight - this.btn.offsetHeight - 5) + "px" });
		if(!this.params.showTitle) this.text.hide();
		if(!this.params.showbutton) this.btn.hide();
		
		for(var i = 0; i < this.params.images.length; i++){
			this.AddItem(this.params.images[i]);
		}
	},
	
	Start : function(){
		var linkListTmp = this.slider.getElementsByTagName("a");
		for (var i = 0; i < linkListTmp.length; i++){
			linkListTmp[i].hide();
			this.links.push(linkListTmp[i]);
		}
		this.displayer = document.createElement("a");
		this.displayer.style.display = "none";
		this.displayer.style.overFlow = "hidden";
		this.slider.appendChild(this.displayer);
		if(!this.links.length) return;
		
		for (var i = 0; i < this.links.length ; i++){
			var btnTmp = document.createElement("li");
			if (!i) btnTmp.className = "current";		
			btnTmp.innerHTML = (i+1);
			this.buttons.push(btnTmp);
			this.btn.appendChild(btnTmp);			
			btnTmp.onclick = this.GotoFunction(i);
		}
		
		var me = this;
		this.running = false;
		this.current = 0;
		this.next = 0
		this.target = null;
		
		this.links[this.current].show();
		this.text.update(this.titles[this.current]);
		this.clock = setTimeout(
				function(){
					me.Goto(null);
				}, 
				this.params.speed
		);
	},
	
	AddItem : function(args){
		if(!args) return;	
		var div = Builder.node("div", { style: "overflow: hidden; margin:0px; padding:0px; " });
		var img = Builder.node("img", { src: args.image, border: "0", width: this.handle.offsetWidth, height: this.handle.offsetHeight})
		div.appendChild(img);
		div.setStyle({ width: this.handle.offsetWidth +"px", height: this.handle.offsetHeight + "px"});
		if(this.params.autoSize){
			var imgPreloader = new Image();
			var me = this;
			imgPreloader.onload = (function(){
					var width = imgPreloader.width;
					var height = imgPreloader.height;
					var scale = width / height;
					width = me.handle.offsetWidth;
					height = width / scale;
					if(height < me.handle.offsetHeight){
						height = me.handle.offsetHeight;
						width = height * scale;
						img.setStyle({ margin: "0px 0px 0px " + ((me.handle.offsetWidth - width) / 2) + "px" });
					}else{
						img.setStyle({ margin: ((me.handle.offsetHeight - height) / 2) + "px 0px 0px 0px" });
					}
					img.setStyle({ width: width +"px", height: height + "px"});
			}).bind(this);
			imgPreloader.src = args.image;
		}		
		this.slider.appendChild(
				Builder.node("a", { href: args.link, target: "_blank" },[ div ])
			);
		this.titles.push(args.title);
	},
	
	GotoFunction : function(index){
		var me = this;
		return function(){
			me.Goto(index);
		};
	},
	
	Goto : function(index){
		if(this.links.length < 2) return;
		if (index != null){
			if (index == this.next)
				return;
			else
				this.target = index;
		}
		clearTimeout(this.clock);
		if(this.running) return;	
		this.running = true;
		
		this.current = this.next;
		this.next = (this.next + 1) % this.links.length;
		if (this.target !== null)
			this.next = this.target;
		this.target = null;		
		
		this.displayer.parentNode.insertBefore(this.links[this.current], this.displayer);
		this.links[this.current].setStyle({ position: "relative" });
		this.links[this.next].setStyle({ position: "absolute" }).show();
		this.buttons[this.current].className = "";
		this.buttons[this.next].className = "current";
		this.text.update(this.titles[this.next]);
		
		if(!this.params.effect){
			this.links[this.current].hide();
			this.running = false;
			var me = this;
			this.clock = setTimeout(
					function(){
						me.Goto(null);
					}, 
					this.params.speed
			);
			return;
		}
		
		var alpha = 100;
		var me = this;
		var iClock = setInterval(
				function(){
					alpha = Math.max(alpha - me.step, 0);
					me.links[me.current].setStyle({ opacity: alpha / 100 });
					if (!alpha){
						clearInterval(iClock);
						me.links[me.current].setStyle({ opacity: 100 });
						me.TransCompleted();
					}
				}, 
				20
			);
	},
	
	TransCompleted : function(){
		this.links[this.current].hide();
		this.running = false;
		var me = this;
		this.clock = setTimeout(
			function(){
				me.Goto(null);
			}, 
			this.target===null ? this.params.speed : 200
		);
	}
});

Elan.UI.PageLoader = {
	ElementCreated : false,
	Init : function(){		
		var documentBody = $$("body")[0];
		documentBody.appendChild(
						Builder.node('div', { id: "ElanWebLoading", style: "text-align:center; position:absolute; background:#fff; z-index:99999999; font-family:Arial; " })
					);
		this.handle = $("ElanWebLoading");
		this.handle.setStyle({ width: this.params.width + "px", height: (this.params.height / 2) + "px", paddingTop: (this.params.height / 2 - 50) + "px" }).hide();
		this.handle.update(this.params.icon + "<br /> Loading ......");
		this.ElementCreated = true;
		return this;
	},
	
	Show : function(){
		var defaults = {width: 350, height: 200, icon: Elan.Resources.Loading.big, make: true }
		this.params = Object.extend(defaults, arguments[0] || { });
		if(!this.ElementCreated){
			this.Init();
		}
		this.Resize();
		this.eventResize    = this.Resize.bindAsEventListener(this);
		Event.observe(window, "resize", this.eventResize);
		return this;
	},
	
	Resize : function(){
		var pageScroll = document.viewport.getScrollOffsets();
		var left = (document.viewport.getWidth() - this.params.width) / 2;
		var top = pageScroll.top + (document.viewport.getHeight() - this.params.height)  / 2;
		
		if(this.params.make) Elan.UI.Make.Show();
		if(this.handle) this.handle.setStyle({ left: left + "px", top: top + "px" }).show();
	},
	
	Hide : function(){
		Elan.UI.Make.Hide();
		if(this.handle) this.handle.hide();
		if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
	}
};

Elan.UI.Window = {
	Created : false,
	IsDrag : false,
	OrgHeight : "",
	defaults : {
			width : 500,
			height: "",
			title : "Web Window",
			textBtnOk : "确定",
			textBtnClose : "关闭",
			content : "",
			showBtnOk : false,
			showBtnClosed : true,
			type: "",
						
			onShow: null,
			onOk : null,
			onClosed : null		,
			onDrag : null
	},
	
	Init : function(){		
		var documentBody = $$("body")[0];
		documentBody.appendChild(
			Builder.node("div", { id: "ElanWebWindow", "class": "webwindow" },[
				Builder.node("div", { id: "ElanWebWindow_head", "class": "head"},[					
					Builder.node("div", { id: "ElanWebWindow_closed", "class": "closed"}),
					Builder.node("div", { id: "ElanWebWindow_title", "class": "title"})
				]),
				Builder.node("div", { id: "ElanWebWindow_body", "class": "body"}),
				Builder.node("div", { id: "ElanWebWindow_bottom", "class": "bottom"}, [
					Builder.node("input", { id: "ElanWebWindow_btnOk", type: "button"}),
					Builder.node("input", { id: "ElanWebWindow_btnClosed", type: "button"})
				])
			])
		);
		
		this.handle = $("ElanWebWindow");
		this.head = $("ElanWebWindow_head");
		this.title = $("ElanWebWindow_title");
		this.closed = $("ElanWebWindow_closed");
		this.body = $("ElanWebWindow_body");
		this.bottom = $("ElanWebWindow_bottom");
		this.btnOk = $("ElanWebWindow_btnOk");
		this.btnClosed = $("ElanWebWindow_btnClosed");
		
		this.title.update(this.params.title);
		this.btnOk.value = this.params.textBtnOk;
		this.btnClosed.value = this.params.textBtnClose;
		this.closed.setAttribute("title", this.params.textBtnClose);
		
		if(!this.params.showBtnOk) this.btnOk.hide();
		if(!this.params.showBtnClosed) this.btnClosed.hide();
		
		this.eventClose     = this.Hide.bindAsEventListener(this);
		this.eventMouseDown = this.StartDrag.bindAsEventListener(this);
		this.eventMouseUp   = this.StopDrag.bindAsEventListener(this)
		this.eventMouseMove = this.Dragging.bindAsEventListener(this);
		this.eventESC       = this.ESC.bindAsEventListener(this);
		//this.eventResize    = this.Resize.bindAsEventListener(this);
		
		Event.observe(this.closed, "click", this.eventClose);
		Event.observe(this.btnClosed, "click", this.eventClose);	
		
		this.handle.setStyle({ left : "-9999px", top: "-9999px" }).show();
		this.OrgHeight = this.handle.offsetHeight;
		this.handle.hide();
		this.Created = true;
		return this;
	},
	
	Show : function(){
		this.params = Object.extend(this.defaults, arguments[0] || { });
		this.params.width = this.params.width.toString().toLowerCase().Trim();
		this.params.height = this.params.height.toString().toLowerCase().Trim();
		this.IsDrag = false;
		
		if(!this.Created){
			this.Init();
		}
		
		if(this.params.onShow) this.params.onShow.call();
		Elan.UI.Make.Show();		
		this.Resize();
		this.Update(this.params.content);
		
		Event.observe(this.head, "mousedown", this.eventMouseDown);
		Event.observe(document, "mouseup", this.eventMouseUp);
		Event.observe(document, "mousemove", this.eventMouseMove);
		Event.observe(document, "keydown", this.eventESC);
		//Event.observe(window, "resize", this.eventResize);	
		
		if(this.params.onOk){
			Event.observe(this.btnOk, "click", this.params.onOk.bindAsEventListener(this));
		}
		
		return this;
	},
	
	Resize : function(){
		var width = "", height = "", bodyHeight;
		
		if(this.params.width.indexOf('%') < 0 && this.params.width != '' && this.params.width != 'auto'){
			width = this.params.width + "px";
		}else{
			width = this.params.width;
		}
		
		if(this.params.height.indexOf('%') < 0 && this.params.height != '' && this.params.height != 'auto'){			
			bodyHeight = (this.params.height - this.OrgHeight) + "px";
			height = this.params.height + "px";
		}else{
			height = this.params.height;
			bodyHeight = this.params.height;
		}
		
		if(this.body) this.body.setStyle({ height: bodyHeight });
		if(this.handle) this.handle.setStyle({ width: width, height: height }).show();	
		
		var pageScroll = document.viewport.getScrollOffsets();
		var left = (document.viewport.getWidth() - this.params.width) / 2;
		var top = pageScroll.top + (document.viewport.getHeight() - this.handle.offsetHeight)  / 2;	
		
		if(this.handle) this.handle.setStyle({ left: left + "px", top: top + "px" }).show();	
		return this;
	},
	
	Update : function(content){
		if(this.body){
			switch(this.params.type.toLowerCase()){
				case "link":
				    this.body.update("<iframe id='ElanWebWindow_iframe' src='"+ content +"' frameborder='0' scrolling='auto' width='"+ this.body.offsetWidth +"' height='"+ this.body.offsetHeight +"'></iframe>");
				    break;
				case "image":
				    this.body.update("<img src='"+ content +"' border='0' width='"+ this.body.offsetWidth +"' height='"+ this.body.offsetHeight +"' />");
				    break;
				default:
				    this.body.update(content);
					break;
			}			
		}
		return this;
	},
	
	StartDrag : function(){
		if(!this.handle) return;		
		if(Event.isLeftClick(event)){
			var src = Event.element(event);
			if(((tag_name = src.tagName.toUpperCase()) && (
														  tag_name=='INPUT' || 
														  tag_name=='SELECT' || 
														  tag_name=='OPTION' || 
														  tag_name=='BUTTON' || 
														  tag_name=='TEXTAREA'
														  )
													) || this.closed == src
			){
			}else{
				this.IsDrag = true;
				var pointer = [Event.pointerX(event), Event.pointerY(event)];
				this.cacheX = pointer[0];
				this.cacheY = pointer[1];			
			}
		}
		document.onselectstart = function(){ return false; }
		Event.stop(event);
	},
	
	StopDrag : function(){
		this.IsDrag = false;
		document.onselectstart = function(){ return; }
	},
	
	Dragging : function(e){
		if(!this.IsDrag) return;
		var pointer = [Event.pointerX(e), Event.pointerY(e)];
		var offsetLeft = this.handle.offsetLeft;
		var offsetTop = this.handle.offsetTop;		
		this.handle.setStyle({left: (offsetLeft + (pointer[0] - this.cacheX)) + "px", top: (offsetTop + (pointer[1] - this.cacheY)) + "px"});
		this.cacheX = pointer[0];
		this.cacheY = pointer[1];
		if(this.params.onDrag) this.params.onDrag.call();
	},
	
	ESC : function(){
	    if(KeyCode(event) == Event.KEY_ESC) this.Hide();
	},
	
	Hide : function(){
		if(this.handle){
			if(this.params.onClosed) this.params.onClosed.call();
			
			Elan.UI.Make.Hide();
			this.handle.hide();
			
			if(this.eventMouseDown) Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
			if(this.eventMouseUp) Event.stopObserving(document, "mouseup", this.eventMouseUp);
			if(this.eventMouseMove) Event.stopObserving(document, "mousemove", this.eventMouseMove);
			if(this.eventESC) Event.stopObserving(document, "keydown", this.eventESC);
			//if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);	
			if(this.params.onOk) Event.stopObserving(this.btnOk, "click", this.params.onOk);	
		}
		return this;
	}
};

Elan.UI.Tips = {
	ElementCreated : false,
	IsOver : false,
	defaults : {
		width : 450,
		title : "Web Tips",
		content : ""
	},
	
	Show : function(){
		var me = this;
		if(event) Event.stop(event);
		this.eventHide   = this.Hide.bindAsEventListener(this);
		this.eventResize = this.Resize.bindAsEventListener(this);
		
		if(this.ElementCreated == false || !this.handle){
			var documentBody = $$('body')[0];
			documentBody.appendChild(
					Builder.node('div', { id: "ElanWebTips", "class": "tips" }, [
						    Builder.node("div", { id: "ElanWebTips_top", "class": "top" }),
							Builder.node("div", { id: "ElanWebTips_head", "class": "head" }, [
									Builder.node("div", { id: "ElanWebTips_btnClose", "class": "close" }),
									Builder.node("div", { id: "ElanWebTips_title", "class": "title" })
							]),
							Builder.node("div", { id: "ElanWebTips_panel", "class": "panel" }, 
									Builder.node("div", { id: "ElanWebTips_body", "class": "body" })
							)
					])
				);	
			this.handle = $("ElanWebTips");
			this.top = $("ElanWebTips_top");
			this.head = $("ElanWebTips_head");
			this.title = $("ElanWebTips_title");
			this.btnClose = $("ElanWebTips_btnClose");
			this.body = $("ElanWebTips_body");
			
			Event.observe(this.btnClose, "click", function(){ me.IsOver = false; });
			this.ElementCreated = true;
		}
		if(!this.handle) return;		
		this.params = Object.extend(this.defaults, arguments[0] || { });		
		
		this.title.update(this.params.title);
		this.body.update(this.params.content);	
		this.target = event.target || event.srcElement; 
		this.Resize();
						
		Event.observe(document, "click", this.eventHide);		
		Event.observe(this.handle, "mousemove", function(){ me.IsOver = true; });
		Event.observe(this.handle, "mouseout", function(){ me.IsOver = false; });
		Event.observe(window, "resize", this.eventResize);
		return this;
	},
	
	Resize : function(){
		this.topX = this.params.width * .25;
		this.x = 100; // left
		this.y = 100; // top
		
		var pageScroll = document.viewport.getScrollOffsets();	
		if(this.target){
			var p = Elan.UI.GetElementOffsets(this.target);	
			var targetX = p.left - this.target.offsetWidth / 2;
			if(targetX < document.body.clientWidth / 2){
				this.topX = this.params.width * .25;
			}else{
				this.topX = this.params.width * .75;
			}			
			this.x = p.left - this.topX + this.target.offsetWidth / 2;
			this.y = p.top + this.target.offsetHeight;
			
			if(this.x + this.params.width > document.body.clientWidth){
				this.topX += this.x - (document.body.clientWidth - this.params.width - 10);
				this.x = document.body.clientWidth - this.params.width - 10;
			}else if(this.x < 10){
				this.topX -= 10 - this.x;
				this.x = 10;				
			}
		}
		this.top.setStyle({ backgroundPosition: this.topX +"px top" });
		this.handle.setStyle({ width: this.params.width +"px", top: this.y +"px", left: this.x +"px" }).show();
		return this;
	},
	
	Loading : function(){
		this.body.update(Elan.Resources.Loading.big);
		return this;
	},
	
	Update : function(content){
		this.body.update(content);
		return this;
	},
	
	Hide : function(){
		if(this.handle && !this.IsOver){
			this.handle.hide();
			this.IsOver = false;
			this.target = null;
			if(this.eventHide) Event.stopObserving(document, "click", this.eventHide);
			if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
		}		
		return this;
	}
};

Elan.UI.DropDown = {
	ElementCreated : false,	
	IsShow : false,
	IsOver : false,
	selectIndex: -1,
	Show : function(){
		var defaults = {
			control: null, 
			valueField: null, 
			textField: null,
			title: "Data Selector", 
			data: [], 
			dataFormat: ["text", "caption", "value"],
			setFocus: null,
			onComplete: null
		};
		this.params = Object.extend(defaults, arguments[0] || { });
		if(!this.params.control) return;
		this.control = $(this.params.control);
		this.data = this.params.data; // json数据对象成员: text, caption, value
		if(!this.control || !this.data) return;
		
		this.textField = this.params.textField ? this.params.textField : this.control;
		this.dataFormat = this.params.dataFormat
		this.valueField = $(this.params.valueField);
		this.params.setFocus = this.params.setFocus ? $(this.params.setFocus) : null;
		this.defaultValue = "";		
		if(this.control.getAttribute("default")){
			this.defaultValue = "|" + this.control.getAttribute("default").toLowerCase() + "|";		
		}
		
		if(this.ElementCreated == false){
			var documentBody = $$('body')[0];
			documentBody.appendChild(
					Builder.node('div', { id: "ElanWebDropDown", "class": "dropdown" }, [
						    Builder.node("div", { id: "ElanWebDropDown_title", "class": "title" }),
							Builder.node("div", { id: "ElanWebDropDown_list", "class": "list" })
					])
				);	
			
			this.div = $("ElanWebDropDown");
			this.title = $("ElanWebDropDown_title");
			this.list = $("ElanWebDropDown_list");
			this.div.hide();
			this.ElementCreated = true;
		}else{
			this.div = $("ElanWebDropDown");
			this.title = $("ElanWebDropDown_title");
			this.list = $("ElanWebDropDown_list");
		}
		
		this.title.update(this.params.title);
		this.eventDomKeyUp    = this.DomKeyUp.bindAsEventListener(this);
		this.eventDomKeyDown  = this.DomKeyDown.bindAsEventListener(this);
		this.eventHide        = this.Hide.bindAsEventListener(this);
		this.eventResize      = this.Resize.bindAsEventListener(this);
		var me = this;		
		
		Event.observe(this.control, "keyup", this.eventDomKeyUp);
		Event.observe(this.control, "keydown", this.eventDomKeyDown);		
		Event.observe(this.div, "mousemove", function(){ me.IsOver = true; });
		Event.observe(this.div, "mouseout", function(){ me.IsOver = false; });	
		Event.observe(document, "click", this.eventHide);	
		Event.observe(window, "resize", this.eventResize);	
		
		this.Pop();		
	},
	
	Pop : function(){
		this.Resize();
		this.IsShow = true;
		Elan.UI.HideSelects();
		this.LoadData();
	},
	
	Resize : function(){
		var pageScroll = document.viewport.getScrollOffsets();
		var pos = this.control.viewportOffset();
		var left = pos.left;
		var top = pageScroll[1] + pos.top + this.control.offsetHeight + 1;	
		this.div.setStyle({ left: left + "px", top: top + "px" }).show();
	},
	
	LoadData : function(){
		Elan.UI.RemoveElement(this.list);		
		this.SearchData();
		if(this.cacheData.length == 0) return;
		this.list.update(Elan.Resources.Loading.small);	
		var ul = Elan.UI.CreateElement({ element: "ul" });
		var me = this;
		var dfValue = this.textField.value;		
		this.selectedIndex = -1;
		if(!dfValue){
			dfValue = this.cacheData[0][this.dataFormat[0]];
			this.selectedIndex = 0;
		}
		
		for(var i = 0; i < this.cacheData.length; i++){
			var li = Elan.UI.CreateElement({ element: "li" });			
			var dataText = this.cacheData[i][this.dataFormat[0]];
			var dataCaption = this.cacheData[i][this.dataFormat[1]];
			var dataValue = this.cacheData[i][this.dataFormat[2]];			
				
			li.setAttribute("dataValue", dataValue);
			li.setAttribute("dataText", dataText);
			li.setAttribute("index", i.toString());
			if(dfValue == dataText){				
				this.selectedIndex = i;
			}
			li.appendChild(Elan.UI.CreateElement({ element: "span", text: dataText, className: "text"  }));
			li.appendChild(Elan.UI.CreateElement({ element: "span", text: dataCaption, className: "caption"  }));
			li.appendChild(Elan.UI.CreateElement({ element: "div", className: "c"  }));
			
			Event.observe(li, "mouseover", function(){ me.SetClassCss(this.getAttribute("index").ToNumber()); });			
			Event.observe(li, "mousedown", function(e){
											Event.stop(e);
											me.SetData(me);
										}
									);			
			
			ul.appendChild(li);
		}
		if(this.selectedIndex == -1) this.selectedIndex = 0;		
		Elan.UI.RemoveElement(this.list);
		this.list.appendChild(ul);	
		if(this.cacheData.length > 0) this.list.getElementsByTagName("li")[this.selectedIndex].className = "over";
	},
	
	SetData : function(th){
		if(!th) th = this;
		if(th.textField) th.textField.value = th.cacheData[th.selectedIndex][th.dataFormat[0]];
		if(th.valueField) th.valueField.value = th.cacheData[th.selectedIndex][th.dataFormat[2]];
		this.IsOver = false;
		th.Hide();
		if(th.params.onComplete) th.params.onComplete.call(th, th.cacheData[th.selectedIndex]);
		if(th.params.setFocus) th.params.setFocus.focus();
	},
	
	SetClassCss : function(index){
		var li = this.list.getElementsByTagName("li");
		if(!li) return;
		if(li[index]){
			li[this.selectedIndex].className = "";
			li[index].className = "over";
			this.selectedIndex = index;
		}
	},
	
	DomKeyDown : function(e){
		var key = KeyCode(e);
		if(key == Event.KEY_RETURN && this.IsShow){
			Event.stop(e);
			this.SetData(this);
		}
	},
	
	DomKeyUp : function(e){			
		if(!this.IsShow){
			this.Pop();
			return;
		}
		var key = KeyCode(e);
		var li = this.list.getElementsByTagName("li");	
		var index = 0;
		if(key == Event.KEY_UP){			
			index = this.selectedIndex - 1;
			index = index < 0 ? this.cacheData.length - 1 : index;
			this.SetClassCss(index);
		}else if(key == Event.KEY_DOWN){
			index = this.selectedIndex + 1;
			index = index >= this.cacheData.length ? 0 : index;
			this.SetClassCss(index);
		}else{
			this.LoadData();
		}
		this.Scrolling();		
	},
	
	Scrolling : function(){
		var scrollHeight = this.list.scrollHeight;
		var listHeight = this.list.offsetHeight;
		if(this.cacheData.length == 0){
			return;
		}		
		var scrollTop = this.list.scrollTop;
		var itemHeight = this.list.getElementsByTagName("li")[0].offsetHeight;		
		var current = (this.selectedIndex + 1) * itemHeight;		
		if((current - scrollTop) >= listHeight){
		    this.list.scrollTop = current - listHeight;
		}else if(current <= scrollTop){
			this.list.scrollTop = current - itemHeight;
		}
	},
	
	SearchData : function(){
		var key = this.control.value.toLowerCase();
		this.cacheData = new Array();
		if(key == ""){
			if(this.defaultValue != ""){
				for(var i = 0; i < this.data.length; i++){
					var dataText = "|" + this.data[i][this.dataFormat[0]].toString().toLowerCase() + "|";
					var dataCaption = "|" + this.data[i][this.dataFormat[1]].toString().toLowerCase() + "|";
					var dataValue = "|" + this.data[i][this.dataFormat[2]].toString().toLowerCase() + "|";
					
					if(this.defaultValue.indexOf(dataText) != -1 || this.defaultValue.indexOf(dataCaption) != -1 || this.defaultValue.indexOf(dataValue) != -1){
						this.cacheData[this.cacheData.length] = this.data[i];
					}
				}
			}
			return;
		}
		for(var i = 0; i < this.data.length; i++){
			var dataText = this.data[i][this.dataFormat[0]].toString().toLowerCase();
			var dataCaption = this.data[i][this.dataFormat[1]].toString().toLowerCase();
			var dataValue = this.data[i][this.dataFormat[2]].toString().toLowerCase();

			if(key.length == 1){
				if(dataText.indexOf(key) == 0 || dataCaption.indexOf(key) == 0 || dataValue.indexOf(key) == 0){
					this.cacheData[this.cacheData.length] = this.data[i];
				}
			}else{
				if(dataText.indexOf(key) != -1 || dataCaption.indexOf(key) != -1 || dataValue.indexOf(key) != -1){
					this.cacheData[this.cacheData.length] = this.data[i];
				}
			}
		}
	},
	
	Finally : function(){
		if(!this.control) return;
		if(this.control.value.Trim() == ""){
			if(this.valueField) this.valueField.value = "";
			return;
		}
		if(this.valueField){
			var value = this.valueField.value.Trim();
			for(var i = 0; i < this.data.length; i++){
				if(this.data[i][this.dataFormat[2]].toString().Trim() == value){
					this.control.value = this.data[i][this.dataFormat[0]];
					break;
				}
			}
		}
	},
	
	Hide : function(){
		if(this.div && !this.IsOver){
			this.div.hide();		
			this.IsShow = false;
			this.IsOver = false;
			if(this.eventDomKeyUp) Event.stopObserving(this.control, "keyup", this.eventDomKeyUp);
			if(this.eventDomKeyDown) Event.stopObserving(this.control, "keydown", this.eventDomKeyDown);
			if(this.eventHide) Event.stopObserving(document, "click", this.eventHide);
			if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
			if(this.control) this.control.blur();
			Elan.UI.ShowSelects();
		}	
		this.Finally();
	}
};

Elan.UI.Calendar = {
	Show : function(){
		var defaults = {
			handle: null, 
			field: null, 
			nextHandle: null, 
			nextField: null, 
			beginDate: (new Date()).AsString(), 
			endDate: DateAdd("y", 100, (new Date())).AsString(), 
			week: null, 
			validateDays: null, 
			callBack: null,
			defaultDate: null,
			setFocus: null,
			autoBindDate: true
		};
		
		this.options = Object.extend(defaults, arguments[0] || {});
		if(this.options.handle){
			this.handle = $(this.options.handle);
		}else{
			alert("handle error.");
			return;
		}
				
		this.calendar = $("ElanWebCalender");		
		this.caldocument = $Frame("ElanWebCalender");		
		if(!this.caldocument || !this.caldocument.complete){
			alert("initialize error.");
			return;
		}		
		
		this.caldocument.defaultDate = this.options.defaultDate;
		this.caldocument.beginDate = this.options.beginDate.AsDate();
		this.caldocument.endDate = this.options.endDate.AsDate();		
		this.caldocument.nextHandle = this.options.nextHandle;
		this.caldocument.nextField = this.options.nextField;
		this.caldocument.autoBindDate = this.options.autoBindDate;
		if(this.options.field){
			this.caldocument.date = $F(this.options.field).AsDate();
			this.caldocument.field = $(this.options.field);
		}else{
			if(this.handle.tagName.toLowerCase() == "input" || (this.handle.type.toLowerCase() == "text" && this.handle.type == "hidden")){
				this.options.field = this.handle;
				this.caldocument.field = this.options.field;
				this.caldocument.date = $F(this.options.field).AsDate();
			}
		}
		if(this.options.week) this.caldocument.enableWeek = this.options.week.split(",");
		if(this.options.validateDays) this.caldocument.validateDays = this.options.validateDays.split(",");
		this.caldocument.callBack = this.options.callBack;
		this.caldocument.setFocus = this.options.setFocus;
		this.caldocument.calObject = this;
		this.caldocument.Init();		
		
		this.eventHide   = this.Hide.bindAsEventListener(this)
		this.eventResize = this.Resize.bindAsEventListener(this)
		Event.observe(document, "click", this.eventHide);	
		Event.observe(window, "resize", this.eventResize);
		this.calendar.show();
		this.Resize();
		return this;
	},
	
	Resize : function(){
		var pageScroll = document.viewport.getScrollOffsets();
		var pos = this.handle.viewportOffset();	
		var left = pos.left;
		var top = pageScroll[1] + pos.top + this.handle.offsetHeight;
		var cWidth = parseFloat(this.calendar.getStyle("width").replace("px", ""));
		var cHeight = parseFloat(this.calendar.getStyle("height").replace("px", ""));
		var winWidth = document.viewport.getWidth();
		var winHeight = document.viewport.getHeight();
		if((left + cWidth) > winWidth){
			left -= (left + cWidth) - winWidth;
		}
		if((top + cHeight - pageScroll[1]) > winHeight){
			top = top - this.handle.offsetHeight - cHeight - 1;
		}else{
			top += 1;
		}
		this.calendar.setStyle({left: left + "px", top: top + "px"});
		return this;
	},
	
	Hide : function(){			
		if(this.calendar) this.calendar.hide();
		if(this.eventHide) Event.stopObserving(document, "click", this.eventHide);
		if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
		return this;
	}
};

Elan.GetJson = function(data){
	if(!data) return null;
	var text = data.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
	return eval("("+ text +")");
}

Elan.Cookie = {
	Read : function(name){
		var arr = document.cookie.match(new RegExp("(^| )"+ name +"=([^;]*)(;|$)"));
		if(arr != null){
			var value = "";
			var aCharCode = arr[2].split(",");
			for(var i = 0; i < aCharCode.length; i++){
				value += String.fromCharCode(aCharCode[i]);
			}
			return value;
		}
		return "";
	},
	
	Write : function(name, value){
		if(!name) return;
		var expires = 0;
		if(arguments[2]) expire = arguments[2].toString().ToNumber(0);	
		var cookie = name + "=";
		if(value.length > 0){
			var str = "";
			for(var i = 0; i < value.length; i++){
				str += value.charCodeAt(i).toString() + ",";
			}
			str = str.substring(0, str.length - 1);
			cookie += (str);
		}		
		if(expires >= 0){
			var date = new Date();
			date.setTime(date.getTime() + (expires == 0 ? 365 : expires) * 24 * 60 * 60 * 1000);
			cookie += ";expires=" + date.toGMTString();
		}
		cookie += ";path=/";
		document.cookie = cookie;
	},
	
	Remove : function(name){
		if(!name) return;
		var date = new Date();
		date.setTime(date.getTime() - 1);
		var value = this.Read(name);
		if(value != null) document.cookie = name + "=" + value + ";expires=" + date.toGMTString();
	}
};
