function $(objName){
	if(document.getElementById){
		return document.getElementById(objName);
	}else{
		return document.all.objName;
	}
}
if( typeof $C == 'undefined' )$C = function(t){return document.createElement(t)};

function oEvent(evt){ 
	var evt = evt ? evt : (window.event ? window.event : null);
	var objSrc = (evt.target) ? evt.target : evt.srcElement;
	return(objSrc);
}

function getEvent(){
	var evt = window.event ? window.event : getEvent.caller.arguments[0];
	return(evt);
}

Function.prototype.Bind = function() { 
	var __m = this, object = arguments[0], args = new Array(); 
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function() {
		return __m.apply(object, args);
	}
};

Function.prototype.BindForEvent = function() { 
	var __m = this, object = arguments[0], args = new Array();
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function(event) {
		return __m.apply(object, [( event || window.event)].concat(args));
	}
}

function GetOffsetPos(element) {
	var posTop = 0, posLeft = 0;
	//var element = document.getElementById(element);
	do {
		posTop += element.offsetTop || 0;
		posLeft += element.offsetLeft || 0;
		element = element.offsetParent;
		} while (element);
	return [posLeft, posTop];
}


var RowOverCtrl = function () {
	this.Init.apply(this, arguments);
}

RowOverCtrl.prototype = {
	activeIndex: null,

	Init: function (oNodes) {
		this.oRows = [];
		for (var i = 0; i < oNodes.length; i++) {
			if (oNodes[i].nodeType == 1){
				this.oRows.push(oNodes[i]);
			}
		};

		for (var j = 0; j < this.oRows.length; j++) {
			this.oRows[j].onmouseover = this.bgRender.Bind(this, j);
			this.oRows[j].onmouseout = this.bgRemove.Bind(this, j);
		};
	},

	bgRender: function (_index) {
		this.oRows[_index].className = "active";
	},

	bgRemove: function (_index) {
		this.oRows[_index].className = "";
	}
}

var SearchBtnsCtrl = {
	Init: function (oTable) {
		this.oRows = oTable.tBodies[0].rows;
		this.oInputs = [];
		this.oSelects = [];

		for (var i = 0; i < this.oRows.length; i++) {
			for (var j = 0; j < this.oRows[i].cells[1].childNodes.length; j++) {
				var sTagName = this.oRows[i].cells[1].childNodes[j].tagName;
				if (sTagName) {
					switch (sTagName.toUpperCase()) {
					case "INPUT":
						this.oInputs.push(this.oRows[i].cells[1].childNodes[j]);
						break;

					case "SELECT":
						this.oSelects.push(this.oRows[i].cells[1].childNodes[j]);
						break;
					}
				}
				
			};
		};

		$("clear_btn").onclick = this.clear.Bind(this);
		$("_form").onsubmit = this.check.Bind(this);
	},

	clear: function () {
		for (var i = 0; i < this.oInputs.length; i++) {
			if (this.oInputs[i].value != "") {
				this.oInputs[i].value = this.oInputs[i].className != "date" ? "" : "任意时间";
			}
		};
		for (var j = 0; j < this.oSelects.length; j++) {
			this.oSelects[j].selectedIndex = "0";
		};
	},

	check: function () {
		for (var i = 0; i < this.oInputs.length; i++) {
			if (this.oInputs[i].value != "" && this.oInputs[i].value != "任意时间") {
				return true;
			}
		};

		if (this.oSelects[0].selectedIndex != 0) {
			return true;
		}

		alert("请填写搜索条件！");
		return false;
	}
}



function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

var PopupCtrl = {
	popupWidth: 804,
	popupHeight:328,

	Init: function () {
		this.aPageSize = getPageSize();
		this.oMask = $("mask");
		this.oPopup = $("popup");
		$("reSrc").onclick = this.show.Bind(this);
		$("close").onclick = this.hide.Bind(this);

		this.toLeft = (this.aPageSize[0] - this.popupWidth) / 2;
		this.toTop = (this.aPageSize[3] - this.popupHeight) / 2;
	},

	show: function () {
		this.oMask.style.height = this.aPageSize[1] + "px";
		this.oMask.style.display = "block";
		this.oPopup.style.left = this.toLeft + "px";
		this.oPopup.style.top = this.toTop + getPageScroll()[1] + "px";
		this.oPopup.style.display = "block";
	},

	hide: function () {
		this.oPopup.style.display = "none";
		this.oMask.style.display = "none";
	}
}


