	// ===============
// Globals
// ===============
var idForm		= '#members-search';
var idQuery		= '#members-query';
var idGrantors		= '#members-grantors';
var idCategories	= '#members-categories';
var idRegions		= '#members-regions';
var idSubmit		= '#members-submit';
var idResults		= '#results';
var idResultsList	= '#resultsList';
var idResultsPages	= '.resultsPagination';
var idResultsQueryText	= '.resultsQueryText';
var idResultsQueryOpts	= '.resultsQueryParams';
var idNoResults		= '#resultsEmpty';
var idResult		= '#details';
var restCallAll		= 'all';

var idMap		= "#map";
var idStreet		= "#street";
var idDirections	= "#directions"

var infoLength		= 256;
var htmlResults		= '';
var tplResultsCompany 	= '';
var loadingImage	= '<img src="/system/modules/com.navyblue.opencms.site.members/resources/images/is/loader.gif"/>';
//===============
// Templates
//===============	
var tplResultsCompany;	
var tplResultCompany;	

(function($) {
	
$.widget("ui.memberssearch", {
	// default options
	options: {
		host: "http://database.rwha.co.uk/rest/",
		serviceCategories: 	'category/',
		serviceGrantors: 	'household/',
		serviceRegions: 	'region/',
		serviceSearch: 		'search/external',
		serviceCompany: 	'company/',
		restCallAll:		'all',
		restCallBack: 		'?callback=?',
		type:			'l', // Should be 'l' or 'm'
		auto:			'n' // auto load results.
	},
	// ===============
	// Initialise
	// ===============
	_init: function() {
		// Set up
		this.query		= {};
		this.company 		= {};
		this.companyAddress 	= {};
		this.companyId 		= 0;
		this.mapInfo = { postcode: '', address: '', name: '' }
		this.results = {};
		this.pageSize = 10;
		// Config
		$(idResults).hide();
		$(idNoResults).hide();
		$('#startAt').val(0);
		jQuery.metadata.setType("attr","data");

		// Load and start parsing the interface...
		// If we need to load the templates
		if (this.options.type == 'm')
			this._loadTemplates();
		this._loadCategories();
		this._loadRegions();
		this._initEvents();
		this._initForm();
		if (this.options.type == 'm' && this.options.auto == 'y') {
			this.searchOnLoad();
		}		
	},
	_initEvents: function() {
		var self	= this;	
		// If we're on the full page
		if (this.options.type == 'm') {
			$(idForm).bind("submit", function (event) {
				console.log("EVENTS: Fire Submit");
		    		try {
		    			self.search();
		    			return false;
		    		}
		    		catch (err) {
		    			console.log("ERROR", err);
		    		}	
		    		return false;
		    	}); 	    
		    	// Query - Query Click EVENT
		    	$(idQuery).bind('click', function () {
				console.log("EVENTS: Query Change");
				$(this).attr('value','');
		    		self._setStartAt(0);
				$(idResult).fadeOut(300);
		    		$(idResults).hide();
		    	});
			$('#directory').slideDown(100);	
		}
		$(idForm).bind("hover click keydown", function (event) {
	    		$("#directory").expose({ loadSpeed: 0});	    	
	    	})
	},
	// Initialise the form
	_initForm: function() { },
	// The the jTemplates remotely
	_loadTemplates: function () {
		// Extend the sweet libraries
		// with some additional utitlty functions to make the
		// template a little smaller and more compact
		$.Sweet.setDelimiters('<%...%>');
		$.Sweet.extendUtil({
			findCompanyAddress: function(c) {
				var a = {};
				$.each (c, function (index, address) { 
					if (address.type.id == '1') { a = address; }
				});
				return a;
			},
			findPurplePagesContacts : function (c) {
				var a = [];
				$.each (c, function (index, contact) { 
					if (contact.showmembers) { a.push(contact); }
				});
				return a;
			},
			utilTruncateInformation : function (i) {
				var trunc = i;
				if (trunc.length > infoLength) { trunc = trunc.substring(0, infoLength); trunc = trunc.replace(/\w+$/, '');	 trunc += ' ... '; }
				return trunc;
			},
			utilFormatInformation : function (i) {				
				return i.replace(/\\n/g,"<br/>");
			},
			utilGenerateBannerPath : function (i, n) {				
				var path	= '';
				var el		= n.replace(/\&/g, "").replace(/LTD/g, "").toLowerCase();
				var els		= el.split(' ');
				
				$.each(els, function (index, element) {
					if (element != '')
						path += element	+ '/'				
				})
				path += i;
				return path;
			}
		});
		// Load the templates...
		$.ajax({ url : '/members-directory/tpl/results.tpl', async: false, cache: true, dataType: 'text', success: function(data, text, xhtmlr) { tplResultsCompany = data; } });
		$.ajax({ url : '/members-directory/tpl/result.tpl', async: false, cache: true, dataType: 'text', success: function(data, text, xhtmlr) { tplResultCompany = data; } });
		$(idResultsList).template(tplResultsCompany);
		$(idResult).template(tplResultCompany);
	},
	_loadCategories : function () {
		_self = this;
		_self._loadJSON(this.options.host + this.options.serviceCategories + this.options.restCallAll + this.options.restCallBack,
				function (xhtmlr, text, code) { _self.evntShowError('Error loading Categories','There was an error loading the search results, ' + text + "<br/>Code [" + code + "]")},
				function(data, text, xhtmlr) { 			
						$.each(data.result.items, function (index, value) {
							$(idCategories).append('<option value="'+value.id+'">'+value.name+'</option>');	
						})
				});
	},
	_loadRegions : function () {
		_self = this;
		_self._loadJSON(this.options.host + this.options.serviceRegions + this.options.restCallAll + this.options.restCallBack,
				function (xhtmlr, text, code) { _self.evntShowError('Error loading Regions','There was an error loading the search results, ' + text + "<br/>Code [" + code + "]")},
				function(data, text, xhtmlr) { 			
						$.each(data.result.items, function (index, value) {
							$(idRegions).append('<option value="'+value.id+'">'+value.name+'</option>');	
						})
				});
	},
	_loadGrantors : function () { },
	// ===============
	// Search
	// ===============
	search: function () {
		this._setStartAt(0);
		this._showLoading();
    		this._resultsProcess();
		this._resultsLoad();		    	
		return false;
	},
	searchOnLoad: function () {
		this._setStartAt(0);
		$('#query').val($.url.param('query'));
		$('#pageSize').val($.url.param('pageSize'));
		$('#startAt').val($.url.param('startAt'));
		this.query = window.location.search.substr(1).trim();
		this._showLoading();
		this._resultsLoad();
		return false;		    	
	},
	page: function (page) {
		if (page == undefined || page != null) {
			this._setStartAt(page * this.pageSize);
		}
    		this._resultsProcess();
		this._pageLoad();		    	
	},
	// ===============
	// Results
	// ===============
	_resultsProcess : function () {		
		// Get the form fields...
		$.mask.close();
		this.query = $(idForm).serialize();
	},
	_resultsLoad : function () {
		_self = this;
		_self._loadJSON(this.options.host + this.options.serviceSearch + this.options.restCallBack,
				function (xhtmlr, text, code) { _self.evntShowError('Error loading Search Results','There was an error loading the search results, ' + text + "<br/>Code [" + code + "]")},
				function(data, text, xhtmlr) { 
					_self.results = data; 
					_self._resultsBuildMarkup();
					_self._resultsBuildSummary();
					return false;		
				},
				this.query
		);
		return false;
	},
	_pageLoad : function () {
	    	_self = this;
	        _self._loadJSON(this.options.host + this.options.serviceSearch + this.options.restCallBack,
			function (xhtmlr, text, code) {
	            		_self.evntShowError('Error loading Search Results','There was an error loading the search results, ' + text + "<br/>Code [" + code + "]")
			},
	            	function(data, text, xhtmlr) {
	            		_self.results = data;
	            		_self._resultsBuildMarkup();
			},
			this.query
			);
		},
	_resultsBuildSummary : function () {
		this._resultsBuildPagination();
		$(idResultsQueryText).html($(idQuery).val());
	},
	_resultsBuildPagination : function () {	
		_self = this;
		$(idResultsPages).pagination(this.results.result.count, {
			num_edge_entries: 2,
			num_display_entries: 8,
			prev_text: ' ',
			next_text: ' ',
			items_per_page: 10,
			load_first_page: false,
			callback: function (page_id, panel) {
				console.log("Calling callback");
				_self.page(page_id);
			}
	    });
	},	
	_resultsBuildMarkup : function () {
		_self = this;
		try {
			if (_self.results.result.count > 0) {
				$(idResultsList).applyData(_self.results.result, {noIterate: true});
				$(".loadLink").bind("click", function () {
					_self._companyShow($(this));
				})
			}
			else {
				_self._emptyShow();
			}
		}
		catch (e) { 
			console.log(e); 
		}
		$(idResults).fadeIn(300);
	},
	_resultsHide: function () {
		$(idResults).fadeOut(300, function () {
			$(idResult).fadeIn(300);
		});				
	},
	_emptyShow: function () {
			
	},
	// ===============
	// Result
	// ===============
	_companyShow: function (l) {
		_self = this;
		this.companyId = l.metadata().id;
		this._companyLoad();		
	},
	_companyLoad: function () {
		this._showLoading();
		_self = this;
		_self._loadJSON(_self.options.host + _self.options.serviceCompany + _self.companyId + _self.options.restCallBack,
				function (xhtmlr, text, code) { _self.evntShowError('Error loading Search Results','There was an error loading the search results, ' + text + "<br/>Code [" + code + "]")},
				function(data, text, xhtmlr) { 
					_self.company = data; 
					console.log(data);
					_self._companyLoadMapInfo();
					$(idResult).applyData(_self.company.company);
					$('.button[rel^="bookmark"]').jFav();						
					$('.button[rel^="print"]').bind("click", function () { $(idResult).jqprint(); return false; });
					$('.button[rel^="back"]').bind("click", function () { _self._companyHide(); return false; });
					$('a[rel^="map"]').bind("click", function () {
						console.log("Map click");
						$(document).unbind("afterReveal.facebox");
						console.log("Map click - unbounded");
						$(document).bind("afterReveal.facebox", function () {
							console.log("BIN");
							initialiseMap(_self.mapInfo.postcode, _self.mapInfo.address);
						});
						console.log("Map click");
						$.facebox({ width: 550, height: 600, ajax:"maps/index.jsp", title: _self.company.name });
						return false;
					});
					$('a[rel^="directions"]').bind("click", function () {
						$(document).unbind("afterReveal.facebox");
						$(document).bind("afterReveal.facebox", function () {
							console.log("BIN D");
							initialiseDirections(_self.mapInfo.postcode, _self.mapInfo.address);
						});
						$.facebox({ width: 550, height: 600, ajax:"maps/directions.jsp", title: _self.company.name });
						return false;
					}); 
					$('a[rel^="street"]').bind("click", function () {
						$(document).unbind("afterReveal.facebox");
						$(document).bind("afterReveal.facebox", function () {
							console.log("BIN S");
							initialiseStreet(_self.mapInfo.postcode, _self.mapInfo.address);
						});
						$.facebox({ width: 1000, height: 470, ajax: "maps/street.jsp?"});
						return false;
					});
					$('a[rel^="map"], a[rel^="directions"], a[rel^="street"]').facebox();
					_self._resultsHide();

				}
		);
	},
	_companyLoadBanner: function (id) {
//		var ban_u = 'http://ads.rwha.co.uk/www/delivery/avw.php?campaignid=5&amp;what=keywords:co_'+this.company.company.id+'&amp;cb=0';
//		$('.result_banner').html('<img/>')
//		$('.result_banner > img').attr('src',ban_u);
	},
	_companyLoadMapInfo: function () {
		this._companyLoadAddress();
		this.mapInfo.postcode = this.companyAddress.postcode;		
		this.mapInfo.address = "<strong>"+ this.company.company.name.replace('&','&amp;') + "</strong>";
		if (this.companyAddress.address1 != undefined && this.companyAddress.address1 != '') this.mapInfo.address += "<br/>" + this.companyAddress.address1;
		if (this.companyAddress.address2 != undefined && this.companyAddress.address2 != '') this.mapInfo.address += "<br/>" + this.companyAddress.address2;
		if (this.companyAddress.address3 != undefined && this.companyAddress.address3 != '') this.mapInfo.address += "<br/>" + this.companyAddress.address3;
		if (this.companyAddress.address4 != undefined && this.companyAddress.address4 != '') this.mapInfo.address += "<br/>" + this.companyAddress.address4;
		if (this.companyAddress.towncity != undefined && this.companyAddress.towncity != '') this.mapInfo.address += "<br/>" + this.companyAddress.towncity;
		if (this.companyAddress.postcode != undefined && this.companyAddress.potcode != '') this.mapInfo.address += "<br/>" + this.companyAddress.postcode;
		this.mapInfo.name = this.company.company.name;
	},
	_companyLoadAddress: function () {
		_self = this;
		$.each (_self.company.company.addresses, function (index, address) { 
			if (address.type.id == '1') { _self.companyAddress = address; }
		});
	},
	_companyHide: function () { $(idResult).fadeOut(300, function () { $(idResults).fadeIn(300); }); return false; },
	_loadJSON: function (url, err, suc, data) { 
		$.ajax({ 
			url : url, 
			async: false, 
			cache: false, 
			dataType: 'jsonp', 
			data: data, 
			type: 'GET', 
			error: err, 
			success: suc 
		}); 
	},
	_setStartAt: function (page) { $('#startAt').val(page); },
	_showLoading : function () { $.jnotify(loadingImage + "Loading...", 1000); },
	_showSticky : function (m) { $.jnotify(loadingImage + m, true); },
	_showMessage : function (m) { $.jnotify(loadingImage + m, 4000); },
	_showWarning : function (m) { $.jnotify(loadingImage + m, "warning", 2000); },
	_showError : function (m) {  $.jnotify(loadingImage+ m, "error", 2000); },
	_showWarningSticky : function (m) { $.jnotify(loadingImage + m, "warning", true); },
	_showError : function (m) {  $.jnotify(loadingImage + m, "error", 2000); },
	_showErrorSticky : function (m) { $.jnotify(loadingImage + m, "error", true); },
	destroy: function() { $.Widget.prototype.destroy.apply(this, arguments); }
});

})(jQuery);
