var isIE = (navigator.appName.indexOf("Microsoft") > -1);
var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var isIE8 = false /*@cc_on || @_jscript_version == 5.8 @*/;
var isIELower9 = false /*@cc_on || @_jscript_version <= 5.8 @*/;
var isAndroid = (navigator.userAgent.toLowerCase().search('android') > -1);
var isGalaxyTab = (navigator.userAgent.toLowerCase().search('gt-') > -1);
var isIpad = checkIsIphoneIpad();
var isMobile = checkMobile();
var logoColor = 0;
var ieVersion;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))	ieVersion = new Number(RegExp.$1);
var d = document;
var alive=/(k11concepts\.com|cloudapp\.net)$/.test(d.domain);
//var cloudServer='http://k11storage.blob.core.windows.net/media/';
var cloudServer='http://k11concepts.blob.core.windows.net/media/';
if(!alive){
	alive=true;
	cloudServer='http://k11storage.dclook.com/media/';
	//cloudServer='http://k11concepts.dclook.com/media/';
}

if (!levelArray)	var levelArray = new Array();


function init()
{
	if (levelArray.length == 0)	getLevel();
	if (isMobile)	addIpadCSS();
	if (!isMobile)	new setLayout();
	new setTopNav();
	
	changeLogoColor(logoColor);
	setFieldFocus();
	
	var mainNav = d.getElementById('k11_mainNav');
	var btn = getElementsByClassName(mainNav, 'art')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'art active')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'art highlight')[0];
	var menu = d.getElementById('menuArt');
	new setMainNav(btn, menu);
	
	var btn = getElementsByClassName(mainNav, 'blogger')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'blogger active')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'blogger highlight')[0];
	var menu = d.getElementById('menuBlogger');
	new setMainNav(btn, menu);
	
	var btn = getElementsByClassName(mainNav, 'dining')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'dining active')[0];
	if (btn == undefined)	btn = getElementsByClassName(mainNav, 'dining highlight')[0];
	var menu = d.getElementById('menuDining');
	new setMainNav(btn, menu);
	
	//new setAnnouncement();
	
	/*window.onload = function()
	{
		//Character Motion
		new setCharacter();
	}*/
}

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 ){
		if (obj != 'index.aspx')
		{
			levelArray[levelArray.length-1] = obj.replace('.aspx', '');
		}
		else
		{
			levelArray.pop();
		}
		//alert(levelArray);
	}
}

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 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);
	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)
{
  if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  el.style.visibility = 'visible';
  //el.style.zIndex = 2;
  setOpacity(el, 0);
  fadeImage(el, 0);
}

function fadeImage(el, currentOpacity)
{
  currentOpacity += 20;

  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); }, 10);
  }
}

function startFadingOut(el)
{
  if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  el.style.visibility = 'visible';
  //el.style.zIndex = 2;
  setOpacity(el, 100);
  fadeImageOut(el, 100);
}

function fadeImageOut(el, currentOpacity)
{
  currentOpacity -= 25;

  if (currentOpacity <= 0)
  {
    setOpacity(el, 0);
    //el.style.zIndex = 1;
	el.style.display = 'none';
	if (el.fadinTimeout)	clearTimeout(el.fadinTimeout);
  }
  else
  {
    setOpacity(el, currentOpacity);
    el.fadinTimeout = setTimeout(function() { fadeImageOut(el, currentOpacity); }, 10);
  }
}

function setOpacity(el, opacity)
{
	opacity /= 100;
	el.style.opacity = opacity;
	el.style.MozOpacity = opacity;
	el.style.filter = "alpha(opacity=" + (opacity*100) + ")";
}

function addEvent (o, t, f)
{
	removeEvent (o, t, f);
	if (o.attachEvent) o.attachEvent('on'+ t, f);
	else o.addEventListener(t, f, false);
};

function removeEvent (o, t, f)
{
	if (o.detachEvent) o.detachEvent('on'+ t, f);
	else o.removeEventListener(t, f, false);
};

function loadXML(url, isHTML)
{
	var x;
	var self = this;

	this.action = function()	{};

	if (typeof(XMLHttpRequest) == 'undefined')
	{
		XMLHttpRequest = function()
		{
		    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
				catch(e) {}
		    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
				catch(e) {}
		    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
				catch(e) {}
		    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
				catch(e) {}
		    throw new Error("This browser does not support XMLHttpRequest.");
		};
	}

	x = new XMLHttpRequest();
	if (x.overrideMimeType)	x.overrideMimeType((isHTML)?'text/html':'text/xml');

	if (x)
	{
		x.onreadystatechange = function()
		{
			if (x.readyState == 4 && x.status == 200)
			{
				self.action(x);
			}
		}
		x.open('GET', url, true);
		x.send(null);
	}
}

function getChildNodes(xml)
{
	var obj = new Object();
	for (var i=0; i<xml.length; i++)
	{
		if (!isIE)	if (xml[i].toString() == '[object Text]')	continue;
		var name = xml[i].nodeName.toString();
		var value = (xml[i].firstChild)	?	xml[i].firstChild.data.toString()	:	'';
		obj[name] = value;
	}
	return obj;
}

function getAttributes(xml)
{
	var obj = new Object();
	for (var i=0; i<xml.attributes.length; i++)
	{
		obj[xml.attributes[i].name.toString()] = xml.attributes[i].value.toString();
	}
	return obj;
}

function addZero(num)
{
	if (num < 10)	num = '0' + num;
	return	num;
}

function setFieldFocus()
{
	var input = d.getElementsByTagName('input');

	for (var i=0; i<input.length; i++)
	{
		if (input[i].type != 'text')		continue;
		if (input[i].defaultValue == '')	continue;

		input[i].onfocus = function()
		{
			if (this.value == this.defaultValue)	this.value = '';
		}

		input[i].onblur = function()
		{
			if (this.value == '')	this.value = this.defaultValue;
		}
	}
}

function checkIsIphoneIpad()
{
	var pda_user_agent_list = new Array("iPhone", "iPod", "iPad"/*, "GTB"*/);
	var pda_app_name_list = new Array("Microsoft Pocket Internet Explorer");

	var user_agent = navigator.userAgent.toString();
	for (var i=0; i<pda_user_agent_list.length; i++) {
		if (user_agent.indexOf(pda_user_agent_list[i]) >= 0) {
			return true;
		}
	}
	var appName = navigator.appName.toString();
	for (var i=0; i<pda_app_name_list.length; i++) {
		if (user_agent.indexOf(pda_app_name_list[i]) >= 0) {
			return true;
		}
	}

	return false;
}