var WorkScroll = {
	sWidth: 116,
	steps: null,
	scrolling: 0,
	paceTime: 50,
	index: 0,
	Init: function () {
		this.scrollContainer = $("scroll_container");
		this.scrollContainer.scrollLeft = 0;
		this.wrap = $("work_wrap");
		this.btnPre = $("pre");
		this.btnNext = $("next");
		this.works =[];
		this.pace = this.sWidth / this.steps;

		var tempNodes = this.wrap.childNodes;
		for (var i = 0; i < tempNodes.length; i++){
			if (tempNodes[i].nodeType == 1){
				this.works.push(tempNodes[i]);
			}
		};

		if (this.works.length <= 5) {
			this.btnPre.style.visibility = "hidden";
			this.btnNext.style.visibility = "hidden";
			return ;
		}

		this.checkState();

		this.btnPre.onclick = this.movePre.Bind(this);
		this.btnNext.onclick = this.moveNext.Bind(this);

// obj_x += (cursor_x - obj_x) * k + (end_x - cursor_x)

		this.aPace = [];
		var _v = 0, k = 0.32, maxSteps = 20;
		for (var i = 0; i < maxSteps; i++) {
			var temp = _v;
			_v += (this.sWidth - _v) * k;
			this.aPace.push(Math.round(_v - temp));

			if (this.sWidth - _v < 2 || i == maxSteps - 1) {
				this.steps = this.aPace.length;
				break;
			}
		};
	},

	movePre: function () {
		if (!this.scrolling && this.index > 0) {
			this.scroll(-1);
		}
	},

	moveNext: function () {
		if (!this.scrolling && this.index < this.works.length - 5) {
			this.scroll(1);
		}
	},

	checkState: function (change) {
		if (change != undefined) {
			this.index += change;
		}

		switch (this.index) {
		case 0:
//			this.btnPre.className = "disable";
			this.btnPre.style.visibility = "hidden";
			break;
		case this.works.length - 5:
//			this.btnNext.className = "disable";
			this.btnNext.style.visibility = "hidden";
			break;
		default:
			if (this.btnPre.style.visibility == "hidden") {
				this.btnPre.style.visibility = "";
			}
			if (this.btnNext.style.visibility == "hidden") {
				this.btnNext.style.visibility = "";
			}
			break;
		}
	},

	scroll: function (direction) {
		if (this.scrolling == this.steps) {
			switch (this.direction) {
			case 1:
				this.scrollContainer.scrollLeft = this.lastPos + this.sWidth;
				break;
			case -1:
				this.scrollContainer.scrollLeft = this.lastPos - this.sWidth;
				break;
			}
			this.checkState(this.direction);
			this.scrolling = 0;
			window.clearTimeout(this.scrollTimeout);
			return ;
		}

		if (!this.scrolling) {
			this.lastPos = this.scrollContainer.scrollLeft;
			this.direction = direction;
		}

		switch (this.direction) {
		case 1:
			this.scrollContainer.scrollLeft += this.aPace[this.scrolling];
			break;
		case -1:
			this.scrollContainer.scrollLeft -= this.aPace[this.scrolling];
			break;
		}

		this.scrolling++;
		
		this.scrollTimeout = window.setTimeout(this.scroll.Bind(this), this.paceTime);
	}
}


