// JavaScript Document

var loading = new Array();
var section = document.location.href.replace(/^.*(&|\?)section=([^&]*).*$/g, '$2');
var module  = document.location.href.replace(/^.*(&|\?)module=([^&]*).*$/g, '$2');

window.addEvent('load', function(){
	try {
		loading.forEach(eval);
	} catch (e) {}	
});

listLatEdited = 1;
function nifty(name, option)
{
	var divlist = $$(name);	
	var div = new Array();
	
	option = option ? option : {};
	option.n = option.n ? option.n : 9;

	for(var i=0; i<divlist.length; i++){
		var main = divlist[i];
		if(main.niftilized) continue;
		main.niftilized = true;
		var niftyClass = name.replace(/^[^\.]*\.(.+)$/i, '$1');
		
		for (var j=0; j<option.n; j++) {
			div[j] = new Element('div');
			if(j){
				div[j].addClass('div'+j);
				div[j-1].adopt(div[j]);
			} else {
				div[0].addClass(niftyClass);
			}
		}
		
		main.replaceWith(div[0]);
		div[option.n-1].adopt(main);
		main.removeClass(niftyClass);
		div[0].setStyles(
			{
				width:main.getSize().size.x+'px',
				height:main.getSize().size.y+'px'
			});
		
		if(!option.fixStyle) {
			main.setStyle('border', '0');
		}
	}
}

function msg(m)
{
	if(m = Json.evaluate(m)) {
		m.each( function(el) {
			if(el.text) alert(el.text);
		});	
	}
}

// new ajax(url, {update:myObj}).request();
var ajax = Ajax.extend({
		xAjaxOptions: function(){
		return {										//change this values on site change
			loading: '/images/loading.gif',
			onError: function(tr){alert('Error in Ajax')},
			retry: 1,
			method: 'get',
			evalScripts: true,
			
			update: null,
			Tupdate: null,
			retryCount: 0
		};
	},

	initialize: function(url, options){
		this.addEvent('onFailure', this.onError);
		this.setOptions(this.xAjaxOptions(), options);
		this.parent(url, this.options);
	},

	onError: function(){
		if(this.retryCount>0) {
			this.request.delay(20, this, [true]);	
		} else {
			if(this.options.loading && $(this.options.update)) {
				$(this.options.update).replaceWith(this.Tupdate);
			}
			this.fireEvent('onError', [this.transport], 20);
		}
	},
	
	request: function(retry){
		if(!retry && this.url && this.options.loading && $(this.options.update)){
			this.Tupdate = $(this.options.update).clone();
			$(this.options.update).setHTML('');
			if(this.options.loading.test(/\.gif|png|jpg|jpeg$/i)) {
				var img = new Element('img');
				img.setProperty('id', 'loadingimg');
				img.setProperty('src', this.options.loading);
				$(this.options.update).adopt(img);
			} else {
				$(this.options.update).appendText(this.options.loading);
			}
		}
		this.retryCount = retry ? this.retryCount-1 : this.options.retry;
		var data = null;
		switch ($type(this.options.postBody)){
			case 'element': data = $(this.options.postBody).toQueryString(); break;
			case 'object': data = Object.toQueryString(this.options.postBody); break;
			case 'string': data = this.options.postBody;
		}
		if (this._method) data = (data) ? [this._method, data].join('&') : this._method;
		var url = this.url+(this.url.test(/^.+\?.+/) ? '&' : '?')+'_r_='+$random(1, 1000000);
		return this.send(url, data);
	}
});

