var preloadFlag = false;
var mouseX = 0;
var mouseY = 0;

var usingIE = false;
var usingFF = false;
var usingSF = false;
var usingCR = false;
var usingiPhone = false;
var usingIPad = false;
var usingMac = false;

var tooltips = new String();


/////////// Top Google Search box setting
var googleSearchIframeName = "cse-search-results";
var googleSearchFormName = "cse-search-box";
var googleSearchFrameWidth = 990;
var googleSearchDomain = "www.google.com";
var googleSearchPath = "/cse";

if(navigator.userAgent.indexOf('Macintosh')>0)
	usingMac = true;

if(navigator.userAgent.indexOf('iPhone')>0)		//iPhone first, followed by Safari, Macintosh
	usingIPhone = true;
else if(navigator.userAgent.indexOf('Chrome')>0)
	usingCR = true;
else if(navigator.userAgent.indexOf('Safari')>0)			
	usingSF = true;
else if(navigator.userAgent.indexOf('iPad')>0)
	usingIPad = true;
else if(navigator.userAgent.indexOf('Firefox')>0)
	usingFF = true;
else if(navigator.userAgent.indexOf('MSIE')>0)
	usingIE = true;

var actionAfterClose = null;	//run after showHide();

Array.prototype.getUniqueValues=function(){var h = new Object();for(j=0; j<this.length; j++)h[this[j]] = true;var a=new Array();for(v in h)a.push(v);return a;}
String.prototype.trim=function(){return this.replace(/^\s*|\s*$/g,"");}

String.prototype.substr_count = function (substring) {
	var ret = 0; 
	for(var i=0; i<this.length; i++) { 
		if (substring == this.substr(i, substring.length)) 
			ret++;
	} 
	return ret;
}

function removeHTMLTags(s){s=s.replace(/&(lt|gt);/g,function(strMatch,p1){return (p1=="lt")?"<":">";});return s.replace(/<\/?[^>]+(>|$)/g,"");}
function padzero(n,l){var s=''+n;while(s.length<l){s='0'+s;}return s;}
function getToday(){var d=new Date();return d.getFullYear() + "-" + padzero((d.getMonth()+1),2) + "-" + padzero(d.getDate(),2);}
function getNow(){var d=new Date();return d.getFullYear() + "-" + padzero((d.getMonth()+1),2) + "-" + padzero(d.getDate(),2) + " " + padzero(d.getHours(),2) + ":" + padzero(d.getMinutes(),2)+ ":" + padzero(d.getSeconds(),2);}

//return the type of a variable
function realTypeOf(obj) {return Object.prototype.toString.call(obj).slice(8, -1);} 
function getFileExtension(f){return(/[.]/.exec(f)) ? /[^.]+$/.exec(f) : undefined;}
function getFileName(f){return f.replace(/^.*(\\|\/|\:)/, '');}

function getObject(id){

	if(document.getElementById){
		return document.getElementById(id);
	}
	else if(document.all){
		return document.all[id];
	}
	return null;
}

function getElement(formObj, name)
{
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.name==name)
			return e;
	}
}

function debug()
{
	var ret = new String();
	for(var i=0; i<arguments.length; i++)
		ret += '[' + arguments[i] + ']\n';
    alert(ret);
}

function charDebug(str)
{
	var ret = new String();
	for(var i=0; i<str.length; i++)
		ret += i + ' [' + str.substring(i, i+1) + ']\n';
	alert(ret);
}

var afterCloseAction = new String();
function showPopup(HTMLmesg, offsetX, offsetY, absolute_position)
{
	var bsd = getObject('blackoutScreenDIV');
	if(HTMLmesg==null || HTMLmesg==0) {
		jQuery("#div_popup").fadeOut();
		if(bsd!=null)
			jQuery("#blackoutScreenDIV").fadeOut();
		if(afterCloseAction!=null && afterCloseAction.length>0)
			eval(afterCloseAction);
		return;
	}
	HTMLmesg = "<table cellpadding=0 cellspacing=0 border=0>" +
				"<TR><TD align=right height=20 valign=top><a href=# onClick='showPopup(); return false;'><img src=http://www.hkatv.com/v5/_image/btn-close.png border=0 title='關閉 关闭 Close'></a></td>" +
				"<tr><TD>" + HTMLmesg + "</td></table>";

	jQuery("#div_popup_content").html(HTMLmesg);

	if(absolute_position!=null && absolute_position=='blackout') {
		jQuery('#blackoutScreenDIV').css({'opacity':0.7, 'width':jQuery(document).width(), 'height':jQuery(document).height()});   	
		jQuery('#blackoutScreenDIV').fadeIn('fast');
	}

	if(offsetX!=null) {
		if(absolute_position==null)
			jQuery("#div_popup").css("left", mouseX+offsetX);
		else if(absolute_position!='center' && absolute_position!='blackout')
			jQuery("#div_popup").css("left", offsetX);
	}
	if(offsetY!=null) {
		if(absolute_position==null)
			jQuery("#div_popup").css("top", mouseY+offsetY);
		else if(absolute_position=='center' || absolute_position=='blackout') {
			jQuery("#div_popup").center();
		} else
			jQuery("#div_popup").css("top", offsetY);
	}
	if( jQuery("#div_popup").css("display")=='none' ) {
		jQuery("#div_popup").fadeIn();
	}
}

