// JavaScript Document

//Global vriables
var focusedRow, rowPostfix, mouseOverdRow, modified
rowPostfix = 0;

function init() {
	focusedRow = null;
	mouseOverdRow = null;
	rowPostfix = 999; //begin new id postfix
	modified = false;
}

function like(baseStr,searchStr) {
	if (baseStr.indexOf(searchStr) == -1) 
		return true;
	else
		return false;
}

function sisFilter(filterId,tableId,gridType) {
	var tbBody = document.getElementById(filterId).tBodies[0];
	var fieldIndex = tbBody.rows[1].cells[0].childNodes[0].selectedIndex;
	var operator = tbBody.rows[1].cells[1].childNodes[0].value;
	var usrTxt = tbBody.rows[1].cells[2].childNodes[0].value.toLowerCase(); 

	var replaceStr = "";
    var nbspStr = "&nbsp;";
	
	if ( gridType == 'dblist' ) {
		startRow = 1;
		increment = 1;
	}
	else {
		startRow = 2;
		increment = 2;
	}
		
	var theTableBody = document.getElementById(tableId).tBodies[0];
	for ( var i=0; i<theTableBody.rows.length; i++ )
	if ( theTableBody.rows[i].modified ) {
		alert("برخي از سطرها در مد ويرايش هستند لطفا ابتدا\nانها را به مد خواندني ببريد سپس فيلتر کنيد.");
		return -1;
	}	

	for(var i=startRow; i<theTableBody.rows.length; i+=increment) {
		if ( theTableBody.rows[i].cells[fieldIndex].childNodes[0].nodeName == "A" )
			var colText = trim(theTableBody.rows[i].cells[fieldIndex].childNodes[0].innerText);
		else	
			var colText = trim(theTableBody.rows[i].cells[fieldIndex].innerHTML);
		
		var re = new RegExp(nbspStr , "g");
		var colText = colText.toLowerCase().replace(re, replaceStr);
		switch( operator ) {
			case "" : theTableBody.rows[i].style.display = ""; break;
			case "not like" : if( !like(colText,usrTxt) )
								theTableBody.rows[i].style.display = "none";
							  else
								theTableBody.rows[i].style.display = "";
							  break;	 
			case "like" : if( like(colText,usrTxt) )
							theTableBody.rows[i].style.display = "none";
						  else
							theTableBody.rows[i].style.display = "";
						  break;	
			default : if( !eval('("'+colText+'"'+operator+'"'+usrTxt+'")') ) 
						theTableBody.rows[i].style.display = "none";
					 else
						theTableBody.rows[i].style.display = "";
		}	
	}
}

function checkAllRadio(radioId) {
	var radio = document.getElementById(radioId);
	var theTableBody = radio.parentElement.parentElement.parentElement;
	var objIndex=0;
	while(objIndex<theTableBody.rows[0].cells[radio.colIndex].childNodes.length) {
		if(theTableBody.rows[0].cells[radio.colIndex].childNodes[objIndex].type == "radio")
			break;
		objIndex++;	
	}
	
	var index=0;	
	for(var i=2; i<theTableBody.rows.length; i++)
		if( (i % 2 ) == 0 ) {
			if( theTableBody.rows[i].style.display == 'none' && theTableBody.rows[i+1].style.display != '') { i++; continue; }
			theTableBody.rows[i].cells[radio.colIndex].innerHTML = (radio.checked)?theTableBody.rows[i+1].cells[radio.colIndex].childNodes[objIndex].checkedCaption:
														                             theTableBody.rows[i+1].cells[radio.colIndex].childNodes[objIndex].unCheckedCaption;														                             
		}
		else {
			index = 0;
			while(theTableBody.rows[i].cells[index] != null) {
				cell = theTableBody.rows[i].cells[index];
				if (cell.childNodes[0].type == "radio" &&  index != radio.colIndex) {
					viewCell = theTableBody.rows[i-1].cells[index];				
					viewCell.innerHTML = theTableBody.rows[i].cells[index].childNodes[0].unCheckedCaption;
				}	
				index ++;
			}		
			//set row op
			var strId = theTableBody.rows[i].id.toString();
			var op = document.getElementById(strId.substring(0,strId.length-1) + "1Op");
			if ( op.value != "new" ) //new operation not change
				op.value = "replace";
			//***
			theTableBody.rows[i].cells[radio.colIndex].childNodes[objIndex].checked=radio.checked;
		}
	modified = true;
}