function cover(obj, parent, id)
{
	if (Window.ie && !Window.ie7)
	{
		var style = {
						position: 'absolute',
						height: $(obj).getSize().size.y+'px',
						width: $(obj).getSize().size.x+'px',
						top: $(obj).getTop()+'px',
						left: $(obj).getLeft()+'px'
					 };
		var ziropos = {border:0, margin:0, padding:0, top:0, left:0, bakground:'transparent'};			
					 
		var div = new Element('div');
		div.setStyles(style);
		
		var iframe = new Element('iframe');
		iframe.setProperties({
								src: "javascript:false;",
								frameBorder: "0",
								scrolling: "no"
							 	});
		
		$(obj).setStyles(ziropos);
		div.injectInside(parent ? $(parent) : document.body);
		iframe.setStyles(style);
		iframe.setStyles(ziropos);		
		iframe.setStyle('z-index', '-1');
		iframe.injectInside(div);
		$(obj).injectInside(div);	
		if($(id)) $(id).id = '';
		div.id = id;
		
		return div;
	} 	
	return $(obj);
}

function setSub(parent, child, first, selected)
{										// any lang of parent options must set to somthing like this: <option lang="2=CD||5=DVD" ...
										// SELECT xgroup1id, xgroup1, GROUP_CONCAT( CONCAT(xgroup2id, '=', xgroup2) ORDER BY xgroup2 SEPARATOR '||' ) AS xgroup2 FROM xxgroup2 NATURAL LEFT JOIN xxgroup1 GROUP BY xgroup1id ORDER BY xgroup1
	parent = $(parent);
	child = $(child);
	if(!parent || !child) return;
	first = parseInt(first);
	var sel = parent.selectedIndex != -1 ? parent.options[parent.selectedIndex] : null;
	if(!sel) return;
	
	while(child.options[first]) {
		child.options[first] = null;							  	
	}
	if(sel.lang) {
		sel.lang.split('||').each(function(el){
										 	el = el.split('=', 2);
										   	child.options[first ? first : child.options.length] = new Option(el[1], el[0]);
											first = 0;
										   });	
	}
	if(selected) child.value = selected;
}

function validateForm(frm)
{
	validateInput = function(frm, data, format)
	{
		format = format.split('#');
		for(var i=0; i<format.length; i++){
			var fmt = format[i];
			if(fmt.charAt(0) == '/'){
				//alert('testing: '+fmt+' on '+data);
				fmt=eval(fmt);
				if(!fmt.test(data))
					return false;
			} else {
				fmt = fmt.split('_');
				fmt[1] = fmt[1].test(/^-?[\d]+$/g) ? fmt[1] : document.getElementsByName(fmt[1])[0].value;
				//alert('checking: '+data+' '+fmt[0]+' '+fmt[1]);
				switch(fmt[0]){
					case 'eq': if(data==fmt[1]) continue; else return false;
					case 'ne': if(data!=fmt[1]) continue; else return false;
					case 'gr': if(data >fmt[1]) continue; else return false;
					case 'ge': if(data>=fmt[1]) continue; else return false;
					case 'lr': if(data< fmt[1]) continue; else return false;
					case 'le': if(data>=fmt[1]) continue; else return false;
				};
				alert('Syntax Error.');
			}
		}
		return true;
	};
	
	var list = $$('#'+frm+' INPUT, #'+frm+' SELECT, #'+frm+' TEXTAREA, #'+frm+' CHECKBOX');
	for(var i=0; i<list.length; i++){
		var el = list[i];
		if(el.lang){
			if(!validateInput(frm, el.value, el.lang)) {
				el.focus();
				el.alt = el.alt ? el.alt : el.title;
				alert(el.alt ? el.alt : 'Please enter correct data.');
				return false;
			}
		}	
	};
}

function saveForm(frm, loc, duration)
{
	Cookie.set(loc, $(frm).toQueryString(), {duration: duration});
}

function loadForm(frm, loc)
{
	frm = $(frm);
	var savedVal = Cookie.get(loc) ? '&'+Cookie.get(loc)+'&' : '';
	if(frmid = frm.id){
		var list = $$('#'+frmid+' INPUT, #'+frmid+' SELECT, #'+frmid+' TEXTAREA');
		for(var i=0; i<list.length; i++){
			var ch = list[i];
			if(ch.type && ch.type.test(/button|submit|reset|file|image|hidden/ig) || !ch.name) continue;
			//alert(ch.type+ch.type.test(/password|button|submit|reset|file|image|hidden/ig));
			var reg = new RegExp('^.*&'+encodeURIComponent(ch.name)+'=([^&]*)&.*$');
			var val = decodeURIComponent(savedVal.replace(reg, '$1'));
			val = val.charAt(0)=='&' ? '' : val;
			//alert(reg + '\n' + val);
			if(val){
				if(ch.type && (ch.type=='checkbox' || ch.type=='radio')){
					ch.checked = (ch.value == val);
				} else {
					ch.value = val;
				}
			}
		}
	}
}

