/* Site search */
SiteSearch = function (divId) {
	this.div = $('#'+divId);
	this.input = this.div.find('input[type=text]');
	this.button = this.div.find('input[type=submit]');
	if (!this.input.length) return;
	this.defaultValue = this.input.attr('defaultValue');
	this.defaultWidth = this.input.width();
	var wrapper = this.div.parent();
	this.fullWidth = wrapper.innerWidth()
		- this.button.outerWidth()
		- parseInt(this.button.css('border-left-width'))
		- parseInt(this.button.css('border-right-width'))
		- parseInt(this.div.css('padding-left'))
		- parseInt(this.div.css('padding-right'))
		- parseInt(this.input.css('border-left-width'))
		- parseInt(this.input.css('border-right-width'))
		- parseInt(this.input.css('padding-left'))
		- parseInt(this.input.css('padding-right'))
		- parseInt(this.input.css('margin-left'))
		- parseInt(this.input.css('margin-right'));
	var siteSearch = this;
	this.input.focus(function() {
		if (siteSearch.input.val() == siteSearch.defaultValue) {
			siteSearch.input.attr('value', '');
		}
		if (!siteSearch.input.hasClass('search-enabled')) {
			siteSearch.input.addClass('search-enabled');
			if (!siteSearch.input.closest('div.main-search').hasClass('main-search-index')) {
				siteSearch.input.animate({width: siteSearch.fullWidth}, 'fast');
			}
		}
	}).blur(function() {
		if (siteSearch.input.val() == "" || siteSearch.input.val() == siteSearch.defaultValue) {
			siteSearch.input
				.removeClass('search-enabled')
				.attr('value', siteSearch.defaultValue);
			if (!siteSearch.input.closest('div.main-search').hasClass('main-search-index')) {
				siteSearch.input.animate({width: siteSearch.defaultWidth}, 'fast');
			}
		}
	});
	this.input.bind('focus blur keyup', function () {
		if (
			siteSearch.input.val() == ""
			|| siteSearch.input.val() == siteSearch.defaultValue) {
			siteSearch.button.attr('disabled', 'disabled');
		}
		else siteSearch.button.removeAttr('disabled');
	});
}

