var lang = 0; // 1: Farsi, 0: English

var farsikey = [
   0x0020, 0x0021, 0x0022, 0x066B, 0x00A4, 0x066A, 0x060C, 0x06AF,
   0x0029, 0x0028, 0x002A, 0x002B, 0x0648, 0x002D, 0x002E, 0x002F,
   0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
   0x0038, 0x0039, 0x003A, 0x06A9, 0x003E, 0x003D, 0x003C, 0x061F,
   0x066C, 0x0624, 0x200C, 0x0698, 0x0649, 0x064D, 0x0625, 0x0623,
   0x0622, 0x0651, 0x0629, 0x00BB, 0x00AB, 0x0626, 0x004E, 0x005D,
   0x005B, 0x0652, 0x064B, 0x0621, 0x060C, 0x064E, 0x0056, 0x064C,
   0x0058, 0x0650, 0x061B, 0x062C, 0x005C, 0x0686, 0x00D7, 0x0640,
   0x200D, 0x0634, 0x0630, 0x0632, 0x06CC, 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 browserCheck() {
var agt = navigator.userAgent.toLowerCase(), 
	is_major = parseInt(navigator.appVersion), 
	is_minor = parseFloat(navigator.appVersion), 
	is_ie = -1 != agt.indexOf('msie') && -1 == agt.indexOf('opera'), 
	is_ie3 = is_ie && is_major < 4, 
	is_ie4 = is_ie && 4 == is_major && -1 != agt.indexOf('msie 4'), 
	is_ie4up = is_ie && is_major >= 4, 
	is_ie5 = is_ie && 4 == is_major && -1 != agt.indexOf('msie 5.0'), 
	is_ie5_5 = is_ie && 4 == is_major && -1 != agt.indexOf('msie 5.5'), 
	is_ie5up = is_ie && !is_ie3 && !is_ie4, 
	is_ie5_5up = is_ie && !is_ie3 && !is_ie4 && !is_ie5, 
	is_ie6 = is_ie && 4 == is_major && -1 != agt.indexOf('msie 6.'), 
	is_ie6up = is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5;
	return is_ie6up;
}

function uploadPicInDaneshnameh(num, pageName) {
	window.showModalDialog('mavara-daneshnameh_upload.php?page=' + pageName, window, 'dialogWidth:700px;dialogHeight:700px');
	return false;
}
 //pourshahmir 84/6/29  add search to daneshnameh_upload
function add_url(field){
	url = window.prompt('آدرس پیوند  را کادر زیر وارد نمایید .','http://');
	if(url != null)
	{
		field.value+="<a href="+url+" target=_blank>";
		label = window.prompt('عنوان پیوند را در کادر زیر وارد نمایید .','');		
		if(label != null)
			field.value +=label+"</a>";
		else
			field.value +=url+"</a>";			
	}	
		
	return;
}	
function loadiFrame(id){
    try{
    	  if(document.getElementById(id).src != "about:blank"){
          		var htm = document.getElementById(id).contentWindow.document.body.innerHTML;
          		document.getElementById('div_' + id).innerHTML = htm;
          		document.getElementById(id).contentWindow.document.body.innerHTML = '';
          		document.getElementById(id).src="about:blank";
          }
      }
    catch(e){alert(e.description);}
    return;
}
function AJAXForm(form,area,messageIdle){
	ids = new Array();
	for(var i=0;i<form.elements.length;i++){
		switch(form.elements[i].type){
			case 'checkbox':
			case 'radio' :
					if(form.elements[i].checked && form.elements[i].id)
						ids[ids.length] = form.elements[i].id;			
					break;	
			default :
					if(form.elements[i].id)			
						ids[ids.length] = form.elements[i].id;			
		}	
	}	
	syncRequest(form.action,ids,area,messageIdle,form.method.toUpperCase(),true);	
	return false;
}	
function setPic(form,value,imageName,wait_name,is_exist,imgName){
		form.elements['localExist_'+imageName].value =1;
			document.getElementById(wait_name).value =0;
			document.getElementById(is_exist).value  =0;			
		if(/\.swf/.exec(value)==null){
			document.images[imageName].src     = value;
			document.getElementById(wait_name).value =1;
			document.getElementById(is_exist).value  =1;			
			document.getElementById(imgName).value   = value ;		
			return true;
		}
		return false;
}
function showId(id){
	var elementStyle = document.getElementById(id).style.display='block';
}	
function hideId(id){
	var elementStyle = document.getElementById(id).style.display='none';
}	
function finalizeDescripImage(idx){
		document.getElementById('box_befor_upload'+idx).style.display='block';
		document.getElementById('box_after_upload'+idx).style.display='none';	 
	return false;
}	
function imageGalley(form,chk,path,name,use_filename,description,picfile,galleryId){
		if(chk.checked==true){
			name.disabled=true;
			use_filename.disabled=true;
			description.disabled=true;
			picfile.disabled=true;												
			galleryId.disabled=true;	
			searchWindowGallery(form.name,path.name);			
		}					
		if(chk.checked==false){
			name.disabled=false;
			use_filename.disabled=false;
			description.disabled=false;
			picfile.disabled=false;												
			galleryId.disabled=false;																
		}					
}	
function setImgUpType(form,otherName,id,image,value){
	hideId(otherName);
	form.elements['use_'+otherName].checked=false;
	form.elements['localExist_'+image].value=1;
	change_state_show(id);
	document.images[image].src = value;
}	
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){
	var elementStyle = document.getElementById(id).style;	
	elementStyle.display = ('none' == elementStyle.display) ? 'block':'none';
}	

