/* INTERNAL SCRIPT */

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

function warn(v)    {
	console.log(v);
}

function doHighlight( bodyText, searchTerm, highlightStartTag, highlightEndTag )    {
	// the highlightStartTag and highlightEndTag parameters are optional
	if ((!highlightStartTag) || (!highlightEndTag)) {
		highlightStartTag = '<span style="color:blue; background-color:yellow;">';
		highlightEndTag = '</span>';
	}
  
	// find all occurences of the search term in the given text, and add some "highlight" tags to them (we're not using a
	// regular expression search, because we want to filter out matches that occur within HTML tags and script blocks, so
	// we have to do a little extra validation)
	var newText = "",
		i = -1,
		lcSearchTerm = searchTerm.toLowerCase(),
		lcBodyText = bodyText.toLowerCase();

	while (bodyText.length > 0) {
		i = lcBodyText.indexOf(lcSearchTerm, i+1);
		if (i< 0) {
			newText += bodyText;
			bodyText = '';
		} else {
			// skip anything inside an HTML tag
			if (bodyText.lastIndexOf('>', i) >= bodyText.lastIndexOf('<', i)) {
				// skip anything inside a <script> block
				if (lcBodyText.lastIndexOf('/script>', i) >= lcBodyText.lastIndexOf('<script', i)) {
					newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
					bodyText = bodyText.substr(i + searchTerm.length);
					lcBodyText = bodyText.toLowerCase();
					i = -1;
				}
			}
		}
	}
	return newText;
}

(function ($) {
	$.fn.submitForm = function (cmd, options) {
		var settings = {
			cmd: cmd || 'save'
		};
		$.extend(settings, options || {});
		if ($(this).validateForm(settings)) {
			$(this).append('<input type="hidden" name="cmd" value="' + settings.cmd + '" />');
			$(this).submit();
		} else {
			return false;
		}
	};
	$.fn.validateForm = function (options) {
		var settings = {
			container: '.errors',
			render: true
		};
		$.extend(settings, options || {});
		var form = $(this);
		if (typeof settings.target != undefined) {
			form.attr('target', settings.target);
		} else {
			form.attr('target', '');
		}
		form.find("input:enabled, select:enabled, textarea:enabled").each(function () {
			if ($(this).hasClass("required") || $(this).hasClass("validate")) {
				var name = $(this).attr("name");
				var name = name.replace(/[\]\[]/gi, "");
				$("#" + name + "_required").hide();
				$("#" + name + "_validate").hide();
				$("#" + name + "_strlen").hide();
				if (settings.container) {
					$(settings.container).hide();
				}
				$(this).removeClass('err');
			}
		})
		var success = true;
		form.find("input:enabled, select:enabled, textarea:enabled").each(function () {
			if ($(this).hasClass("required") || $(this).hasClass("validate") || $(this).hasClass("strlen")) {
				var value = $(this).val();
				var required = false;
				var validate = false;
				var strlen = false;
				if ((!value || value == 0 || value == 'other') && $(this).hasClass("required")) {
					required = true;
				}
				if ($(this).hasClass("email") && value) {
					var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
					if (!pattern.test(value)) {
						validate = true;
					}
				}
				if ($(this).hasClass("number") && value) {
					var pattern = /^([0-9.-])+/;
					if (!pattern.test(value)) {
						validate = true;
					}
				}
				if ($(this).hasClass("password") && value) {
					var repass = $("#re" + $(this).attr("name")).val();
					if (repass != value) {
						validate = true;
					}
				}
				if ($(this).hasClass("time") && value) {
					var pattern = /^[0-2]?[0-9]\:[0-5][0-9]$/;
					if (!pattern.test(value)) {
						validate = true;
					}
				}
				if ($(this).hasClass("phone") && value) {
					var pattern = /^(0?\([\d]+\))?\s*[\d\-\s]+$/;
					if (!pattern.test(value)) {
						validate = true;
					}
				}
				if ($(this).hasClass("strlen") && value) {
					if (value.length < $(this).attr("minlength") || value.length > $(this).attr("maxlength")) {
						strlen = true;
					}
				}
				if (required) {
					var name = $(this).attr("name");
					var name = name.replace(/[\]\[]/gi, "");
					if (settings.render) {
						$("#" + name + "_required").css({
							display: 'block',
							width: $(this).attr('clientWidth') + 'px'
						});
					} else {
						$("#" + name + "_required").css({
							display: 'block'
						});
					}
					$(this).addClass('err');
					if (success) {
						$(this).focus();
					}
					$(this).css({
						'background-color': '#FAE0DB',
						'border': '1px solid #EDAB9E'
					});
					if (settings.container) {
						$(settings.container).show();
					}
					success = false;
				}
				if (validate) {
					var name = $(this).attr("name");
					var name = name.replace(/[\]\[]/gi, "");
					if (settings.render) {
						$("#" + name + "_validate").css({
							display: 'block',
							width: $(this).attr('clientWidth') + 'px'
						});
					} else {
						$("#" + name + "_validate").css({
							display: 'block'
						});
					}
					$(this).addClass('err');
					if (success) {
						$(this).focus();
					}
					$(this).css({
						'background-color': '#FAE0DB',
						'border': '1px solid #EDAB9E'
					});
					if (settings.container) {
						$(settings.container).show();
					}
					success = false;
				}
				if (strlen) {
					var name = $(this).attr("name");
					var name = name.replace(/[\]\[]/gi, "");
					if (settings.render) {
						$("#" + name + "_strlen").css({
							display: 'block',
							width: $(this).attr('clientWidth') + 'px'
						});
					} else {
						$("#" + name + "_strlen").css({
							display: 'block'
						});
					}
					$(this).addClass('err');
					if (success) {
						$(this).focus();
					}
					$(this).css({
						'background-color': '#FAE0DB',
						'border': '1px solid #EDAB9E'
					});
					if (settings.container) {
						$(settings.container).show();
					}
					success = false;
				}
			}
		})
		return success;
	}
})(jQuery);

