var isIE = (navigator.appName.indexOf("Microsoft") > -1);
var d = document;
var returnlogin = "http://common.hkjc.com/corporate/ProcessLogon.aspx?Lang=C";
var returnpreference = "http://common.hkjc.com/corporate/ProcessLogon.aspx?Lang=C&Pref=Y";
var returnlogout = "http://common.hkjc.com/corporate/ProcessLogon.aspx?Lang=C&SignOut=true";
var returnregister = "http://common.hkjc.com/corporate/ProcessLogon.aspx?Lang=C&Reg=Y";
var returnFAQ = "http://common.hkjc.com/utility/faq/chinese/general/index.aspx";

var sectionArray = new Array('football', 'entertainment', 'racing', 'member', 'charities', 'corporate');
if (!levelArray)	var levelArray = new Array();

//Check Language Cookie
checkLangCookie();

function checkLangCookie()
{
	if (!getCookie('language'))	return;
	
	var cookieLang = getCookie('language');
	var array = new Array('english', 'chinese');
	var lang;
	var url = top.location.href;
	if (top.location.hash)	url = top.location.href.replace(top.location.hash, '');
	
	for (var i=0; i<array.length; i++)
	{
		if (url.indexOf('/' + array[i] + '/') < 0)	continue;
		lang = array[i];
	}
	if (lang != cookieLang)	
	{
		url = url.replace('/' + lang + '/', '/' + cookieLang + '/');
		window.top.location.href = url;
	}
}

function init()
{
	removeImg();
	new setNav();
	setTimeout(function(){setFooterYear();}, 100);
}

function getLevel()
{
	var url = location.pathname;
	var array = url.split('/');
	
	for (var i=0; i<array.length; i++)
	{
		if (array[i].indexOf('_') >= 0)
		{
			
			var array1 = array[i].split('_');
			for (var j=0; j<array1.length; j++)
			{
				levelArray.push(array1[j]);
			}
			
		}
		else
		{
			levelArray.push(array[i]);
			
		}
	}
	
	levelArray.shift();
	//levelArray.shift();
	
	var obj = levelArray[levelArray.length-1];
	if (obj != 'index.html')
	{
		levelArray[levelArray.length-1] = obj.replace('.aspx', '');
	}
	else
	{
		levelArray.pop();
	}
	//alert(levelArray);
}

