/*
	Copyright © Eleanor CMS
	URL: http://eleanor-cms.ru, http://eleanor-cms.su, http://eleanor-cms.com, http://eleanor-cms.net, http://eleanor.su
	E-mail: support@eleanor-cms.ru
	Developing: Alexander Sunvas*
	Interface: Rumin Sergey
	=====
	*Pseudonym
*/

var uagent=navigator.userAgent.toLowerCase(),
	CORE={	//Настройки	c_domain:"",
	c_prefix:"",
	c_time:"",
	site_path:"",

	//Путь к AJAX файлу
	ajax_file:"ajax.php",

	//Языки
	lang_name:"",
	lang:[],
	Lang:function(arr,a)
	{		if(typeof arr=="string")
		{
			var ret=typeof this.lang[arr]=="undefined" ? "" : this.lang[arr],
				f=false;

			a=a || [];
			for(var i in a)
				ret=ret.replace("{"+i+"}",a[i]);
			return ret;
		}
		else			for(var i in arr)
				this.lang[i]=arr[i];
	},

	//Браузер
	browser:
	{
		safari:(uagent.indexOf('safari')!=-1 || navigator.vendor=="Apple Computer, Inc." || uagent.indexOf('konqueror')!=-1 || uagent.indexOf('khtml')!=-1),
		opera:uagent.indexOf('opera')!=-1,
		ie:(uagent.indexOf('msie')!=-1 && !this.opera && !this.safari),
		mozilla:navigator.product=='Gecko'
	},
	//Ajax обертка
	in_ajax:false,
	after_ajax:[],
	Ajax:function(arr,func,err)
	{		var th=this,
			info={};
		switch(typeof func)
		{			case "function":
				info.OnSuccess=func;
			break;
			case "object":
				info=func;		}
		if(typeof err!="undefined")
			info.OnFail=err;
		info=$.extend(
			{				OnBegin:function(){ th.ShowLoading(); },
				OnEnd:function(){ th.HideLoading(); },
				OnSuccess:function(){},
				OnFail:function(s){ alert(s); }			},
			info
		);
		info.OnBegin();
		$.post(
			this.ajax_file,
			arr,
			function(data)
			{				info.OnEnd();				if(!data || typeof data!="object")
					return info.OnFail(data);
				if(typeof data.error!="undefined" && data.error)
					return info.OnFail(data.error);
				if(typeof data.data=="undefined")
					throw "No data";
				th.in_ajax=true;
				th.after_ajax=[];
				var DoFunc=function(){					info.OnSuccess(data.data);					if(typeof data.head!="undefined")
						for(var i in data.head)
							th.AddHead(i,data.head[i]);
					th.in_ajax=false;
					for(var i in th.after_ajax)
						th.after_ajax[i]();
				}
				if(typeof data.scripts!="undefined" && $.isArray(data.scripts) && data.scripts.length>0)
					th.AddScript(data.scripts,DoFunc);
				else
					DoFunc();			},
			"json"
		);	},

	loading:"#loading",
	ShowLoading:function()
	{		if(this.loading)
			$(this.loading).show().trigger("show");	},
	HideLoading:function()
	{		if(this.loading)
			$(this.loading).hide().trigger("hide");	},

	//Установка и удаление кук
	SetCookie:function(name,value,ctime)
	{
		var data=new Date();
		data.setTime(data.getTime()+(ctime ? ctime : this.c_time)*1000);
		document.cookie=escape(this.c_prefix+name)+"="+escape(value)+';expires='+data.toGMTString()+";domain="+this.c_domain+";path="+this.site_path;
	},
	GetCookie:function(name)
	{
		var res;
		if(res=document.cookie.match(new RegExp(escape(this.c_prefix+name)+"=([^;]+)","i")))
			return unescape(res[1]);
		return false;
	},

	//Переход по страницам
	JumpToPage:function(result,pages)
	{
		var s=prompt(this.Lang('page_jump'),'');
		if(!s || isNaN(s) || (s=parseInt(s))<=0)
			return;
		pages=parseInt(pages);
		if(s>pages)
			s=pages;
		if(typeof result=="function")
			result(s);
		else
			window.location.href=result.replace('{page}',s);
	},

	//Добавляем стиль
	head:[],//Дополнения в head
	AddHead:function(key,data)
	{		var m=false;		if(m=key.match(/^[0-9]+$/) || $.inArray(key,this.head)!=1)
		{
			$("head:first").append(data);
			if(!m)
				this.head.push(key);
		}
	},

	//Загружаемые скрипты
	scripts:[],
	AddScript:function(s,func)
	{		if(!$.isArray(s))
			s=[s];

		var num=0,
			texts={},
			F=function(){if(s.length==num){				$.each(s,function(i,n){					if(texts[i])
						$.globalEval(texts[i]);				});
				if(typeof func!="undefined")
					func();			}};
		$.each(s,function(i,n){			if(n && $.inArray(n,CORE.scripts)==-1)
			{				if(n.indexOf("://")>0)
					$.ajax({
						url:n,
						success:function(d){
							CORE.scripts.push(n);
							texts[i]=false;
							num++;
							F();
						},
						dataType:"script",
						async:false,
						cache:true
					});
				else
					$.get(n,{},function(d){						CORE.scripts.push(n);						texts[i]=d;
						num++;
						F();					},"text");			}
			else
			{				texts[i]=false;
				num++;
				F();			}		});
	},

	//Для манипуляции с историей
	history:false,
	HistoryInit:function(F,data)
	{		this.history=[];
		if($.isFunction(F))
			this.history.push(F);
		else
			F=false;
		history.replaceState({f:F ? this.history.length-1 : false,data:data||false},"",window.location.href);		var OnPop=function(e){			var st=e.state||false;
			if(st && st.f!==false && typeof CORE.history[st.f]!="undefined")
				CORE.history[st.f](st.data);
		}
		if(window.addEventListener)
			window.addEventListener("popstate",OnPop,false);
		else
			window.attachEvent("onpopstat",OnPop);
	},
	HistoryPush:function(href,F,data)
	{		if($.isFunction(F))
			this.history.push(F);
		else
			F=false;
		try
		{			history.pushState({f:F ? this.history.length-1 : false,data:data||false},"",href);
		}
		catch(e){}	},

	/*
		Функций уменьшения картинок
		obj - объект в котором надо производить уменьшение картинок.
		width - граничная ширина после которой картинка считается слишком большой и урезается.
		percent - процент от width, до которого ужмется изображение
	*/
	ResizeBigImages:function(obj,width,percent)
	{
		obj=$(obj ? obj : document);
		if(!percent)
			percent=30;
		percent/=100;
		if(!width)
		{
			width=obj.width();
			var sw=screen.width*0.95;//Может ширина экрана меньше, чем контейнера.. Возьмем 95%
			if(sw<width)
				width=sw;
		}
		var mwidth=width*percent,//Максимальная ширина, которая должна быть у картинки
			padding=2,
			ResizeFunc=function(img)
			{				var iw=$(img).prop("naturalWidth"),
					ih=$(img).prop("naturalHeight");
				if(img.resized || iw<=mwidth)
					return;
				var p=mwidth/iw*100,
					click=$("<div>").html("<img src=\"images/img-resized.png\" style=\"vertical-align:middle\" />&nbsp; <b>"+Math.round(p)+'%</b> [ '+iw+' x '+ih+' ] &raquo; [ '+mwidth+' x '+Math.round(ih/100*p)+' ]')
					.width(mwidth-(padding*2)+'px').addClass('resized-image-header').css('padding',padding+'px').css('cursor','pointer').click(function(){window.open(img.src)});

				$(img.parentNode.nodeName=='A' ? img.parentNode : img).wrap("<div class=\"posted-image\">").width(mwidth+"px").after(click);
				img.resized=true;
			}
		if(mwidth>0)
			obj.find("img").each(function(){
				if(!this.resized && this.className=="posted-image")
				{
					if(CORE.browser.opera || CORE.browser.mozilla)
						ResizeFunc(this);
					$(this).load(function(){
						ResizeFunc(this);
					})
				}
		})
	},

	//MultiSite
	mssites:[],
	msisuser:false,
	msservice:"",
	mslogined:[],
	msinqueue:true,
	msfqueue:[],
	MSGetLogined:function(F)
	{		if(typeof F=="undefined")
		{			if(!this.msinqueue)
				$.each(this.msfqueue,function(k,v){					v(CORE.mslogined);				});
		}		else if($.isFunction(F))
			if(this.msinqueue)
				this.msfqueue.push(F);
			else
				F(this.mslogined);
	},
	LoginFrom:function(sn)
	{		if(this.msinqueue || typeof this.mslogined[sn]=="undefined" || this.msisuser)
			return false;
		var ls=true,
			Mess=function(r)
			{
				//Ни IE, ни Chrome не умеют напрямую принимать объекты... А опере придется страдать из-за этого :(
				var data=$.parseJSON(r.data);
				if(data.w=="ms-getlogin")
					CORE.Ajax(
						$.extend(
							data,
							{								direct:"mslogin",
								type:"login",
								sn:sn,
								service:CORE.msservice
							}
						),
						{							OnBegin:function(){ ls=false; },
							OnSuccess:function(r){								if(r)
									window.location.reload();							}						}
					);
			}
		if(window.addEventListener)
			window.addEventListener("message",Mess,false);
		else
			window.attachEvent("onmessage",Mess);

		this.ShowLoading();
		var fr=$("<iframe>").prop({
				src:this.mssites[sn].address+"ajax.php?direct=mslogin&type=getlogin&service="+CORE.msservice+(this.mssites[sn].secret ? "&secret=1" : ""),
				style:"display:none"
			})
			.css({position:"absolute",left:"-1000px",top:"-1000px"}).width("1px").height("1px")
			.load(function(){
				setTimeout(function(){
					if(window.removeEventListener)
						window.removeEventListener("message",Mess,false);
					else
						window.detachEvent("onmessage",Mess);
					fr.remove();
					if(ls)
						CORE.HideLoading();
				},1000);
			}).appendTo("body");
	},
	MSJump:function(sn)
	{		if(typeof this.mssites[sn]=="undefined" || !this.msisuser)
			return false;
		this.Ajax(
			{				direct:"mslogin",
				type:"prejump",
				sn:sn,
				service:this.msservice			},
			function(r)
			{				var form=$("<form method=\"post\">").prop("action",r.address+"ajax.php?direct=mslogin&type=jump&service="+CORE.msservice);
				$.each(r,function(k,v){					$("<input type=\"hidden\">").prop({						name:k,
						value:v					}).appendTo(form);				})
				form.appendTo("body").submit();			}
		);
	}
},
EDITOR=
{
	active:null,
	editors:[],
	Insert:function(text,id)
	{
		if(!id)
			id=this.active;
		if(id && typeof this.editors[id]=='object' && typeof this.editors[id]['insert']=='function')
			try
			{
				return this.editors[id]['insert'](text);
			}catch(e){}
		return false;
	},
	GetValue:function(id)
	{
		if(!id)
			id=this.active;
		if(id && typeof this.editors[id]=='object' && typeof this.editors[id]['getvalue']=='function')
			try
			{
				return this.editors[id]['getvalue']();
			}catch(e){}
		return false;
	},
	SetValue:function(text,id)
	{
		if(!id)
			id=this.active;
		if(id && typeof this.editors[id]=='object' && typeof this.editors[id]['setvalue']=='function')
			return this.editors[id]['setvalue'](text);
		return false;
	},
	ReplaceSelection:function(pre,after,textfunc,id)
	{
		if(!id)
			id=this.active;
		if(id && typeof this.editors[id]=='object')
			try
			{
				return typeof this.editors[id]['selection']=='function' ? this.editors[id]['selection'](pre,after,textfunc) : this.Insert(pre+after,id);
			}catch(e){}
		return false;
	},
	//Служебные функции
	NewEditor:function(id,insert_cb,setvalue_cb,getvalue_cb,insert_selection_cb)
	{
		if(!id || typeof insert_cb!='function')
			return false;
		this.editors[id]={
			insert:insert_cb,
			setvalue:setvalue_cb,
			getvalue:getvalue_cb,
			selection:insert_selection_cb
		};
		this.active=id;
		return true;
	},
	RemoveEditor:function(id)
	{
		if(!id)
			id=this.active;
		this.editors[id]=null;
	},
	ActivateEditor:function(id)
	{
		if(id && typeof this.editors[id]=='object')
			this.active=id;
	}
}

