Query.init();

function scrollToElement(element) {
	var top = jQuery(element).offset().top;

	if (typeof(arguments[1]) === 'number') {
		top = top + arguments[1];
	}

	if (jQuery.browser.msie) jQuery(document.documentElement).animate({scrollTop: top}, 200);
	else if (jQuery.browser.mozilla || jQuery.browser.opera) jQuery("html").animate({scrollTop: top}, 200);
	else jQuery(document.body).animate({scrollTop: top}, 200);
}

var LazyJSLoad = function () {
	var head = document.getElementsByTagName('head')[0];

	function load(url) {
		var script   = document.createElement('script'),
			callback = arguments[1] || false;

		script.charset = 'utf8';
		script.src = url;

		if (callback) {
			var scope = arguments[2] || window,
				args  = arguments[3] || [];

			script.onreadystatechange = function () {
				if (script.readyState == 'loaded' || script.readyState == 'complete') {
					callback.apply(scope, args.constructor === Array ? args : [args]);
				}
			};

			script.onload = function () {
				callback.apply(scope, args.constructor === Array ? args : [args]);
			};
		}

		head.appendChild(script);
	}

	return {
		load: function () {
			load.apply(null, arguments);
		},
		onready: function () {
			var args = arguments;

			jQuery(document).ready(function () {
				load.apply(null, args);
			});
		}
	};
}();

jQuery.extend(jQuery.easing, {
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t /= d) < (1 / 2.75)) {
			return c * (7.5625 * t * t) + b;
		} else if (t < (2 / 2.75)) {
			return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
		} else if (t < (2.5 / 2.75)) {
			return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
		} else {
			return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
		}
	}
});

function show_all_left_menu(x) {
	var obj = $('#id_left_menu');
	var switcher_left_menu = $(x).find('a');
	if (obj.hasClass('opened_menu')) {
		obj.animate({height: "40px"}).removeClass('opened_menu');
		switcher_left_menu.removeClass('i_arrow_up').addClass('i_arrow_down').attr('stick', 'Еще');
		$.cookie("left_menu_status", 'close', {
			path: "/",
			domain: "." + serverName
		});
	} else {
		obj.animate({height: "85px"}).addClass('opened_menu');
		switcher_left_menu.removeClass('i_arrow_down').addClass('i_arrow_up').attr('stick', 'Свернуть');
		$.cookie("left_menu_status", 'open', {
			path: "/",
			domain: "." + serverName
		});
	}
}

function resetForm(a, b) {
	if (!b) {
		b = 'input,select,textarea'
	}
	$(document.forms[a]).find(b).val('')
}

function submitForm(a) {
	$(document.forms[a]).submit()
}

function nl2br(str) {
	return (str + '').replace(/([^>]?)\n/g, '$1<br />\n')
}


(function($) {
	var popupsArray = new Array();
	var popupTemplate = '<div class="hide" style="position:relative"><table class="auto popup"><tr><td class="tl">&nbsp;</td><td class="t">&nbsp;</td><td class="tr">&nbsp;</td></tr><tr><td class="l">&nbsp;</td><td class="content"><div class="content"></div></td><td class="r">&nbsp;</td></tr><tr><td class="bl"><img src="/i/small/0.gif" width="13" heigth="13"/></td><td class="b">&nbsp;</td><td class="br"><img src="/i/small/0.gif" width="13" heigth="13"/></td></tr></table><i class="close_i imgs i_x_grey" style="position: absolute; right: 10px; top: 12px; z-index: 26000;"><i/></i></div>';
	var buttonWrapper = '<div class="popup_wrapper"></div>';
	var duration = 100;
	var margin = -18;
	var selfWindow = $(window);

	/**
	 * @param text
	 * @param auto_close
	 * @param force_open
	 * @param root_element
	 */
	$.fn.ShowAlert = function(text, auto_close, force_open, root_element) {
		this.each(function() {
			var self = $(this);

			if (force_open === true || ! self.data('alert')) {
				window.setTimeout(function () {
					self.data('alert', ShowAlert(self, text, root_element));

					if (auto_close) {
						self.HideAlert(2000);
					}
				}, 100);
			}
		});

		return $(this);
	};

	function removeAlert(el) {
		$(el.data('alert')).remove();
		el.data('alert', null);
	}

	$.fn.HideAlert = function(delay) {
		this.each(function() {
			var self = $(this);

			if (self.data('alert')) {
				if (delay) {
					window.setTimeout(function() {
						removeAlert(self);
					}, delay);
				}
				else {
					removeAlert(self);
				}
			}
		});

		return $(this);
	}

})(jQuery);