function getQueryString(p){p=p.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]").toLowerCase();var r="[\\?&]"+p+"=([^&#]*)";var rx=new RegExp(r);var rr=rx.exec(window.location.href.toLowerCase());if(rr==null)return "";else return rr[1];} 

//e.g. var e = document.form1.elements['discount'+i]
//     getCheckedValue(e);
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// get checkbox or radio value by element name
// e.g.   var value = getCheckedValue2(document.form1, 'choices[]');
function getCheckedValue2(formObj, elementName) {
	if(formObj==null || elementName==null || elementName.length<0)
		return "";
	
	var ret = 0;
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.name==elementName && (e.type=='checkbox' || e.type=='radio') && e.checked)
			ret += e.value;
	}
	return ret;
}



function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


//remove duplciated values and split into correct lines
function normalizeInput(obj, delimiter)
{
	if(delimiter==null)
		delimiter = "\n";
	ret = obj.value.trim().split(/\s|[^A-Za-z0-9_.@-]/).getUniqueValues();
	ret.sort();
	obj.value = ret[0];
	for(i=1; i<ret.length; i++)
		obj.value += delimiter + ret[i];
}

function validateEmail(elementValue){   
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;   
   return emailPattern.test(elementValue);   
}  

function verifyEmail(formElement, mesgDIV)
{
	if(mesgDIV==null)
		return validateEmail(formElement.value);
	else {
		getObject(mesgDIV).innerHTML = "";
	}

	if(formElement.value==null || formElement.value.length<1)
		return;

	if(!validateEmail(formElement.value)) {
		formElement.focus();
		//formElement.value = '';
		getObject(mesgDIV).innerHTML = "Invalid Email address!";
	}
}

function MM_preloadImages() {var d=document;if(d.images){if(!d.MM_p)d.MM_p=new Array();var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0;i<a.length;i++)if(a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}}
function getImageRealDim(src){var t=new Image();t.src = src;return new Array(t.width, t.height);}
function reloadImg(id){var o=document.getElementById(id);if(o==null){alert('No image to reload');return false;}var s=o.src;var p=s.indexOf('?');if(p>=0){s=s.substr(0,p);}var d=new Date();o.src =s+'?v='+d.getTime();return false;}

function openWin(url, w, h, name, offsetW, offsetH, left)
{
	if(w==null || w==0)		w = screen.width - 50;
	else if(w>screen.width)	w = screen.width;

	if(h==null || h==0)      h = screen.height - 150;
	else if(h>screen.height)  h = screen.height;

	if(name==null || name.length<1)
		name = 'newwin';
	
	var l = (screen.width - w) / 2; 
	var t = (screen.height - h) / 2 ;
	if(offsetW!=null)
		l += offsetW;
	if(offsetH!=null)
		t += offsetH;
	if(left!=null)
		l = left;

	win = window.open(url, name, "width=" + w + ",height=" + h + ",top="+t+",left="+l+"resizable=1,scrollbars=1,status=1");
	if(win==null) {
		var lang=1;
		var pos = url.indexOf("LANG=");
		if(pos>0)
			lang = url.substr(pos+5, 1);
		if(lang==2)
			alert('对不起, 请容许浏览器跳出窗口或按着 Ctrl 再点');
		else if(lang==3)
			alert('對不起, 請容許瀏覽器彈出視窗或按著 Ctrl 再點擊');
		else
			alert('Sorry, please allow Pop-up on your Browser or hold Ctrl and click again');
	} else
		win.focus()
}

// make windows full screen
function maxWindow()
{
	window.moveTo(0,0);
	if(document.all) {
		top.window.resizeTo(screen.availWidth, screen.availHeight);
	} else if (document.layers||document.getElementById) {
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth)
		{
			top.window.outerHeight = screen.availHeight;
			top.window.outerWidth = screen.availWidth;
		}
	}
}

function webtv(url)
{
	if(!url){
		url = "http://app2.hkatv.com/v5/video/video.php";
	} else {
		if(url.search(/www.hkatv.com/gi)>0)
			url = url.replace ('www.hkatv.com', 'app2.hkatv.com');
		else if(url.search(/app.hkatv.com/gi)<0 && url.search(/app2.hkatv.com/gi)<0) {
			url = 'http://app2.hkatv.com' + url;
		}
		
		if(url.search(/control.php/gi)>0) {
			url = url.replace ('webtv/control.php', 'v5/video/video.php');
		}
	}
	remote = window.open(url, "webtv", 
		"toolbar=0,width=685,height=402,resizable=0,status=0," +
		"menubar=0,toolbar=0," 
		+ "scrollbars=1,directories=0,copyhistory=no,top=0,left=0");
	if(remote != null) remote.focus()
}

//simple show hide effect by jQuery
function showHide(layer_name)
{
	layer_name = '#' + layer_name
	var d = jQuery(layer_name).css('display');
	if(d=='none') {
		jQuery(layer_name).fadeIn();
	} else {
		if(jQuery("#blackoutScreenDIV").length>0)
			jQuery("#blackoutScreenDIV").fadeOut();
		jQuery(layer_name).fadeOut();
		if(actionAfterClose!=null) {
			eval(actionAfterClose);
			actionAfterClose = null;
		}
	}
}

