jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { 
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

(function($) {

$.extend({
  metadata : {
    defaults : {
      type: 'class',
      name: 'metadata',
      cre: /({.*})/,
      single: 'metadata'
    },
    setType: function( type, name ){
      this.defaults.type = type;
      this.defaults.name = name;
    },
    get: function( elem, opts ){
      var settings = $.extend({},this.defaults,opts);
      if ( !settings.single.length ) settings.single = 'metadata';
      
      var data = $.data(elem, settings.single);
      if ( data ) return data;
      
      data = "{}";
      
      var getData = function(data) {
        if(typeof data != "string") return data;
        
        if( data.indexOf('{') < 0 ) {
          data = eval("(" + data + ")");
        }
      }
      
      var getObject = function(data) {
        if(typeof data != "string") return data;
        
        data = eval("(" + data + ")");
        return data;
      }
      
      if ( settings.type == "html5" ) {
        var object = {};
        $( elem.attributes ).each(function() {
          var name = this.nodeName;
          if(name.match(/^data-/)) name = name.replace(/^data-/, '');
          else return true;
          object[name] = getObject(this.nodeValue);
        });
      } else {
        if ( settings.type == "class" ) {
          var m = settings.cre.exec( elem.className );
          if ( m )
            data = m[1];
        } else if ( settings.type == "elem" ) {
          if( !elem.getElementsByTagName ) return;
          var e = elem.getElementsByTagName(settings.name);
          if ( e.length )
            data = $.trim(e[0].innerHTML);
        } else if ( elem.getAttribute != undefined ) {
          var attr = elem.getAttribute( settings.name );
          if ( attr )
            data = attr;
        }
        object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
      }
      
      $.data( elem, settings.single, object );
      return object;
    }
  }
});

$.fn.metadata = function( opts ){
  return $.metadata.get( this[0], opts );
};

})(jQuery);

(function($, undefined){
	$.fn.autoComplete = function(){
		var args = Slice.call(arguments),
			self = this, 
			first = args.shift(),
			isMethod = (typeof first === 'string');

		if (isMethod) first = first.replace('.', '-');
		
		// аргументы
		args = first === 'button-supply' || first === 'direct-supply' ? $.isArray(args[0]) && $.isArray(args[0][0]) ? args[0] : args :
			args[1] === undefined && $.isArray(args[0]) ? args[0] : args;

		// триггеры
		return isMethod ?
			$(self)[ first === 'option' && args.length < 2 ? 'triggerHandler' : 'trigger' ]('autoComplete.'+first, args) :
			first && first[$.expando] ? $(self).trigger(first, args) :
			AutoCompleteFunction.call(self, first);
	};

	// это для грёбанного IE
	$.fn.bgiframe = $.fn.bgiframe ? $.fn.bgiframe : $.fn.bgIframe ? $.fn.bgIframe : function(){
		return this;
	};

	$.expando = $.expando !== undefined ? $.expando : (function(){
		var event = $.Event('keyup'), i;
		for (i in event)
			if (i.indexOf('jQuery') === 0)
				return i;
		return 'jQuery'+event.timeStamp;
	})();

	function now(){
		return (new Date).getTime();
	}


var
	TRUE = true,
	FALSE = false,

	Slice = Array.prototype.slice,

	AutoComplete = $.autoComplete = {
		counter: 0,
		length: 0,
		stack: {},
		order: [],
		hasFocus: FALSE,
		getFocus: function(){
			return this.order[0] ? this.stack[ this.order[0] ] : undefined;
		},
		getPrevious: function(){
			for ( var i=1, l=this.order.length; i < l; i++ )
				if (this.order[i])
					return this.stack[ this.order[i] ];
			return undefined;
		},

		remove: function(i){
			for ( var k=0, l=this.order.length; k < l; k++ )
				if (this.order[k] === i)
					this.order[k] = undefined;
			this.stack[i] = undefined;
			this.length--;
			delete this.stack[i];
		},

		getAll: function(){
			for ( var i = 0, l = this.counter, stack = []; i < l; i++ )
				if (this.stack[i])
					stack.push(this.stack[i]);
			return $(stack);
		},

		// настройки
		defaults: {
			backwardsCompatible: FALSE,
			// путь к скриту
			ajax: '/w.html',
			ajaxCache: $.ajaxSettings.cache,
			dataSupply: [],
			dataFn: undefined,
			dataName: 'ac-data',
			list: 'auto-complete-list',
			rollover: 'auto-complete-list-rollover',
			width: undefined,
			striped: undefined,
			maxHeight: undefined,
			newList: FALSE,
			postVar: 'value',
			postData: {},
			minChars: 1,
			maxItems: -1,
			maxRequests: 0,
			requestType: 'POST',
			inputControl: undefined,
			autoFill: FALSE,
			nonInput: undefined,
			multiple: FALSE,
			multipleSeparator: ' ',
			onBlur: undefined,
			onFocus: undefined,
			onHide: undefined,
			onLoad: undefined,
			onMaxRequest: function(){},
			onRollover: undefined,
			onSelect: function() {$('#formsearch').submit()},
			onShow: undefined,
			onSubmit: function(){return TRUE;},
			spinner: undefined,
			preventEnterSubmit: FALSE,
			delay: 0,
			useCache: TRUE,
			cacheLimit: 50
		}
	},

	AutoCompleteFunction = function(options){
		return this.each(function(){
		var
			self = this,
			$input = $(self).attr('autocomplete', 'off'),
			Active = TRUE,
			LastEvent = {},
			inputval = '',
			$elems = {length:0},
			$li,
			view, ulHeight, liHeight, liPerView,
			ulOpen = FALSE,
			timeid,
			xhr,
			liFocus = -1, liData,
			separator,
			inputIndex = (function(){ AutoComplete.length++; return ++AutoComplete.counter; })(),
			requests = 0,
			cache = {
				length: 0,
				val: undefined,
				list: {}
			},

			settings = $.extend(
				{ width: $input.outerWidth()-2 },
				AutoComplete.defaults, 
				options||{},
				$.metadata ? $input.metadata() : {}
			),

			$ul = !settings.newList && $('ul.'+settings.list)[0] ?
				$('ul.'+settings.list).eq(0).bgiframe().data('autoComplete', TRUE) :
				$('<ul/>').appendTo('body').addClass(settings.list).bgiframe().hide().data('ac-selfmade', TRUE).data('autoComplete', TRUE),

			$doc = $(document).bind('click.autoComplete-'+inputIndex, function(event){
				var $elem;
				if (Active && ulOpen &&
					(!LastEvent || event.timeStamp - LastEvent.timeStamp > 200) && 
					( $elem = $(event.target) ).closest('ul').data('ac-input-index') !== inputIndex &&
					$elem.data('ac-input-index') !== inputIndex){
						$ul.hide(event);
						$input.blur();
				}
				LastEvent = event;
			});

			newUl();
			settings.requestType = settings.requestType.toUpperCase();
			separator = settings.multiple ? settings.multipleSeparator : undefined;
			AutoComplete.stack[inputIndex] = self;

			$input.data('autoComplete', TRUE)
			.data('ac-input-index', inputIndex)
			.data('ac-active', Active)
			.data('ac-initial-settings', $.extend(TRUE, {}, settings)).data('ac-settings', settings)
			.bind(window.opera ? 'keypress.autoComplete' : 'keydown.autoComplete', function(event){
				if (!Active) return TRUE;
				var key = (LastEvent = event).keyCode, enter = FALSE;

				// табуляция
				if (key == 9 && ulOpen){
					select(event);
				}
				// ввод
				else if (key == 13 && $li){
					enter = settings.preventEnterSubmit && ulOpen ? FALSE : TRUE;
					select(event);
					$ul.hide(event);
				}
				// ввод
				else if (key == 13 && !$li){
					enter = TRUE;
					select(event);
					$ul.html('').hide(event);
				}
				// вверх
				else if (key == 38){
					if (liFocus > 0){
						liFocus--;
						up(event);
					}else{
						liFocus = -1;
						$input.val(inputval);
						$ul.hide(event);
					}
				}
				// вниз
				else if (key == 40){
					if (liFocus < $elems.length-1){
						liFocus++;
						down(event);
					}
				}
				// pageup 
				else if (key == 33){
					if (liFocus > 0){
						liFocus -= liPerView;
						if (liFocus < 0) liFocus = 0;
						up(event);
					}
				}
				// pagedown
				else if (key == 34){
					if (liFocus < $elems.length-1){
						liFocus += liPerView;
						if (liFocus > $elems.length-1) liFocus = $elems.length-1;
						down(event);
					}
				}
				else if (settings.nonInput && $.inArray(key, settings.nonInput)){
					$ul.html('').hide(event);
				}
				else{
					return TRUE;
				}

				LastEvent[$.expando + '_autoComplete_keydown'] = TRUE;
				return enter;
			})
			.bind('keyup.autoComplete', function(event){
				if (!Active || LastEvent[$.expando + '_autoComplete_keydown']) return TRUE;

				inputval = $input.val();
				var key = (LastEvent = event).keyCode,
					val = separator ? inputval.split(separator).pop() : inputval;
				if (key != 13){
					cache.val = settings.inputControl === undefined ? val : 
						settings.inputControl.apply(self, settings.backwardsCompatible ? 
							[val, key, $ul, event] : [event, {val: val, key: key, ul: $ul}]);
					if (cache.val.length >= settings.minChars)
						sendRequest(event, settings, cache, (key==8||key==32));
					else if (key == 8)
						$ul.html('').hide(event);
				}
			})
			.bind('blur.autoComplete', function(event){
				if (!Active || ulOpen) return TRUE;
				LastEvent = event;
				$input.data('ac-hasFocus', FALSE);
				liFocus = -1;
				if (AutoComplete.order[0] !== undefined)
					AutoComplete.order.unshift(undefined);
				AutoComplete.hasFocus = FALSE;
				$ul.hide(event);
				if (settings.onBlur) settings.onBlur.apply(self, settings.backwardsCompatible ?
					[inputval, $ul, event] : [event, {val: inputval, ul: $ul}]);
			})
			.bind('focus.autoComplete', function(event, flag){
				if (!Active || 
					(AutoComplete.focus === inputIndex && flag === $.expando + '_autoComplete') || 
					LastEvent[$.expando + '_autoComplete_enter'])
						return TRUE;
				LastEvent = event;
				if (inputIndex != $ul.data('ac-input-index'))
					$ul.html('').hide(event);
				$input.data('ac-hasFocus', TRUE);
				if (AutoComplete.order[0] === undefined){
					if (AutoComplete.order[1] === inputIndex)
						AutoComplete.order.shift();
					else
						AutoComplete.order[0] = inputIndex;
				}
				else if (AutoComplete.order[0] != inputIndex && AutoComplete.order[1] != inputIndex)
					AutoComplete.order.unshift(inputIndex);
				if (AutoComplete.order.length > AutoComplete.defaults.cacheLimit)
					AutoComplete.order.pop();
				AutoComplete.hasFocus = TRUE;
				if (settings.onFocus) settings.onFocus.apply(self, settings.backwardsCompatible ? [$ul, event] : [event, {ul: $ul}]);
			})

			.bind('autoComplete.settings', function(event, newSettings){
				if (!Active) return TRUE;
				if ($.isFunction(newSettings)){
					var ret = newSettings.apply(self, settings.backwardsCompatible ? 
						[settings, cache, $ul, event] : [event, {settings: settings, cache: cache, ul: $ul}]);
					if ($.isArray(ret) && ret[0] !== undefined){
						settings = $.extend(TRUE, {}, settings, ret[0]||settings);
						cache = $.extend(TRUE, {}, cache, ret[1]||cache);
					}
				}else{
					settings = $.extend(TRUE, {}, settings, newSettings||{});
				}
				settings.requestType = settings.requestType.toUpperCase();
				separator = settings.multiple ? settings.multipleSeparator : undefined;
				$input.data('ac-settings', settings);
				$ul = !settings.newList && $ul.hasClass(settings.list) ? $ul : 
					!settings.newList && $('ul.'+settings.list)[0] ? $('ul.'+settings.list).bgiframe().data('autoComplete', TRUE) : 
					$('<ul/>').appendTo('body').addClass(settings.list).bgiframe().hide()
						.data('ac-selfmade', TRUE).data('autoComplete', TRUE);
				newUl();
				return LastEvent = event;
			})
			.bind('autoComplete.flush', function(event, cacheOnly){
				if (!Active) return TRUE;
				cache = {length:0, val:undefined, list:{}};
				if (!cacheOnly) requests = 0;
				return LastEvent = event;
			})
			.bind('autoComplete.button-ajax', function(event, postData, cacheName){
				if (!Active) return TRUE;
				LastEvent = event;
				$input.trigger('focus', [$.expando + '_autoComplete']);
				if (typeof postData === 'string'){
					cacheName = postData;
					postData = {};
				}
				cache.val = cacheName||'NON_404_<>!@$^&';
				return sendRequest(
					event, 
					$.extend(TRUE, {}, settings, {maxItems: -1, postData: postData||{}}), 
					cache
				);
			})
			.bind('autoComplete.button-supply', function(event, data, cacheName){
				if (!Active) return TRUE;
				LastEvent = event;
				$input.trigger('focus', [$.expando + '_autoComplete']);
				if (typeof data === 'string'){
					cacheName = data;
					data = undefined;
				}
				cache.val = cacheName||'NON_404_SUPPLY_<>!@$^&';
				data = $.isArray(data) && data.length ? data : settings.dataSupply;
				return sendRequest(
					event,
					$.extend(TRUE, {}, settings, {maxItems: -1, dataSupply: data, dataFn: function(){ return TRUE; } }), 
					cache
				);
			})
			.bind('autoComplete.direct-supply', function(event, data, cacheName){
				if (!Active) return TRUE;
				LastEvent = event;
				$input.trigger('focus', [$.expando + '_autoComplete']);
				if (typeof data === 'string'){
					cacheName = data;
					data = undefined;
				}
				cache.val = cacheName||'NON_404_SUPPLY_<>!@$^&';
				data = $.isArray(data) && data.length ? data : settings.dataSupply;
				return loadResults(
					event,
					data,
					$.extend(TRUE, {}, settings, {maxItems: -1, dataSupply: data, dataFn: function(){ return TRUE; } }), 
					cache
				);
			})
			.bind('autoComplete.search', function(event, value){
				if (!Active) return TRUE;
				cache.val = value||'';
				return sendRequest(LastEvent = event, settings, cache);
			})
			.bind('autoComplete.option', function(event){
				if (!Active) return TRUE;
				LastEvent = event;
				var args = Slice.call(arguments), length = args.length;
				return length == 3 ? (function(){settings[ args[1] ] = args[2]; $input.data('ac-settings', settings); return args[2];})() :
					length == 2 ? (function(){ 
						switch (args[1]){
							case 'ul': return $ul;
							case 'cache': return cache;
							case 'xhr': return xhr;
							case 'input': return $input;
							default: return settings[ args[1] ] || undefined;
						}
					})() :
					settings;
			})
			.bind('autoComplete.enable', function(event){
				$input.data('ac-active', Active = TRUE);
				return LastEvent = event;
			})
			.bind('autoComplete.disable', function(event){
				$input.data('ac-active', Active = FALSE);
				$ul.html('').hide(event);
				return LastEvent = event;
			})
			.bind('autoComplete.destroy', function(event){
				$input
					.removeData('autoComplete')
					.removeData('ac-input-index')
					.removeData('ac-initial-settings')
					.removeData('ac-settings')
					.removeData('ac-active')
					.unbind('.autoComplete')
					.unbind( 'autoComplete.' + [
							'settings',
							'flush',
							'button-ajax',
							'button-supply',
							'direct-supply',
							'search',
							'option',
							'enable',
							'disable',
							'destroy'
						].join(' autoComplete.') )
					.parents('form').eq(0).unbind('submit.autoComplete-'+inputIndex);
				$doc.unbind('click.autoComplete-'+inputIndex);
				AutoComplete.remove(inputIndex);
				Active = FALSE;
				var list = $ul.html('').hide(event).data('ac-inputs'), i;
				list[inputIndex] = undefined;
				for (i in list)
					if (list[i] === TRUE)
						return LastEvent = event;
				if ($ul.data('ac-selfmade') === TRUE) $ul.remove();
				return LastEvent = event;
			})

			.parents('form').eq(0).bind('submit.autoComplete-'+inputIndex, function(event){
				if (!Active) return TRUE;
				var flag = LastEvent[$.expando + '_autoComplete_enter']||FALSE;
				LastEvent = event;
				return settings.preventEnterSubmit ?
					(ulOpen || flag) ? FALSE : settings.onSubmit.call(self, event, {form: this, ul: $ul}) :
					settings.onSubmit.call(self, event, {form: this, ul: $ul});
			});
	
			function sendRequest(event, settings, cache, backSpace, timeout){
				if (settings.spinner) settings.spinner.call(self, event, {active: TRUE, ul: $ul});
				if (timeid) timeid = clearTimeout(timeid);
				if (settings.delay > 0 && timeout === undefined) return timeid = setTimeout(function(){
						sendRequest(event, settings, cache, backSpace, TRUE);
						timeid = clearTimeout(timeid);
					}, settings.delay);

				if (xhr) xhr.abort();

				if (settings.useCache && cache.list[cache.val])
					return loadResults(event, cache.list[cache.val], settings, cache, backSpace);

				if (settings.dataSupply.length)
					return userSuppliedData(event, settings, cache, backSpace);

				if (settings.maxRequests && ++requests >= settings.maxRequests){
					$ul.html('').hide(event);
					if (settings.spinner) settings.spinner.call(self, event, {active: FALSE, ul: $ul});
					return requests > settings.maxRequests ?
						FALSE : settings.onMaxRequest.apply(self, settings.backwardsCompatible ? 
								[cache.val, $ul, event, inputval] : [event, {search: cache.val, val: inputval, ul: $ul}]);
				}

				settings.postData[settings.postVar] = cache.val
				return xhr = $.ajax({
					type: settings.requestType,
					url: settings.ajax,
					data: settings.postData,
					dataType: 'json',
					cache: settings.ajaxCache,
					success: function(list){
						loadResults(event, list, settings, cache, backSpace);
					},
					error: function(){
						$ul.html('').hide(event);
						if (settings.spinner) settings.spinner.call(self, event, {active: FALSE, ul: $ul});
					}
				});
			}

			function userSuppliedData(event, settings, cache, backSpace){
				var list = [], // результат
					args = [], // запрос
					fn = $.isFunction(settings.dataFn), // калбек
					regex = fn ? undefined : new RegExp('^'+cache.val, 'i'),
					k = 0, entry, i=0, l=settings.dataSupply.length;

				for ( ; i < l; i++ ){
					entry = settings.dataSupply[i];
					entry = typeof entry === 'object' && entry.value ? entry : {value: entry};
					args = settings.backwardsCompatible ? 
						[cache.val, entry.value, list, i, settings.dataSupply, $ul, event] :
						[event, {val: cache.val, entry: entry.value, list: list, i: i, supply: settings.dataSupply, ul: $ul}];
					if ((fn && settings.dataFn.apply(self, args)) || (!fn && entry.value.match(regex))){
						if (settings.maxItems > -1 && ++k > settings.maxItems)
							break;
						list.push(entry);
					}
				}
				return loadResults(event, list, settings, cache, backSpace);
			}

			function select(event){
				if (ulOpen){
					if (settings.onSelect) settings.onSelect.apply(self, settings.backwardsCompatible ? 
						[liData, $li, $ul, event] : [event, {data: liData, li: $li, ul: $ul}]);
					autoFill(undefined);
					inputval = $input.val();
					if (LastEvent.type=='keydown') LastEvent[$.expando + '_autoComplete_enter'] = TRUE;
				}
				$ul.hide(event);
				return $li;
			}

			function up(event){
				if ($li) $li.removeClass(settings.rollover);
				$ul.show(event);
				$li = $elems.eq(liFocus).addClass(settings.rollover);
				liData = $li.data(settings.dataName);
				if (!$li.length || !liData) return FALSE;
				autoFill( liData.value||'' );
				if (settings.onRollover) settings.onRollover.apply(self, settings.backwardsCompatible ? 
					[liData, $li, $ul, event] : [event, {data: liData, li: $li, ul: $ul}]);
				var v = liFocus*liHeight;
				if (v < view-ulHeight){
					view = v+ulHeight
					$ul.scrollTop( v );
				}
				return $li;
			}

			function down(event){
				if ($li) $li.removeClass(settings.rollover);
				$ul.show(event);
				$li = $elems.eq( liFocus ).addClass( settings.rollover );
				liData = $li.data( settings.dataName );
				if (!$li.length || !liData) return FALSE;
				autoFill( liData.value||'' );
				var v = (liFocus+1)*liHeight;
				if (v > view)
					$ul.scrollTop( (view = v) - ulHeight );
				if (settings.onRollover) settings.onRollover.apply(self, settings.backwardsCompatible ? 
					[liData, $li, $ul, event] : [event, {data: liData, li: $li, ul: $ul}]);
				return $li;
			}

			function newUl(){
				if (! $ul[$.expando + '_autoComplete']){
					var hide = $ul.hide, show = $ul.show;
					$ul.hide = function(event, speed, callback){
						if (settings.onHide && ulOpen){
							settings.onHide.call(self, event, {ul: $ul});
							LastEvent[$.expando + '_autoComplete_hide'] = TRUE;
						}
						ulOpen = FALSE;
						return hide.call($ul, speed, callback);
					};
					$ul.show = function(event, speed, callback){
						if (settings.onShow && !ulOpen) settings.onShow.call(self, event, {ul: $ul});
						ulOpen = TRUE;
						return show.call($ul, speed, callback);
					};
					$ul[$.expando + '_autoComplete'] = TRUE;
				}
				var list = $ul.data('ac-inputs')||{};
				list[inputIndex] = TRUE;
				return $ul.data('ac-inputs', list);
			}

			function autoFill(val){
				if (val === undefined){
					var start, end; start = end = $input.val().length;
				}else{
					if (separator) val = inputval.substr( 0, inputval.length-inputval.split(separator).pop().length ) + val + separator;
					var start = inputval.length, end = val.length;
					$input.val(val);
				}

				if (! settings.autoFill || start > end){
					return FALSE;
				}
				else if (self.createTextRange){
					var range = self.createTextRange();
					if (val === undefined) {
						range.move('character', start);
						range.select();
					}else{
						range.collapse(TRUE);
						range.moveStart("character", start);
						range.moveEnd("character", end);
						range.select();
					}
				}
				else if (self.setSelectionRange){
					self.setSelectionRange(start, end);
				}
				else if (self.selectionStart){
					self.selectionStart = start;
					self.selectionEnd = end;
				}
				return TRUE;
			}

			function loadResults(event, list, settings, cache, backSpace){
				if (settings.onLoad) list = settings.onLoad.call(self, event, {list: list, settings: settings, cache: cache, ul: $ul});
				if (settings.spinner) settings.spinner.call(self, event, {active: FALSE, ul: $ul});
				if (settings.useCache && cache.list[cache.val] === undefined){
					cache.length++;
					cache.list[cache.val] = list;
					if (cache.length > settings.cacheLimit){
						cache.list = {};
						cache.length = 0;
					}
				}

				if (!list || list.length < 1)
					return $ul.html('').hide(event);

				liFocus = -1;

				var offset = $input.offset(), 
				    container = [], // 
				    aci=0,k=0,i=0,even=FALSE,length=list.length; 

				for (; i < length; i++){
					if (list[i].value){
						if (settings.maxItems > -1 && ++aci > settings.maxItems)
							break;
						container.push(
							settings.striped && even ? '<li class="'+settings.striped+'">' : '<li>',
							list[i].display||list[i].value,
							'</li>'
						);
						even = !even;
					}
				}

				$elems = $ul.html( container.join('') ).children('li');
				for ( length = $elems.length; k < length; k++ ){
					$.data( $elems[k], settings.dataName, list[k] );
					$.data( $elems[k], 'ac-index', k );
				}


				if (settings.autoFill && ! backSpace){
					liFocus = 0;
					liData = list[0];
					autoFill( liData.value||'' );
					$li = $elems.eq(0).addClass( settings.rollover );
				}

				$ul.unbind('.autoComplete')
				.data('ac-input-index', inputIndex)
				.bind('mouseout.autoComplete', function(){
					$li.removeClass(settings.rollover);
				})
				.bind('mouseover.autoComplete', function(event){
					$li = $(event.target).closest('li');
					if ($li.length < 1) return FALSE;
					$elems.filter('.'+settings.rollover).removeClass(settings.rollover);
					liFocus = $li.addClass(settings.rollover).data('ac-index');
					liData = $li.data( settings.dataName );
					if (settings.onRollover) settings.onRollover.apply(self, settings.backwardsCompatible ? 
						[liData, $li, $ul, event] : [event, {data: liData, li: $li, ul: $ul}]);
				})
				.bind('click.autoComplete', function(event){
					$input.trigger('focus', [$.expando + '_autoComplete']);
					liData = $li.data(settings.dataName);
					$input.val( inputval = separator ? 
						inputval.substr( 0, inputval.length-inputval.split(separator).pop().length ) + liData.value + separator :
						liData.value 
					);
					$ul.hide(event);
					autoFill(undefined);
					if (settings.onSelect) settings.onSelect.apply(self, settings.backwardsCompatible ? 
						[liData, $li, $ul, event] : [event, {data: liData, li: $li, ul: $ul}]);
				})
				.css({
					top: offset.top + $input.outerHeight(),
					left: offset.left,
					width: settings.width
				})
				.scrollTop(0);

				if (settings.maxHeight) $ul.css({
					height: liHeight*$elems.length > settings.maxHeight ? settings.maxHeight : 'auto', 
					overflow: 'auto'
				});

				ulHeight = $ul.show(event).outerHeight();
				view = ulHeight;
				liHeight = $elems.eq(0).outerHeight();
				liPerView = Math.floor(view/liHeight);

				LastEvent.timeStamp = now();

				return $ul;
			}
		});
	};
})(jQuery);

cTmt = false;
cImg = false;
cGid = false

oTimtOt = false;

$(document).ready(function(){
	
	/* resize */
	resize_results();
	
	/* autocomplete */
	if ($.cookie('qs')!=1) $('#q').autoComplete();

	$('form #q, form .q').each(function(){
		if (!($(this)).val()) return true;
		$(this).next().css('top',($(this).position().top+$(this).height()/2 - 5) );
		$(this).next().css('left',($(this).position().left+$(this).width() - 15) );
	});	
	
	$('form #q, form .q').focus(function(){
		if (!($(this)).val()) return true;
		$(this).next().css('top',($(this).position().top+$(this).height()/2 - 5) );
		$(this).next().css('left',($(this).position().left+$(this).width() - 15) );
		$(this).next().show();
	});

	$('.clear_button').click(function(){
		$(this).prev().val('');
		$(this).prev().focus();
		$(this).hide();
		return false;
	});

	
	/* favorites */
	$("td div.add").attr('title','Add to favorites');
	$("td div.remove").attr('title','Remove from favorites');
	
	$("td div.add, td div.remove").hover(
		function() {
			$(this).addClass('stable');
			if ($('form.iphone').length) return;
			$(this).css('background-position',$(this).hasClass('add') ? '-15px 0px' : '-45px 0px');
		},
		function() {
			$(this).removeClass('stable');
			if ($('form.iphone').length) return;
			$(this).css('background-position',$(this).hasClass('add') ? '0px 0px' : '-30px 0px');
		}
	);
	
	$('.tag a').each(function(){$(this).attr('href',$(this).attr('href').replace('?q=','?t='))});
	$('.tag a, .relcat a').each(function(){$(this).attr('href',$(this).attr('href').replace('?q=','?r='))});
	$('.model a').each(function(){$(this).attr('href',$(this).attr('href').replace('?q=','?m='))});
	$('.tube a,.site a,').each(function(){$(this).attr('href',$(this).attr('href').replace('?q=','?c='))});
	
	$("td div.add, td div.remove").click(function(){
		if ($(this).hasClass('add')) {
			if ( $.cookie("favs") && ( (( $.cookie("favs").split('|').length - 2 ) *1) >=100) ) {
				if (confirm('The maximum of 100 favorites is exceeded.' + "\n" + 'Do you want register for free and creating a collection of up to 3,000 of your favorite videos?')) {
					window.top.location.href = 'http://my.nudevista.com';
				}
				return;
			}
			if ($('form.iphone').length) {
				$(this).css('background-position','-50px 0px').attr('title','Remove from Favorites').addClass('remove').removeClass('add');
			} else {
				$(this).css('background-position','-45px 0px').attr('title','Remove from Favorites').addClass('remove').removeClass('add');
			}
    		$(this).parent().removeClass('deleted');
			$(this).next().children('img').eq(0).clone(true).attr('name',$(this).next().children('img').eq(0).attr('id')).attr('id','fly').css('position','absolute').insertAfter(this).animate({
				marginTop: -$(this).position().top+5,
				marginLeft: $(window).width()-$(this).position().left-150,
				height: 10,
				width: 10,
		        opacity: 0.2
		      }, 700 ,function(){
		    	$('#mf').text(faved($(this).attr('name'),true));
		    	$(this).remove();
		      });
		} else {
			if ($('form.iphone').length) {
				$(this).css('background-position','0px 0px').attr('title','Add to Favorites').removeClass('remove').addClass('add');
			} else {
				$(this).css('background-position','-15px 0px').attr('title','Add to Favorites').removeClass('remove').addClass('add');
			}
	    	faved($(this).next().children('img').eq(0).attr('id'));
	    	if (window.top.location.href.indexOf('/favorites/')!=-1) {
	    		$(this).parent().addClass('deleted');
	    	}
		}
	});
	
	$('td img').each(function(){
		if ($(this).attr('src').indexOf('http://t')!==-1) $(this).width(185);
	})
	
	$('.results td img').css('border','1px solid gray');
	
	/* sharing */
	$(".results a.name").each(function(){
//		if ($(this).children('img').attr('share')=='share') {
//			$(this).prepend($('<div class="share" title="Embed video"></div>'));
//		}
		if ($.cookie('nw')==1) $(this).attr('target','_self');
	})
	
	/* thumb rotate */
	$("#results td a img, #results_2 td a img").hover(
		function() {
			if ($.cookie("at")==1) return true;
			$(this).parent().parent().children('div').addClass('stable');
			cImg = this.id;
			cTmt = window.setTimeout('shownext()',50);
		},
		function() {
			$(this).parent().parent().children('div').removeClass('stable');
			stop(cImg);
			cImg = false;
			window.clearTimeout(cTmt);
		}
	);
	
	/* tabs */
	$('#iti a, #it a').click(function(){
		
		if ( ($(this).attr('id')=='livesex') || ($(this).hasClass('noclick')) ) return true;
		
		var s = $(this).attr('href').split('&s='); s = (s[1]) ? s[1] : '';
		var q = $('#q').val(); if (q=='') {
			q = '*';
			$('#q').val('*');
		}
		
		if ( (q=='*') && (s=='s') ) {
			window.top.location.href='/models/';
			return false;
		}
		
		if (s=='') {
			$('#set').attr('disabled','disabled');
		} else {
			$('#set').removeAttr('disabled');
			$('#set').val(s);
		}
		
		$('#formsearch').submit();
		return false;
	})
	
	_current_position = 1;
	$(".results td img").each(function(){
		$(this).attr('position',_current_position++);
	})

	$(".results td img").click(function(){
		
//		if ($(this).attr('share')) { share_result = share($(this).attr('id')) }

		$.post('http://click.nudevista.com/',{
			"i":$(this).attr('id'), "p":$(this).attr('position'), "c":$('a.name img').length, "a": ($('.addon').length) ? 'addon' : ''
			},function(data){
			}
		);

//		if ($(this).attr('share')) { return share_result; }

		return true;
	});

	$("#results a.name").parent().hover(
		function() {
			
				if ($.cookie("mi")==1) return true;
				if($.browser.msie){
					userAgent = $.browser.version;
					userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
					version = userAgent;
					if (version==6)  return true;
				}

				$('#info').remove();
				
				$(this).append('<p id="info" style="display:none"></p>')

				inerthtml = '';

				if ($(this).children('b').length && $(this).children('b').html()!='') {
					inerthtml += '<p class="name"><a href="'+ $(this).children('a').attr('href') +'" target="'+ $(this).children('a').attr('target') +'">'+ $(this).children('b').html() +'</a></p>';
				} else {
					$('#info').css('padding-top','4px').css('margin-top','0px');
				}

				temp_ob = $(this).children('small').children('i.tube');
				if ( temp_ob.length ) {
					inerthtml += '<p class="tube">Tube: ' + clearcomma(temp_ob.html()) + '</p>';
				}
				
				temp_ob = $(this).children('small').children('i.site');
				if ( temp_ob.length ) {
					inerthtml += '<p class="site">Site: ' + clearcomma(temp_ob.html()) + '</p>';
				}
				
				temp_ob = $(this).children('small').children('i.model');
				if ( temp_ob.length ) {
					inerthtml += '<p class="model">Model' + ( temp_ob.length > 1 ? 's' : '' ) + ': ';
					temp_ob.each(function(){
						inerthtml += $(this).html();
					});
					inerthtml = clearcomma(inerthtml) + '</p>';
				}
				
				temp_ob = $(this).children('small').children('i.tag');
				if ( temp_ob.length ) {
					inerthtml += '<p class="tag">Tag' + ( temp_ob.length > 1 ? 's' : '' ) + ': ';
					temp_ob.each(function(){
						inerthtml += $(this).html();
					});
					inerthtml = clearcomma(inerthtml) + '</p>';
				}
				
				temp_ob = $(this).children('small').children('i.date');
				if ( temp_ob.length ) {
					inerthtml += '<p class="date">Added ' + temp_ob.html() + '</p>';
				}
	
//				if ($(this).children('a.name').children('img').attr('share')=='share') {
//					inerthtml += '<p class="share">Embed video</p>';
//				}
				if (window.top.location.href.indexOf('/favorites/')==-1) {
					inerthtml += '<p class="flag"><a href="#/flag" onClick="return gallery_flag('+ $(this).children('a.name').children('img').attr('id') +')" class="flag">Report problem</a>';
					if ($.cookie('NVSIDA')) inerthtml += ' or <a href="#/edit" onClick="return gallery_edit('+ $(this).children('a.name').children('img').attr('id') +')" class="edit">edit</a>';
					inerthtml += '</p>';
				}
				
				$('#info').html(inerthtml);
				
				$('#info').hover(
					function(){
						$(this).addClass('hover');
					},function(){
						$(this).removeClass('hover');
					}
				);

				$("#info .name a").click(function(){
					$.post('http://click.nudevista.com/',{
						"i":$(this).parent().parent().parent().children('a.name').children('img').attr('id'), "p":$(this).parent().parent().parent().children('a.name').children('img').attr('position'), "c":$('a.name img').length, "a": ($('.addon').length) ? 'addonname' : 'name'
						},function(data){
						}
					);
				});
				
				
				$(this).children('b').slideUp(150);
				$(this).children('small').slideUp(150,function(){
					$(this).hide();
					$('#info').slideDown('fast');
				});
		},
		function() {
			
			if ($.cookie("mi")==1) return true;
			
			$('#info').remove();
			$(this).children('small').slideDown('fast');
			$(this).children('b').slideDown('fast');
		}
	);

	$('i.date').each(function(){if ($(this).text()!='today' && $(this).text()!='Added today') $(this).text($(this).text()+' ago') });
	
	if ($('#livesearch').length) showlive();
	shownext();

//	if ( (location.hash!="") && (location.hash!="#")) share(location.hash);

	/* admin */
	$('#send_to_pi a').click(function(){
		$('body').append('<div id="embedbg"><img src="http://i99.nudevista.com/_/loader_b.gif"></div>'); $('#embedbg').height($(document).height()); $('#embedbg img').css('margin-top',Math.round($(window).height()/2)-30+$(document).scrollTop()); $('#embedbg').fadeTo('slow',0.7);
		$('body').append('<div id="embedpl"><div class="header"><img src="http://i99.nudevista.com/_/pi.png" border="0" align="absmiddle" />Send</div><div class="message"><form><input type="hidden" name="porninspector" value="1"><div><div style="width:700px;margin-top:20px" class="thumbs"></div>' +
		'<p class="send_help">&nbsp;Select galleries by left click.</p><p><input type="button" value="Send to PornInspector" class="save"> &nbsp; <a href="#/close/" class="close" onclick="return share_destroy()">Oh no, it was misclick</a></p></form></div></div>');
		$('#embedbg').html('');
		$('a.name img').each(function(){ id = $(this).attr('id'); if ( ((id % 10) == 1) ) { $('.thumbs').append($(this).clone().attr('id','d'+id)); $('.thumbs').append('<input type="checkbox" value="'+id+'" name="send[]" style="display:none" id="send'+id+'" />'); } })
		if (!$('.thumbs').children().length) {
			$('.thumbs').append('<div>Nothing to send</div>'); $('.save').attr('disabled','disabled'); $('.send_help').hide();
		} else {
			$('.thumbs img').css('height','90px'); $('.thumbs img').fadeTo('slow',0.4)
			$('.thumbs img').click(function(){ if ($(this).hasClass('selected')) { $(this).fadeTo('slow',0.4); $(this).removeClass('selected'); $('#sen' + $(this).attr('id')).removeAttr('checked'); } else { $(this).fadeTo('slow',1); $(this).addClass('selected'); $('#sen' + $(this).attr('id')).attr('checked','checked'); } })
			$('#embedpl input.save').click(function(){
				$.post('/e.html?'+Math.random(),$('#embedpl div.message form').serialize(),function(data){ $('#embedpl div.message').html('<p>Successfully sended. Galleries will be included in next export and during next twenty four hours they will appear on PornInspector.</p><p><a href="#/close/" class="close" onclick="return share_destroy()">Yes, thanks, I understand</a></p>'); share_position(); });
				share_position(); return false;
			});				
		}
		share_position(); return false;
	})
	$('#correct a.remove').click(function(){
		if (!confirm('Remove "'+ $(this).attr('request') +'" from spell checking?')) return false;
		$('#admin_form').attr('action','/e.html');
		$('#admin_form').append('<input type="hidden" name="spell_remove" value="'+ $(this).attr('request') +'" />');
		$('#admin_form').submit();
		return false;
	});
	$('.relcat a.edit').click(function(){
		$('li.relrel').slideUp('fast',function(){$('li.reledit').slideDown('fast')});
		return false;
	})
	$('.relcat a.cancel').click(function(){
		$('li.reledit').slideUp('fast',function(){$('li.relrel').slideDown('fast')});
		return false;
	})

})

var currentTr = 0;
function resize_results() {

	if (!$('#listing_advert').length) return;

	if($.browser.msie){
		userAgent = $.browser.version;
		userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
		version = userAgent;
		if (version==6) {
			$('.middle, .results').width('1000px');
			$('#advert').css('position','absolute');
			$('#advert').show();
		}
	}
		
	var maxLine = ($('#model').length) ? 2 : 3;
	if ( ($('#listing_advert').width() > 780) && ($('#listing_advert').attr('resized')) ) {
		$('#listing_advert').removeAttr('resized');
		currentTr = 0;
		$('td.addon').each(function(){
			tr = $(this).parent();
			$(this).removeClass('addon').appendTo($('tr').eq(currentTr));
			if ($(tr).children('td').length == 0) $(tr).remove();
			currentTr++;
		})

	} else if ( ($('#listing_advert').width() < 780) && !($('#listing_advert').attr('resized')) ) {
		$('#listing_advert').attr('resized','resized');

		$('#listing_advert tr').each(function(){
			if ( ($(this).children('td').length > maxLine) ) {
				if ( ($('#listing_advert tr').last().children('td').length > maxLine-1) ) {
					$('<tr></tr>').appendTo($('#listing_advert').children('table'));
				}
			$(this).children('td').eq(maxLine).addClass('addon').appendTo($('#listing_advert tr').last());
			}
		});
	}

	if ( $('#advert').css('display') == 'none' ) $('#advert').show();
}


function faved(id,act) {
		
	var cf = $.cookie("favs");
	cf = (cf) ? cf : '|';
	cf = cf.replace('||','|');
	cf = cf.replace('||','|');
	cf = cf.replace('||','|');
	if (act) {
		if (cf.indexOf('|' + id + '|' )==-1) $.cookie("favs", cf + id + '|', { path: '/', expires: 365 , domain: '.nudevista.com'});
		return $.cookie("favs_count")*1 + ($.cookie("favs").split('|').length - 2);
	} else {
		if (cf.indexOf('|' + id + '|' )!=-1) $.cookie("favs", cf.replace('|' + id,''), { path: '/', expires: 365 , domain: '.nudevista.com' });
		$.post('/s.html?'+Math.random(),{'id':id,'remove':1},function(data){
			$('#mf').text(data);
		});
	}
}

function stop(id) {
	iImg = $('#'+id);
	src = $(iImg).attr('src');
	cur = src.split('.');
	cur = cur[cur.length-2];
	return $(iImg).attr('src',src.replace(Math.floor(id/10)+'.'+cur+'.jpg',Math.floor(id/10)+'.jpg'));
}

function shownext() {
	window.clearTimeout(cTmt);
	if (cImg==false) return;
	
	iImg = $('#'+cImg);
	oSrc = icount($(iImg).attr('num'),$(iImg).attr('src'),cImg);
	if (oSrc!=false) $(iImg).attr('src',oSrc); 

	if (
//		( $(iImg).parent().attr('href').indexOf('slutload')==-1 ) &&
		( $(iImg).parent().attr('href').indexOf('pornomovies')==-1 )
	) cTmt = window.setTimeout('shownext()',750);
}

function icount(cnt,src,id) {
	if (!cnt) return false;
	cnt = cnt*1 - 1;
	if (cnt==0) return false;
	
	cur = src.split('.');
	cur = cur[cur.length-2];
	
	if (cur.length!=1) return src.replace(Math.floor(id/10)+'.jpg',Math.floor(id/10)+'.'+1+'.jpg');
	if ( (cur*1) == cnt) return src.replace(Math.floor(id/10)+'.'+cur+'.jpg',Math.floor(id/10)+'.jpg');
	return src.replace(Math.floor(id/10)+'.'+cur+'.jpg',Math.floor(id/10)+'.'+(cur*1+1)+'.jpg');
}

currentTitle = '';

function share(shareId) {
	return true;
		
	if ($.cookie("ss")==1) return true;
	
	if ($('form.iphone').length)  return true;
	if ($('form.phone').length)  return true;
	
	if (shareId!=window.location.hash) {
		currentHref = window.top.location.href.indexOf('#');
		currentHref = (currentHref==-1) ? window.top.location.href : window.top.location.href.substr(0,currentHref)
		currentTitle = document.title;
	
		if ($('#'+shareId).length) $('#'+shareId).attr('id',shareId+'_tmp');
	
		fx = $( '<a></a>' ).css({position:'absolute',visibility:'hidden',top: $(document).scrollTop() + 'px'}).attr( 'id', shareId ).appendTo( document.body );
		window.top.location.href = currentHref + '#' + shareId;
		fx.remove();
		if ($('#'+shareId+'_tmp').length) $('#'+shareId+'_tmp').attr('id',shareId);
		document.title = currentTitle;
	} else {
		shareId = shareId.replace('#','');
	}

	share_destroy();
	
	$('body').append('<div id="embedbg"><img src="http://i99.nudevista.com/_/loader_b.gif"></div>');
	$('#embedbg').height($(document).height());
	$('#embedbg img').css('margin-top',Math.round($(window).height()/2)-30+$(document).scrollTop());
	$('#embedbg').fadeTo('slow',0.7);
	$.get('/p.html?'+shareId+'&'+Math.random(),function(data){
		if (data.indexOf('<')==-1) {
			return share_destroy();
		}
		$('body').append('<div id="embedpl">'+data+'</div>');
		addthis.toolbox("#toolbox");
		$('#embedbg').html('');
		if ($('#embedpl #embedsrcid').length) {
			$('#embedpl').width($('#embedpl #embedsrcid').width());
			$('#embedpl').height($('#embedpl #embedsrcid').height()*1 + 30);
		} else if ($('#embedpl embed').length) {
			$('#embedpl').width($('#embedpl embed').css('width').replace('px',''));
			$('#embedpl').height($('#embedpl embed').css('height').replace('px','')*1 + 30);
		} else {
			$('#embedpl').width($('#embedpl object').width());
			$('#embedpl').height($('#embedpl object').height()*1 + 30);
		}
		$('body').append('<iframe id="embedadv" src="http://i99.nudevista.com/_/eroadverttxt.html" scrolling="no"></iframe>');
		$('#embedadv').height($('#embedpl').height()-30);
		$('#embedpl a.close').click(function(){
			window.location.hash="";
			
			share_destroy();
			document.title = currentTitle;
			return false;
		});
		$('#embedpl a.stopsharing').click(function(){
			$('#embedpl').html('<div class="header"><img src="http://i99.nudevista.com/_/ico-cancel.png" border="0" align="absmiddle" />Stop sharing?</div><div class="message"><p>Sharing is a new feature on the site NudeVista.com.<br />Now you can play many videos without leaving the site, simply by clicking on the preview.<br />You can cancel this functionality and all the videos again will lead to the tubes.</p><p><a  href="#/stop-sharing/" class="stopsharing">Yes, I want to cancel Sharing</a> &nbsp; &nbsp;  <a href="#/close/" onclick="return share_destroy();" class="close">No, I like it</a></p></div>');
			$('#embedpl').width('auto');
			$('#embedpl').height('auto');
			share_position();
			
			$('#embedpl a.stopsharing').click(function(){
				$.cookie("ss", 1, { path: '/', expires: 365, domain: '.nudevista.com' });
				share_destroy();
				document.title = currentTitle;
				return false;
			});
			
			return false;
		});
		share_position();
	});

	document.title = currentTitle;
	return false;
}

$(document).keyup(function(e) {
  if (e.keyCode == 27) { share_destroy(); }   // esc
});

function share_position() {

	if (!$('#embedpl').length) return true;
	tTop = Math.round(($(window).height() - $('#embedpl').height())/2)+$(document).scrollTop();
	tTop = tTop<$(document).scrollTop()?$(document).scrollTop():tTop;
	$('#embedpl').css('top',tTop);
	$('#embedadv')
		.css('top',tTop+30)
		.css('left', ($('#advert').length) ? $('#advert').position().left-7 : ( ($('#livesex').length) ? ($('#livesex').position().left-182) : 700)  );
	tLeft = Math.round(($(window).width() - $('#embedpl').width())/2)-60;
	tLeft = ( tLeft + $('#embedpl').width() + 320 > $(window).width() ) ? $(window).width() - $('#embedpl').width() - 320 : tLeft;
	tLeft = ( tLeft < 0 ) ? 0 : tLeft;
	$('#embedpl').css('left',tLeft);

	return true;
}

function share_destroy() {
	$('#embedbg').remove();
	$('#embedpl').remove();
	$('#embedadv').remove();
	return false;
}

$(window).scroll(function(){return share_position()});
$(window).resize(function(){resize_results();share_position();});


function clearcomma(text) {
	text = text.replace(/\s+$/,"");
	if (text[text.length-1] == ',') {
		text = text.substring(0,text.length-2);
	}
	return text + ' ';
}

function gallery_edit(id) {
	share_destroy();
	
	$('body').append('<div id="embedbg"><img src="http://i99.nudevista.com/_/loader_b.gif"></div>');
	$('#embedbg').height($(document).height());
	$('#embedbg img').css('margin-top',Math.round($(window).height()/2)-30+$(document).scrollTop());
	$('#embedbg').fadeTo('slow',0.7);
	$.post('/e.html?'+Math.random(),{'id':id,'edit':1},function(data){
		if (data.indexOf('<')==-1) {
			return share_destroy();
		}
		$('body').append('<div id="embedpl"><div class="header"><img src="http://i99.nudevista.com/_/ico-edit.png" border="0" align="absmiddle" />Edit</div>' +
		data +
		'</div>');
		$('#embedbg').html('');
		share_position();

		$('#embedpl div.message img').click(
			function(){
				if ($(this).hasClass('deleted')) return false;
				$('#embedpl div.message img.main').removeClass('main');
				$(this).addClass('main');
				$('#embedpl div.message input[name="main"]').val($(this).attr('name'));
			}
		);
		
		$('#embedpl div.message img').bind("contextmenu",function(e){
				if ($(this).hasClass('main')) return false;
				if ($(this).attr('nodelete')) return false;
				$(this).toggleClass('deleted');
				$('#embedpl div.message input[name="deleted['+ $(this).attr('name') +']"]').attr('checked',($(this).hasClass('deleted')));
				return false;
			}
		);

		$('#embedpl input.save').click(function(){
			$.post('/e.html?'+Math.random(),$('#embedpl div.message form').serialize(),function(data){
				$('#embedpl div.message').html('<p>Successfully saved. Please note that to view the changes you need to press Ctrl+F5,<br />but this may not be achievable due to caching on the server side.</p><p><a href="#/close/" class="close" onclick="return share_destroy()">Yes, thanks, I understand</a></p>');
				share_position();
			});
			share_position();
			return false;
		});
		
		$('#embedpl input.remove').click(function(){
			if (!confirm('You are sure to remove?')) return false;
			$.post('/e.html?'+Math.random(),{'id':id,'remove':1},function(data){
				$('#embedpl div.message').html('<p>Successfully deleted.</p><p>Gallery will be excluded from the search results after next indexing.</p><p><a href="#/close/" class="close" onclick="return share_destroy()">Yes, thanks, I understand</a></p>');
				share_position();
			});
			share_position();
			return false;
		});
		
		$('#embedpl input.delete').click(function(){
			if (!confirm('Are you sure?\nFor immediate removal of the pages appear blank spaces instead of images since the next inspection')) return false;
			$.post('/e.html?'+Math.random(),{'id':id,'delete':1},function(data){
				$('#embedpl div.message').html('<p>Gallery removed.</p><p>Refresh the page if you want to look at the result.</p><p><a href="#/close/" class="close" onclick="return share_destroy()">Yes, thanks, I understand</a></p>');
				share_position();
			});
			share_position();
			return false;
		});
		
		share_position();
	});
	return false;
}

function gallery_flag(id) {
//	share_destroy();
	
	if ($('#embedbg').length) {
		$('#embedbg').html('<img src="http://i99.nudevista.com/_/loader_b.gif">');
		$('#embedpl').remove();
	} else {
		$('body').append('<div id="embedbg"><img src="http://i99.nudevista.com/_/loader_b.gif"></div>');
		$('#embedbg').height($(document).height());
	}
	$('#embedbg img').css('margin-top',Math.round($(window).height()/2)-30+$(document).scrollTop());
	$('#embedbg').fadeTo('slow',0.7);
	$.post('/e.html?'+Math.random(),{'id':id,'flag':1},function(data){
		if (data.indexOf('<')==-1) {
			return share_destroy();
		}
		$('body').append('<div id="embedpl"><div id="buttons" style="float:right"><div><a href="#/close/" onclick="return share_destroy()" class="close"><img src="http://i99.nudevista.com/_/ico-stop.png" border="0" align="absmiddle" /></a><a href="#/close/" onclick="return share_destroy()" class="close">Close</a></div></div><div class="header"><img src="http://i99.nudevista.com/_/ico-flag.png" border="0" align="absmiddle" />Report this</div>' +
		data +
		'</div>');
		$('#embedbg').html('');
		share_position();

		$('#embedpl input.save').click(function(){
			$.post('/e.html?'+Math.random(),$('#embedpl div.message form').serialize(),function(data){
				$('#embedpl div.message').html('<p>Successfully sended.<br />Thank you for assistance. Together we\'ll make it better!</p><p><a href="#/close/" class="close" onclick="return share_destroy()">Yes, shure!</a></p>');
				share_position();
			});
			share_position();
			return false;
		});
				
		share_position();
	});
	return false;
}

current_block=1;

function showlive() {
	
	if (!$('#livesearch').length) return;
	if ($('#livesearch div').length==1) {
		for(i=1;i<=7;i++) $('#livesearch').append('<div class="tag"/>');
		$('#listing').css('margin-top','7px').css('position','relative');
		$('#livesearch .t').append('<br /><a href="#/switch-off/" id="switch">switch it off</a>');
		$('#livesearch #switch').click(function(){
			$(this).parent().parent().fadeOut('slow',function(){
				$(this).remove();
				$('#listing').css('margin-top','12px').css('position','relative');
				$.cookie("ls", 1, { path: '/', expires: 365, domain: '.nudevista.com' });
			})
			return false;
		});
	}

	$.get('/_tools/live_search.html?limit=7&'+Math.random(),function(data){
		$(data.split('|')).each(function(){
			obl = $('#livesearch').children(':eq('+ current_block +')');
			obl.append('<div><a href="/?q=' + this.toLowerCase().replace(/ /gi,'+') + '">'+ this +'</a></div>').hover(function(){
				$(this).addClass('stop');
			},function(){
				$(this).removeClass('stop');
			});
			current_block++; if (current_block==8) current_block = 1;
		})
		hidelive();
	});
	
	window.setTimeout('showlive()',7000);
}

function hidelive(ob) {
	if ($(ob).hasClass('tag')==false) {
		ob=$('#livesearch div.tag')[0];
	}
	if ($(ob).children().length<2) return;
	
	if ($(ob).hasClass('stop')) {
		hidelive($(ob).next());
		return;
	}
	
	$(ob).children(':eq(0)').slideUp('fast',function(){
		next = $(this).parent().next();
		$(this).remove();
		hidelive(next);
	})
}