function checkBoxes(fmobj)
{
	for(var i = 0; i < fmobj.elements.length; i ++)
	{

		var e = fmobj.elements[i];
		if((e.type == 'checkbox') && (e.type == 'checkbox') && (e.checked == true))
		{
			return true;
		}
	}	
}

function checkAll(fmobj)
{
	for(var i = 0; i < fmobj.elements.length; i ++)
	{
		var e = fmobj.elements[i];
		if((e.name != 'allbox') && (e.type == 'checkbox') && (!e.disabled))
		{
			e.checked = fmobj.allbox.checked;
		}
	}
}

function checkCheckedAll(fmobj)
{	
	var TotalBoxes = 0;
	var TotalOn = 0;
	for(var i = 0; i < fmobj.elements.length; i ++)
	{
		var e = fmobj.elements[i];
		if((e.name != 'allbox') && (e.type == 'checkbox'))
		{
			TotalBoxes ++;
			if(e.checked)
			{
				TotalOn ++;
			}
		}
	}
	
	if (TotalBoxes == TotalOn)
	{
		fmobj.allbox.checked = true;
		return -1;		// all of them checked
	}
	else
	{
		fmobj.allbox.checked = false;
		return TotalOn;	// none of them checked=0 else some of them checked
	}
}

//------------ mail module ---------
function saveMail(id)
{
	$('cmd').value = 'save';
	if(id){		
		$('id').value = id;
	}
	$('form1').submit();
}

function sendMail(type)
{
	$('cmd').value = 'send';
	if(type){		
		$('type').value = type;
	}
	$('form1').submit();	
}
//------------/mail module ---------

function ajaxDelete(action, objName, sender)
{
	new ajax(action).request();
	if(objName && sender) {
		while(sender = sender.parentNode){
			if(sender.className == objName || sender.id == objName || sender.name == objName){
				sender.style.display = 'none';
				if(sender.tagName=="TR") {
					sender.parentNode.deleteRow(sender.sectionRowIndex);
				}
				return true;
			}
		}
	}
	return false;
}

function trace(val, obj)
{
	if(obj) {
		var res = [];
		res.push(val);
		var el;
		for (el in val) {
			res.push(el+' = '+val[el]);
		}
		res = res.join('<br>\n');
	} else {
		res = val;
	}
//	alert(val);
	var div = new Element('div');
	div.innerHTML = res;
	div.injectInside(document.body);
}

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 ? 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;
    }

}

Object.toQueryString = function(source){
	var queryString = [];
	for (var property in source) if(source[property]!='') queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property]));
	return queryString.join('&');
};

function addStandardClass(parent)
{
	parent = parent ? parent+' ' : '';
	var list = $$(parent+'input');
	for(var i=0; i<list.length; i++) {
		var input = list[i];
		var type = input.getProperty('type') ? input.getProperty('type') : 'text';
		input.addClass('input_'+type);	
	}
}

function goto(idx, force)
{
	var cur = parseInt($('offset').value);
	var last = $('offset').options[$('offset').options.length-1].value;
	switch(idx) {
			case 'first': 
				idx = 1;
				break;
			case 'previous': 
				idx = cur==1 ? 1 : cur-1;
				break;
			case 'last': 
				idx = last;
				break;
			case 'next': 
				idx = cur==last ? cur :  cur+1;
				break;
			default:
				idx = Math.min(Math.max(idx, 1), last);
	}
	if(cur!=idx || force) {
		//if($('searchform')) $('searchform').reset();
		if($('offset')) $('offset').value = idx;
		loadList();	
	}
}