function setNav()
{
	var mainNav = d.getElementById('mainNav');
	var topNav = getElementsByClassName(mainNav, 'nav')[0];
	//var topSubNav = getElementsByClassName(mainNav, 'subNav')[0];
	//var navArray = new Array(topNav, topSubNav);
	var navArray = new Array(topNav);
	var self = this;
	
	this.init = function()
	{
		//this.leftNavOpen();
		
		//Highlight Nav
		for (var i=0; i<navArray.length; i++)
		{
			this.setHighlightNav(i);
		}
	};
	
	this.setHighlightNav = function(id)
	{
		var nav = navArray[id];
		var a = nav.getElementsByTagName('a');
		
		/*if (id == 1)
		{
			var ul = topSubNav.getElementsByTagName('ul')[0];
			for (var i=0; i<a.length; i++)
			{
				a[i].onmouseover = function()
				{
					if (this.className.indexOf(' active') >= 0)	return;
					self.topSubNavOver(this, true);
				}
				a[i].onmouseout = function()
				{
					if (this.className.indexOf(' active') >= 0)	return;
					self.topSubNavOver(this, false);
				}
				
				new this.setMenu(a[i]);
				
				//Highlight Nav
				if (!levelArray[id])	continue;
				if (a[i].rel == levelArray[id])
				{
					self.topSubNavOver(a[i], true);
					a[i].className += ' active';
				}
			}
		}
		else
		{*/
			for (var i=0; i<a.length; i++)
			{
				/*if (!a[i].rel)	continue;
				if (!a[i].getElementsByTagName('img').length)	continue;
				
				a[i].img = a[i].getElementsByTagName('img')[0];
				a[i].oldSrc = a[i].img.src;
				a[i].newSrc = a[i].oldSrc.replace('.gif', '_over.gif');
				
				a[i].onmouseover = function()
				{
					if (this.className.indexOf(' active') >= 0)	return;
					this.img.src = this.newSrc;
				}
				a[i].onmouseout = function()
				{
					if (this.className.indexOf(' active') >= 0)	return;
					this.img.src = this.oldSrc;
				}
				
				//Highlight Nav
				if (!levelArray[id])	continue;
				if (a[i].rel == levelArray[id])
				{
					a[i].className += ' active';
					a[i].img.src = a[i].newSrc;
				}*/
				
				new this.setMenu(a[i]);
			}
		//}
	};
	
	this.leftNavOpen = function(menu)
	{
		if (!d.getElementById('leftNav'))	return;
		
		var leftNav = d.getElementById('leftNav');
		if (!getElementsByClassName(leftNav, levelArray[1]).length)	return;
		var menu = getElementsByClassName(leftNav, levelArray[1])[0];
		menu.style.display = 'block';
		navArray.push(menu);
		
		this.leftSubNavOpen(menu);
	};
	
	this.leftSubNavOpen = function(menu)
	{
		if (!getElementByRel(menu, levelArray[2]))	return;
		var dd = getElementByRel(menu, levelArray[2]).parentNode;
		
		if (!dd.getElementsByTagName('dl').length)	return;
		var dl = dd.getElementsByTagName('dl')[0];
		
		dl.style.display = 'block';
		
		if (!getElementByRel(dl, levelArray[3]))	return;
		var a = getElementByRel(dl, levelArray[3]);
		a.className += ' active';
	};
	
	this.topSubNavOver = function(btn, over)
	{
		var ul = topSubNav.getElementsByTagName('ul')[0];
		
		if (over)
		{
			if (ul.className.indexOf('dim') < 0)	ul.className += ' dim';
			//btn.className += ' active';
			btn.parentNode.style.zIndex = 100;
		}
		else
		{
			if (!levelArray[1])	ul.className = ul.className.replace(/dim/, '');
			//btn.className = btn.className.replace(/active/, '');
			btn.parentNode.style.zIndex = 1;
		}
	};
	
	this.setMenu = function(btn)
	{
		var li = btn.parentNode;
		var time;
		
		var mode = (btn.parentNode.nodeName.toUpperCase() == 'LI')?	1:2;
		//if (mode == 2)
		//{
			if (btn.getElementsByTagName('img').length)
			{
				btn.img = btn.getElementsByTagName('img')[0];
				btn.oldSrc = btn.img.src;
				btn.newSrc = btn.oldSrc.replace('.gif', '_over.gif');
			}
		//}
		btn.onmouseover	= function() {btn.hit = true;	showLayer(1, mode); self.btnMenuHit = true;};
		btn.onmouseout	= function() {btn.hit = false;	showLayer(0, mode); self.btnMenuHit = false;};
		
		if (getElementsByClassName(li, 'pullmenu', true).length)
		{
			var menu = getElementsByClassName(li, 'pullmenu', true)[0];
			menu.onmouseover	= function() {btn.hit = true;	showLayer(1, mode); self.btnMenuHit = true;};
			menu.onmouseout		= function() {btn.hit = false;	showLayer(0, mode); self.btnMenuHit = false;};
			time = 0;
			
			if (mode == 2)
			{
				btn.className += ' subArrow';
				var span = d.createElement('span');
				btn.appendChild(span);
			}
			setTimeout(function(){menu.style.height = menu.offsetHeight - 9 + 'px';}, 300);
		}
		else
		{
			time = 0;
		}
		
		//Check Domain
		if (location.hostname.indexOf('teamsite.hkjc.com') >= 0)
		{
			var url = btn.href;
			var array = url.split('/');
			if (!array[2])	return;
			var array1 = array[2].split('.');
			var subDomain = array1[0];
			btn.href = url.replace(subDomain + '.', 'teamsite.');
			return;
		}
		var url = btn.href;
		//url = url.replace('www.', '');
		var array = url.split('/');
		var subDomain = url.substring(7, url.indexOf('.'));
		var section = null;
		for (var i=0; i<sectionArray.length; i++)
		{
			if (sectionArray[i] == array[3])
			{
				section = array[3];
				break;
			}
		}
		if (section)	btn.href = url.replace(subDomain, section);
		
		function showLayer(over, mode)
		{
			if (over == 1)
			{
				if (btn.className.indexOf('active') < 0)
				{
					btnOver(btn, mode, true);
					//if (mode == 1)	self.topSubNavOver(btn, true);
					
				}
				if (menu)
				{
					menu.style.visibility = 'visible';
					self.menuHideSelect(menu, 'hidden');
				}
			}
			else
			{	
				setTimeout(function()
				{
					if (btn.hit)	return;
					//if (btn.rel != levelArray[1])
					//{
						btnOver(btn, mode, false);
						//if (mode == 1)	self.topSubNavOver(btn, false);
					//}
					if (menu)
					{
						menu.style.visibility = 'hidden';
						if (!self.btnMenuHit)	self.menuHideSelect(menu, 'visible');
					}
				}, time);
			}
		}
		
		function btnOver(btn, mode, over)
		{
			if (over)
			{
				btn.className += ' active';
			}
			else
			{
				btn.className = btn.className.replace(/active/, '');
			}
			
			if (btn.img)
			{	
				if (over)
				{
					//if (btn.className.indexOf(' active') >= 0)	return;
					btn.img.src = btn.newSrc;
				}
				else
				{
					//if (btn.className.indexOf(' active') >= 0)	return;
					btn.img.src = btn.oldSrc;
				}
			}
		}
	};

	this.menuHideSelect = function(div, boolHide)
	{
		var selectHide = false;
		if (isIE)
		{
			var str = Number(navigator.appVersion.indexOf('MSIE ')) + 5;
			var version = Number(navigator.appVersion.substring(str, (str+1)));
			if (version < 7)	selectHide = true;
		}
		if (!selectHide)	return;
		
		var selects = d.getElementsByTagName('select');
		for (var i=0; i<selects.length; i++)
		{
			selects[i].style.visibility = boolHide;
		}
	};
	
	this.init();
}