function checkMobile()
{
	var pda_user_agent_list = new Array("2.0 MMP", "240320", "AvantGo","BlackBerry", "Blazer",
			"Cellphone", "Danger", "DoCoMo", "Elaine/3.0", "EudoraWeb", "hiptop", "IEMobile", "KYOCERA/WX310K", "LG/U990",
			"MIDP-2.0", "MMEF20", "MOT-V", "NetFront", "Newt", "Nintendo Wii", "Nitro", "Nokia",
			"Opera Mini", "Opera Mobi",
			"Palm", "Playstation Portable", "portalmmm", "Proxinet", "ProxiNet",
			"SHARP-TQ-GX10", "Small", "SonyEricsson", "Symbian OS", "SymbianOS", "TS21i-10", "UP.Browser", "UP.Link",
			"Windows CE", "WinWAP", "Android", "iPhone", "iPod", "iPad", "Windows Phone", "HTC"/*, "GTB"*/);
	var pda_app_name_list = new Array("Microsoft Pocket Internet Explorer");

	var user_agent = navigator.userAgent.toString();
	for (var i=0; i<pda_user_agent_list.length; i++) {
		if (user_agent.indexOf(pda_user_agent_list[i]) >= 0) {
			return true;
		}
	}
	var appName = navigator.appName.toString();
	for (var i=0; i<pda_app_name_list.length; i++) {
		if (user_agent.indexOf(pda_app_name_list[i]) >= 0) {
			return true;
		}
	}

	return false;
}

function addIpadCSS()
{
	var cssLink = document.createElement('link');
	cssLink.setAttribute('rel', 'stylesheet');
	cssLink.setAttribute('type', 'text/css');
	cssLink.setAttribute('href', '/' + lang + '/css/ipad.css');
	d.getElementsByTagName('head')[0].appendChild(cssLink);

	d.body.className += ' iPad';
}

function setLayout()
{
	var mainContainer = d.getElementById('k11_mainContainer');
	var contentContainer = d.getElementById('k11_contentContainer');
	var contentW = 990;
	var borderW = 50; //border L + border R
	var self = this;

	this.init = function()
	{
		self.resizeDiv();
		addEvent(window, 'resize', function(){self.resizeDiv();});
	};

	this.resizeDiv = function()
	{
		contentContainer.style.display = 'none';

		var w = mainContainer.offsetWidth;
		var h = mainContainer.offsetHeight;

		contentContainer.style.width = w - borderW + 'px';
		contentContainer.style.height = h - borderW + 'px';

		if (w <= (contentW + borderW))
		{
			contentContainer.style.left = (w - contentW)/2 + 'px';
		}
		else
		{
			contentContainer.style.left = '25px';
		}

		contentContainer.style.display = 'block';
	};

	this.init();
}

function resizeSVGObjs(svg, fixW, fixH, ratio, alignH, alignV, caseH, caseV, maxS)
{
	if (!fixW)		fixW = 990;
	if (!fixH)		fixH = 595;
	if (!ratio)		ratio = 10;
	if (!alignH)	alignH = 'C';
	if (!alignV)	alignV = 'C';
	var resizeArray = new Array();
	var self = this;

	this.init = function()
	{
		var time = (isIELower9)?100:0;

		if (!isMobile)
		{
			addEvent(window, 'resize', function()
			{
				setTimeout(function(){self.resizeAllObj();}, time);
			});
		}
	}

	this.addObj = function(target, isScale, posX, posY, motion)
	{
		target.initX = findTransformAtt(target, 'translate')[0];
		target.initY = findTransformAtt(target, 'translate')[1];
		//alert(target.initX + '  :  ' + target.initY);
		resizeArray.push({target:target, isScale:isScale, posX:posX, posY:posY, motion:motion});
		self.resizeObj(target, isScale, posX, posY, motion, true);
	};

	this.resizeAllObj = function()
	{
		for (var i=0; i<resizeArray.length; i++)
		{
			var obj = resizeArray[i];
			self.resizeObj(obj.target, obj.isScale, obj.posX, obj.posY, obj.motion);
		}

		//var suspendID = svg.suspendRedraw(5000);
		//svg.unsuspendRedraw(suspendID);
		// could also do root.unsuspendRedrawAll() to clear out all suspended
	};

	this.resizeObj = function(target, isScale, posX, posY, motion, start)
	{
		var screenW = svg.offsetWidth;
		var screenH = svg.offsetHeight;
		var scale;

		if (isScale)
		{
			if (screenW >= fixW && screenH <= fixH || caseH)
			{
				scale = screenW/fixW;
			}
			else if (screenW <= fixW && screenH >= fixH || caseV)
			{
				scale = screenH/fixH;
			}
			else if (screenW > fixW && screenH > fixH)
			{
				if ((screenH/fixH) > (screenW/fixW))
				{
					scale = screenH/fixH;
				}
				else
				{
					scale = screenW/fixW;
				}
			}
			else
			{
				scale = 1;
			}

			if (maxS)
			{
				if (scale > maxS)	scale = maxS;
			}

			//offset the image
			var x = 0;
			var y = 0;

			if (alignH == 'C')
			{
				if (fixW*scale > screenW)
				{
					x = - Math.floor((fixW*scale - screenW)/2);
				}
			}
			if (alignV == 'C')
			{
				if (fixH*scale > screenH)
				{
					y = - Math.floor((fixH*scale - screenH)/2);
				}
			}

			target.setAttribute('transform', 'scale(' + scale + ', ' + scale + ') translate(' + x + ', ' + y + ')');
		}
		else
		{
			var tempX;
			var tempY;

			if (posX == 1)
			{
				tempX = 0;
			}
			else if (posX == 2)
			{
				tempX = (screenW - fixW);
			}
			else if (posX == 3)
			{
				//tempX = (target.startX*(screenW/fixW) - target.startX);
			}
			else
			{
				tempX = (screenW - fixW)/2;
			}
			if (posY == 1)
			{
				tempY = 0;
			}
			else if (posY == 2)
			{
				tempY = (screenH - fixH);
				if (isIpad && tempY != null && fixH >= 595)	tempY -= 30;
			}
			else if (posY == 3)
			{
				//tempY = (target.startY*(screenH/fixH) - target.startY);
			}
			else
			{
				tempY = (screenH - fixH)/2;
			}

			target.resizeX = Math.round(tempX);
			target.resizeY = Math.round(tempY);

			var targetX = target.initX + Math.round(tempX);
			var targetY = target.initY + Math.round(tempY);

			if (motion && !start)
			{
				//$('#' + target.id).animate({svgTransform: 'translate(' + targetX + ', ' + targetY + ')'}, 300);
				new animateSVG(target, {x:targetX, y:targetY}, ratio);
			}
			else
			{
				target.setAttribute('transform', 'translate(' + targetX + ', ' + targetY + ')');
			}
		}
	};

	this.init();
};