function loadList()
{
	var query1 = $('searchform') ? '&'+$('searchform').toQueryString() : '';
	var query2 = $('sortform')   ? '&'+$('sortform').toQueryString()   : '';
	var query3 = $('listform')   ? '&'+$('listform').toQueryString()   : '';
	var url = document.location.href.replace(/&cmd=[^&]*/, '').replace(/#.*/, '')+'&cmd=list'+query1+query2+query3;
	while (url.match(/(&|\?)[^=]+=(undefined)?(&|$)/ig))
		url = url.replace(/(&|\?)[^=]+=(undefined)?(&|$)/ig, '$3');
	new ajax(url, {update:'listdiv'}).request();
}

function saveToCookie(obj)
{
	var name = $pick($(obj).getProperty('id'), $(obj).getProperty('name'));
	var path = section + '/' + module + '/' + name;
	Cookie.set(encodeURI(path), $(obj).value, {});
}

function printTo(port, content)
{
	switch(port) {
		case 'prn':
			$each($(document.body).getChildren(), function(el){el.addClass('hidden');});
			printdiv = $(content).clone();
			printdiv.setStyles({
								height: Window.getSize().size.y+'px',
								background: '#FFFFFF',
								margin: '0',
								padding: '0'
						 		});
			printdiv.injectInside(document.body);
			printdiv.id="printdiv";
			var tdiv = new Element('div');
			tdiv.id = 'tdiv';			
			$each($$('#printdiv .noprint'), function(el){
				el.remove();
			});	
			
			$each($$('#printdiv .title'), function(el){
				el.setStyle('margin', '0 0 10px 0');
			});
			
			tdiv.setHTML('<div style="margin:20px; " class="noprint"><input type="button" value="Return" onclick="printTo(\'return\')"></div>');
			tdiv.injectBefore(printdiv.getFirst());
			setTimeout('window.print()', 10);
			break;	

		case 'return':
			$each(document.body.getChildren(), function(el){el.removeClass('hidden');});
			printdiv.remove();
			break;
	}
}

function openNewWindow(url, w, h)
{
	w = (w==null) ? 600 : w;
	h = (h==null) ? 450 : h;
	var target = url.test(/^index\.php.*/i) ? 'popup' : '_blank';
	var aWindow = makePopup(url, target, w, h, 'yes', 'yes');
}

function makePopup(pageURL, pageName, w, h, pageScroll, pageCenter)
{
	if(pageCenter == 'no')	{
		LeftPosition = 10;
		TopPosition = 10;
	} else {
		LeftPosition = (screen.width) ? (screen.width-w) / 2 : 0;
		TopPosition = (screen.height) ? (screen.height-h) / 2 : 0;
	}

	var pageConfig = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=' + pageScroll + ', resizable=yes, width=' + (w + 18) + ', height=' + (h + 18) + ', left=' + LeftPosition + ', top=' + TopPosition;
	var popup = window.open(pageURL.replace(/&popup=[^&]*/,'')+'&popup=1', pageName, pageConfig);
	popup.focus();
	return popup;
}

function findID(obj)
{	
	if(obj = $(obj)) {
		while(obj = obj.getParent()) {
			if(obj.id) {
				var id =  parseInt(obj.id.replace(/^list_row_(\d)+$/ig, '$1'));
				if(id){				
					return id;
				}
			}
		}
	}
	return false;
}

function hideLoading()
{
	$('loading').addClass('hidden');	
}

function doDelete(obj, id)
{
	var id = id ? id : findID(obj);
	new ajax('index.php?section='+section+'&module='+module+'&cmd=delete&id='+id, { onComplete:loadList }).request();
	
}

function doEdit(obj, id)
{
	if( typeof(a_window) != 'undefined') a_close(a_window, 'edit_box');
	var cmd = id ? 'edit' : 'new';
	var id = id ? id : findID(obj);
	$('edit_box').style.top =  window.getSize().scroll.y+4+'px';
	$('edit_box').style.left = Math.max((window.getSize().size.x-$('edit_box').getSize().size.x)/2, 8)+'px';
	$('loading').removeClass('hidden');
	var url = document.location.href.replace(/&cmd=[^&]*/, '').replace(/#.*/, '')+'&cmd='+cmd+'&id='+id;
	
	//new ajax('index.php?section='+section+'&module='+module+'&cmd='+cmd+'&id='+id, { update:'edit_box', loading:null, onComplete:hideLoading }).request();
	new ajax(url, { update:'edit_box', loading:null, onComplete:hideLoading }).request();
}

function doSubmit(frm, iframe)
{
	if($('a_submit').value == 'Saving...') return false;
	
	var oDoc = $('myframe').contentWindow || $('myframe').contentDocument;
	if (oDoc.document) {
		oDoc = oDoc.document;
	}
	oDoc.body.innerHTML = '';
	doSubmit.submitOK = function(res){
		var script, regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
		while ((script = regexp.exec(res))) eval(script[1]);
		if(res.indexOf('[[error]]')>-1) {
			alert('Error in saving.');
			$('a_submit').value = $('a_submit').pre_value;
		} else if(res.indexOf('[[fault]]')>-1) {// error with php message
			$('a_submit').value = $('a_submit').pre_value;	
		} else {	
			a_close('edit_box');	
			loadList();	
		}
	};
	
	doSubmit.check = function(){
		var oDoc = $('myframe').contentWindow || $('myframe').contentDocument;
		if (oDoc.document) {
			oDoc = oDoc.document;
		}
		var txt = oDoc.body ? oDoc.body.innerHTML : '';
		if(txt!='' && txt!='false') {
			doSubmit.submitOK(txt);	
			//doSubmit.myframe.remove();
		} else {
			doSubmit.check.delay(500);
		}
	};
	
	if(iframe) {
		doSubmit.check.delay(500);
	} else {
		var a = new ajax(null, { evalScripts:true, onComplete:this.submitOK, method:'post' });
		a.setHeader('Content-type', 'multipart/form-data; charset=utf8');
		a.send('index.php', $('adminform').toQueryString());
	}
	$('a_submit').pre_value = $('a_submit').value;
	$('a_submit').value = 'Saving...';
	return iframe;
}

function doDeleteImage(dir, id)
{
	doDeleteImage.removeImage = function()
	{
		$('imageBox') && $('imageBox').remove();
	}
	new ajax('index.php?section='+section+'&module='+module+'&cmd=deleteimage&id='+id, {onComplete:doDeleteImage.removeImage, update:'imageBox'}).request();
}

function a_close(obj, newid)
{
	$(obj).setHTML('');
	if(newid) $(obj).id = newid;
}

function a_minimize(sender, obj)
{
	$(obj).t_height = $(obj).getSize().size.y;
	
	var style = {
					height: '23px',
					overflow: 'hidden' 
				};				
	$(obj).setStyles(style);
	$(sender).addClass('hidden');
	$(sender).getNext().removeClass('hidden');
}

function a_restore(sender, obj)
{
	var style = {
					height: $(obj).t_height,
					overflow: 'visible' 
				};
	$(obj).setStyles(style);
	sender.addClass('hidden');
	sender.getPrevious().removeClass('hidden');
}

function setGroupName(selobj, inpobj, imgobj, group)
{
	if($(selobj)) {
		$(inpobj).value=$(selobj).options[$(selobj).selectedIndex].text;	
		$(imgobj).src = '/global/showpic.php?mw=64&mh=64&dir='+group+'&pic='+$(selobj).value;
	}
}

function doNewGroup(rowobj, cmdobj, txtobj)
{
	$(cmdobj).value = 'insert';
	$(rowobj).remove();
	$(txtobj).value='';
}

function doDeleteGroup(cmdobj)
{
	if(confirm('Do you want to delete this group?')) {
		$(cmdobj).value = 'delete';
		$(cmdobj).form.submit();
	}
}

function addRecord(sender, obj)
{
	obj = $(obj);
	var clone = obj.clone();
	clone.injectBefore($(sender));
	clone.id = 'temp_cloned';
	$$('#temp_cloned INPUT, #temp_cloned SELECT, #temp_cloned TEXTAREA').each(function(el){
		el.name = el.name.replace(/^~/, '');
	});
	clone.id = null;
	clone.removeClass('hidden');
}

function resetRows(id)
{
	$$('tr.ron').each(function(el){el.removeClass('ron');});
	if(typeof(id) != "undefined")
		listLatEdited = id;
}

function printForm()
{
	var nw = window.open('', 'PrintWindow', 'width=720px,height=500px,scrollbars=yes');
	nw.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
	'<html>'+
	'<head>'+
	'<link type="text/css" rel="stylesheet" href="/+style/admin.css" />'+
	'<link type="text/css" rel="stylesheet" media="print" href="/+style/print.css" />'+
	'<title></title>'+
	'<script language="javascript" type="text/javascript" src="/+script/class.js"></script>'+
	'<script language="javascript" type="text/javascript">'+
	'function printWindow(){'+
		'document.body.innerHTML = window.opener.document.getElementById("edit_main").innerHTML;'+
		'window.opener.hideDetail();'+
		'setTimeout("window.print();", 200);'+
	'}'+
	'</script>'+
	'<style type="text/css">'+
		'.button, .noprint{'+
			'display:none;'+
		'}'+
	'</style>'+
	'</head>'+
	'<body dir="rtl" onload="window.printWindow();"></body></html>');
	nw.document.close();
}

function setRows()
{
	resetRows();
	if(listLatEdited){
		try{
			$(listLatEdited).addClass('ron');
		}catch(e){}
	}	
}
setRows();


function formatInt(num)
{
	if(typeof(num) == "undefined" || String(num).trim() == '')
		return '';
	var sep = ',';
	var cnt = 3;
	num = String(num).replace(/٫/, '.');
	num = String(num).replace(/[^0-9۰۱۲۳۴۵۶۷۸۹.٫]+/g, '');
	var part = num.split('.', 2);
	num = part[0];
	if(!num) num = '0';
	var res = '';
	var mod = num.length % cnt;
	for(var i=0; i<num.length; i++) {
		res += num.charAt(i);
		if((i+1)%cnt==mod && i+1!=num.length)
			res += sep;
	}
	res = res+(enInt(0+part[1])!=0 ? '.'+part[1] : '');
	return res;
}

function E_(num)
{
	num = String(num);
	num = (num).replace(/٫/g, '.');
	num = (num).replace(/۰/g, '0');
	num = (num).replace(/۱/g, '1');
	num = (num).replace(/۲/g, '2');
	num = (num).replace(/۳/g, '3');
	num = (num).replace(/۴/g, '4');
	num = (num).replace(/۵/g, '5');
	num = (num).replace(/۶/g, '6');
	num = (num).replace(/۷/g, '7');
	num = (num).replace(/۸/g, '8');
	num = (num).replace(/۹/g, '9');
	
	num = (num).replace(/٤/g, '4');
	num = (num).replace(/٥/g, '5');
	num = (num).replace(/٦/g, '6');
	return num;
}

function enInt(num)
{
	if(!num) num = '0';
	num = E_(num);	
	num = num.replace(/[,]+/g, '');
	if(!num) num = '0';
	return num;
}

function F_(num)
{
	num = String(num);
	num = (num).replace(/0/g, '۰');
	num = (num).replace(/1/g, '۱');
	num = (num).replace(/2/g, '۲');
	num = (num).replace(/3/g, '۳');
	num = (num).replace(/4/g, '۴');
	num = (num).replace(/5/g, '۵');
	num = (num).replace(/6/g, '۶');
	num = (num).replace(/7/g, '۷');
	num = (num).replace(/8/g, '۸');
	num = (num).replace(/9/g, '۹');
	return num;
}

function faInt(num)
{
	return F_(num);
}