function convertFormData(formObj)
{
	if(formObj==null || formObj.elements==null) {
		alert('submitForm: formObj is null');
		return;
	}
	var postString = "";
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if((e.type=='radio' || e.type=='checkbox') && !e.checked)
			continue;
		if(e.name.length>0 && e.value.length>0)
			postString = postString + e.name + '=' + EncodeParm(e.value) + '&';
	}
	return postString.slice(0, -1);	//remove the last '&';
}

function clearForm(formObj)
{
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.type=='hidden' || e.type=='button' || e.type=='submit')
			continue;
		if(e.type=='select-one')
			e.selectedIndex = 0;
		else if(e.type=='checkbox' || e.type=='radio')
			e.checked = false
		else {
			e.value = '';
		}
	}
}

function submitForm(formObj)
{
	if(formObj==null || formObj.elements==null) {
		alert('submitForm: formObj is null');
		return;
	}
	var postString = "";
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if((e.type=='radio' || e.type=='checkbox') && !e.checked)
			continue;
		if(e.name.length>0 && e.value.length>0)
			postString = postString + e.name + '=' + EncodeParm(e.value) + '&';
	}
	return postString.slice(0, -1);	//remove the last '&';
}


function checkAll(formObj, v) 
{
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.type=='checkbox')
			e.checked = v;
	}
}
 
//http://techpatterns.com/downloads/javascript_cookies.php
function Set_Cookie(name, value, expires, path, domain, secure) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	//if the expires variable is set, make the correct 
	//expires time, the current script below will set 
	//it for x number of days, to make it for hours, 
	//delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	var cookieStr = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) +  ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
//	alert(cookieStr);
	document.cookie = cookieStr;
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
		return null;
}

function changeLang(goSimp)
{
	var url = self.location.href.replace('#', '');
	if(goSimp!=null && url.substring(0,21)=='http://www.hkatv.com/')
	{
		self.location.href = 'http://www.hkatv.com.cn/' + url.substring(21, url.length);
	}
	else if (url.substring(0,24)=='http://www.hkatv.com.cn/')
	{
		self.location.href = 'http://www.hkatv.com/' + url.substring(24, url.length);
	} 
	else if(goSimp==null)	// go to traditional version
		self.location.href = 'http://www.hkatv.com/v3/';
	else
		self.location.href = 'http://www.hkatv.com.cn/v3/';
}

function changeLanguage(no_cookie)
{
	var url = self.location.href;
	var cookie = 'hk';

	if(url.indexOf('.php')>0) 
	{
		if(url.indexOf('&cn=1')>0) {
			url = url.replace('&cn=1', '');
		} else if(url.indexOf('?cn=1&')>0) {
			url = url.replace('cn=1&', '');
		} else if(url.indexOf('?cn=1')>0) {
			url = url.replace('?cn=1', '');
		} else {
			cookie = 'cn';
			if(url.indexOf('?')>0) {
				if(url.indexOf('cn=0')>0)
					url = url.replace('cn=0', 'cn=1');
				else
					url = url + '&cn=1';
			} else
				url = url + '?cn=1';
		}
	} 
	else
	{
		if(url.indexOf('.html')<0 ) {		//add html at the end
			cookie = 'cn';
			if(url.substr(url.length-1, 1)=='/')
				url = 'http://' + window.location.host + window.location.pathname + 'index_cn.html';
			else
				url = 'http://' + window.location.host + window.location.pathname + '/index_cn.html';
		} 
		else if(url.indexOf('_cn')>0) {		//in simplified language
			url = url.replace('_cn', '');
		} 
		else {
			cookie = 'cn';
			if(url.indexOf('?')>0)
				url = 'http://' + window.location.host + window.location.pathname.match(/[^\.]+/) + "_cn." + getFileExtension(window.location.pathname) + url.substring(url.indexOf('?'));
			else {
				url = 'http://' + window.location.host + window.location.pathname.match(/[^\.]+/) + "_cn." + getFileExtension(window.location.pathname) + window.location.hash;
			}
		}
	}
	if(no_cookie==null)
		Set_Cookie('Language', cookie, 60, '/'); 
	self.parent.location.href = url;
}

//useful when transferring data by AJAX
//http://www.webtoolkit.info/javascript-url-decode-encode.html
function urlEncode(string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
 	for (var n = 0; n < string.length; n++) {
		var c = string.charCodeAt(n);
 		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	return escape(utftext);
}

function EncodeParm(str)
{
	var ret = encodeURI(str);
	ret = ret.replace(/&amp;/g, "%26");
	ret = ret.replace(/&/g, "%26");
	return ret.replace(/[+]/g, "%2B");
}

function tradSimpConvert(s, o, is){showWaiting(1);var p='t='+EncodeParm(s);if(is!=null)p+='&isSimp=1';AJAXconnect('/v5/ajax-simptrad.php', p, tsc_cb, o);}
function tsc_cb(o){showWaiting();o.value=ajax_request.responseText;}

/******** general function for fetching dynamic result by HTTP *********/
// IMPORTANT: for firefox/netscape, this works only when file is on the server. local calling has no effect
function httpConnect(url, objInnerHTML, objValue, alertString)
{
	var xmlhttp = null;
	if (window.XMLHttpRequest)
		xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject)
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 
	//does not support XMLHTTP, use popup instead
	if (xmlhttp == null)
	{
		alert("Please use IE6.0 or above to visit this site.\n请使用 IE 6.0 或更高版本 (1)");
	}
	else {
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function(){ 

			if (xmlhttp.readyState != 4)
				return; 
			if (xmlhttp.status == 200)
			{
				if(objInnerHTML!=null)
					objInnerHTML.innerHTML = xmlhttp.responseText;
				else if(objValue!=null) 
					objValue.value = xmlhttp.responseText;
				else if(alertString!=null) 
					alert(alertString + xmlhttp.responseText);
				// it cannot return value. value is passed by reference.
			} 
			else
			{
				alert("Please use IE6.0 or above to visit this site.\n请使用 IE 6.0 或更高版本 (2)");
			}
		}
		xmlhttp.send(null);
	}
}