var RateCtrl = {
	rGet: 'http://mark.sina.com.cn/v2/GetDataList.php?p_mark=hyss&i_mark=@NAME@&need=score',
	rPost: 'http://mark.sina.com.cn/v2/DoData.php?p_mark=hyss&i_mark=@NAME@&option_44=@RATE@&question[]=44&type=get&ext1=@CAT@',
	stars: [],
	Init: function () {
		this.allrate = $("allRate");
		this.oriRate = $("rate_wrap_dl");

		var scriptLoader = new IO.Script(), url = this.rGet.replace("@NAME@", shortname);
		scriptLoader.load(url, this.fill.Bind(this));

		tempNodes = $("user_rate_dl").childNodes;

		for (var i = 0; i < tempNodes.length; i++){
			if (tempNodes[i].nodeType == 1){
				this.stars.push(tempNodes[i]);
			}
		};

		for (var j = 0; j < this.stars.length; j++) {
			this.stars[j].onmouseover = this.rate.Bind(this, j);
			this.stars[j].onclick = this.postRate.Bind(this, j);
		};

		this.allrate.onmouseover = this.change.Bind(this, 0);
		this.allrate.onmouseout = this.change.Bind(this, 1);
	},

	fill: function () {
		var nRate = Math.round(window.score[shortname]);
		this.oriRate.innerHTML = "";
		for (var k = 0; k < 5; k++) {
			if (k < nRate) {
				var _dt = $C("DT");
				this.oriRate.appendChild(_dt);
			}
			else {
				var _dd = $C("DD");
				this.oriRate.appendChild(_dd);
			}
		};
	},

	postRate: function (_index) {
		var scriptLoader = new IO.Script();
		var url = this.rPost.replace("@NAME@", shortname).replace("@CAT@", category).replace("@RATE@", 175 + _index) +　"?" + (new Date()).getTime();
		scriptLoader.load(url, this.getStatus.Bind(this));
	},

	getStatus: function () {
		if (success) {
			alert("投票成功！");
		}
		else {
			alert("失败");
		}
	},

	change: function (_index) {
		switch (_index) {
		case 0:
			this.allrate.className = "rate1";
			break;

		case 1:
			this.allrate.className = "rate0";
			break;
		}
	},

	rate: function (nStars) {
		for (var i = 0; i < this.stars.length; i++) {
			if (i < nStars + 1 && this.stars[i].className != "active") {
				this.stars[i].className = "active";
			}
			else if (i >= nStars + 1 && this.stars[i].className != "") {
				this.stars[i].className = "";
			}
		};
	}
}


