$(function(){	
    var scroll= cookie('scroll');
    if(scroll){
    	window.scrollTo(0,scroll);
    	cookie('scroll',0);
    };
	$('.storepos').mousedown(function(){
	    cookie('scroll'
	    	,(window.scrollY) ? window.scrollY : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop
	    	,{ expires:10000})
	});
	$("#debug").ajaxError(function(event, request, settings){
		$(this).append("<li>Error requesting page " + settings.url + "<"+"/li>");
	});
function WindowO(e,s,w,h)
{
	var $x=$(e).attr('href');
//	if($x && ($x.length>2)) { return true;}
	if(s.match(/\/$/)) return false ;
	try{
	  var par="location=no,toolbar=no,resizable=yes";
	  if((w+100>window.screen.width)||(h+100>window.screen.height))
	  	par+=",scrollbars=yes"
  	  par+=',width='+(w||100); 
 	  par+=',height='+(h||100);
	  wind=open("","win",par);
	  wind.document.writeln('<html>'+
		'<head><title><'+'/title><style>body,html{width:100%;height:100%;padding:0;margin:0;}\n'+
		'body{overflow:auto;}\n</'+'style>\n<'+'script>function fitPic(){'+
	 	'iWidth = window.innerWidth||document.body.clientWidth;'+
	 	'iHeight = window.innerHeight||document.body.clientHeight;'+
		'iWidth = document.images[0].width - iWidth;'+
		'iHeight = document.images[0].height - iHeight;'+
		'if(iWidth && iHeight)window.resizeBy(iWidth,iHeight);self.focus();'+
		//'alert([window.screen.height,window.screen.width, iWidth,iHeight,document.images[0].width,window.innerWidth,document.body.clientWidth]);'+
		'};</'+'script>'+
		'<'+'/head><'+'body onload="fitPic()">'+
		'<img src="'+s+'"><button style="position:absolute;right:10px;bottom:10px;" '+
		'onclick="self.close();">close</button><'+'/body><'+'/html>');
	  wind.document.close();
	} catch(e) {
	  alert('Всплывающие окна заблокированы! Разрешите всплывающие окна для нормального функционирования.')
	}
	return false;
};window.WindowO=WindowO;
    $first=null;
	$('.galleryX a').each(function(){
		if(this.href && this.href.match(/\.(jpe?g|png|gif)/)) {
		    this.__done=true;
		    $(this).click(function(){ 
				var t=$(this).parents('.galleryX').find('img')[0];
				t.src=this.href;
				return false
			})
			if(!$first){
				$first=true;
				$(this).click();
			}
			
		}			
	})
	$first=null;
	$('.gallery a, .cat_border a').removeAttr('onclick').each(function(){
		if(this.href && this.href.match(/\.(jpe?g|png|fig)/)) {
			if(!this.__done)
				if($.fn.colorbox)
					$(this).colorbox();
				else				
					$(this).click(function(){return WindowO(this,this.href)});
		} else if(this.href && this.href.match(/#$|uploaded\/$/)) {
			$x=$(this).html();
			if($x)
				$(this).replaceWith($x);
		}
		$(this).find('img').bind('load',checkImg).each(function(){
			if(this.complete)
				checkImg(this);
		});
	});
	$(window).resize(function(){
		$('.wideable').css({width:200,visibility:'hidden'}).each(function(){
			var self=this;
			var interval=setInterval(function(){
				var width=self.parentNode.clientWidth||self.parentNode.scrollWidth;
				if(!width)
					width=self.parentNode.parentNode.clientWidth;
				if(!width){
					//$('#debug').html($('#debug').html()+self.parentNode.tagName);
					clearInterval(interval);
					return;
				}
				//$('#debug').html($('#debug').html()+'<br>'+width)
				clearInterval(interval);
				$(self).css({visibility:'visible',width: width});
				self=null;
			},50)
		})		
	}).trigger('resize');
	$('.scroll_gal').each(function(){
		
		var div,lock;
		
		var  mousemove =function(e){
			if(lock)return;
		    var left = Math.max(0,(e.pageX - div.offset().left) * (this.scrollWidth-this.clientWidth) / this.clientWidth);
			if(Math.abs(div.scrollLeft()-left)>30){
				lock=true;
				div.stop(true,false).animate({ scrollLeft:left},100,function(){lock=false});
			} else
		    	div.scrollLeft(left);
		  };
		
		$(this).hover(
			function(){ div=$(this);$(this).bind('mousemove',mousemove)},
			function(){div=null;$(this).unbind('mousemove')}
		);		
	})
	$('a.url_page').click(function(){
		if(this.href && !this.href.match(/javascript/i)){
			var self=this,parent=$(this).parents('.para')[0];
			function clickit(e){
				if(e && self) return false;
			    $(this).find('.back').toggleClass('hidden');
			  	$(this.container).toggle('normal');
				//    $('#debug').append("<li>click "+ "<"+"/li>");
				return false;
			}
			$.getJSON(this.href.replace('ajax=1','').replace(/(do=\w*)/,'$1&ajax=1'),function(data){
				if(data.error) alert(data.error);
				if(data.debug) alert(data.debug);
				if(data.data) {
				    self.container=$('<div class="ainfo"></div>').insertAfter($(parent)).hide().html(data.data)[0];
//				    $('#debug').append("<li>click "+ "<"+"/li>");
				    clickit.apply(self);
				    self=null;
				} 
			})
			this.href='javascript:;';
			$(this).click(clickit);
		}
   		return false;	
	})// init menu
menu('#searchbar',{
	show:function(){$(this).show('hormal',function(){
		$('#search_string').focus();
	})},
	hide:function(){$(this).hide('hormal')}
});
window.showsearchbar=function (){
	var x=$('#searchbar')[0];
	if(!x.shown)
		x.show_menu();
	return false;
};
})	
// поставить куку cookie.
function cookie(name,value,opt){
	if (typeof value != 'undefined') { // name and value given, set cookie
		opt = opt || {};
		if (value === null) {
			value = '';
			opt.expires = -1;
		}
		var expires = '';//expires:10
		if (opt.expires && (typeof (opt.expires) == 'number' || opt.expires.toUTCString)) {
			var date;
			if (typeof opt.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + Math.round(opt.expires * 24 * 60 * 60 * 1000));
			}
			else {
				date = opt.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		document.cookie = name + '=' + encodeURIComponent(value) + expires +
			(opt.path ? '; path=' + opt.path : '') +
			(opt.domain ? '; domain=' + opt.domain : '') +
			(opt.secure ? '; secure' : '')
	}
	else { // only name given, get cookie
		if (document.cookie && document.cookie != '') {
			var cook = (new RegExp(";\\s*" + name + "\\s*=([^;]+)")).exec(';' + document.cookie);
			return cook && decodeURIComponent(cook[1]);
		}
		return null;
	}
};function checkImg(el,width,height){
    if(!el || !el.src) return ;
	var Img=new Image();
	var load_function= function(){
		Img.onload = null;
		if(!!this.__lastTry && (this.width==0 || this.height==0)){
			this.__lastTry=true;
			setTimeout(load_function,100); return;
		}
		if(this.width && this.height) {
			if(!width) if(el.style.width) width=parseInt(el.style.width);
			if(!height) if(el.style.height) height=parseInt(el.style.height);
			// looks like loaded!
			var k=1; // 1 - вписываем 0 - расширяем по габаритам
			if(width) k=Math.max(k,Img.width/width); else width=Img.width;
			if(height) k=Math.max(k,Img.height/height); else height=Img.height;
			if(!k) k=1;
	//		if (Img.width>width || Img.height>height){
				el.style.width=Math.round(Img.width/k)+'px';
				el.style.height=Math.round(Img.height/k)+'px';
	//		}
		}
		Img=null;
		load_function=null;
	}
	Img.onload=load_function;
	Img.src=el.src;
}/**
 * Установка выпадающего меню
 */
function menu(_self,param){
    if(!param) param={};
    else if(typeof(param)=='function')
    	param={show:param};
    if(!(_self=$(_self)[0])) return;	
    	
	function checkMouse (e){
	     var el = e.target;
	     while (true){
			if (el == _self) {
				return true;
			} else if (el == document) {
				hide_menu();
				return false;
			} else {
				el = el.parentNode;
			}
		}
	};
	
	function show_menu(){
	  if(param.show) param.show.apply(_self);
	  else $(_self).show();
	  _self.shown=true;
	  $(document).bind('mousedown', checkMouse);
	  return false;
	};
	
	function hide_menu(){
	  $(document).unbind('mousedown', checkMouse);	
	  if(param.hide)
	  	param.hide.apply(_self);
	  else
	  	$(_self).hide();
	  _self.shown=false;
	  return false;
	};
	_self.show_menu=show_menu;
	_self.hide_menu=hide_menu;
	$(window).bind('unload', function(){_self=null});
};

