/*
 * TSF Javascript, base on mootools
 */
 
/* TSFRequestObj, Ajax service manager */
var TSFRequestObj = new Class({
	initialize: function() {
		this.requests = [];
		 window.addEvent('domready', function(){
			this.initAjaxLink();
			
			var isIe = Client.Engine.ie6;
			var tip = new Tips(null, {offsets:{x:isIe ? 0:10,y:0}, fixed: false,
			onShow: function(tip){
				tip.setStyle('display', '');
			},
			onHide: function(tip){
				tip.setStyle('display', 'none');
			}});
			tip.toolTip.setStyle('visibility', '').setStyle('display', 'none');
			$(document).addEvent('mousemove', tip.locate.bind(tip, null, true));
			tip.wrapper.setHTML('<div id="loader" class="png">'
				+ '<div class="faceplate"></div>'
				+ '<div class="progress"></div></div>');
			if(isIe) {
				var pngHandler = new PNGHandler();
				pngHandler.init();
			}
			this.progress = tip;
			
		 }.bind(this));
	},
	/* simple load */
	simple: function (url, callback) {
		var tmp, r;
		tmp = this.progress;
		delete this.progress;
		r = this.create(url, 'get', null, callback);
		this.progress = tmp;
		return r;
	},
	/* Load url */
	load: function (url, callback) {
		return this.create(url, 'get', null, callback);
	},
	/* Post data to url */
	post: function (url, data, callback) {
		return this.create(url, 'post', data, callback);
	},
	/* Load url and update element html by response */
	update: function (elm, url, data, callback, method) {
		this.requests.each(function(r){
			if(r && r.updateElement == elm) r.cancel();
		}, this);
		
		callback	= callback || $empty;
		var self	= this;
		var shadow	= TSF.createShadow(elm);
		var req		= this.create(url, method||'get', data, function(r, success){
			callback(r, success);
			try{ shadow.remove(); }catch(e){}
			if(success) {
				$(elm).setHTML(r);
				req.evalScripts();
				self.initAjaxLink(elm);
			}
		});
		req.updateElement = elm;
		this.fireEvent('UpdateElement', elm);
		return req;
	},
	start: function() {
		if(this.progress) {
			this.progress.show();
		}
	},
	/* @private call on finish rerquest(suceess, error) */
	finish: function (id) {
		delete this.requests[id];
		if(this.progress) {
			this.progress.hide();
		}
	},
	/* @private return new ajax request */
	create: function (url, method, data, callback) {
		var func = callback || $empty;
		var id = this.requests.length, self = this;
		this.start();
		var r = new Ajax(url, {'method': method, 'data': data, /*evalScripts: true,*/
			onSuccess: function(a) {
			   	func(a, true);
			   	self.finish();
			}, onFailure: function() {
				func(null, false);
				self.finish();
			}
		}).request();
		r.request_id = id;
		this.requests.push(r);
		return r;
	},
	/* @public load script by ajax */
	script: function(src, callback) {
		var req = TSF.get(src, function(r, success) {
			req.evalScripts();
			if(success) (callback||$empty).delay(100);
		});
		return req;
	},
	/* init ajax link, append ajax load on onclick event */
	initAjaxLink: function (root, klass) {
		var self = this;
		$(root||document).getElements('a.' + (klass||'ajax')).each(function(el){
			el.target = el.target || 'home';
			el.addEvent('click', function(ev){
				ev.stop();
				var cnf = el.getAttribute('confirm');
				if(cnf != null && !window.confirm(cnf)) {
					return false;
				}
				if(el.target == 'home') TSF.page(el.href);
				else self.update(el.target, el.href+(el.href.indexOf('?')==-1?'?':'&')+'output=module');
			});
		});
	}
});
TSFRequestObj.implement(new Options, new Events);

/* TSFHomePageLoad, Ajax home load */
var TSFHomePageLoad = new Class({
	options: {
		element: 'main_pan'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.status = 'idle';
		this.divContainer = new Element('div');
		this.lastRequests = null;
	},
	load: function(url, data, method) {
		if(this.lastRequests) {
			this.lastRequests.cancel();
		}
		url =  url + (url.indexOf('?') == -1 ? '?':'&') + 'output=page';
		this.lastRequests = TSF.update($(this.options.element), url, data, function(r, success){
			this.lastRequests = null;
			if(!success) return false;
			if(this.status != 'display') {
				this.moveChildsTo($(this.options.element), this.divContainer);
			}
			this.status = 'display';
			window.scrollTo(0, 0);
		}.bind(this), method);
	},
	back: function() {
		if(window.currentPage && !/^\s*$/.test(String(window.currentPage))) {
			location = baseUrl;
			return;
		}
		if(this.divContainer.childNodes.length) {
			this.moveChildsTo(this.divContainer, $(this.options.element).setHTML(''));
		} else {
			location = baseUrl + 'index.php';
		}
		this.status = 'idle';
	},
	moveChildsTo: function(fromElement, toElement) {
		while (fromElement.childNodes.length > 0) {
			toElement.appendChild(fromElement.childNodes[0]);
		}
		return toElement;
	}
});
TSFHomePageLoad.implement(new Options);