//http://www.captain.at/howto-ajax-form-post-request.php
var http_request = false;
function makePOSTRequest(url, parameters) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!http_request) {
		alert('There is some problem with your browser. Cannot create XMLHTTP instance. We are going to send your message in traditional way!');
		document.form1.action = 'contactusSend.php';
		document.form1.submit();
		return false;
	}
  
	http_request.onreadystatechange = httpPostRequestHandler;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}



/************  the following is just an example
               you should always write your own httpPostRequestHandler()
//////////////////////////////////////////////////////////////////////
function httpPostRequestHandler() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			result = http_request.responseText;
		} else {
			alert('There was a problem with the request.');
		}
	}
}
**************************************************************************/

/******************** latest version for AJAX request, 2010-9-16 **************/
//be careful  url doesn't end with '?'
var ajax_request = false;
function AJAXconnect(url, parameters, handlerFunction, handlerFunctionParam) {
	ajax_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		ajax_request = new XMLHttpRequest();
		if (ajax_request.overrideMimeType) {
			ajax_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!ajax_request) {
		alert('Error AJAXconnect()');
		showWaiting();
		return false;
	}
	ajax_request.onreadystatechange = function() {
		if (ajax_request.readyState == 4) {
			if (ajax_request.status == 200) {
				handlerFunction(handlerFunctionParam);
			} else {
				alert('Error AJAXconnect() 2');
			}
		}
	}
	ajax_request.open('POST', url, true);
	ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajax_request.setRequestHeader("Content-length", parameters.length);
	ajax_request.setRequestHeader("Connection", "close");
	ajax_request.send(parameters);
}

/*
function handlerFunction(handlerFunctionParam)
{
	alert(ajax_request.responseText);
}
*/

function submitFormAJAX(url, formObj, handlerFunction, handlerFunctionParam, debug) {
	var xhr = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xhr = new XMLHttpRequest();
		if (xhr.overrideMimeType) {
			xhr.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!xhr) {
		alert('Error submitFormAJAX(). AJAX function not available.');
		showWaiting();
		return false;
	}
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				handlerFunction(xhr.responseText, handlerFunctionParam);
			} else {
				alert('Error submitFormAJAX(). No response from url. ('+xhr.status+')');
				showWaiting();
			}
		} 
	}
	var parameters = convertFormData(formObj) + '&dummy=' + new Date().getTime();
	if(debug!=null)
		alert(parameters);

	xhr.open('POST', url, true);
	//xhr.timeout = 5000;
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", parameters.length);
	xhr.setRequestHeader("Connection", "close");
	xhr.send(parameters);
}

//////////////////////////////////////////// tool tips function

function showTips(url, lang)
{
	var subobj = document.getElementById('tipsBox');
	if(subobj==null)
		return;

	subobj.style.width = 600;
	subobj.style.height = 300;

	if(usingIE) {
		subobj.style.left = 260; //(document.body.clientWidth - parseInt(subobj.style.width))/2;
		subobj.style.top = (document.body.clientHeight - parseInt(subobj.style.height))/2;
	} else {
		subobj.style.left = 260; //(window.innerWidth - parseInt(subobj.style.width))/2;
		subobj.style.top = (window.innerHeight - parseInt(subobj.style.height))/2;
	}
	httpConnect('http://www.pandaoffice.com/v1/ajax/tooltips.php?url='+url+'&LANG='+lang, subobj);

	// you must display it only when it really has content. displaying an empty DIV causes problems in IE7.
	setTimeout( function() 
		{
			if(subobj.innerHTML.length>0) {
				subobj.style.display = "block";
			} 
		}, 
	500); 
}

function closeToolTips(url, lang)
{
	var subobj = document.getElementById('tipsBox');
	if(subobj==null)
		return;

	if(url=='noMoreTips') {
		httpConnect('http://www.pandaoffice.com/v1/ajax/tooltips.php?action=closed&url='+url+'&LANG='+lang, subobj);
	} else {
		subobj.style.display = "none";
		if(url!=null)
			httpConnect('http://www.pandaoffice.com/v1/ajax/tooltips.php?action=closed&url='+url);
	}
}