function animateSVG(target, obj, ratio, action)
{
	var XReady = true;
	var YReady = true;
	var SReady = true;
	var AReady = true;
	var isStop = false;
	var self = this;

	this.init = function()
	{
		if (target.timeOut)	clearTimeout(target.timeOut);
		this.motion();
	}

	this.motion = function()
	{
		var str = '';

		//x, y
		if (obj.x != null || obj.y != null)
		{
			target.X = findTransformAtt(target, 'translate')[0];
			target.Y = findTransformAtt(target, 'translate')[1];
		}

		if (obj.x != null)
		{
			target.goStepX = (obj.x - target.X)/ratio;
			if (target.goStepX > 0)	target.goStepX = Math.ceil(target.goStepX);
			if (target.goStepX < 0)	target.goStepX = Math.floor(target.goStepX);

			if (!(Math.abs(obj.x - target.X) < 2))
			{
				target.X += target.goStepX;
				XReady = false;
			}
			else
			{
				target.X = obj.x;
				XReady = true;
			}
		}

		if (obj.y != null)
		{
			target.goStepY = (obj.y - target.Y)/ratio;
			if (target.goStepY > 0)	target.goStepY = Math.ceil(target.goStepY);
			if (target.goStepY < 0)	target.goStepY = Math.floor(target.goStepY);

			if (!(Math.abs(obj.y - target.Y) < 3))
			{
				target.Y += target.goStepY;
				YReady = false;
			}
			else
			{
				target.Y = obj.y;
				YReady = true;
			}
		}
		//window.status = obj.y + '  :  ' + target.Y;

		if (obj.x != null || obj.y != null)	str += ' translate(' + target.X + ', ' + target.Y + ')';

		//Scale
		if (obj.s != null)
		{
			target.S = findTransformAtt(target, 'scale')[0];

			target.goStepS = (obj.s - target.S)/ratio;
			if (target.goStepS > 0) target.goStepS += 0.01;
			if (target.goStepS < 0) target.goStepS -= 0.01;

			if (!(Math.abs(obj.s - target.S) < 0.05))
			{
				target.S += target.goStepS;
				SReady = false;
			}
			else
			{
				target.S = obj.s;
				SReady = true;
			}

			str += ' scale(' + target.S + ', ' + target.S + ')';
		}

		if (str != '')	target.setAttribute('transform', str);

		//Alpha
		if (obj.a != null)
		{
			target.style.display = 'block';
			target.A = (isNaN(target.style.opacity))?	1:Number(target.style.opacity);
			target.goStepA = (obj.a - target.A)/ratio;
			if (target.goStepA > 0) target.goStepA += 0.01;
			if (target.goStepA < 0) target.goStepA -= 0.01;
			//window.status = obj.a + '  :  ' + target.A;

			if (!(Math.abs(obj.a - target.A) < 0.05))
			{
				target.A += target.goStepA;
				AReady = false;
			}
			else
			{
				target.A = obj.a;
				if (target.A == 0)	target.style.display = 'none';
				AReady = true;
			}

			target.style.opacity = target.A;
		}

		if ((XReady && YReady && SReady && AReady) || isStop)
		{
			//if (target.targetW == 0)	target.style.display = 'none';
			clearTimeout(target.timeOut);
			if (action)	action();
		}
		else
		{
			target.timeOut = setTimeout(function(){self.motion(target, obj, ratio);}, 10);
		}
	};

	this.stop = function()
	{
		isStop = true;
		clearTimeout(target.timeOut);
	};

	this.init();
}

function findTransformAtt(target, transformAtt)
{
	var str = target.getAttribute('transform');
	if (!str)	return new Array(0, 0);

	var pos1 = str.indexOf(transformAtt);
	str = str.substring(pos1, str.length);
	var pos2 = str.indexOf(')') + 1;
	str = str.substring(0, pos2);
	//var animateArray = str.split(/[0-9]/g);
	//str = str.replace(animateArray[0], '');
	//str = str.replace(animateArray[animateArray.length-1], '');
	str = str.replace((transformAtt + '('), '');
	str = str.replace(')', '');
	if (str.indexOf(',') >= 0)
	{
		var array = str.split(',');
	}
	else
	{
		var array = str.split(' ');
	}
	var x = Number(array[0]);
	var y = (array.length == 1)?0:Number(array[array.length-1]);
	
	if (isNaN(x))	x = 0;
	if (isNaN(y))	y = 0;
	
	return new Array(x, y);
}

/*function animateSVG(target, obj, ratio)
{
	var animateList = new Array('transform');
	var timeout;
	var self = this;

	this.init = function()
	{
		for (var i=0; i<animateList.length; i++)
		{
			if (!obj[animateList[i]])	continue;

			var att = animateList[i];
			var newAtt = obj[att];
			//var oldAtt = target.getAttribute(att);self.findAtt(oldAtt), self.findAtt(newAtt)
			var newAttArray = self.findAtt(newAtt);

			new self.animate(att, [newAttArray[0], newAttArray[1], newAttArray[2]]);
		}
	};

	this.findAtt = function(str)
	{
		var animateArray = str.split(/[0-9]/g);
		str = str.replace(animateArray[0], '');
		str = str.replace(animateArray[animateArray.length-1], '');
		var array = str.split(',');
		var x = parseInt(array[0]);
		var y = (array.length == 1)?0:parseInt(array[array.length-1]);
		var att = animateArray[0].replace('(', '');

		return new Array(att, x, y);
	};

	this.animate = function(att, animateArray)
	{

	};

	this.init();
}*/