//
//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;	
			}
//			document.getElementById(file_id).value= unicodeURLEncode(file);
			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);
}

/*=============== Start: Javascript Preview ===============================*/
	function unicode2TwoSingleBytes(unicodeChar) {
	var	i;
	var 	persianChars = new Array(		
		'ا', 'ب', 'پ', 'ت', 'ث', 'ج', 'چ', 'ح', 
		'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش', 
		'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 
		'ک', 'گ', 'ل', 'م', 'ن', 'و', 'ه', 'ی', 
		'ء', '،', '؛', 'ٍ', 'ً', 'ٌ', 'ٍ', 'َ', 
		'ُ', 'ِ', 'ّ', 'ْ', 'آ', '«', '»', '؟', 
		'ء', 'أ', 'إ', 'ؤ', 'ي', 'ة', '×', 'ئ',
		'+','&');
	var 	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',
		'%2B','%26');
		if(-1 != (index = getIndex(persianChars, unicodeChar))) {
			return persianCharsURLEncoded[index];
		}
		return escape(unicodeChar);
	}
	
	function unicodeURLEncode(str) {
		if('undefined' == typeof(str) ) return str;
		var	i, s;
		x=false
		for(i = 0, s = ''; i < str.length; ++i) {
			t =  unicode2TwoSingleBytes(str.charAt(i));
			s += '%u200C' == t ? '%0C%20':t;
		}
		return s;
	}
	function strip(str) {
		if('undefined' == typeof(str) ) return str;
		var	i, s;
		var unacceptable =['&','+'];
		var acceptable =['%26','%2B'];		
		for(i = 0, s = ''; i < str.length; ++i) {
			t = str.charAt(i);
			if(-1 != (index = getIndex(unacceptable, t))) 			
					t =  acceptable[index];
			s +=t;
		}
		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+$)|(^\s+)/g, '');
		//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 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 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 = data.replace(/\{[t]?picture\s*([^\}]+)\}/g, function makeImageLink(whole, firstMatch) {for(var i = 0, imgTag = '<img', params = firstMatch.split(' '); i < params.length; ++i) {params[i] = params[i].replace(/^\=/, '');params[i] = params[i].replace(/\/+/,'/',params[i].replace(/.*\/([^\/]*)/,'${1}'));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 'file':imgTag += ' src="' + sides[1] + '"';break;default:imgTag += ' ' + sides[0] + '="' + sides[1] + '"';break;}}return imgTag + '>';});
		// 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:$1;">$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 showPreview(data, id, allowHTML) {
		try{
				if(!document.getElementById(id)) {
					alert('Fast Preview area not defined!');
					return false;
				}
				if(false === allowHTML) {
					data = data.replace(/>/g, '&gt;').replace(/</g, '&lt;');
				}
				document.getElementById(id).innerHTML = '<div class="daneshnamehtext"><center><b><small>توجه: ممکن است بعضی از دستورات ماورا در نمایش سریع عمل نکنند. برای مشاهده آن ها از `پیش نمایش` استفاده کنید!</small></b></center><br><h2>پیش نمایش سریع: </h2>\n<br><br>\n' + parse_data(data) + '</div>';
				document.location.href += (-1 == document.location.href.indexOf('#') ? '#' : ''); // Go top if necessary!
		}catch(e){alert(e.description)}			
	}