if(typeof jQuery != 'undefined') {
	jQuery.fn.center = function () {     
		this.css("position", "absolute");     
		this.css("top", (jQuery(window).height() - this.height() ) / 2 + jQuery(window).scrollTop() + "px");     
		this.css("left", (jQuery(window).width() - this.width() ) / 2 + jQuery(window).scrollLeft() + "px");     
		return this; 
	} 

	jQuery.fn.moi = function() {
		this.hover(
			function() {
				jQuery(this).fadeTo(400, 0.7);
				var filename = jQuery(this).attr("src");
				if(filename.indexOf('-over.')<0) {
					var src = jQuery(this).attr("src").match(/[^\.]+/) + "-over." + getFileExtension(filename);         
					jQuery(this).attr("src", src); 
				}
			},
			function() {
				jQuery(this).fadeTo(200, 1);
				var src = jQuery(this).attr("src").replace("-over", "");   
				jQuery(this).attr("src", src); 
			}
		);
	}

	//dim for every kind of image when mouseover EXCEPT for PNG in IE
	jQuery.fn.moi_dim = function () {     
		this.hover(
			function() {
				var extension = getFileExtension( jQuery(this).attr("src") );
				if(extension=='png' && usingIE)
					return;
				jQuery(this).fadeTo(400, 0.7);
			},
			function() {
				var extension = getFileExtension( jQuery(this).attr("src") );
				if(extension=='png' && usingIE)
					return;
				jQuery(this).fadeTo(200, 1);
			}
		);
	} 

	//dim for every kind of image when mouseover
	jQuery.fn.moi_dim2 = function () {     
		this.hover(
			function() {
				jQuery(this).fadeTo(400, 0.7);
			},
			function() {
				jQuery(this).fadeTo(200, 1);
			}
		);
	} 

	//it's better to put outside
	var currentClicked_id = new String();
	jQuery.fn.moi_selected = function() {
		this.click(function(){
			currentClicked_id = jQuery(this).attr('id');
			jQuery(this).fadeTo(10, 1);

			jQuery(this).parents("TABLE").find("IMG").each(function(){
				var obj = jQuery(this);
				if(obj.attr('id')!=currentClicked_id) {
					var src = obj.attr("src").replace("-over", "");   
					obj.attr("src", src); 
				}
			});

		})
		this.hover(
			function() {
				var id = jQuery(this).attr("id");
				if(currentClicked_id!=id) {
					jQuery(this).fadeTo(400, 0.7);
					var filename = jQuery(this).attr("src");
					if(filename.indexOf('-over.')<0) {
						var src = jQuery(this).attr("src").match(/[^\.]+/) + "-over." + getFileExtension(filename);    
						jQuery(this).attr("src", src); 
					}
				} 
			},
			function() {
				var id = jQuery(this).attr("id");
				if(currentClicked_id!=id) {
					jQuery(this).fadeTo(200, 1);
					var src = jQuery(this).attr("src").replace("-over", "");   
					jQuery(this).attr("src", src); 
				} 
			}
		);
	}

}

function printShare(cn)
{
	document.write('<table height=30 cellpadding=0 cellspacing=0 border=0><TR>');
	
	if(cn==null || cn==0) {
		document.write("<TD align=left style='padding-left:7px;'><a href=http://www.facebook.com/hkatv target=_blank><img src=http://www.hkatv.com/v3/_image/logo-facebook.png border=0></a></td>");
		document.write("<td> &nbsp; &nbsp; <a href=http://www.youtube.com/hkatv target=_blank><img src=http://www.hkatv.com/v5/_image/logo-youtube.jpg></a></td>");
	}
	document.write("<td> &nbsp; &nbsp; <a href=http://weibo.com/2010hkatv target=_blank><img src=http://www.hkatv.com/v5/_image/logo-sinaweibo.png></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=http://www.three.com.hk/website/appmanager/three/home?_nfpb=true&_pageLabel=P400328951219906687968&lang=eng&pageid=361301 target=_blank><img src=http://www.hkatv.com/v5/_image/logo-three.png></a></td>");
	document.write("<td align=left style='padding: 0px 5px 0px 40px'><img src=http://www.hkatv.com/v5/_image/arrow-green.png></td>");
	document.write("<td align=left style='padding: 0px 20px 0px 0px' class=clr_dgrey>分享至 </td>");

	if(cn==null || cn==0) {
		document.write("<td align=left valign=middle><a rel='nofollow' href='http://www.facebook.com/share.php?u=<;url>' onclick='return fb_share_click()' target=_blank style='text-decoration:none;'><img src=http://www.hkatv.com/v5/_image/logo-facebookshare.gif title='分享本頁至facebook'></a></td>");
	}
		
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(1); return false'><img src=http://www.hkatv.com/v5/_image/logo-weibo.gif></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(2); return false'><img src=http://www.hkatv.com/v5/_image/logo-renren.gif></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(3); return false'><img src=http://www.hkatv.com/v5/_image/logo-qq.gif></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(4); return false'><img src=http://www.hkatv.com/v5/_image/logo-kaixin.gif></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(5); return false'><img src=http://www.hkatv.com/v5/_image/logo-todou.gif></a></td>");
	document.write("<td> &nbsp; &nbsp; <a href=# onClick='shareToNetwork(6); return false'><img src=http://www.hkatv.com/v5/_image/logo-163.gif></a></td>");
	document.write("</table>");
}