/* Suggest */
Suggest = function (inputId, url) {
	this.url = url;
	this.keys = {
		up: 38,
		down: 40,
		enter: 13,
		esc: 27
	};
	this.isOpen = false;
	this.isMouseOver = false;
	this.timeout = 300;
	this.timerId = 0;
	this.request = 0;
	this.input = $('#'+inputId);
	var suggest = this;
	this.div = $('<div>', {
		'class': 'suggest',
		mouseenter: function () {
			suggest.isMouseOver = true;
		},
		mouseleave: function () {
			suggest.isMouseOver = false;
		}
	}).insertAfter(this.input);
	this.input
		.keyup(function(e) { return suggest.processInput(e) })
		.keydown(function(e) { if (e.keyCode == suggest.keys.enter) return true; })
		.blur(function(e) { if (!suggest.isMouseOver) suggest.close(); })
		.attr('autocomplete', 'off')
		;
};
Suggest.prototype.open = function () {
	this.div.show();
	this.isOpen = true;
};
Suggest.prototype.close = function () {
	this.div.hide();
	this.isOpen = false;
	this.isMouseOver = false;
};
Suggest.prototype.query = function(text, callback) {
	if (this.timerId) {
		window.clearTimeout(this.timerId);
	}
	if (this.request) {
		this.request.abort();
		this.request = 0;
	}
	var suggest = this;
	this.timerId = window.setTimeout(function() {
		suggest.timerId = 0;
		suggest.request = $.post(suggest.url, {query: text}, callback, 'json');
	}, this.timeout);
};
Suggest.prototype.highlite = function(value, text) {
	if (!text) return '';
	var words = value.split(' ');
	words.sort(function ($one, $two) {
		return $two.length-$one.length;
	});
	return text.replace(new RegExp('('+words.join('|')+')', 'gi'), '<span class="hl">$1</span>');
};
Suggest.prototype.render = function(data, value) {
	if (data && data.length) {
		this.div.empty();
		this.div.css({
			top: this.input.position().top+this.input.outerHeight(),
			left: this.input.position().left
		});
		var div = this.div;
		var suggest = this;
		$(data).each(function () {
			if (this.type == 'caption') {
				var item = $('<div>', {
					'class': this.type
				}).append($('<strong>').html(this.name)).appendTo(div);
				return;
			}
			var item = $('<a>', {
				href: this.url,
				'class': this.type,
				mouseenter: function () {
					div.find('a.active').removeClass('active');
				}
			});
			if (this.img) $('<img>', {
				src: this.img
			}).appendTo(item);
			var inner = $('<span>').html(suggest.highlite(value, this.name));
			if (this.info) {
				inner.append($('<span>', { 'class': 'info' }).html(suggest.highlite(value, this.info)));
			}
			inner.appendTo(item);
			item.appendTo(div);
		});
		this.open();
	} else {
		this.close();
	}
};
Suggest.prototype.processInput = function(e) {
	if (this.isOpen && (e.keyCode == this.keys.down || e.keyCode == this.keys.up)) {
		var active = this.div.find('a.active');
		if (active.length) {
			active = e.keyCode == this.keys.down ? active.nextAll('a:first') : active.prevAll('a:first');
			if (active.length) {
				this.div.find('a.active').removeClass('active');
				active.addClass('active');
			}
		} else {
			var pos = e.keyCode == this.keys.down ? 'first' : 'last';
			this.div.find('a:'+pos).addClass('active');
		}
	} else if (this.isOpen && e.keyCode == this.keys.enter) {
		var active = this.div.find('a.active:first');
		if (active.length) {
			location = active.attr('href');
		} else {
			return true;
		}
	} else if (this.isOpen && e.keyCode == this.keys.esc) {
		this.close();
	} else {
		var suggest = this;
		var value = this.input.val();
		if (value.length > 0) {
			this.query(value, function (data) {
				suggest.render(data, value);
			});
		} else {
			this.close();
		}
	}
	return false;
};

/* Gallery filters menu */
var GalleryFilter = {
	currentMenuId: 0,
	div: null,
	slider: null,
	wrapper: null,

	fixWrapperHeight: function () {
		var wrapperPadding = parseFloat(this.wrapper.css('paddingBottom').replace(/auto/, 0));
		if (this.wrapper.innerHeight()-wrapperPadding < this.div.height()) {
			this.wrapper.css('height', this.div.height()+wrapperPadding);
		}
	},

	isNotInScreen: function(currentId) {
		var needFix = false;
		if (this.div.outerHeight() > $(window).height()) needFix = true;
		if (this.div.outerHeight() > this.wrapper.height()) needFix = true;
		var wrapperPadding = parseFloat(this.wrapper.css('paddingBottom').replace(/auto/, 0));
		if (currentId && this.wrapper.innerHeight()-wrapperPadding < this.div.offset().top+this.div.outerHeight()) {
			needFix = true;
		}
		return needFix;
	},

	fixMenu: function (currentId) {
		if (this.isNotInScreen(currentId)) {
			gal = this;
			$($.makeArray(this.div.find('ul:visible')).reverse()).each(function() {
				if (this.id == GalleryFilter.menu.attr('id')) return;
				if (this.id == currentId) return;
				if (this.id == GalleryFilter.currentMenuId) return;
				if (gal.isNotInScreen(currentId)) $(this).hide();
			});
		}
	},

	init: function(id, idMenu, idSlider, idWrapper, currentMenuId) {
		this.div = $('#'+id);
		this.slider = $('#'+idSlider);
		this.wrapper = $('#'+idWrapper);
		this.menu = $('#'+idMenu);
		this.currentMenuId = currentMenuId;
		var div = this.div;
		var wrapper = this.wrapper;
		var slider = this.slider;

		// filter menu
		this.menu.children('li').mouseover(function () {
			$(this).find('ul:hidden').slideDown(100, 'linear', function () {
				GalleryFilter.fixMenu(this.id);
			});
		});

		// fix height
		this.fixWrapperHeight();
		this.fixMenu(null);

		// browser does not support position:fixed
		if ($.browser.msie && $.browser.version.substr(0,1)=="6") {
			$(window).scroll(function () {
				var newTop = $(this).scrollTop()-slider.offset().top;
				if (newTop+div.outerHeight() <= wrapper.height()) {
					div.stop().animate({top: newTop > 0 ? newTop : 0}, 100, 'linear');
				}
			});
			return;
		}

		// follow the scroll
		var divTop = div.offset().top - parseFloat(div.css('marginTop').replace(/auto/, 0));
		$(window).bind("scroll", function (event) {
			if ($(this).scrollTop() >= divTop) {
				if (!div.hasClass('fixed')) {
					div.css({left: slider.offset().left, top: 0}).addClass('fixed');
				}
				var divBottom = div.offset().top+div.height();
				var wrapperBottom = GalleryFilter.wrapper.offset().top+GalleryFilter.wrapper.height();
				if (divBottom >= wrapperBottom) {
					var newTop = GalleryFilter.wrapper.innerHeight()-div.outerHeight();
					div.css({
						left: 0,
						top: newTop
					}).removeClass('fixed');
				}
			} else {
				div.css({left: 0, top: 0}).removeClass('fixed');
			}
		}).bind('resize', function () {
			$(this).trigger('scroll');
			if (div.hasClass('fixed')) {
				div.css({left: slider.offset().left, top: 0});
			} else {
				div.css({left: 0, top: 0});
			}
			GalleryFilter.fixMenu();
		});

		if ($.browser.mozilla) {
			$(window).trigger('resize');
		}
	}
}