function bringToFrontSVG(element)
{
	var parent = element.parentNode;
	parent.removeChild(element);
	parent.appendChild(element);
}

function setTopNav()
{
	var topNav = d.getElementById('k11_topNav');
	//var btnMore = getElementsByClassName(topNav, 'more')[0];
	var btnMore = d.getElementById('btnMore');
	var menu = d.getElementById('menuMore');
	var ul = menu.getElementsByTagName('ul')[0];
	var initPos = new Object();
	var endPos = new Object();
	var hit = false;
	var isOpen = false;
	var animateClass;
	var self = this;

	this.init = function()
	{
		initPos.x = -menu.offsetWidth;
		initPos.y = -menu.offsetHeight;
		endPos.x = 0;
		endPos.y = 0;
		$('#menuMore').css({right:initPos.x, top:initPos.y, visibility:'visible'});

		if (isMobile)
		{
			btnMore.onclick = function()
			{
				self.menuGo(!isOpen);
				isOpen = !isOpen;
			};
		}
		else
		{
			btnMore.onmouseover = function()
			{
				self.menuGo(true);
			};
			/*btnMore.onmouseout = function()
			{
				setTimeout(function()
				{
					if (hit)	return;
					self.menuGo(false);
					hit = false;
				}, 300);
			};*/

			ul.onmouseover = function()
			{
				hit = true;
			};
			ul.onmouseout = function()
			{
				hit = false;
				setTimeout(function()
				{
					if (hit)	return;
					self.menuGo(false);
				}, 10);
			};
		}
	};

	this.menuGo = function(isOpen)
	{
		if (isOpen)
		{
			if (hit)	return;
			if (animateClass)	animateClass.stop();
			animateClass = $('#menuMore').animate({right:endPos.x, top:endPos.y}, 200, 'easeInOutQuad', function(){});
			$('#menuMore').css({visibility:'visible'});
		}
		else
		{
			//if (!hit)	return;
			if (animateClass)	animateClass.stop();
			animateClass = $('#menuMore').animate({right:initPos.x, top:initPos.y}, 200, 'easeInOutQuad', function()
			{
				$('#menuMore').css({visibility:'hidden'});
			});
		}
	};

	this.init();
}

function setMainNav(btn, menu)
{
	var mainContainer = d.getElementById('k11_mainContainer');
	var initPos = new Object();
	var endPos = new Object();
	var hit = false;
	var isOpen = false;
	var animateClass;
	var self = this;

	this.init = function()
	{
		initPos.y = 60 - menu.offsetHeight;
		endPos.y = 7;
		$('#' + menu.id).css({bottom:initPos.y, visibility:'visible'});

		if (isMobile)
		{
			btn.onclick = function()
			{
				self.menuGo(!isOpen);
				isOpen = !isOpen;
			};
		}
		else
			{
			btn.onmouseover = function()
			{
				self.menuGo(true);
			};

			menu.onmouseover = function()
			{
				hit = true;
			};
			menu.onmouseout = function()
			{
				hit = false;
				setTimeout(function()
				{
					if (hit)	return;
					self.menuGo(false);
				}, 10);
			};
		}

		/*if (isMobile)
		{
			addEvent(mainContainer, 'mousedown', hideAllMenu);

			function hideAllMenu()
			{
				setTimeout(function(){if (ipadHit)	return; self.menuGo(false);}, 10);
			}
		}*/
	};

	this.menuGo = function(isOpen)
	{
		if (isOpen)
		{
			if (hit)	return;
			if (animateClass)	animateClass.stop();
			if (btn.className.indexOf('active') < 0)	btn.className += ' active';
			animateClass = $('#' + menu.id).animate({bottom:endPos.y}, 300, 'easeInOutQuad', function(){});
			//$('#menuArt').css({visibility:'visible'});
		}
		else
		{
			//if (!hit)	return;
			if (animateClass)	animateClass.stop();
			btn.className = btn.className.replace(/active/, '');
			animateClass = $('#' + menu.id).animate({bottom:initPos.y}, 200, 'easeInOutQuad', function()
			{
				//$('#menuArt').css({visibility:'hidden'});
			});
		}
	};

	this.init();
}

function changeLogoColor(id)
{
	$('#k11_logo').css({display:'block'});

	if (isIELower9)
	{
		addRemoveClass();
		return;
	}

	if ($('#k11_logo').animateClass)	$('#k11_logo').animateClass.stop();
	$('#k11_logo').animateClass = $('#k11_logo').animate({opacity:0}, 100, 'easeInOutQuad', function()
	{
		addRemoveClass();
		if ($('#k11_logo').animateClass)	$('#k11_logo').animateClass.stop();
		$('#k11_logo').animateClass = $('#k11_logo').animate({opacity:1}, 100, 'easeInOutQuad', function(){});
	});

	function addRemoveClass()
	{
		if (id == 1)
		{
			$('#k11_logo').addClass('active');
		}
		else
		{
			$('#k11_logo').removeClass('active');
		}
	}
}

function sortShopList(){

	var tempList=[];
	shopIds=[];

	for(var i in shoplist){
		tempList.push({
			id:i,
			name:shoplist[i].shopname['en'],
			shopno:shoplist[i].shopno,
			category:shoplist[i].category
		});
	}

	if($('#shop-list-header a').length>0){
		$('#shop-list-header a').each(function(i){
			if(this.className.indexOf('active')>-1){
				if(i==0){
					tempList.sort(sortByName);
				}else if (i==1){
					tempList=sortByLocation(tempList);
				}else if (i==2){
					tempList.sort(sortByCategory);
				}
				return;
			}
		});
	}else{
		tempList.sort(sortByName);
	}

	for(var i in tempList)
		shopIds.push(tempList[i].id);

	function sortByName(a,b){
		var v1=a.name.toLowerCase(), v2=b.name.toLowerCase();
		if(v1 < v2)
			return -1;
		if(v1 > v2)
			return 1;
		return 0;
	}

	function sortByLocation(arr){

		var floors=['B2','B1','G','1','2','3','4'];
		var i,j,floor,tempArr=[],output=[];

		for(i=0;i<floors.length;i++)
			tempArr[floors[i]]=[];

		for(i=0;i<arr.length;i++){
			floor=arr[i].shopno.substring(0,2);
			if(floor!='B2' && floor!='B1')
				floor=floor.substring(0,1);
			tempArr[floor].push(arr[i]);
		}

		for(i=0;i<floors.length;i++){
			tempArr[floors[i]].sort(sortByShopno);
			for(j=0;j<tempArr[floors[i]].length;j++)
				output.push(tempArr[floors[i]][j]);
		}
				
		return output;

	}

	function sortByShopno(a,b){
		var v1=a.shopno, v2=b.shopno;
		if(v1 < v2)
			return -1;
		if(v1 > v2)
			return 1;
		return 0;
	}

	function sortByCategory(a,b){
		var v1=a.category, v2=b.category;
		if(v1 < v2)
			return -1;
		if(v1 > v2)
			return 1;
		return 0;
	}

}