function shareToNetwork(n, target_uri)
{
	if(n==null || n<1 || n>6)	return;
	var url = new String();
	var name = new String();
	var param = 'toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=360';
	var uri = window.location.href;
	if(target_uri!=null)
		uri = target_uri;
	var title = encodeURIComponent(document.title);
	if(n==1)
	{
		url = 'http://v.t.sina.com.cn/share/share.php?title=' + title + '&url=' + uri + '&source=bookmark';
		name = 'sina';
		param = 'toolbar=0,resizable=1,scrollbars=yes,status=1,width=610,height=360';
	}
	if(n==2)
	{
		url = 'http://share.renren.com/share/buttonshare.do?link='+uri+'&title='+title;
		name = 'fav_renren';
		param = 'toolbar=0,resizable=1,scrollbars=yes,status=1,width=610,height=360';
	}
	if(n==3) 
	{
		url = 'http://shuqian.qq.com/post?from=3&title=' + title + '&uri=' + uri + '&jumpback=2&noui=1';
		name = 'favit';
		param = 'width=930,height=470,left=50,top=50,toolbar=no,menubar=no,location=no,scrollbars=yes,status=yes,resizable=yes';
	}
	if(n==4)
	{
		url = 'http://www.kaixin001.com/repaste/share.php?rtitle='+title+'&rurl='+uri+'&rcontent='
		name = 'fav_kaixin';
	}
	if(n==5)
	{
		url = 'http://www.douban.com/recommend/?url=' + uri + '&title='+title;
		name = 'douban';
	}
	if(n==6)
	{
		url = 'http://t.163.com/article/user/checkLogin.do?link=http://news.163.com/&info=' + title + ' ' + uri + '&' + new Date().getTime();
		name = 'netease';
		param = 'toolbar=0,resizable=1,scrollbars=yes,status=1,width=710,height=480';
	}
	window.open(url, name, param);
}

//the following requires   getMouseXY(e) to be activated and must have the following HTML code at the bottom of the document
//<div id="waitingDIV" style="position:absolute; display:none; top: 0px; left: 0px; width=100%; height=100%;"><table width=100% bgcolor=white><TR><TD align=center><img src=/v1/_image/loading.gif></td></table></div>
function showWaiting(mode)
{
	var obj = getObject('waitingDIV');
	if(obj==null)	{
		if(typeof jQuery=='undefined') { 
			alert("showWaiting cannot find \'waitingDIV\'");
			return;
		} else {
			jQuery("<div id='waitingDIV' style='position:absolute; display:none; top: 0px; left: 0px;'><table width=1024><TR bgcolor=#eeeeee><TD align=center><img src=http://www.hkatv.com/v5/_image/loading.gif></td></table></div>").appendTo("body")
			obj = getObject('waitingDIV');		
		}
	}
	if(mode==null || mode==0)
		obj.style.display = 'none';
	else {
		if(typeof jQuery!='undefined') { 
			jQuery("#waitingDIV").children().css('width', jQuery(window).width());
			jQuery("#waitingDIV").center();
		} else if(mouseY!=null && mouseY>0) {
			var y = mouseY + 25;
			obj.style.top = y + 'px';
		}
		obj.style.display = 'block';
	}
}

//facebook share button
function fb_share_click() { 
	u = location.href;
	t = document.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436');
	return false;
}

var isMouseOver = 0;
var sto = null;
function setMouseOverState(flag)
{
	if(flag!=null) {
		clearTimeout(sto);	//to cancel  sto = setTimeout("isMouseOver=0", 2000); in showMenu();
		isMouseOver = flag;
	}
}

function hideMenu(state)
{
	if(state==null) {
		isMouseOver = 0;
		setTimeout("hideMenu(1);", 1000);	
	} else if(isMouseOver==0) {
		if(jQuery('#div_MediaPlayer').length>0 && jQuery('#div_MediaPlayer').css('left')!='0px')
			jQuery('#div_MediaPlayer').css('left', '0px');
		jQuery('#div_mesgbox').fadeOut('fast');
	}
}

var lastClickedMenuButton = null
function showMenu(obj, no)
{
	var x = -55;
	var y = 5;
	if(obj==null) {
		jQuery('html, body').animate({scrollTop: 0}, 500);
		if(no==1)
			obj = '#btn_schedule';
		else if(no==2)
			obj = '#btn_homechannel';
		else if(no==3)
			obj = '#btn_asiachannel';
		else if(no==4)
			obj = '#btn_worldchannel';
		if(!usingIE)
			y = 46;	
	}

	var box = jQuery('#div_mesgbox');
	isMouseOver = 1;	
	sto = setTimeout("isMouseOver=0", 2000);		//assume mouse is not over after 2 seconds.
	if(obj==lastClickedMenuButton && box.css("display")=='block')
		return;	
	lastClickedMenuButton = obj;
	box.hide();


	//calculating the display coord for the mesgbox
	if(jQuery(obj).length>0) {
		x += jQuery(obj).offset().left;
		y += jQuery(obj).offset().top;
	}
	if(usingIE)
		y += 40;

	var jObject = jQuery('#div_schedule');
	if(no==4) {
		jObject = jQuery('#div_world');
	} else if(no==2) {
		jObject = jQuery('#div_home');
	} else if(no==3) {
		jObject = jQuery('#div_asia');
	}
	var w = jObject.width();
	if(w>180) {
		x = x - (w-170)/2;
		w = Math.round((w-12)/2+0.5);
	} else
		w = 84;		//default minimum width
	jQuery('#div_mesgbox_td1').width(w);
	jQuery('#div_mesgbox_td2').width(w);
	var html = jObject.html();
	jQuery('#div_mesgboxcontent').html(html);

	if(jQuery('#div_MediaPlayer').length>0) {
		if(box.height()>166)
			jQuery('#div_MediaPlayer').css('left', '-1000px');
		else if(jQuery('#div_MediaPlayer').css('left')!='0px')
			jQuery('#div_MediaPlayer').css('left', '0px');
	}

	box.css("left", x);
	box.css("top", y+10);
	box.animate({opacity: "show", top: y}, "500");
}

