/**
 * @author kleppe
 */

Form.ajaxify = function(container, options){

	var forms = container.getElementsByTagName("form");

	if (forms.length == 0) {

		return;
	}

	var form = forms[0];
	var submit = Form.getInputs(form).find(function(input){return input.type == "submit" || input.type == "button";});

	var cancel = document.createElement("input");
	cancel.type = "button";
	cancel.className = "button";
	cancel.value = $M.CANCEL;

	submit.parentNode.appendChild(cancel);

	Event.observe(cancel, "click", function(event){

		Event.stop(event);
		options.onCancel();
	});

	Event.observe(submit, "click", function(event){

		Event.stop(event);

		submit.value = $M.SAVING;
		submit.disabled = true;

		form.request({onComplete: options.onResponse});


	});

	return form;
};


Ajax.Inline = Class.create();

Ajax.Inline.prototype = {

	stores: [],

	initialize: function(link, action){

		this.link = link;
		this.action = action;

		this.linkText = this.link.innerHTML;

		this.url = link.href;

		switch (this.action){

			case "edit":
				this.target = $(link.rel) || this.createTarget();
				break;

			case "add":
				this.target = document.createElement("div");

				Element.extend(this.target);
				$(link.rel).appendChild(this.target);
				this.target.innerHTML = $M.LOADING;
				break;
		}

		console.log("target:", this.target);

		if (this.action == "edit"){
			Element.store(this.link);
			this.link.innerHTML = $M.LOADING;
			this.target.show();

		}

		this.load();
	},

	createTarget: function(){

		var id = this.link.id;

		if (!id){

			var index = 0;
			do {id = "inline_edit_" + (++index);} while ($(id));
		}

		new Insertion.After(this.link, '<div id="' + id + '_view"></div>');
		return $(id + "_view");
	},

	load: function(){

		var ajax = new Ajax.Request(this.url, {

			method: 'get',
			onComplete: function(response){

				this.handleResponse(response, this.prepareFirstForm.bind(this));

			}.bind(this)
		});

		console.log("load", ajax);
	},

	handleResponse: function(ajax, handler){

		console.log("response:", ajax, handler);

		var response;

		try {

			response = ajax.responseText.evalJSON();

		} catch (e){

			response = {

				content: ajax.responseText,
				error: "Could not parse response",
				success: false
			};

			console.error(response, ajax);
		}

		if (typeof response.content == "string"){

			handler(this.target, response.content);

		} else if (response.content.length){

			response.content.each(function(element){

				handler($(element.target), element.content);

			}.bind(this));


		} else if (response.content.target){

			handler($(response.content.target), response.content.content);
		}


		if (!response.success){
			//alert("ERROR: " + response.error);
		}

		//this.link.hide();
	},

	prepareFirstForm: function(container, content){


		if (this.action == "edit"){

			this.stores.push(container);
			Element.store(container);
		}

		this.prepareForm(container, content);
	},

	prepareForm: function(container, content){


		if (this.action == "add"){

			container = this.target;
		}

		console.log("form", container, this.action, this.target);
		container.update(content);
		console.log("update", container, this.action, this.target);

		triplib.initLinks(Selector.findChildElements(container,  ["a.ajax"]));
		triplib.initInputs($$("input.ajax"));

		this.form = Form.ajaxify(container, {

			onCancel: this.restore.bind(this),
			onResponse: this.updateForm.bind(this)
		});
	},

	restore: function(){
		this.stores.each(function(stored){
								  Element.restore(stored); 
						});

		if (this.action == "add"){

			this.target.hide();
		}

		this.link.show();
		this.link.innerHTML = this.linkText;
		// Element.restore(link); // REMOVED FOR DEBUGGING
	},

	updateForm: function(response){

		this.handleResponse(response, this.prepareForm.bind(this));

		if (this.link.id == 'addTravelReportLocationLink') {
			Element.insert($$('div.intro').last(), { after: '<div id="addTravelReportLocation" class="addTravelReportLocation">' + $('addTravelReportLocation').innerHTML + '</div>' } );
			$$('div.addTravelReportLocation').first().remove();
			triplib.initLinks(Selector.findChildElements($('addTravelReportLocation'),  ["a.ajax"]));
		}

		this.link.show();
		this.link.innerHTML = this.linkText;
		Element.restore(link);

	}
};

