Ajax.Responders.register({onCreate:startLoading, onComplete:stopLoading});
var loaded = false;


var ScreenerContextMenu = {

	// private attributes
	_menus : new Array,
	_attachedElement : null,
	_menuElement : null,
	_preventDefault : true,
	_preventForms : true,


	// public method. Sets up whole context menu stuff..
	setup : function (conf) {

		if ( document.all && document.getElementById && !window.opera ) {
			ScreenerContextMenu.IE = true;
		}

		if ( !document.all && document.getElementById && !window.opera ) {
			ScreenerContextMenu.FF = true;
		}

		if ( document.all && document.getElementById && window.opera ) {
			ScreenerContextMenu.OP = true;
		}

		if ( ScreenerContextMenu.IE || ScreenerContextMenu.FF ) {

			document.oncontextmenu = ScreenerContextMenu._show;
			document.onclick = ScreenerContextMenu._hide;

			if (conf && typeof(conf.preventDefault) != "undefined") {
				ScreenerContextMenu._preventDefault = conf.preventDefault;
			}

			if (conf && typeof(conf.preventForms) != "undefined") {
				ScreenerContextMenu._preventForms = conf.preventForms;
			}

		}

	},


	// public method. Attaches context menus to specific class names
	attach : function (classNames, menuId) {

		if (typeof(classNames) == "string") {
			ScreenerContextMenu._menus[classNames] = menuId;
		}

		if (typeof(classNames) == "object") {
			for (x = 0; x < classNames.length; x++) {
				ScreenerContextMenu._menus[classNames[x]] = menuId;
			}
		}

	},


	// private method. Get which context menu to show
	_getMenuElementId : function (e) {

		if (ScreenerContextMenu.IE) {
			ScreenerContextMenu._attachedElement = event.srcElement;
		} else {
			ScreenerContextMenu._attachedElement = e.target;
		}

		while(ScreenerContextMenu._attachedElement != null) {
			var className = ScreenerContextMenu._attachedElement.className;

			if (typeof(className) != "undefined") {
				className = className.replace(/^\s+/g, "").replace(/\s+$/g, "")
				var classArray = className.split(/[ ]+/g);

				for (i = 0; i < classArray.length; i++) {
					if (ScreenerContextMenu._menus[classArray[i]]) {
						return ScreenerContextMenu._menus[classArray[i]];
					}
				}
			}

			if (ScreenerContextMenu.IE) {
				ScreenerContextMenu._attachedElement = ScreenerContextMenu._attachedElement.parentElement;
			} else {
				ScreenerContextMenu._attachedElement = ScreenerContextMenu._attachedElement.parentNode;
			}
		}

		return null;

	},


	// private method. Shows context menu
	_getReturnValue : function (e) {

		var returnValue = true;
		var evt = ScreenerContextMenu.IE ? window.event : e;

		if (evt.button != 1) {
			if (evt.target) {
				var el = evt.target;
			} else if (evt.srcElement) {
				var el = evt.srcElement;
			}

			var tname = el.tagName.toLowerCase();

			if ((tname == "input" || tname == "textarea")) {
				if (!ScreenerContextMenu._preventForms) {
					returnValue = true;
				} else {
					returnValue = false;
				}
			} else {
				if (!ScreenerContextMenu._preventDefault) {
					returnValue = true;
				} else {
					returnValue = false;
				}
			}
		}

		return returnValue;

	},


	// private method. Shows context menu
	_show : function (e) {

		ScreenerContextMenu._hide();
		var menuElementId = ScreenerContextMenu._getMenuElementId(e);

		if (menuElementId) {
			var m = ScreenerContextMenu._getMousePosition(e);
			var s = ScreenerContextMenu._getScrollPosition(e);

			ScreenerContextMenu._menuElement = document.getElementById(menuElementId);
			ScreenerContextMenu._menuElement.style.left = m.x + s.x + 'px';
			ScreenerContextMenu._menuElement.style.top = m.y + s.y + 'px';
			ScreenerContextMenu._menuElement.style.display = 'block';
			return false;
		}

		return ScreenerContextMenu._getReturnValue(e);

	},


	// private method. Hides context menu
	_hide : function () {

		if (ScreenerContextMenu._menuElement) {
			ScreenerContextMenu._menuElement.style.display = 'none';
		}

	},


	// private method. Returns mouse position
	_getMousePosition : function (e) {

		e = e ? e : window.event;
		var position = {
			'x' : e.clientX,
			'y' : e.clientY
		}

		return position;

	},


	// private method. Get document scroll position
	_getScrollPosition : function () {

		var x = 0;
		var y = 0;

		if( typeof( window.pageYOffset ) == 'number' ) {
			x = window.pageXOffset;
			y = window.pageYOffset;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}

		var position = {
			'x' : x,
			'y' : y
		}

		return position;

	}

}