$(function(){	if(CORE.mssites || CORE.msisuser)
	{		var n=0,
			Mess=function(r)
			{				//Ни IE, ни Chrome не умеют напрямую принимать объекты... А опере придется страдать из-за этого :(				var data=$.parseJSON(r.data);
				if(data.w=="ms-check")
					CORE.mslogined[data.sn]=data.login;			}
		if(window.addEventListener)
			window.addEventListener("message",Mess,false);
		else
			window.attachEvent("onmessage",Mess);

		$.each(CORE.mssites,function(sn,site){			n++;			var fr=$("<iframe>").prop({					src:site.address+"ajax.php?direct=mslogin&type=check&service="+CORE.msservice+"&sn="+sn,
					style:"display:none"
				})
				.css({position:"absolute",left:"-1000px",top:"-1000px"}).width("1px").height("1px")
				.load(function(){					setTimeout(function(){						if(--n==0)
						{							if(window.removeEventListener)
								window.removeEventListener("message",Mess,false);
							else
								window.detachEvent("onmessage",Mess);							CORE.msinqueue=false;
							CORE.MSGetLogined();
						}						fr.remove();
					},1000);				}).appendTo("body");
		});
	}
	else
	{
		CORE.msinqueue=false;
		CORE.MSGetLogined();
	}
	//Уменьшаем изображения до уровня страницы:
	CORE.ResizeBigImages("#resizedimage",0,75);

	//Подсветим активные пункты меню
	var now="";
	with(window.location)
	{
		now+=protocol+"//"+hostname+(port ? ":"+port : "")+CORE.site_path;
		now=href.substr(now.length);
	}
	$(".menu a").filter(function(){		return $(this).attr("href")==now;	}).addClass("active");

	//Определим какие скрипты подключены
	var cut=$("head base").attr("href");
	$("head script").each(function(){		if($(this).attr("src"))
			CORE.scripts.push(this.src.indexOf(cut)==-1 ? this.src : this.src.substr(cut.length));
	});

	//CTRL + Enter для всех форм
	$("form:has(textarea)").find("textarea").keypress(function(e){
		if(e.keyCode==13 && e.ctrlKey)
			$(this).closest("form").submit();
	})
});