function checkAll(checkBoxId) {
	var chkbox = document.getElementById(checkBoxId);
	var theTableBody = chkbox.parentElement.parentElement.parentElement;
	var objIndex=0;
	while(objIndex<theTableBody.rows[0].cells[chkbox.colIndex].childNodes.length) {
		if(theTableBody.rows[0].cells[chkbox.colIndex].childNodes[objIndex].type == "checkbox")
			break;
		objIndex++;	
	}
	
	for(var i=2; i<theTableBody.rows.length; i++)
		if( (i % 2 ) == 0 ) {
			if( theTableBody.rows[i].style.display == 'none' && theTableBody.rows[i+1].style.display != '') { i++; continue; }
			theTableBody.rows[i].cells[chkbox.colIndex].innerHTML = (chkbox.checked)?theTableBody.rows[i+1].cells[chkbox.colIndex].childNodes[objIndex].checkedCaption:
														                             theTableBody.rows[i+1].cells[chkbox.colIndex].childNodes[objIndex].unCheckedCaption;
		}
		else {
			//set row op
			var strId = theTableBody.rows[i].id.toString();
			var op = document.getElementById(strId.substring(0,strId.length-1) + "1Op");
			if ( op.value != "new" ) //new operation not change
			 	op.value = "replace";
			//***
			theTableBody.rows[i].cells[chkbox.colIndex].childNodes[objIndex].checked=chkbox.checked;
		}
	modified = true;
}

function verifyClose() {
	if ( modified )
		event.returnValue = "مقادير برخي از فيلدها تغيير کرده است ، در صورت خروج\n.از صفحه بدون ثبت ، تغييرات ناديده گرفته خواهد شد";
		//"you change some fields ,if leave without apply ,any change will be loosed."
}

function alertOff(tableId) {
	if( tableId ) {
		var theTableBody = document.getElementById(tableId).tBodies[0];
		for ( var i=0; i<theTableBody.rows.length; i++ ) 
			if ( theTableBody.rows[i].modified == true ) {
				modified = true;
				return -1;
			}	
	}		
	modified = false;
}

function getDefaultRow(tableId) {
	var Data = new Array( );
	var defaultRow = document.getElementById(tableId+"DefaultRow");
	for(var i=0; i<defaultRow.cells.length; i++)
		Data[i] = defaultRow.cells[i].innerHTML;
	return Data;
}

function genrateId(tableId, rowClass) {
	if ( rowClass == "visible" )
		rowPostfix++;
	return tableId + "Row" + rowPostfix.toString();
}

function getRowIndex(tableId,row) {
	if ( row == null )
		return -1;
	var i=0;
	var theTableBody = document.getElementById(tableId).tBodies[0];
	while ( theTableBody.rows[i].id != row.id )
		i++;
	var strId = row.id.toString();
	if ( strId.charAt(strId.length-1) == "1" ) //this is edit row
		return i;
	else									   //this is view row
		return i+1;
}

function prepareRowForUndelete(row) {
	var locStr = window.location.toString();

	for (var i=0 ;i<row.cells.length - 1 ;i++)  {
		row.cells[i].ondblclick = ""; //he can't double click
	}
	if ( row.cells[row.cells.length-1].childNodes[0].name != "delete" ) {
		row.cells[row.cells.length-1].childNodes[0].src = sisIMAGEPATH + "grid/edit_disable.gif";
		row.cells[row.cells.length-1].childNodes[0].onclick = "";
	}
	if( row.cells[row.cells.length-1].childNodes[1] ) {
		row.cells[row.cells.length-1].childNodes[1].src = sisIMAGEPATH + "grid/undelete.gif";
		row.cells[row.cells.length-1].childNodes[1].alt = "لغو عمل حذف";
		row.cells[row.cells.length-1].childNodes[1].onclick = undeleteRow;
	}
	else {
		row.cells[row.cells.length-1].childNodes[0].src = sisIMAGEPATH + "grid/undelete.gif";
		row.cells[row.cells.length-1].childNodes[0].alt = "لغو عمل حذف";
		row.cells[row.cells.length-1].childNodes[0].onclick = undeleteRow;
	}

}