function highlightLeftNav()
{
	if (!d.getElementById('leftNav'))	return;
	var leftNav = d.getElementById('leftNav');
	
	if (!getElementsByClassName(leftNav, levelArray[0]).length)	return;
	var menu = getElementsByClassName(leftNav, levelArray[0])[0];
	menu.style.display = 'block';
	
	setLeftNav(menu);
	
	function setLeftNav(menu)
	{
		var a = menu.getElementsByTagName('a');
		
		for (var i=0; i<a.length; i++)
		{
			a[i].img = a[i].getElementsByTagName('img')[0];
			a[i].oldSrc = a[i].img.src;
			a[i].newSrc = a[i].img.src.replace('.gif', '_over.gif');
			
			a[i].onmouseover = function()
			{
				if (this.className.indexOf(' active') >= 0)	return;
				this.img.src = this.newSrc;
			}
			a[i].onmouseout = function()
			{
				if (this.className.indexOf(' active') >= 0)	return;
				this.img.src = this.oldSrc;
			}
			
			//Highlight Left Nav
			if (a[i].rel == levelArray[1])
			{
				a[i].className += ' active';
				a[i].img.src = a[i].newSrc;
			}
		}
	}
}

function NewWindow(mypage, myname, w, h, scroll,resizable) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable='+resizable+','
	win = window.open(mypage, myname, winprops)
	win.self.focus()
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function createImg(src, alt, w, h, link, t, className)
{
	var img = d.createElement('img');
	if (src)	img.setAttribute('src', src);
	if (alt)	img.setAttribute('alt', alt);
	//add by Alex Lee
	if (alt)	img.setAttribute('title', alt);
	//add by Alex Lee
	if (w)	img.setAttribute('width', w);
	if (h)	img.setAttribute('height', h);
	if (className)	img.className = className;
	
	if (link)
	{
		img.setAttribute('border', 0);
		
		var a = d.createElement('a');
		a.setAttribute('href', link);
		if (t && typeof(t) != 'undefined')	a.setAttribute('target', t);
		a.appendChild(img);
		return a;
	}
	else
	{	
		return img;
	}
}

function createA(link, t, txt, id, className)
{		
	var a = d.createElement('a');
	if (link)	a.setAttribute('href', link);
	if (t && typeof(t) != 'undefined')	a.setAttribute('target', t);
	
	//if (txt)	a.appendChild(d.createTextNode(txt));
	if (txt)	a.innerHTML = txt;
	if (id)	a.setAttribute('id', id);
	if (className)	a.className = className;
	
	return a;
}

function createDiv(id, className, txt)
{		
	var div = d.createElement('div');
	if (id)	div.setAttribute('id', id);
	if (className)	div.className = className;
	//if (txt)	div.appendChild(d.createTextNode(txt));
	if (txt)	div.innerHTML = txt;
	return div;
}

function createTag(tag, id, className)
{		
	var div = d.createElement(tag);
	if (id)	div.setAttribute('id', id);
	if (className)	div.className = className;
	return div;
}

function createInput(name, type, value, className)
{		
	var input = d.createElement('input');
	if (name)	input.setAttribute('name', name);
	if (type)	input.setAttribute('type', type);
	if (value)	input.setAttribute('value', value);
	if (className)	input.className = className;
	return input;
}

function setChildNodes(obj, tagName)
{
	var array = new Array();
	
	for (var i=0; i<obj.childNodes.length; i++)
	{
		if (tagName)
		{
			//alert(obj.childNodes[i].tagName)
			if (obj.childNodes[i].tagName != tagName)	continue;
		}
		if (obj.childNodes[i].toString().toLowerCase().indexOf('text') >= 0)	continue;
		array.push(obj.childNodes[i]);
	}
	
	return array;
}

function getElementsByClassName(p, c, selected)
{
	var array = new Array();
	var tags = p.getElementsByTagName('*');
	
	for (var i=0; i<tags.length; i++)
	{
		if (!tags[i].className)	continue;
		if (selected)
		{
			if (tags[i].className.indexOf(c) >= 0)	array.push(tags[i]);
		}
		else
		{
			if (tags[i].className == c)	array.push(tags[i]);
		}
	}
	
	return array;
}

