$(document).ready(
	function(){
		
		/* About link */
		$('#about-link').click(
			function(){
				this.iMsg=new iMsg(
					{
						type:'about',
						title:'Обо мне',
						buttons:[],
						onBuild:function(im){
							im.msgContainer.html(
								fetchTemplate(
									'iMsg_about',
									{
										about:ABOUT_INFO,
										imgHtml:(ABOUT_INFO.img && ABOUT_INFO.img.src)?'<img src="'+PATH_FILES+'_about_r'+getRevision()+'.jpg" width="'+ABOUT_INFO.img.width+'" height="'+ABOUT_INFO.img.height+'" alt="Обо мне" id="about-img" />':''
										}
									)
								);
							}
						}
					);
				return false;
				}
			);
		
		/* Mailme link */
		$('#mailme-link').click(
			function(){
				this.iMsg=new iMsg(
					{
						type:'mailme',
						title:'Напишите мне',
						onBuild:function(ie){
							var fieldPrefix='mailme_';
							ie.msgContainer.html(fetchTemplate('iMsg_mailme',{prefix:fieldPrefix}));
							$('#mailme_firstname').focus();
							var df=new DOCUMENT_IFORM(
								{
									form:$('form',ie.msgContainer)[0],
									fieldsPrefix:fieldPrefix,
									onresult:function(fields){
										$A(
											'mailme',
											fields,
											function(res){
												ie.hide();
												}
											);
										}
									}
								);
							},
						buttons:[
							{
								caption:'Отправить',
								action:function(ie){
									$('form',ie.msgContainer).submit();									
									}
								},
							'Отменить'
							]
						}
					);
				return false;
				}
			);
		
		}
	);

function getRevision(){
	return REVISION||Math.round(Math.random()*1000);
	}

