$.extend($.fn, {
	reset: function() {
		return $(this).each(function() {
			$(this).is('FORM') && this.reset();
			$(this).is('INPUT') && $(this).attr({
				value: ''
			});
		});
	}
});
var AjaxRequester = {
	replaceScripts: function(str, path) {
		var head = $('head');
		if ( $(head).is('head') ) {
			var exists = false;
			$(head).find('script[rel=' + path + ']').each(function(i) {
				exists = true;
			});
			$(head).find('script[src=' + path + ']').each(function(i) {
				exists = true;
			});
			if ( !exists ) {
				$.ajax({
					type: 'GET',
					url: path,
					data: '',
					async: false,
					success: function() {
					},
					dataType: 'script'
				});
				var script = document.createElement('script');
				$(script).attr({
					type: 'text/x-javascript',
					rel: path
				});
				head[0].appendChild(script);
			}
		}
		return '';
	},
	replacePageTitle: function(str, title) {
		if ( title.length > 0 ) {
			document.title = title;
		}
		return '';
	},
	replaceStyles: function(str, href) {
		var head = document.getElementsByTagName('HEAD');
		if ( $(head).is('head') ) {
			var exists = false;
			$(head).find('link[href=' + href + ']').each(function(i) {
				exists = true;
			});
			if ( !exists ) {
				var link = document.createElement('link');
				$(link).attr({
					rel: 'stylesheet',
					href: href
				});
				head[0].appendChild(link);
			}
		}
		return '';
	},
	callback: function(data, container) {
		var scripts = [];
		data = data.replace(/<script[^>]*?src[^=]*?=\"([^>]+?)\"[^>]*?><\/script>/gi, AjaxRequester.replaceScripts);
		data = data.replace(/<title>([^>]*?)<\/title>/gi, AjaxRequester.replacePageTitle);
		data = data.replace(/<link[^>]*?href[^=]*?=\"([^>]+?)\" \/>/gi, AjaxRequester.replaceStyles);
		var q, b = 0;
		while ( (q = data.indexOf('<script', b)) != -1 ) {
			var b = data.indexOf('>', q);
			if ( b != -1 ) {
				b += 1;
			}
			var j = data.indexOf('</script>', q);
			if ( j != -1 ) {
				scripts[scripts.length] = data.substr(b, j - b);
				data = data.substr(0, q) + data.substr(j + 9);
			}
		}
		container = container || 'center';
		if ( window.popup ) {
			container = $(window).attr('popup');
			$('#' + container).css({
				top: $(document).scrollTop() + 50
			});
		}
		if ( data.length > 0 ) {
			$('#' + container).empty().html(data).show();
		}
		if ( window.popup ) {
			$(document.createElement('DIV')).appendTo($('#' + container)).attr({
				id: 'close-btn'
			})
			.click(function() {
				$('#popup-overlay').click();
			});
		}
		try {
			for ( var i in scripts ) {
				if ( scripts[i] != '' ) {
					try {
						$.globalEval(scripts[i]);
					} catch ( e ) {
					}
				}
			}
			$.applyUI();
		} catch ( e ) {
		}
	},
	load: function(url, form, container, method, callback) {
		var data = [];
		if ( $(form).is('FORM') ) {
			data = $(form).serializeArray();
		}
		var method = method || 'GET';
		callback = callback || function(str) {
			AjaxRequester.callback(str, container);
		};
		try {
			$.ajax({
				type: method,
				url: url,
				data: data,
				success: callback,
				dataType: ''
			});
		} catch ( e ) {
		}
	}
}
$.applyUI = function() {
	/* Price range */
	var range1 = $('input[name="FILTER[PRICE_FROM]"]').val();
	var range2 = $('input[name="FILTER[PRICE_TO]"]').val();
	$('#slider-range').slider({
		range: true,
		min: 0,
		max: 100000,
		values: [range1, range2],
		slide: function(event, ui) {
			$('input[name="FILTER[PRICE_FROM]"]').val(ui.values[0]);
			$('input[name="FILTER[PRICE_TO]"]').val(ui.values[1]);
		}
	});
}
var snow = false;
$(document).ready(function() {
	/* Search autocomplete */
	$('input#search-query[autocomplete="on"]').autocomplete('/search/', {
		dataType: "json",
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					value: row.value,
					result: row.value
				}
			});
		},
		formatItem: function(item) {
			return item.value;
		}
	});
	/* Snow */
	if ( snow ) {
		$().jSnow({
			zIndex: 1000000,
			flakes: 100
		});
	}
	$('#tag-cloud ul > li').tsort({
		order: 'rand'
	});
	$('#tag-cloud ul').tagcloud({
		type: 'list',
		sizemin: 8,
		height: 300,
		width: 300,
		colormin: 'd88',
		colormax: '0a0'
	});
	$('body').bind('copy', function(e) {
		alert('При копировании текстов не забывайте указывать ссылку на первоисточник, а именно http://www.1000v1.ru/');
	});
	var overlay = document.createElement('DIV');
	$(overlay).appendTo(document.body).hide()
	.attr({
		id: 'popup-overlay'
	})
	.height($(window).height() + 'px').click(function() {
		$(this).hide();
		$('#' + $(window).attr('popup')).remove();
		$('#' + 'overlay-frame').hide();
		$(window).attr({
			popup: ''
		});
	});
	/* Overlay iframe */
	var overlay = document.createElement('IFRAME');
	$(overlay).height($(window).height() + 'px').appendTo(document.body).hide()
	.attr({
		src: 'javascript:\'\';',
		scrolling: 'no',
		frameborder: 0,
		id: 'overlay-frame'
	});
	/* Togglers */
	$('#phone > div.all > b.toggler').click(function() { $('#all-cities').show(); });
	$('#all-cities > div.close > b.toggler').click(function() { $('#all-cities').hide(); });
	$('#opinions div.add b.toggler').click(function() {
		$('#add-comment').show();
	});
	$('#opinions div.all b.toggler').click(function() {
		$('#opinions div.hidden-opinion').removeClass('hidden-opinion').addClass('opinion');
		$(this).hide();
	});
	$('#add-comment input.close').click(function() {
		$('#add-comment').hide();
	});
	$('#quick-search form').submit(function() {
		var searchVal = $(this).find('input#search-query').val();
		if ( searchVal == 'Поиск товара' || searchVal == '' ) {
			alert('Пустой поисковый запрос');
			return false;
		}
	});
	var prevSQuery = '';
	$('input#search-query').focus(function() {
		prevSQuery = $(this).val();
		if ( prevSQuery == 'Поиск товара' ) {
			$(this).val('');
		}
	})
	.blur(function() {
		var curSQuery = $(this).val();
		if ( curSQuery == '' ) {
			if ( prevSQuery != '' ) {
				$(this).val(prevSQuery);
			} else {
				$(this).val('Поиск товара');
			}
		}
	})
	.keypress(function() {
		prevSQuery = '';
	});
	$('#filter div.toggler b.toggle').live('click', function() {
		var fields = $('#filter').find('div.filter-fields');
		if ( $(fields).css('display') !== 'none' ) {
			$(fields).hide();
		} else {
			$(fields).show();
		}
	});
	$('#vendors input').live('click', function() {
		$(this).parents('form').submit();
	});
	$('#quick-search p.for-example b.example').click(function() { $('#quick-search input#search-query').val($(this).text()); });
	$('#short-brands div.toggler b.all').click(function() {
		$(this).hide();
		$(this).next('b.short').show();
		$('#short-brands').find('div.short-list').hide();
		$('#all-brands').show();
	});
	$('#short-brands div.toggler b.short').click(function() {
		$(this).hide();
		$(this).prev('b.all').show();
		$('#short-brands').find('div.short-list').show();
		$('#all-brands').hide();
	});
	$('#order a.toggler').click(function() {
		var el = $(this).attr('href');
		if ( $(el).css('display') !== 'none' ) {
			$(el).hide();
			$(this).css('font-style', '');
		} else {
			$(this).css('font-style', 'italic');
			$(el).show();
		}
		return false;
	});
	/* Buttons */
	$('a.short-view, a.detail-view').live('click', function() {
		var btnsWrap = $(this).parents('div.buttons');
		$(btnsWrap).find('li').removeClass('active');
		$(this).parent().parent().addClass('active');
	});
	$('a.short-view').live('click', function() {
		$(this).parents('div.block').find('div.catalog-row').each(function(i) {
			$(this).find('div.detail-product').removeClass('detail-product').addClass('short-product');
		});
		var modeToggler = $(this).parents('.view-mode');
		if ( $(modeToggler).is('DIV') ) {
			$.cookie($(modeToggler).attr('id') + '_VIEW_MODE', 'S', {
				path: '/'
			});
		}
	});
	$('a.detail-view').live('click', function() {
		$(this).parents('div.block').find('div.catalog-row').each(function(i) {
			$(this).find('div.short-product').removeClass('short-product').addClass('detail-product');
		});
		var modeToggler = $(this).parents('.view-mode');
		if ( $(modeToggler).is('DIV') ) {
			$.cookie($(modeToggler).attr('id') + '_VIEW_MODE', 'D', {
				path: '/'
			});
		}
	});
	if ( !$('#see-also').is('DIV') ) {
		$('#see-also-btn').remove();
	}
	/* Rating */
	$('div.rating ul.units li a').click(function() {
		var grade = parseInt($(this).text());
		$(this).parent().parent().find('li.current-rating').width(17 * grade);
		$(this).parent().parent().parent().parent().find('input[name="ELEMENT_GRADE"]').val(grade);
	});
	/* Photos */
	var photos = $('div.short-product div.photo a img, #compare div.photo img');
	$.each(photos, function(i) {
		$(this).attr('src', $(this).attr('src') + '?' + Math.random());
		$(this).load(function() {
			height = $(this).height();
			if ( height <= 93 ) {
				j = (93 - $(this).height())/2;
				if ( j > 5 ) {
					$(this).css('margin', j + 2 + 'px 0');
				}
			}
		});
	});
	/* Photos */
	$('.photos a').hover(function() {
		$('.big-photo img').attr({
			src: $(this).attr('href').replace(/\/data\/uploads\//i, '/data/thumbs/200/200/P/')
		});
		$('.photos li').removeClass('active');
		$(this).parent().addClass('active');
	});
	/* Help */
	$('#filter .help').hover(function() {
		$('<div class="help-popup">' + $(this).find('span').text() + '</div>').insertAfter($(this));
	}, function() {
		$('.help-popup').remove();
	});
	/* Widgets */
	$('#widgets .blink').fadeOut(1000).fadeIn(600, function() {
		$(this).css('opacity', 0.9);
		$(this).fadeOut(1000).fadeIn(600).fadeOut(1000, function() {
			$(this).css('opacity', '');
			$(this).fadeIn(600);
		});
	});
	/* Callback */
	$('#callback img').click(function() {
		var opened = $('#callback').hasClass('open');
		$('#callback').toggleClass('open');
		$('#callback .form-wrap').animate({
			width: 'toggle'
		}, 500, function() {
			if ( opened ) {
				if ( !$('#callback .result .error').is('DIV') ) {
					$('#callback form').reset();
				}
				$('#callback .result').remove();
				$('#callback form').show();
			}
		});
	});
	$('#callback .result .error b').live('click', function() {
		$(this).parents('.result').hide();
		$('#callback form').show();
	});
	$('#callback form').submit(function() {
		$('#callback form .submit').attr("disabled", "disabled");
		var form = $(this);
		$('#callback .result').remove();
		data = $(form).serializeArray();
		try {
			$.ajax({
				type: 'POST',
				url: '/websms/gate.php',
				data: data,
				success: function (str) {
					$('#callback form .submit').removeAttr("disabled");
					$(str).insertAfter($(form));
					$(form).hide();
				},
				dataType: ''
			});
		} catch ( e ) {
		}
		return false;
	});
	/* Zoom */
	$('.photos').ImageZoom();
	/* Apply UI */
	$.applyUI();
	/* Cart */
	function basketUpdate() {
		$.ajax({
			type: "GET",
			url: '/basket/?SHORT_BASKET=Y',
			success: function(str) {
				$('#short-cart').html($(str).html());
			},
			dataType: ''
		});
	}
	/* Ajax */
	$('a.basket.add').live('click', function() {
		var container = 'popup-window';
		if ( !$('#' + container).is('DIV') ) {
			var popup = document.createElement('DIV');
			$(popup).appendTo(document.body).hide().attr({
				id: container
			});
		} else {
			popup = $('#' + container);
		}
		$(window).attr({
			popup: $(popup).attr('id')
		});
		$(popup).addClass('basket-popup');
		var url = $(this).attr('href');
		if ( url.length > 0 ) {
			AjaxRequester.load(url, '', container, 'GET', function(str) {
				AjaxRequester.callback(str);
				basketUpdate();
			});
			$('#popup-overlay').show();
		}
		return false;
	});
	$('a.compare.add').click(function() {
		var button = $(this);
		$.ajax({
			type: 'GET',
			url: $(this).attr('href'),
			success: function() {
				var url = $(button).attr('href');
				var re = /\/catalog\/(\d+)\/detail\/(\d+)\/compare\//g;
				url = url.replace(re, '/catalog/compare/$1/');
				$(button).text('Сравнить').removeClass('add').addClass('active').attr('href', url).attr('onmouseover', '').unbind('click').unbind('mouseover').click(function() {
					var url = $(this).attr('href');
					openWin(url);
					return false;
				});
			},
			async: false
		});
		return false;
	});
	/* Forms */
	$('label').live('click', function() {
		$(this).next(':input').focus();
	});
	$('.err-field').mousedown(function() {
		$(this).removeClass('err-field');
	})
	.blur(function() {
		var v = $(this).val() || [];
		if ( v.length == 0 ) {
			$(this).addClass('err-field');
		}
	})
	.change(function() {
		$(this).removeClass('err-field');
	});
	/* Hot keys */
	$(document).keypress(function(event) {
		if ( !event ) {
			event = window.event;
		}
		var key = event.keyCode;
		if ( event.ctrlKey ) {
			var el;
			if ( key == 37 ) {
				el = $('.prev a');
			}
			if ( key == 39 ) {
				el = $('.next a');
			}
			if ( $(el).is('A') ) {
				$(el).trigger('mouseover');
				var url = $(el).attr('href');
				window.location = url;
			}
		}
	});
}).ajaxSend(function() {
	$('#overlay-frame').show().height($(window).height() + 'px');
}).ajaxComplete(function() {
	if ( !window.popup ) {
		$('#overlay-frame').hide();
	}
});
function openWin(url, width, height) {
	var top = 0, left = 0;
	if ( !width ) {
		width = screen.width - screen.width * 0.1;
	}
	if ( !height ) {
		height = screen.height - screen.height * 0.1;
	}
	if ( height < screen.height - 28 ) {
		top = Math.floor((screen.height - height)/2 - 14);
	}
	if ( width < screen.width - 10 ) {
		left = Math.floor((screen.width - width)/2);
	}
	width = Math.min(width, screen.width - 10);	
	height = Math.min(height, screen.height - 28);	
	window.open(url, '', 'menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height+',left='+left+',top='+top);
}
