﻿/// <reference path="../../../js/jquery-1.4.1-vsdoc.js" />
/// <reference path="../../../js/MicrosoftAjax.debug.js" />

Function.prototype.delegate = function(ref) {
	var f = this;
	return function() { return f.apply(ref, arguments); };
};
(function() {
	function responseParser(onSuccess, onError, context) {
		return function(data, textStatus, XMLHttpRequest) {
			Sys.Debug.traceDump(data);
			if (!data)
				return onError.call(context, { "_FORM": "Data not found" });
			if (data.Errors)
				return onError.call(context, data.Errors);
			return onSuccess.call(context, data);
		}
	}
	function requestErrorParser(onError) {
		return function(XMLHttpRequest, textStatus, errorThrown) {
			onError({ "_FORM": "Request error." });
		}
	}
	window.Bmsi = {
		LoginPath: "/",
		RecoverPasswordPath: "/user/reset",
		SuggestionsService: '/getsuggestions/',

		responseParser: responseParser,
		GetFirstError: function(errors) {
			for (name in errors) {
				return errors[name][0];
			}
		},
		AjaxRequestError: function(XMLHttpRequest, textStatus, errorThrown) {
			//TODO: Требуется красивая обработка событий
		},
		Login: function(userEmail, userPassword, onSuccess, onError) {
			Sys.Debug.trace('Bmsi.Login');
			jQuery.ajax({
				url: Bmsi.LoginPath, cache: false, dataType: "json", type: "POST",
				data: { userEmail: userEmail, userPassword: userPassword },
				success: responseParser(onSuccess, onError),
				error: requestErrorParser(onError)
			});
		},
		RecoverPassword: function(userEmail, captchaText, onSuccess, onError) {
			jQuery.ajax({
				url: Bmsi.RecoverPasswordPath, cache: false, dataType: "json", type: "POST",
				data: { userEmail: userEmail, captchaText: captchaText },
				success: responseParser(onSuccess, onError),
				error: requestErrorParser(onError)
			});
		}
	};

})();
(function() {
	$ = jQuery;
	$('li.icon-fav a').live('click', function() {
		var a = this;
		jQuery.ajax({
			url: this.href, cache: false, dataType: "json", type: "POST",
			success: function(data) {
				if (data === true)
					$(a).attr("title", "Удалить из избранного").attr("href", a.href.replace("add", "remove")).parent().removeClass("icon-fav").addClass("icon-favactive")
					;
			},
			error: Bmsi.AjaxRequestError
		});
		return false;
	});
	$('li.icon-favactive a').live('click', function() {
		var a = this;
		jQuery.ajax({
			url: this.href, cache: false, dataType: "json", type: "POST",
			success: function(data) {
				if (data === true)
					$(a).attr("title", "Добавить в избранное").attr("href", a.href.replace("remove", "add")).parent().removeClass("icon-favactive").addClass("icon-fav")
					;
			},
			error: Bmsi.AjaxRequestError
		});
		return false;
	});
	$('div.updateable-content div.h-stripe a').live('click', function() {
		show_progress(this);
		$(this).parents('div.updateable-content:first').load(this.href, { _ajax: true }, function() {
			hide_progress(this);
			recalculate_all();
		});
		return false;
	});
	$("#block-filter").live('submit', function() {
		var update = $('div.updateable-content');
		if (!update.length)
			return;
		show_progress(update);
		$(this).ajaxSubmit({
			type: 'GET', dataType: 'html', data: { _ajax: true }
			, success: function(result) {
				update.html(result); hide_progress(update); recalculate_all();
				if (update.find('ul.main').find('li.clearfix').length > 0) {
					hide_noresults(update);
				}
				else {
					show_noresults(update);
					update = $(update).hasClass('block') ? update : $(update).parents(".block:first");
					update.hide();
				}
			}
			, error: function(xhr, status, e) { hide_progress(update); }
		});
		return false;
	});


	var servicePath = Bmsi.SuggestionsService;
	$.fn.hasValue = function(name, value) {
		return this.find('input[name=' + name + '][value=' + value + ']').length > 0;
	};
	function suggestionParser(request, response, obj) {
		return function(data) {
			if (data != null && jQuery.isArray(data) && data.length > 0) {
				var re = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi");
				response($.map(data, function(d) {
					return {
						id: d.ID,
						label: d.DisplayName.replace(re, "<strong>$1</strong>"),
						value: d.DisplayName
					};
				}));
				return;
			}
			response([]);
			obj.onEmpty();
		}
	}
	function getTargetList(element) {
		var p = $(element).parent(), list = p.find('ul.selected');
		if (list.length)
			return list;
		return $('<ul class="selected"></ul>').appendTo(p);
	}
	function renderItem(data, obj) {
		return $('<li></li>').attr("id", data.id || data.ID).text(data.value || data.DisplayName)
						.append(
							$('<input type="hidden"/>').attr("name", obj.name).val(data.id || data.ID)
		//						).append(
		//							$('<a href="#" class="name"></a>').text(data.value || data.DisplayName)
						).append(
							$('<a href="#delete" class="delete" title="Удалить"></a>')
						);
	}
	function checkValues(el, obj) {
		var values = $(el).parent().add(obj.targetList).find('input:hidden[name=' + obj.name + ']');
		if (!values.length)
			return;
		var target = getTargetList(el);
		values.each(function() {
			var tf = $(this), val = tf.val(); tf.remove();

			tf = $('<li></li>').attr("id", val).appendTo(obj.targetList);
			$.getJSON(servicePath + obj.type + '/Item/' + val, function(data) {
				if (data != null)
					tf.replaceWith(obj.renderItem(data, obj));
				else
					tf.remove();
			});
		});
	}

	$.fn.entitySuggestions = function(opts) {

		this.filter('input').each(function() {
			var targetInput = $(this);
			if (targetInput.data('Bmsi.filterSuggestions') != null)
				return;
			var obj = {
				delay: opts.delay || 500,
				type: opts.type,
				criteria: opts.criteria || {},
				name: targetInput.attr("name"),
				source: opts.source || function(request, response) {
					var c = obj.criteria;
					if (typeof (c) == 'function')
						c = opts.criteria.call(obj, request);
					$.extend(c, { input: request.term });
					$.getJSON(servicePath + obj.type, c, suggestionParser(request, response, obj));
				},
				appendTo: opts.appendTo || targetInput.parent(),
				renderItem: opts.renderItem || renderItem,
				targetList: opts.targetList || getTargetList(targetInput)[0],
				select: opts.select || function(event, ui) {
					if ($('#' + ui.item.id, obj.targetList).length)
						return;
					obj.renderItem(ui.item, obj).appendTo(obj.targetList);
				},
				close: opts.close,
				onEmpty: function() {
					var q = $('p.nothing', this.appendTo);
					if (!q.length)
						q = $('<p class="nothing">Ничего не найдено!</p>').appendTo(this.appendTo);
					q.show();

				}
			};
			targetInput.data('Bmsi.filterSuggestions', obj);
			try { targetInput[0].removeAttribute("name"); }
			catch (e) { targetInput.attr("name", null); }
			checkValues(targetInput, obj);

			targetInput.autocomplete({
				appendTo: obj.appendTo,
				source: obj.source,
				delay: 500,
				select: obj.select,
				open: function() {
					$('p.nothing', obj.appendTo).hide();
				},
				close: function() {
					targetInput.val('');
					$('p.nothing', obj.appendTo).hide();
					if (typeof (obj.close) == 'function')
						obj.close.apply(obj, arguments);
					//return false;
				}
			});
		});
		return this;
	}
	$.fn.entitySuggestions.renderItem = renderItem;
	$('ul a.delete').live('click', function() {
		$(this).parent().remove();
		return false;
	});

	//Sys.Debug.traceDump(this.selectedIndex);

})();