/**
 * Отобразить сообщение об ошибке
 * @param el целевой элемент
 * @param text текст
 * @return HTMLDivElement
 */
function ShowAlert(el, text) {
	var element = $(el);
	var element_offset = element.offset();
	var root_element = arguments[2] || null;

	if (root_element) {
		var root_element_offset = root_element.offset();

		element_offset = {
			top: element_offset.top - root_element_offset.top,
			left: element_offset.left - root_element_offset.left
		};
	}

	var alert_text = text || 'undefined';
	var alert_block = $('<div class="info_stick"></div>').text(alert_text).css({
		top: element_offset.top - 23,
		left: element_offset.left + 10
	});

	switch (element[0].tagName.toLowerCase()) {
		case 'textarea':
		case 'input':
			var input_event_key_down = function() {
				alert_block.remove();
				$(this).unbind('keyup', input_event_key_down);
				$(this).unbind('change', input_event_change);
			};

			var input_event_change = function() {
				alert_block.remove();
				$(this).unbind('keyup', input_event_key_down);
				$(this).unbind('change', input_event_change);
			};

			element.bind('keyup', input_event_key_down);
			element.bind('change', input_event_change);
			break;
		case 'select':
		case 'checkbox':
			var event_change = function() {
				alert_block.remove();
				$(this).unbind('change', event_change);
			};

			element.bind('change', event_change);
			break;
		default:
			var event_click = function() {
				alert_block.remove();
				$(this).unbind('click', event_click);
			};

			element.bind('click', event_click);
			break;
	}

	$(root_element || document.body).append(alert_block);

	return alert_block.get(0);
}

function spawnChat(userId) {
	userId = parseInt(userId);

	if (!userId) {
		return;
	}

	var popupWin = window.open(siteRoot + "/messages/chat/" + userId, "chat" + userId, "status=0,toolbar=0,location=0,menubar=0,directories=0,scrollbars=0,resizable=0,location,width=530,height=590,fullscreen=0");

	if (popupWin) {
		popupWin.focus();
	}
}

function rateItem(_rate, _itemId, serviceName, _parentId, fields, url, callback) {
	var rate = parseInt(_rate),
			itemId = parseInt(_itemId),
			parentId = parseInt(_parentId);

	Query.add(siteRoot + '/vote/vote/', {
		rate: rate,
		itemId: itemId,
		parentId: parentId,
		serviceName: serviceName
	}, function (response) {
		if (response == 'ok') {
			if (fields == 'reload') {
				if (url) window.location.href = (url.indexOf('http://') == -1 ? siteRoot : '') + url;
				else window.location.reload();
				return;
			}

			$(fields).each(function () {
				var current_value = parseInt($(this).text());
				var new_value = current_value + rate;
				$(this).text(new_value);
			});

			if (typeof callback == 'function') {
				callback();
			}
		}
	});
}

function addToNotepad(element, id, author, type) {
	element = $(element);

	Query.add(siteRoot + '/favorites/ajax/add/', {id: id, author: author, type: type}, function (data) {
		if (data == 'ok' && element.length) {
			element.unbind('click').click(function() {
				removeFromNotepad(element, id, author, type);
			});
			element.find('span').text('Удалить из закладок');
		}
	});
}

function removeFromNotepad(element, id, author, type) {
	element = $(element);

	Query.add(siteRoot + '/favorites/ajax/remove/', {id: id, author: author, type: type}, function (data) {
		if (data == 'ok' && element.length) {
			element.unbind('click').click(function() {
				addToNotepad(element, id, author, type);
			});
			element.find('span').text('В закладки');
		}
	});
}

function aut_popup(text) {
	if (text) $('#aut_popup_text').html(text);

	show_popup('autorization_popup');

	return false;
}