/* Free home estimate form */
var EstimateForm = {

	init: function() {
		// Init submit.
		var submit = $("#sendFormLink");
		if (submit.length) {
			submit.click(function() {
				this.onclick = 'return false';
				return EstimateForm.disableSubmitButton(this);
			});
		}

		// Init stone name field.
		var field = $("#stoneNameField.with-placeholder");
		if (field.length) {
			field.click(function() {
				if ($(this).attr('value') == $(this).attr('defaultValue')) {
					$(this).attr('value', '');
					$(this).removeClass('with-placeholder');
				}
			}).blur(function() {
				if ($(this).attr('value') == '') {
					$(this).attr('value', $(this).attr('defaultValue'));
					$(this).addClass('with-placeholder');
				}
			});
		}

		// Init edges images.
		$('.edges input').change(function () {
			$('.edge').removeClass('active');
			$(this).closest('.edge').addClass('active');
		});
	},

	disableSubmitButton: function(e) {
		document.send_request.submit();
		return false;
	}

};

var Cookie = {
	set: function (name, value, expires, path, domain, secure) {
		document.cookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
	},

	get: function (name) {
		var cookie = " " + document.cookie;
		var search = " " + name + "=";
		var setStr = null;
		var offset = 0;
		var end = 0;
		if (cookie.length > 0) {
			offset = cookie.indexOf(search);
			if (offset != -1) {
				offset += search.length;
				end = cookie.indexOf(";", offset)
				if (end == -1) {
					end = cookie.length;
				}
				setStr = cookie.substring(offset, end);
			}
		}
		return(setStr);
	}
}