var popupmesgID = 0;
function showPopupMesg(id, html, bg_width, height)
{
	if(id==null || html==null) {
		var hd = getCheckedValue(document.form_popupMessage.hideDay);
		if(hd!=null && hd>0) {
			Set_Cookie('popupMesg' + popupmesgID, 1, hd); 	
		}
		jQuery('#div_popupMessage').fadeOut('fast');
		return;
	}
	popupmesgID = id;
	if(Get_Cookie('popupMesg' + id)==null) {
		if(bg_width!=null && height!=null) {
			jQuery('#table_popupMessage').css({'background-image':'url(http://www.hkatv.com/v5/_image/bg_popupMessage'+bg_width+'.png)'});
			jQuery('#table_popupMessage').css({'width':bg_width});
			jQuery('#table_popupMessage').css({'height':height});
		}
		jQuery('#div_popupMessage_content').html(html);
		jQuery('#div_popupMessage').center();
		jQuery('#div_popupMessage').fadeIn();
	}
}

/* same as showPopupMesg() Just swap paramter position */
function showPopupMesg2(id, html, height, bg_width)
{
	if(id==null || html==null) {
		var hd = getCheckedValue(document.form_popupMessage.hideDay);
		if(hd!=null && hd>0) {
			Set_Cookie('popupMesg' + popupmesgID, 1, hd); 	
		}
		jQuery('#div_popupMessage').fadeOut('fast');
		return;
	}
	popupmesgID = id;
	if(Get_Cookie('popupMesg' + id)==null) {
		if(bg_width!=null && height!=null) {
			jQuery('#table_popupMessage').css({'background-image':'url(http://www.hkatv.com/v5/_image/bg_popupMessage'+height+'.png)'});
			jQuery('#table_popupMessage').css({'width':bg_width});
			jQuery('#table_popupMessage').css({'height':height});
		}
		jQuery('#div_popupMessage_content').html(html);
		jQuery('#div_popupMessage').center();
		jQuery('#div_popupMessage').fadeIn();
	}
}

/* the following functions are mostly used in program contents */
function showProgramContent(id)
{
	if(id.length>20 || jQuery('#'+id).length==0) {
		jQuery('#div_content').html(id);
		return;
	}
	var html = jQuery('#'+id).html();
	jQuery('#div_content').html(html);
}

function showNextweek(pid, cn)
{
	if(cn==null)
		cn = 0;
	var html = "<iframe id=if src=http://app2.hkatv.com/v5/nextweek/nextweek.php?p="+pid+"&cn="+cn+" scrolling=auto frameborder='no' style='position:relative; left: 3px; top: 0px; width:974px; height:520px; z-index:9;'></iframe>";
	jQuery('#div_content').html(html);
}


function showPhoto(obj, caption)
{
	var max_w = jQuery(window).width() - 90;
	var max_h = jQuery(window).height() - 90;
	if(caption==null)
		caption = '';

	if(realTypeOf(obj)=='String')
	{
		jQuery('#blackoutScreenDIV').css({'opacity':0.7, 'width':jQuery(document).width(), 'height':jQuery(document).height()});   	
		jQuery('#blackoutScreenDIV').fadeIn('fast');

		showWaiting(1);
		var src = obj; 
		jQuery('#imagebuffer').attr('src', src);
		jQuery("#imagebuffer").bind("load", function()
		{ 
			var dim = getImageRealDim(src);
			var width = dim[0];
			var height = dim[1];

			var html = '<a href=# onClick="jQuery(\'#div_tooltips\').fadeOut(\'fast\'); jQuery(\'#blackoutScreenDIV\').hide(); return false;">';
			//we try to fix the height
			if(height<max_h && width<max_w) {
				html += '<img id=bigPhoto src=' + src + ' title="'+caption+'"></a>';
			} else {
				if(max_h/height*width > max_w)
					html += '<img id=bigPhoto src=' + src + ' width=' + max_w + ' title="'+caption+'"></a>';
				else
					html += '<img id=bigPhoto src=' + src + ' height=' + max_h + ' title="'+caption+'"></a>';
			}

			showWaiting(); 
			jQuery('#div_tooltips_content').html(html);
			jQuery('#div_tooltips').center();
			jQuery('#div_tooltips').fadeIn();
		}); 

		return;

	} 
	
	var src = jQuery(obj).find("IMG").attr('src');

	var dim = getImageRealDim(src);
	var width = dim[0];
	var height = dim[1];

	var html = '<a href=# onClick="jQuery(\'#div_tooltips\').fadeOut(\'fast\'); jQuery(\'#blackoutScreenDIV\').hide(); return false;">';

	jQuery('#blackoutScreenDIV').css({'opacity':0.7, 'width':jQuery(document).width(), 'height':jQuery(document).height()});   	
	jQuery('#blackoutScreenDIV').fadeIn('fast');

	//we try to fix the height
	if(height<max_h && width<max_w) {
		html += '<img id=bigPhoto src=' + src + ' title="'+caption+'"></a>';
	} else {
		if(max_h/height*width > max_w)
			html += '<img id=bigPhoto src=' + src + ' width=' + max_w + ' title="'+caption+'"></a>';
		else
			html += '<img id=bigPhoto src=' + src + ' height=' + max_h + ' title="'+caption+'"></a>';
	}
	jQuery('#div_tooltips_content').html(html);
	jQuery('#div_tooltips').center();
	jQuery('#div_tooltips').fadeIn();
}
/* END OF the following functions are mostly used in program contents */


