﻿/// <reference path="../jquery-1.3.2-vsdoc.js" />

/*
	Updates to this file must be run through the compressor at:
	http://javascriptcompressor.com/
	then the dsbo.ajax-extensions.min.js file must be updated
*/

/*global jQuery, document */

jQuery.extend({
	getAntiForgeryToken: function() {
		var field = document.getElementsByName("__RequestVerificationToken");
		if (field.length > 0) {
			return jQuery(field[0]).serialize();
		} 
		else {
			return "__RequestVerificationToken=";
		}
	},
	postJSON: function(url, data, callback) {
		jQuery.post(url, data, callback, 'json');
	},
	getHTML: function(url) {
		var htm = jQuery.ajax({
			url: url,
			async: false
		}).responseText;
		return htm;
	},
	ajaxUpload: {
		createUploadIframe: function(frameId) {
			var io = jQuery('<iframe>').attr({
				id: frameId,
				name: frameId,
				src: 'javascript:false'
			});

			// set css
			io.css('position', 'absolute');
			io.css('top', '-1000px');
			io.css('left', '-1000px');

			// append
			io.appendTo(document.body);

			return io.get(0);
		},
		createUploadForm: function(formId, frameId, url, data) {
			// create form 
			var form = jQuery('<form></form>').attr({
				id: formId,
				action: url,
				target: frameId,
				method: "post",
				name: formId,
				enctype: "multipart/form-data"
			});

			// set css
			form.css('position', 'absolute');
			form.css('top', '-1200px');
			form.css('left', '-1200px');
			
			// append
			form.appendTo(document.body);
			
			// create hidden fields
			jQuery.each(data, function(name, val) {
				jQuery('<input type="hidden" />').attr('name', name).attr('value', val).appendTo(form);
			});

			return form.get(0);
		}
	}
});

jQuery.fn.extend({
	ajaxFileUpload: function(s) {
		s = jQuery.extend({}, jQuery.ajaxSettings, s,
		{
			contentType: 'multipart/form-data',
			cache: false,
			type: 'POST',
			async: true,
			username: null,
			password: null
		}); // Some forced options

		if (s.data && s.processData && typeof s.data === "string")
			throw "Can't use a string as data - sorry";

		var id = (new Date().getTime());
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;

		var io = jQuery.ajaxUpload.createUploadIframe(frameId);
		var form = jQuery.ajaxUpload.createUploadForm(formId, frameId, s.url, s.data);

		var oldElems = jQuery(this);
		var newElems = oldElems.clone();

		oldElems.attr('id', '');

		jQuery.each(oldElems, function(i) {
			jQuery(oldElems[i]).before(newElems[i]);
		});

		oldElems.appendTo(form);

		// Watch for a new set of requests
		if (s.global && !jQuery.active++)
			jQuery.event.trigger("ajaxStart");

		var getDocument = function(io) {
			if (io.contentWindow) {
				return io.contentWindow.document;
			}
			else if (io.contentDocument) {
				return io.contentDocument.document;
			}

			return null;
		};

		// Create the request object
		var xml = {
			timeoutTimer: null,
			clearTimer: null,
			requestDone: false,

			getResponseHeader: function(str) {
				if (str.toLowerCase() == 'content-type') {
					try {
						var doc = getDocument(io);

						// The firefox way
						if (doc && doc.contentType) {
							return doc.contentType;
						}
					}
					catch (ex) { }

					//We have to guess...
					if (s.dataType == 'xml' && this.responseXML && this.responseXML.documentElement && this.responseXML.documentElement.nodeName != 'HTML') {
						return 'text/xml';
					}

					return 'text/html';
				}

				throw "Unknown response header " + str;
			},
			getAllResponseHeaders: function() {
				return [this.getResponseHeader('content-type')];
			},
			abort: function() {
				if (this.clearTimer) { return; }
				if (this.timeoutTimer) {
					window.clearTimeout(this.timeoutTimer);
					this.timeoutTimer = null;
				}

				this.requestDone = true;

				// The request was completed
				if (s.global) {
					jQuery.event.trigger("ajaxComplete", [xml, s]);
				}

				// Handle the global AJAX counter
				if (s.global && ! --jQuery.active) {
					jQuery.event.trigger("ajaxStop");
				}

				var that = this;

				this.clearTimer = setTimeout(function() {
					try {
						jQuery(io).remove();
						jQuery(form).remove();
					}
					catch (e) {
						jQuery.handleError(s, that, null, e);
					}
					finally {
						that.clearTimer = null;
					}
				}, 100);
			}
		};

		if (s.global) {
			jQuery.event.trigger("ajaxSend", [xml, s]);
		}
		
		// Wait for a response to come back
		var uploadCallback = function(reason) {
			if (xml.requestDone) return;
			xml.requestDone = true;

			try {
				var doc = getDocument(io);

				if (doc) {
					if (doc.location.href != s.url && doc.location.href == 'about:blank') {
						throw "Bad HTTP status";
					}

					// IE is EVIL!
					if (doc.XMLDocument && s.dataType == 'xml')
						doc = doc.XMLDocument;

					if (s.dataType == 'html' && doc.documentElement && doc.documentElement.innerHTML) {
						xml.responseText = doc.documentElement.innerHTML;
					}
					else if (doc.documentElement && (doc.documentElement.textContent || doc.documentElement.innerText)) {
						xml.responseText = doc.documentElement.innerText ? doc.documentElement.innerText : doc.documentElement.textContent
					}
					else {
						xml.responseText = '';
					}

					xml.responseXML = doc;
				}
			}
			catch (e) {
				jQuery.handleError(s, xml, null, e);
			}

			var status;

			status = reason != "" ? reason : "success";

			// Make sure that the request was successful or notmodified
			if (status == "success") {
				// process the data (runs the xml through httpData regardless of callback)
				try {
					var data = jQuery.httpData(xml, s.dataType, s.dataFilter);
				}
				catch (ex) {
					status = "parseerror";
				}
			}

			if (status == "success") {
				// If a local callback was specified, fire it and pass it the data
				if (s.success) {
					s.success(data, status);
				}

				// Fire the global callback
				if (s.global) {
					jQuery.event.trigger("ajaxSuccess", [xml, s]);
				}
			}
			else {
				jQuery.handleError(s, xml, status);
			}

			// Process result
			if (s.complete) {
				s.complete(xml, status);
			}

			xml.abort();
		};

		// Timeout checker
		if (s.timeout > 0) {
			xml.timeoutTimer = setTimeout(function() {
				// Check to see if the request is still happening
				if (!xml.requestDone) uploadCallback("timeout");
			}, s.timeout);
		}

		jQuery(io).load(function() { uploadCallback(""); });

		try {
			form.submit();
		}
		catch (e) {
			jQuery.handleError(s, this, null, e);
		}

		return xml;
	}
});