// 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');
		}
	}
}

// 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('&');
};

//loading.push('addStandardClass()');
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 doSetcooki(obj, league)
{
	var league = league ? league: findLeague(obj);
	Cookie.set("league", Base64.encode(league));
	document.location.reload();

}
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 = '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.hideProductDetail();'+
		'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 getContent(url, query, cmd, cmdOnError, method, retry)				
{
	if(typeof(cmdOnError)=='undefined')
		cmdOnError = ';';
	if(typeof(method)=='undefined')
		method = 'GET';
	else
		method = method.toUpperCase();
	retry  = (retry || 0);
	if(retry > 5){
		try{
			eval(cmdOnError);
		} catch(e){}
		return;
	}
	var A = createAjax();
	if(method == "GET")
		A.open(method, url+'?'+query+'&_r_=done'+Math.random(), true);
	else
		A.open(method, url, true);

	var onreadystatechange = function(){
			if(A.readyState==4)
				if(A.status==200 || A.status == 304){
					Contents = A.responseText;
					var ScriptCode, regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
					while (ScriptCode = regexp.exec(Contents))
						try{
							eval(ScriptCode[1]);
						}catch(e){}
					// do the finish CMD
					try{
						eval(cmd);
					} catch(e){}
				}else {
					getContent(url, query, cmd, cmdOnError, method, (retry+1));
					}
			};
	A.onreadystatechange = onreadystatechange;
	if(method == "GET")
		A.send(null);
	else{
		var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
		A.setRequestHeader("Content-Type", contentType);
		A.send(query+'&_r_=done'+Math.random());
	}
}
function xMakeVisible(obj, d)												
{
	if(typeof(d) == "undefined")
		d = false;
	if(typeof(obj) != "object")
		obj = $(obj);
	if(!d)
		obj.style.display	= '';
	obj.style.visibility = "visible";
}
function xMakeHidden(obj, d)												
{
	if(typeof(d) == "undefined")
		d = false;
	if(typeof(obj) != "object")
		obj = $(obj);
	if(!d)
		obj.style.display	= 'none';
	obj.style.visibility = "hidden";
}												
function createAjax() 														
{
	try { return new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) {}
	try { return new XMLHttpRequest(); }
		catch(e) {}
	return null;
}
/*
var $ =	function (eName)													
	{
		return document.getElementById(eName);	
	};
*/	
function xFindPosX(obj)														
{
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
			}
		}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function xFindPosY(obj)														
{
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
			}
		}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
function xRemovePX(strNum)													
{
	return strNum.substr(0, strNum.length - 2) * 1;
}
//-------------------------------//Image Loader//----------------------------------
var xImages = new Array();
var _xImages = new Array();
function _xloadImages() 													
{
	var i,key;
	for (i=0; i<_xloadImages.arguments.length; i++) {
		if (typeof(_xloadImages.arguments[i]) == 'string') {
			_xImages.push(document.createElement('img'));
			_xImages[_xImages.length-1].src = _xloadImages.arguments[i];
			}
		else if (typeof(_xloadImages.arguments[i]) == 'object')
			for(key in _xloadImages.arguments[i])
				if(typeof(_xloadImages.arguments[i][key]) != 'function') {
					_xImages.push(document.createElement('img'));
					_xImages[_xImages.length-1].src = _xloadImages.arguments[i][key];
					}
		}
}
function xloadImages()														
{
	var i,key;
	if (xloadImages.arguments.length == 0) {
		_xloadImages(xImages);
		return true;
		}
//	if (pageLoaded) {
//		for (i=0; i<xloadImages.arguments.length; i++)
//			_xloadImages(xloadImages.arguments[i]);
//		return true;
//		}
	for (i=0; i<xloadImages.arguments.length; i++){
		if (typeof(xloadImages.arguments[i]) == 'string') {
			xImages.push(xloadImages.arguments[i]);
			}
		else if (typeof(xloadImages.arguments[i]) == 'object') 
			for(key in xloadImages.arguments[i])
				if(typeof(xloadImages.arguments[i][key]) != 'function') {
					xImages.push(xloadImages.arguments[i][key]);
					}
		}
}
function xBtnCreate(obj, cmd, cmd2, type)									
{
	if(typeof(cmd2) == "undefined")
		cmd2 = "";
	if(typeof(type) == "undefined")
		type = "normal";
	if(type == "check"){
		oName = (obj.name)?obj.name:obj.id;
		if(oName.length < 1)
			oName = "rcoId"+Math.round(Math.random()*9999);
		var Obj = document.createElement('input');
		Obj.type = 'hidden';
		Obj.name = oName+"IN";
		Obj.id = oName+"IN";
		Obj.value = 0;
		obj.parentNode.appendChild(Obj);
		if(!obj.id)
			obj.id = oName;
	}
	var img = new Array();
	var tmp = obj.src.split('/images/');
	img['path'] = tmp[0]+"/images/";
	tmp = tmp[1].split('.');
	img['img'] = tmp[0];
	img['ext']  = tmp[1];
	if(typeof(img['img']) == 'undefined' || img['img'] == 'undefined' )
		return;
	_xloadImages (img['path']+img['img']+"."+	img['ext'],
				 img['path']+img['img']+"-over"+"."+img['ext'],
				 img['path']+img['img']+"-down"+"."+img['ext']
				);
	obj.style.cursor = "pointer";
	doWhileUp		= function(OBJid, CMD, targetV1, targetV2){
						try{
							OBJ = $(OBJid);
							if(OBJ.src != targetV1 && OBJ.src != targetV2){
								eval(CMD);
								setTimeout("doWhileUp('"+OBJid+"', '"+CMD+"', '"+targetV1+"', '"+targetV2+"')", 50);
								}
							}
						catch(e){}
						};
	obj.onmouseover	= function(){
							if(obj.src == img['path']+img['img']+"-down."+img['ext'])
								obj.src=img['path']+img['img']+"-down-over."+img['ext'];
							else
								obj.src=img['path']+img['img']+"-over."+img['ext'];
						};
	obj.onmouseout	= function(){
							if(obj.src == img['path']+img['img']+"-down-over."+img['ext'])
								obj.src=img['path']+img['img']+"-down."+img['ext'];
							else
								obj.src=img['path']+img['img']+"."+img['ext'];
						};
	obj.onmouseup 	= function(){
							if(type == "check"){
								if ($(obj.id+"IN").value == '0')
									obj.src=img['path']+img['img']+"-down-over."+img['ext'];
								else
									obj.src=img['path']+img['img']+"-over."+img['ext'];
								$(obj.id+"IN").value = ($(obj.id+"IN").value == '1')?0:1;
							}else							
								obj.src=img['path']+img['img']+"-over."+img['ext'];
						};
	obj.onmousedown = function(){
							obj.src=img['path']+img['img']+"-down."+img['ext'];
							if(typeof(cmd2) != "undefined" && cmd2.length > 0)
								doWhileUp(obj.id, cmd2, img['path']+img['img']+"-over."+img['ext'], img['path']+img['img']+"."+img['ext']);
						};
	obj.onclick		= function(){
							try{
								eval(cmd);
							} catch(e){}
						};
						
	obj.onload		= function(){
						};
	obj.ondblclick	= function(){
							obj.src=img['path']+img['img']+"."+img['ext'];
						};
}