function undeleteRow() {
	var locStr = window.location.toString();
	var highLight = GRID_HIGHLIGHTCOLOR; 

	curRow = mouseOverdRow;//focusedRow;
	curRow.style.backgroundColor = curRow.unDeleteColor;
	curRow.deleteStatus = 'normal';	
	curRow.oldColor = curRow.unDeleteColor;
	focused(curRow);
	if( curRow.cells[curRow.cells.length-1].childNodes[0].name == "edit" )
		for (var i=0 ;i<curRow.cells.length - 1 ;i++)
			curRow.cells[i].ondblclick = switchRow; //he can double click

	if( curRow.cells[curRow.cells.length-1].childNodes[0].name != "delete" ) {
		curRow.cells[curRow.cells.length-1].childNodes[0].src = sisIMAGEPATH + "grid/edit.gif";
		curRow.cells[curRow.cells.length-1].childNodes[0].onclick = switchRow;
	}
	if( curRow.cells[curRow.cells.length-1].childNodes[1] ) {
		curRow.cells[curRow.cells.length-1].childNodes[1].src = sisIMAGEPATH + "grid/delete.gif";
		curRow.cells[curRow.cells.length-1].childNodes[1].alt = "حذف";
		curRow.cells[curRow.cells.length-1].childNodes[1].onclick = removeRow;
	}
	else {
		curRow.cells[curRow.cells.length-1].childNodes[0].src = sisIMAGEPATH + "grid/delete.gif";
		curRow.cells[curRow.cells.length-1].childNodes[0].alt = "حذف";
		curRow.cells[curRow.cells.length-1].childNodes[0].onclick = removeRow;
	}
	//set row op
	var strId = curRow.id.toString();
	var op = document.getElementById(strId.substring(0,strId.length-1) + "1Op");
	op.value = (op.value=="view")? "new" : "replace"; //update any way
	//***
}

function removeRow() {
	var curRow = mouseOverdRow;//focusedRow;
		
	if ( curRow != focusedRow )
		curRow.unDeleteColor = curRow.style.backgroundColor; //save current color for undelete
	else
		curRow.unDeleteColor = curRow.oldColor; //save current color for undelete
	var strId = curRow.id.toString();
	if ( strId.charAt(strId.length-1) == "1" ) {//editing
		switchRow();
		var postfix = (strId.charAt(strId.length-1) == "0")? "1" : "0";
		curRow =document.getElementById(strId.substring(0,strId.length-1) + postfix);
		if ( curRow != focusedRow )
			curRow.unDeleteColor = curRow.style.backgroundColor; //save current color for undelete
		else
			curRow.unDeleteColor = curRow.oldColor; //save current color for undelete
	}
	else
		focused(curRow);

	curRow.style.backgroundColor = GRID_DELETE_HIGHLIGHTCOLOR; 
	curRow.oldColor = GRID_DELETECOLOR; 
	curRow.deleteStatus = 'delete';
	//set row op
	var op = document.getElementById(strId.substring(0,strId.length-1) + "1Op");
	op.value = (op.value=="new")? "view" : "del";
	//***
	modified = true;
	//change status bar text
	var statusBar = document.getElementById(curRow.parentElement.parentElement.id+"_statusBar").tBodies[0];
	if ( modified )	
		statusBar.rows[0].cells[0].innerText = "وضعيت: تغييريافته";
	//***
	prepareRowForUndelete(curRow);
}

function appendRow(tableId) {
	insertTableRow(tableId,-1,"visible");
	insertTableRow(tableId,-1,"hidden");
	modified = true;
}

function addRow(tableId) {
	var where;
	if ( (where=getRowIndex(tableId,focusedRow)) == -1 ) {
		appendRow(tableId);
		return;
	}
	else
		where += 1;
	insertTableRow(tableId,where,"visible");
	insertTableRow(tableId,where+1,"hidden");
	modified = true;
}

function getAttributesStr(tag) {
	var attrStr = '';
	for(var i=0; i<tag.attributes.length; i++) {
		if(!tag.attributes[i].specified)
		continue;
		if(tag.attributes[i].name == 'style') // style have a different treat
		attrStr += tag.attributes[i].name + "='" + tag.style.cssText + " '";
		else
		attrStr += tag.attributes[i].name + "='" + tag.attributes[i].nodeValue + " '";
	}
	return attrStr;
}