var deflabel = "deflabel";
function showCrit(txt,rowindex){
	showMenuType(TYPE_MENUS['crit'],txt,rowindex);
}

function showCond(txt,rowindex){
	if(!FILTER[rowindex])
		return false;
	if(FILTER[rowindex][0] == 0)
		return false;
	var condmidx = ROW_MENU[rowindex][1];
	showMenu(condmidx,txt,rowindex);

}
function showValue(txt,rowindex){

}

//silmul
var basepath="";
function startLoading() {
		loaded = false;
		window.setTimeout("showLoading()", 100);
	}
	function showLoading() {
		if(!loaded){
			Element.show("loading_box");
			$('filter').disabled="disabled";
		}
	}
	function stopLoading() {
			loaded = true;
			Element.hide("loading_box");
			$('filter').disabled = "";
	}

function doAjaxSubmit(){

	var ni = document.getElementById('myDiv');
				var num = document.getElementById('theValue').value;
				//parse num thanh so co he co so 10.
				num = parseInt(num, 10) ;
				document.getElementById('theValue').value = num;
				var divIdName = num;
				var newdiv = document.createElement('div');
				newdiv.setAttribute("id",divIdName);

				var a = document.getElementById('innerCriteriaField_'+num).value;

				var b = document.getElementById('innerCompanyCode_'+num).value;
				var c = document.getElementById('innerOperatorField_'+num).value;
				if(a.length == 0){
					alert("Please enter data");

					return false;
				}else
				if(b.length == 0){
					alert("Please enter data");

					return false;
				}else
				if(c.length == 0){
					alert("Please enter data");

					return false;
				}
		var objForm = document.stockScreener;
		new Ajax.Updater({success:"resultTable", failure:"resultTable"}, basepath + "/stockscreener.do", {parameters:Form.serialize(objForm), evalScripts:true});
		return true;
	}