function setCookie(name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=name+"="+escape(value)+((expiredays==null)?"":";expires="+exdate.toGMTString())+';path=/';
}

function getCookie(name){
	if(document.cookie.length>0){
		start=document.cookie.indexOf(name+"=");
		if(start!=-1){
			start=start+name.length+1;
			end=document.cookie.indexOf(";",start);
			if(end==-1)
				end=document.cookie.length;
			return unescape(document.cookie.substring(start,end));
		}
	}
	return "";
}

function detectTouch(obj, config)
{
    if (!config)	config =
	{
		min_move_x: 20,
		wipeLeft: function(x) {},
		wipeRight: function(x) {},
		min_move_y: 20,
		wipeTop: function(y) {},
		wipeBottom: function(y) {},
		preventDefaultEvents: true
	};

	var startX;
	var startY;
	var isMoving = false;

	function cancelTouch()
	{
		this.removeEventListener('touchmove', onTouchMove);
		startX = null;
		startY = null;
		isMoving = false;
	}

	function onTouchMove(e)
	{
		if (config.preventDefaultEvents)
		{
			e.preventDefault();
		}
		if (isMoving)
		{
			var x = e.touches[0].pageX;
			var dx = startX - x;
			if (Math.abs(dx) >= config.min_move_x)
			{
				cancelTouch();
				if (dx > 0)
				{
					config.wipeLeft(dx);
				}
				else
				{
					config.wipeRight(dx);
				}
			}
			var y = e.touches[0].pageY;
			var dy = startY - y;
			if (Math.abs(dy) >= config.min_move_y)
			{
				cancelTouch();
				if (dy > 0)
				{
					config.wipeTop(dy);
				}
				else
				{
					config.wipeBottom(dy);
				}
			}
		}
	}

	function onTouchStart(e)
	{
		if (e.touches.length == 1)
		{
			startX = e.touches[0].pageX;
			startY = e.touches[0].pageY;
			isMoving = true;
			this.addEventListener('touchmove', onTouchMove, false);
		}
	}

	obj.addEventListener('touchstart', onTouchStart, false);
 }


function heightResize (id, num)
{
	if (!num)	num = 213
	$(window).load(function(){
		heightListResize();
		$(window).resize(heightListResize);
	});
	function heightListResize(){
		
		var h = (isMobile)?	690:$(window).height();
		h -= num;
		$('#' + id).height(h);
	}

}

/* lightbox */
var lightbox={};
lightbox.status=0;
lightbox.contentId=false;
lightbox.selector='a[rel=lightbox]';
lightbox.width=800;
lightbox.height=550;

lightbox.closeLabel=[];
lightbox.closeLabel['en']='close';
lightbox.closeLabel['tc']='關閉';
lightbox.closeLabel['sc']='关闭';

lightbox.ini=function(){

	$(lightbox.selector).unbind().click(function(e){

		e.preventDefault();

		lightbox.status=1;
		lightbox.overlay();

		$('<div id="lightbox" />').appendTo('body').css({
			'width':lightbox.width,
			'height':lightbox.height,
			'z-index':5001
		}).append('<div class="heading"><div class="title"></div><a class="close" href="javascript:;">'+lightbox.closeLabel[lang]+'</a></div>').center();

		$('#lightbox .close').click(lightbox.close);
		
		//Hard Code for Announcement
		if (this.href.indexOf('#announcement') >= 0)	$('#lightbox').addClass('announcement');

		if(this.title)
			$('#lightbox .title').html(this.title);
		else if(this.name)
			$('#lightbox .title').html('<img src="'+this.name+'"/>');

		// launch flv player
		if(this.href.toLowerCase().indexOf('.mp4')>-1 || this.href.toLowerCase().indexOf('.flv')>-1){
			
			var srcPath=this.href.substring(this.href.indexOf('#')+1);
			
			$('#lightbox').append('<div id="lightbox_flash" />');
				
			var video_width=600;
			var video_height=337;
			
			if(iPx()){
				
				$('#lightbox').css({
					'width':video_width,
					'height':video_height+100
				}).find('.heading').css('width',video_width);
				
				//window.location=srcPath;
				//lightbox.close();
				//alert(srcPath)
				
				var video=d.createElement('video');
				video.width=video_width;
				video.height=video_height;
				//video.poster=thumbnail;
				video.controls='controls';
				video.autoplay='autoplay';
				
				var source=d.createElement('source');
				source.src=srcPath;
				source.type='video/mp4';
				
				var object=d.createElement('object');
				object.width=video_width;
				object.height=video_height;
				object.classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B';
				object.data=srcPath;
				
				var param=d.createElement('param');
				param.name='src';
				param.value=srcPath;
				
				var param2=d.createElement('param');
				param2.name='autoplay';
				param2.value='true';
				
				object.appendChild(param);
				object.appendChild(param2);
				video.appendChild(source);
				video.appendChild(object);
				
				d.getElementById('lightbox_flash').appendChild(video);
				video.play();
				
			}else{
				
				$('#lightbox').css({
					'width':video_width,
					'height':video_height+100
				}).find('.heading').css('width',video_width);
				
				var flashvars = {
					srcPath:srcPath,
					downloadPath:"",
					imgPath:"",
					videoW:video_width,
					videoH:video_height,
					autoLoop:"false",
					controlBarAutoHide:"false",
					autoPlay:"true"
				};
				var flash_params = {
					menu: "false",
					scale: "noScale",
					allowFullscreen: "true",
					allowScriptAccess: "always",
					bgcolor: "#FFFFFF",
					wmode:"opaque"
				};
	
				swfobject.embedSWF(cloudServer + 'images/swf/flvPlayer.swf', 'lightbox_flash', video_width, video_height, '9.0.0', "expressInstall.swf", flashvars, flash_params);
				
			}
			
			lightbox.relocate();
			$(window).resize(lightbox.relocate);

		}else{

			$('#lightbox').append('<div id="lightbox_content" />');

			if(this.href.indexOf('#')>-1){

				var id=this.href.substring(this.href.indexOf('#')+1);
				lightbox.contentId=id;

				/* do not process if content is not found */
				if(!d.getElementById(id)){
					lightbox.close();
					return false;
				}

				var headingHeight=$('#lightbox .heading').height();
				var $content=$('#'+id).removeClass('hidden');
				$('#lightbox').css({
					'width':$content.width(),
					'height':$content.height()+80
				}).center();
				$content.appendTo('#lightbox_content').show();
				$(window).unbind('scroll').resize(lightbox.relocate);

			}

		}

	});

};