function getElementByRel(parent, obj)
{
	var a = parent.getElementsByTagName('a');
	for (var i=0; i<a.length; i++)
	{
		if (a[i].rel == obj)
		{
			return a[i];
		}
	}
}

function GetParam(name)
{
	var start=location.search.indexOf("?"+name+"=");
	if (start<0) start=location.search.indexOf("&"+name+"=");
 	if (start<0) return '';
 	start += name.length+2;
 	var end=location.search.indexOf("&",start)-1;
 	if (end<0) end=location.search.length;
 	var result=location.search.substring(start,end);
 	var result='';
 	for(var i=start;i<=end;i++)
 	{
 		var c=location.search.charAt(i);
 		result=result+(c=='+'?' ':c);
 	}
 	//alert(unescape(result));
 	return unescape(result);
}

function startFading(el, fadeOut)
{
  if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  //el.style.visibility = 'visible';
  //el.style.zIndex = 2;
  
  if (!fadeOut)
  {
	  setOpacity(el, 0);
	  fadeImage(el, 0);
  }
  else
  {
	  setOpacity(el, 100);
	  fadeOutImage(el, 100);
  }
}

function fadeImage(el, currentOpacity)
{
  currentOpacity += 10;

  if (currentOpacity > 100)
  {
    setOpacity(el, 100);
    //el.style.zIndex = 1;
	if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  }
  else
  {
    setOpacity(el, currentOpacity);
    el.fadinTimeout = setTimeout(function() { fadeImage(el, currentOpacity); }, 30);
  }
}

function fadeOutImage(el, currentOpacity)
{
  currentOpacity -= 10;

  if (currentOpacity < 0)
  {
    setOpacity(el, 0);
    //el.style.zIndex = 1;
	if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  }
  else
  {
    setOpacity(el, currentOpacity);
    el.fadinTimeout = setTimeout(function() { fadeOutImage(el, currentOpacity); }, 30);
  }
}

function setOpacity(el, opacity)
{
	opacity /= 100;
	el.style.opacity = opacity;
	el.style.MozOpacity = opacity;
	el.style.filter = "alpha(opacity=" + (opacity*100) + ")";
}

function getServerTime(type)
{
	var xmlHttp = false;

	//get server time
	try
	{
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e2) {}
	}
	
	if (!xmlHttp && typeof(XMLHttpRequest) != 'undefined')
	{
		xmlHttp = new XMLHttpRequest();
	}

	xmlHttp.open('GET', '/home/common/chinese/images/logo_hkjc.gif', false);
	xmlHttp.setRequestHeader('Range', 'bytes=-1');
	xmlHttp.send(null);

	severtime = new Date(xmlHttp.getResponseHeader('Date'));
	//alert('severtime:  ' + severtime)
	
	//get server date
	var year = severtime.getFullYear();
	var month = severtime.getMonth() + 1;
	var date = severtime.getDate();

	//get server time
	var hour = severtime.getHours();
	var minu = severtime.getMinutes();
	var seco = severtime.getSeconds();
	var time = severtime.getTime();
	
	if (type == 'date')
	{
		return severtime;
	}
	else if (type == 'year')
	{
		return year;
	}
	else
	{
		return time;
	}
}

function setCookie(name, value, expires, path, domain, secure)
{	
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

	document.cookie = curCookie;
}

function getCookie(name)
{
	if (document.cookie.indexOf(name) < 0)	return null;
	
	var startStr = document.cookie.indexOf(name) + name.length + 1;
	var endStr = document.cookie.indexOf(";", startStr);
	if (endStr == -1)	endStr = document.cookie.length;
	return unescape(document.cookie.substring(startStr, endStr));
}

function changeLanguage()
{
	var array = new Array('english', 'chinese');
	var lang;
	var url = top.location.href;
	if (top.location.hash)	url = top.location.href.replace(top.location.hash, '');
	
	for (var i=0; i<array.length; i++)
	{
		if (url.indexOf('/' + array[i] + '/') < 0)	continue;
		
		for (var j=0; j<array.length; j++)
		{
			if (url.indexOf('/' + array[j] + '/') >= 0)	continue;
			url = url.replace('/' + array[i] + '/', '/' + array[j] + '/');
			lang = array[j];
			break;
		}
		break;
	}
	//Check default no language homepage
	if (!lang)
	{
		lang = array[0];
		url = '/home/' + lang + '/index.asp';
	}
	
	var expires = new Date();
	expires.setTime(expires.getTime()+(365*24*60*60*1000));
	setCookie('language', lang, expires, '/', location.domain);
	
	window.top.location.href = url;
}