var Calendar = {
	colorTd: function (td) {
		td.style.backgroundColor = "#999999";
		td.style.color = "#FFFF00";
		td.style.cursor = "pointer";
	},
	discolorTd: function (td) {
		if (td.today == "today") {
			td.style.color = "#FFFFFF";
			td.style.backgroundColor = "#999999";
		}
		else {
			td.style.backgroundColor = "#FFFFFF";
			td.style.color = "";
		}
	},
	selectTd: function (day, id) {
		var targetObj = $(id);
		targetObj.value = targetObj.year.innerHTML + '-' + (targetObj.month.innerHTML * 1 < 10 ? "0" : "") + targetObj.month.innerHTML + '-' + (day * 1 < 10 ? "0" : "") + day;
		Calendar.clean(targetObj);
	},
	getMonthString: function(monthNumber) {
		if (monthNumber < 0 || monthNumber > 11) {
			return '';
		}
//		monthArr = Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
		monthArr = Array('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月');
		return monthArr[monthNumber];
	},
	moveDate: function (type, id) {
		var targetObj = $(id);
		var year = targetObj.year.innerHTML * 1;
		var month = targetObj.month.innerHTML * 1 - 1;
		switch (type) {
			case "year-1":
				year--;
				break;
			case "year+1":
				year++;
				break;
			case "month-1":
				month = (month + 11) % 12;
				break;
			case "month+1":
				month = (month + 1) % 12;
				break;
		};
		var date = targetObj.date.getDate();
		var newDate = new Date(year, month, date);
		var dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if (month == 1 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) {
			dates[1] = 29;
		}
		if (newDate.getMonth() != month) {
			date = dates[month];
		}
		targetObj.date = new Date(year, month, date);
		targetObj.reflashed = true;;
		Calendar.reflash(targetObj);
	},
	reflash: function (obj) {
		var date = obj.date;
		var day = new Date(date.getFullYear(), date.getMonth(), 1).getDay();
		var result = new String();
		result += '<table class="CalenderTableTitle" border="0" cellpadding="0" cellspacing="0">';
		result += '	<tr>';
		result += '		<td style="width: 15px;" onmouseover="Calendar.colorTd(this);" onmouseout="Calendar.discolorTd(this);" onmousedown="Calendar.moveDate(\'year-1\', \'' + obj.id + '\');">&nbsp;&laquo;&nbsp;</td>';
		result += '		<td style="width: 15px;" onmouseover="Calendar.colorTd(this);" onmouseout="Calendar.discolorTd(this);" onmousedown="Calendar.moveDate(\'month-1\', \'' + obj.id + '\');">&nbsp;&lsaquo;&nbsp;</td>';
		result += '		<td colspan="3">';
		result += '			<span>' + this.getMonthString(date.getMonth()) + '</span>';
		result += '			<span id="' + obj.id + '_calendar_month" style="display:none;">' + (date.getMonth() + 1) + '</span>';
		result += '			<span id="' + obj.id + '_calendar_year">' + date.getFullYear() + '</span>';
		//result += '			<span>Year</span>';
		result += '		</td>';
		result += '		<td style="width: 15px;" onmouseover="Calendar.colorTd(this);" onmouseout="Calendar.discolorTd(this);" onmousedown="Calendar.moveDate(\'month+1\', \'' + obj.id + '\');">&nbsp;&rsaquo;&nbsp;</td>';
		result += '		<td style="width: 15px;" onmouseover="Calendar.colorTd(this);" onmouseout="Calendar.discolorTd(this);" onmousedown="Calendar.moveDate(\'year+1\', \'' + obj.id + '\');">&nbsp;&raquo;&nbsp;</td>';
		result += '	</tr>';
		result += '<table>';
		result += '<table class="CalenderTable" border="0" cellpadding="0" cellspacing="0"><tr class="daysName"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
		var pos = 0;
		var dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if (date.getMonth() == 1 && ((date.getFullYear() % 4 == 0 && date.getFullYear() % 100 != 0) || date.getFullYear() % 400 == 0)) {
			dates[1] = 29;
		}
		for (var i = 0; i < day; i++) {
			if (pos == 0) {
				result += '<tr>';
			}
			pos++;
			result += '<td></td>';
			if (pos == 7) {
				result += '</tr>';
				pos = 0;
			}
		}
		for (var i = 1; i < dates[date.getMonth()] + 1; i++) {
			if (pos == 0) {
				result += '<tr>';
			}
			pos++;
			result += '<td onmouseover="Calendar.colorTd(this);" onmouseout="Calendar.discolorTd(this);" onmousedown="Calendar.selectTd(' + i + ', \'' + obj.id + '\');" ' + ((i == date.getDate() && obj.reflashed != true) ? ' style="background-color:#999999;color:#FFFFFF;" today="today"' : ' style="background-color:#FFFFFF;"') + '>' + i + '</td>';
			if (pos == 7) {
				result += '</tr>';
				pos = 0;
			}
		}
		for (var i = 0; i < (7 - (day + dates[date.getMonth()]) % 7) % 7; i++) {
			if (pos == 0) {
				result += '<tr>';
			}
			pos++;
			result += '<td></td>';
			if (pos == 7) {
				result += '</tr>';
				pos = 0;
			}
		}
		result += '</table>';

		obj.element.innerHTML = result;
		
		obj.year = $(obj.id + "_calendar_year");
		obj.month = $(obj.id + "_calendar_month");
	},
	focusObj: function (obj) {
		obj.reflashed = false;
		
		var tempOuterId = obj.id + "_calendar";
		if (!$(tempOuterId)){
			var tempOuter = document.createElement("DIV");
			
			var tempWidth = obj.clientWidth;

			tempOuter.id = tempOuterId;
			tempOuter.className = "Calender";

			var _XY = GetOffsetPos(obj);
			tempOuter.style.left = _XY[0] + "px";
			tempOuter.style.top = _XY[1] + "px";

			document.body.insertBefore(tempOuter, document.body.childNodes[0]);
//			document.body.appendChild(tempOuter);
		}

		$(tempOuterId).style.display = "";
		obj.element = $(obj.id + "_calendar");
		if (!/\d{4}\-\d{1,2}\-\d{1,2}/.test(obj.value)) {
			obj.value = "";
			obj.date = new Date();
			Calendar.reflash(obj);
//			Calendar.clean(obj);
		}
		else {
			var arr = obj.value.match(/\d{4}\-\d{1,2}\-\d{1,2}/)[0].split("-");

			obj.date = new Date(arr[0] * 1, arr[1] - 1, arr[2] * 1)
			Calendar.reflash(obj);
		}
	},
	clean: function (obj) {
		obj.reflashed = true;
		
		var tempOuterId = obj.id + "_calendar";

		$(tempOuterId).style.display = "none";

	},
	blurObj: function (obj) {
		if (obj.value == "") {
			obj.value = "任意时间";
		}
		else if (!/\d{4}\-\d{1,2}\-\d{1,2}/.test(obj.value)) {
			obj.value = "任意时间";
			alert('请按"2008-01-01"格式输入时间，或直接从弹出日历中选择日期。');
		}
		Calendar.clean(obj);
	}
};