var core = {
	checkAll: function (name, flag) {
		$("input[name='" + name + "'][type='checkbox']").attr('checked', flag);
	},
	redirect: function (href, options) {
		var o = options;
		if (o && (typeof o.name == 'string')) {
			var expires, value = '';
			if (o.value) {
				value = o.value;
			}
			if (typeof o.days == 'number') {
				var date = new Date();
				date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * o.days));
				expires = "; expires=" + date.toUTCString();
			}
			document.cookie = o.name + '=' + value + expires + '; path=/';
		}
		if (!href || (typeof href == 'undefined')) {
			href = document.location.pathname;
		}
		document.location.href = href;
	},
	center: function (el, position) {
		if (position == undefined || position == 'absolute') {
			var y = $(window).attr('scrollY') || 0;
		} else {
			var y = 0;
		}
		el.css("position", position || "absolute");
		el.css("left", ($(window).width() - el.width()) / 2 + "px");
		el.css("top", ($(window).height() - el.height()) / 2 + y + "px");
	},
	formPost: function (form, opt) {
		var $form = $(form);
		opt = $.extend({
			action: $form.attr('action') || document.location.href,
			isRedirect: false,
			href: document.location.href
		}, opt);
		$.post(opt.action, $form.serialize(), function(data) {
			if (!data.success) {
				if (data.errors) {
					for (var type in data.errors) {
						$.each(data.errors[type], function (name, error) {
							console.log('#' + name + '_' + type);
							$('#' + name + '_' + type).show();
						})
					}
				}
				if (opt.callbackError) {
					opt.callbackError(data);
				}
				return false;
			}
			if (opt.callback) {
				opt.callback(data);
			}
			if (opt.isRedirect) {
				core.redirect(opt.href);
			}
		}, 'json');
	},
	blocked: function (settings) {
		try {
			settings = $.extend({
				focus: window
			}, settings);
			var id = document.getElementById('maskoverlay');
			if (id) {
				return;
			}
			var left = '0px',
				top = '0px',
				height = '100%',
				width = '100%';
			if (typeof settings.el != 'undefined') {
				settings = $.extend(settings, {
					el: (typeof settings.el == 'string' ? $('#' + settings.el) : settings.el)
				});
				height = $(settings.el).height() + 'px';
				width = $(settings.el).width() + 'px';
				var offset = $(settings.el).offset();
				left = offset.left - $(window).scrollLeft() + 'px';
				top = offset.top - $(window).scrollTop() + 'px';
			}
			$('body').append('<div id="maskimg" style="display:none; width: 202px; height: 20px; background-color:transparent; border:0px solid black; display:none; font-style:normal; padding:0px; margin:0px; z-index:1002;"><img alt="Идет загрузка данных" src="/img/loading-horizont.gif" /></div>');
			this._center({
				el: $('#maskimg'),
				focus: settings.focus
			}).show();
		} catch (e) {}
		return this;
	},
	dark: function (settings) {
		try {
			settings = $.extend({
				focus: window
			}, settings);
			var id = document.getElementById('maskoverlay');
			if (id) {
				return;
			}
			var left = '0px',
				top = '0px',
				height = '100%',
				width = '100%';
			if (typeof settings.el != 'undefined') {
				settings = $.extend(settings, {
					el: (typeof settings.el == 'string' ? $('#' + settings.el) : settings.el)
				});
				height = $(settings.el).height() + 'px';
				width = $(settings.el).width() + 'px';
				var offset = $(settings.el).offset();
				left = offset.left - $(window).scrollLeft() + 'px';
				top = offset.top - $(window).scrollTop() + 'px';
			}
			$('body').append('<div id="maskoverlay" style="display:none; height:' + height + '; width:' + width + '; left:' + left + '; top:' + top + '; background-color:#111111; position:fixed; z-index:1001;"></div>').append('<div id="maskimg" style="display:none; width: 202px; height: 20px; background-color:transparent; border:0px solid black; display:none; font-style:normal; padding:0px; margin:0px; z-index:1002;"><img alt="Идет загрузка данных" src="/res/img/loader.gif"></div>');
			$('#maskoverlay').css({
				opacity: 0.0
			}).show().fadeTo('medium', 0.7);
			this._center({
				el: $('#maskimg'),
				focus: settings.focus
			}).show();
		} catch (e) {}
		return this;
	},
	unblocked: function () {
		$('#maskoverlay,#maskimg').remove();
		return this;
	},
	_center: function (settings) {
		settings = $.extend({
			focus: window
		}, settings);
		var el = settings.el;
		settings.focus = (typeof settings.focus == 'string' ? $('#' + settings.focus) : settings.focus);
		try {
			var offset = $(settings.focus).offset();
		} catch (e) {}
		var left = $(window).scrollLeft();
		var top = $(window).scrollTop();
		if (offset) {
			left = offset.left;
			top = offset.top;
		}
		el.css("position", "absolute");
		el.css("left", ($(settings.focus).width() - el.width()) / 2 + left + "px");
		el.css("top", ($(settings.focus).height() - el.height()) / 2 + top + "px");
		return el;
	}
};