function setScroll(container, sBar)
{
	var nav = d.getElementById(container);
	var scroll = d.getElementById(sBar);
	var total;
	var scroller;
	var scrollbar;
	var self = this;
	
	this.init = function ()
	{
		//Set Container's Width
		var h = nav.parentNode.offsetHeight;
		
		while (nav.offsetHeight > nav.parentNode.offsetHeight)
		{
			var num = nav.offsetWidth;
			num ++;
			nav.style.width = num + 'px';
		}
		//alert(nav.offsetWidth + '  :  ' + nav.parentNode.offsetWidth)
		//alert(nav.offsetHeight + '  :  ' + nav.parentNode.offsetHeight)
		
		scroller  = new Scrolling.Scroller(nav, scroll.offsetWidth, scroll.offsetHeight);
		scrollbar = new Scrolling.Scrollbar(scroll, scroller, new Scrolling.ScrollTween());
	};
	
	this.init();
}

function setHomeNews()
{
	var whatsnew = d.getElementById('whatsnew');
	var events = d.getElementById('events');
	var whatsnewEvent;
	var eventsEvent;
	var root = this;
	
	this.init = function()
	{
		for (var i=0; i<homeNewsArray.length; i++)
		{
			new this.genNews(homeNewsArray[i].id, homeNewsArray[i]);
		}
		whatsnewEvent = new this.setOpen(whatsnew);
		eventsEvent = new this.setOpen(events);
	};
	
	this.genNews = function(id, array)
	{
		if (!d.getElementById(id))	return;
		var obj = d.getElementById(id);
		
		var nav = getElementsByClassName(obj, 'nav')[0];
		var img = nav.getElementsByTagName('img')[0];
		img.src = array.titleImg;
		img.alt = array.title;
		
		var mask = getElementsByClassName(obj, 'mask')[0];
		var img = mask.getElementsByTagName('img')[0];
		img.src = array.img;
		img.alt = array.imgAlt;
		
		var ul = mask.getElementsByTagName('ul')[0];
		ul.innerHTML = '';
		for (var i=0; i<array.content.length; i++)
		{
			var newsArray = array.content[i];
			var li = d.createElement('li');
			var a = createA(newsArray.link, newsArray.target);
			var strong = d.createElement('span');
			strong.innerHTML = newsArray.title;
			a.appendChild(strong);
			var str = newsArray.description.replace('<p>', '');
			str = str.replace('</p>', '');
			a.innerHTML += str;
			li.appendChild(a);
			ul.appendChild(li);
		}
	};
	
	this.boxOpen = function(id, isOpen)
	{
		if (id == 'whatsnew')
		{
			whatsnewEvent.boxOpen(!isOpen);
			eventsEvent.boxOpen(isOpen);
		}
		else
		{
			whatsnewEvent.boxOpen(isOpen);
			eventsEvent.boxOpen(!isOpen);
		}
	};
	
	this.setOpen = function(obj)
	{
		var mask = getElementsByClassName(obj, 'mask')[0];
		var btnEnlarge = getElementsByClassName(obj, 'nav')[0];
		var boxIsOpen = false;
		var self = this;
		
		//mask.initH = mask.offsetHeight;
		//mask.endH = mask.scrollHeight;
		mask.initH = 0;
		mask.endH = 238;
		
		btnEnlarge.onclick = function()
		{
			root.boxOpen(obj.id, boxIsOpen);
		}
		
		this.boxOpen = function(isOpen)
		{
			if (isOpen)
			{
				btnEnlarge.className += ' active';
				mask.H = mask.endH;
			}
			else
			{
				btnEnlarge.className = btnEnlarge.className.replace(/active/, '');
				mask.H = mask.initH;
			}
			
			this.motion(mask);
			boxIsOpen = isOpen;
		};
		
		this.motion = function(obj, start)
		{
			if (start)
			{
				obj.style.height = obj.H + 'px';
				return;
			}
			
			obj.objH = obj.offsetHeight;
			
			obj.goStep = (obj.H - obj.objH)/4;
			if (obj.goStep > 0)	obj.goStep = Math.ceil(obj.goStep);
			if (obj.goStep < 0)	obj.goStep = Math.floor(obj.goStep);

			if (!(Math.abs(obj.objH - obj.H) < 1))
			{
				obj.objH += obj.goStep;
				obj.timeOut = setTimeout(function(){self.motion(obj);}, 10);
			}
			else
			{
				obj.objH = obj.H;
				clearTimeout(obj.timeOut);
			}
			
			obj.style.height = obj.objH + 'px';
			//window.status = obj.offsetHeight + '  :  ' + obj.H;
		};
	};
	
	this.init();
}

