/*
*  Ajax Autocomplete for jQuery, version 1.1
*  (c) 2009 Tomas Kirda
*
*  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
*  For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*  Last Review: 09/27/2009
*/
(function(d){function l(a,b,c){b="("+c.replace(m,"\\$1")+")";return a.replace(new RegExp(b,"gi"),"<strong>$1</strong>")}function k(a,b){this.el=d(a);this.el.attr("autocomplete","off");this.suggestions=[];this.data=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.el.val();this.intervalId=0;this.cachedResponse=[];this.onChangeInterval=null;this.ignoreValueChange=false;this.serviceUrl=b.serviceUrl;this.isLocal=false;this.options={autoSubmit:false,minChars:1,maxHeight:300,deferRequestBy:0, width:0,highlight:true,params:{},fnFormatResult:l,delimiter:null,zIndex:9999};this.initialize();this.setOptions(b)}var m=new RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\)","g");d.fn.autocomplete=function(a){return new k(this.get(0),a)};k.prototype={killerFn:null,initialize:function(){var a,b,c;a=this;b=(new Date).getTime();c="Autocomplete_"+b;this.killerFn=function(e){if(d(e.target).parents(".autocomplete").size()===0){a.killSuggestions();a.disableKillerFn()}};if(!this.options.width)this.options.width= this.el.width();this.mainContainerId="AutocompleteContainter_"+b;d('<div id="'+this.mainContainerId+'" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="'+c+'" style="display:none; width:300px;"></div></div></div>').appendTo("body");this.container=d("#"+c);this.fixPosition();window.opera?this.el.keypress(function(e){a.onKeyPress(e)}):this.el.keydown(function(e){a.onKeyPress(e)});this.el.keyup(function(e){a.onKeyUp(e)});this.el.blur(function(){a.enableKillerFn()}); this.el.focus(function(){a.fixPosition()})},setOptions:function(a){var b=this.options;d.extend(b,a);if(b.lookup){this.isLocal=true;if(d.isArray(b.lookup))b.lookup={suggestions:b.lookup,data:[]}}d("#"+this.mainContainerId).css({zIndex:b.zIndex});this.container.css({maxHeight:b.maxHeight+"px",width:b.width})},clearCache:function(){this.cachedResponse=[];this.badQueries=[]},disable:function(){this.disabled=true},enable:function(){this.disabled=false},fixPosition:function(){var a=this.el.offset();d("#"+ this.mainContainerId).css({top:a.top+this.el.innerHeight()+"px",left:a.left+"px"})},enableKillerFn:function(){var a=this;d(document).bind("click",a.killerFn)},disableKillerFn:function(){var a=this;d(document).unbind("click",a.killerFn)},killSuggestions:function(){var a=this;this.stopKillSuggestions();this.intervalId=window.setInterval(function(){a.hide();a.stopKillSuggestions()},300)},stopKillSuggestions:function(){window.clearInterval(this.intervalId)},onKeyPress:function(a){if(!(this.disabled|| !this.enabled)){switch(a.keyCode){case 27:this.el.val(this.currentValue);this.hide();break;case 9:case 13:if(this.selectedIndex===-1){this.hide();return}this.select(this.selectedIndex);if(a.keyCode===9)return;break;case 38:this.moveUp();break;case 40:this.moveDown();break;default:return}a.stopImmediatePropagation();a.preventDefault()}},onKeyUp:function(a){if(!this.disabled){switch(a.keyCode){case 38:case 40:return}clearInterval(this.onChangeInterval);if(this.currentValue!==this.el.val())if(this.options.deferRequestBy> 0){var b=this;this.onChangeInterval=setInterval(function(){b.onValueChange()},this.options.deferRequestBy)}else this.onValueChange()}},onValueChange:function(){clearInterval(this.onChangeInterval);this.currentValue=this.el.val();var a=this.getQuery(this.currentValue);this.selectedIndex=-1;if(this.ignoreValueChange)this.ignoreValueChange=false;else a===""||a.length<this.options.minChars?this.hide():this.getSuggestions(a)},getQuery:function(a){var b;b=this.options.delimiter;if(!b)return d.trim(a);a= a.split(b);return d.trim(a[a.length-1])},getSuggestionsLocal:function(a){var b,c,e,g,f;c=this.options.lookup;e=c.suggestions.length;b={suggestions:[],data:[]};a=a.toLowerCase();for(f=0;f<e;f++){g=c.suggestions[f];if(g.toLowerCase().indexOf(a)===0){b.suggestions.push(g);b.data.push(c.data[f])}}return b},getSuggestions:function(a){var b,c;if((b=this.isLocal?this.getSuggestionsLocal(a):this.cachedResponse[a])&&d.isArray(b.suggestions)){this.suggestions=b.suggestions;this.data=b.data;this.suggest()}else if(!this.isBadQuery(a)){c= this;c.options.params.query=a;c.el.after('<span id="autocompleteProgress"></span>');d.get(this.serviceUrl,c.options.params,function(e){d("#autocompleteProgress").remove();c.processResponse(e)},"text")}},isBadQuery:function(a){for(var b=this.badQueries.length;b--;)if(a.indexOf(this.badQueries[b])===0)return true;return false},hide:function(){this.enabled=false;this.selectedIndex=-1;this.container.hide()},suggest:function(){if(this.suggestions.length===0)this.hide();else{var a,b,c,e,g,f,h,i;a=this; b=this.suggestions.length;e=this.options.fnFormatResult;g=this.getQuery(this.currentValue);h=function(j){return function(){a.activate(j)}};i=function(j){return function(){a.select(j)}};this.container.hide().empty();for(f=0;f<b;f++){c=this.suggestions[f];c=d((a.selectedIndex===f?'<div class="selected"':"<div")+' title="'+c+'">'+e(c,this.data[f],g)+"</div>");c.mouseover(h(f));c.click(i(f));this.container.append(c)}this.enabled=true;this.container.show()}},processResponse:function(a){var b;try{b=eval("("+ a+")")}catch(c){return}if(!d.isArray(b.data))b.data=[];this.cachedResponse[b.query]=b;b.suggestions.length===0&&this.badQueries.push(b.query);if(b.query===this.getQuery(this.currentValue)){this.suggestions=b.suggestions;this.data=b.data;this.suggest()}},activate:function(a){var b,c;b=this.container.children();this.selectedIndex!==-1&&b.length>this.selectedIndex&&d(b.get(this.selectedIndex)).attr("class","");this.selectedIndex=a;if(this.selectedIndex!==-1&&b.length>this.selectedIndex){c=b.get(this.selectedIndex); d(c).attr("class","selected")}return c},deactivate:function(a,b){a.className="";if(this.selectedIndex===b)this.selectedIndex=-1},select:function(a){var b;if(b=this.suggestions[a]){this.el.val(b);if(this.options.autoSubmit){b=this.el.parents("form");b.length>0&&b.get(0).submit()}this.ignoreValueChange=true;this.hide();this.onSelect(a)}},moveUp:function(){if(this.selectedIndex!==-1)if(this.selectedIndex===0){this.container.children().get(0).className="";this.selectedIndex=-1;this.el.val(this.currentValue)}else this.adjustScroll(this.selectedIndex- 1)},moveDown:function(){this.selectedIndex!==this.suggestions.length-1&&this.adjustScroll(this.selectedIndex+1)},adjustScroll:function(a){var b,c;a=this.activate(a);a=a.offsetTop;b=this.container.scrollTop();c=b+this.options.maxHeight-25;if(a<b)this.container.scrollTop(a);else a>c&&this.container.scrollTop(a-this.options.maxHeight+25)},onSelect:function(a){var b,c,e,g;b=this;c=b.options.onSelect;e=function(f){var h,i;h=b.options.delimiter;if(!h)return f;i=b.currentValue;h=i.split(h);if(h.length=== 1)return f;return i.substr(0,i.length-h[h.length-1].length)+f};g=b.suggestions[a];a=b.data[a];b.el.val(e(g));d.isFunction(c)&&c(g,a)}}})(jQuery);


function calculate_pos(){
	var win_width = $(window).width();
	var btn_pos = 0;
	if (win_width <= 998){
		btn_pos = 20;
	}
	else {
		btn_pos = Math.round((win_width - 998) / 2 + 20);
	}
	return btn_pos + 'px';
}

$(function(){

	$('#search input[name="search"]').autocomplete({
		serviceUrl: $('#search form').attr('action') + 'suggest/',
		minChars: 5,
		width: 400,
		deferRequestBy: 250,
	});

	var reg = /^(.*?\/)(\?|$)/;
	var result = reg.exec(document.URL);
	if (result != null) {
		var thisPageUrl = result[1];
		var ids = '';
		$('.electronshik_id').each(function() {
			ids += this.value + ',';
		});
		if (ids != '') {
			$.get(thisPageUrl + 'electronshik/', {'ids': ids, 'r': new Date().getTime()}, function(xml) {
				var reg = /<item.*?id="(.*?)".*?value="(.*?)".*?\/>/;
				while (matches = reg.exec(xml)) {
					xml = xml.replace(matches[0], '');
					$('#present_all_' + matches[1]).html(matches[2]);
				}
			});
		}
	}
	var coeff = 0.8;
	var new_width = $(window).width() * coeff;
	var new_height = $(window).height() * coeff;

	$('.add-cart').addClass('iframe').fancybox({'width' : 550, 'height' : 440, 'hideOnOverlayClick' : true, 'hideOnContentClick': false, 'centerOnScroll' : true, 'titleShow' : false, 'padding' : 0, 'transitionIn' : 'none', 'transitionOut' : 'none', 'onStart' : function() {$("body").css("overflow", "hidden");}, 'onClosed' : function() {$("body").css("overflow", "visible");}});
	$('.descriptionLink').each(function () {
		$(this).attr('href', $(this).attr('href') + '?lightbox');
	}).addClass('iframe').fancybox({'width' : new_width, 'height' : new_height, 'hideOnOverlayClick' : true, 'hideOnContentClick': false, 'centerOnScroll' : true, 'titleShow' : false, 'padding' : 0, 'transitionIn' : 'none', 'transitionOut' : 'none', 'onStart' : function() {$("body").css("overflow", "hidden");}, 'onClosed' : function() {$("body").css("overflow", "visible");}});
	$('#login_form #email').focus();
	$('#last_name').focus();
	s = $('#search_field').val();
	const_s = "Поиск по каталогу";
	if (s != const_s) {
		$('#search_field').focus().val('');
		$('#search_field').val(s);
	}

	$('.button-to-the-top').css('right', calculate_pos);
	$(window).resize(
		function() {
			$('.button-to-the-top').css('right', calculate_pos);
		}
	);

	$('.button-to-the-top').click(
		function() {
			$("html,body").animate({scrollTop:0}, 'fast');
		}
	);

	$('.to-good').click(
		function() {
			$('#'+$(this).attr('name')).addClass('viewed-good');
		}
	);

	$('.descriptionLink').click(
		function() {
			$('#viewed-goods-link').css('display', 'block');
		}
	);


});