/*=============== End: Javascript Preview ===============================*/
function saveDoc(contents) {
var win = window.open('', '_blank', 'top=10000');
	win.document.open('text/plain', '_blank');
	win.document.charset = 'UTF-8';
	win.document.writeln(contents);
	win.document.execCommand('SaveAs', false, '.txt')
	win.close();
}

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 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 getIndex(theArray, theValue) {
	for(var i = 0; i < theArray.length; ++i)
		if(theValue == theArray[i])
			return i;
	return -1;
}

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() {
var key = window.event.keyCode;
	correctLangValue(key);
	if(lang == 0 || key == 13) {
		return true; 
	}
	key = uniformCharCodes(key);
	if(key > farsikey.length + 0x0020) {
		if(-1 == (index = getIndex(farsikey, key))) {
			return true;
		}
		key = index + 0x0020;
	}
	window.event.keyCode = 0x0020 == key && window.event.shiftKey ? 0x200C : farsikey[key - 0x0020];
	window.event.keyCode = farsikey[key - 0x0020] == 92 ? 0x0698 : (farsikey[key - 0x0020] == 8205 ? 0x067E : window.event.keyCode);
	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 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 addEventHandlerToObject(objTypes, evtInfo) {
	for(var formCnt = 0; formCnt < document.forms.length; ++formCnt) {
	var docFormElements = document.forms[formCnt];
		for(var ec = 0; ec < docFormElements.elements.length; ++ec) {
			for(otc = 0; otc < objTypes.length; ++otc) {
				if(docFormElements.elements[ec].type == objTypes[otc]) {
					for(var evc = 0; evc < evtInfo.length; ++evc) {
						eval('docFormElements.elements[' + ec + '].' + evtInfo[evc][0] + ' = ' + evtInfo[evc][1]);
					}
					break; // Skip other types
				}
			}
		}
	}
	return true;
}

//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';
}
function session_refresh(first){
//	alert(typeof(first));
//	setcookie('last_refresh', time(), time()+3600);
//	last_refresh = getCookie('last_refresh');
//	sameAsBigDay = new Date();
//	alert(sameAsBigDay.getTime());
//	setTimeout("session_refresh()",5000);
//	syncRequest('session_refresh.php',new Array(),'','',POST,true);	
}	

//end
addEventHandlerToObject(new Array('password'), new Array(new Array('onkeypress', forceEnglishInput)));
addEventHandlerToObject(new Array('text', 'textarea'), new Array(new Array('onkeypress', FKeyPress), new Array('onkeydown', FKeyDown), new Array('onkeyup', storeCaret), new Array('onclick', storeCaret), new Array('onselect', storeCaret), new Array('onbeforepaste', pasteCharConvert)));