if (!homeFeatureObj1)	var  homeFeatureObj1 = new Object();
if (!homeFeatureObj2)	var  homeFeatureObj2 = new Object();
if (!homeFeatureObj3)	var  homeFeatureObj3 = new Object();

function genHomeFeature(id)
{
	var obj = eval('homeFeatureObj' + id);
	//var innerContent = d.getElementById('innerContent');
	//var homeItem = getElementsByClassName(innerContent, 'homeItem')[id - 1];
	//var homeItem = getElementsByClassName(d.body, 'homeItem')[id - 1];
	var homeItem = d.getElementById('homeFeature'+id);
	var detail = getElementsByClassName(homeItem, 'detail')[0];
	var self = this;
	
	this.init = function()
	{
		if (obj.title)	this.genDetails();
	};
	
	this.genDetails = function()
	{
		var img = homeItem.getElementsByTagName('img')[0];
		img.src = obj.img;
		img.alt = obj.imgAlt;
		//add by Alex Lee
		img.title = obj.imgAlt;
		//add by Alex Lee
		var a = createA(obj.link, obj.target);
		var strong = d.createElement('strong');
		strong.innerHTML = obj.title;
		a.appendChild(strong);
		a.innerHTML += '<br />' + obj.content;
		detail.appendChild(a);
		
		var more = getElementsByClassName(homeItem, 'more')[0];
		more.href = obj.moreLink;
		more.target = obj.moreTarget;
		
		//alert(obj.title + '  :  ' + homeItem.innerHTML)
	};
	
	this.init();
}

function setMainVisual(obj)
{
	var container = d.getElementById(obj);
	var imgs = container.getElementsByTagName('img');
	var highlightImg;
	var total = imgs.length;
	var index = 1;
	var curIndex = 0;
	var timeout;
	var time = 5000;
	var self = this;
	
	this.init = function()
	{
		this.changeImg(0);
		if (total > 1)	this.autoChange();
	};
	
	this.changeImg = function(id)
	{
		var img = imgs[id];
		img.style.display = 'block';
		if (highlightImg)	highlightImg.style.zIndex = index;
		index ++;
		img.style.zIndex = index;
		startFading(img);
		highlightImg = img;
	};
	
	this.autoChange = function()
	{
		clearInterval(timeout);
		
		timeout = setInterval(function()
		{
			curIndex ++;
			if (curIndex >= total)	curIndex = 0;
			
			self.changeImg(curIndex);
		}, time);
	};
	
	this.init();
}

function listScroll(obj, autoPlay)
{
	var container = d.getElementById(obj);
	var div  = setChildNodes(container)[0];
	var timeOutSpeed = 30;
	var containerW = container.offsetWidth;
	var w = div.offsetWidth;
	var timeOut;
	var timeOut2;
	var self = this;
	
	this.init = function()
	{	
		container.onmouseover	= function() {self.stopScroll();};
		container.onmouseout	= function() {self.autoScrollStart();};
		
		if (autoPlay)	this.autoScrollStart();
	};
	
	this.reset = function()
	{
		div.style.left = 0;
	};
	
	this.autoScrollStart = function()
	{
		this.stopScroll();
		timeOut2 = setTimeout(function(){self.autoScroll();}, 1000);
	};
	
	this.autoScroll = function()
	{
		this.stopScroll();
		this.motion();
	};
	
	this.motion = function()
	{
		var objL = div.offsetLeft;
		objL --;
		if (objL < -w)	objL = containerW;
		
		div.style.left = objL + 'px';
		
		timeOut = setTimeout(function() {self.motion();}, timeOutSpeed);
	};
	
	this.stopScroll = function()
	{
		clearTimeout(timeOut);
		clearTimeout(timeOut2);
	};
	
	this.init();
}

function removeImg()
{
	if (d.getElementById('headerImg'))
	{
		var headerImg = d.getElementById('headerImg');
		headerImg.parentNode.parentNode.removeChild(headerImg.parentNode);
	}
	
	if (d.getElementById('mainNavImg'))
	{
		var mainNavImg = d.getElementById('mainNavImg');
		mainNavImg.parentNode.parentNode.removeChild(mainNavImg.parentNode);
	}
	
	if (d.getElementById('seoImg'))
	{
		var seoImg = d.getElementById('seoImg');
		seoImg.parentNode.parentNode.removeChild(seoImg.parentNode);
	}
	
	if (d.getElementById('footerImg'))
	{
		var footerImg = d.getElementById('footerImg');
		footerImg.parentNode.parentNode.removeChild(footerImg.parentNode);
	}
}