var PageShadow = new Class({
	
	initialize: function() {
		this.shadow = new Element('div').setStyles({
			'position': 'absolute',
			'left': '0px',
			'top': '0px',
			'backgroundColor': '#000',
			'opacity': .6,
			'text-align': 'center',
			'zIndex': 10000
		}).setStyle('display', 'none');
		
		window.addEvent('domready', function(){
			this.shadow.inject(document.body, 'bottom');
		}.bind(this));
		
		this.preview = new Element('div').setStyles({
			'position': 'absolute',
			'left': '0px',
			'top': '0px',
			'width': 'auto',
			'height': 'auto',
			'border': '4px solid #525252',
			'backgroundColor': '#FFF',
			'padding': '5px',
			'zIndex': 10001,
			'visibility': 'hidden'
		});
		
		window.addEvent('domready', function(){
			this.preview.inject(document.body, 'bottom');
		}.bind(this));
		
		//$$(this.getShadow(), this.getPreview()).addEvent('click', this.hideShadow.bind(this));
		this.timer=null;
	},
	
	getShadow: function() {
		return this.shadow;
	},
	
	getPreview: function() {
		return this.preview; 
	},
	
	addClose: function() {
		new Element('div').setStyles({
			'position': 'absolute',
			'right': '-15px',
			'top': '-15px',
			'width': '35px',
			'height': '35px',
			'cursor': 'pointer'
		})
		.setHTML('<img src="'+themeUrl+'images/close.png" />')
		.inject(this.preview, 'bottom')
		.addEvent('click', this.hideShadow.bind(this));
	},
	
	makeCenter: function() {
		var e = this.getPreview();
		var l = (Window.getWidth() / 2) - (e.offsetWidth / 2);
		var t = (Window.getHeight()/ 2) - (e.offsetHeight/ 2) + (document.documentElement.scrollTop || 0);
		t = Math.max(0,t);
		e.setStyles({'left': l + 'px', 'top': t + 'px', 'visibility': 'visible'});
	},
	
	showShadow: function() {
		with(this.getShadow().style) {
			if (!window.ie) {
				position = 'fixed';
				width = "100%";
				height = "100%";
			} else {
				left = document.body.offsetLeft + 'px';
				position = 'absolute';
				width = ((document.compatMode == 'BackCompat')?document.body:document.documentElement).scrollWidth + 'px';
				height = document.documentElement.scrollHeight + 'px';
			}
			display = '';
		}
		this.getPreview().setHTML('<img src="'+themeUrl+'images/loadingAnimation.gif" />');
		this.timer = this.makeCenter.delay(200, this);
	},
	
	hideShadow: function() {
		clearTimeout(this.timer);
		this.getPreview().setStyle('visibility', 'hidden').setHTML('');
		this.getShadow().setStyle('display', 'none');
	},
	
	update: function(html) {
		this.getPreview().setStyle('visibility', 'hidden').setHTML(html);
		this.timer = this.makeCenter.delay(200, this);
		this.addClose();
	}
});

var TSF = (function(){
	
	/* Create TSFRequest*/
	var TSFRequest = new TSFRequestObj();
	var TSFHomeLoad= new TSFHomePageLoad();
	
	Element.extend({
		toggleClass: function(klass){
			return this[ this.hasClass(klass) ? 'removeClass':'addClass' ](klass);
		},
		getTagParent: function(tag){
			var el = this;
			do {
				el = el.parentNode;
			} while(el.nodeName != tag.toUpperCase());
			return $(el);
		}
	});
	
	return {
		basket: {},
		createShadow: function(el) {
			var d1 = new Element('div').inject(el, 'top');
			var d2 = new Element('div').inject(d1);
			d1.setStyles({
				'position': 	'relative',
				'width': 		'100%',
				'height':		'0px',
				'border-width': '0'
			});
			d2.setStyles({
				'position':			'absolute',
				'backgroundColor':	'#000',
				'opacity':			'0.5',
				'zIndex':			2,
				'width':			el.offsetWidth + 'px',
				'height':			el.offsetHeight+ 'px'
			});
			return d1;
		},
		
		addRequestEvent: function(name, func) {
			TSFRequest.addEvent(name, func);
		},
	
		simple:	TSFRequest.simple.bind(TSFRequest),
		get:	TSFRequest.load.bind(TSFRequest),
		post:	TSFRequest.post.bind(TSFRequest),
		update:	TSFRequest.update.bind(TSFRequest),
		script:	TSFRequest.script.bind(TSFRequest),
		
		page:	TSFHomeLoad.load.bind(TSFHomeLoad),
		back:	TSFHomeLoad.back.bind(TSFHomeLoad)
	};
})();



////////////////////////////////////// Manage ostan

// city Option
function cOption(id, pid, name) {
	this.id 			= id;
	this.pid 	 		= pid;
	this.name 			= name;
	this.o 			 	= new Option(name, id);
	
}

