/*
---
name: MooDialog.Request
description: Loads Data into a Dialog with Request
authors: Arian Stolwijk
license:  MIT-style license
requires: [MooDialog, Core/Request.HTML]
provides: MooDialog.Request
...
*/

MooDialog.AddressSelect = new Class({

	Extends: MooDialog,

	initialize: function(url, requestOptions, postcode){
		this.parent();
		this.requestOptions = requestOptions || {};

		this.addEvent('open', function(){
			var request = new Request.JSON(this.requestOptions).addEvent('success', function(response, responseText){
			    var title = [];
			    if (response.street) title.push(response.street);
			    if (response.dependentLocality) title.push(response.dependentLocality);
			    if (response.postTown) title.push(response.postTown);
			    if (response.county) title.push(response.county);
			    var h = new Element("h3", {"html": title.join(',')});
			    var ul = new Element("ul", {"class": "address_list"});
			    response.premise.each(function(addr) {
			        var n = []
			        if (addr["organisationName"]) n.push(addr["organisationName"]);
			        if (addr["formattedPremise"]) n.push(addr["formattedPremise"]);

			        var li = new Element("li", {"html": n.join(', ')});
			        li.store("addr", addr);
			        li.inject(ul, 'bottom');
			        li.addEvent("click", function(event) {
			         var a = li.retrieve("addr");
			         ids = findRegionAndCounty(response.county);
			         if (ids) {
			          $("region_select_reg").set("value", parseInt(ids[0]));
			          
			          jQuery("#region_select_reg").trigger("change");
			          
			          $("county_select_reg").set("value", parseInt(ids[1]));
			         }
			         $("town_input").set("value", response.postTown);
			         $("address_one").set("value", a.formattedPremise + ", " + response.street);
			         this.close();
			         event.stop();
			        }.bind(this));
			    }.bind(this));
				this.setContent(h, ul);
			}.bind(this)).addEvent("failure", function() {
			                 var text = new Element("div", {html: "Sorry, Nothing was found.<br /> Please enter address in the form. <br />Thank You!"});
			                 this.setContent(text);
		                }.bind(this)).send("postcode=" + postcode);
		}.bind(this));

		if (this.options.autoOpen) this.open();

	},

	setRequestOptions: function(options){
		this.requestOptions = Object.merge(this.requestOptions, options);
		return this;
	}

});