var Nav = function (arrayData) {
	this.element = $("nav");
	var table = $C("table");
	table.className = "table";
	table.cellPadding = 0;
	table.cellSpacing = 0;
	table.border = 0;
	var line = table.insertRow(0);
	for (var i = 0; i < arrayData.length; i++) {
		var cell = line.insertCell(i);
		cell.className = i == 0 ? "index" : "off";
		cell.onmouseover = function () {
			this.className = this.className == "index" ? "index" : "on";
		};
		cell.onmouseout = function () {
			this.className = this.className == "index" ? "index" : "off";
		};
		var link = $C("a");
		link.target = "_blank";
		link.href = arrayData[i][0];
		link.innerHTML = arrayData[i][1];
		cell.appendChild(link);
	}
	this.element.appendChild(table);
};

function generateNav() {
	window.nav = new Nav(
		[
			["http://finance.sina.com.cn/", "财经首页"],
			["http://finance.sina.com.cn/stock/index.shtml", "股票首页"],
			["http://stock.finance.sina.com.cn/", "行情"],
			["http://finance.sina.com.cn/column/jsy.html", "大盘"],
			["http://finance.sina.com.cn/column/ggdp.html", "个股"],
			["http://finance.sina.com.cn/column/ywgg.html", "要闻"],
			["http://finance.sina.com.cn/column/ssgs.html", "公司"],
			["http://finance.sina.com.cn/stock/newstock/index.shtml", "新股"],
			["http://finance.sina.com.cn/column/data.html", "数据"],
			["http://finance.sina.com.cn/stock/reaserchlist.shtml", "报告"],
			["http://finance.sina.com.cn/bbs/index.shtml", "论坛"],
			["http://finance.sina.com.cn/stock/usstock/index.shtml", "美股"],
			["http://finance.sina.com.cn/stock/hkstock/index.shtml", "港股"],
			["http://biz.finance.sina.com.cn/hq/", "行情中心"],
			["http://vip.stock.finance.sina.com.cn/portfolio/main.php", "自选股"]
		]
	);
}

function main_index () {
	var RowCtrl = new RowOverCtrl($("search_detail").tBodies[0].rows);
	SearchBtnsCtrl.Init($("search_detail"));
}

function main_result () {
	var RowCtrl = new RowOverCtrl($("search_detail").tBodies[0].rows);
	var RowCtrl = new RowOverCtrl($("list_dl").childNodes);
	SearchBtnsCtrl.Init($("search_detail"));
	PopupCtrl.Init();
}

function main() {
	WorkScroll.Init();
}