function getNodeText(nodeObj) {
	var txt = '';

	for( var k=0; k<nodeObj.childNodes.length; k++) {

		var curNode = nodeObj.childNodes[k];

		switch(curNode.nodeName) {
			case "INPUT" :
				switch ( curNode.type ) {
					
					case "text" :   
						if(curNode.value == '')
							txt += '&nbsp;';
						else
							txt += curNode.value;
						break;
						
					case "checkbox" :
					case "radio" : 
						if ( curNode.checked )
							txt += curNode.getAttribute('checkedCaption');
						else
							txt += curNode.getAttribute('unCheckedCaption');
						break;
				}
				break;
				
			case "SELECT":  
				var selectedIndex = curNode.selectedIndex;
				txt += (curNode.options[selectedIndex].text == "")?" ":curNode.options[selectedIndex].text;
				break;
				
			case "TEXTAREA":
				txt += curNode.value;
				break;
				
			case "#text":
				txt += curNode.nodeValue;
				break;
				
			case "BR": 
				txt += '<BR>';
				break;
				
			case "BUTTON":  //ignore nodes
			case "IFRAME":
			case "ACRONYM" : //use for not transform a node
				break;
				
			default :
				txt += '<' + curNode.nodeName + ' ' + getAttributesStr(curNode) + ' >' + getNodeText(curNode) + '</' + curNode.nodeName + '>';
				break;
		}
	}
	return txt;
}

function postRow() {
	var curRow = mouseOverdRow;//focusedRow;
	var strId = curRow.id.toString();
	var postfix = (strId.charAt(strId.length-1) == "0")? "1" : "0";
	var sibRow= document.getElementById(strId.substring(0,strId.length-1) + postfix);
	var formId = curRow.parentElement.parentElement.id;
	if (!eval('ChkGridRow'+formId+'('+sibRow.index+');'))
		return false;
		
	for ( var i=0; i < curRow.cells.length - 1; i++ ) {
		sibRow.cells[i].innerHTML = getNodeText(curRow.cells[i]);
	}
	//set row op
	var op = document.getElementById(strId.substring(0,strId.length-1) + "1Op");
	if ( op.value != "new" ) //new operation not change
		op.value = "replace";			
		
	//***
	modified = true;
	switchRow();
}

function fillRow(tableId, newRow, rowClass) {
	var Data = getDefaultRow(tableId);
	var theTableBody = document.getElementById(tableId).tBodies[0];
	var defaultRow = theTableBody.rows[0];
	var recordNo = (theTableBody.rows.length - 4 ) / 2; // 1 row title + 1 row default
	var searchStr = "default_value_for_change";								// 2 row new added = 4
	var replaceStr = recordNo.toString();
	var re = new RegExp(searchStr , "g");
	var locStr = window.location.toString();
	
	newRow.newRow = true;
	for (var i = 0; i < Data.length; i++) {
		newCell = newRow.insertCell(i);
		newCell.height = defaultRow.cells[i].height;
		newCell.align = defaultRow.cells[i].align;
		newCell.className = defaultRow.cells[i].className;
		if ( i < Data.length - 1 ) {
				newCell.onclick = onFocus;
				if( rowClass != "visible" )
					newCell.ondblclick = postRow;
				else
					newCell.ondblclick = switchRow;
			}
		if ( rowClass != "visible" ) {
			//correct sisRecord index
			Data[i] = Data[i].replace(re, replaceStr);
			if ( Data[i] == "" ) Data[i] = 'جديد';
			newCell.innerHTML = Data[i];
		}
		else {
			if ( i == Data.length - 1 )
				newCell.innerHTML = "<img name=\"edit\" alt=\"ويرايش\" src=\"" + sisIMAGEPATH + "grid/edit.gif\" onclick=switchRow('mouse')>" +
									"<img name=\"delete\" alt=\"حذف\" src=\"" + sisIMAGEPATH + "grid/delete.gif\" onclick=removeRow('mouse')>";

			else
				newCell.innerHTML = "&nbsp;";
		}
	}
	//correct row op
	if (  rowClass != "visible" )  {
		var op = newRow.cells[Data.length - 1].childNodes[newRow.cells[Data.length - 1].childNodes.length - 3];  
		op.id = newRow.id + "Op";							   
		op.value = "new";
		if (typeof defaultRow.onBeginEditRow == 'function') //must be correct
			defaultRow.onBeginEditRow(newRow.index);//must be correct
	}
	else if (typeof defaultRow.onBeginEditRow == 'function') //must be correct
		newRow.onBeginEditRow = defaultRow.onBeginEditRow; //must be correct
}