/* Displaying page
====================================*/
	function SitePageBase(){	
		}
		
	SitePageBase.prototype={		
		
		setTitle:function(title){
			return document.title=(title?String(title).html_entity_decode()+' | ':'')+SITE_NAME;
			},			
		
		redirect:function(page){
			if(!page) page="/";
			if (page.search(/^http\:\/\//i)<0){
				if (page.substr(0,1)!='/')
					page="/"+page;
				page=SITE_URL+page;
				}
			window.location=page;
			return false;
			},
			
		refresh:function(){
			window.location.reload(false);
			},
		
		GET:{},
		
		prepareHash:function(h){
			var strHash='';
			if (is_object(h)){
				var arHash=[];
				for (var pName in h){
					if ((is_string(h[pName]) || is_numeric(h[pName])) && typeof(h)!='undefined'){
						arHash.push(pName+'='+String(h[pName]));
						}					
					}
				strHash=arHash.join('&');
				}
			else if (is_string(h)){
				strHash=h;
				}
			else{
				return false;
				}
			return strHash;
			},
			
		setHash:function(h){
			var strHash=this.prepareHash(h);
			if (strHash){
				location.hash=strHash;
				}
			},	
			
		getHash:function(){
			return (decodeURI(location.hash)).substr(1);
			},
		
		getClearHashParts:function(){
			var parts=[];
			var h=this.getHash();
			if (h.length>0 && h.charAt(h.length-1)=='/'){
				h=h.substr(0,h.length-1);
				}
			if (h.length>0 && h.charAt(0)=='/'){
				h=h.substr(1);
				}
			parts=this.parts=h.split('/');
			return parts;
			},
		runApropriate:function(){
			var parts=this.getClearHashParts();
			var params=[];
			var method='run';
			while(parts.length>0){
				var m='do_'+parts.join('_');				
				if (method_exists(this,m)){
					method=m;
					break;
					}
				params.unshift(parts.pop());
				}
			this[method](params);
			},
		run:function(parts){
			alert('default run activated');
			},
		parseHash:function(){
			var 
				h=this.getHash(),
				params={};
			if (!isset(h) || h==''){
				return false;
				}
			var arHash=h.split('&');
			for (var i in arHash){
				if (!is_string(arHash[i])){
					continue;
					}
				var p=arHash[i].split('=');
				if (!p.length || p.length<2){
					continue;
					}
				params[p[0]]=p[1];
				}
			this.$GET=params;
			return params;			
			}
		
		}
		
	var SitePage=new SitePageBase();

var fetchTemplate=function(tmpl,ns){
	return _tmpl(MAIN_TEMPLATES[tmpl],ns);
	}

	

/* AboutInfo
================================================*/
	function AboutInfo(){		
		this.initialize();
		}
		
	AboutInfo.prototype={
		initialize:function(){
			this.data={};
			this._builded=false;
			this.fields={
				'phone':{
					fieldName:'phone',
					fieldTmpl:'phone',
					fieldType:'input',
					fieldLabel:'Изменить телефон'
					},
				'mail':{
					fieldName:'mail',
					fieldTmpl:'mail',
					fieldType:'input',
					fieldLabel:'Изменить адрес'
					},
				'outro':{
					fieldName:'outro',
					fieldTmpl:'itemDescription',
					fieldType:'textarea'
					},
				'description':{
					fieldName:'description',
					fieldTmpl:'itemDescription',
					fieldType:'textarea'
					},
				'counters':{
					fieldName:'counters',
					fieldTmpl:'itemDescription',
					fieldType:'textarea'
					}
				}
			},
		/* Business
		================================================*/
		getFieldProperties:function(field){
			return $.extend(
				this.fields[field],
				{
					fieldValue:this.getData(field)
					}
				);
			},
		/* Load
		================================================*/
		transport:function(todo,params,onload,onerror){
			var $this=this;
			var wasScreenBlocked=isScreenBlocked();
			blockScreenTransparent();
			this.status(STATUSMSG_LOADING);
			$A(
				todo,
				params,
				function(res){
					$this.status(STATUSMSG_LOADING_SUCCESS);
					if (!wasScreenBlocked){
						unblockScreen();
						}
					onload(res);
					},
				function(msg){							
					$this.status(TESTENV?'AboutInfo transport error: '+msg:AJAX_ERROR_MESSAGE,STATUSTYPE_ERROR);
					if (!wasScreenBlocked){
						unblockScreen();
						}					
					(onerror||onload)(null);
					}
				);
			},
		loadData:function(onload,onerror){
			var $this=this;
			this.transport(
				'AboutInfo.load',
				null,
				function(res){
					$this._builded=true;
					$this.setData(res);
					$function(onload,res);
					},
				function(msg){
					$this._builded=true;
					$function(onerror,res);
					}
				);			
			},
		
		
		status:function(msg){
			/* FIXME */
			},
		/* Base
		================================================*/
		/* getData:function(onload,property){
			var $this=this;
			if (this.isBuilded()){
				$function(onload,(property?this.data[property]:this.data));
				}
			else{
				this.loadData(
					function(){
						$this.getData(onload,property);
						}
					);
				}			
			}, */
		getData:function(property){
			if (property){
				return this.data[property];
				}
			else{
				return this.data;
				}
			},
		setData:function(data,val){
			if (!data){
				return false;
				}
			if (is_object(data)){
				for (var opt in data){
					this.data[opt]=data[opt];
					}
				}
			else{
				this.data[data]=val;
				}
			return this.data;
			},
		isBuilded:function(){
			return this._builded;
			}
		}
		
/* iMsg
================================================*/
function iMsg(data){
	this.initialize(data);
	}
iMsg.prototype={
	initialize:function(data){
		this.container=$('#imsg');
		if (!this.container.length){
			this.container=$(fetchTemplate('iMsg')).appendTo(document.body);
			}
		this.container.attr('className','').addClass('imsg');		
		var $this=this;	
		var defaultData=this.defaultData||{
			'title':'Внимание!',
			'msg':'',
			'buttons':['OK']
			}
		this.defaultButton={
			'caption':'OK',
			action:function(){
				$this.hide();
				}
			}
		this.hiddenStyle={
			'left':-3000,
			'top':0
			}
		if (BROWSER.isIE6){
			this.iframe=$('<iframe frameborder="0"></iframe>').appendTo(this.container);
			}
		this.data=$.extend(defaultData,data);
		this.titleContainer=$('.h',this.container);
		this.msgContainer=$('.cnt',this.container);
		this.buttonsContainer=$('.buttons',this.container);
		this._buttons=[];	
		this.render();
		this.show();
		
		$('h2 .close')
			.mousedown(
				function(e){
					e.stopPropagation();
					}
				)
			.click(
				function(e){
					e.stopPropagation();
					$this.hide();
					}
				);
			
		$('h2',this.container)
			.css('cursor','move')
			.mousedown(
				function(e){
					startDrag(e,this,$this.container[0],$this.data.dragSettings||{});
					}
				);
		
		},
	render:function(){
		var $this=this;
		this.reset();
		if (this.data.type){
			this.container.addClass('imsg-'+this.data.type);
			}
		this.titleContainer.html(this.data.title);
		this.msgContainer.html(this.data.msg);		
		$.each(
		   	this.data.buttons,
			function(num){
				$this.appendButton(this,num)
				}
			);		
		if (is_function(this.data.onBuild)){
			this.data.onBuild(this);
			}
		this.actualize();
		},	
	actualize:function(){		
		if (this.iframe){
			this.iframe.height($(this.msgContainer).height()+7 ).width( $(this.container).width());
			}
		},
	appendButton:function(button,num){
		var $this=this;
		button=concatObjects((button.caption || button.action)?button:{caption:String(button)},this.defaultButton);	

		var action=button.action;
		$(
		  	'<button name="btn-cancel" class="form-btn"><strong>&nbsp;&nbsp;'+button.caption+'&nbsp;&nbsp;<span class="tl"></span><span class="tr"></span><span class="br"></span><span class="bl"></span></strong></button>'
			)
			.appendTo(this.buttonsContainer)
			.focus(selfBlur)
			.click(
				function(){
					return action.call(this,$this);
					}
				);
		this._buttons.push(button);
		},
	getData:function(property){
		if (property){
			return this.data[property];
			}
		else{
			return this.data;
			}
		},		
	setData:function(data,val){
		if (!data){
			return false;
			}
		if (is_object(data)){
			for (var opt in data){
				this.data[opt]=data[opt];
				}
			}
		else{
			this.data[data]=val;
			}
		return this.data;
		},
	refresh:function(data){
		this.data=$.extend(this.data,data);
		this.render();
		},
	show:function(){
		blockScreen(true);
		putInScreenCenter(this.container[0],true);		
		///this.container.css('top',(this.container.offset().top*0.6)+'px');
		var winY=document.body.scrollTop || document.documentElement.scrollTop || 0;
		this.container.css('top',(winY+60)+'px');
		},
	hide:function(){
		unblockScreen();
		this.container.css(this.hiddenStyle);
		},
	reset:function(){
		this.buttonsContainer.empty();
		this._buttons=[];
		}
	}
	
/* Viewer
================================================*/
var picViewer=(
	function PicViewer(data){
		var $this=this;
		data.dragSettings={
			oncomplete:function(){
				$this.saveShowStyle();	
				}
			,onmove:function(){
				resizeBlockScreen();
				}
			};
		this.initialize(data);		
		}
	).inheritsFrom(iMsg);
	
	$.extend(
		picViewer.prototype,
		{			
			saveShowStyle:function(){
				
				var wh=$where(this.container);	
				var xCenter=document.documentElement.offsetWidth/2;
				var winY=document.body.scrollTop || document.documentElement.scrollTop || 0;
				this.showStyle={
					top:wh.top,
					left:wh.left,
					yOffset:wh.top-winY,
					xCenterOffset:wh.left-xCenter,
					xCenter:wh.left+$(this.container).width()/2
					};
				return this.showStyle;
				},
			render:function(){
				var $this=this;
				this._parentMethod('render');		
				//this.msgContainer.html('test');
				if (!this.prevArrow){
					this.prevArrow=$('<span class="prevnext prevnext-prev"></span>')
						.appendTo(this.container)
						.click(
							function(){
								if ($this.data.onPrevClick){
									$function($this.data.onPrevClick());
									}
								}
							);						
					}
				if (!this.nextArrow){
					this.nextArrow=$('<span class="prevnext prevnext-next"></span>')
						.appendTo(this.container)
						.click(
							function(){
								if ($this.data.onNextClick){
									$function($this.data.onNextClick());
									}
								}
							);
					}
				},
			show:function(){
				/* if (this._isShow){
					return;
					} */
				//this.container.show();
				blockScreen(true);
				var winY=document.body.scrollTop || document.documentElement.scrollTop || 0;
				if (!this.showStyle){					
					putInScreenCenter(this.container,true);
					///this.container.css('top',(this.container.offset().top*0.6)+'px');					
					this.container.css('top',(winY+60)+'px');
					//this.saveShowStyle();
					}
				else{
					var xCenter=document.documentElement.offsetWidth/2;
					this.container.css(
						{			   
							top:winY+this.showStyle.yOffset,
							left:Math.max(this.showStyle.xCenter-$(this.container).width()/2,0)
							}
						);
					}				
				this._isShow=true;
				resizeBlockScreen();
				},
			
			hide:function(){
				//this.saveShowStyle();
				this._parentMethod('hide');
				//unblockScreen();
				//this.container.hide();
				this._isShow=false;				
				}
			}
		);
		
/* Pulldown
================================================*/
	function Pulldown(handler,type){
		var $this=this;
		this.handler=$(handler);
		this.type=type||'';
		if (!this.handler.length){
			return false;
			}		
		this.render();
		if (!Pulldown.initialized){
			$(document.body).click(
				function(){					
					$this.hideElseOther(true);
					
					}
				);
			Pulldown.initialized=true;
			}		
		}
	Pulldown.prototype={
		render:function(){
			var $this=this;			
			var id='pulldown_'+(Math.round(Math.random()*10000));
			this.body=$('<div class="pulldown'+(this.type?' pulldown-'+this.type:'')+'" id="'+id+'"></div>')
				.appendTo('#main')
				.css(
					{
						position:'absolute',
						display:'none',
						zIndex:1000
						}					
					)
				.click(
					function(e){
						e.stopPropagation();
						}
					);
			if (!Pulldown._global){
				Pulldown._global={};
				}
			Pulldown._global[id]=this.body;
			$(window).resize(
				function(){
					$this.actualize();
					}
				);
			this.actualize();			
			//this.hideElseOther();
			},
		actualize:function(){
			var wh=$where(this.handler[0]);
			var offsetRight=0;
			var offsetTop=0;
			
			if (this.type=='light'){
				offsetRight=-75;
				offsetTop=-26;
				}
			else if (this.type=='filter'){
				offsetRight=5;
				offsetTop=-10;
				}
			$(this.body).css(
				{
					right:$(document.body).width()-wh.right+offsetRight,
					top:wh.bottom+offsetTop
					}
				);
			},
		toggle:function(){			
			this.hideElseOther();
			this.actualize();
			this.body.slideToggle('fast');
			},
		hide:function(){
			this.actualize();
			this.body.slideUp('fast');
			},
		hideElseOther:function(force){
			var id=this.body[0]['id']||null;
			if (Pulldown._global){
				$.each(
					Pulldown._global,
					function(nam){						
						if (force || !id || nam!=id){
							this.hide();
							}
						}
					)				
				}
			}
		}
		
/* Rolling
=================================================*/
function iRolling(container){
	this.container=container;
	this.initialize();
	}
	
iRolling.prototype={
	initialize:function(){
		
			this.ARROWDISABLED_CLASS='arrow-disabled';
			
			this._inAction=false;
			this._interval=null;
			this._timeStep=10;
			this._defaultMoveStep=6;
			this._moveStep=this._defaultMoveStep;
			this._movingByCursor=false;
			this._stepByCursor=this._defaultMoveStep;
			this._mouseSensitivity=0.005;
			this.apropriateItemWidth=75;
		
		var 
			$this=this,			
			coreWrapper=this.coreWrapper=$('.rolling-core',this.container)[0],
			core=this.core=$('ul',coreWrapper)[0],			
			arrowLeft=this.arrowLeft=$('.arrow-left',this.container)[0],
			arrowRight=this.arrowRight=$('.arrow-right',this.container)[0];
		if (arrowLeft){
			arrowLeft.direction=1;
			}
		if (arrowRight){
			arrowRight.direction=-1;
			}
		if (!core || !coreWrapper || !arrowLeft || !arrowRight){
			return false;
			}
		if (!this.isNeedRolling()){
			this.cancelRolling()
			return false;
			}
		$([arrowLeft,arrowRight]).mousedown(
			function(){				
				$this.move(this.direction);				
				return false;
				}
			);
		$(document).mouseup(
			function(){
				$this.stop();
				$this.actualize();
				return false;
				}
			);
		$(window).resize(
			function(){
				$this.actualize();
				}
			);
		if (this._movingByCursor){
			$(this.coreWrapper)
				.mouseover(
					function(e){					
						$this.moveByCursor(e);
						}
					)
				.mousemove(
					function(e){
						$this.moveByCursor(e);
						}
					)
				.mouseout(
					function(){
						$this.stop();
						}
					);
			}
		//this.setRandomPosition();
		},
	isNeedRolling:function(){
		var wrapWidth=$(this.coreWrapper).width();
		var coreWidth=$(this.core).width();
		var apropriateCoreWidth=($(this.core).children().length*this.apropriateItemWidth);
		return (wrapWidth<apropriateCoreWidth)
		},
	cancelRolling:function(){
		$(this.arrowLeft).hide();
		$(this.arrowRight).hide();
		$(this.container).removeClass('rolling');
		},
	actualize:function(){
		var pos=this.getPosition();
		var 
			aLeft=$('span',this.arrowLeft),
			aRight=$('span',this.arrowRight),
			cl=this.ARROWDISABLED_CLASS;

		if ( ( (pos.x>=pos.maxX && this.arrowLeft.direction==-1) || (pos.x<=pos.minX && this.arrowLeft.direction==1) )){
			aRight.addClass(cl);
			}
		else if (aRight.hasClass(cl)){
			aRight.removeClass(cl);
			}
		if ((pos.x<=pos.minX &&  this.arrowLeft.direction==-1 || pos.x>=pos.maxX && this.arrowLeft.direction==1)){
			aLeft.addClass(cl);
			}
		else if (aLeft.hasClass(cl)){
			aLeft.removeClass(cl);
			}
		
		},
	moveByCursor:function(e){
		
		this.setStepByCursor(e);
		if (this.isInAction()){			
			return false;
			} 
		var 
			$this=this;			
		
		//this.stop();
		clearInterval(this._interval);
		this._interval=null;
		this._interval=setInterval(
			function(){
				//$id('status').innerHTML+='interval ';
				//$this.setStepByCursor();
				
				/* if (step<0.5){
					step=0;
					} */
				$this.step($this._stepByCursor);
				},
			$this._timeStep
			);
		$this._inAction=true;
		
		},
	setStepByCursor:function(e){
		var 
			hCenter=$(this.coreWrapper).width()/2,
			wrapperPos=$where(this.coreWrapper),
			cursorPos=getWhereIsEvent(e),
			pos={
				left:cursorPos.left-wrapperPos.left,
				top:cursorPos.top-wrapperPos.top
				},
			direction=(pos.left>hCenter?-1:1),
			step=Math.abs(pos.left-hCenter)*this._mouseSensitivity;
		this._stepByCursor=direction*step;

		return this._stepByCursor;
		},
	move:function(direction){
		var $this=this;
		if (!direction){
			direction=1;
			}
		if (this.isInAction()){
			return false;
			}

		this._interval=setInterval(
			function(){
				$this.step(direction*$this._moveStep);			
				},
			$this._timeStep
			);
		$this._inAction=true;
		
		},
	step:function(x){
		var pos=this.getPosition();
		$(this.core).css('left',(Number(pos.x+x)).between(pos.minX,pos.maxX));
		this.actualize();
		},
	getPosition:function(){
		var x=$(this.core).css('left');
		if (x.slice(-2)=='px'){
			x=Number(x.slice(0,-2));
			}
		else if (isNaN(Number(x))){
			x=0;
			}
		return {
			x:x,
			minX:$(this.coreWrapper).width()-$(this.core).width(),
			maxX:0
			};
		},
	setRandomPosition:function(){
		var 
			minVisibleChildren=3,
			children=$(this.core).children(),
			rcNum=Math.floor(Math.random()*(children.length-minVisibleChildren)),
			rc=children[rcNum];
		$(this.core).css('left',-rc.offsetLeft);
		this.actualize();
		},	
	setPositionToItem:function(rcNum){		
		var 
			minVisibleChildren=5,
			children=$(this.core).children();
		rcNum=Number(rcNum-2).between(0,Math.max(0,children.length-minVisibleChildren));
		var rc=children[rcNum];
		$(this.core).css('left',-rc.offsetLeft);
		this.actualize();
		},
	stop:function(){
		var $this=this;
		if (!this.isInAction()){
			return false;
			}
		clearInterval(this._interval);
		this._interval=null;
		$this._inAction=false;
		},
	isInAction:function(){
		return this._inAction;
		}
	}
	
var iRollingVertical=( 
	function(container,data){	
		this.container=container;
		this.apropriateItemHeight=50;
		this._mouseSensitivity=0.015;
		this.data=data;
		this.initialize();
		}
	).inheritsFrom(iRolling);
	$.extend(
		iRollingVertical.prototype,
		{
			isNeedRolling:function(){
				var wrapHeight=$(this.coreWrapper).height();
				var coreHeight=$(this.core).height();
				var apropriateCoreHeight=($(this.core).children().length*this.apropriateItemHeight);
				return (wrapHeight<apropriateCoreHeight || wrapHeight<coreHeight)
				},
			cancelRolling:function(){
				$(this.arrowLeft).hide();
				$(this.arrowRight).hide();
				$(this.container).removeClass('rolling');
				$(this.coreWrapper).removeClass('rolling-core');
				if (this.data && this.data.oncancel && is_function(this.data.oncancel)){
					this.data.oncancel(this);
					}
				},
			actualize:function(){
				var pos=this.getPosition();
				var 
					aLeft=$('span',this.arrowLeft),
					aRight=$('span',this.arrowRight),
					cl=this.ARROWDISABLED_CLASS;
		
				if ( ( (pos.y>=pos.maxY && this.arrowLeft.direction==-1) || (pos.y<=pos.minY && this.arrowLeft.direction==1) )){
					aRight.addClass(cl);
					}
				else if (aRight.hasClass(cl)){
					aRight.removeClass(cl);
					}
				if ((pos.y<=pos.minY &&  this.arrowLeft.direction==-1 || pos.y>=pos.maxY && this.arrowLeft.direction==1)){
					aLeft.addClass(cl);
					}
				else if (aLeft.hasClass(cl)){
					aLeft.removeClass(cl);
					}
				
				},
			getPosition:function(){
				var y=$(this.core).css('top');
				if (y.slice(-2)=='px'){
					y=Number(y.slice(0,-2));
					}
				else if (isNaN(Number(y))){
					y=0;
					}
				return {
					y:y,
					minY:$(this.coreWrapper).height()-$(this.core).height(),
					maxY:0
					};
				},
			setStepByCursor:function(e){
				var 
					hCenter=$(this.coreWrapper).height()/2,
					wrapperPos=$where(this.coreWrapper),
					cursorPos=getWhereIsEvent(e),
					pos={
						left:cursorPos.left-wrapperPos.left,
						top:cursorPos.top-wrapperPos.top
						},
					direction=(pos.top>hCenter?-1:1),
					step=Math.abs(pos.top-hCenter)*this._mouseSensitivity;
				this._stepByCursor=direction*step;
		
				return this._stepByCursor;
				},
			step:function(y){
				var pos=this.getPosition();
				$(this.core).css('top',(Number(pos.y+y)).between(pos.minY,pos.maxY));
				this.actualize();
				},
			setPositionToItem:function(rcNum){		
				var 
					minVisibleChildren=5,
					children=$(this.core).children();
				rcNum=Number(rcNum-2).between(0,Math.max(0,children.length-minVisibleChildren));
				var rc=children[rcNum];
				$(this.core).css('top',-rc.offsetTop);
				this.actualize();
				}
			}					
		);