lightbox.open=function(id, title, noClose, dom){

		lightbox.status=1;
		lightbox.overlay(noClose);

		$('<div id="lightbox" />').appendTo('body').css({
			'width':lightbox.width,
			'height':lightbox.height,
			'z-index':5001
		}).center();

		if (title != 'none')
		{
			$('#lightbox').append('<div class="heading"><div class="title"></div><a class="close" href="javascript:;">'+lightbox.closeLabel[lang]+'</a></div>')
		}

		$('#lightbox .close').click(lightbox.close);
		$('#lightbox .title').html(title);

		$lightbox=$('#lightbox').append('<div id="lightbox_content" />');

		lightbox.contentId=id;
		
		var $content;
		if (!dom)
		{
			$content=$('#'+id);
		}
		else
		{
			$content = $(dom);
		}
		$content.appendTo('#lightbox_content');
		
		$lightbox.width($content.width()).height($content.height()+((title == 'none')?0:50) + 20).center();
		if(parseInt($lightbox.css('top'))<0)
			$lightbox.css('top','0px');

		$content.show();
		$(window).unbind('resize').resize(lightbox.relocate);

}

lightbox.relocate=function(){
	if(lightbox.status==1){
		lightbox.overlay();
		var $lightbox=$('#lightbox').center();
		if(parseInt($lightbox.css('top'))<0)
			$lightbox.css('top','0px');
	};
}

lightbox.overlay=function(noClose){

	$('#overlay').remove();
	
	var w_width=$(document).width();
	var w_height=$(document).height();

	if($.browser.msie){
		if(parseInt($.browser.version)==6)
			w_width=w_width-scrollbarWidth()-8;
		else if(parseInt($.browser.version)==8)
			w_width=w_width-scrollbarWidth()-8;
	}

	$('<div id="overlay" />').appendTo('body').css({
		'width':w_width,
		'height':w_height,
		'z-index':5000
	});

	if (!noClose)	$('#overlay').click(lightbox.close);

	// IE6 select box fix
	if ($.browser.msie && parseInt($.browser.version)<=6){
		$('select').css('visibility','hidden');
		$('.popup select').css('visibility','visible');
	}

}

lightbox.close=function(){

	if(lightbox.contentId!=false){
		$('#'+lightbox.contentId).hide().appendTo('body');
		lightbox.contentId=false;
	};

	$('#overlay, #lightbox').remove();

	// IE6 select box fix
	if ($.browser.msie && parseInt($.browser.version)<=6)
		$('select').css('visibility','visible');

	lightbox.status=0;

}

/* center positioning */
jQuery.fn.center = function () {
	
	var top=( $(window).height() - this.height() ) / 2+$(window).scrollTop();
	var left=( $(window).width() - this.width() ) / 2+$(window).scrollLeft();
	
    this.css("position","absolute");
    this.css("top", top + "px");
    this.css("left", left + "px");
    return this;
};


/* detect iDevice */
function iPx(){
	if((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPod/i)) ||  (navigator.userAgent.match(/iPad/i)))
		return true;
	return false;
}


function replaceSwfWithEmptyDiv(targetID){
	var el = document.getElementById(targetID);
	if(el){
		var div = document.createElement("div");
		el.parentNode.insertBefore(div, el);
		swfobject.removeSWF(targetID);
		div.setAttribute("id", targetID);
	};
}


function scrollbarWidth() {
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"/></div>');
    /* Append our div, do our calculation and then remove it */
    $('body').append(div);
    var w1 = $('div', div).innerWidth();
    div.css('overflow-y', 'scroll');
    var w2 = $('div', div).innerWidth();
    $(div).remove();
    return (w1 - w2);
}

$(function(){
	lightbox.ini();
});

function setPreloader()
{
	var preloader = d.getElementById('preloader');
	var mainContainer = d.getElementById('k11_mainContainer');
	var $preloader = $('#preloader');
	var imgs = preloader.getElementsByTagName('img');
	var animateClass;
	var curIndex;
	var total = imgs.length;
	var time = 100;
	var timeout;
	var img;
	var self = this;

	this.init = function()
	{
		addEvent(window, 'resize', function()
		{
			self.setCenter();
		});

		curIndex = 0;
		imgs[curIndex].style.display = 'block';
		img = imgs[curIndex];

		timeout = setInterval(function()
		{
			curIndex ++;
			if (curIndex >= total)	curIndex = 0;

			imgs[curIndex].style.display = 'block';
			if (img)	img.style.display = 'none';
			img = imgs[curIndex];
		}, time);

		this.show();
	};

	this.setCenter = function()
	{
		var w = mainContainer.offsetWidth;
		var h = mainContainer.offsetHeight;

		$preloader.css({top:(h - preloader.offsetHeight)/2, left:(w - preloader.offsetWidth)/2});
	};

	this.show = function()
	{
		if (!isIE)
		{
			$preloader.css({opacity:0, display:'block'});
			animateClass = $preloader.animate({opacity:1}, 200, 'easeInOutQuad', function(){});
		}
		else
		{
			$preloader.css({display:'block'});
		}
		self.setCenter();
	};

	this.hide = function()
	{
		if (!isIE)
		{
			animateClass = $preloader.animate({opacity:0}, 200, 'easeInOutQuad', function()
			{
				clearTimeout(timeout);
				$preloader.css({display:'none'});
			});
		}
		else
		{
			$preloader.css({display:'none'});
		}
	};

	this.init();
}