core.popup = {
	show: function (id, url, data, config) {
		var self = this;
		config = config || {};
		core.blocked();
		$('body').append('<div id="popupbg" style="height:'+$(document).height()+'px;width:'+$(document).width()+'"></div>');
		$('#popupbg').click(function(){
			self.close(id);
		});
		$('#popupbg').css({display: 'block'});
		$.ajax({
			url: url,
			data: data,
			type: 'post',
			success: function (response) {
				var html = '<div class="popup-window ' + (config.cls || '') + '">' + '<table width="100%" cellspacing="0" cellpadding="0" class="popup_table">' +
					'<tr><td class="td11">&nbsp;</td><td class="td12">&nbsp;</td><td class="td13">&nbsp;</td></tr>' +
					'<tr><td class="td21">&nbsp;</td><td class="td22">' + '<div class="popup_title">' +
					'<a href="javascript:void(0)" class="close" onclick="$(this).parents(\'.popup-window\').remove(); $(\'#popupbg\').css({display:\'none\'}); return false;">x</a>' +
					'<span>' + (config.title || '') + '</span>' + '</div>' + '<div style="' + (config.style ? config.style : '') + '" class="' +
					(config.cls ? config.cls + '_content' : '') + '">' + response + '</div>' + '</td><td class="td23">&nbsp;</td></tr>' +
					'<tr><td class="td31">&nbsp;</td><td class="td32">&nbsp;</td><td class="td33">&nbsp;</td></tr>' + '</table>' + '</div>';
				var win = $(html).attr('id', id);
				$('body').append(win);
				win.fadeIn('slow');
				core.center(win, 'fixed');
				core.unblocked();
			}
		});
		$(window).resize(function () {
			$('#'+id).css({
				left: ($(window).width() - $('#'+id).width()) / 2
			});
			$('#popupbg').css({
				width: $(document).width(),
				heigth: $(document).width()
			});
		});
	},
	win: function (url, name, attrs) {
		if (!attrs) attrs = "height=550,width=1000,status=no,left=100,top=1,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no";
		window.open(url, name, attrs);
	},
	close: function (id) {
		$('#'+id).remove();
		$('#popupbg').css({display: 'none'});
	}
};