function showPopupVideo(pid, cid, cn)
{
	var html = "<table cellpadding=0 cellspacing=0 border=0>" +
				"<TR><TD align=right height=20 valign=top><a href=# onClick='showPopupVideo(0); return false;'><img src=http://www.hkatv.com/v5/_image/btn-close.png border=0 title='關閉 关闭 Close'></a></td>" +
				"<tr><TD><iframe id=if src=http://app2.hkatv.com/v5/video/iframe.php?p=" + pid + "&c=" + cid + "&cn=" + cn + " scrolling=auto frameborder='no' style='position:relative; left: 3px; top: 0px; width:490px; height:370px; z-index:9;'></iframe></td></table>";

	jQuery("#div_popup_content").html(html);
	jQuery("#div_popup").center();
	jQuery("#div_popup").fadeIn();

	if(pid==0) {
		jQuery("#div_popup").hide();
//		if(cn==null || cn==0)
//			alert('關閉影片需要一段時間，請耐心等候');
//		else
//			alert('关闭视频需要一段时间，请耐心等候');
		self.location.reload();
		return;
	}
}

jQuery(document).ready(function($) {
	$(".showtooltips, .showtooltips_nodim").mousemove(function(event) {
		mouseX = event.pageX;
		mouseY = event.pageY;
		var h = jQuery('#div_tooltips').height();
		var w = jQuery('#div_tooltips').width() + mouseX + 10;
		if(w>document.body.clientWidth)
			jQuery('#div_tooltips').css('left', mouseX-10-jQuery('#div_tooltips').width());
		else
			jQuery('#div_tooltips').css('left', mouseX+10);
		jQuery('#div_tooltips').css('top', mouseY-h/3);
	});
	$(".showtooltips").mouseover(function(){
		jQuery(this).fadeTo(400, 0.7);
		jQuery('#div_tooltips_content').html(tooltips);
		jQuery('#div_tooltips').show();
	});
	$(".showtooltips").mouseout(function(){
		jQuery(this).fadeTo(200, 1);
		jQuery('#div_tooltips').hide();
	});
	$(".showtooltips_nodim").mouseover(function(){
		jQuery('#div_tooltips_content').html(tooltips);
		jQuery('#div_tooltips').show();
	});
	$(".showtooltips_nodim").mouseout(function(){
		jQuery('#div_tooltips').hide();
	});

	
	$(".moi").moi();
	$(".moi_dim").moi_dim();
	$(".moi_dim2").moi_dim2();

	setBGposition();

//	var cookie_language = Get_Cookie('Language');
})


///////// https://www.google.com/analytics/provision/tracking?scid=24340047
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24023769-1']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
///////// https://www.google.com/analytics/provision/tracking?scid=24340047


var windowWidth = 0;
function setBGposition()
{
	if(jQuery(window).width()==windowWidth) {
		if(typeof window.alignTableHeight == 'function')
			alignTableHeight();
		MM_preloadImages('http://www.hkatv.com/v5/_image/loading.gif', '_image/menu01-over.gif', '_image/menu02-over.gif', '_image/menu03-over.gif', '_image/menu04-over.gif', '_image/menu05-over.gif');
		return;
	}

	//don't run this function
	if(typeof(dont_setBGposition)!='undefined' && dont_setBGposition!=null && dont_setBGposition)
		return;

	windowWidth = jQuery(window).width();
	var x = -1 * Math.round((1920 - windowWidth)/2 + 0.5);		//1920 is the width of the background image
	if(usingFF)	x = x - 4;										//firefox offset correction
//	if(usingIE)	x = x - 4;										//firefox offset correction
	jQuery('body').css({backgroundPosition: x + 'px 0px'});
	setTimeout("setBGposition()", 500);
}

function searchHotKW(k)
{
	if(self.location.href.indexOf('/archive/')>0) {
		document.form_search.keyword.value = k;
		searchNow(1);
		return;
	}

	if(self.location.href.indexOf('_cn.html')>0 || getQueryString('cn')==1) {
		window.open('http://app2.hkatv.com/v5/archive/archive_cn.html?k=' + k);
	} else
		self.location = 'http://app2.hkatv.com/v5/archive/archive.html?k=' + k;
}
