dojo.require('dijit.Dialog');
dojo.require('dojox.image');

dojo.declare
(
	'MinsterMapManager',
	null,
	{
		_show_networks_popup: null,
		
		_national_network_url: '/group/id/national.htm',
		
		constructor: function()
		{
		    // create the dijit dialog:
		    this._show_networks_popup = new dijit.Dialog( {
		        style: 'width: 300px',
		        title: 'Branches in This Region',
		        id: 'networks_popup'
		    } );
		
			// ensure we have tundra on body
			dojo.addClass( dojo.query( 'body' )[0], 'tundra' );
			
			// wire up click handler on map
			var highlight_images = [];
			dojo.forEach
			( 
				dojo.query( '#content [name=main_imagemap] area' ), 
				function( area )
				{
					highlight_images.push( this._getHighlightImage( area ) );
					dojo.connect( area, 'onmouseover', this, this.highlightNetwork );
					dojo.connect( area, 'onmouseout', this, this.unhighlightNetwork );
					dojo.connect( area, 'onclick', this, this.showNetworks );
					area.href="#"; // remove html link
				}, 
				this
			);
			
			// preload highlights to avoid loading delay
			dojox.image.preload( highlight_images );
			
			// wire up town search box
			dojo.connect( dijit.byId( 'town_select' ), 'onChange', this, this.townSelected );
			
			// and town button
			dojo.connect( dijit.byId( 'town_select_button' ), 'onClick', this, this.townSelected );
			
			// ensure postcodes have spaces
			this._initPostcodeValidation();
			
			// wire up postcode button
			dojo.connect( dijit.byId( 'postcode_textbox_button' ), 'onClick', this, this.postcodeSelected );
		},
		
		_getHighlightImage: function( area )
		{
			var region_id = dojo.attr( area, 'data-region' );
			return '/bespoke/minster/resources/branch_locator/images/map_portal_region_' + region_id + '.png';
		},
		
		highlightNetwork: function( event )
		{
			var image = this._getHighlightImage( event.target );
			dojo.attr( 'locator_map', 'src', image );
		},
		
		unhighlightNetwork: function()
		{
			// return to grey map
			dojo.attr( 'locator_map', 'src', '/bespoke/minster/resources/branch_locator/images/map_portal.png' );
		},
		
		showNetworks: function( event )
		{
			var region_id = dojo.attr( event.target, 'data-region'  );
			
			this._show_networks_popup.set( 'title', '' );
			this._show_networks_popup.set( 'content', '<p class="loading_msg">Loading branches...</p>' );
			this._show_networks_popup.show();
			
			dojo.xhrGet( {
				url: page_uri + '?xhr_source=minster_branch_locator&do=xhr_networks_popup_contents&region_id=' + region_id,
				handleAs: 'text',
				load: dojo.hitch
				(
					this,
					function( data )
					{
						var container = dojo.create( 'div', {id:'networks_contents_container', style: 'overflow: auto;'} );
						dojo.place( data, container );
						this._show_networks_popup.set( 'title', 'Branches in This Region' );
						this._show_networks_popup.set( 'content', container );
					}
				),
				error: dojo.hitch
				(
					this,
					function( error )
					{
						this._show_networks_popup.set( 'title', 'Error' );
						this._show_networks_popup.set( 'content', 'Branches cannot be retrieved at this time. Please try later or use the dropdown box on this page. <br /><br />Error:' + error );
						this._show_networks_popup.show();
					}
				)
			} );
		},
		
		// assumes page_uri variable set by PHP in global scope (with $this->UriManager->buildLinkUrl)
		townSelected: function()
		{
			if( !dijit.byId( 'town_select').isValid() )
			{
				location.href = this._national_network_url;
			}
			else
			{
				//var town_id = dijit.byId( 'town_select' ).get( 'value' );
				
				// get region
				town_store.fetchItemByIdentity( {
					identity: dijit.byId( 'town_select' ).get( 'value' ),
					onItem: function( item ) {
						location.href = item['url'];
					}, 
					onError: function( error ) {
						console.log( 'Failed to find region. Error: ' + error );
					}
				} );
			}
		},
		
		_initPostcodeValidation: function()
		{
			//var regex = /^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$/i;
			/*var regex_1 = /^(GIR|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])$/i;
			dijit.byId( 'postcode_textbox_1' ).validator = function( value, constraints ) 
			{
				return regex_1.test( value );
			};
			
			var regex_2 = /^[0-9][ABD-HJLNP-UW-Z]$/i;
			dijit.byId( 'postcode_textbox_2' ).validator = function( value, constraints ) 
			{
				return regex_2.test( value );
			};*/
		},
		
		postcodeSelected: function()
		{
			var postcode_1 = dijit.byId( 'postcode_textbox_1' ).get( 'value' ),
			postcode_2 = dijit.byId( 'postcode_textbox_2' ).get( 'value' ),
			regex_1 = /^([A-Z]{1,2}[0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z]{2}[0-9][A-Z])$/i,
			regex_2 = /^[0-9][A-Z]{2}$/i;
			
			if( postcode_1 == '' )
			{
				this._show_networks_popup.set( 'title', 'Postcode Empty' );
				this._show_networks_popup.set( 'content', '<p>The first part of the postcode is empty.</p><p>Please enter your postcode and try again.</p>' );
				this._show_networks_popup.show();
			}
			else if( postcode_2 == '' )
			{
				this._show_networks_popup.set( 'title', 'Postcode Empty' );
				this._show_networks_popup.set( 'content', '<p>The second part of the postcode is empty.</p><p>Please enter your postcode and try again.</p>' );
				this._show_networks_popup.show();
			}
			else if( !regex_1.test( postcode_1 ) )
			{
				this._show_networks_popup.set( 'title', 'Postcode Invalid' );
				this._show_networks_popup.set( 'content', '<p>The first part of the postcode is invalid.</p><p><b>' + postcode_1 + '</b></p><p>Please check and try again.</p>' );
				this._show_networks_popup.show();
			}
			else if( !regex_2.test( postcode_2 ) )
			{
				this._show_networks_popup.set( 'title', 'Postcode Invalid' );
				this._show_networks_popup.set( 'content', '<p>The second part of the postcode is invalid.</p><p><b>' + postcode_2 + '</b></p><p>Please check and try again.</p>' );
				this._show_networks_popup.show();
			}
			else
			{
				dojo.xhrGet( {
					url: page_uri + '?xhr_source=minster_branch_locator&do=xhr_check_postcode',
					content: { postcode: postcode_1 },
					handleAs: 'json',
					load: dojo.hitch
					(
						this,
						function( response )
						{
							if( response.success !== undefined && response.success == true )
							{
								window.location = response.url;
							}
							else if( response.success !== undefined && response.success == false )
							{
								/*this._show_networks_popup.set( 'title', 'Sorry' );
								this._show_networks_popup.set( 'content', response.msg + '<br><br>The postcode you entered was not recognised. Please check and try again.<br><br>Alternatively, please use the town finder or clickable map.' );
								this._show_networks_popup.show();*/
								location.href = this._national_network_url;
							}
							else
							{
								throw( 'Invalid XHR response.' );
							}
						}
					),
					error: dojo.hitch
					(
						this,
						function( error )
						{
							this._show_networks_popup.set( 'title', 'Error' );
							this._show_networks_popup.set( 'content', 'Postcodes check failed. Please try later or use the town finder or clickable map. <br /><br />Error: ' + error );
							this._show_networks_popup.show();
						}
					)
				} );
			}
		}
	}
);

dojo.ready( function() {
	window.oMinsterMapManager = new MinsterMapManager();
	console.log( 'oMinsterMapManager', oMinsterMapManager );
} );