function resize_popup() {
	var a = $('#popup_window div.content');

	$('#popup_window').find('.popup-tc, .popup-bc').css({'width':'auto'});
	$('#popup_window').removeClass('hide');

	var width_obj = Math.round(a.get(0).offsetWidth);
	var height_obj = Math.round(a.get(0).offsetHeight);

	$('#popup_window').find('.popup-tc, .popup-bc').css({'width':width_obj + 'px'});
	$('#popup_window').css({
		'marginTop': -height_obj / 2 + 'px',
		'marginLeft': -width_obj / 2 + 'px'
	});
}

function show_popup(z) {
	close_popup(false);

	var popup = $('#popup_window');

	if (! popup.data('expose')) {
		popup.expose({color: '#fff', zIndex: 100001, loadSpeed: 0, closeSpeed: 0, onBeforeClose: function () {close_popup(false);}});
	}

	popup.data('expose').load();
	popup.data('element', z);
	popup.find('div.content').append($('#' + z).children());

	resize_popup();
}

function close_popup() {
	if (arguments[0] !== false && $('#popup_window').data('expose')) {
		$('#popup_window').data('expose').close();
	}

	var popup = $('#popup_window');

	popup.addClass('hide');

	var content = popup.find('div.content');
	var el = $('#' + popup.data('element'));

	if (el.length) {
		el.append(content.children());
	}

	popup.data('element', null);
	content.html('');
}

function send_user_message_about_error() {
	var error_email = $('#error_user_message_name').val();
	var error_message = $('#error_user_message').val();
	if (error_email.length != 0 && error_message.length != 0) {
		Query.init();
		Query.add(siteRoot + '/feedback/ajax/?action=send', { 'email' : error_email, 'text' : error_message }, function(data) {
			if (data == 'OK') {
				show_popup('user_answer_about_error_ok');
			}
		});
	}
}

function quickForm(url, key, value) {
	var form = document.createElement('form');

	form.action = (url || window.location.href);
	form.method = 'post';

	for (var i = 1; i < arguments.length; i = i + 2) {
		var input = document.createElement('input');

		input.type  = 'hidden';
		input.name  = arguments[i];
		input.value = arguments[i + 1];

		form.appendChild(input);
	}

	document.body.appendChild(form);

	form.submit();
}

function Paginator(link, dom_element) {
	$(dom_element).load(link, function() {
		var offset = $(dom_element).offset();

		window.scrollTo(offset.left, offset.top - 50);
	});
}

/**
 * @param container - string or object
 * @param button_left - string or object
 * @param button_right - string or object
 * @param speed - integer
 * @param total_pages - integer
 * @param images_qty - integer
 * @param item_width - integer
 * @param url - string
 * @param load_img - string
 * @param ajax_params - object
 */