var popupStatus = 'none';
var popupLastPage = '';

function popupWin(cmd, txt, page)						
{
	var popupWidth={
					"news-detail":600
					};
	if(typeof(page) == "undefined")
		page = 'en';
	if(typeof(txt) == "undefined")
		txt = 0;
	switch(cmd){
		case "create":		
			var Obj = document.createElement('div');
			Obj.id = "popupWinHolder";
			Obj.style.position = "absolute";
			document.getElementsByTagName('body')[0].appendChild(Obj);
			$("popupWinHolder").innerHTML =	'<table border="0" cellpadding="0" cellspacing="0" style="width:100%;">'+
													'<tr>'+
														'<td style="background:url(../images/them/Gray90_cornner.gif) no-repeat top left; width:15px; height:15px"></td>'+
														'<td style="background:url(../images/them/bgGray90.gif) repeat ;height:15px"></td>'+
														'<td style="background:url(../images/them/Gray90_cornner.gif) no-repeat top right; width:15px; height:15px"></td>'+
													'</tr>'+
													'<tr style="background:url(../images/them/bgGray90.gif) repeat ;">'+
														'<td style="width:15px"></td>'+
														'<td>'+
															'<div class="liveReportWin">'+
																'<div style="width:100%;height:23px;background:url(../images/them/liveRepWinHeaderBig.gif) repeat-x top;border:1px solid #969696;border-bottom:0;">'+
																	'<img src="../images/them/xwinBtnClose.gif" width="19" height="19" alt="" title="" style="margin:2px 4px 2px 2px; float:right" onLoad="xBtnCreate(this, \'popupWin(\\\'hide\\\')\')" />'+
																	'<img src="../images/them/xwinBtnMin.gif" id="popupBtnMinimize" width="19" height="19" alt="" title="" style="margin:2px; float:right" onLoad="xBtnCreate(this, \'popupWin(\\\'minimize\\\')\')" />'+
																	'<img src="../images/them/xwinBtnMax.gif" id="popupBtnMaximize" width="19" height="19" alt="" title="" style="margin:2px; float:right; display:none;" onLoad="xBtnCreate(this, \'popupWin(\\\'maximize\\\')\')" />'+
																'</div>'+
																'<div style="width:100%; background:#FFFFFF;border:1px solid #969696; border-bottom:0;">'+
																	'<table id="popupwinMainTable" border="0" cellpadding="0" cellspacing="5" style="width:100%;; background:#F4F3F3">'+
																		'<tr>'+
																			'<td id="popupWinContainer">'+
																			'</td>'+
																		'</tr>'+
																	'</table>'+
																'</div>'+
																'<div style="width:100%;height:20px;background:#FFFFFF url(../images/them/liveRepWinStratus.gif) no-repeat bottom left;text-align:right;border:1px solid #969696;color:#666666;" id="popupWinStatus"></div>'+
															'</div>'+
														'</td>'+
														'<td style="width:15px"><div style="display:none"><input type="hidden" id="popupwinPage" /><input type="hidden" id="popupwinText" /><input type="hidden" id="popupwinDirectUrl" /></div></td>'+
													'</tr>'+
													'<tr>'+
														'<td style="background:url(../images/them/Gray90_cornner.gif) no-repeat bottom left; width:15px; height:15px"></td>'+
														'<td style="background:url(../images/them/bgGray90.gif) repeat ;height:15px"></td>'+
														'<td style="background:url(../images/them/Gray90_cornner.gif) no-repeat bottom right; width:15px; height:15px"></td>'+
													'</tr>'+
												'</table>';	
			popupStatus = 'created';
			break;
		case "show":		
			i = 0;
			if(popupStatus == 'none')
				popupWin('create', txt, page);
			popupWin('maximize');
			$("popupWinHolder").style.width = 650 +"px";
//			if(eval("popupLastPage != '"+page+"#"+txt+"';"))
//			{
			popupWin('loading', txt, page);
			if(txt.length < 4)
				txt =  "news-detail&id=" + txt;
			popupWin('fetch', txt, page);
//			}
			popupLastPage = page+"#"+txt;
			var sw = document.getElementsByTagName("body")[0].clientWidth || screen.width;
			var sl = Math.round((sw - 650 )/2);
			st = 250+document.documentElement.scrollTop*1;
			$("popupWinHolder").style.top = st + 'px';
			$("popupWinHolder").style.left = sl + 'px';
			xMakeVisible("popupWinHolder");
			popupStatus = 'visible';
			break;
		case "hide":		
			if(popupStatus == 'none')
				break;
			xMakeHidden("popupWinHolder");
			popupStatus = 'hidden';
			break;
		case "minimize":	
			xMakeHidden('popupwinMainTable');
			xMakeHidden('popupBtnMinimize');
			xMakeVisible('popupBtnMaximize');
			break;
		case "maximize":	
			xMakeVisible('popupwinMainTable');
			xMakeVisible('popupBtnMinimize');
			xMakeHidden('popupBtnMaximize');
			break;
		case "fetch":		
			popupWin("status", "درحال بارگزاری...", page);
			getContent(
						txt,
							'',//'section=guest&module='+txt+'&lang='+page,
								'$("popupWinContainer").innerHTML = Contents;'+
								'popupWin("status", "انجام شد", "'+page+'");',
									'popupWin("status", "بارگزاری مجدد...", "'+page+'");'+
									'popupWin("error", "'+txt+'", "'+page+'")',
										'GET'
					);
			break;
		case "loading":		
			$("popupWinContainer").innerHTML =	'<div style="margin:0;background:#FFFFFF;width:300px; margin:0 auto;">'+
													'<table border="0" cellpadding="0" cellspacing="5" width="100" style="margin:0 auto; direction:ltr	">'+
													  '<tr><td><br><br><br><br><br><br></td></tr>'+
													  '<tr>'+
														'<td width="80%" style="text-align:right">لطفاً صبر کنيد</td>'+
														'<td width="20%" style="text-align:left"><img src="../images/them/loading.gif" width="16" height="16" alt="" /></td>'+
													  '</tr>'+
													  '<tr><td><br><br><br><br><br><br></td></tr>'+
													'</table>'+
												'</div>';
			break;
		case "reload":		
			if($('popupwinPage')){
				popupWin('loading');
				popupWin('fetch', $('popupwinText').value, $('popupwinPage').value);
			}
			break;
		case "error":		
			popupWin("status", "اشکال در دريافت اطلاعات!", page);
			$("popupWinContainer").innerHTML =	'<div class="whiteBoxHolder" style="margin:0;  width:300px;text-align:left">'+
													'<div class="BoxHeader"><div></div></div>'+
													'<div class="BoxContent" style="margin:0; padding:100px 0;">'+
													'<table border="0" cellpadding="0" cellspacing="0" width="100px" style="margin:0 auto">'+
													  '<tr>'+
														'<td>دريافت اطلاعات با مشکل مواجه شد. لطفاً بعد از بررسی ارتباط خود با اينترنت دوباره سعی کنيد</td>'+
														'<td><img src="../images/them/iconTimeout.gif" width="24" height="24" alt="" /></td>'+
													  '</tr>'+
													'</table>'+
													'</div>'+
													'<div class="BoxFooter""><div></div></div>'+
												'</div>';
			break;
		case "status":
			$("popupWinStatus").innerHTML = "<div style='direction:rtl'>&nbsp;&nbsp;&nbsp;" + txt + "&nbsp;&nbsp;&nbsp;</div>";
			break;
	}
}


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