function genEmergencyMessage()
{
	var array = messageArray[0];
	var str = '';
	var self = this;
	
	this.init = function()
	{
		if (array.show != 'true')	return;
		
		/*var emergency = d.getElementById('emergency');
		emergency.getElementsByTagName('p')[0].innerHTML = array.description;*/
		
		var emergency = createDiv('emergency');
		str += '<img alt="Emergency Message" src="/home/common/chinese/images/title_emergency.gif"><br />';
		str += '<div id="emergencyMessage">';
		str += '<p>' + array.description + '</p>';
		str += '</div>';
		emergency.innerHTML = str;
		emergency.style.display = 'block';
		
		if (d.getElementById('newsHeadlines'))
		{
			var newsHeadlines = d.getElementById('newsHeadlines');
			newsHeadlines.parentNode.insertBefore(emergency, newsHeadlines);
		}
		else
		{
			var homeFeature1 = d.getElementById('homeFeature1');
			homeFeature1.parentNode.parentNode.insertBefore(emergency, homeFeature1.parentNode);
		}
		
		new listScroll('emergencyMessage', true);
		
		return;
		
		var y = emergency.parentNode.offsetTop + emergency.offsetHeight + 10;
		
		//Home Landing
		var homeItem = getElementsByClassName(d.body, 'homeItem');
		for (var i=0; i<homeItem.length; i++)
		{
			homeItem[i].parentNode.style.top = y + 'px';
		}
	};
	
	this.init();
}

function setPromoPopup(link, w, h, scroll, resizable, probability)
{
	if (!link || link == '')	return;
	var probability = probability/100;
	
	var randomNum = Math.ceil(Math.random()*10);
	probability = 10 - Number(probability)*10;
	if (randomNum < probability)	return;
	//alert (randomNum + '  :  ' + probability);
	
	var cookieName = 'promoPopupLink';
	
	if (getCookie(cookieName))
	{
		if (getCookie(cookieName) == link)	return;
	}
	var expires = new Date();
	expires.setTime(expires.getTime()+(365*24*60*60*1000));
	setCookie(cookieName, link, expires, '/', location.domain);
	
	NewWindow(link, 'hkjcPromo', w, h, scroll, resizable);
}

function setFooterYear()
{
	if (!d.getElementById('footer'))	return;
	var footer = d.getElementById('footer');
	var copyright = getElementsByClassName(footer, 'copyright')[0];
	var year = getServerTime('year');
	
	copyright.innerHTML = '版權所有 不得轉載 &copy; 2000-' + year + ' 香港賽馬會';
}

function setNewsHeadlines()
{
	if (!d.getElementById('newsHeadlines'))	return;
	
	var container = d.getElementById('newsHeadlines');
	var span = container.getElementsByTagName('span')[0];
	var array = newsHeadlinesArray;
	var total = array.length;
	var highlightA;
	var curIndex = 0;
	var timeout;
	var time = 5000;
	var self = this;
	
	this.init = function()
	{
		this.changeNews(0);
		if (total > 1)	this.autoChange();
	};
	
	this.changeNews = function(id)
	{
		var obj = array[id];
		
		if (highlightA)	startFading(highlightA, true);
		
		setTimeout(function()
		{
			var a = createA(obj.link, obj.target, obj.title);
			span.innerHTML = '';
			span.appendChild(a);
			startFading(a);
			highlightA = a;
		}, 500);
	};
	
	this.autoChange = function()
	{
		clearInterval(timeout);
		
		timeout = setInterval(function()
		{
			curIndex ++;
			if (curIndex >= total)	curIndex = 0;
			
			self.changeNews(curIndex);
		}, time);
	};
	
	this.init();
}

function setSpotlight()
{
	if (!d.getElementById('spotlight'))	return;
	
	var container = d.getElementById('spotlight');
	var details = getElementsByClassName(container, 'details')[0];
	var obj = spotlightobj;
	var self = this;
	
	this.init = function()
	{
		details.innerHTML = '';
		
		var titleImg = createImg(obj.titleImg, obj.titleImgAlt);
		var img = createImg(obj.img, obj.imgAlt, '', '', obj.link, obj.target);
		details.appendChild(titleImg);
		details.innerHTML += '<br />';
		details.appendChild(img);
	};
	
	this.init();
}

//JC POPUPS START