function addEvent() {
	var ni = document.getElementById('myDiv');
	var num = document.getElementById('theValue').value;
	//parse num thanh so co he co so 10.
	num = parseInt(num, 10) + 1;
	document.getElementById('theValue').value = num;
	var divIdName = num;
	var newdiv = document.createElement('div');
	newdiv.setAttribute("id",divIdName);

	newdiv.innerHTML = ""
	+ 	'<table class="ovbotr2" border="0" cellpadding="0" cellspacing="5"  width="100%">'
	+	'	<tr height="15px" valign="top">'
	+   '		<td width="21%">'
	+	'			<input type="hidden" name="innerListValue" id="innerListValue" value="'+ num +'"/>'
	+	'			<select style="width:200px;" name="innerCriteriaField_' + num + '" id="innerCriteriaField_' + num + '" onchange="industrySymbolChange('+ num +');">'
	+	'				<option selected value="">--</option>'
	+	'				<option value="companyCode" onclick="changeCond(\'s\','+ num + ')">Market</option>'
	+	'				<option value="companyCode" onclick="changeCond(\'s\','+ num + ')">Stock Symbol</option>'
	+	'				<option value="industryCode" onclick="changeCond(\'s\','+ num + ')">Industry Symbol</option>'
	+	'				<option value="sectorsymbol" onclick="changeCond(\'s\','+ num + ')">Sector Symbol</option>'
	+	'				<option value="pe" onclick="changeCond(\'f\','+ num + ')">P/E</option>'
	+	'				<option value="bv" onclick="changeCond(\'f\','+ num + ')">P/BV</option>'
	+	'				<option value="eps" onclick="changeCond(\'f\','+ num + ')">EPS</option>'
	+	'				<option value="roe" onclick="changeCond(\'f\','+ num + ')">ROE</option>'
	+	'				<option value="roa" onclick="changeCond(\'f\','+ num + ')">ROA</option>'
	+	'				<option value="loiNhuanBien" onclick="changeCond(\'f\','+ num + ')">Gross Margin</option>'
	+	'			</select>'
	+	'		</td > '
	+	'		<td width="11%">'
	+	'			<select style="width:200px;" name="innerOperatorField_' + num + '" id="innerOperatorField_' + num + '" onchange="">'
	+	'				<option selected value="">--</option>		'
	+	'				<option value="Equal">&nbsp;&nbsp;=</option>'
	+	'				<option value="GreaterEqual">&nbsp;&nbsp;> =</option>'
	+	'				<option value="LessEqual">&nbsp;&nbsp;< =</option>'
	+	'				<option value="Like">&nbsp;&nbsp;Like</option>'
	+	'				<option value="NotLike">&nbsp;&nbsp;Not like</option>'
	+	'			</select>'
	+	'		</td>'
	+	'		<td  width="27%">'
	+	'			<input type="text" name="innerCompanyCode_' + num + '" id="innerCompanyCode_' + num + '"/>'
	+	'		</td>'
	+	'		<td width="41%">'
	+	'			<input style="width:25px" type="button" id="addCriteriaBut_' + num + '" value="+" onclick="doChange(this.id,this.name,' + num + ')">'
	+	'		</td>'
	+	'	</tr>'
	+	'</table>';

	ni.appendChild(newdiv);
}

function addEvent2() {
	var ni = document.getElementById('myDiv');
	var num = document.getElementById('theValue').value;
	//parse num thanh so co he co so 10.
	num = parseInt(num, 10) + 1;
	document.getElementById('theValue').value = num;
	var divIdName = num;
	var newdiv = document.createElement('div');
	newdiv.setAttribute("id",divIdName);

	newdiv.innerHTML = ""
	+ 	'<table border="0" cellpadding="2" width="98%" cellspacing="0">'
	+	'	<tr valign="middle">'
	+   '		<td width="30%" style="padding-left: 10px">'
	+	'			<input type="hidden" name="innerListValue" id="innerListValue" value="'+ num +'"/>'
	+	'			<select style="width:160px;" name="innerCriteriaField_' + num + '" id="innerCriteriaField_' + num + '" onchange="fillSelect(this.value,this.form[\'innerOperatorField_' + num + '\'])">'
	+	'			</select>'
	+	'		</td > '
	+	'		<td width="30%">'
	+	'			<select style="width:160px;" name="innerOperatorField_' + num + '" id="innerOperatorField_' + num + '" onchange="">'

	+	'			</select>'
	+	'		</td>'
	+	'		<td  width="28%">'
	+	'			<input type="text" style="width: 90%" name="innerCompanyCode_' + num + '" id="innerCompanyCode_' + num + '"/>'
	+	'		</td>'
	+	'		<td width="12%" align="right">'
	+	'			<input class="button1" type="button" id="addCriteriaBut_' + num + '" value="' + document.getElementById('changeAdd').value + '" name="+" onclick="doChange(this.id,this.name,' + num + ')">'
	+	'		</td>'
	+	'	</tr>'
	+	'</table>';


	ni.appendChild(newdiv);
	fillSelect("startList",document.forms["stockScreener"]['innerCriteriaField_' + num]);
}