function insertTableRow(tableId, where, rowClass) {
	var theTableBody = document.getElementById(tableId).tBodies[0];
	var rowType = ( rowClass == "visible" )?"0" : "1";
	var newCell;
	var newRow = theTableBody.insertRow(where);
	var rowIdName = genrateId(tableId,rowClass)+rowType;
	//set new row attribute
	newRow.id = rowIdName;
	var recordNo = Math.round((theTableBody.rows.length - 4 ) / 2);
	newRow.index = recordNo;
	newRow.style.backgroundColor = GRID_NEWCOLOR;
	newRow.onmouseover = updateOverRow;
	rowDisplay = ( rowClass == "visible" )? "none" : ""; 
	newRow.style.display  = rowDisplay;
	fillRow(tableId,newRow,rowClass);
	focusOnFirstNode(newRow);
	focused(newRow);
}

function hiddenRow(rowId) {
	var one = document.getElementById(rowId);
	one.style.display="none"; 	
}

function visibleRow(rowId) {
	var one=document.getElementById(rowId);
	one.style.display = "";
	focused(one);
	focusOnFirstNode(one);
}

function focusOnFirstNode(nodeObj) {
	for( var k=0; k<nodeObj.childNodes.length; k++) {

		var curNode = nodeObj.childNodes[k];

		switch(curNode.type) {
			case 'text':
			case 'select-one':
			case 'input':
			case 'textarea':
			case 'radio':	
			case 'checkbox':
				curNode.focus();
				return true;
			default:
				if( focusOnFirstNode(curNode) )
					return true;
				else	
					break;					
		}
	
	}
	return false;
}

function switchRow() {
	var curRow = mouseOverdRow;	
	var statusBar = document.getElementById(curRow.parentElement.parentElement.id+"_statusBar").tBodies[0];
	if ( modified )	
		statusBar.rows[0].cells[0].innerText = "وضعيت: تغييريافته";
	//***
	if( curRow.modified )
		curRow.modified = false;
	hiddenRow(curRow.id);
	var strId = curRow.id.toString();
	var postfix = (strId.charAt(strId.length-1) == "0")? "1" : "0";
	if( postfix == "1" ) {
		 var one = document.getElementById(strId.substring(0,strId.length-1) + postfix);
		 one.modified = true;
	}	
	visibleRow(strId.substring(0,strId.length-1) + postfix);
	if (typeof curRow.onBeginEditRow == 'function')
		curRow.onBeginEditRow(curRow.index);	

}

function updateOverRow(row) {
	if ( row == null )
		mouseOverdRow = this;
	else
		mouseOverdRow = row;
}
function onFocus(col) {
	if ( col == null )
		focused(this.parentElement);
	else
		focused(col.parentElement);
}

function focused(row) {
	//change status bar text
	var statusBar = document.getElementById(row.parentElement.parentElement.id+"_statusBar").tBodies[0];
	if (row.cells[0].innerText.length > 15)
		statusBar.rows[0].cells[2].innerText = "سطر جاري: " + row.cells[0].innerText.substring(0,15) + "...";
	else
		statusBar.rows[0].cells[2].innerText = "سطر جاري: " + row.cells[0].innerText;
	curRowIndex = (row.index*1) + 1;
	statusBar.rows[0].cells[1].innerText = "سطر " + curRowIndex + " از " +(row.parentElement.rows.length - 2)/2;
	//***
	var highLight = GRID_HIGHLIGHTCOLOR;
	var removeHighLight = GRID_DELETE_HIGHLIGHTCOLOR; 
	if ( focusedRow != null ) 
		 focusedRow.style.backgroundColor = focusedRow.oldColor;
	focusedRow = row;
	row.oldColor = row.style.backgroundColor;
	if ( row.style.backgroundColor == GRID_DELETECOLOR )
		row.style.backgroundColor = removeHighLight;
	else
		row.style.backgroundColor = highLight;
}

function hexToInt(hex) {
	return eval("0x" + hex.substring(1,hex.length).toUpperCase());
}

window.onbeforeunload = verifyClose;
init();