﻿(function($) {
	var ie6 = $.browser.msie && ($.browser.version < 8);
	var autoHideTime = 2000;
	var formDataPath = "/_c/popupForms.ashx";
	var formSendingHtml = '<p id="popupFormSendingMessage" style="text-align:center;width:160px;padding:20px;">Отправка данных...</p>';
	var formWrapHtml = '<div style="text-align:center;position:fixed;top:0;left:0;width:100%;height:100%;"></div>';
	var bgDivHtml = '<div style="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;"></div>';
	var fromPlaceHtml = '<div style="text-align:left;margin-top:200px;height:70px;padding:10px 20px 20px;display:none;background:#FFF;position:relative;"><div style="text-align:right;margin-right:-10px;"><a id="closePopupLink" href="#">[X]</a></div><div id="popupFormPlace"><p style="text-align:center;width:160px;padding:20px;">Загрузка...</p></div></div>';
	$.fn.popupAjaxForm = function() {
		this.filter("a").bind('click.popup-form-plugin', function(e) {
			e.preventDefault();
			new popupForm(this.getAttribute('href'));
		});
		return this;
	}
	function onResizeWindow(e) {
		var l = $(window).width() - e.data.outerWidth();
		if (l > 0)
			e.data.css("left", Math.round(l / 2));
		else
			e.data.css("left", 0);
	}
	function onScrollWindow(e) {
		var t = $(window).scrollTop();

		e.data.bg.css({ top: t });
		e.data.wrap.css({ top: t });
	}
	function popupForm(url) {
		var t = this;
		t.formId = null;
		t.url = url;

		t.show = showForm;
		t.showSend = showSendText;
		t.close = closeForm;
		t.onSend = formSended;
		t.onBeforeSend = onBeforeSend;

		t.bg = $(bgDivHtml).eq(0).css("opacity", .5).appendTo(document.body);
		t.wrap = $(formWrapHtml).appendTo(document.body).eq(0);
		t.place = $(fromPlaceHtml).eq(0).appendTo(t.wrap);
		if (ie6) {
			t.bg.css({ position: "absolute" });
			t.wrap.css({ position: "absolute" });
			$(window).bind("scroll", t, onScrollWindow);
		}
		else {

			var l = Math.round(($(window).bind("resize", t.place, onResizeWindow).width() - t.place.outerWidth()) / 2);
			l = (l > 0) ? l : 0;
			t.place.css({ "width": t.place.width(), left: l }).show("normal");
		}
		t.req = $.ajax({
			url: t.url, global: false, type: "GET", dataType: "xml", error: formLoadError,
			complete: function(XMLHttpRequest, textStatus) {
				t.req = null;
				if (XMLHttpRequest.responseXML != null && XMLHttpRequest.responseXML.documentElement.nodeName == "form") {
					t.formId = XMLHttpRequest.responseXML.documentElement.getAttribute("id");
					t.show(XMLHttpRequest.responseText);
				}
				else
					formLoadError(XMLHttpRequest, textStatus, null);
			}
		});
		t.trgt = t.place.find("#popupFormPlace").eq(0);
		t.place.find("#closePopupLink").click(function(e) {
			e.preventDefault();
			t.close();
		});
	};
	function formLoadError(XMLHttpRequest, textStatus, errorThrown) {
		alert("Ошибка");
	};
	function closeForm() {
		var t = this;
		if (t.req != null)
			t.req.abort();
		t.place.empty();
		t.place.hide("normal", function() {
			t.wrap.remove();
			t.bg.remove();
		});
	};
	function doScroll() { }
	function showForm(text) {
		var t = this;
		t.hidding = false;
		if (text && !t.form) {
			var testDiv = $('<div style="position:absolute;left:-15000px;"></div>').html(text).eq(0).appendTo(document.body);
			t.width = testDiv.width();
			t.oWidth = testDiv.outerWidth();
			var h = testDiv.height() + 10, l = Math.round(($(window).width() - t.oWidth) / 2);
			l = (l > 0) ? l : 0;
			testDiv.remove();
			t.trgt.empty();
			var ap = ie6 ? { width: t.width, height: h} : { width: t.width, height: h, left: l };
			t.place.animate(ap, 400, null, function() {
				t.form = t.trgt.html(text).find("form").eq(0).ajaxForm({ bind: t, beforeSend: onBeforeSend, send: formSended, url: t.url }); //, error: null
				t.sendText = $(formSendingHtml).eq(0).hide().insertBefore(t.form);
			});
		} else if (t.sendText) {
			t.sendText.hide();
			var l = 0, ap = ie6 ? { width: t.width, height: t.form.height() + 10} : { width: t.width, height: t.form.height() + 10,
				left: (l = Math.round(($(window).width() - t.oWidth) / 2)) > 0 ? l : 0
			};
			t.place.animate(ap, 400, null, function() {
				if (!t.hidding) t.form.show();
			});
		}
	};
	function showSendText(message) {
		var t = this;
		t.hidding = true;
		if (t.sendText) {
			var l = 0, ap = ie6 ? { width: 200, height: 70} : { width: 200, height: 70, left: (l = Math.round(($(window).width() - 200) / 2)) > 0 ? l : 0 };
			t.form.hide();
			t.place.animate(ap, 400, null, function() {
				if (message) t.sendText.text(message);
				if (t.hidding) t.sendText.show();
			});
		}
	};
	function formSended(data, ts) {
		var t = this;
		if (data.documentElement.nodeName == "success") {
			$.ajax({ url: t.url, global: false, type: "GET", data: { debugId: data.documentElement.getAttribute("debugId"), formId: t.formId} });
			t.showSend(data.documentElement.getAttribute("message"));
			setTimeout(function() { t.close(); }, autoHideTime);
		} else {
			$(data.documentElement.childNodes).each(function() {
				var id = this.getAttribute("id"), message = this.getAttribute("message");
				t.form.find("#" + id).prev(".message").text(message);
			});
			t.show();
		}
	};
	function onBeforeSend() {
		this.showSend();
		this.form.find(".message").html("");
	}
	//success
	$.fn.popupFormSubmit = function(options) {
		var b = options.bind || this;
		if (typeof (options.beforeSend) == 'function')
			options.beforeSend.call(b);
		$.ajax({
			url: options.url, global: false, type: "POST", dataType: "xml", data: $.param($(this).serializeForm(false)), error: formLoadError,
			success: function(data, ts) {
				if (typeof (options.send) == 'function')
					options.send.call(b, data, ts);
			},
			complete: function(XMLHttpRequest, textStatus) {
				$("#TextArea1").val(XMLHttpRequest.responseText);
			}
		})
	};
	$.fn.serializeForm = function(semantic) {
		var a = [];
		if (this.length == 0) return a;

		var form = this[0];
		var els = form.elements;
		if (!els) return a;
		for (var i = 0, max = els.length; i < max; i++) {
			var el = els[i];
			var n = el.name;
			if (!n) continue;

			if (semantic && form.clk && el.type == "image") {
				// handle image inputs on the fly when semantic == true
				if (!el.disabled && form.clk == el)
					a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
				continue;
			}

			var v = $.fieldValue(el, true);
			if (v && v.constructor == Array) {
				for (var j = 0, jmax = v.length; j < jmax; j++)
					a.push({ name: n, value: v[j] });
			}
			else if (v !== null && typeof v != 'undefined')
				a.push({ name: n, value: v });
		}

		if (!semantic && form.clk) {
			// input type=='image' are not found in elements array! handle them here
			var inputs = form.getElementsByTagName("input");
			for (var i = 0, max = inputs.length; i < max; i++) {
				var input = inputs[i];
				var n = input.name;
				if (n && !input.disabled && input.type == "image" && form.clk == input)
					a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
			}
		}
		return a;
	};
	/**
	* Returns the value of the field element.
	*/
	$.fieldValue = function(el, successful) {
		var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
		if (typeof successful == 'undefined') successful = true;

		if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

		if (tag == 'select') {
			var index = el.selectedIndex;
			if (index < 0) return null;
			var a = [], ops = el.options;
			var one = (t == 'select-one');
			var max = (one ? index + 1 : ops.length);
			for (var i = (one ? index : 0); i < max; i++) {
				var op = ops[i];
				if (op.selected) {
					var v = op.value;
					if (!v) // extra pain for IE...
						v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
					if (one) return v;
					a.push(v);
				}
			}
			return a;
		}
		return el.value;
	};

	/**
	* ajaxForm() provides a mechanism for fully automating form submission.
	*
	* The advantages of using this method instead of ajaxSubmit() are:
	*
	* 1: This method will include coordinates for <input type="image" /> elements (if the element
	*	is used to submit the form).
	* 2. This method will include the submit element's name/value data (for the element that was
	*	used to submit the form).
	* 3. This method binds the submit() method to the form for you.
	*
	* The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
	* passes the options argument along after properly binding events for submit elements and
	* the form itself.
	*/
	$.fn.ajaxForm = function(options) {
		return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
			e.preventDefault();
			$(this).ajaxSubmit(options);
		}).bind('click.form-plugin', function(e) {
			var target = e.target;
			var $el = $(target);
			if (!($el.is(":submit,input:image"))) {
				// is this a child element of the submit el?  (ex: a span within a button)
				var t = $el.closest(':submit');
				if (t.length == 0)
					return;
				target = t[0];
			}
			var form = this;
			form.clk = target;
			if (target.type == 'image') {
				if (e.offsetX != undefined) {
					form.clk_x = e.offsetX;
					form.clk_y = e.offsetY;
				} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
					var offset = $el.offset();
					form.clk_x = e.pageX - offset.left;
					form.clk_y = e.pageY - offset.top;
				} else {
					form.clk_x = e.pageX - target.offsetLeft;
					form.clk_y = e.pageY - target.offsetTop;
				}
			}
			// clear form vars
			setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
		});
	};

	// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
	$.fn.ajaxFormUnbind = function() {
		return this.unbind('submit.form-plugin click.form-plugin');
	};

})(jQuery);