function scrollbarWidth() {
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"/></div>');
    /* Append our div, do our calculation and then remove it */
    $('body').append(div);
    var w1 = $('div', div).innerWidth();
    div.css('overflow-y', 'scroll');
    var w2 = $('div', div).innerWidth();
    $(div).remove();
    return (w1 - w2);
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function changeLanguage(target)
{
	var array = new Array('en', 'tc', 'sc');
	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;
		url = url.replace('/' + array[i] + '/', '/' + target + '/');
		break;
	}
	
	window.top.location.href = url;
}

function setCharacter()
{
	var container = d.getElementById('k11_contentContainer');
	var character;
	var characterArray;
	var characterTotal;
	var limitTime = 20 * 1000; //milliseconds 
	var self = this;
	
	var directGoTimeout;
	var loadCount = 0;
	
	var frameTimeout;
	var frameArray;
	var frameRate = 200;
	var frameIndex = 0;
	var frameTotal;
	
	var motionTimeout;
	var motionArray;
	var motionIndex = 0;
	var motionTotal;
	var animateClass;
	
	var fixW = 990;
	var fixH = 595;
	var contentW = fixW;
	var contentH = fixH;
	var offsetX;
	var offsetY;
	
	var characterArray = [
		{
			motion:[
				{time:3*frameRate,	initX:1000,	endX:853,	initY:358,	endY:358, initXMode:'R', endXMode:'R', initYMode:'B', endYMode:'B'},
				{time:12*frameRate,	initX:853,	endX:853,	initY:358,	endY:358, initXMode:'R', endXMode:'R', initYMode:'B', endYMode:'B'},
				{time:3*frameRate,	initX:853,	endX:1000,	initY:358,	endY:358, initXMode:'R', endXMode:'R', initYMode:'B', endYMode:'B'}
			],
			frames:[
				{frame:3, img:'images/character/motion2/Atrium_a_01.png', w:137, h:237},
				{frame:2, img:'images/character/motion2/Atrium_a_02.png', w:137, h:237},
				{frame:1, img:'images/character/motion2/Atrium_a_03.png', w:137, h:237},
				{frame:1, img:'images/character/motion2/Atrium_a_04.png', w:137, h:237},
				{frame:1, img:'images/character/motion2/Atrium_a_05-1.png', w:137, h:237},
				{frame:3, img:'images/character/motion2/Atrium_a_05-2.png', w:137, h:237},
				{frame:7, img:'images/character/motion2/Atrium_a_01.png', w:137, h:237}
			]
		},
		{
			motion:[
				{time:22*frameRate,	initX:1000,	endX:200,	initY:319,	endY:319, initXMode:'R', endXMode:'L', initYMode:'B', endYMode:'B'},
				{time:12*frameRate,	initX:200,	endX:200,	initY:319,	endY:319, initXMode:'L', endXMode:'L', initYMode:'B', endYMode:'B'},
				{time:9*frameRate,	initX:200,	endX:-200,	initY:319,	endY:319, initXMode:'L', endXMode:'L', initYMode:'B', endYMode:'B'}
			],
			frames:[
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				
				{frame:1, img:'images/character/motion1/Atrium_b_04.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_05.png', w:127, h:276},
				{frame:10, img:'images/character/motion1/Atrium_b_06.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_05.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_04.png', w:127, h:276},
				
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_03.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_02.png', w:127, h:276},
				{frame:1, img:'images/character/motion1/Atrium_b_01.png', w:127, h:276}
			]
		}
	];
	var characterTotal = characterArray.length;
	var motionId;
	
	this.init = function()
	{
		var isShow = this.getCookie();
		//if (!isShow)	return;
		
		motionId = Math.floor(Math.random() * characterTotal);
		//motionId = 0;
		
		self.resizeDiv();
		addEvent(window, 'resize', function(){self.resizeDiv();});
		
		setTimeout(function()
		{
			self.genCharacter();
			
			setInterval(function()
			{
				self.reset();
			}, (limitTime + 100));
		}, 2500);
	};
	
	this.reset = function()
	{
		motionId ++;
		if (motionId >= characterTotal)	motionId = 0;
		//d.title = 'motionId:  ' + motionId;
		
		loadCount = 0;
		motionIndex = 0;
		frameIndex = 0;
		clearTimeout(motionTimeout);
		clearTimeout(frameTimeout);
		frameArray = new Array();
		motionArray = new Array();
		
		this.getCookie();
		self.genCharacter();
	};
	
	this.getCookie = function()
	{
		var date = new Date();
		var time = date.getTime();
		//alert(time);
		
		if (getCookie('characterTime') == '')
		{
			setCookie('characterTime', time, 60);
			return true;
		}
		else
		{
			var cookieTime = getCookie('characterTime');
			//alert(cookieTime);
			
			if (time - cookieTime >= limitTime)
			{
				setCookie('characterTime', time, 60);
				return true;
			}
			else
			{
				return false;
			}
		}
	};

	this.resizeDiv = function()
	{
		contentW = container.offsetWidth;
		contentH = container.offsetHeight;
		
		offsetX = contentW - fixW;
		offsetY = contentH - fixH;
		
		//var isIpad = (navigator.userAgent.toLowerCase().search('ipad') > -1);
		//if (isIpad)	offsetX -= 30;
		//if (isIpad)	offsetY -= 30;
	};

	this.genCharacter = function()
	{
		character = createDiv('character');
		character.img = createImg(cloudServer + 'en/images/spacer.gif');
		character.appendChild(character.img);
		character.style.display = 'none';
		
		self.preloadImages(characterArray[motionId].frames);
	};

	this.preloadImages = function(array)
	{
		frameArray = array;
		frameTotal = array.length;
		
		for (var i=0; i<frameTotal; i++)
		{
			var img = new Image()
			img.src = cloudServer + array[i].img;
			//img.onload = function()
			var imgOnLoad = function()
			{
				self.imgLoadComplete();
			}
			addEvent (img, 'load', imgOnLoad);
			//if (img.complete)	self.imgLoadComplete();
		}
		
		//Direct Go
		directGoTimeout = setTimeout(function()
		{
			self.imgLoadComplete(true);
		}, 2000);
	};
	
	this.imgLoadComplete = function(directGo)
	{
		loadCount ++;
		//alert(loadCount + "  :  " + frameTotal);
		if (loadCount >= frameTotal || directGo)
		{
			//alert('Load Complete!!!');
			clearTimeout(directGoTimeout);
			
			this.motionInit();
		}
	};
	
	this.motionInit = function()
	{
		motionArray = characterArray[motionId].motion;
		motionTotal = motionArray.length;
		
		container.appendChild(character);
		
		setTimeout(function()
		{
			$('#character').css({'display':'block'});
			self.motionGo(0);
			
			self.framesInit();
		}, 10);
	};
	
	this.motionGo = function(i)
	{
		//var initX = motionArray[i].initX + Math.round(offsetX*(fixW/contentW));
		//var endX = motionArray[i].endX + Math.round(offsetX*(fixW/contentW));
		var initX = motionArray[i].initX;
		var endX = motionArray[i].endX;
		var initY = motionArray[i].initY;
		var endY = motionArray[i].endY;
		if (motionArray[i].initXMode == 'R')	initX += offsetX;
		if (motionArray[i].endXMode == 'R')		endX += offsetX;
		if (motionArray[i].initYMode == 'B')	initY += offsetY;
		if (motionArray[i].endYMode == 'B')		endY += offsetY;
		//alert(initX + '  :  ' + initY);
		
		if (animateClass)	animateClass.stop();
		$('#character').css({'left':initX, 'top':initY});
		
		if (motionArray[i].initX == motionArray[i].endX && motionArray[i].initY == motionArray[i].endY)
		{
			setTimeout(function()
			{
				motionIndex ++;
				if (motionIndex < motionTotal)
				{
					self.motionGo(motionIndex);
				}
				else
				{
					//alert('complete!!');
					container.removeChild(character);
				}
			}, motionArray[i].time);
		}
		else
		{
			animateClass = $('#character').animate({'left':endX, 'top':endY}, motionArray[i].time, '', function()
			{
				motionIndex ++;
				if (motionIndex < motionTotal)
				{
					self.motionGo(motionIndex);
				}
				else
				{
					container.removeChild(character);
					//alert('complete!!');
				}
			});
		}
	};
	
	this.framesInit = function()
	{
		this.framesGo(0);
	};
	
	this.framesGo = function(i)
	{
		character.img.src = cloudServer + frameArray[i].img;
		character.img.width = frameArray[i].w;
		character.img.height = frameArray[i].h;
		
		frameTimeout = setTimeout(function()
		{
			frameIndex ++;
			if (frameIndex < frameTotal)
			{
				self.framesGo(frameIndex);
			}
		}, frameRate*frameArray[i].frame);
	};

	this.init();
}