var jQueryAjaxScroller = {
	__construct: function(container, button_left, button_right, speed, total_pages, images_gty, item_width, url, load_img, ajax_params) {
		// init all params
		this.container = (typeof container == 'string') ? $(container) : container;
		this.button_left = (typeof button_left == 'string') ? $(button_left) : button_left;
		this.button_right = (typeof button_right == 'string') ? $(button_right) : button_right;
		this.speed = parseInt(speed);
		this.total_pages = parseInt(total_pages);
		this.width = parseInt(images_gty) * parseInt(item_width);
		this.url = url;
		this.load_img = load_img;

		// init ajax_params and set default values
		this.ajax_params = ajax_params;
		this.ajax_params.page = this.ajax_params.page || 1;

		// init some start parameters
		this.init();
	},

	init: function() {
		// save link to Object
		var self = this;

		// set first element as current at start
		this.current = $(this.container.children()[0]);
		this.current.addClass('currentElement');

		if (this.ajax_params.page == 1) { // if page == 1, hide left arrow
			this.button_left.css('visibility', 'hidden');
		}

		if (this.ajax_params.page == this.total_pages) { // if page == total, hide right arrow
			this.button_right.css('visibility', 'hidden');
		}

		// set left button listener
		this.button_left.click(function() {
			if (self.current.prev().length == 0) { // if there is no previous item
				// show "loading" image & reduce page per one
				self.container.css('background', 'url(\'' + self.load_img + '\') center no-repeat');
				self.ajax_params.page--;

				Query.add(self.url, self.ajax_params, function(result) { // init AJAX query
					// on ready, remove "loading" image, insert response & animate movement
					self.container.css('background', 'none');
					self.container.prepend(result);
					self.moveLeft(true);
				});
			} else { // if previous item already loaded
				// reduce page per one & animate movement
				self.ajax_params.page--;
				self.moveLeft();
			}
		});

		// set right button listener
		this.button_right.click(function() {
			if (self.current.next().length == 0) { // if there is no next item
				// show "loading" image & increace page per one
				self.container.css('background', 'url(\'' + self.load_img + '\') center no-repeat');
				self.ajax_params.page++;

				Query.add(self.url, self.ajax_params, function(result) { // init AJAX query
					// on ready, remove "loading" image, insert response & animate movement
					self.container.css('background', 'none');
					self.container.append(result);
					self.moveRight();
				});
			} else { // if next item already loaded
				// increace page per one & animate movement
				self.ajax_params.page++;
				self.moveRight();
			}
		});
	},

	moveLeft: function(isAjax) {
		if (this.ajax_params.page > 0) { // if there is other pages
			// set current on previous item
			this.current.removeClass('currentElement');
			this.current = this.current.prev();
			this.current.addClass('currentElement');
			// set width of current
			this.current.css('width', this.width + 'px');

			if (isAjax) { // if function called from AJAX query
				// hide item for further animation
				this.current.css('marginLeft', '-' + this.width + 'px');
			}

			if (this.ajax_params.page == 1) { // if this is first page
				// hide left button
				this.button_left.css('visibility', 'hidden');
			}

			// always show right button
			this.button_right.css('visibility', 'visible');

			// animate first scroller element, to shift other items
			$(this.container.children()[0]).animate({'marginLeft': '+=' + this.width}, this.speed);
		} else { // if there is no other pages
			// hide left button
			this.button_left.css('visibility', 'hidden');
		}
	},

	moveRight: function() {
		if (this.ajax_params.page <= this.total_pages) { // if there is other pages
			// set current on next item
			this.current.removeClass('currentElement');
			this.current = this.current.next();
			this.current.addClass('currentElement');
			// set width of current
			this.current.css('width', this.width + 'px');

			if (this.ajax_params.page == this.total_pages) { // if this is last page
				// hide right button
				this.button_right.css('visibility', 'hidden');
			}

			// always show left button
			this.button_left.css('visibility', 'visible');

			// animate first scroller element, to shift other items
			$(this.container.children()[0]).animate({'marginLeft': '-=' + this.width}, this.speed);
		} else { // if there is no other pages
			// hide left button
			this.button_right.css('visibility', 'hidden');
		}
	}
};

function close_current_infoblock(date_block) {
	$.cookie("close_current_infoblock", date_block, {
		path: "/",
		domain: ".{/literal}{$serverName}{literal}"
	});
	$('#closeQuestionsAboutSetHomePage').remove();
	$('#informer_top').animate({height:"0px"});
}

function activeSmallTabFunc() {
	var tab = jQuery(this);
	tab.parent().find('.tab_on').removeClass('tab_on').addClass('tab_off');
	if (!tab.hasClass('tshirt') && !tab.hasClass('tshirt_select')) {
		tab.removeClass('tab_off').addClass('tab_on');
	}
}


function insertSmile(smile_source) {
	if (current_wisywig_area && current_wisywig_area.length) {
		current_wisywig_area.htmlarea("smiley_insert", smile_source);
	}
}
function insertImageWisywig(urls) {
	if (current_wisywig_area && current_wisywig_area.length) {
		current_wisywig_area.htmlarea("insertImages", urls);
	}
}

