var Base={
	spinner:'<span style="background:url(./images/loading.gif) no-repeat 0 50%;font-style:italic;font-size:12px;text-align:right;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Wait&#8230;</span>',
	onready:[],
	advanced:null,
	actionUrl:null,
	undefined:"undefined",
	func:"function",
        object:"object",
	onReady:function(){
		for(var i=0;i<Base.onready.length;i++){
			var func=Base.onready[i];
			if(typeof(func)=='function'){
				func();
			}
		}
	},
    addOnReady:function(func){
        Base.onready[Base.onready.length]=func;
    },
	focusField:function(type,which) {
	   if(type) {
		  if(which.value == which.defaultValue) {
			 which.value = '';
		  } else {
			 which.select();
		  }
	   } else {
		  if(which.value == '') {
			 which.value = which.defaultValue;
		  }
	   }
	},
	emailWrong:function(email){
		if(typeof(email)!="string" || email.search(new RegExp("^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,3})$"))==-1){
			return true;
		}
		return false;
	},
	isSuccess:function(response){
		if(response.success==1){return true;}
	},
	loadRight:function(action,postAction){
		if(action)
			Base.postJSON({action:action},
				function(response){
					jQuery("#page1").html(response.html);
					if(postAction && typeof(postAction)=="function")
						postAction(response);
				}
			);
	},
	formatCalendar:function(){
		jQuery('.cal').datepicker({showOn:'button',buttonImageOnly:true,dateFormat:'dd.mm.yy',buttonImage:'images/b_calendar.png'});
	},
	formatTable:function(){
		jQuery(".tablesorter").tablesorter();
	},
	isExpired:function(response){
		if(typeof response.expired!=Base.undefined) {
			document.location.href='./index.php?'+Math.random();
			return true;
		}
		return false ;
	},
	onEnter:function(form,e,func){
		var keynum;
		if(window.event){
		  keynum = e.keyCode;
		}else if(e.which){
		  keynum = e.which;
		}
		if(keynum==13){
			if(Base.textTimer){
				clearTimeout(Base.textTimer);
				Base.textTimer=null;
			}
			if(typeof(func)=="function"){
				func(form);
			}
			return false;
		}else{
			return true;
		}
	},
	onEnterNoSpace:function(form,e,func){
		var keynum;
		if(window.event){
		  keynum = e.keyCode;
		}else if(e.which){
		  keynum = e.which;
		}
		if(keynum==13){
			if(Base.textTimer){
				clearTimeout(Base.textTimer);
				Base.textTimer=null;
			}
			if(typeof(func)=="function"){
				func(form);
			}
			return false;
		}else if(keynum==32){
			return false;
		}else{
			return true;
		}
	},
	textTimer:null,
	onTextChange:function(ctrl,e,action,validate){
		var k,c;
		if(window.event){
		  k=e.keyCode;
		}else if(e.which){
		  k=e.which;
		}
		c=ctrl;
		if(Base.textTimer || k>45 || k==8 || k==32){
			if(Base.textTimer){
				clearTimeout(Base.textTimer);
				Base.textTimer=null;
			}
			if(c.value!=c.defaultValue && typeof(action)=="function")
				Base.textTimer=setTimeout(function(){
					if(validate==undefined || typeof(validate)=="function" && validate(c)){
						action(c);
					}
					c.defaultValue=c.value;
				}
				,900);
		}
	},
	validateDate:function(ctrl){
		var d=ctrl.value;
		if(!d) return true;
		if(!/^\d{1,2}\.\d{1,2}\.\d{4}$/.test(d))
			return false;
		else {
			var matches=d.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
			var date=new Date();
			var day1=new Number(matches[1]);
			var month1=new Number(matches[2]);
			var year1=new Number(matches[3]);
			date.setDate(day1);
			date.setMonth(month1-1);
			date.setFullYear(matches[3]);
			if(date.getDate()==day1 || date.getMonth()==month1-1 || date.getFullYear()==year1)
				return true;
		}
		return false;
	},
	evalResponse:function(object){
		if(typeof(object)=="object"){
			for(var propertyName in object){
				var value=object[propertyName];
				if(typeof(value)=="string" && /^function()/.test(value)){
					eval("var a="+value);
					object[propertyName]=a;
				}else if(typeof(value)=="object"){
					Base.evalResponse(value);
				}
			}
		}
		return object;
	},
	/* TODO add Base.name='aaa'; if(typeof(response.aaa)=='object'){...}
	 * TODO for(var propertyName in response){if(typeof(response[propertyName])!="object"){....}}
	 * TODO receive response post-action
	 */
	postJSON:function(data,func){
		jQuery.post(Base.actionUrl,data,
			function(response){
				if(!Base.isExpired(response)){
					Base.evalResponse(response);
					if(typeof(func)=='object' && typeof(func.preOp)=='function'){
						func.preOp(response);
					}
					if(response.preOp)
						response.preOp(response);
					for (var propertyName in response) {
						if(new RegExp(","+propertyName+",").test(",htmls,rowCount,html,message,expired,success,postAction,preOp,postOp,")!=true)
							jQuery("#"+propertyName).html(response[propertyName]);
					}
					if(response.htmls){
						for(var tagId in response.htmls){
							var property=response.htmls[tagId];
							if(tagId=="js"){
								property(response);
							}else if(typeof(property)=="string"){
								jQuery("#"+tagId).html(property);
							}else if(typeof(property)=="object") {
								for(var propertyName in property){
									if(propertyName=="html"){
										jQuery("#"+tagId).html(property[propertyName]);
									}else if(propertyName=="css"){
										for(var cssName in property[propertyName]){
											jQuery("#"+tagId).css(cssName,property[propertyName][cssName]);
										}
									}else{
										jQuery("#"+tagId).attr(propertyName,property[propertyName]);
									}
								}
							}
						}
					}
					if(response.postAction){
						response.postAction(response);
					}
					if(response.postOp)
						response.postOp(response);
					if(typeof(func)=='function')
						func(response);
					if(typeof(func)=='object' && typeof(func.postOp)=='function')
						func.postOp(response);
				}
			},"json");
	},
	postForm:function(form){
		if(form.message)
			jQuery("#"+form.message.value).empty();
		if(form.target)
			jQuery("#"+form.target.value).html(Base.spinner); // where to write http query result
		Base.postJSON(jQuery(form).serializeArray(),
			function(response){ // form.action.value - hidden should contains action string id for current post
				if(response.html && form.target)  // where to write http query result
					jQuery("#"+form.target.value).html(response.html);
				else if(form.target)
					jQuery("#"+form.target.value).empty();
				if(response.message)jQuery("#"+form.message.value).html(response.message); // where to write http query message
				if(form.postaction){ // if hidden variable exists - it containts js to run after http reesponse
					var func=eval(form.postaction.value);
					if(typeof(func)=='function'){
						func(response,form);
					}
				}
			});
	},
	runFunc:function(func,data){
		if(typeof(func)=="function"){
			func(data);
		}
	},
	parentPos:function(elem){
		var parent=jQuery(elem).offsetParent();
		return (/^body|html$/i.test(parent[0].tagName)) ? { top: 0, left: 0 } : parent.offset();
	},
	getPossition:function(elem){ // TODO: apply this
		var elPos    =jQuery(elem).position(); // jQuery(elem).offsetParent().get(0).tagName
		var parPos=Base.parentPos(elem);
		var elTopMargin=parseInt(jQuery(elem).css('margin-top').replace(/px/,""));
		var elTopPadding=parseInt(jQuery(elem).css('padding-top').replace(/px/,""));
		elPos.left+=parPos.left;
		elPos.top +=parPos.top+elTopMargin+elTopPadding;
		return elPos;
	},
	jQueryUi:function(func){
		if(jQuery.datepicker==undefined){
			var head = document.getElementsByTagName('head');
			if(head.length==0)
				$(document.createElement('head')).appendTo(document);
			head = document.getElementsByTagName('head')[0];
			jQuery(document.createElement('link'))
			    .attr({type: 'text/css', href: "css/jquery-ui-1.7.1.custom.css", rel: 'stylesheet', media:'screen'})
			    .appendTo(head); 
			jQuery.getScript("js/jquery-ui-1.7.1.custom.min.js",function(){
				jQuery(document).ready(function() {
					if(typeof(func)=="function")
						func();
					});
				});
		}else if(typeof(func)=="function")
			func();
	},
	findUpForm:function(el){
		var form=el;//.parentNode.parentNode.parentNode.parentNode.parentNode;
		//while(form.parentNode && (form.nodeName!="FORM" || form.name!="html" || form.name!="body"))form=form.parentNode;// td/tr/tbody/table/form
		while(form.parentNode && !/^body|form|html$/i.test(form.nodeName))
			form=form.parentNode;// td/tr/tbody/table/form
		//alert(form.nodeName);
		if(/^body|form|html$/i.test(form.nodeName))
			return form;
		else
			return null;
	},
	findUpElement:function(el,search){
		var found=el;
		var re=new RegExp("^body$|^form$|^html$|^"+search+"$","i");
		while(found.parentNode && !re.test(found.nodeName))
			found=found.parentNode;
		return found;
	}
};
jQuery(document).ready(Base.onReady);

