// JavaScript Document

window.addEvent('load', function(){
	loading.each(eval);
});

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 msg(m)
{
	if(m = Json.evaluate(m)) {
		if(typeof(m)=='array') $(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 intval(val)
{
	var res = parseInt(val);
	return isNaN(res) ? 0 : res;
}

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

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 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 hideLoading()
{
	$('loading').addClass('hidden');	
}

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 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');
	new ajax('index.php?section='+section+'&module='+module+'&cmd='+cmd+'&id='+id, { update:'edit_box', loading:null, onComplete:hideLoading }).request();
}

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 saveToCookie(obj)
{
	var name = $pick($(obj).getProperty('id'), $(obj).getProperty('name'));
	var path = section + '/' + module + '/' + name;
	Cookie.set(encodeURI(path), $(obj).value, {});
}

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;
	new ajax(url, {update:'listdiv'}).request();
}

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

//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 findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			if(obj.style.position!='absolute')
				curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			if(obj.style.position!='absolute')
				curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function dropDown(e) {
	e = new Event(e);
	obj = $(e.target);
	if($$('.dropdownbox')[0]) {
		$$('.dropdownbox')[0].remove();
		return;
	}	
	var div = new Element('div');
	div.setStyles({
		overflow: 'auto',
		background: '#fffffd',
		border: '1px solid #666666',
		position: 'absolute',
		'z-index': 1,
		color: '#333333',
		padding: '0px', 
		width: (obj.getSize().size.x-2)+'px',
		direction: 'rtl',
		'text-align': 'right',
		cursor: 'default',
		top: findPosY(obj)+obj.getSize().size.y+'px',
		left: findPosX(obj)+'px'
	});
	obj.addClass('dropdownfield');
	div.addClass('dropdownbox');
	var list = obj.select.options;
	for(var i=0; i<list.length; i++) {
		var divitem = new Element('div');		
		divitem.setStyles({
			overflow: 'hidden',
			width: (obj.getSize().size.x-10)+'px',
			'white-space': 'nowrap',
			padding: '2px',
			height: '14px'
		});
		divitem.addEvent('mouseover', function(e){
			e = new Event(e);
			$(e.target).setStyles({
				background: '#66AAEE',
				color: '#ffffff'
			});
		});
		divitem.addEvent('mouseout', function(e){
			e = new Event(e);
			$(e.target).setStyles({
				background: '',
				color: ''
			});
		});
		divitem.addEvent('click', function(e){
			e = new Event(e);
			e.target.parentField.value = e.target.innerHTML;
			e.target.parentField.select.selectedIndex = e.target.value;
			$(e.target).getParent().remove();
			e.target.parentField.focus();
		});
		divitem.addClass('dropdownitem');
		divitem.parentField = obj;
		divitem.index = i;
		divitem.value = list[i].value;
		divitem.setHTML(list[i].text);
		divitem.injectInside(div);
	}
	div.injectAfter(obj);
}
function hyperSelect(opt) {
	$$('.hyperselect').each(function(el){
		var inp = new Element('input');
		for(i in el.style) {
			try {
				inp.setStyle(i, el.style[i]);
			} catch(e){};
		}
		inp.setProperty('type', 'text');
		inp.setProperty('name', '~'+el.name);
		if(el.hasClass('readonly'))
			inp.setProperty('readonly', '1');
		inp.setStyles({
			padding: '1px 1px 1px 18px',
			background: 'url(../images/admin/combo.png) left center no-repeat',
			border: '1px solid #999999',
			cursor: 'default',
			height: '16px'
		});
		inp.value = el.options[el.selectedIndex].text;
		inp.injectAfter(el);
		if(opt.fixedsize)
			inp.setStyle('width', (inp.getSize().size.x-41)+'px');
		inp.addEvent('click', dropDown);
		inp.select = el;
		el.setProperty('tabindex', '-1');
		var cel = new Element('div');
		cel.setStyles({
			width: '0px',
			height: '0px',
			float: 'left',
			overflow: 'hidden'
		});
		cel.injectInside(el.getParent());
		cel.adopt(el);
	});
		
	window.addEvent('mousedown', function(e) {
		if($(e.target).hasClass('dropdownfield') || $(e.target).hasClass('dropdownbox') || $(e.target).hasClass('dropdownitem')) return;
		var ddb = $$('.dropdownbox');
		if(ddb.length > 0)
			ddb[0].remove();
	});
}

//firebug substitute
if(typeof(console)!='object') {
	console = new Class();
	console.extend({
		log: function(){},
		debug: function(){},
		dir: function(){},
		dirxml: function(){},
		warn: function(){},
		info: function(){},
		error: function(){},
		time: function(){},
		timeEnd: function(){},
		profile: function(){},
		profileEnd: function(){},
		group: function(){},
		groupEnd: function(){},
		count: function(){},
		assert: function(){}		   
	});
}