function setUserbarPosition() {
	jQuery('#top_user_menu').each(function () {
		var top_user_menu = jQuery(this);
		var top_user_menu_absolute = false;
		var top_user_menu_scroll_height = 225;
		var d = jQuery.browser.msie ? window : document;

		jQuery(d).scroll(function(event) {
			var current_scroll_top = $(this).scrollTop();

			if (current_scroll_top > top_user_menu_scroll_height && !top_user_menu_absolute ) {
				top_user_menu_absolute = true;
				top_user_menu.css('top', top_user_menu_scroll_height).css('position','absolute');
			} else if (current_scroll_top < top_user_menu_scroll_height && top_user_menu_absolute ) {
				top_user_menu_absolute = false;
				top_user_menu.css('top', 0).css('position','fixed');
			}
		});

		if (currentUserId) { //если юзер залогинен, для него выполням код
			var top_user_buttons = top_user_menu.find('div.top_user_buttons');

			top_user_buttons.find('span.switcher_services i').mousedown(function(event) {
				event.preventDefault();

				if (jQuery(this).hasClass('i_arrow_down')) {
					jQuery(this).removeClass('i_arrow_down').addClass('i_arrow_up');
					top_user_buttons.addClass('top_user_buttons_bg');
				}
				else {
					jQuery(this).removeClass('i_arrow_up').addClass('i_arrow_down');
					top_user_buttons.removeClass('top_user_buttons_bg');
				}

			});
		}

		jQuery(d).scroll();
	});
}

//TOP MENU CODE
jQuery(document).ready(function() {
	jQuery('div.autoriz_user_area', '#top_user_menu').each(function () {
		var autorization_area = jQuery(this);

		jQuery('#enter_top_button').click(function() {
			autorization_area.addClass('enter_open');

			$('#login_input').focus();

			function bodyClick(event) {
				if (! autorization_area.find(event.target).size() && event.target != autorization_area[0]) {
					autorization_area.removeClass('enter_open');
					jQuery(document.body).unbind('click', bodyClick);

					$('#password_restore_cancel').click();
				}
			}

			jQuery(document.body).bind('click', bodyClick);
		});

		jQuery(document.body).scroll(function (event) {
			console.debug(event);
		});
	});

	jQuery('div.main_search_inp', '#top_user_menu').each(function () {
		var top_main_seach_block = jQuery(this);
		var menu_type_open = false;

		top_main_seach_block.find('td.where_search_select, td.where_search_select_end').mousedown(menu_seach_type_toggle);
		top_main_seach_block.find('#menu_list a').click(function(event) {
			top_main_seach_block.find('span.current_search_type').html(jQuery(this).html());

			jQuery('a', '#menu_list').removeClass('this_type_selected');
			jQuery('#area-current-input').val(jQuery(this).attr('area'));
			jQuery(this).addClass('this_type_selected');
			menu_seach_type_toggle(event);
		});

		function menu_seach_type_toggle(event) {
			event.preventDefault();

			if (! menu_type_open) {
				top_main_seach_block.find('#menu_list').animate({'height':111},200);
				top_main_seach_block.find('td.where_search_select_end i').removeClass('i_arrow_down').addClass('i_arrow_up');
				menu_type_open = true;
			}
			else {
				top_main_seach_block.find('#menu_list').animate({'height':0},200);
				top_main_seach_block.find('td.where_search_select_end i').removeClass('i_arrow_up').addClass('i_arrow_down');
				menu_type_open = false;
			}
		}
	});

	jQuery('div.tabbed-container').each(function () {
		var cont = jQuery(this);
		var tabs = cont.children('table').find('td:even');
		var contents = cont.children('div').children().children().children('div.tabs-content');

		tabs.each(function (index) {
			jQuery(this).mousedown(function (event) {
				event.preventDefault();

				tabs.removeClass('active');
				tabs.addClass('unactive');

				tabs.eq(index).addClass('active').removeClass('unactive');

				contents.removeClass('active');
				contents.eq(index).addClass('active');
			});
		});
	});
});

(function ($) {
	var isSupported = document.createElement('input').placeholder === 'string';

	$.fn.placeholder = function () {
		this.each(function () {
			if (isSupported) return;

			var input = $(this), empty = false;

			input.parents('form:first').submit(function () {
				if (empty) input.val('');
			});

			input.blur(function () {
				if (empty = ($.trim(input.val()).length === 0)) {
					input.val(input.attr('placeholder'));
					input.css('color', '#A9A9A9');
				}
			});

			input.focus(function () {
				if (empty) {
					input.val('');
					input.css('color', '');
				}
			});

			input.blur();
		});

		return this;
	};
})(jQuery);
