//Offline editor: Start
	var lang = 0;// 1: Farsi, 0: English
	var farsikey = [
	   0x0020, 0x0021, 0x061B, 0x066B, 0x00A4, 0x066A, 0x060C, 0x06AF,
	   0x0029, 0x0028, 0x002A, 0x002B, 0x0648, 0x002D, 0x002E, 0x002F,
	   0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
	   0x0038, 0x0039, 0x003A, 0x0643, 0x003E, 0x003D, 0x003C, 0x061F,
	   0x066C, 0x0624, 0x200C, 0x0698, 0x0649, 0x064D, 0x0625, 0x0623,
	   0x0622, 0x0651, 0x0629, 0x00BB, 0x00AB, 0x0621, 0x004E, 0x005D,
	   0x005B, 0x0652, 0x064B, 0x0626, 0x064F, 0x064E, 0x0056, 0x064C,
	   0x0058, 0x0650, 0x0643, 0x062C, 0x005C, 0x0686, 0x00D7, 0x0640,
	   0x200D, 0x0634, 0x0630, 0x0632, 0x064A, 0x062B, 0x0628, 0x0644,
	   0x0627, 0x0647, 0x062A, 0x0646, 0x0645, 0x067E, 0x062F, 0x062E,
	   0x062D, 0x0636, 0x0642, 0x0633, 0x0641, 0x0639, 0x0631, 0x0635,
	   0x0637, 0x063A, 0x0638, 0x007D, 0x007C, 0x007B, 0x007E];
	function getIndex(theArray, theValue) {
		for(var i = 0; i < theArray.length; ++i)
			if(theValue == theArray[i])
				return i;
		return -1;
	}
	function unicode2TwoSingleBytes(unicodeChar) {
	var	i, persianChars = new Array(
			'ا', 'ب', 'پ', 'ت', 'ث', 'ج', 'چ', 'ح',
			'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش',
			'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق',
			'ک', 'گ', 'ل', 'م', 'ن', 'و', 'ه', 'ی',
			'ء', '،', '؛', 'ٍ', 'ً', 'ٌ', 'ٍ', 'َ',
			'ُ', 'ِ', 'ّ', 'ْ', 'آ', '«', '»', '؟',
			'ء', 'أ', 'إ', 'ؤ', 'ي', 'ة', '×', 'ئ'
		),
		persianCharsURLEncoded = new Array(
			'%D8%A7', '%D8%A8', '%D9%BE', '%D8%AA', '%D8%AB', '%D8%AC', '%DA%86', '%D8%AD',
			'%D8%AE', '%D8%AF', '%D8%B0', '%D8%B1', '%D8%B2', '%DA%98', '%D8%B3', '%D8%B4',
			'%D8%B5', '%D8%B6', '%D8%B7', '%D8%B8', '%D8%B9', '%D8%BA', '%D9%81', '%D9%82',
			'%DA%A9', '%DA%AF', '%D9%84', '%D9%85', '%D9%86', '%D9%88', '%D9%87', '%DB%8C',
			'%D8%A1', '%D8%8C', '%D8%9B', '%D9%8D', '%D9%8B', '%D9%8C', '%D9%8D', '%D9%8E',
			'%D9%8F', '%D9%90', '%D9%91', '%D9%92', '%D8%A2', '%C2%AB', '%C2%BB', '%D8%9F',
			'%D8%A1', '%D8%A3', '%D8%A5', '%D8%A4', '%D9%8A', '%D8%A9', '%C3%97', '%D8%A6'
		);
		if(-1 != (index = getIndex(persianChars, unicodeChar))) {
			return persianCharsURLEncoded[index];
		}
		return escape(unicodeChar);
	}
	function unicodeURLEncode(str) {
	var	i, s;
		for(i = 0, s = ''; i < str.length; ++i) {
			s += unicode2TwoSingleBytes(str.charAt(i));
		}
		return s;
	}
	function str_replace(searchStr, replaceStr, subject) {
	var	theIndex, startIndex;
		for(theIndex = 0, startIndex = 0; -1 != (theIndex = subject.indexOf(searchStr, startIndex)); startIndex = theIndex + replaceStr.length) {
			subject = subject.substr(0, theIndex) + replaceStr + subject.substr(theIndex + searchStr.length);
		}
		return subject;
	}
	function appendCloseList(listType, numOpened, numClosed) {
	var	j, str;
		for(j = numOpened, str = ''; j > numClosed; --j) {
			str += '</' + listType + '>';
		}
		return str;
	}
	function substr_count(haystack, needle) {
	var	cnt, index;
		for(cnt = 0, index = -1; -1 != (index = haystack.indexOf(needle, index + 1)); ++cnt);
		return cnt;
	}
	function replaceListsAndLineBreaks(data) {
	var	str, lines, matches, prologue, curLineType, lastLineType, curLevel = 0,
		numOpened = 0, numClosed = 0, header, inTable, i;
		for(lines = data.split('\n'), lastLineType = '', curLineType = '', str = '', inTable = 0, i = 0; i < lines.length; ++i) {
			matches = lines[i].match(/^([*|#]+)(.+)$/);
			if(null !== matches && matches.length > 0) {
				newLineMustBeTranslated = false;
				prologue = '';
				if(lastLineType != (curLineType = ('#' == lines[i].charAt(0) ? 'o' : 'u') + 'l')) {
					prologue = appendCloseList(lastLineType, numOpened, numClosed);
					curLevel = numOpened = numClosed = 0;
				}
				if(curLevel < matches[1].length) { //A new level encountered
					numOpened++;
					header = '<' + curLineType + '>';
				} else if(curLevel > matches[1].length) {
					numClosed++;
					header = appendCloseList(curLineType, curLevel, matches[1].length);
				} else {
					header = '';
				}
				lastLineType = curLineType;
				curLevel = matches[1].length;
				lines[i] = prologue + header + '<li>' + matches[2] + '</li>';
			} else {
				newLineMustBeTranslated = true;
				lines[i] += appendCloseList(lastLineType, numOpened, numClosed);
				curLevel = numOpened = numClosed = 0;
			}
			inTable += substr_count(lines[i], '<table') - substr_count(lines[i], '</table');
			str += lines[i] + (true === newLineMustBeTranslated && inTable <= 0 ? '<br>' : '') + '\n';
		}
		return str + appendCloseList(lastLineType, numOpened, numClosed);
	}
	function strTrim(s) {
		return s.replace(/^\s*/, '').replace(/\s*$/, '');
	}
	function parse_htmlchar(data) {
		// cleaning some user input
		data = data.replace(/&(?!([a-z]{1,7};))/, '&amp;');
		// oft-used characters (case insensitive)
	    data = data.replace(/~bs~/i, '&#92;');
	    data = data.replace(/~hs~/i, '&nbsp;');
	    data = data.replace(/~amp~/i, '&amp;');
	    data = data.replace(/~ldq~/i, '&ldquo;');
	    data = data.replace(/~rdq~/i, '&rdquo;');
	    data = data.replace(/~lsq~/i, '&lsquo;');
	    data = data.replace(/~rsq~/i, '&rsquo;');
	    data = data.replace(/~c~/i, '&copy;');
	    data = data.replace(/~--~/, '&mdash;');
	    data = data.replace(/ -- /, ' &mdash; ');
	    data = data.replace(/~lt~/i, '&lt;');
	    data = data.replace(/~gt~/i, '&gt;');
	   	// HTML numeric character entities
	    data = data.replace(/~([0-9]+)~/, '&#$1;');
	    return data;
	}
	function makeTOC(data, lineEnd) {
	var	lines, matches, tocStr, str, i;
		for(lines = data.split('\n'), str = '', tocStr = '', i = 0; i < lines.length; ++i) {
			matches = lines[i].match(/^(!+)(.+)$/);
			if(null !== matches && matches.length > 0) {
				tocStr += str_replace('!', '*', matches[1]) + '<a href="#' + (randomID = parseInt(100000 * Math.random())) + '">' + str_replace('))', '', str_replace('((', '', matches[2])) + '</a>' + lineEnd;
				str += matches[1] + '<a id="' + randomID + '">' + matches[2] + '</a>\n';
			} else {
				str += lines[i] + '\n';
			}
		}
		return str.replace(/[H|V]{maketoc}/i, tocStr);
	}
	function extractElementParameters(element) {
	var	abbrParams = new Array('a', 'h', 'w', 'cs', 'rs', 'cbgc'),
		fullParams = new Array('align', 'height', 'width', 'colspan', 'rowspan', 'bgcolor');
		for(var i = 0, extra = ''; i < abbrParams.length; ++i) {
			if(null != (match = element[0].match(new RegExp('~' + abbrParams[i] + ':([^\\s]+)', 'i')))) {
				extra += ' ' + fullParams[i] + '="' + match[1] + '"';
				element[0] = element[0].replace(match[0], '');
			}
		}
		return extra;
	}
	function fancyTablePlugin(args, body) {
	var i, j, allArgs, argParts, allHeadings, headingClause = '', valignClause = '', params = '', dummy = new Array();
		allArgs = args.split(',');
		for(i = 0; i < allArgs.length; ++i) {
			argParts = allArgs[i].split('=');
			switch(strTrim(argParts[0])) {
				case 'bc':
					params += ' bordercolor="' + argParts[1] + '"';
					break;
				case 'head':
					allHeadings = argParts[1].split('~|~');
					for(j = 0; j < allHeadings.length; ++j) {
						dummy[0] = allHeadings[j];
						headingClause += '<th ' + extractElementParameters(dummy) + '>' + dummy[0] + '</th>';
					}
					break;
				case 'tbgc':
					params += ' bgcolor="' + argParts[1] + '"';
					break
				case 'border':
					params += ' border="' + argParts[1] + '"';
					break;
				case 'cvalign':
					valignClause = ' valign="' + argParts[1] + '"';
					break;
			}
		}
		if('|~|' == (tableRowSeparator = -1 != body.indexOf('|~|') ? '|~|' : '\n')) {
			body = str_replace('\n', '<br>', body);
		}
		allBodyLines = body.split(tableRowSeparator);
		for(i = 0, rows = '<tr>'; i < allBodyLines.length; ++i) {
			if('' == strTrim(allBodyLines[i])) {
				continue;
			}
			parts = allBodyLines[i].split('~|~');
			for(j = 0; j < parts.length; ++j) {
				dummy[0] = parts[j];
				rows += '<td ' + valignClause + ' ' + extractElementParameters(dummy) + '>' + ('~blank~' == strTrim(dummy[0]) ? '&nbsp;' : dummy[0]) + '</td>';
			}
			rows += '</tr>\n';
		}
		return '<table style="border-collapse: collapse;" cellpadding="0" cellspacing="0" ' + params + '>\n' + ('' != headingClause ? '<tr>' + headingClause + '</tr>\n' : '') + rows + '\n</table>\n';
	}
	function replacePlugins(str) {
		while(null != (components = str.match(/{([^(]+)\(([^)]*)\)}([^{]*){\1}/))) {
			switch(strTrim(components[1])) {
				case 'FANCYTABLE':
					str = str.replace(components[0], fancyTablePlugin(components[2], components[3]));
					break;
				default:
					str = str.replace(components[0], '');
					break;
			}
		}
		return str;
	}
	function set_url_file(filename,with_name){
		if(undefined == typeof(with_name)){
			with_name = true;
		}
		hash = MD5(filename).toLowerCase();
		url  = hash.substr(0,1)
		url += "/" + hash.substr(0, 2 ) ;
		if(with_name){
			return  url+"/"+hash;
		}else{
			return  url+"/";
		}
	}
     function preg_match_all(pattern, subject, outMatches) {
     	if(undefined == outMatches) {
     		outMatches = new Array();
     	}
     	for(var numSubPatterns, matches; matches = pattern.exec(subject);) {
     		for(numSubPatterns = 0; numSubPatterns < matches.length; ++numSubPatterns) {
     			if(undefined == outMatches[numSubPatterns]) {
     				outMatches[numSubPatterns] = new Array(matches[numSubPatterns])
     			} else {
     				outMatches[numSubPatterns].push(matches[numSubPatterns]);
     			}
     		}
     	}
     	return outMatches;
     }
	function parse_data(data) {
		data = parse_htmlchar(data);
		//Process TOC
		matches = data.match(/([H|V]){maketoc}/i);
		if(null !== matches && matches.length > 0) {
			data = makeTOC(data, 'V' == matches[1].toUpperCase() ? '\n' : '');
		}
		// Replace Inline Images
		data = str_replace('{picture=', '{picture file=', data);//Legacy support
		data = data.replace(/\{[t]?picture\s*([^\}]+)\}/g,
			function makeImageLink(whole, firstMatch) {
			var allParams, retValue = '';
				allParams = preg_match_all(/\s*([a-zA-Z]+)\s*=\s*([^"\s}]+)/g, firstMatch, preg_match_all(/\s*([a-zA-Z]+)\s*=\s*"([^"}]+)"/g, firstMatch, allParams));
				/*
					allParams[0] = Whole matches
					allParams[1] = Name parts
					allParams[2] = Value parts
				*/
				if(allParams) {
					$.ajax({
						type: 'POST',
						url: 'mavara-parse_inline_images.php',
						data: {
							'valueNameParts': JSONstring.make(allParams)
						},
						dataType: 'json',
         				async: false,
						success: function(httpResponse, status) {
							if(httpResponse.retCode < 0) {
								alert(httpResponse.retCodeDesc);
							} else {
								if(httpResponse.finalImgTagParts && undefined != httpResponse.finalImgTagParts.src) {
									imgTagParams = '';
									for(var namePart in httpResponse.finalImgTagParts) {
										imgTagParams += namePart + '="' + httpResponse.finalImgTagParts[namePart] + '" ';
									}
									retValue = '<img ' + imgTagParams + ' />';
								} else {
									retValue = 'picture not found';
								}
							}
						}
					});
				}
				return retValue;
			}
		);
		// Replace Images
		data = data.replace(/\{img ([^\}]+)\}/g, function makeImages(whole, firstMatch) {var alignPrologue = alignEpilogue = descPrologue = descEpilogue = linkPrologue = linkEpilogue = paramStr = '';for(var i = 0, params = firstMatch.split(' '); i < params.length; ++i) {params[i] = params[i].replace('/\}/', '');params[i] = params[i].replace('/\{/', '');params[i] = params[i].replace("/\'/", '');params[i] = params[i].replace('/\"/', '');sides = params[i].split('=');switch(sides[0] = sides[0].toLowerCase()) {case 'alt':case 'src':case 'width':case 'height':paramStr += ' ' + sides[0] + '="' + sides[1] + '"';break;case 'align':alignPrologue = '<div class="img" align="' + sides[1] + '">';alignEpilogue = '</div>';break;case 'desc':descPrologue = '<table cellpadding="0" cellspacing="0"><tr><td>';descEpilogue = '</td></tr><tr><td class="mini">' + sides[1] + '</td></tr></table>';break;case 'link':linkPrologue = '<a href="' + sides[1] + '">';linkEpilogue = '</a>';break;}}return alignPrologue + descPrologue + linkPrologue + '<img border="0"' + paramStr + '>' + linkEpilogue + descEpilogue + alignEpilogue;});
		// Replace ((text~hint))
		data = data.replace(/\(\(([^~\(\)]+)~([^~\(\)]*)\)\)/g, '<a title="$1"><font color="#008040"><u>$2</u></font></a>');
		// Replace ^text^ with boxes
		data = data.replace(/\^([^\^]+)\^/mg, '<div style="margin-left: 1px; margin-right: 1px; margin-top: 5px; margin-bottom: 5px; padding-left: 2px; padding-top: 2px; padding-bottom: 2px; padding-right: 2px; border: 1px solid black; background: #EFEFEF; width: 97%; font-family: Tahuma, Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">$1</div>');
		// Replace colors ~~color:text~~
		data = data.replace(/\~\~([^\:]+):((~[^\~]|[^\~])+)\~\~/mg, '<span style="color:$1;">$2</span>');
		// Replace fonts @#font:text#@
		data = data.replace(/@#([^\:]+):((#[^@]|[^#])+)#@/mg, '<span style="font-size:$1px;">$2</span>');
		// Underlined text
		data = data.replace(/===((==[^\=]|=[^\=]|[^\=])+)===/mg, '<span style="text-decoration: underline;">$1</span>');
		// Center text
		data = data.replace(/::((:[^:]|[^:])*)::/mg, '<div align="center">$1</div>');
		// Left text
		data = data.replace(/@@((@[^@]|[^@])+)@@/mg, '<div align="left">$1</div>');
		// Smileys
		data = data.replace(/\(:([^:]+):\)/g, '<img alt="$1" src="img/smiles/icon_$1.gif" />');
		// Replace Internal Links
		data = data.replace(/\(\(([^\|\(\)]+)\|*([^\|\(\)]*)\)\)/mg, function makeInternalLink(whole, firstMatch, secondMatch) {return '<a href="mavara-index.php?page=' + unicodeURLEncode(firstMatch) + '">' + ('' == secondMatch ? firstMatch : secondMatch) + '</a>';});
		// Replace External Links
		data = data.replace(/\[([^\|\[\]]+)\|*([^\|\[\]]*)\]/mg, function makeExternalLink(whole, firstMatch, secondMatch) {return '<a href="' + firstMatch + '">' + ('' == secondMatch ? firstMatch : secondMatch) + '</a>';});
		// Replace Tables
		data = data.replace(/\|\|(([^|]|\|[^|])*)\|\|/mg, function makeTables(whole, firstMatch) {var j, k, str, rows, cols, maxCols; str = '<table class="daneshnamehtable">\n'; for(j = 0, maxCols = -1, rows = firstMatch.split('\n'); j < rows.length; maxCols = Math.max(maxCols, rows[j].split('|').length), ++j); for(j = 0; j < rows.length; str += '</tr>\n', ++j) { for(k = 0, str += '<tr>\n', cols = rows[j].split('|'); k < cols.length; ++k) {str += '<td class="daneshnamehcell" colspan="' + (k < cols.length - 1 ? 1 : maxCols - cols.length + 1) + '">' + cols[k] + '</td>\n'; }} return str + '</table>\n';});
		// Replace Plugins
		data = replacePlugins(data);
		// Replace Titlebar
		data = data.replace(/-=((=[^-]|[^-])+)=-/mg, '<div style="background: #EFEFEF; color: #006396; font-weight: bold; border:1px solid blue; padding-left: 1px; padding-right: 1px; padding-top:1px; padding-bottom: 1px; margin: 1px 1px; width: 99%; clear: both;">$1</div>');
		if(matches = data.match(/{\*((\*[^}]|[^}])+)\*}/mg)) {
			data = justifyText(data, matches);
		}
		// Monospaced text
		data = data.replace(/-\+((\+[^-]|[^\+])+)\+-/mg, '<code>$1</code>');
		// Bolded text
		data = data.replace(/__((_[^_]|[^_])*)__/mg, '<b>$1</b>');
		// Italicized text
		data = data.replace(/\'\'((\'[^\']|[^\'])+)\'\'/mg, '<i>$1</i>');
		// Replace definition lists
		data = data.replace(/^;(.*):[^\/\/](.*)/g, '<dl><dt>$1</dt><dd>$2</dd></dl>');
		// Replace (un)ordered Lists and (\n)s
		data = replaceListsAndLineBreaks(data);
		// Replace --- with <hr>
		data = data.replace(/^---/mg, '<hr/>');
		// Replace Headings
		data = data.replace(/^(!+)(.+)*/mg, function makeHeading(whole, firstMatch, secondMatch) {return '<h' + firstMatch.length + '>' + secondMatch + '</h' + firstMatch.length + '>';});
		data = str_replace('</div><br>', '</div>', data);
		return data;
	}
	function showOfflinePreview(data, title) {
		pwind = open('', '', 'dependent=yes,resizable=yes,scrollbars=yes,menubar=yes,locationbar=no,status=yes,toolbar=yes').document;
		pwind.write('<html dir="rtl">\n<head>\n<title>Mavara Preview</title>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style type="text/css">\nBody {font-family: Tahoma;}\n</style>\n</head>\n<body>\n');
		pwind.write('<h1 style="font-weight: bold; font-size: 26px; font-family: Tahoma; color: #006699;">' + title + '</h1>\n');
		pwind.write(parse_data(data));
		pwind.write('\n</body>\n</html>');
	}
	function showPreview(data, id, allowHTML, anchorTag, thisElementRef) {
	var	displayAreaRef = document.getElementById(id);
		if(!displayAreaRef) {
			alert('Fast Preview area not defined!');
			return false;
		}
		/*if('none' != displayAreaRef.style.display) {
			displayAreaRef.style.display = 'none';
			return;
		}*/
		displayAreaRef.style.display = 'inline';
		if(false === allowHTML) {
			data = data.replace(/>/g, '&gt;').replace(/</g, '&lt;');
		}
		$('#' + id).html('<div class="daneshnamehtext"><center><b><small>توجه: ممکن است بعضی از دستورات ماورا در نمایش سریع عمل نکنند. برای مشاهده آن ها از `پیش نمایش` استفاده کنید!</small></b></center><br><h2>پیش نمایش سریع: </h2>\n<br><br>\n' + parse_data(data) + '</div>');
		//displayAreaRef.innerHTML = '<div class="daneshnamehtext"><center><b><small>توجه: ممکن است بعضی از دستورات ماورا در نمایش سریع عمل نکنند. برای مشاهده آن ها از `پیش نمایش` استفاده کنید!</small></b></center><br><h2>پیش نمایش سریع: </h2>\n<br><br>\n' + parse_data(data) + '</div>';
		if(-1 == (poundPos = document.location.href.indexOf('#'))) {
			document.location.href += '#' + anchorTag;
		} else {
			document.location.href = document.location.href.substring(0, poundPos + 1) + anchorTag;
		}
	}
	function findNewLineCharFromPosition(haystack, needle, position, direction) {
	var io, lio;
		if('BACKWARD' == direction) {
			return -1 != (lio = haystack.lastIndexOf(needle, position)) ? lio + needle.length : position;
		}
		return -1 != (io = haystack.indexOf(needle, position)) ? io - needle.length : position;
	}
	function justifyText(data, match) {
	var fp, lp, startTag = '<div style="text-align: justify; text-justify: kashida; text-kashida: 0%;">', endTag = '</div>';
		for(var i = 0; i < match.length; ++i) {
			data = str_replace(match[i], processedMatch = str_replace('*}', '', str_replace('{*', '', match[i])), data);
			fp = findNewLineCharFromPosition(data, '\n', matchStartIndex = data.indexOf(processedMatch), 'BACKWARD');
			lp = findNewLineCharFromPosition(data, '\r', matchStartIndex + processedMatch.length, 'FORWARD');
			data = data.substr(0, fp) + startTag + str_replace('\r\n', endTag + startTag, str_replace('<br>', '\r\n', data.substr(fp, lp - fp + 1))) + endTag + data.substr(lp + 1);
		}
		return data;
	}
	function readDoc(fileName) {
	var fso, f, contents;
		globalFileName = fileName;
		alert('To read from your file system, an ActiveX control is needed. Please answer YES to the subsequent warning\nجهت خواندن فایل از سیستم شما نیاز به ActiveX Control است که استفاده از آن باعث صدور یک هشدار می شود. لطفا به آن، پاسخ مثبت دهید');
		fso = new ActiveXObject('Scripting.FileSystemObject');
		f = fso.OpenTextFile(fileName, 1 /*For Reading*/, false /*No File Creation*/, -1 /*Unicode*/);
		contents = f.ReadAll();
		f.Close();
		return contents;
	}
	function saveDoc(contents, charset) {
	var win = window.open('', '_blank', 'top=10000');
		win.document.open('text/plain', '_blank');
		win.document.charset = undefined == charset ? 'UTF-8' : charset;
		win.document.writeln(contents);
		win.document.execCommand('SaveAs', false, '.txt')
		win.close();
	}
	function correctLangValue(key) {
		if(lang == 0 && key != 32 && (key == 247 || key > 1000))
			lang = 1;
		else if(lang == 1 && key < 247 && key != 32)
			lang = 0;
		return true;
	}
	function uniformCharCodes(code) {
	var	index;
	var	curCodes = new Array(247, 1662, 125, 1688, 8520, 1610, 1603); // Grave, Backslash, shift-x, and ??? respectively
	var	newCodes = new Array(0x0060, 0x0060, 0x0698, 0x0698, 0x0698, 0x06CC, 0x06A9); // Peh, Zheh, Ya, and Kaf respectively
		if(-1 == (index = getIndex(curCodes, code)))
			return code;
		return newCodes[index];
	}
	function storeCaret() {
		if(this.createTextRange)
			this.caretPos = document.selection.createRange().duplicate();
		return true;
	}
	function FKeyDown() {
		lang ^= true === window.event.shiftKey && true === window.event.altKey ? 1 : 0
		return true;
	}
	function FKeyPress(event) {
		event = event || window.event;
	var isIECompliant = event.which ? false : true;
	var key = true === isIECompliant ? event.keyCode : event.which;
		correctLangValue(key);
		if(lang == 0 || key == 13) {
			return true;
		}
		key = uniformCharCodes(key);
		if(key > farsikey.length + 0x0020) {
			if(-1 == (index = getIndex(farsikey, key))) {
				if(true === isIECompliant) {
					event.keyCode = key;
				} else {
					event.which = key;
				}
				return true;
			}
			key = index + 0x0020;
		}
		if(true === isIECompliant) {
			event.keyCode = 0x0020 == key && event.shiftKey ? 0x200C : farsikey[key - 0x0020];
			event.keyCode = farsikey[key - 0x0020] == 92 ? 0x0698 : (farsikey[key - 0x0020] == 8205 ? 0x067E : event.keyCode);
		} else {
			event.which = 0x0020 == key && event.shiftKey ? 0x200C : farsikey[key - 0x0020];
			event.which = farsikey[key - 0x0020] == 92 ? 0x0698 : (farsikey[key - 0x0020] == 8205 ? 0x067E : event.which);
		}
		return true;
	}
	function pasteCharConvert() {
	var toCharCodeArray = new Array(1705, 1740);
	var fromCharCodeArray = new Array(1603, 1610);
	var	clipboardData = window.clipboardData.getData('Text');
		if('string' != typeof(clipboardData)) {
			return true;
		}
		for(var i = 0; i < clipboardData.length; ++i) {
			while(i < clipboardData.length && -1 !== (index = getIndex(fromCharCodeArray, clipboardData.charCodeAt(i)))) {
				clipboardData = clipboardData.substr(0, i) + String.fromCharCode(toCharCodeArray[index]) + clipboardData.substr(i + 1);
				++i;
			}
		}
		window.clipboardData.setData('Text', clipboardData);
		return true;
	}
	function setSomeElement(fooel, foo1) {
		document.getElementById(fooel).value = document.getElementById(fooel).value + foo1;
	}
	function setSelectionRange(textarea, selectionStart, selectionEnd) {
	  if (textarea.setSelectionRange) {
	    textarea.focus();
	    textarea.setSelectionRange(selectionStart, selectionEnd);
	  }
	  else if (textarea.createTextRange) {
	    var range = textarea.createTextRange();
	    textarea.collapse(true);
	    textarea.moveEnd('character', selectionEnd);
	    textarea.moveStart('character', selectionStart);
	    textarea.select();
	  }
	}
	function setCaretToPos (textarea, pos) {
	  setSelectionRange(textarea, pos, pos);
	}
	function insertAt(elementId, replaceString) {
		try {
		var toBeReplaced = /text|page|area_name/;
			textarea = document.getElementById(elementId);
			if(textarea.setSelectionRange) {
		    var selectionStart = textarea.selectionStart;
		    var selectionEnd = textarea.selectionEnd;
		    var scrollTop=textarea.scrollTop;
				if(selectionStart != selectionEnd) {
				var newString = replaceString.replace(toBeReplaced, textarea.value.substring(selectionStart, selectionEnd));
					textarea.value = textarea.value.substring(0, selectionStart) + newString + textarea.value.substring(selectionEnd);
					setSelectionRange(textarea, selectionStart, selectionStart + newString.length);
				} else {
					textarea.value = textarea.value.substring(0, selectionStart) + replaceString + textarea.value.substring(selectionEnd);
					setCaretToPos(textarea, selectionStart + replaceString.length);
				}
				textarea.scrollTop=scrollTop;
			} else if(document.selection) {
				textarea.focus();
				var range = document.selection.createRange();
					if(range.parentElement() == textarea) {
					var isCollapsed = range.text == '';
						if(!isCollapsed)  {
							range.text = replaceString.replace(toBeReplaced, range.text);
							range.moveStart('character', -range.text.length);
							range.select();
						} else {
							range.text = replaceString;
						}
					}
				} else {
					setSomeElement(elementId, replaceString)
			}
		} catch(e){
			alert(e.description)
		}
	}
	function textareasize(elementId, height, width, formId) {
		textarea = document.getElementById(elementId);
		form = document.getElementById(formId);
		if (textarea && height != 0 && textarea.rows + height > 5) {
			textarea.rows += height;
			if (form.rows)
				form.rows.value = textarea.rows;
		}
		if (textarea && width != 0 && textarea.cols + width > 10) {
			 textarea.cols += width;
			if (form.cols)
				form.cols.value = textarea.cols;
		}
	}
//Offline editor: End
function showId(id){
	var elementStyle = document.getElementById(id).style.display='block';
}
function hideId(id){
	var elementStyle = document.getElementById(id).style.display='none';
}
function searchWindowGallery(form,field,image,find) {
	window.showModalDialog('mavara-browse_galleries.php?popup=1&form='+form+'&field='+field+'&image='+image+'&find='+unicodeURLEncode(find), window, 'dialogWidth:750px;dialogHeight:600px');
	return false;
}
function finalizeSearch(tail,form,field,image,imageId,src) {
	if('' != tail) {
		window.dialogArguments.document.forms[form].elements[field].value = tail;
		window.dialogArguments.document.forms[form].elements[image].src =src;
		window.dialogArguments.document.forms[form].elements['var_'+image].value =imageId;
	}
	window.close();
}
function change_state_show(id) {
	if(elemRef = document.getElementById(id)) {
		elemRef.style.display = 'none' == elemRef.style.display ? 'block' : 'none';
	}
}
function checkOperationComplete(){
	change_state_show('objectContainer');
	change_state_show('wait_layer');
	change_state_show('shadow_layer');
}
//pourshahmir 84/6/7  upload in survey
function uploadPicInSurvey(surveyId, questionId) {
	target = 'mavara-survey_upload.php?surveyId=' + surveyId;
	if(questionId != undefined || parseInt(questionId) > 0) {
		target += ' questionId' + questionId;
	}
	window.showModalDialog(target, window, 'dialogWidth:500px;dialogHeight:500px');
	return false;
}
//
function showWaitMessage(areaID) {
	document.getElementById(areaID).innerHTML = '<center>لطفا صبر کنید...<img src="img/icons/wait.gif"></center>';
	return true;
}
function SubmitCompeletForm(cat_unidId,file_id){
	try{
		file = document.getElementById(file_id).value;
		if(cat_ids[cat_unidId]!=undefined && cat_ids[cat_unidId].length>0){
			if(file.length<1){
				alert('نام فایل نمی تواند خالی باشد !');
				return false;
			}
			return true;
		}
		alert('Please categorize this ' + '' + '\nلطفا طبقه بندی ' + '' + ' را مشخص کنید');
		return false;
	}catch(e){alert(e.description)}
}
function submitUploadDaneshnameh(form,areaID){
	try{
		for(var i=1;i<=3;i++){
			if(form.elements['use_upload'+i].checked==true){
				if(form.elements['localExist_imagePreview'+i].value==0){
					alert('! عکس شماره '+ i + ' موجود نیست ');
					return false;
				}
			  	if(form.elements['filename_wait'+i].value==1){
					alert('!عکس شماره '+ i + ' در حال بررسی است ');
					return false;
				}
				if(form.elements['filename_exist'+i].value==1){
					alert('! نام عکس شماره'+i+'موجود است ');
					return false;
				}
			}
		}
		showWaitMessage(areaID);
		return true;
	}catch(e){alert(e.description)}
}
//end
function finalizeUpload(tail) {
		if('' != tail) {
			window.dialogArguments.document.myName.edit.value += tail;
		}
		window.close();
}
function finalizeUploadinSurvey(tail) {
	if('' != tail) {
		window.dialogArguments.document.myName.question.value += tail;
	}
	window.close();
}
function requestForDeletion(page) {
var len = strTrim(reason = window.prompt('Reason for Deletion\nدلیل حذف', '')).length;
	if(0 == len) {
		alert('You must give a reason\nذکر دلیل حذف الزامی است');
		return;
	} else if(len < 10) {
		alert('Reason cannot be understood\nدلیل نا مفهوم است');
		return;
	}
	location.href = 'mavara-add_page_del_req.php?page=' + unicodeURLEncode(page) + '&reason=' + unicodeURLEncode(reason);
}
function requestForRename(page) {
var len = strTrim(newName = window.prompt('New Name\nنام جدید', '')).length;
	if(0 == len) {
		alert('You must give a new name\nذکر نام جدید الزامی است');
		return;
	} else if(len < 4) {
		alert('New name is too short\nطول نام جدید کم است');
		return;
	}
	location.href = 'mavara-add_page_ren_req.php?page=' + unicodeURLEncode(page) + '&newName=' + unicodeURLEncode(newName);
}
	function createIFrame(iframeID, resultAreaId, dumbRPC ,after_onload_callmethod ,form) {
	var tempIFrame, iframe;
		if(!document.createElement) {
			return false;
		}
		tempIFrame = document.createElement('iframe');
		tempIFrame.setAttribute('id', iframeID);
		tempIFrame.style.border = tempIFrame.style.width = tempIFrame.style.height = '0px';
		if(false === dumbRPC) {
			tempIFrame.attachEvent('onload',
				function() {
					if('undefined' != typeof(tempIFrame.readyState) && 'complete' == tempIFrame.readyState && resultAreaId) {
						if(tempIFrame.contentDocument) { // For NS6
							document.getElementById(resultAreaId).innerHTML = tempIFrame.contentDocument.body.innerHTML;
						} else if(tempIFrame.contentWindow) { // For IE5.5 and IE6
							document.getElementById(resultAreaId).innerHTML = tempIFrame.contentWindow.document.body.innerHTML;
						} else if(tempIFrame.document) { // For IE5
							document.getElementById(resultAreaId).innerHTML = tempIFrame.document.body.innerHTML;
						} else {
							alert('Error: could not find IFRAME document');
							return false;
						}
						window.status = 'Done'; //Workaround for incorrect browser statusbar status
						if('undefined' != typeof(after_onload_callmethod) &&  false !== after_onload_callmethod){
							eval(after_onload_callmethod);
						}
						checkOperationComplete();
					}
					if(tempIFrame) {
						tempIFrame.removeNode(true); //Remove iFrame from the object tree
						tempIFrame = null;
					}
					return true;
				}
			);
		}
		iframe = document.body.appendChild(tempIFrame);
		iframe.contentWindow.document.write(form)
		if(document.frames) {
			iframe = document.frames[iframeID];
		}
		return document.getElementById(iframeID);
	}
function replaceString(oldS,newS,fullS) {
// Replaces oldS with newS in the string fullS
	for (var i=0; i<fullS.length; i++) {
		if (fullS.substring(i,i+oldS.length) == oldS) {
			fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length)
		}
	}
	return fullS
}
function setClass(className , obj){
	try{
		obj = ('object' == typeof(obj))?obj:document.getElementById(obj);
		obj.className = className;
	}catch(e){}
}
function setActivateStateArea(objects ,idxActive ,classActive ,classDeactivate){
	try{
		var objects;
		for(var i=0;i<objects.length;i++){
			object = ('object' == typeof(objects[i]))?objects[i]:document.getElementById(objects[i]);
			object.className = (i == idxActive) ? classActive:classDeactivate;
		}
	}catch(e){}
}
var expires = new Date();
var offset = -(expires.getTimezoneOffset() * 60);
expires.setFullYear(expires.getFullYear() + 1);
setCookie("tz_offset", offset, expires, "/");
/****************** My Grid *******************/
function extendRow(tableId, src) {
var thisRow = src.parentElement.parentElement.rowIndex + 1, newRow = document.all(tableId).insertRow(thisRow),
	tbody = document.getElementById(tableId + '_tbody'), randomNo = parseInt(1000000 * Math.random());
	src.parentElement.rowSpan++;
	for(var initialValue, i = 1; i < tbody.rows[thisRow - 1].cells.length; ++i) {
		newRow.insertCell().innerHTML = tbody.rows[thisRow - 1].cells[i].innerHTML.replace(/value=/ig, '');
	}
	return true;
}
/****************** My Grid *******************/
function floatingArea(floatingAreaId, onElementId, masterFloatingDivId, searchBoxDivId, xOffset, yOffset) {
var floatingAreaRef;
	xOffset = undefined == xOffset ? -100 : xOffset;
	yOffset = undefined == yOffset ? 20 : yOffset;
	if(undefined != searchBoxDivId && undefined != masterFloatingDivId) {
	var searchBoxDivRef, masterFloatingDivRef;
		if((undefined != (searchBoxDivRef = document.getElementById(searchBoxDivId)) && undefined != (masterFloatingDivRef = document.getElementById(masterFloatingDivId))) && searchBoxDivRef.parentElement != masterFloatingDivRef) {
			searchBoxDivRef.firstChild.value = '';
			searchBoxDivRef.parentElement.removeChild(searchBoxDivRef);
			masterFloatingDivRef.insertBefore(searchBoxDivRef, masterFloatingDivRef.firstChild)
		}
	}
	floatingAreaRef = document.getElementById(floatingAreaId).parentElement;
	ar = getPosition(onElementId);
	ar['x'] += xOffset;
	ar['y'] += yOffset;
	floatingAreaRef.style.position = 'absolute';
	floatingAreaRef.style.left = ar['x'];
	floatingAreaRef.style.top = ar['y'];
	floatingAreaRef.style.display = 'block';
	floatingAreaRef.parentElementId = onElementId;
	floatingAreaRef.onkeydown = function(ev) {
		e = event || ev;
		if(27 == e.keyCode) {
			floatingAreaRef.style.display = 'none';
		}
	}
	floatingAreaRef.focus();
	return false;
}
/****************** Checkbox/Radio Utils *******************/
function getSelectedRadio(buttonGroup) {
	// returns the array number of the selected radio button or -1 if no button is selected
	if(buttonGroup[0]) { // if the button group is an array (one button is not an array)
		for(var i = 0; i < buttonGroup.length; i++) {
			if(buttonGroup[i].checked) {
				return i
			}
		}
	} else {
		if(buttonGroup.checked) {
			return 0;
		} // if the one button is checked, return zero
	}
	// if we get to this point, no radio button is selected
	return -1;
} // Ends the "getSelectedRadio" function
function getSelectedRadioValue(buttonGroup) {
	// returns the value of the selected radio button or "" if no button is selected
	var i = getSelectedRadio(buttonGroup);
	if (i == -1) {
		return '';
	} else {
		if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
			return buttonGroup[i].value;
		} else { // The button group is just the one button, and it is checked
			return buttonGroup.value;
		}
	}
} // Ends the "getSelectedRadioValue" function
function getSelectedCheckbox(buttonGroup) {
	// Go through all the check boxes. return an array of all the ones
	// that are selected (their position numbers). if no boxes were checked,
	// returned array will be empty (length will be zero)
	var retArr = new Array();
	var lastElement = 0;
	if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
		for(var i = 0; i < buttonGroup.length; i++) {
			if (buttonGroup[i].checked) {
				retArr.length = lastElement;
				retArr[lastElement] = i;
				lastElement++;
			}
		}
	} else { // There is only one check box (it's not an array)
		if (buttonGroup.checked) { // if the one check box is checked
			retArr.length = lastElement;
			retArr[lastElement] = 0; // return zero as the only array value
		}
	}
	return retArr;
} // Ends the "getSelectedCheckbox" function
function getSelectedCheckboxValue(buttonGroup) {
	// return an array of values selected in the check box group. if no boxes
	// were checked, returned array will be empty (length will be zero)
	var retArr = new Array(); // set up empty array for the return values
	var selectedItems = getSelectedCheckbox(buttonGroup);
	if(selectedItems.length != 0) { // if there was something selected
		retArr.length = selectedItems.length;
		for(var i = 0; i < selectedItems.length; i++) {
			if(buttonGroup[selectedItems[i]]) { // Make sure it's an array
				retArr[i] = buttonGroup[selectedItems[i]].value;
			} else { // It's not an array (there's just one check box and it's selected)
				retArr[i] = buttonGroup.value;// return that value
			}
		}
	}
	return retArr;
} // Ends the "getSelectedCheckBoxValue" function
/****************** My Grid *******************/
function myParseFloat(num) {
	return '' == num ? 0 : parseFloat(isNaN(num) ? 0 : num);
}
function myParseInt(num) {
	return ('' == num || null == num )? 0 : parseInt(isNaN(num) ? 0 : num);
}
function xmlParser(xmlString) {
var doc, parser;
	if(window.ActiveXObject) {
		doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.async = 'false';
		doc.loadXML(xmlString);
	} else {
		parser = new DOMParser();
		doc = parser.parseFromString(xmlString, 'text/xml');
	}
	return doc;
}
function getVisibleContent(elementId, contentIsHTML, valueFieldName) {
var eTagName, elementRef = document.getElementById(elementId);
	if(!elementRef) {
		return false;
	}
	if(undefined == valueFieldName) {
		valueFieldName = 'value';
	}
	if(undefined == contentIsHTML) {
		contentIsHTML = false;
	}
	if('input' == (eTagName = elementRef.tagName.toLowerCase())) {
		return elementRef[valueFieldName];
	} else if('select' == eTagName) {
		return elementRef[elementRef.selectedIndex][valueFieldName];
	} else if('span' == eTagName) {
		return true === contentIsHTML ? elementRef.innerHTML : elementRef.innerText;
	}
	return eTagName;
}
function setVisibleContent(elementId, content, contentIsHTML) {
var eTagName, elementRef = document.getElementById(elementId);
	if(!elementRef) {
		return false;
	}
	if(undefined == contentIsHTML) {
		contentIsHTML = false;
	}
	if('input' == (eTagName = elementRef.tagName.toLowerCase())) {
		elementRef.value = content;
	} else if('span' == eTagName || 'div' == eTagName || 'td' == eTagName) {
		if(true === contentIsHTML) {
			elementRef.innerHTML = content;
		} else {
			elementRef.innerText = content;
		}
	}
	return true;
}
function publishReqInfo(xmlStr, publishAreaInfo, qtyAreaID, reqAmountTotalAreaID, totalNumAreaID, totalAmountAreaID) {
var x, formattedNum;
	if(!(x = xmlParser(xmlStr).documentElement)) {
		return;
	}
	if('object' != typeof(qtyAreaID)) {
		qtyAreaID = new Array(qtyAreaID);
	}
	if('&nbsp;' == x.childNodes[0].childNodes[0].nodeValue) { //Invalid barcode
		alert('بار کد اشتباه است');
		return false;
	}
	setVisibleContent(publishAreaInfo[0], x.childNodes[0].childNodes[0].nodeValue);
	setVisibleContent(publishAreaInfo[1], formattedNum = makeStrFromNumber(x.childNodes[1].childNodes[0].nodeValue));
	if(undefined != publishAreaInfo[2]) {
		setVisibleContent(publishAreaInfo[2], makeStrFromNumber(x.childNodes[2].childNodes[0].nodeValue));
	}
	setVisibleContent(reqAmountTotalAreaID, formattedNum);
	for(qaii = 0; qaii < qtyAreaID.length; ++qaii) {
		document.getElementById(qtyAreaID[qaii]).value = 1;
	}
	document.getElementById(qtyAreaID[0]).focus();
	return true;
}
function searchInAssocArray(mainArray, key, keyValue) {
	for(var i = 0; i < mainArray.length; ++i) {
		if(undefined != mainArray[i][key] && keyValue == mainArray[i][key]) {
			return i;
		}
	}
	return -1;
}
/*
	var infoArray = new Array(
			{
				"type": 'numeric',
				"mustbeformatted": true,
				"showArea": 'someAreaID',
				"eqTagInXMLContent": 'priceValue'
			},
			{
				"type": 'string',
				"mustbeformatted": false,
				"showArea": 'someOtherAreaID',
				"eqTagInXMLContent": 'partName'
			}
		);
	var extraWorks = new Array(
			{
				"type": 'numeric',
				"mustbeformatted": true,
				"showArea": 'somePlaceID',
				"value": someValue
			});
*/
function publishXMLInfo(xmlStr, infoArray, extraWorks, highlightGrandParentElementOnFailure, thisElementId, highlightColor) {
var x, infoArrayIndex, formattedValue;
	if(!(x = xmlParser(xmlStr).documentElement)) {
	var thisElementRef = document.getElementById(thisElementId);
		if(undefined != highlightGrandParentElementOnFailure && undefined != thisElementId && undefined != thisElementRef) {
			thisElementRef.parentElement.parentElement.bgColor = undefined != highlightColor ? highlightColor : '#FF0000';
		}
		return;
	}
	for(var i = 0; i < x.childNodes.length; ++i) {
		if(-1 == (infoArrayIndex = searchInAssocArray(infoArray, 'eqTagInXMLContent', x.childNodes[i].nodeName))) {
			continue;
		}
		formattedValue = undefined == x.childNodes[i].childNodes[0] ? '' : x.childNodes[i].childNodes[0].nodeValue;
		if('numeric' == infoArray[infoArrayIndex]['type'] && true === infoArray[infoArrayIndex]['mustbeformatted'] && '' != formattedValue) {
			formattedValue = makeStrFromNumber(formattedValue);
		}
		setVisibleContent(infoArray[infoArrayIndex]['showArea'], formattedValue);
	}
	if(undefined != extraWorks) {
		for(var j = 0, resultAreaRef; j < extraWorks.length; ++j) {
			formattedValue = undefined == extraWorks[j]['valueIsID'] ? extraWorks[j]['value'] : getVisibleContent(extraWorks[j]['value']);
			if('numeric' == extraWorks[j]['type'] && true == extraWorks[j]['mustbeformatted'] && 'string' != typeof(formattedValue)) {
				formattedValue = makeStrFromNumber(formattedValue);
			}
			setVisibleContent(extraWorks[j]['showArea'], formattedValue);
		}
	}
	/*setVisibleContent(reqAmountTotalAreaID, formattedNum);
	for(qaii = 0; qaii < qtyAreaID.length; ++qaii) {
		document.getElementById(qtyAreaID[qaii]).value = 1;
	}
	document.getElementById(qtyAreaID[0]).focus();
	*/
	return true;
}
function findRowIndex(x, code) {
	for(var i = 0; i < x.childNodes.length; ++i) {
		if(code == x.childNodes[i].childNodes[0].childNodes[0].nodeValue) {
			return i;
		}
	}
	return -1;
}
function publishFeeAndBacklogInfo(xmlStr, publishAreaInfo) {
var x, index;
	if(!(x = xmlParser(xmlStr).documentElement)) {
		return;
	}
	for(var i = 0; i < publishAreaInfo.length; ++i) {
		if(-1 == (index = findRowIndex(x, getVisibleContent('StfCodeAreaID' + publishAreaInfo[i])))) {
			continue;
		}
		setVisibleContent('feeAreaID' + publishAreaInfo[i], makeStrFromNumber(x.childNodes[index].childNodes[1].childNodes[0].nodeValue));
		setVisibleContent('DrAmountTotalAreaID' + publishAreaInfo[i], makeStrFromNumber(getVisibleContent('ApprovedItemQtyAreaID' + publishAreaInfo[i]) * x.childNodes[index].childNodes[1].childNodes[0].nodeValue));
		setVisibleContent('backlogAreaID' + publishAreaInfo[i], makeStrFromNumber(x.childNodes[index].childNodes[2].childNodes[0].nodeValue));
	}
}
function keyupProcess(keyCode, thisFieldRef, checkForUniqueness, randNums, ajaxScript, inputParamsArray, resultAreaID, waitMessage, formMethod, forceReexecution, onRequestCompletion) {
	if(13 == keyCode && true === checkForUniqueness) {
		for(var curStfCodeId = '', curContent = getVisibleContent(thisFieldRef.id), i = 0; i < randNums.length; ++i) {
			if((curStfCodeId = 'StfCodeAreaID' + randNums[i]) != thisFieldRef.id && getVisibleContent(curStfCodeId) == curContent) {
				setVisibleContent(thisFieldRef.id, '', false);
				alert('مقدار  ' + curContent + '  تکراری است');
				return false;
			}
		}
		ajaxSyncRequest(ajaxScript, inputParamsArray, resultAreaID, waitMessage, formMethod, forceReexecution, onRequestCompletion);
	}
	return false;
}
function getRewquestNumber() {
var rn = window.prompt('شماره درخواست: ');
	return false;
}
function updateRequestTotal(randNums, qtyIDStr, feeIdStr, totalIdStr, totalQtyAreaId, totalPriceAreaId) {
	for(var product = 0, i = 0, numItems = 0, total = 0; i < randNums.length; ++i) {
		randNoAreaIDStr = 'AreaID' + randNums[i];
		numItems += qty = makeNumberFromStr(getVisibleContent(qtyIDStr + randNoAreaIDStr));
		total += product = qty * makeNumberFromStr(getVisibleContent(feeIdStr + randNoAreaIDStr));
		setVisibleContent(totalIdStr + randNoAreaIDStr, makeStrFromNumber(product));
	}
	setVisibleContent(totalQtyAreaId, makeStrFromNumber(numItems));
	setVisibleContent(totalPriceAreaId, makeStrFromNumber(total));
}
function updateFactorTotal(formObj, qtyIDStr, feeIdStr, totalIdStr, totalQtyAreaId, totalPriceAreaId, discountPercentAreaId, discountValAreaId, discountAreaId, paidValAreaId, payableAreaId, payableTextAreaId, remainderAreaId) {
	try {
		for(var wholeDiscount = 0, product = 0, i = 0, numItems = 0, total = 0; i < formObj.length; ++i) {
			if(formObj.elements[i].id.substr(0, qtyIDStr.length) == qtyIDStr) {
				randNo = formObj.elements[i].id.substr(qtyIDStr.length + 'AreaID'.length)
				numItems += qty = myParseInt(formObj.elements[i].value);
				total += product = qty * makeNumberFromStr(getVisibleContent(feeIdStr + 'AreaID' + randNo));
				setVisibleContent(totalIdStr + 'AreaID' + randNo, makeStrFromNumber(product));
			}
		}
		setVisibleContent(totalQtyAreaId, makeStrFromNumber(numItems));
		setVisibleContent(totalPriceAreaId, makeStrFromNumber(total));
		setVisibleContent(discountAreaId, makeStrFromNumber(wholeDiscount = total * myParseFloat(document.getElementById(discountPercentAreaId).value) / 100 + myParseFloat(document.getElementById(discountValAreaId).value)));
		setVisibleContent(payableAreaId, makeStrFromNumber(total - wholeDiscount));
		setVisibleContent(payableTextAreaId, numberToText(total - wholeDiscount));
		setVisibleContent(remainderAreaId, makeStrFromNumber(total - wholeDiscount - myParseFloat(document.getElementById(paidValAreaId).value)));
	} catch(e) {
		alert('Error in `updateFactorTotal`: ' + e.description);
	}
}
function getThisRowNum(src) {
	return src.parentElement.parentElement.rowIndex;
}
function getThisColNum(src) {
	return src.parentElement.cellIndex;
}
function getNumTableRows(tableId) {
	for(numRows = 0, rowSetRef = document.getElementById(tableId + '_tbody').rows; numRows < rowSetRef.length; ++numRows) {
		if(undefined != rowSetRef[numRows].rowIndicator && 'last' == rowSetRef[numRows].rowIndicator) {
			return numRows;
		}
	}
	return numRows;
}
function getNumTableCols(tableId) {
	return document.getElementById(tableId + '_tbody').rows[0].cells.length;
}
function getCellAttribute(tableId, row, col, attribute) {
var innerHTML = document.getElementById(tableId + '_tbody').rows[row].cells[col].innerHTML, newAttribute,
	stPos = innerHTML.indexOf(newAttribute = attribute + '=');
	if(-1 == stPos) {
		return false;
	}
	for(var endPos = stPos; endPos < innerHTML.length; ++endPos) {
		theChar = innerHTML.charAt(endPos);
		if(' ' == theChar || '"' == theChar || '>' == theChar) {
			break;
		}
	}
	return innerHTML.substring(stPos + newAttribute.length, endPos);
}
function setCellAttribute(tableId, row, col, attribute, value) {
var innerHTML = document.getElementById(tableId + '_tbody').rows[row].cells[col].innerHTML, newAttribute,
	stPos = innerHTML.indexOf(newAttribute = attribute + '=');
	if(-1 == stPos) { //attribute is new to the object, create it
		if(-1 == (stPos = innerHTML.indexOf('>'))) { //Not an HTML element
			return false;
		}
		return document.getElementById(tableId + '_tbody').rows[row].cells[col].innerHTML = innerHTML.substring(0, stPos) + ' ' + newAttribute + value + innerHTML.substr(stPos);
	}
	for(var endPos = stPos; endPos < innerHTML.length; ++endPos) {
		theChar = innerHTML.charAt(endPos);
		if(' ' == theChar || '"' == theChar || '>' == theChar) {
			break;
		}
	}
	return document.getElementById(tableId + '_tbody').rows[row].cells[col].innerHTML = innerHTML.substring(0, stPos + newAttribute.length) + value + innerHTML.substring(endPos, innerHTML.length);
}
function addRow(src, tableId, updateMethodNo, hasAddIcon, hasDelIcon, randNums, emptyNewCells) {
var thisRow = src.parentElement.parentElement.rowIndex + 1, newRow = document.all(tableId).insertRow(thisRow);
var tbody = document.getElementById(tableId + '_tbody'), randomNo = parseInt(1000000 * Math.random()), newRowFirstColId;
	emptyNewCells = 'undefined' == typeof(emptyNewCells) ? 'y' : emptyNewCells;
	randNums.push(randomNo);
	newRow.insertCell().innerText = thisRow; //Row Number
	thisRowIndex = getThisRowNum(src);
	for(var tempCell, initialValue, i = 1; i < tbody.rows[thisRowIndex].cells.length - 1; ++i) {
		if('y' === emptyNewCells) {
			if('SELECT' == tbody.rows[thisRowIndex].cells[i].innerHTML.substr(1, 'SELECT'.length)) {
				initialValue = tbody.rows[thisRowIndex].cells[i].innerHTML.replace(/AreaID[0-9]*/ig, 'AreaID' + randomNo);
			} else {
				if(matches = tbody.rows[thisRowIndex].cells[i].innerHTML.match(/defaultValue="(.*)"/)) {
					initialValue = tbody.rows[thisRowIndex].cells[i].innerHTML.replace(/value=/g, '').replace(/CHECKED/g, '')./*replace(/disabled/g, '').*/replace(/BACKGROUND/g, 'dummy').replace(/>.*</, '><').replace(/AreaID[0-9]*/ig, 'AreaID' + randomNo).replace(/defaultValue=/ig, 'value="' + matches[1] + '" defaultValue='); //Empty Contents
				} else {
					initialValue = tbody.rows[thisRowIndex].cells[i].innerHTML.replace(/value=/g, '').replace(/CHECKED/g, '')./*replace(/disabled/g, '').*/replace(/BACKGROUND/g, 'dummy').replace(/>.*</, '><').replace(/AreaID[0-9]*/ig, 'AreaID' + randomNo); //Empty Contents
				}
			}
		} else {
			initialValue = tbody.rows[thisRowIndex].cells[i].innerHTML.replace(/AreaID[0-9]*/ig, 'AreaID' + randomNo);
		}
		if(-1 == tbody.rows[thisRowIndex].cells[i].innerHTML.indexOf('fixed')) {
			initialValue = initialValue.replace(/readonly/ig, '');
		}
		tempCell = newRow.insertCell();
		tempCell.innerHTML = initialValue;
        tempCell.className = tbody.rows[thisRowIndex].cells[i].className;//Preserve Class
		tempCell.style.cssText = tbody.rows[thisRowIndex].cells[i].style.cssText;// and style
	}
	if('y' == hasAddIcon || 'y' == hasDelIcon) {
	var iconSectionContent = '';
		if('y' == hasAddIcon) {
			iconSectionContent += '<img src="imgs/plus.gif" onClick="addRow(this, \'' + tableId + '\', ' + updateMethodNo + ', \'' + hasAddIcon + '\', \'' + hasDelIcon + '\', randNums, \'' + emptyNewCells + '\');" />';
		}
		if('y' == hasDelIcon) {
			iconSectionContent += '<img src="imgs/minus.gif" onClick="removeRow(this, \'' + tableId + '\', ' + updateMethodNo + ', randNums);" />';
		}
		newRow.insertCell().innerHTML = iconSectionContent;
	}
	if(newRowFirstColId = getCellAttribute(tableId, thisRow, 0, 'id')) {
		document.getElementById(newRowFirstColId).focus();
	}
	renumberRows(tableId, thisRow + 1, 1);
	updateMethodNo = undefined == updateMethodNo ? 0 : updateMethodNo;
	switch(updateMethodNo) {
		case 1: 
			break;
		default:
			break;
	}
	return true;
}
function renumberRows(tableId, startRow, offset) {
	for(var tbody = document.getElementById(tableId + '_tbody'), i = startRow, numRows = getNumTableRows(tableId) - 1/*Excluding the footer*/; i < numRows; ++i) {
		tbody.rows[i].cells[0].innerText = myParseInt(tbody.rows[i].cells[0].innerText) + offset;
	}
}
function removeRow(src, tableId, updateMethodNo, randNums) {
	if(document.getElementById(tableId + '_tbody').rows.length > 3) {
	var tempRef, removedCellId = getCellAttribute(tableId, src.parentElement.parentElement.rowIndex, 1, 'id'),
		removedCellRandNo = removedCellId.substr(removedCellId.indexOf('AreaID') + 'AreaID'.length),
		removedCellRandNoIndex = getIndex(randNums, removedCellRandNo);
		if(-1 != removedCellRandNoIndex) {
			randNums.splice(removedCellRandNoIndex, 1);
		}
		updateMethodNo = undefined == updateMethodNo ? 0 : updateMethodNo;
		switch(updateMethodNo) {
			case 1:
				if(tempRef = document.getElementById('switcherAreaID' + removedCellRandNo)) {
					true === tempRef.checked && tempRef.click();
				}
				break;
			default:
				break;
		}
		renumberRows(tableId, src.parentElement.parentElement.rowIndex + 1, -1);
		document.all(tableId).deleteRow(src.parentElement.parentElement.rowIndex);
	}
	return true;
}
function replaceValuesWithValueIDsAndSubmit(formObj, colNameArray) {
	for(var i = 0; i < formObj.length; ++i) {
		for(var j = 0; j < colNameArray.length; ++j) {
			if(formObj[i].name && colNameArray[j] == formObj[i].name.substr(0, colNameArray[j].length) && undefined != formObj[i].valueId) {
				formObj[i].value = formObj[i].valueId;
			}
		}
	}
	return true;
}
function submitDocument(formObj, AccIdColName, CcrIdColName, checkBalance, dbColName, crColName, msgOnFail) {
	if(undefined == checkBalance) {
		checkBalance = false;
	}
var balanced = !checkBalance;
	if(true === checkBalance) {
	var dbCol, crCol;
		dbCol = sumOfCells(formObj, dbColName);
		crCol = sumOfCells(formObj, crColName);
		balanced = dbCol == crCol && 0 != dbCol;
	}
	if(false === balanced) {
		alert(msgOnFail);
		return false;
	}
	replaceValuesWithValueIDsAndSubmit(formObj, new Array(AccIdColName, CcrIdColName));
	formObj.submit();
	return true;
}
function sumOfCells(formObj, cellName) {
	for(var i = 0, sum = 0; i < formObj.length; ++i) {
		if(cellName == formObj[i].name) {
			sum += myParseFloat(formObj[i].value);
		}
	}
	return sum;
}
function updateDbCrTotal(formObj, dbFieldName, crFieldName, dbAreaId, crAreaId) {
	setVisibleContent(dbAreaId, makeStrFromNumber(sumOfCells(formObj, dbFieldName)));
	setVisibleContent(crAreaId, makeStrFromNumber(sumOfCells(formObj, crFieldName)));
}
/****************** My Grid *******************/
function checkFieldEmptiness(filedValue, minFieldLen, emptyPrompt) {
	if(filedValue.length >= minFieldLen) {
		return true;
	}
	alert(emptyPrompt);
	return false;
}
function toggleAllCheckboxes(formObj, cbName, boolValue) {
	for(var i = 0; i < formObj.length; ++i) {
		if(formObj.elements[i].name == cbName) {
			formObj.elements[i].checked = boolValue;
		}
	}
}
function seeIfDocHasBeenCategorized(formName, fieldName, eObjectName, pObjectName) {
	for(var i = 0; i < formName[fieldName].length; ++i) {
		if(true === formName[fieldName][i].checked) {
			return true;
		}
	}
	alert('Please categorize this ' + eObjectName + '\nلطفا طبقه بندی ' + pObjectName + ' را مشخص کنید');
	return false;
}
function forceEnglishInput() {
	FKeyPress();
var englishKeyArray = new Array(65 /*A*/, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 /*Z*/, 97 /*a*/, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,  121, 122 /*z*/, 45 /*-*/, 61 /*=*/, 91 /*[*/, 93 /*]*/, 92 /*\*/, 59 /*;*/, 39 /*'*/, 44 /*,*/, 46 /*.*/, 47 /*/*/, 95 /*_*/, 43 /*+*/, 123 /*{*/, 125 /*}*/, 124 /*|*/, 58 /*:*/, 34 /*"*/, 60 /*<*/, 62 /*>*/, 63 /*?*/);
var persianKeyArray = new Array(1614 /*A*/, 1573, 1688, 1616, 1613, 1617, 1618, 1570, 91, 1600, 171, 187, 1569, 1571, 93, 92, 1611, 1604, 1615, 1548, 44, 1572, 1612, 1610, 1563, 1577 /*Z*/, 1588 /*a*/, 1584, 1586, 1740, 1579, 1576, 1604, 1575, 1607, 1578, 1606, 1605, 1574, 1583, 1582, 1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589, 1591, 1594, 1592 /*z*/,  45, 61, 1580, 1670, 1662, 1705, 1711, 1608, 46, 47, 45, 61, 123, 125, 124, 58, 34, 60, 62, 1567);
	if(-1 != (index = getIndex(persianKeyArray, window.event.keyCode))) {
		window.event.keyCode = englishKeyArray[index];
	}
	return true;
}
function addEvent(obj, evType, fn, useCapture){
	if(obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if(obj.attachEvent) {
		return obj.attachEvent('on' + evType, fn);
	}
	alert('Handler could not be attached');
}
function removeEvent(obj, evType, fn, useCapture) {
	if(obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if(obj.detachEvent) {
		return obj.detachEvent('on' + evType, fn);
	}
	alert('Handler could not be removed');
} 			
function addEventHandlerToObject(objTypes, evtInfo, tagName, defaultEventHandlerFirst) {
	defaultEventHandlerFirst = undefined == defaultEventHandlerFirst ? false : defaultEventHandlerFirst;
	if(true === defaultEventHandlerFirst) {
		for(var theObjRef, allTags = document.getElementsByTagName('*'), i = 0; i < allTags.length; ++i) {
			if(getIndex(tagName, allTags[i].tagName.toLowerCase()) >= 0) {
				for(otc = 0; otc < objTypes.length; ++otc) {
					if(allTags[i].type == objTypes[otc]) {
						for(var evc = 0; evc < evtInfo.length; ++evc) {
							addEvent(allTags[i], evtInfo[evc][0], evtInfo[evc][1]);
						}
						break; //Skip other types
					}
				}
			}
		}
	} else {
		for(var theObjRef, allTags = document.getElementsByTagName('*'), i = 0; i < allTags.length; ++i) {
			if(getIndex(tagName, allTags[i].tagName.toLowerCase()) >= 0) {
				for(otc = 0; otc < objTypes.length; ++otc) {
					if(allTags[i].type == objTypes[otc]) {
						for(var evc = 0; evc < evtInfo.length; ++evc) {
							//eval('curEventHandler = allTags[' + i + '].on' + evtInfo[evc][0]);
							//eval('allTags[' + i + '].on' + evtInfo[evc][0] + ' = null');
							//addEvent(allTags[i], evtInfo[evc][0], curEventHandler);
							addEvent(allTags[i], evtInfo[evc][0], evtInfo[evc][1]);
						}
						break; //Skip other types
					}
				}
			}
		}
	}
	return true;
}
findNeedleInHaystack.numTimesDownArrowPressed = 0
function findNeedleInHaystack(searchTextRef, searchAreaId) {
var matchSpecs, moreSpecificMatch, thisRef, newA, jumpPointRef, searchBoxRef;
	if(matchSpecs = document.getElementById(searchAreaId).innerHTML.match(new RegExp('<a class=treeElements id=anchor[0-9]* [^\>]*>' + searchTextRef.value, 'gi'))) {
		if(40 == event.keyCode && findNeedleInHaystack.numTimesDownArrowPressed < matchSpecs.length - 1) {//DnArrow
			findNeedleInHaystack.numTimesDownArrowPressed++;
		} else if(38 == event.keyCode && findNeedleInHaystack.numTimesDownArrowPressed) {//UpArrow
			findNeedleInHaystack.numTimesDownArrowPressed--;
		}else if(8 == event.keyCode) {//BackSpace
			findNeedleInHaystack.numTimesDownArrowPressed = 0;
		}
		if(undefined == matchSpecs[findNeedleInHaystack.numTimesDownArrowPressed]) {
			return false;
		}
		moreSpecificMatch = matchSpecs[findNeedleInHaystack.numTimesDownArrowPressed].match(new RegExp('<a class=treeElements id=anchor([0-9]*) [^\>]*>' + searchTextRef.value, 'i'));
		if(undefined == moreSpecificMatch || undefined == moreSpecificMatch[1] || !(thisRef = document.getElementById('anchor' + moreSpecificMatch[1]))) {
			return false;
		}
		if(jumpPointRef = document.getElementById('jumphere')) { //Previous search
			if(jumpPointRef.parentElement) { //Restore color
				jumpPointRef.parentElement.style.color = '';
				jumpPointRef.parentElement.removeChild(jumpPointRef);
			}
		}
		thisRef.style.color = '#ff0000';
		for(var parentId = thisRef.parentElement; parentId;) {
			if('DIV' == parentId.tagName.toUpperCase() && 'none' == parentId.style.display) {
				flipWithSign(parentId.id);
				parentId.style.display = 'block';
			}
			parentId = parentId.parentElement;
		}
		newA = document.createElement('a');
		newA.id = 'jumphere';
  		thisRef.appendChild(newA);
  		searchTextRef.parentElement.parentElement.removeChild(searchTextRef.parentElement);
  		thisRef.appendChild(searchTextRef.parentElement);
  		location.href = '#jumphere';
  		searchTextRef.focus(); //Get focus to searchbox, position the cursor at the start
  		searchTextRef.value = searchTextRef.value; //position the cursor at the end
	}
	return false;
}
//Omid
function myToggle(senderId, id, commentId, flag) {
	if('undefined' == typeof(flag)) {
		 flag = false;
	} else if(true === flag) {
		document.getElementById(id).setAttribute('counted', null);
	}
	try {
	var elementStyle = document.getElementById(id).style;
	var div = document.getElementById('th'+commentId);
		if('none' == elementStyle.display || true === flag) {
			document.getElementById('xsenderId1').value = senderId;
			document.getElementById('xid1').value = id;
			document.getElementById('xcommentId1').value = commentId;
			document.getElementById(senderId).src = 'img/icons/minus_icon.gif';
			elementStyle.display = 'block';
			try {
				if(document.getElementById(id).getAttribute('counted') == null) {
					document.getElementById('forumId').value = div.getAttribute('fid');
					document.getElementById('commentId').value = commentId;
					document.getElementById('comments_parentId').value = div.getAttribute('comments_parentId');
					document.getElementById('topics_threshold').value = 0;
					document.getElementById('topics_offset').value = 0;
					document.getElementById('topics_sort_mode').value = 'commentDate_desc';
					document.getElementById('count').value = 'y';
					syncRequest('threads.php', new Array('forumId','commentId','comments_parentId', 'topics_threshold', 'topics_offset', 'topics_sort_mode', 'count'), 'th'+commentId, div.getAttribute('msg'), 'POST', flag);
					document.getElementById('hits'+commentId).innerText++;
					document.getElementById('a' + commentId).setAttribute('className', 'forumnameread');
					document.getElementById(id).setAttribute('counted', '1');
				}
			} catch(e) {
				alert(e.description);
			}
		} else {
			document.getElementById(senderId).src = 'img/icons/plus_icon.gif';
			elementStyle.display = 'none';
		}
	} catch(e) {
		alert(e.description);
	}
	return false;
}
//pourshahmir 84/5/19
function change_state(foo)
{
	element=document.getElementById(foo);
	if (getCookie(foo)=='o') {
			element.src = 'img/icons/plus_icon.gif';
		 	setCookie(foo, "c");
	}else{
			element.src = 'img/icons/minus_icon.gif';
			 setCookie(foo, "o");
	}
}
function set_ToggleComment(senderId,dixfaqQuestionId,faqQuestionId,target,q,parent) {
			if (getCookie(senderId) == "o" && (parent==0 || getCookie('img'+parent)=="o")){
							set_ToggleFaq(senderId,dixfaqQuestionId,faqQuestionId,target);
			}
			return true;
}
function set_ToggleFaq(senderId,dixfaqQuestionId,faqQuestionId,target) {
		if (getCookie(senderId) == "o"){
			change_state(senderId);
			ToggleFaq(senderId,dixfaqQuestionId,faqQuestionId,target);
		}
}
function ToggleFaq( senderId,dixfaqQuestionId,faqQuestionId,target) {
	try{
		change_state(senderId);
		var elementStyle = document.getElementById(dixfaqQuestionId).style;
		var frame = document.getElementById('threads'+faqQuestionId);
    	var src = target;
		if('none' == elementStyle.display) {
         	elementStyle.display = 'block';
            if (document.getElementById(dixfaqQuestionId).getAttribute('counted')== null) {
                frame.src= src;
                elementStyle.display = 'block';
                document.getElementById('th'+faqQuestionId).innerHTML = '<p align=center><font color=red size=4>' + document.getElementById('th'+faqQuestionId).getAttribute('msg') + '</font></p>';
                document.getElementById(dixfaqQuestionId).setAttribute('counted', '1');
            }
	} else {
      		elementStyle.display = 'none';
	}
  }catch(e){alert(e.description);}
	return false;
}
function setForm(id,idt,ids,threadId,parentId,$title,$answer)
	{
		var elementStyle=document.getElementById(idt).style;
		if('none' == elementStyle.display){
			id=id.replace(/test/i,'frm');
			temp=document.getElementById(ids).innerHTML;
			document.getElementById(idt).innerHTML=temp.replace(/frm_new_comment/i,id+" threadId="+threadId+" parentId="+parentId);
			if($title!=undefined){
					form=document.getElementById(id)
					form.elements['comments_title'].value=$title;
					if($answer!=undefined)
						form.elements['comments_data'].value=$answer;
					form.elements['edit'].value=1;
			}
		elementStyle.display = 'block';
		}else{
			document.getElementById(idt).innerHTML="";
			elementStyle.display = 'none';
		}
	}
function subForm(formId)
	{
		var form=document.getElementById(formId);
		form.target="_self";
		if(form.parentId!=undefined)
			form.elements['comments_parentId'].value=form.threadId;
		return true;
	}
function preViewForm(form)
	{
		form.target="_blank";
		form.submit();
		return true;
	}
//pourshahmir
function postThread(id, comments_offset, quote, comments_threadId, comments_parentId, comments_threshold, comments_sort_mode, topics_offset, topics_find, topics_sort_mode, topics_threshold, forumId, comments_postComment, check) {
var form = document.getElementById('oeditpageform');
      to = document.getElementById('u' + id).value;
      ano = document.getElementById('anonym').value;
      if (document.getElementById('userr').value != to && to != ano && check == 'y'){
        r = window.prompt(document.getElementById('oreason').value, '');
        form.user_message.value = r;
        form.to.value = to;
      }
    form.comments_offset.value = comments_offset;
    form.quote.value = quote;
    form.comments_threadId.value = comments_threadId;
    form.comments_parentId.value = comments_parentId;
    form.comments_threshold.value = comments_threshold;
    form.comments_sort_mode.value = comments_sort_mode;
    form.topics_offset.value = topics_offset;
    form.topics_find.value = topics_find;
    form.topics_sort_mode.value = topics_sort_mode;
    form.topics_threshold.value = topics_threshold;
    form.forumId.value = forumId;
    form.comments_postComment.value = comments_postComment;
    form.comments_title.value = document.getElementById('comments_title' + id).value.replace(/(\s+$)|(^\s+)/g, '');
    form.comments_data.value = document.getElementById('editpost' + id).value;
    var tId = comments_parentId == 0 ? comments_threadId : comments_parentId ;
    form.senderId1.value = 'img' + tId;
    form.commentId1.value = tId;
    form.id1.value = 'dix' + tId;
    form.forumId1.value = forumId;
    if(comments_parentId == 0){
			var ctt, cts;
			//var div = document.getElementById('mdiv' + comments_threadId).document.getElementById('TypeRow' + comments_threadId);
			if(ctt = document.getElementById('ctt' + comments_threadId)) {
				form.comment_topictype.value = ctt.item(ctt.selectedIndex).value;
			}
			if(cts = document.getElementById('cts' + comments_threadId)) {
				form.comment_topicsmiley.value = cts.item(cts.selectedIndex).value;
			}
		}
		//syncRequest(form.action,new Array('user_message', 'to', 'comments_offset', 'quote','comments_threadId', 'comments_parentId', 'comments_sort_mode', 'topics_offset', 'topics_find', 'topics_sort_mode', 'topics_sort_mode', 'topics_threshold', 'forumId', 'comments_postComment', 'comments_title', 'comments_data', 'senderId1', 'id1', 'commentId1', 'forumId1'), document.getElementById('mdiv' + id),'<p align=center><font color=red size=3>لطفا چند لحظه صبر کنید</font></p>',form.method.toUpperCase(),true);
    form.submit(form);
}
function handleResponse(hits) {
var iframe;
	if(iframe = document.getElementById('iFrameReply')){
		iframe.src = 'about:blank';
	}
}
function handleScorePost(id, score) {
	var iframe;
	if((iframe = document.getElementById('iFrameReply'))){
		iframe.src= 'about:blank';
    document.getElementById(id).innerHTML=score;
  }
}
function handleRemove(msg) {
	var iframe;
	if((iframe = document.getElementById('iFrameReply'))){
		iframe.src= 'about:blank';
    alert(msg);
    window.location=window.location;
  }
}
function handleMonitor(threadId,watch) {
var iframe;
	if(iframe = document.getElementById('iFrameReply')){
		iframe.src = 'about:blank';
    if('y' == watch){
      document.getElementById('wat'+threadId).src='img/icons/icon_unwatch.png';}
    else{
      document.getElementById('watc'+threadId).src='img/icons/icon_watch.png';}
	}
}
function sendServer(url){
  document.getElementById('iFrameReply').src=url;
}
function handlePostBack() {
var iframe;
	if(iframe = document.getElementById('iFrameReply')){
		iframe.src = 'about:blank';
	}
}
function handleReport(threadId) {
var iframe;
	if(iframe = document.getElementById('iFrameReply')){
		iframe.src = 'about:blank';
 	}
}
function doConfirm(msg , url, id, note, hasChild) {
  var r = '';
  var to = '';
 if(window.confirm(msg)) {
	  if(hasChild == 'y' )
	  	alert('چون این نامه دارای جواب است، فقط متن آن حذف می شود');
      to = document.getElementById('u' + id).value;
      ano = document.getElementById('anonym').value;
      if (document.getElementById('userr').value != to && to != ano){
      //if (document.getElementById('userr').value != document.getElementById('u' + id).value){
        r = window.prompt(note,'');//"please enter your reason for author", '');
        if(r == '' || r == null) r = document.getElementById('nr').innerText;
        to = document.getElementById('u' + id).value;
      }
      var form = document.getElementById('editpageform');
      if (document.getElementById('xsenderId1'))
          form.action = url + '&senderId_1=' + document.getElementById('xsenderId1').value + '&id_1=' + document.getElementById('xid1').value  + '&commentId_1=' + document.getElementById('xcommentId1').value + '&user_message=' + r + '&to=' + to;
      else
          form.action = url+'&daconfirm=confirm&stay=1'+ '&user_message=' + r + '&to=' + to;
      //window.status = 'Please Wait...';
      form.submit();
  }
}function setReason(msg){
  try{
			var form = document.getElementById('abcForm');
			var r = '';
			var selUsers = document.getElementById('selUsers');
  		var sel = document.getElementById('sel');
			var userr = document.getElementById('userr').value
      var ano = document.getElementById('anonym').value;
      var optUser;
      var ask = false;
			if(selUsers.length>0){
				for(var i=0; i<selUsers.length;i++){
						optUser = selUsers.item(i);
						if(userr != optUser.text && optUser.text != ano){
							ask = true;
							break;
						}
				}
				if(ask)
				r = window.prompt(msg,'');
				if(r == '' || r == null ) r = document.getElementById('nr').innerText;
				form.user_message.value = r;
				document.getElementById('batchMsg').style.display = 'block';
				form.submit();
			}else
				  return false;
  }catch(e){alert(e.description);}
}
function showX(id, tId) {
var element = document.getElementById(id);
	element.innerHTML = document.getElementById(tId).innerHTML;
	element.style.display = 'block';
}
function hideX(id) {
var mid = id.substring(4,id.length);
  document.getElementById('editpost' + mid).value = '';
  document.getElementById('comments_title' + mid).value = '';
	document.getElementById(id).innerHTML = '';
	document.getElementById(id).style.display = 'none';
}
function hideXX(id) {
	document.getElementById('dix' + id).style.display = 'none';
  document.getElementById('img' + id).src='img/icons/plus_icon.gif';
  return false;
}
function showMyDiv(ID, comments_offset, quote, comments_threadId, comments_parentId, comments_threshold, comments_sort_mode, topics_offset, topics_find, topics_sort_mode, topics_threshold, forumId, comments_title, comments_postComment) {
var div = document.getElementById('mdiv' + ID),
	htm = document.getElementById('nmdiv').innerHTML,
	s = '<input type="button" name="Topcomments_postComment" id="Topcomments_postComment" value="' + document.getElementById('btnCancel').value + '" onclick="hideX(\'mdiv' + ID + '\')" />';
	htm = htm.replace(/ORTESTX/g, s);
	htm = htm.replace(/editpost___/g, 'editpost' + ID);
	htm = htm.replace(/TREXD/g, '<input type="button" name="Top_postComment" id="ToppostComment" value="' + document.getElementById('btnPost').value + '" onclick="postThread(\'' + ID +'\', \'' + comments_offset + '\',\'' + quote + '\',\'' + comments_threadId + '\',\'' + comments_parentId + '\',\'' + comments_threshold + '\',\'' + comments_sort_mode + '\',\'' + topics_offset + '\',\'' + topics_find + '\',\'' + topics_sort_mode + '\',\'' + topics_threshold + '\',\'' + forumId + '\', \'' + comments_postComment + '\',\'n\')" />');
	htm = htm.replace(/COMMENT_TITLE_TEXTINPUT/, '<input type=\'text\' id=\'comments_title' + ID + '\' value=\'>' + comments_title.replace(/(\s+$)|(^\s+)/g, '') + '\' maxlength="100" />');
	htm = htm.replace(/PASSWORD_TEXTINPUT/, '<input type=\'password\' id=\'password' + ID + '\' />');
	htm = htm.replace(/COMMENTS_DATA_TEXTAREA/, '<textarea id=\'editpost' + ID + '\' class=\'daneshnamehedit\' name=\'comments_data' + ID + '\' rows=\'20\' cols=\'80\'></textarea>');
	htm = htm.replace(/XSD/g, 'onClick="showPreview(eval(\'comments_data' + ID + '.value\'), eval(\'comments_title' + ID + '.value\'), \'\', \'fastpreviewarea\', \'false\');"');
	div.innerHTML = htm;
	div.style.display = 'block';
	div.scrollIntoView();
}
function setOptionSelected(combo, value){
	for(var i = 0; i<combo.options.length; i++) combo.item(i).selected = combo.item(i).value == value ? 'selected': '';
}
function setCommentText() {
var frame = document.getElementById('frameContent');
	if (frame.src == 'about:blank') {
		return;
	}
var htm = frame.contentWindow.document.body.innerText;
	try{
	var s, ss, i, len;
		s = '';
		ss = htm.split("\\z");
		for (len = ss.length, i = 0; i < len; i++) {
			s  += ss[i].replace(/(\s+$)|(^\s+)/g, '') + '\n';
		}
		s = s.substring(0, s.length - 2);
		document.getElementById(document.getElementById('data').value).value = s;
    	tid = frame.getAttribute('tid');
    	if(ctt = frame.getAttribute('ctt')) {
    		setOptionSelected(document.getElementById('ctt' + tid), ctt);
    	}
    	if(cts = frame.getAttribute('cts')) {
			setOptionSelected(document.getElementById('cts' + tid), cts);
    	}
    	frame.src = 'about:blank';
    } catch(e){
    	alert(e.description);
    }
}
function showEdit(ID, comments_offset, quote, comments_threadId, comments_parentId, comments_threshold, comments_sort_mode, topics_offset, topics_find, topics_sort_mode, topics_threshold, forumId, comments_title, comments_postComment) {
var div = document.getElementById('mdiv' + ID);
var f = document.getElementById('frameContent');
	document.getElementById('data').value='editpost'+ ID;
	htm = document.getElementById('nmdiv').innerHTML;
	edit = document.getElementById('edit' + ID);
	s = '<input type="button" name="Topcomments_postComment" id="Topcomments_postComment" value="' + document.getElementById('btnCancel').value + '" onclick="hideX(\'mdiv' + ID + '\')" />';
	htm = htm.replace(/ORTESTX/g, s);
	htm = htm.replace(/editpost___/g, 'editpost' + ID);
	htm = htm.replace(/TREXD/g, '<input type="button" name="Top_postComment" id="ToppostComment" value="' + document.getElementById('btnPost').value + '" onclick="postThread(\'' + ID +'\', \'' + comments_offset + '\',\'' + quote + '\',\'' + ID + '\',\'' + comments_parentId + '\',\'' + comments_threshold + '\',\'' + comments_sort_mode + '\',\'' + topics_offset + '\',\'' + topics_find + '\',\'' + topics_sort_mode + '\',\'' + topics_threshold + '\',\'' + forumId + '\', \'' + comments_postComment + '\',\'y\')" />');
	htm = htm.replace(/COMMENT_TITLE_TEXTINPUT/, '<input type=\'text\' id=\'comments_title' + ID + '\' value=\'' + comments_title.replace(/(\s+$)|(^\s+)/g, '') + '\' maxlength="100" />');
	htm = htm.replace(/PASSWORD_TEXTINPUT/, '<input type=\'password\' id=\'password' + ID + '\' />');
	htm = htm.replace(/COMMENTS_DATA_TEXTAREA/, '<textarea id=\'editpost' + ID + '\' class=\'daneshnamehedit\' name=\'comments_data' + ID + '\' rows=\'20\' cols=\'80\'></textarea>');
	htm = htm.replace(/XSD/g, 'onClick="showPreview(eval(\'comments_data' + ID + '.value\'), eval(\'comments_title' + ID + '.value\'), \'\', \'fastpreviewarea\', \'false\');"');
	var style = comments_parentId == 0 ? 'style = "display:block"' : 'style = "display:none"';
	htm = htm.replace(/TypeRow/g, ' id = "TypeRow' + ID + '"' + style);
	htm = htm.replace(/COMMENT_TOPICTYPE_COMBO/g, 'name = "comment_topictype" id = "ctt' + ID + '"');
	htm = htm.replace(/COMMENT_TOPICSMILEY_COMBO/g, 'name = "comment_topicsmiley" id = "cts' + ID + '"');
	div.innerHTML = htm;
	div.style.display = 'block';
	div.scrollIntoView();
	f.setAttribute('ctt', edit.getAttribute('ctt'));
	f.setAttribute('cts', edit.getAttribute('cts'));
	f.setAttribute('tid', ID);
	f.src = 'mavara-view_forum.php?forumId=' + forumId + '&cid=' + ID;
}
function postScore(url){
  document.getElementById('iFrameReply').src=url;
}
function moveSelected(){
  	document.getElementById('forums').style.display='block';
  	return false;
}
function copySelected(){
  	document.getElementById('copytoforums').style.display='block';
  	return false;
}
function mergeTopics(){
  document.getElementById('topics').style.display='block';
  clean(document.getElementById('selTopic'));
  copy(document.getElementById('sel'),document.getElementById('selTopic'));
  return false;
}
function exemptTopics(){
  document.getElementById('topics').style.display='block';
  clean(document.getElementById('selTopic'));
  copy(document.getElementById('sel'),document.getElementById('selTopic'));
  return false;
}
function copyTo(){
  try{
			var form = document.getElementById('abcForm');
			document.getElementById('batchMsg').style.display = 'block';
			form.submit();
  }catch(e){alert(e.description);}
}
function addChecked(id, topic){
var sel=document.getElementById('sel');
var selUsers = document.getElementById('selUsers');
var user = document.getElementById('u' + id);
var opt;
var optUsers;
  try{
	  	if (document.getElementById('chk' + id).checked == true){
		  		opt=document.createElement('option');
		      opt.id='opt' + id;
		  		opt.innerText=topic;
		  		opt.setAttribute('value',id);
		  		sel.appendChild(opt);
					optUsers=document.createElement('option');
		      optUsers.id='optUsers' + id;
		  		optUsers.innerText=user.value;
		  		optUsers.setAttribute('value',id);
		  		selUsers.appendChild(optUsers);
	  	}
	    else{
        	sel.removeChild(document.getElementById('opt' + id));
        	selUsers.removeChild(document.getElementById('optUsers' + id));
	    }
  }catch(e){alert(e.description);}
}
function copy(src,trg){
var i=0;
var count=src.children.length;
var opt;
	clean(trg);
	for(i=0;i<count;i++){
		opt=document.createElement('option');
		opt.innerText=src.children[i].innerText;
    opt.value=src.children[i].value;
		trg.appendChild(opt);
	}
}
function clean(src){
var i=0;
var count=src.children.length;
var opt;
	for(i=src.children.length-1;i>=0;i--){
		src.removeChild(src.children[i]);
	}
}
function loadFrame(id){
    try{
          var htm = document.getElementById('threads' + id).contentWindow.document.body.innerHTML;
          document.getElementById('th' + id).innerHTML = htm;
          //window.location = window.location.toString();
      }
    catch(e){alert(e.description);}
}
//1384/08/02
function showNew(){
	document.getElementById('new_section').style.display = 'block';
}
function cancelNew(){
	document.getElementById('new_section').style.display = 'none';
	document.getElementById('order').value = '';
	document.getElementById('section').value = '';
}
function saveNew(){
	if(document.getElementById('edit').value == 'edit'){
		syncRequest('mavara-forum_sections.php', new Array('section','order', 'editSection'), 'sections', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	}
	else{
		syncRequest('mavara-forum_sections.php', new Array('section','order', 'save'), 'sections', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	}
	document.getElementById('new_section').style.display = 'none';
	document.getElementById('order').value = '';
	document.getElementById('section').value = '';
	document.getElementById('edit').value == ''
}
function removeSection(Id){
	cancelNew();
	document.getElementById('removeSection').value = Id;
	syncRequest('mavara-forum_sections.php', new Array('removeSection'), 'sections', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	document.getElementById('removeSection').value = '';
}
function editSection(Id){
	document.getElementById('editSection').value = Id;
	document.getElementById('section').value =document.getElementById('section_title' + Id).value;
	document.getElementById('order').value = document.getElementById('section_order' + Id).value;
	document.getElementById('new_section').style.display = 'block';
	document.getElementById('edit').value = 'edit';
}
//1384/08/02
//1384/08/07
function showNewComment(){
	document.getElementById('new_comment').style.display = 'block';
}
function cancelNewComment(){
	document.getElementById('new_comment').style.display = 'none';
	document.getElementById('comment').value = '';
}
function saveNewComment(){
	if(document.getElementById('edit').value == 'edit'){
		syncRequest('mavara-default_descriptions.php', new Array('comment', 'comment_type', 'editComment'), 'comments', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	}
	else{
		syncRequest('mavara-default_descriptions.php', new Array('comment', 'comment_type', 'save'), 'comments', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	}
	document.getElementById('new_comment').style.display = 'none';
	document.getElementById('comment').value = '';
	document.getElementById('edit').value == ''
}
function removeComment(Id){
	document.getElementById('removeComment').value = Id;
	syncRequest('mavara-default_descriptions.php', new Array('removeComment', 'comment_type' ), 'Comments', '<p align=center><font color=red size=4>لطفا چند لحظه صبر کنید</font></p>', 'POST', true);
	document.getElementById('removeComment').value = '';
}
function editComment(Id){
	document.getElementById('editComment').value = Id;
	document.getElementById('comment').value =document.getElementById('dc' + Id).value;
	document.getElementById('new_comment').style.display = 'block';
	document.getElementById('edit').value = 'edit';
}
//1384/08/07
function localsave( area ){
	area = ('undefined' == typeof(area)  )?'queue_list':area;
var win = window.open('', '_blank', 'top=10000');
var contents = document.getElementById(area).innerHTML;
	win.document.open('text/HTML', '_blank');
	win.document.charset = 'UTF-8';
	contents = '<div dir="rtl" >' + contents + '</div>';
	win.document.writeln(contents);
	win.document.execCommand('SaveAs', true, '.htm');
	win.close();
}
function showDateCondition(){
	var cmbDC = document.getElementById('datecond');
	cmbDC.item(cmbDC.selectedIndex).value == 'All' ? hideId('divDC'): showId('divDC');
}
function addDefaultComment(){
var data = document.getElementById('data');
var src = document.getElementById('default_comment');
		data.focus();
		var sel = document.selection.createRange();
		sel.text = src.item(src.selectedIndex).innerText;
}
//OMID
//POURSAHMIR 84/05/22  FAQ'S
function golink(node,url) {
	var frame=document.getElementById('threads'+node);
	frame.src=url;
	return true;
}
function remove_comment(node,url) {
	var frame=document.getElementById('threads'+node);
    var ok=confirm('do you want remove this comment!');
    if(ok)
  		frame.src=url;
	return true;
}
function addCheckedMessage(f){
	var messages = document.getElementById('messages');
	for (i=0;i<messages.elements.length;i++){
		if(messages.elements[i].type == 'checkbox' && messages.elements[i].checked == true){
			chk=document.createElement('INPUT');
			chk.type = 'CHECKBOX';
			chk.name = 'selmsg[]';
			chk.style.display = 'none';
	    chk.checked = messages.elements[i].checked;
			f.appendChild(chk);
		}
	}
	for (i=0;i<f.elements.length;i++){
		if(f.elements[i].type == 'checkbox')
	    f.elements[i].checked = true;
	}
	var win = window.open('about:blank','download','left=20,top=20,width=300,height=70,toolbar=0,resizable=0,menubar=0');
	var form = '<form action = "messu-mailbox_backup.php" method = "POST" id = "f" >';
	var x = f.innerHTML;
	form = form + x;
	form  = form + '</form>';
	var st = '<html><head><title>Test</title><head>';
	st  = st + '<script language = "javascript" FOR="window" EVENT="onload()">';
	st  = st + 'document.getElementById("f").submit;';
	st = st + '</script></hrad><body>' + form + '</body>';
	win.document.write(st);
	//f.submit;
}
function fillDates(){
		fday = document.getElementById('fday');
		fmonth = document.getElementById('fmonth');
		fyear = document.getElementById('fyear');
		tday = document.getElementById('tday');
		tmonth = document.getElementById('tmonth');
		tyear = document.getElementById('tyear');
		var i;
		for(i = 1; i<32; i++){
  		opt = document.createElement('option');
      opt.id = 'fday' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		fday.appendChild(opt);
  		opt = document.createElement('option');
      opt.id = 'tday' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		tday.appendChild(opt);
		}
		for(i = 1; i<13; i++){
  		opt = document.createElement('option');
      opt.id = 'fmonth' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		fmonth.appendChild(opt);
  		opt = document.createElement('option');
      opt.id = 'tmonth' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		tmonth.appendChild(opt);
		}
		for(i = 1382; i<1982; i++){
  		opt = document.createElement('option');
      opt.id = 'fyear' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		fyear.appendChild(opt);
  		opt = document.createElement('option');
      opt.id = 'tyear' + i;
  		opt.innerText = i;
  		opt.setAttribute('value', i);
  		tyear.appendChild(opt);
		}
}
function toggleDiv(divId){
	var div = document.getElementById(divId);
	try{
		if(div.getAttribute('first') == 'y'){
				fillDates();
				div.setAttribute('first', 'n');
		}
	}catch(e){};
	div.style.display = div.style.display == 'block' ? 'none' : 'block';
}
var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
		}
		return output;
	},
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = Base64._utf8_decode(output);
		return output;
	},
	// private method for UTF-8 encoding
	_utf8_encode : function (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 utftext;
	},
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
function afterNewItemAction(response, displayAreaId, resultAreaId) {
var json_data_object, resultAreaRef = document.getElementById(resultAreaId), displayAreaRef = document.getElementById(displayAreaId);
	try {
		json_data_object = eval('(' + response + ')');
		displayAreaRef.innerHTML = '';
		if(json_data_object['id'] > 0) {
			opt = document.createElement('option');
			opt.innerText = json_data_object['value'];
			opt.setAttribute('value', json_data_object['id']);
			resultAreaRef.insertBefore(opt, resultAreaRef.firstChild);
		} else {
			alert(json_data_object['value']);
		}
		resultAreaRef.selectedIndex = 0;
	} catch(e) {
		alert('Error occured in method `afterNewItemAction` ' + e.description);
	}
}
function checkForNewItem(dynamicFormIdStr, selectElement, newFieldsInfo, displayAreaId) {
var formRef, submitForm, displayAreaRef;
	try {
		displayAreaRef = document.getElementById(displayAreaId);
		if('NewElement' == selectElement.value) {
			if(displayAreaRef) {
				if(formRef = document.getElementById(dynamicFormIdStr)) {
					displayAreaRef.removeChild(formRef);
				}
				document.body.appendChild(submitForm = document.createElement('FORM'));
				submitForm.method = 'POST';
				submitForm.id = dynamicFormIdStr;
				submitForm.attachEvent('onsubmit',
					function() {
						hide(displayAreaId);
						for(var tempVal, elemRef, inputElementsIds = new Array('dbObjAliasAreaId'), i = 0; i < newFieldsInfo.fieldsInfo.length; ++i) {
							if(undefined != newFieldsInfo.fieldsInfo[i].fieldId) {
								inputElementsIds.push(newFieldsInfo.fieldsInfo[i].fieldId);
								if(elemRef = document.getElementById(newFieldsInfo.fieldsInfo[i].fieldId)) {
									tempVal = '';
									if(undefined != newFieldsInfo.fieldsInfo[i].isMandatory && true === newFieldsInfo.fieldsInfo[i].isMandatory) {
										tempVal += '/isMandatory'
									}
									if(undefined != newFieldsInfo.fieldsInfo[i].isUnique && true === newFieldsInfo.fieldsInfo[i].isUnique) {
										tempVal += '/isUnique'
									}
									if('' != tempVal) {
										elemRef.value = Base64.encode(elemRef.value) + '/' + Base64.encode(newFieldsInfo.fieldsInfo[i].fieldPrompt) + tempVal;
									}
								}
							}
						}
						ajaxSyncRequest(newFieldsInfo.serverSide, inputElementsIds, null, '', 'POST', false, 'afterNewItemAction(http.responseText, "' + displayAreaId + '", "' + selectElement.id + '");');
						return false;
					}
				);
				submitForm.appendChild(document.createElement('<input type="hidden" name="dbObjAlias" id="dbObjAliasAreaId" value="' + newFieldsInfo.dbObjAlias + '" />'));
				submitForm.appendChild(document.createTextNode('   '));
				for(var selObjRef, i = 0; i < newFieldsInfo.fieldsInfo.length; ++i) {
					submitForm.appendChild(document.createTextNode(newFieldsInfo.fieldsInfo[i].fieldPrompt));
					switch(newFieldsInfo.fieldsInfo[i].fieldType.toLowerCase()) {
						case 'text':
							submitForm.appendChild(document.createElement('<input type="' + newFieldsInfo.fieldsInfo[i].fieldType + '" name="' + newFieldsInfo.fieldsInfo[i].fieldName + '" id="' + newFieldsInfo.fieldsInfo[i].fieldId + '" value="' + newFieldsInfo.fieldsInfo[i].fieldDefaultValue + '" />'));
							break;
						case 'select':
							selObjRef = document.createElement('SELECT');
							selObjRef.id = newFieldsInfo.fieldsInfo[i].fieldId;
							selObjRef.name = newFieldsInfo.fieldsInfo[i].fieldName;
							for(var j = 0; j < newFieldsInfo.fieldsInfo[i].optionsList.length; ++j) {
								theOption = document.createElement('OPTION');
								theOption.innerText = newFieldsInfo.fieldsInfo[i].optionsList[j].optionPrompt;
								theOption.setAttribute('value', newFieldsInfo.fieldsInfo[i].optionsList[j].optionValue);
								selObjRef.appendChild(theOption);
							}
							submitForm.appendChild(selObjRef);
							break;
					}
				}
				submitForm.appendChild(document.createTextNode('   '));
				submitForm.appendChild(document.createElement('<input type="submit" value="' + newFieldsInfo.submitButtonTitle + '">'));
				submitForm.appendChild(document.createTextNode('   '));
				displayAreaRef.appendChild(submitForm);
			}
		} else {
			if(formRef = document.getElementById(dynamicFormIdStr)) {
				displayAreaRef.removeChild(formRef);
			}
		}
		displayAreaRef.style.display = 'inline';
	} catch(e) {
		alert('Error occured in method `checkForNewItem` ' + e.description);
	}
	return true;
}
function objFields(obj, message) {
	if(!message) { 
		message = obj; 
	}
	var details = '_________' + '\n' + message + '\n';
	var fieldContents;
	for(var field in obj) {
		fieldContents = obj[field];
		if('function' == typeof(fieldContents)) {
			fieldContents = '(function)';
		}
		details += '  ' + field + ': ' + fieldContents + '\n';
	}
	document.write(details);
}
function progressbarColor(percent) {
var intVal = parseInt(percent);
	if(intVal <= 30) {
		return 'c0ffc0';
	} else if(intVal > 30 && intVal <= 60) {
		return 'a0ffa0';
	} else {
		return '#00ff00';
	}
}
function biasFileSize(fSize) {
var giga = (mega = (kilo = 1 << 10) << 10) << 10;
	if(fSize < kilo) {
		return fSize + 'B';
	} else if(fSize < mega && fSize > kilo) {
		return (fSize / kilo).toFixed(2) + 'KB';
	} else if(fSize < giga && fSize > mega) {
		return (fSize / mega).toFixed(2) + 'MB';
	} else {
		return (fSize / giga).toFixed(2) + 'GB';
	}
}
function goToBookmark(bookmark) {
	try {
		self.location = bookmark;
	} catch(e) {
		alert('Error in `goToBookmark`: ' + e.description)
	}
}
function isUserLoggedOn(confMsg) {
var userIsLoggedOn = false;
	$.ajax({
		type: 'POST',
		async: false,
		dataType: 'json',
		url: 'mavara_user_is_logged_on.php',
		success: function(httpResponse, status) {
			if(false === (userIsLoggedOn = httpResponse.userIsLoggedOn)) {
				userIsLoggedOn = window.confirm(confMsg);
			}
		}
	});
	return userIsLoggedOn;
}
//end
addEventHandlerToObject(new Array('password'), new Array(new Array('keypress', forceEnglishInput)), new Array('input', 'textarea'));
addEventHandlerToObject(new Array('text', 'textarea'), new Array(new Array('keypress', FKeyPress), new Array('keydown', FKeyDown), new Array('select', storeCaret), new Array('beforepaste', pasteCharConvert)), new Array('input', 'textarea'));