var comment = {
	url: '/ajax/comment/',
	add: function(item_id, parent_id) {
		var data = {
			'cmd': 'form',
			'item_id': item_id,
			'parent_id': parent_id
		};
		core.popup.show('comment', this.url, data, {
			title: "Добавить отзыв",
			cls: 'popup_comment'
		});
	},
	'delete': function(id) {
		var data = {
			'cmd': 'del',
			'id': id
		};
		$.ajax({
			url: this.url,
			data: data,
			type: 'post',
			success: function (r) {
				$('#count_votes').text(r.votes_count);
				$('#count_comments').text(r.comments_count);
				$('#item_stars').css('width', r.rating+'%');
				for (var i=0; i<r.ids.length; i++) {
					$('#comment-'+r.ids[i]).fadeOut('slow', function() {
						$('#comment-'+r.ids[i]).remove();
					});
				}
			}
		});
	},
	send: function(form) {
		if (!$(form).validateForm()) return;
		core.formPost(form, {
			callback: function (r) {
				core.popup.close('comment');
				$('#count_votes').text(r.votes_count);
				$('#count_comments').text(r.comments_count);
				$('#item_stars').css('width', r.rating+'%');
				var comment = $('<li id="comment-' + r.id + '">' +
					'<div class="caption"><span class="header">' + r.user_name + '</span><span class="date">' + r.user_date + '</span></div>' +
					'<div class="clr"></div><div class="reviews_main"><table class="main_review"><tbody><tr><td class="condition_product">' +
					'Оценка пользователя:</td><td class="stars"><div class="rating"><div class="stars_grey_big"><div style="width:' +
					r.user_rating + '%;" class="stars_vote_big"></div></div></div></td></tr></tbody></table></div></div>' +
					'<div class="reviews_text">' +
					(r.user_use_period.length > 0 ? '<span class="reviews_title inline">Пользуюсь:</span> ' + r.user_use_period : '') +
					(r.user_benefits.length > 0 ? '<span class="reviews_title">Преимущества:</span>' + r.user_benefits : '') +
					(r.user_disadvantages.length > 0 ? '<span class="reviews_title">Недостатки:</span>' + r.user_disadvantages : '') +
					(r.user_text.length > 0 ? '<span class="reviews_title">Отзыв пользователя:</span>' + r.user_text : '') + '</div>' +
					'<div class="reviews_service"><a href="javascript:void(0)" onclick="comment.add(' + r.item_id + ', ' + r.id + ')" class="reply">Ответить</a>' +
					(r.user_admin > 0 ? '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onclick="comment.delete(' + r.id + ')" class="delete">Удалить</a>' : '') +
					'</div></li>').hide();
				if (r.root_id > 0) {
					var parent = $('#comment-' + r.parent_id);
					parent.find('.reviews_service').remove();
					comment.addClass('comnt').insertAfter(parent);
				} else {
					$('#reviews_ct').prepend(comment);
				}
				comment.fadeIn('slow');
			}
		});
	},
	useful: function (link, comment_id, yesno) {
		$.ajax({
			url: this.url,
			data: {
				cmd: 'useful',
				comment_id: comment_id,
				yesno: yesno ? 1 : 0
			},
			type: 'POST',
			dataType: 'json',
			success: function (r) {
				$(link).parent().find('.useful_yes').html((r.useful_yes > 0 ? '(' + r.useful_yes + ')' : ''));
				$(link).parent().find('.useful_no').html((r.useful_no > 0 ? '(' + r.useful_no + ')' : ''));
			}
		});
	}
};
