var userAgent = navigator.userAgent.toLowerCase();
var isOpera = userAgent.indexOf('opera') != -1 && opera.version();
var isMoz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var isIE = (userAgent.indexOf('msie') != -1 && !isOpera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
var isMac = userAgent.indexOf('mac') != -1;
/************************************************************************************************************************************************/
var intval = 0, intvalT = 0;

var con = new Array();
con['country'] = 	new Array(
										'Australia','Bangladesh','Brunei','Cambodia','China','Egypt','France','Germany','Hong Kong','India','Indonesia',
										'Japan','Malaysia','Pakistan','Philippines','Saudi Arabia','Singapore','Spain','Sri Lanka','Switzerland',
										'Thailand','United Arab Emirates','United Kingdom','United States of America','Vietnam'
									);
con['hpdigit'] = new Array();
con['hpdigit'][7] = new Array('Brunei','Germany','Indonesia');
con['hpdigit'][8] = new Array('Cambodia','Hong Kong','Indonesia','Japan','Philippines','Singapore','Spain','Switzerland');
con['hpdigit'][9] = new Array('Australia','Egypt','France','Saudi Arabia','Sri Lanka','Thailand','United Arab Emirates','Vietnam');
con['hpdigit'][10] = new Array('Bangladesh','Malaysia','Pakistan','United Kingdom','United States of America','India');
con['hpdigit'][11] = new Array('China');

con['digitname'] = new Array('zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve');

con['column'] = new Array();
con['column'][99] = {};
con['column'][0] = {'shortname':0,'last':1,'change':2,'chgpct':3,'open':4,'high':5,'low':6,'prev':7,'volume':8};
con['column'][1] = {'shortname':0,'symbol':1,'last':2,'change':3,'chgpct':4,'bidq':5,'bid':6,'ask':7,'askq':8,'open':9,'high':10,'low':11,'prev':12,'volume':13};
con['column'][2] = {'shortname':0,'last':1,'change':2};
con['column'][3] = {'shortname':0,'last':1,'change':2,'chgpct':3};
con['column'][4] = {'longname':0,'last':1,'change':2,'chgpct':3};
con['column'][5] = {'last':0,'change':1,'chgpct':2,'high':3,'open':4,'low':5,'prev':6};
con['column'][6] = {'last':0,'change':1,'chgpct':2,'high':3,'open':4,'low':5,'pd':6};
con['column'][7] = {'longname':0,'last':1,'change':2,'high':3,'low':4,'pd':5};
con['column'][8] = {'symbol':0,'last':1,'change':2,'chgpct':3,'bidq':4,'bid':5,'ask':6,'askq':7,'open':8,'high':9,'low':10,'prev':11,'volume':12};

function x() {}
function $id(id) {
	return document.getElementById(id);
}

function $N(id) {
	return document.getElementsByName(id);
}

function $T(id) {
	return document.getElementsByTagName(id);
}

function instr(se,v) {
	if(typeof(v) == 'undefined' || v == undefined || v == 'undefined') return false;
	return (v.indexOf(se) > -1) ? true : false;
}

function iif(v,t,f){
	return v ? t : f;
}

function sizeof(arr){
	if(!isEmpty(arr.length)) return arr.length;
	else {
		var c = 0;
		for(var i in arr) c++;
		return c;
	}
}

function print_r(array,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;j++) level_padding += "    ";
	if(typeof(array) == 'object') { //Array/Hashes/Objects
		var obj = 0;
		for(var item in array) {
			var value = array[item];
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "[" + item + "] => Array\n " + level_padding + "( \n";
				dumped_text += print_r(value,level+1);
				dumped_text += level_padding + ")\n";
			} else {
				dumped_text += level_padding + level_padding +  "[" + item + "] => " + value + "\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===&gt;"+array+"&lt;===("+typeof(array)+")";
	}
	return dumped_text;
}

function ucwords(str) {
	return (str + '').replace(/^(.)|\s(.)/g, function ($1) { return $1.toUpperCase(); });
}

function nohtml(str) {
	return preg_replace([(isMac && isIE ? '&' : '&(?!#[0-9]+;)'), '<', '>', '"'], ['&amp;', '&lt;', '&gt;', '&quot;'], str);
}

function preg_replace(search, replace, str) {
	var len = search.length;
	for(var i = 0; i < len; i++) {
		re = new RegExp(search[i], "ig");
		str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
	}
	return str;
}

function setCommonVar(obj) {
	var str = '';
	var v = obj.action;
	if($id('__pg')) str += (str ? '&' : '') + 'pg='+$id('__pg').value;
	if($id('__sort')) str += (str ? '&' : '') + 'sort='+$id('__sort').value;
	if($id('__order')) str += (str ? '&' : '') + 'order='+$id('__order').value;
	if(instr('?',v)) str = str ? (v + '&' + str) : v;
	obj.action = str;
}

function resizeIframe(obj) {
	var height = (isMoz ? $id(obj).contentDocument.body.scrollHeight : top.frames[$id(obj).id].document.body.scrollHeight) + 50;
	height = (height < 500) ? 500 : height;
	$id(obj).style.height = height + 'px';
}

function getHeight() {
	var height = isMoz ? window.innerHeight + window.scrollMaxY : document.body.scrollHeight;  
	document.getElementById('ht').value = height;
	parent.document.getElementById('allpage').style.height = height + 'px';
}

// function chkMulti(id) {
	// var obj = $T('INPUT');
	// for(var i=0;i<obj.length;i++) {
		// alert(obj[i].id);
		// if(instr(id,obj[i].id) {
			// obj[i].checked = $(id).checked;
		// }
	// }
// }

function LTrim(v) {
	var re = /\s*((\S+\s*)*)/;
	return v.replace(re, "$1");
}

function RTrim(v) {
	var re = /((\s*\S+)*)\s*/;
	return v.replace(re, "$1");
}

function trim(v) {
	return (v + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function isNum(v) {
  return !(isNaN(v) || isEmpty(v));
}

function isChar(val) {
	var re = /^([a-zA-Z])$/;
	return (re.test(val));
}

function isEmpty(v) {
	v = trim(v);
	return (v == '' || v == null || v == 'null' || isUndefined(v));
}

function isUndefined(v) {
	return (typeof(v) == 'undefined' || v == undefined || v == 'undefined');
}

function isEmail(v) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(v);
}

function in_array(str, arr) {
	for (var s = 0; s <arr.length; s++) {
		v = arr[s].toString();
		if (v == str) return true;
	}
	return false;
}

function getClassStyle(obj,att) {
	if(typeof(obj) == 'string') obj = $id(obj);
	if(document.defaultView) {
		return rgbToHex(document.defaultView.getComputedStyle(obj,'').getPropertyValue(att));
	} else if(obj.currentStyle) {
		var v  = att.split('-');
		if(v[0] && v[1]) att = v[0] + ucwords(v[1]);
		return obj.currentStyle[att];
	} else {
		return '';
	}
}

function rgbToHex(txt) {
	if (instr('#',txt)) return txt;
	if (txt == 'transparent') return '';
	
	// txt = txt.replace(/ /gi,'');
	var exp = new RegExp(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/gi);
	var matchs = exp.exec(txt);
	if(!isUndefined(matchs)) {
		// alert([matchs[1],matchs[2],matchs[3]]);
		if(matchs[1] && matchs[2] && matchs[3]) {
			var R = parseInt(matchs[1]);
			var G = parseInt(matchs[2]);
			var B = parseInt(matchs[3]);
			return '#' + toHex(R)+toHex(G)+toHex(B);
		} else {
			return '';
		}
	} else {
		return txt;
	}
}

function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}


function IncludeJavaScript(jsFile) {
  document.write('<script type="text/javascript" src="includes/js/' + jsFile + '"></script>'); 
}

IncludeJavaScript('ajax.js');
IncludeJavaScript('nvdom.js');
IncludeJavaScript('fade.js');

function openTellUs(page) {
  window.open('tellus.php?page='+page, 'tellus', 'height=600,width=600,status=no,menubar=no,location=no,resizable=no,scrollbars=no,fullscreen=no');
}

/*************************************************************************************************************/
/***** AJAX **************************************************************************************************/
/*************************************************************************************************************/
function rmvCommas(v) {
	return isEmpty(v) ? '' : v+''.replace(/\,/g,'');
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function upDownStill(con1,con2) {
	// if(isEmpty(con2)) con2 = 'BLANK';
	if(con2 == 'BLANK') {
		if (con1) return "Up";
		else return "Down";
	} else {
		if (con1) return "Up";
		else if (con2) return "Down";
		else return "Still";
	}
}

function setValue(id,v,t,ref) {
	if (t == 1) myClass = "cssGreen";
	else if (t == 0) myClass = "cssRed";
	else myClass = "cssYellow";
	
	$('#'+id).html(v);
	// alert(isEmpty(ref));
	if(isEmpty(ref) || ref == 0 || ref == '0') {
		$('#'+id).removeClass("common").addClass(myClass);
		setTimeout('$("#'+id+'").removeClass("'+myClass+'").addClass("common")', 2000);
	}
}

function decFormat(v,d1,d2) {
	if(isEmpty(v) || !isNum(v)) v = 0;
	v = parseFloat(v);
	if(isEmpty(d1)) d1 = 2;
	if(isEmpty(d2)) d2 = 2;
	return addCommas(iif(v < 1,v.toFixed(d1),v.toFixed(d2)));
}

function abs(v) {
	if(isEmpty(v) || !isNum(v)) v = 0;
	v = parseFloat(v);
	return Math.abs(v);
}

function setFloat(v) {
	if(isEmpty(v) || !isNum(v)) v = '0';
	v = rmvCommas(v);
	return parseFloat(v);
}

function onlyNum(myfield, e, isdec, dec) {
	if (typeof(myfield) == 'object') myfield = myfield.value;
	var key;
	var keychar;
	if (isdec && isEmpty(dec)) dec = 2;

	if (window.event) key = window.event.keyCode;
	else if (e) key = e.which;
	else return true;
	keychar = String.fromCharCode(key);
// alert([key,keychar]);
	var sysKey = new Array(8,9,13,16,17,18,35,36,37,38,39,40,46,144);
	// var numKey = new Array(48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105);
	// var sysKeyChar = new Array(8,9,13,16,17,18,35,36,37,38,39,40,46,144);
	var numKeyChar = new Array('1','2','3','4','5','6','7','8','9','0');
	
	if ((key==null) || in_array(keychar,numKeyChar) || in_array(key,sysKey)) {
			return true;

	} else if (isdec && keychar == '.') {
		if (myfield.indexOf('.') > -1) return false;
		else return true;
	
	} else return false;
}

function loadPortfolio() {
	$.get("portfolio_delay.php", function(data) { document.getElementById('portfolio').innerHTML = data; });
}

function getLiveQuote(ss,exch) {
	$.get("quote_live.php?ss="+ss+'&exch='+exch, function(data) { document.getElementById('quote').innerHTML = data; setTimeout('getLiveQuote("'+ss+'","'+exch+'")', 1000); });
}

function getLivePortfolio() {
	$.get("portfolio_live.php", function(data) { document.getElementById('portfolio').innerHTML = data; setTimeout('getLivePortfolio()', 1000); });
}

function getLiveData(type,val) {
	intval = clearTimeout(intval);

	var rowID, nparam = '';
	var newValue = new Array();
	var oldValue = new Array();
	var rndNum = (Math.floor(Math.random()*9))*1000;
	var column = new Array();
	// var param = getParam(p);
	
		// alert('list_live.php?type='+type+'&country='+globalVar['symbol']+'&exch='+globalVar['shortname']+'&'+val);
	$.get('list_live.php?type='+type+'&country='+globalVar['symbol']+'&exch='+globalVar['shortname']+'&'+val, function(data) { 
	// var a = new ajax({
		// method : 'GET',
		// param : 'type='+type+'&country='+globalVar['symbol']+'&exch='+globalVar['shortname']+'&'+val,
		// url : 'list_live.php',
		// success : function(result) {
			var newData = data.split("^");
			var p = getParam(val);
			for(var pp in p) if(pp != 'refresh' && pp != 'rrefresh' && typeof p[pp] == 'string') nparam += (nparam ? '&' : '' ) + pp+'='+p[pp];
			// alert(p['refresh']);
			
			// if(type == 'list') {
				// if(p['val'] == 1) column = con["column"][0];
				// else column = con["column"][1];
			
			// } else if(type == 'user') {
				// column = con["column"][1];
			// }
			for (var i=0;i<newData.length;i++) {
				var rows = newData[i].split("|");
				var col = rows[0];
				var tbl = rows[1];
				var row = rows[2];
				var color = '';
				
				if(rows[3]) {
					column = con["column"][col];
					var value = rows[3].split(";");
					for(var j=0;value[j];j++) {
						var item = value[j].split(':');
						var symbol = item[0];
						var col = item[1];
						var v = item[2];
						
						if(symbol != 'idx') {
							var rowID = ''+tbl+'_td_'+row+'_'+col;
							var dValue = $('#'+rowID).text();
							
							if(symbol == 'shortname' || symbol == 'symbol' || symbol == 'bidq' || symbol == 'askq' || symbol == 'prev' || symbol == 'volume') var t = 2;
							else if(setFloat(dValue) > setFloat(v)) var t = 0;
							else if(setFloat(dValue) < setFloat(v)) var t = 1;
							
							if(symbol == 'change' || symbol == 'chgpct') {
								color = upDownStill(setFloat(v) > 0,setFloat(v) < 0);
								v = '<span class="'+color+'">'+v.replace(/\-/gi,'')+'</span>';
							}
							
							setValue(rowID,v,t,p['refresh']);
						}
					}
					
					for(var s in column) {
						color = '';
						var v = $('#'+tbl+'_td_'+row+'_'+column[s]).text();
						if(instr('Down',$('#'+tbl+'_td_'+row+'_'+column[s]+' span').attr("class")) && (s == 'change' || s == 'chgpct' || s == 'pd')) v = setFloat(v)*-1;
						// alert([row,column[s],s,cClass,v]);
						
						var prev = $('#'+tbl+'_td_'+row+'_'+column['prev']).text();
						// if(instr('Down',$('#td_'+row+'_'+column['prev']+' span').attr("class"))) prev = setFloat(prev)*-1;
						switch(s) {
							case 'last':
							// case 'change':
							// case 'chgpct': 
								var change = $('#'+tbl+'_td_'+row+'_'+column['change']).text();
								if(instr('Down',$('#'+tbl+'_td_'+row+'_'+column['change']+' span').attr("class"))) change = setFloat(change)*-1;
								color = upDownStill(setFloat(change) > 0,setFloat(change) < 0);
								// alert([row,s,change,setFloat(change) > 0,color]);
								break;
							case 'bid':
							case 'ask':
								color = upDownStill(setFloat(v) > setFloat(prev),setFloat(v) < setFloat(prev));
								break;
							case 'open':
								color = upDownStill(setFloat(v) > setFloat(prev),setFloat(v) < setFloat(prev));
								break;
							case 'high':
							case 'low':
								color = upDownStill(setFloat(v) > setFloat(prev),setFloat(v) < setFloat(prev));
								// alert([row,s,v,prev,setFloat(v) > setFloat(prev),setFloat(v) < setFloat(prev),color]);
								break;
							case 'pd':
								color = upDownStill(setFloat(v) > 0,setFloat(v) < 0);
								break;
							default:
								color = '';
								break;
						}
						// alert([row,s,v,prev,setFloat(v) > setFloat(prev),setFloat(v) < setFloat(prev),color]);
						// alert([row,column[s],color,v,setFloat($('#td_'+row+'_'+column['change']).text()),setFloat($('#td_'+row+'_'+column['change']).text()) > 0]);
						if(color) {
							$('#'+tbl+'_td_'+row+'_'+column[s]).html('<span class="'+color+'">'+$('#'+tbl+'_td_'+row+'_'+column[s]).text()+'</span>');
							
						}
					}
				}
			}	
			intval = setTimeout('getLiveData("'+type+'","'+nparam+iif(type=='user','&refresh=0&rrefresh=0','')+'")', 1000);
		// }
	})// .send();
}

function loadPage(url,param,div,func) {
	var a = new ajax({
		method : 'POST',
		param : param ? param + '&div='+div : '',
		url : url,
		success : function(result) {
			// alert(div);
			if(!isEmpty(div) && document.getElementById(div)) document.getElementById(div).innerHTML = result;
			if(!isEmpty(func) && typeof(func) == 'function') func();
		}
	}).send();
}

function loadPageTimer(url,param,div,func) {
	intvalT = clearTimeout(intvalT);
	var a = new ajax({
		method : 'POST',
		param : param ? param + '&div='+div : '',
		url : url,
		success : function(result) {
			// alert(div);
			if(!isEmpty(div) && document.getElementById(div)) document.getElementById(div).innerHTML = result;
			if(!isEmpty(func) && typeof(func) == 'function') func();
      
      intvalT = setTimeout("loadPageTimer('"+url+"','"+param+"','"+div+"',"+func+")",30000);
		}
	}).send();
  
}

function bannerRotate(country,loc,val) {
	var a = new ajax({
		method : 'GET',
		url : 'getbanner.php?country='+country+'&loc='+loc+'&var='+val,
		success : function(result) {
			// alert(result);
			eval(result);
		}
	}).send();
}

function loadContent(o,div,param) {
	var obj = document.getElementsByName('mnlink');
	for(var i=0;i<obj.length;i++) obj[i].className = 'morenews';
	o.className = 'morenewsHover';
	if(div) document.getElementById(div).innerHTML = '';
	
	var a = new ajax({
		method : 'POST',
		param : param,
		url : 'news_more.php',
		success : function(result) {
			document.getElementById(div).innerHTML = result;
		}
	}).send();
}

function loadpanel(panel_type, id) {
	// intval = clearTimeout(intval);
	// var a = new ajax({
		// method : 'GET',
		// param : "panel_type="+panel_type+"&country="+country,
		// url : 'bottom5.php',
		// success : function(result) {
			// document.getElementById('bottom5').innerHTML = result;
			if (panel_type == 1) {
				document.getElementById('btn_'+id).className  = 'selected';
				document.getElementById('btn_'+id+'p').className  = '';
				document.getElementById(id+'_div').style.display  = '';
				document.getElementById(id+'p_div').style.display  = 'none';
			} else {
				document.getElementById('btn_'+id).className  = '';
				document.getElementById('btn_'+id+'p').className  = 'selected';
				document.getElementById(id+'_div').style.display  = 'none';
				document.getElementById(id+'p_div').style.display  = '';
			}
		// }
	// }).send();
}

function setParam(v) {
	var param = '';
	for(var i in v) {
		param += (param ? '&' : '') + i + '=' + v[i];
	}
	return param;
}

function getParam(param) {
	var v = new Array();
	if(param) {
		var pair = param.split('&');
		for(var i=0;i<pair.length;i++) {
			var va = pair[i].split('=');
			v[va[0]] = va[1];
		}
	}
	return v;
}

function getNavName(param) {
	if(param) {
		var pair = param.split('&');
		for(var i=0;i<pair.length;i++) {
			var v = pair[i].split('=');
			if(v[0] == 'val') var alpha = v[1];
			else if(v[0] == 'wtype') var wtype = v[1];
			else if(v[0] == 'idx') var idx = v[1];
			else if(v[0] == 'mycountry') var mycountry = v[1];
			else if(v[0] == 'scode') var scode = v[1];
		}
	}
	url = '';

	if(!isEmpty(alpha)) {
		switch(alpha) {
			case '1': nav_name = "All Indices"; break;
			case '2': nav_name = "By Volume"; break;
			case '3': nav_name = "By Value"; break;
			case '4': nav_name = "By Price Up"; break;
			case '5': nav_name = "By Price Up (%)"; break;
			case '6': nav_name = "By Price Down"; break;
			case '7': nav_name = "By Price Down (%)"; break;
			case '9': if(mycountry == 'my') nav_name = "KLCI"; else nav_name = "STI"; break;
			case '10' : nav_name = 'FBM70'; break;
			case '11' : nav_name = 'FBM100'; break;
			case '12' : nav_name = 'FBMSHA'; break;
			default: nav_name = "By Alphabet "+alpha+""; break;
		}
		url = 'by=alp&val='+alpha;
	} else {
		alpha = "0";
		nav_name = "Market Overview";
	}

	if(!isEmpty(idx)) {
		switch(wtype) {
			case '1': nav_name = "Warrants"; break;
			case '2': nav_name = "Covered Warrants"; break;
			case '3': nav_name = "Right"; break;
			case '4': nav_name = "ETF"; break;
			case '5': nav_name = "Warrants"; break;
			case '6': nav_name = "Call Warrants"; break;
			case '7': nav_name = "Right"; break;
		}
		url = 'idx=1&wtype='+wtype;
	} else {
		idx = "0";
		wtype = "0";
	}
	
	if(!isEmpty(scode)) {
		nav_name = "Sector";
		url = 'by=alp&scode='+scode;
	} else {
		scode = "0";
		nav_name = "Sector";
	}

	nav_name = '<li><a href="list.php?'+url+'">'+nav_name+'</a></li>';
	
	marketlist = new Array('2','3','4','5','6','7');
	allstocklist = new Array('1','2','3','4','5','6','7');
	componentlist = new Array('9','10','11','12');
	if (idx == 0 && !in_array(alpha,allstocklist)) nav_name = "<li>All Stock</li><li>&gt;</li>"+nav_name;
	else if (in_array(alpha,marketlist)) nav_name = "<li>Market Overview</li><li>&gt;</li>"+nav_name;
	else if (in_array(alpha,componentlist)) nav_name = "<li>Component Stock</li><li>&gt;</li>"+nav_name;
	
	return nav_name;
}

function getFileName(url) {
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	return url;
}

function setNav(v) {
	var title = 'Summary';
	switch(v) {
		case 'quote_announcement.php' : title = 'Announcements'; break;
		case 'quote_financial.php' : title = 'Financial Statement'; break;
		case 'quote_historical.php' : title = 'Historical Prices'; break;
		case 'quote_jchart.php' : title = 'Streaming Chart'; break;
		case 'quote_news.php' : title = 'News'; break;
		case 'quote_ratios.php' : title = 'Financial Ratios'; break;
		case 'quote_sales.php' : title = 'Time and Sales'; break;
		case 'quote_technical.php' : title = 'Technical'; break;
		default : title = 'Summary'; break;
	}
	var r = '&gt; <a onclick="$.scrollTo($(\'#quoteContent\'), 800, {margin:true})">'+title+'</a>';
	$('#navTitle').html(r);
}

function quoteContent(url,scroll) {
	setNav(getFileName(url));
	if(isEmpty(scroll)) scroll = true;
	if(scroll) $.scrollTo($('#quoteContent'), 800, {margin:true});
	$('#quoteContent').html('<br><br><br><center><IMG src="images/loading_trans.gif"> loading...</center><br><br><br>');
	$.get(url,function(data) {
		$('#quoteContent').html(data);
	});
}

function getAnnouncement(url,scroll,o) {
	if(o) {
		$('.alppaging').removeClass('hover');
		$(o).addClass('hover');
	}
	if(isEmpty(scroll)) scroll = true;
	if(scroll) $.scrollTo($('#announceContent'), 800, {margin:true});
	$('#announceContent').html('<br><br><br><center><IMG src="images/loading_trans.gif"> loading...</center><br><br><br>');
	$.get(url,function(data) {
		$('#announceContent').html(data);
	});
}

function setOnline(sesid) {
	$.get('setonline.php?updatetime=1&sessionid='+sesid,function(data) {
		setTimeout('setOnline("'+sesid+'")',5000);
	});
}

function popbox(url,clss) {
	if(isEmpty(clss)) clss = 'popBox';
	jQuery.facebox({ajax:url}, clss);
}

jQuery.fn.reverse = function() {
	return this.pushStack(this.get().reverse(), arguments);
};

jQuery.fn.disableSelection = function() { 
	this.each(function() {
		this.onselectstart = function() { return false; }; 
		this.unselectable = "on"; 
		jQuery(this).css('-moz-user-select', 'none'); 
	}); 
} 

function loadTrans(pfid,symbol,exch,scroll) {
	if(isEmpty(scroll)) scroll = true;
	$('#petsdivcontainer').html('<br><br><br><br><br><center><IMG src="images/loading_trans.gif"> loading...</center><br><br><br>');
	if(scroll) $.scrollTo($('#petsdivcontainer'), 800, {margin:true});
	$.get('portfolio_trans.php?pfid='+pfid+'&symbol='+symbol+'&exch='+exch,function(data) {
		$('#petsdivcontainer').html(data);
	});
}

var mywatchlist = {
	show : function(type) {
		if(isEmpty(type)) type = 'watch';
		$('#stockpanel').html('<br><br><br><br><br><center><IMG src="images/loading_trans.gif"> loading...</center><br><br><br>');
		$.get('getwatchalpha.php?exch='+$('#excnow').val()+'&by='+$('#bynow').val()+'&curlist='+$('#curlist').val()+'&type='+type,function(data) { $('#stockpanel').html(data)});
	},
	
	addExch : function(v,o,type) {
		$('#excnow').val(v);
		if(o) {
			$('.excpaging').removeClass('hover');
			$(o).addClass('hover');
		}
		mywatchlist.show(type);
	},
	
	addAlpha : function(v,o,type) {
		$('#bynow').val(v);
		if(o) {
			$('.alppaging').removeClass('hover');
			$(o).addClass('hover');
		}
		mywatchlist.show(type);
	},
	
	myList : function() {
		var names = [];
		$('input[name=mylist]').each(function() {
			names.push($(this).val());
		});
		$('#listcount').html(names.length.toString());
		return names.join(',');
	},
	
	addone : function(obj,type) {
		if($('input[name=mylist]').length + 1 > 40 && type != 'portfolio') {
			alert("Only 40 stocks per Watchlist are allowed.\nPlease remove some stocks from your Watchlist.");
		} else {
			$('<div>').addClass('stocklist')
				.html('<input type="checkbox" name="mylist" value="'+$(obj).children(':checkbox').val()+'">'+$(obj).text())
				.click(function(e) {
					if(!e.ctrlKey) {
						$(this).parent().find('input').attr('checked', false);
						$(this).parent().find('.stocklist').removeClass('hover');
					}
					$(this).toggleClass('hover');
					$(this).children(':checkbox').attr('checked',$(this).hasClass('hover') ? true : false);
				}).appendTo($('#mypanel').children(':first'));
			$('#curlist').val(mywatchlist.myList());
			$(obj).hide().removeClass('hover').children(':checkbox').attr('checked', false);
			$("#mypanel").children(':first').animate({ scrollTop: $("#mypanel").children(':first').attr("scrollHeight") },1000);
		}
	},
	
	add : function(type) {
		if($('input[name=stocklist]:checked').length <= 0 && type != 'portfolio') alert("Please select a stock from the left to add into Watchlist.");
		else {
			if($('input[name=stocklist]:checked').length + $('input[name=mylist]').length > 40) {
				alert("Only 40 stocks per Watchlist are allowed.\nPlease remove some stocks from your Watchlist.");
			} else {
				// var names = [];
				$('input[name=stocklist]:checked').each(function() {
					// names.push($(this).val());
					$('<div>').addClass('stocklist')
						.html('<input type="checkbox" name="mylist" value="'+$(this).val()+'">'+$(this).parent().text())
						.click(function(e) {
							if(!e.ctrlKey) {
								$(this).parent().find('input').attr('checked', false);
								$(this).parent().find('.stocklist').removeClass('hover');
							}
							$(this).toggleClass('hover');
							$(this).children(':checkbox').attr('checked',$(this).hasClass('hover') ? true : false);
						}).appendTo($('#mypanel').children(':first'));
				}).parent().hide();
				$('#curlist').val(mywatchlist.myList());
				$('input[name=stocklist]').attr('checked', false);
				$('#stockpanel').find('.stocklist').removeClass('hover');
				$("#mypanel").children(':first').animate({ scrollTop: $("#mypanel").children(':first').attr("scrollHeight") },1000);
			}
		}
	},

	remove : function() {		if($('input[name=mylist]:checked').length <= 0) alert("Please select a stock from the right to remove from Watchlist.");		else {			// var curlist = $('#curlist').val().split(',');			$('input[name=mylist]:checked').each(function() {
				$('#stockpanel').find(':checkbox[value='+$(this).val()+']').parent().show();
			}).parent().remove();			$('#curlist').val(mywatchlist.myList());		}
	},


	up : function() {
		if($('input[name=mylist]:checked').length <= 0) alert("Please select a stock from the right to remove from Watchlist.");		else {			$('input[name=mylist]:checked').parent().each(function() {				var selected = $(this);				var obj = $(this).prev('div').not('.hover');				if ($(obj).text() != "") {					$(this).remove();					$(obj).before($(selected).click(function(e) {						if(!e.ctrlKey) {
							$(this).parent().find('input').attr('checked', false);
							$(this).parent().find('.stocklist').removeClass('hover');
						}
						$(this).toggleClass('hover');						$(this).children(':checkbox').attr('checked',$(this).hasClass('hover') ? true : false);					}));				}			});
			$('#curlist').val(mywatchlist.myList());
		}
	},

	down : function() {		if($('input[name=mylist]:checked').length <= 0) alert("Please select a stock from the right to remove from Watchlist.");		else {			$('input[name=mylist]:checked').parent().reverse().each(function() {				var selected = $(this);				var obj = $(this).next('div').not('.hover');				if ($(obj).text() != "") {					$(this).remove();					$(obj).after($(selected).click(function(e) {						if(!e.ctrlKey) {
							$(this).parent().find('input').attr('checked', false);
							$(this).parent().find('.stocklist').removeClass('hover');
						}
						$(this).toggleClass('hover');						$(this).children(':checkbox').attr('checked',$(this).hasClass('hover') ? true : false);					}));				}			});			$('#curlist').val(mywatchlist.myList());		}	},
		all : function() {
		if($('input[name=mylist]').not(':checked').length > 0) {
			$('input[name=mylist]').attr('checked',true).parent().addClass('hover');
		} else {
			$('input[name=mylist]').attr('checked',false).parent().removeClass('hover');
		}
	},
		del : function() {
		if(!confirm('Are you sure to delete this Watchlist?')) {
			return false;
		}
	},

	check : function(type) {
		if(type == 'portfolio') {
			if(isEmpty($('[name=capital]').val())) {
				alert('Please key in the Capital.');
				$('[name=capital]').focus();
				return false;
			} else if(isEmpty($('[name=bkrpct]').val())) {
				alert('Please key in the Rate(%).');
				$('[name=bkrpct]').focus();
				return false;
			} else if(isEmpty($('[name=bkrmin]').val())) {
				alert('Please key in the Minimum.');
				$('[name=bkrmin]').focus();
				return false;
			} else if(!isNum($('[name=capital]').val())) {
				alert('Only numeric Capital are allowed.');
				$('[name=capital]').focus();
				return false;
			} else if(!isNum($('[name=bkrpct]').val())) {
				alert('Only numeric Rate(%) are allowed.');
				$('[name=bkrpct]').focus();
				return false;
			} else if(!isNum($('[name=bkrmin]').val())) {
				alert('Only numeric Minimum are allowed.');
				$('[name=bkrmin]').focus();
				return false;
			} else if(isEmpty($('#curlist').val())) {
				alert('You cannot have empty Portfolio, please select atleast ONE stock to proceed.');
				return false;
			}
		} else {
			if(isEmpty($('[name=w_name]').val())) {
				alert('Please key in the Watchlist Name.');
				$('[name=w_name]').focus();
				return false;
			} else if(isEmpty($('#curlist').val())) {
				alert('You cannot have empty Watchlists, please select atleast ONE stock to proceed.');
				return false;
			}
		}
	}

		// if (document.frmWatch.wlist.selectedIndex == -1) {			// alert("Please select a stock from the right to shift one level up.");		// } else {			// var index = document.frmWatch.wlist.selectedIndex;			// if (index > 0) {				// var tmpTitle = document.frmWatch.wlist[index].text;				// var tmpValue = document.frmWatch.wlist[index].value;
				
				// document.frmWatch.wlist[index].text = document.frmWatch.wlist[index-1].text;				// document.frmWatch.wlist[index].value = document.frmWatch.wlist[index-1].value;				// document.frmWatch.wlist[index-1].text = tmpTitle;				// document.frmWatch.wlist[index-1].value = tmpValue;				// document.frmWatch.wlist.selectedIndex = index - 1;			// }		// }}
function sValue(v) {
	$('#act').val(v);
}

function sForm() {
	$('#submitbtn, #deletebtn').attr('disabled',true);
	$('#loading').show();
	
	var stkcode = $('#stkcode').val();
	var stkcty = $('#stkcty').val();
	var arr = new Array();
	
	arr['act'] = $('#act').val();
	arr['pfid'] = $('#pfid').val();
	arr['ptid'] = $('#ptid').val();
	
	if(arr['act'] != 'Delete') {
		arr['pstock'] = $('#pstock').val();
		
		arr['pact'] = $('#pact').val();
		arr['pprice'] = $('#pprice').val();
		arr['day'] = $('#day').val();
		arr['month'] = $('#month').val();
		arr['year'] = $('#year').val();
		arr['pvol'] = $('#pvol').val();
		arr['pbkr'] = $('#pbkr').val();
		arr['pmcost'] = $('#pmcost').val();
	}
		
	var param = setParam(arr);
		
	if(arr['act'] != 'Delete') {
		if(isEmpty(arr['pact']) || isEmpty(arr['pprice']) || isEmpty(arr['day']) || isEmpty(arr['month']) || isEmpty(arr['year']) || isEmpty(arr['pvol']) || isEmpty(arr['pbkr']) || isEmpty(arr['pmcost'])) {
			alert('Please fill up all field in order to continue!');
			$('#submitbtn, #deletebtn').attr('disabled',false);
			$('#loading').hide();
			return false;
		}
	}

	if(arr['act'] != 'Delete' || (arr['act'] == 'Delete' && confirm("You are about to delete transaction! This cannot be undone!\nAre you sure want to delete this transaction?"))) {
		$.post('portfoliotrans.php',param,function(data) {
			jQuery(document).trigger('close.facebox');
			loadTrans(arr['pfid'],stkcode,stkcty);
			loadPortfolio();
			// location.href = 'portfolio.php?trans='+arr['pstock'];
		});
	} else {
		$('#submitbtn, #deletebtn').attr('disabled',false);
		$('#loading').hide();
	}
	return false;
}

function moreAction(obj,symbol) {
	if(isEmpty(symbol)) return;
	$("div.moreAction").hide();
	// alert(0);
	var id = 'moreact_'+symbol.replace('.','_');
	// alert(1);
	if($('#'+id).length > 0) {
		// alert('2a');
		var div = $('#'+id);
	} else {
		// alert('2b');
		var div = $('<div>').attr({'id' : id}).addClass('moreAction').html('<ul><li><img src="images/loading_small.gif" align="absmiddle"> Loading...</li></ul>');
		$(obj).after(div);
		$.get('list_ctrl.php','symbol='+symbol+'&exch='+globalVar['shortname'],function(result) {
			$(div).html(result);
		})
	}
	// alert(3);
	// alert([$(div).attr('id'),$('#'+id).length]);
	// var div = $('#moreact_'+symbol).length > 0 ? $('#moreact_'+symbol) : $(obj).after($('<div>').attr({'id' : 'moreact_'+symbol}).addClass('moreAction')).hide();
	$(div).show();
	stopPro();
	// alert(4);
	
}

function stopPro() {
	$('.moreAction').click(function(e) { 
		e.stopPropagation();
	});
	$('div.moreAction').find('*').click(function(e) { 
		e.stopPropagation();
	});
}

$(window).bind("load", function() {
	$(document).click(function() {
		$("div.moreAction").hide();
	});
	$('.moreAction').click(function(e) { 
		e.stopPropagation();
	});
	$('div.moreAction').find('*').click(function(e) { 
		e.stopPropagation();
	});
});