var StoneView = {
	cookieName: 'stone-current',

	imgHolder: null,
	imgSwitcher: null,
	wrapper: null,

	currentId: '',
	ids: new Array(),

	change: function (currentId) {
		if ($.inArray(currentId, this.ids) == -1) {
			this.currentId = currentId = this.ids[0];
		} else {
			this.currentId = currentId;
			this.saveToCookie();
		}

		this.imgSwitcher.find('li').removeClass('active');
		$('#'+currentId).addClass('active');
		var current = $("#"+currentId+'-img');
		var img = current.find('img');
		this.wrapper.css('width', img.attr('width')+'px');
		this.imgHolder.find('li').removeClass('active');
		current.addClass('active');
	},

	next: function () {
		var pos = $.inArray(this.currentId, this.ids);
		this.change(this.ids.length >= pos+1 ? this.ids[pos+1] : this.ids[0]);
	},

	prev: function () {
		var pos = $.inArray(this.currentId, this.ids);
		this.change(pos-1 >= 0 ? this.ids[pos-1] : this.ids[this.ids.length-1]);
	},

	nextStone: function () {
		var link = $('#stone-next');
		if (link.length) {
			window.location = link.attr('href');
		}
	},

	prevStone: function () {
		var link = $('#stone-prev');
		if (link.length) {
			window.location = link.attr('href');
		}
	},

	saveToCookie: function () {
		Cookie.set(this.cookieName, this.currentId);
	},

	restoreFromCookie: function () {
		var restored = Cookie.get(this.cookieName);
		if (restored) {
			this.change(restored);
			return true;
		} else {
			return false;
		}
	},

	init: function () {
		this.imgHolder = $("#stone-img");
		this.imgSwitcher = $("#stone-img-switcher");
		this.wrapper = $("#stone-img-wrapper");
		var view = this;

		var items = this.imgSwitcher.find('li');
		items.each(function () {
			view.ids.push(this.id);
		});

		items.click(function () {
			view.change(this.id);
		});
		this.imgHolder.click(function () {
			view.next();
		});

		$(document).keydown(function(e) {
			if (e.keyCode == 39) { // Right
				e.ctrlKey
					? view.nextStone()
					: view.next();
			} else if (e.keyCode == 37) { // Left
				e.ctrlKey
					? view.prevStone()
					: view.prev();
			}
		});

		if (!this.restoreFromCookie()) {
			this.change(view.ids[0]);
		}
	}
};

var ProductView = {
	imgHolder: null,
	imgSwitcher: null,

	currentId: '',
	ids: new Array(),

	change: function (currentId) {
		if (!this.ids.length) {
			return;
		}
		if ($.inArray(currentId, this.ids) == -1) {
			currentId = this.ids[0];
		}
		this.currentId = currentId;
		this.imgSwitcher.find('li').removeClass('active');
		$('#'+currentId).addClass('active');
		this.imgHolder.find('li').removeClass('active');
		$("#"+currentId+'-img').addClass('active');
	},

	next: function () {
		var pos = $.inArray(this.currentId, this.ids);
		this.change(this.ids.length >= pos+1 ? this.ids[pos+1] : this.ids[0]);
	},

	prev: function () {
		var pos = $.inArray(this.currentId, this.ids);
		this.change(pos-1 >= 0 ? this.ids[pos-1] : this.ids[this.ids.length-1]);
	},

	nextProduct: function () {
		var link = $('#product-next');
		if (link.length) {
			window.location = link.attr('href');
		}
	},

	prevProduct: function () {
		var link = $('#product-prev');
		if (link.length) {
			window.location = link.attr('href');
		}
	},

	init: function () {
		this.imgHolder = $("#product-img");
		this.imgSwitcher = $("#product-img-switcher");
		var view = this;

		var items = this.imgSwitcher.find('li');
		items.each(function () {
			view.ids.push(this.id);
		});
		items.click(function () {
			view.change(this.id);
		});

		this.imgHolder.click(function () {
			view.next();
		});

		$(document).keydown(function(e) {
			if (e.keyCode == 39) { // Right
				e.ctrlKey
					? view.nextProduct()
					: view.next();
			} else if (e.keyCode == 37) { // Left
				e.ctrlKey
					? view.prevProduct()
					: view.prev();
			}
		});
		if (items.length) {
			this.change(view.ids[0]);
		}
	}
};

// Change captcha link
function changeCaptcha(captchaId) {
	var image = document.getElementById("captchaImage_"+captchaId);
	image.src = '/captcha-new/'+captchaId+'?p='+Math.floor(Math.random() * 1000000);
}

// 404 page "Go back"
function init404Page() {
	if (history.length < 2) {
		var span = document.getElementById('backLink');
		if (span) span.style.display = 'none';
	}
}
