/* Popup messages */
(function($){$.jGrowl=function(m,o){if($('#jGrowl').size()==0)
$('<div id="jGrowl"></div>').addClass($.jGrowl.defaults.position).appendTo('body');$('#jGrowl').jGrowl(m,o);};$.fn.jGrowl=function(m,o){if($.isFunction(this.each)){var args=arguments;return this.each(function(){var self=this;if($(this).data('jGrowl.instance')==undefined){$(this).data('jGrowl.instance',$.extend(new $.fn.jGrowl(),{notifications:[],element:null,interval:null}));$(this).data('jGrowl.instance').startup(this);}
if($.isFunction($(this).data('jGrowl.instance')[m])){$(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'),$.makeArray(args).slice(1));}else{$(this).data('jGrowl.instance').create(m,o);}});};};$.extend($.fn.jGrowl.prototype,{defaults:{pool:0,header:'',group:'',sticky:false,position:'top-left',glue:'after',theme:'default',corners:'10px',check:250,life:3000,speed:'normal',easing:'swing',closer:true,closeTemplate:'&times;',closerTemplate:'<div>[ '+t('CloseAll')+' ]</div>',log:function(e,m,o){},beforeOpen:function(e,m,o){},open:function(e,m,o){},beforeClose:function(e,m,o){},close:function(e,m,o){},animateOpen:{opacity:'show'},animateClose:{opacity:'hide'}},notifications:[],element:null,interval:null,create:function(message,o){var o=$.extend({},this.defaults,o);this.notifications.push({message:message,options:o});o.log.apply(this.element,[this.element,message,o]);},render:function(notification){var self=this;var message=notification.message;var o=notification.options;var notification=$('<div class="jGrowl-notification ui-state-highlight ui-corner-all'+
((o.group!=undefined&&o.group!='')?' '+o.group:'')+'">'+'<div class="close">'+o.closeTemplate+'</div>'+'<div class="header">'+o.header+'</div>'+'<div class="message pt10">'+message+'</div></div>').data("jGrowl",o).addClass(o.theme).children('div.close').bind("click.jGrowl",function(){$(this).parent().trigger('jGrowl.close');}).parent();$(notification).bind("mouseover.jGrowl",function(){$('div.jGrowl-notification',self.element).data("jGrowl.pause",true);}).bind("mouseout.jGrowl",function(){$('div.jGrowl-notification',self.element).data("jGrowl.pause",false);}).bind('jGrowl.beforeOpen',function(){if(o.beforeOpen.apply(notification,[notification,message,o,self.element])!=false){$(this).trigger('jGrowl.open');}}).bind('jGrowl.open',function(){if(o.open.apply(notification,[notification,message,o,self.element])!=false){if(o.glue=='after'){$('div.jGrowl-notification:last',self.element).after(notification);}else{$('div.jGrowl-notification:first',self.element).before(notification);}
$(this).animate(o.animateOpen,o.speed,o.easing,function(){if($.browser.msie&&(parseInt($(this).css('opacity'),10)===1||parseInt($(this).css('opacity'),10)===0))
this.style.removeAttribute('filter');$(this).data("jGrowl").created=new Date();});}}).bind('jGrowl.beforeClose',function(){if(o.beforeClose.apply(notification,[notification,message,o,self.element])!=false)
$(this).trigger('jGrowl.close');}).bind('jGrowl.close',function(){$(this).data('jGrowl.pause',true);$(this).animate(o.animateClose,o.speed,o.easing,function(){$(this).remove();var close=o.close.apply(notification,[notification,message,o,self.element]);if($.isFunction(close))
close.apply(notification,[notification,message,o,self.element]);});}).trigger('jGrowl.beforeOpen');if($.fn.corner!=undefined)$(notification).corner(o.corners);if($('div.jGrowl-notification:parent',self.element).size()>1&&$('div.jGrowl-closer',self.element).size()==0&&this.defaults.closer!=false){$(this.defaults.closerTemplate).addClass('jGrowl-closer ui-state-highlight ui-corner-all').addClass(this.defaults.theme).appendTo(self.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){$(this).siblings().children('div.close').trigger("click.jGrowl");if($.isFunction(self.defaults.closer)){self.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);}});};},update:function(){$(this.element).find('div.jGrowl-notification:parent').each(function(){if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl.pause")==undefined||$(this).data("jGrowl.pause")!=true)){$(this).trigger('jGrowl.beforeClose');}});if(this.notifications.length>0&&(this.defaults.pool==0||$(this.element).find('div.jGrowl-notification:parent').size()<this.defaults.pool))
this.render(this.notifications.shift());if($(this.element).find('div.jGrowl-notification:parent').size()<2){$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose,this.defaults.speed,this.defaults.easing,function(){$(this).remove();});}},startup:function(e){this.element=$(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');this.interval=setInterval(function(){$(e).data('jGrowl.instance').update();},this.defaults.check);if($.browser.msie&&parseInt($.browser.version)<7&&!window["XMLHttpRequest"]){$(this.element).addClass('ie6');}},shutdown:function(){$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();clearInterval(this.interval);},close:function(){$(this.element).find('div.jGrowl-notification').each(function(){$(this).trigger('jGrowl.beforeClose');});}});$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults;})(jQuery);

/*scrollto*/
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/* color animate */
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(g.state==0){g.start=c(g.elem,e);g.end=b(g.end)}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);

/*
 * Эффект для кликабельных блочных объектов 
 */
(function($){
	$.fn.burstClick = function(params){
		params = $.extend( {width : 50, color : 'orange', duration: 500}, params); 
		this.each(function() {
			var $object = $(this);
			
			$object.click(function(){
				// создаём релативный слой
				var $parent = $('<div></div>').css({'position':'relative'});
				// создаём и помещаем в него абсолютный слой
				var $absolute = $('<div></div>').css(
					{
						'position' : 'absolute',
						'top' : 0,
						'left' : 0,
						'width' : $object.width() + 'px',
						'height' : $object.height() + 'px',
						'z-index': 1
					}
				);
				
				// если наш объект сдвинут внутри родительского
				var _top = $object.css('marginTop');
				var _left = $object.css('marginLeft');
				$absolute.css({
						'left' : _left?_left:0,
						'top' : _top?_top:0,
						'borderColor' : params.color
					});
				
				$absolute.addClass('radius10');
				
				$object.parent().prepend($parent);
				// и туда же помещаем исходный блок
				$object.appendTo($parent);
				$object.css({'z-index':'100','position':'relative'});

				$absolute.appendTo($parent);
	
				// описание анимации
				_top = parseInt($absolute.css('top'));
				_left = parseInt($absolute.css('left'));
				var _width = parseInt($absolute.css('width'));
				var _height = parseInt($absolute.css('height'));
				$absolute.css('backgroundColor',params.color);
					
				var _width_new = (1 + params.width / 100) * _width;
				var _x = _width_new - _width;
				var _height_new = (1 + params.width / 100) * _height;
				var _y = _height_new - _height;
				
				$absolute.animate({
						'top' : _top - parseInt(_y / 2),
						'left' : _left - parseInt(_x / 2),
						'width' : _width_new,
						'height' : _height_new,
						'opacity' : 0
					}, {
							duration: params.duration, 
							complete: function(){
								console.log( $absolute.remove() );
							},
							specialEasing: {
						      width: 'easeOutElastic',
						      height : 'easeOutElastic',
						      left: 'easeOutElastic',
						      top: 'easeOutElastic',
						      opacity: 'linear'
							}
						}
				);
				
			});
		});
		return this;
	}
}(jQuery))

this.vtip = function() {    
    this.xOffset = -10; // x distance from mouse
    this.yOffset = 30; // y distance from mouse       
    
    $(".vtip").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            $('body').append( '<p id="vtip"><img id="vtipArrow" />' + this.t + '</p>' );
            $('p#vtip #vtipArrow').attr("src", '/images/vtip_arrow.png');
            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").show();
        },
        function() {
            this.title = this.t;
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
                         
            $("p#vtip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};


/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 */
// eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([237-9n-zA-Z]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(s(m){3.fn.pngFix=s(c){c=3.extend({P:\'blank.gif\'},c);8 e=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 5.5")!=-1);8 f=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 6.0")!=-1);p(3.browser.msie&&(e||f)){3(2).B("img[n$=.C]").D(s(){3(2).7(\'q\',3(2).q());3(2).7(\'r\',3(2).r());8 a=\'\';8 b=\'\';8 g=(3(2).7(\'E\'))?\'E="\'+3(2).7(\'E\')+\'" \':\'\';8 h=(3(2).7(\'F\'))?\'F="\'+3(2).7(\'F\')+\'" \':\'\';8 i=(3(2).7(\'G\'))?\'G="\'+3(2).7(\'G\')+\'" \':\'\';8 j=(3(2).7(\'H\'))?\'H="\'+3(2).7(\'H\')+\'" \':\'\';8 k=(3(2).7(\'V\'))?\'float:\'+3(2).7(\'V\')+\';\':\'\';8 d=(3(2).parent().7(\'href\'))?\'cursor:hand;\':\'\';p(2.9.v){a+=\'v:\'+2.9.v+\';\';2.9.v=\'\'}p(2.9.w){a+=\'w:\'+2.9.w+\';\';2.9.w=\'\'}p(2.9.x){a+=\'x:\'+2.9.x+\';\';2.9.x=\'\'}8 l=(2.9.cssText);b+=\'<y \'+g+h+i+j;b+=\'9="W:X;white-space:pre-line;Y:Z-10;I:transparent;\'+k+d;b+=\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;\';b+=\'J:K:L.t.M(n=\\\'\'+3(2).7(\'n\')+\'\\\', N=\\\'O\\\');\';b+=l+\'"></y>\';p(a!=\'\'){b=\'<y 9="W:X;Y:Z-10;\'+a+d+\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;">\'+b+\'</y>\'}3(2).hide();3(2).after(b)});3(2).B("*").D(s(){8 a=3(2).11(\'I-12\');p(a.A(".C")!=-1){8 b=a.13(\'url("\')[1].13(\'")\')[0];3(2).11(\'I-12\',\'none\');3(2).14(0).15.J="K:L.t.M(n=\'"+b+"\',N=\'O\')"}});3(2).B("input[n$=.C]").D(s(){8 a=3(2).7(\'n\');3(2).14(0).15.J=\'K:L.t.M(n=\\\'\'+a+\'\\\', N=\\\'O\\\');\';3(2).7(\'n\',c.P)})}return 3}})(3);',[],68,'||this|jQuery||||attr|var|style||||||||||||||src|navigator|if|width|height|function|Microsoft|appVersion|border|padding|margin|span|px|indexOf|find|png|each|id|class|title|alt|background|filter|progid|DXImageTransform|AlphaImageLoader|sizingMethod|scale|blankgif|appName|Internet|Explorer|parseInt|MSIE|align|position|relative|display|inline|block|css|image|split|get|runtimeStyle'.split('|'),0,{}))

function message(m,type){
	
	data = {};
	
	switch(type){
		case 'sticky':
			data.sticky = true;
			break;
	}
	$.jGrowl(m,data);
}

function msgbox(msg,type){
	message(msg,type);
}
/*end of messages*/


/* generate select object by json data */
function generateSelect(data,id,name,selected,width,height){
	
	$select = $('<select>');

	if(typeof width != 'undefined'){
		$select.addClass('w' + width);
	}	

	if(typeof heigth != 'undefined'){
		$select.addClass('h' + height);
	}else{
		$select.addClass('h25');
	}		
	
	var length = data.length;
	for(row in data){
		$select.append('<option value="'+ data[row].value + '">' + data[row].title + '</option>');
	}
	$select.attr('id',id);
	
	/* если нужно создать массив для пост запроса */
	if(typeof name != undefined){
		$select.attr('name', name);
	}else{
		$select.attr('name', id);
	}
	
	return $select;
}


/* set indicator img */
function setIndicatorImg(id_container){
	$('#'+id_container).html('<img src="/images/indicator.gif"');
} 

/* */
function reload(){
	window.document.location.href = window.location.toString().replace('#', '');
}

function refreshCaptcha(name, container){
	if( typeof container == 'undefined'){
		id = '#captcha';
	}else{
		id = '#' + container;
	}
	
	$(id).html('<img src="/images/indicator.gif"');
		
	$.get('/captcha?' + (new Date()).getTime(),
			function(data){
				$(id).html(data.html);
				$('#' + name + '_id').val(data.id);
			},'json');	

}

/* wait box */
waitBox = {
	container: null,
	indicator: null,
	options:{
		
	},
	init: function(){
		
		if(this.container != null){
			return;
		}
		$wb = $('<div></div>');
		$wb.css({
			'display':'none',
			'top':0,
			'left':0,
			'position': 'absolute',
			'backgroundColor': '#000',
			'opacity': 0.7
		});
		
		$img = $('<img/>');
		$img.attr('src','/images/indicator.gif');
		
		$indicator = $('<div></div>');
		this.indicator = $indicator; 		
		
		$indicator.append($img);
		$wb.append($indicator);
		$('body').append($wb);
		this.container = $wb;
		
	},
	show: function(){
		
		var width = $(document).width();
		var height = $(document).height();
		
		this.indicator.css({
				'marginLeft': ((width / 2) - 10) + 'px',
				'marginTop': ($(window).height() / 2 + $(document).scrollTop()) + 'px'
			});
		
		this.container.css({
				'width': width + 'px',
				'height': height + 'px'
			});
		//this.container.css({'display':'block'});
		this.container.show();
		
	},
	hide: function(){
		this.container.css({'display':'none'});
	}
}; 


/* auto ajax handlers */

function auto_ajax_handlers(){
	
	$('a.call').live('click',function(){
			var link = this;
			
			//check rel
			var rel = $(this).attr('rel');

			waitBox.show();	
			
			$.ajax({
			        type: 'GET',
			        url:  $(this).attr('href') + (rel?'/rel/' + rel:''),
			        dataType: 'json',
			        cache : false,
			        success: function(data, textStatus, xhr){
			            if (xhr.readyState === 4 && xhr.status === 0) {
			    			waitBox.hide();
			    			message(t('NetworkErrors'));
			            }
			            else {
		
			            	if(typeof data.message != 'undefined'){
								message(data.message);
							}
							if(typeof data.url != 'undefined' && data.url.length){
								$(link).attr('href',data.url);
							}
							if(typeof data.text != 'undefined'){
								$(link).html(data.text);
							}

							if(typeof data.rel != 'undefined'){
								// change all relative elements
								for(id in data.rel){
									$('#' + id).html(data.rel[id].text);
									if(typeof data.rel[id]['class'] != 'undefined'){
										if(typeof data.rel[id].class_remove != 'undefined' && data.rel[id].class_remove.length)
											$('#' + id).removeClass(data.rel[id].class_remove);
										$('#' + id).addClass(data.rel[id]['class']);
									}
								}
							}
							
							
							waitBox.hide();	            	
			            	
			            }
			        },
			        error: function(xhr, textStatus, errorThrown) {
						waitBox.hide();
						message(t('ServerErrors'));
			        }
			   });
			
			return false;
	});			
}

/* Do all */
$(function(){
	
	waitBox.init();
	auto_ajax_handlers();
});


/*
 * Код шаблона сайта.
 * 1. Меню выбора типа поиска
 * 2. Меню выбора регионов
 * 3. Карусель - популярные товары
 */
var cWindows = new Array();
var searchTypeSelector = false;

function regionSelector() {
	
	closeLoginForm();
	var $div = $('#regions_list');
	if ($div.length == 1) {
		$('#region').append($div);
		$div.show();
		$div.removeClass('hide');
		cWindows[cWindows.length] = 'regions_list';
	}
	return true;
}

function showSearchTypes(o) {
	$('li.hide', $(o).parent().parent()).removeClass('hide');
}

function hideSearchTypes() {
	$('li', 'ul#srch_type_selector').each(function() {
		if (!$(this).hasClass('selected')) {
			$(this).addClass('hide');
		} else {
			$(this).removeClass('hide');
		}
	});	
	return;
}

function hideSearchTypeSelector() {
	if (searchTypeSelector) {
		hideSearchTypes();
	}
}

function selectSearchType(o) {
	if (!$(o).parent().hasClass('selected')) {
		
		var $li = $(o).parent();
		var $li_s = $('.selected', $li.parent());
		
		//get rels
		$rel1 = $('a', $li).attr('rel');
		$rel2 = $('a', $li_s).attr('rel');
		
		// li to the top of list
		$a_s = $('<a href="#click">' + $('a', $li).text() + '</a>');
		$a_s.click(function() {
			showSearchTypes(this);
		});
		$a_s.attr('rel',$rel1);
		
		$li_sel_new = $('<li></li>').addClass('selected');
		$li_sel_new.append($a_s);
		
		$a = $('<a href="#click">' + $('a', $li_s).text() + '</a>');
		$a.click(function() {
			selectSearchType(this);
		});
		$a.attr('rel',$rel2);
		$li_new = $('<li></li>');
		$li_new.append($a);
		
		$li.parent().prepend($li_new).prepend($li_sel_new);
		
		$li.remove();
		$li_s.remove();
		
		hideSearchTypes();
		
		$li_sel_new.mouseover(function() {
			$(this).addClass('active');
		});
		$li_new.mouseover(function() {
			$(this).addClass('active');
		});
		
		$li_sel_new.mouseout(function() {
			$(this).removeClass('active');
		});
		$li_new.mouseout(function() {
			$(this).removeClass('active');
		});
		
		return false;
	}
}


function search(){
	
}

//clock
function setClockAndDate(){
	dt = new Date();
	h = dt.getHours();
	if(h < 10){ h = '0'+h;}
	m = dt.getMinutes();
	if(m < 10){ m = '0'+m;}
	
	$('#clock_hour').html(h);
	$('#clock_minute').html(m);
	$('#clock_colon').toggleClass('t');
	
}

/**
 * Функция показа формы логина
 */
function showLogin(e){
	$user = $('#login_form_showup').detach();
	$user.appendTo($('#user'));
	$('#login_form_showup').removeClass('hide');
	$('#login_form_showup').show();
	cWindows[cWindows.length] = 'login_form_showup';
}

function checkEMail(a){
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(a);
}

function submitLogin(){
	
	email = $('#email').val();
	pass = $('#pass').val();

	if(!checkEMail(email)){
		message(t('WrongEmail'));
		return false;
	}
	
	if(pass.length < 1){
		message(t('WrongPasswordLength'));
		return false;
	}
	
	return true;
}

function closeLoginForm(){
	$('#login_form_showup').addClass('hide');
}

function weatherRotator() {
	if ($(".weather .area .frame.f").css('display') == 'none') {
		$(".weather .area .frame.f").fadeIn({duration:500});
		$(".weather .area .frame.s").fadeOut({duration:500});
	} else if ($(".weather .area .frame.f").css('display') == 'block') {
		$(".weather .area .frame.f").fadeOut({duration:500});
		$(".weather .area .frame.s").fadeIn({duration:500});
	}
}

$(document).ready(function() {
		
	$('body').click(function(e) {
		if ( cWindows.length > 0 ) {
			for (var i = 0; i < cWindows.length; i++) {
				
				if (	cWindows[i] != null && 
						$(e.target).parents().filter('#' + cWindows[i]).length == 0	&& 
						cWindows[i] != e.target.id &&
						!hasParentId(cWindows[i], e.target) ) {
					
							$('#' + cWindows[i]).hide();
							cWindows[i] = null;
				}
			}
		}
	})
	
	$('#action_login').click(function(e){
		e.stopPropagation();
		showLogin();
		return false;
	});
	
	$('#action_regions').click(function(e){
		e.stopPropagation();
		regionSelector();
		return false;

	});
	
	if ($(".weather .area").length == 1) {
		setInterval(weatherRotator, 5000);
	}
	
	$('ul.menu li').mouseover(function() {
		$(this).addClass('active');
	});
	
	$('ul.menu li').mouseout(function() {
		$(this).removeClass('active');
	});
	
	$('ul#srch_type_selector li').mouseover(function() {
		$(this).addClass('active');
	});
	
	$('ul#srch_type_selector li').mouseout(function() {
		$(this).removeClass('active');
	});
	
	$('ul#srch_type_selector').mouseout(function() {
		if ($('ul#srch_type_selector li.hide').length == 0) {
			searchTypeSelector = true;
			setTimeout(hideSearchTypeSelector, 1000);
		}
	});
	
	$('ul#srch_type_selector').mouseover(function() {
		searchTypeSelector = false;
	});
	
	
	if($(".carousel").length){
		$(".carousel").jCarouselLite({
			btnNext: ".carousel-next",
			btnPrev: ".carousel-prev",
			circular: false,
			mouseWheel: true,
			visible: 6
		});
		
		$(".carousel.articles").jCarouselLite({
			btnNext: ".carousel-next",
			btnPrev: ".carousel-prev",
			circular: false,
			mouseWheel: true,
			visible: 3
		});
		
		$('.carousel ul li .img').each(function() {
			if ($(this).parents('.carousel').hasClass('articles')) return;
			var $div = $(this);
			var $img = $('img', $div);
			var picture = $img.attr('src');
	
			$div.css('background-image', 'url("' + picture + '")')
				.css('background-position', 'center center')
				.css('background-repeat', 'no-repeat');
	
			if ($div.hasClass('active')) {
				$img.attr('src', '/images/tpl/_photo_frame_hover.png');
			} else {
				$img.attr('src', '/images/tpl/_photo_frame.png');
			}
	
			$hover = $('<img src="/images/tpl/_photo_frame_hover.png">').hide();
			$div.append($hover);
			
		});
	
		$('.carousel ul li a, .carousel ul li .img').mouseover(function() {
			if ($(this).parents('.carousel').hasClass('articles')) return;
			$div = $('.img', $(this).parents().filter('li'));
	
			$div.find(">:first-child").hide();
			$div.find(">:last-child").show();
			
		});
	
		$('.carousel ul li a, .carousel ul li .img').mouseout(function() {
			if ($(this).parents('.carousel').hasClass('articles')) return;
			$div = $('.img', $(this).parents().filter('li'));
			
			if ($div.hasClass('active')) return;
	
			$div.find(">:first-child").show();
			$div.find(">:last-child").hide();
			
		});
	
		$('.carousel_bttn').click(function(e) {
			if ($(this).hasClass('disabled')) {
				e.preventDefault();
				e.stopPropagation();
				return false;
			}
		});
	}
	
	$('div.photo_frame').each(function() {
		var $div = $(this);
		var $img = $('img', $div);
		var picture = $img.attr('src');

		$div.css('background-image', 'url("' + picture + '")')
			.css('background-position', 'center center')
			.css('background-repeat', 'no-repeat');

		if ($div.hasClass('size_180')) {
			$img.attr('src', '/images/tpl/_photo_frame_181.png');
		} else if ($div.hasClass('size_52')) {
			$img.attr('src', '/images/tpl/_photo_frame_52.png');
		} else {
			$img.attr('src', '/images/tpl/_photo_frame.png');
		}
		
		//$div.pngFix();
	});
	
	
	
	// search form 
	//$('#srch_keyword').attr('rel',$('#srch_keyword').val());
	$('#srch_keyword').focus(function(){
		if($(this).attr('rel') == $(this).val()){
			$(this).val(''); 			
		}		
	});

	$('#srch_keyword').blur(function(){
		if($(this).val() == ''){
			$(this).val($(this).attr('rel'));
		}
	});
	
	$('#srch_bttn').click(function(){
		$('#srch_form').submit();
		return false;
	})
	
	$('#srch_form').submit(function(){
		if($('#srch_keyword').val().length > 1 && ($('#srch_keyword').val() != $('#srch_keyword').attr('rel'))){
			
			search_query = encodeURIComponent( $('#srch_keyword').val() );
			if($('#srch_form_action').length){
				$('#srch_form').attr('action', $('#srch_form_action').val() + '?sq=' + search_query);
			}else{
				search_type = $('#srch_type_selector .selected a').attr('rel');
				switch(search_type){
					case 'products': case 'firms': case 'news': case 'all':
							break;
					default:
						search_type = 'products';
				}
				 
				$('#srch_form').attr('action','/search/'+search_type+'/?sq=' + search_query);
			}
		}else{
			return false;
		}		
	});
	
	setInterval(setClockAndDate,1000);
	
	$('#catalog_filter form input').change(function(){
		var type = '';
		if ($(this).hasClass('fiprice')) type = 'price';
		if ($(this).hasClass('fifirm')) {
			type = 'firm';
			if ($(this).attr('checked') == true) {
				$('#ffirm').val($('#ffirm').val() ? $('#ffirm').val() + ';' + $(this).val() : $(this).val());
			} else {
				var tmp = $('#ffirm').val().split(';');
				var tmp_str = '';
				
				for(var key in tmp) {
					if (parseInt(tmp[key]) != $(this).val())
					{
						tmp_str = tmp_str ? tmp_str + ';' + tmp[key] : "" + tmp[key];
					}
				}
				$('#ffirm').val(tmp_str);
			}
		}
		if ($(this).hasClass('filoc')) {
			type = 'loc';
			if ($(this).attr('checked') == true) {
				$('#floc').val($('#floc').val() ? $('#floc').val() + ';' + $(this).val() : $(this).val());
			} else {
				var tmp = $('#floc').val().split(';');
				var tmp_str = '';
				
				for(var key in tmp) {
					if (parseInt(tmp[key]) != $(this).val())
					{
						tmp_str = tmp_str ? tmp_str + ';' + tmp[key] : "" + tmp[key];
					}
				}
				$('#floc').val(tmp_str);
			}
		}
		changeFilter(type);
	});

	if($('#login_form').length){
		$('#login_form').submit(function(){
			return submitLogin();
		});
	}
	
	$('#catalog_filter form .show-all').click(function(){
		$('.hide', $(this).parent()).removeClass('hide');
		$(this).remove();
	});
	
	//close error/info messages
	$('.close-message').live('click', function(){
		$parent = $(this).parent();
		if($parent.hasClass('common-message')){
			$parent.hide();
		}
		return false;
	});
	
	
	//check search options
	if($('#srch_type_selector').length){
		rel = 'products';
		if(/^\/firms/g.test(location.pathname) || /^\/search\/firms/g.test(location.pathname)){
			rel = 'firms';
		}else if(/^\/news/g.test(location.pathname) || /^\/search\/news/g.test(location.pathname)){
			rel = 'news';	
		}else if(/^\/search\/all/g.test(location.pathname)){
			rel = 'all';	
		}
		
		selectSearchType($('#srch_type_selector a[rel=' + rel + ']'));
		
	}
	
	//forms limits
	$('.form input,.form textarea').live('focus',function(){
		$('~ .form_field_limits',this).css('visibility','visible');
	});

	$('.form input,.form textarea').live('blur',function(){
		$('~ .form_field_limits',this).css('visibility','hidden');
	})
	
	/**
	 * Fancybox init
	 */
	if (typeof $('a.fancy').fancybox != 'undefined') {
		$('a.fancy').each(function () {
			var $box = $(this);
			$(this).fancybox({
				'titlePosition' : 'over',
				'modal' : $box.hasClass('modal'),
				'onComplete' : function() {
					$("#fancybox-wrap").hover(function() {
						$("#fancybox-title").show();
					}, function() {
						$("#fancybox-title").hide();
					});
				}
			});
		});
	}
	
	// Новый список товаров
	$('.products_list.group_firm .product_wrap').hover(function() {
		$(this).parent().css('border-color', '#f7cb7b');
		$(this).css('border-color', '#dbb66b');
	}, function() {
		$(this).parent().css('border-color', '#ccc');
		$(this).css('border-color', '#ccc');
	});
	
	// Форма отправки запроса
	$('a.requestitem').each(function(){
		$a = $(this); 
		ids = $a.attr('rel').split('-');
		$a.attr('href','/requestitem/'+$a.attr('rel'));
		$a.fancybox({ 
					'titlePosition' : 'over',
					'showCloseButton' : true
				});
	});
	
	// открывание скрытых дивов
	$('a.action_show').each(
		function(){
			$(this).click(
				function(){
					var elem = $('#' + $(this).attr('rel'));
					if(elem.hasClass('hide'))
						elem.removeClass('hide');
					else
						elem.addClass('hide');
					return false;
				}
			)
		}
	);
	
});

function changeFilter(type) {
	var $form = $('#catalog_filter form');
	$('#filter_field_type').val(type);
	var data1 = $form.serialize();
	var fh = $('#catalog_filter form input#fh').val();
	
	$('#catalog_filter form input').attr('disabled', 'disabled');
	
	$.post(fh, data1, function(data) {
		$('#catalog_filter form input').removeAttr('disabled');
		$('#catalog_filter form dd[class!='+type+'_filter_list] label').addClass('disabled');
		$('#catalog_filter form dd[class!='+type+'_filter_list] label span[id^="count_f"]').text('0');

		if (!$.isEmptyObject(data.l)) {
			for(var key in data.l) {
				$('#catalog_filter form label#label_floc_' + key).removeClass('disabled');
				$('#catalog_filter form label span#count_floc_' + key).text(data.l[key]);
			}
		}

		if (!$.isEmptyObject(data.f)) {
			for(var key in data.f) {
				$('#catalog_filter form label#label_ffirm_' + key).removeClass('disabled');
				$('#catalog_filter form label span#count_ffirm_' + key).text(data.f[key]);
			}
		}
	}, 'json');
}

function sendFilter() {
	if ($('#catalog_filter').length == 1) {
		$('#catalog_filter form ins input').remove();
		$('#catalog_filter form').submit();
	}
}

function fancy_remove() {
	$.fancybox.close();
}


function checkFileType(fname,ftype){
	
	if(typeof ftype == 'undefined' || typeof fname == 'undefined'){
		return false;
	}
	
	switch(ftype){
		case 'image':
			res = /\.(png|jpeg|jpg|gif)$/.test(fname)
			break;
		case 'doc':
			res = /\.(doc|docx|rtf|txt)$/.test(fname)
			break;
		default:
			res = false;
	}
	
	return res;
}

function show_instead(id,obj){
	$('#'+id).removeClass('hide');
	$('#'+id).show();
	$(obj).remove();
}


function init_product_gal(){
	$('.images_set_node').click(function(){
		$('#' + $(this).attr('rel')).css({'backgroundImage': $(this).css('backgroundImage').replace('/64/','/175/')});
		re = new RegExp('url\\("?([^")]+)"?\\)', 'ig');
		$('a','#' + $(this).attr('rel')).attr('href',$(this).css('backgroundImage').replace('/64/','/original/').replace(re,'$1'));
	});
}

/**
 * Новый список товаров
 * @param link
 * @returns {Boolean}
 */
function showMoreProducts(link) {
	$prod = $(link).parents().filter('.products');
	if ($('.ep.hide', $prod).length > 0) {
		$('.ep.hide', $prod).removeClass('hide');
		if ($('.more_products.all', $prod).length > 0) {
			$(link).parent().addClass('collapse');
			$(link).text('скрыть дополнительные товары');
			$('.more_products.all', $prod).removeClass('hide').show();
		}
	} else {
		$(link).parent().removeClass('collapse');
		$(link).text('показать больше товаров');
		$('.more_products.all', $prod).addClass('hide').hide();
		$('.ep', $prod).addClass('hide');
	}
	return false;
}

function showExtraContacts(link) {
	$(link).parent().removeClass('hide_ec');
	$(link).remove();
	return false;
}

function hasParentId(id_parent_needle, element) {

	var parent = $($(element).parent());

	while(parent.length){
		if( $(parent).id == id_parent_needle ) {
			return true;
		}
		parent = $(parent).parent();
	}
	
	return false;
}

/* maps */
function show_map(id){
	if(typeof id == 'undefined') {
		id = 'map';
	}
	Office.map = new YMaps.Map(YMaps.jQuery("#"+id)[0]);
	Office.map.addControl(new YMaps.TypeControl());
	Office.map.addControl(new YMaps.Zoom());
	Office.map.addControl(new YMaps.ToolBar());
	Office.map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);
	Office.map.setZoom(14);
    $("#"+id).removeClass('hide');
}


/* contacts */
function init_form_handler(type){
	
	switch(type){
	
		case 'requestitem': case 'contacts':
			
			$('#send_message').click(function(){

				name = $('#name').val().length;
				if(name < 2){
					msgbox(t('TooSmallName'));
					return;
				}
				if(name > 50){
					msgbox(t('TooLargeName'));
					return;
				}		
			
				msg = $('#message').val().length;
				if(msg < 5){
					msgbox(t('TooSmallMessage'));
					return;
				}
				if(msg > 3000){
					msgbox(t('TooLargeMessage'));
					return;
				}		
			
				if($('#tema').length){
					msg = $('#tema').val().length;
					if(msg < 5){
						msgbox(t('TooSmallTema'));
						return;
					}
					if(msg > 100){
						msgbox(t('TooLargeTema'));
						return;
					}		
				}
				
				if(!$('#captcha_code').val().length){
					msgbox(t('CaptchaIRequired'));
					return;
				}
				
				if(type == 'requestitem'){
					
					data = $('#form_contact').serialize();
					
					$.post($('#form_contact_action').val(),data,
						
						function(response){
							
							$('#contact_form_errors').html( response.errors );
						
							if(response.status == 'ok'){
								msgbox('Сообщение успешно отправлено');
								fancy_remove();
							}else{
								$('#captcha').html(response.captcha.html);
							}
								
						}
					
					,'json');
					return;
				}
				
				$('#form_contact').submit();
				
			});
			
			var h = unescape(self.document.location.hash.substring(1));
			if(h.length && ! $('#tema').val().length) {
				$('#tema').val(h);
			}
			
			break;
		default:
			
	}

}