function setAnnouncement()
{
	var container = d.getElementById('announcement');
	var annContent = getElementsByClassName(container, 'item')[0];
	var annNav = d.getElementById('slide');
	
	var nav = d.getElementById('btn_announcement');
	var btn = nav.getElementsByTagName('a')[0];
	
	var navList = new Array();
	var navReady = true;
	var total;
	var section;
	var timeout;
	var time = 7000;
	var curIndex = 0;
	var isOpen = false;
	var self = this;
	
	this.init = function()
	{
		if (!isnewvisit)		return;
		if (!announcementList)	return;
		
		total = announcementList.length;
		if (total == 0)	return;
		
		isOpen = Boolean(isnewvisit == 'Y');
		//isOpen = true;
		
		this.genContents();
	};
	
	this.open = function()
	{
		setTimeout(function()
		{
			$(btn).click();
			
			//self.navClick(navList[0]);
			self.autoGo();
		}, 500);
	};
	
	this.genContents = function()
	{
		container.onmouseover = function()
		{
			clearTimeout(timeout);
		};
		container.onmouseout = function()
		{
			self.autoGo();
		};
		
		btn.onclick = function()
		{
			if (section == 0)	return;
			self.navClick(navList[0]);
			self.autoGo();
		}
		
		this.genNav();
		
		nav.style.display = 'block';
		if (isOpen)	this.open();
	};
	
	this.genNav = function()
	{
		for (var i=0; i<total; i++)
		{
			var a = createA('javascript:;');
			a.num = i;
			a.id = 'item' + (i + 1);
			
			a.onmouseover = function()
			{
				clearTimeout(timeout);
			};
			a.onmouseout = function()
			{
				self.autoGo();
			};
			a.onclick = function()
			{
				if (section == this.num)	return;
				//if (!navReady)	return;
				self.navClick(this);
				self.autoStop();
			}
			annNav.appendChild(a);
			navList.push(a);
		}
		
		//this.navClick(navList[0]);
	};
	
	this.navClick = function(btn)
	{
		if (!isNaN(section))
		{
			var highlightNav = navList[section];
		}
		
		btn.className += ' active';
		if (highlightNav)	highlightNav.className = highlightNav.className.replace(/active/g, '');
		
		//Change Content
		if (highlightNav)
		{
			/*$(annContent).css({'opacity':1});
			$(annContent).animate({'opacity':0}, 100, function()
			{
				genContent();
				$(annContent).animate({'opacity':1}, 300);
			});*/
			
			genContent();
			$(annContent).css({'opacity':0});
			$(annContent).animate({'opacity':1}, 400);
		}
		else
		{
			genContent();
			$(annContent).css({'opacity':0});
			$(annContent).animate({'opacity':1}, 300);
		}
		
		function genContent()
		{
			var p = d.createElement('p');
			p.innerHTML = announcementList[btn.num].Detail[lang];
			annContent.innerHTML = '';
			annContent.appendChild(p);
			
			section = btn.num;
			curIndex = section;
			navReady = true;
		};
		
		navReady = false;
	};
	
	this.autoGo = function()
	{
		//return;
		clearTimeout(timeout);
		timeout = setInterval(function()
		{
			curIndex ++;
			if (curIndex >= total)	curIndex = 0;
			
			self.navClick(navList[curIndex]);
		}, time);
	};
	
	this.autoStop = function()
	{
		return;
		clearTimeout(timeout);
		self.autoGo();
	};
	
	this.init();
}
