// JavaScript Document

window.onload = function()
{
	try {
		loading.forEach(eval);
	} catch (e) {}		
}

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

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 clearAllItems(child)
{
	for(i=child.childNodes.length-1;i>=0;i--) {
		child.removeChild(child.childNodes[i]);
	}
}
function setSubWithGroup(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;
	
	clearAllItems(child);
	window.lastGroup = new Object();
	window.lastGroup.label = 0;
	if(sel.lang) {
		sel.lang.split('||').each(function(el){
										 	el = el.split('=', 3);
											if(el[0]!=window.lastGroup.label) {
												if(window.lastGroup.label) {
													child.appendChild(window.lastGroup);
												}
												window.lastGroup = new Element('optgroup'); 
												window.lastGroup.label = el[0];
											}
											var opt;
										   	window.lastGroup.appendChild(opt = new Option(el[2], el[1]));
											opt.innerHTML = el[2];
										   });	
	}
	child.appendChild(window.lastGroup);	
	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);
}
//-------------------------------//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'];
						};
}