function openEasyform(easyformPath, displayLang){
	if(screen.availHeight >= 700){
		var easyform = window.open(easyformPath + "?lang="+displayLang, "easyform","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,screenX=0,screenY=0,left=0,top=0,maximize=1");

	}else{
		var easyform = window.open(easyformPath + "?lang="+displayLang, "easyform", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,screenX=0,screenY=0,left=0,top=0,maximize=1");
	}
	easyform.focus();
}

function jcew_openCurrentOdds() {
	var tempwin2=window.open('http://bet.hkjc.com/default.aspx?url=/racing/pages/odds_wp.aspx', '','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600,top=80,left=80');
}

function jcew_openEasyWin() {
	openEasyform('/easyform/popIndex.asp', 'tc');
}

function openEasyformShortcut(easyformPath, raceNo, displayLang){
	if(screen.availHeight >= 700){
		var easyform = window.open(easyformPath + "?shortcut=30&raceNo="+raceNo+"&lang="+displayLang, "easyform","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,screenX=0,screenY=0,left=0,top=0,maximize=1");
	}else{
		var easyform = window.open(easyformPath + "?shortcut=30&raceNo="+raceNo+"&lang="+displayLang, "easyform","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,screenX=0,screenY=0,left=0,top=0,maximize=1");
	}
	easyform.focus();
}

function jcew_allupcalculator() {
	var tempwin2=window.open('http://www.hkjc.com/chinese/oddscalc/oddscalc.asp','','width=700,height=560');
}

function jcew_investcalculator() {
	var tempwin2=window.open('http://analysis.hkjc.com/racing/ch/calculator/racingcalculator.html','','width=680,height=570,resizable');
}

function jcew_simulcast_openWin() {
	var tempwin2=window.open('http://www.hkjc.com/chinese/special/Simulcast_races/index.asp', 'simulWin','Height=600,Width=780,resizable=1,scrollbars=yes,menubar=1,toolbar=1,left=20,top=20');
}

function jcew_museum() {
	var tempwin2=window.open('/chinese/special/2004_archives_museum/am04_index_mu.asp', '','Height=600,Width=780,resizable=1,scrollbars=yes,left=20,top=20');
}

function jcew_knowhorse() {
	var tempwin2=window.open('/chinese/special/2002_horse_info/horses02_index.htm', '','Height=600,Width=780,resizable=1,scrollbars=yes,left=20,top=20');
}

function jcew_hworld() {
	var tempwin2=window.open('/chinese/special/20/hw02_index.htm', '','Height=600,Width=780,resizable=1,scrollbars=yes,left=20,top=20');
}

function know_more_horses() {
	var tempwin2=window.open('http://special.hkjc.com/promo/ch/2006_know_more_horses/kmh06_index.asp', '','Height=600,Width=790,resizable=1,scrollbars=yes,left=20,top=20');
}

function jcew_slesson() {
	var tempwin2=window.open('http://special.hkjc.com/promo/ch/summer_lesson/playvideo.asp', '','Height=600,Width=788,resizable=1,scrollbars=yes,left=20,top=20');
}

function jcew_rdb() {
	var tempwin2=window.open('http://special.hkjc.com/promo/ch/2009_rdb/2009_rdb_index.asp', '','Height=700,Width=818,resizable=1,scrollbars=yes,left=5,top=5');
}

function jcew_prs() {
	var tempwin2=window.open('http://www.hkjcridingschools.com/chinese/riding_schools_index.asp', '','Height=600,Width=800,resizable=1,scrollbars=yes,left=20,top=20');
}

//JC POPUPS END

function redirectPage(action) {

  var url = "";
  var returnURL = window.top.location.href;
      returnURL = encodeURIComponent(returnURL);  
  
  if( action == "login") {
     url = returnlogin + "&ReturnURL=" + returnURL;
	 window.top.location.href = url;
	 } else if( action == "logout") {
	            
				alert("如你正在其他視窗開啟馬會網上服務，該等服務亦會同時被登出，如有需要請關閉該等視窗。");
				url = returnlogout + "&ReturnURL=" + returnURL;
				window.top.location.href = url;
			} else if ( action == "register") {
					url = returnregister;
					window.top.location.href = url;
				}
				else if ( action == "preference") {
						url =  returnpreference + "&ReturnUrl=" + returnURL;
						window.top.location.href = url;
				}
				else if ( action == "help") {
				        window.open(returnFAQ);
				}
				
    
  	
}

function setReturnLoginURL(url) {

   returnlogin = url;

}

function setReturnLogoutURL(url) {

   returnlogout = url;

}

function setReturnPreferenceURL(url) {

   returnpreference = url;

}

function setReturnRegisterURL(url) {

   returnregister = url;

}

function showDisplayName(displayname, salutation, lastname,lastnamechinese) {

  var showname = displayname;
   

   if(salutation == "Mr." || salutation == "Mr")
     salutation = "先生";
	 
   if(salutation == "Ms." || salutation == "Ms")
     salutation = "女仕";
	
   if(salutation == "Miss." || salutation == "Miss")
     salutation = "小姐";
	 
   if(salutation == "Mrs." || salutation == "Mrs")
     salutation = "太太";
	
 if(displayname == "" || displayname == null ) 
  {

  if(lastnamechinese == "" || lastnamechinese == null)
      showname = lastname + salutation;
  else
      showname = lastnamechinese + salutation;  
  }
  
  var name = "    你好 " + showname + "    ";
  
  return name;
    
    
}