var sCond = '<option value="Like">&nbsp;&nbsp;Like</option>	<option value="NotLike">&nbsp;&nbsp;Not like</option>';
var fCond = '<option value="Equal">&nbsp;&nbsp;=</option><option value="GreaterEqual">&nbsp;&nbsp;> =</option><option value="LessEqual">&nbsp;&nbsp;< =</option>';

function removeEvent(divNum) {
	var d = document.getElementById('myDiv');
	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
}

// function stockScreenerSubmit dung cho Filter button.
function stockScreenerSubmit(orderColName,orderType) {
	window.document.stockScreener.action= basepath + "/stockscreener.do?orderColName=" + orderColName + "&orderType=" + orderType;
	window.document.stockScreener.submit();
}
function doChangeMarket(form){
	for(var i =0 ; i< form.radiomarket.length; i++){
		if(form.radiomarket[i].checked){
		 var choosenMarket = form.radiomarket[i].value
		}
	}
	form.radiomarket.value = form.radiomarket[i].value;
}
function industrySymbolChange(id) {
	// co 2 cach lay.
	//var criteria = document.forms["stockScreener"].firstCriteriaField;
	var criteria = document.getElementById("innerCriteriaField_"+id);
	var criteriaChoosen = criteria.options[criteria.selectedIndex].value;
}

function doChange(currentid, value, id) {
	//currentid : id of button raise action doChange
	//value: value (+/-) id of button raise action doChange
	//id: id of button raise action doChange
	//case value = +: Add button

	if(value=="+") {
		//Change value to -
		document.getElementById(currentid).name = "-";
		document.getElementById(currentid).value = document.getElementById("changeDel").value;
		//Add new element to div
		addEvent2();
	} else { //case value = -: Remove button
		//Remove exist element.
		removeEvent(id);
	}
}

function stockScreenerSubmitSort(orderColName, orderType) {
	if(orderType == "ASC"){
		orderType = "DESC";
	}else{
		orderType = "ASC";
	}
	$("orderType").value = orderType;
	$("orderColName").value = orderColName;
	var objForm = document.stockScreener;
	new Ajax.Updater({success:"resultTable", failure:"resultTable"}, basepath + "/stockscreener.do", {parameters:Form.serialize(objForm), evalScripts:true});
}

function changeCond(val,idx){

	if(val == 's'){

		$('innerOperatorField_' + idx).innerHTML = sCond;
	}
	else if(val == 'f'){
		$('innerOperatorField_' + idx).innerHTML = fCond;
	}
}

//seg
function doChangeStrategies(sel){
			window.document.getElementById("strategies").value = sel.options[sel.selectedIndex].value;
			$('step').innerHTML = strat[sel.options[sel.selectedIndex].value];
}
function StockScreenerSeqSubmit(){
	window.document.stockScreenerseq.action = basepath + "/stockscreenerseq.do";
	window.document.stockScreenerseq.submit();
}
function doSeqAjaxSubmit(){
	var objForm = document.stockScreenerseq;
	new Ajax.Updater({success:"resultTable", failure:"resultTable"}, basepath + "/stockscreenerseq.do", {parameters:Form.serialize(objForm), evalScripts:true});
}
function critOnChange(sel, idx){
	var selectedIndex = sel.selectedIndex;
	if(selectedIndex == 1){
		$('innerOperatorField_' + idx).innerHTML = sCond;
	}
}

function fillSelect(currCat,currList){
	//clear the second select
	currList.length = 1;
	currList.selectedIndex = 0;

	var nCat = categories[currCat];
	nCat.each(function(s) {
		 var nOption = document.createElement('option');
		 var nData = document.createTextNode(s[1]);
		 nOption.setAttribute('value',s[0]);
		 nOption.appendChild(nData);
		 currList.appendChild(nOption);
	});
}