TSF.manageOstan = {
	
	ostan	: function(ostan_id, name)
	{ 
		ostanOptions.push( new cOption(ostan_id, 0, name ) );
	},
	
	city	: function(id, ostan_id, name)
	{
		cOptions.push( new cOption(id, ostan_id, name) ); 
		
	},
	
	changeOstan : function(ostan_id , cityObjName, selected_city_id)
	{
		var cityObj = document.getElementById(cityObjName); //don't use $, extend elm conflict remove its
		var selectedOptionId = 0;
		if( selected_city_id == undefined) var selected_city_id = 0;	
				
		while (cityObj.childNodes.length > 0) {
	 		cityObj.removeChild( cityObj.childNodes[0] );
		}
		cityObj.options.add( new Option('---', '') );
		if(ostan_id == 0) return;
				
		var o = [];
		var j = 0;
		for(var i=0; i < cOptions.length; i++) 
		{
			if(cOptions[i].pid == ostan_id){
				o.push(cOptions[i].o);
				
				if(cOptions[i].id == selected_city_id) selectedOptionId = j+1;
				j++;
			}
		}

		if(o.length) {
			for( var i=0 ; i < o.length; i++ )
			{
				cityObj.options.add(new Option(o[i].text, o[i].value));
			}
		}
		
		cityObj.options[selectedOptionId].selected = true;

	}
}	

TSF.FormValidate = {
	filters : {
		mail 	: /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i,
		zipcode : /^[0-9]{5}([- /]?[0-9]{5})?$/i
	},
	
	/* by giving the require fields name as an array , it will check all fields for not beeing empty */
	checkAllFormFields : function( parentName, filedNames , errorElem, errorMsg )
	{
		
		this.resetAllFormFieldsFocuse( parentName, filedNames, errorElem );
		
		var error = false;
		var focusElem = ''; // the first field that has an error , and must be focused on 
		for (var i = 0; i < filedNames.length; i++) 
			if( !this.validateFormField( parentName, filedNames[i], errorElem, errorMsg ) && error == false)
			{
				focusElem = $(parentName).getElement(filedNames[i]);
				error 	= true;
			}
		
		if( focusElem != '' ) this.errorFieldStyle( focusElem );
		return !error;
	},
	
	/* checking a field , so it musent be empty */
	validateFormField : function( parentName, filedName, errorElem, errorMsg )
	{
		var fieldElem = $(parentName).getElement(filedName);

		if((fieldElem.value.trim() == '' || fieldElem.value.trim() == 0 ) ) {
			this.showMessageError( errorElem, errorMsg );
			this.errorFieldStyle( fieldElem );
			return false;
		}
		
		return true;
	},
	
	/* check the validation of the value , like email , and zipcode */
	/* note : the field value must not be empty, else it will return true */
	validateFieldValue : function( parentName, filedName, filter, errorElem, errorMsg )
	{
		
		var fieldElem = $(parentName).getElement(filedName);
		
		if(fieldElem.value.trim() == '') return true;
		if(filter == 'mail') 	var filterRegular = this.filters.mail;
		if(filter == 'zipcode') var filterRegular = this.filters.zipcode;
		
		if( !filterRegular ) return false;
		
		var value 		= fieldElem.value;
		var result		= filterRegular.test(value);
				
		if(!result)
		{
			this.showMessageError( errorElem, errorMsg );
			this.errorFieldStyle(fieldElem);
			return false;
		}
		return true;
	},
	
	/* chekcing date validation */
	dateValidate : function( parentName, dayName, monthName, yearName, errorElem, errorMsg)
	{
		var dayElem 	= $(parentName).getElement( dayName );
		var monthElem 	= $(parentName).getElement( monthName );
		var yearElem 	= $(parentName).getElement( yearName );
		
		if(monthElem.value.trim() > 12 || monthElem.value.trim() < 1 ) 	var focusElem = monthElem ;
		if(dayElem.value.trim() > 31 || dayElem.value.trim() < 1 ) 		var focusElem = dayElem ;
		if(focusElem)
		{
			this.showMessageError( errorElem, errorMsg );
			this.errorFieldStyle(focusElem);
			return false;
		}
		return true ; 
	},
	
	/* show error mesage in a div or by giving an alert */
	showMessageError : function( errorElem , msg )
	{
		if( errorElem == undefined ) { alert(msg); return; }
		
		errorElem.innerHTML 	= msg;
		errorElem.setStyle('display','');
	},
	
	/* setting error style to the field */
	errorFieldStyle   : function( fieldElem )
	{
		fieldElem.focus() ;
		fieldElem.addClass('require_field_focuse');
	},
	
	/* by giving the require fields name as an array , it will reset the error style from the fields */
	resetAllFormFieldsFocuse : function( parentName, filedNames, errorElem )
	{
		if( errorElem != undefined ) errorElem.setStyle('display','none');
		for (var i = 0; i < filedNames.length; i++) 
			$(parentName).getElement(filedNames[i]).removeClass('require_field_focuse');
		
		return ;
	}
	
}




/*
CSS Browser Selector v0.3.1
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' '+s+' chrome':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

