/**
  *
  * Client Side Handler for directory handler
  * 
  * Written by R.E.Shine 5.12.2010. Version 1.0
  *
  * Modifications :
  * RES 10.12.2010	Version 2.0 
  *					Re-Written the code so it correctly binds, and uses
  *					prototypes this statements correctly.  
  * RES 12.12.2010	Version 3.0 
  *					Optimised Code for Compression
  * RES 29.08.2011	Version 4.0
  *					Changed to work with Google Maps v3 as SSL is supported via this version.
  *					Had to write my own version of the Map Tab Dialog boxes as google had 
  *					withdrawn this feature in version 3.
  *
  **/
  
var hdsbldir = Class.create({

	_connectURL: '',
	_sslConnector: '',
	_isEncrypted: null,
	_hintRequest: null,
	_assl: {},
	_tabs: {},
	_isShowingDialog: null,
	_timeout: 0,
	_idTimer: null,
	
	_clubmap: null,
	_clubdirMap: null,
	
	
	initialize: function(sConnectURL, sSSLConnector, bIsEncrypted) {
      
		this._connectURL = sConnectURL;
		this._sslConnector = sSSLConnector;
		this._isEncrypted = bIsEncrypted;
		this._isShowingDialog = false;
		
		// Static Property
		hdsbldir._tabbedMapInfoWindow = null;

		//hdsbldir._connectURL = connectURL;
		//hdsbldir._sslConnector = sslConnector;
		//hdsbldir._isEncrypted = isEncrypted;
		//hdsbldir._hintRequest = null;
		//hdsbldir._isShowingDialog = false;
      
		var viewportHeight = document.viewport.getHeight();
		$('id_container').setStyle({height: viewportHeight+'px'});   

		if (this._isEncrypted == true) { 
			this._isShowingDialog = true;
			Dialog.info('Please wait...',{className:"hdsblglass",parent:$('id_container'), showProgress: true});
			// aSSL.connect(sslConnector, this.onSSLComplete.bind(this));
			this._assl = new aSSL(this._sslConnector, this.onSSLComplete.bind(this));
		} else {
			this.sendRequest("init");
		}

		this._tabs = new tabNavigation('tablist','tabclub');
		// hdsbldir._tabbedMapInfoWindow = null;
      
		// Event Handlers
		Event.observe($('frmlogonsubmit'),'click',this.login.bindAsEventListener(this),false);

		// Prepare Players' Directory Tab
		this._hintRequest = null;
		$('idspan_surnameinput').innerHTML = '<input id="id_searchSurname" name="searchSurname" type="text" size="30" />';
		$('id_surnamehints').hide();
		Event.observe($('id_searchSurname'), 'keyup', this.playersearch.bindAsEventListener(this), false);
		Event.observe($('clubmap_canvas'),'click', this.keepalive.bindAsEventListener(this),false);
		Event.observe($('mapdircanvas'),'click', this.keepalive.bindAsEventListener(this),false);
		Event.observe($('tabclub'), 'click', this.ontab_clubdir_click.bindAsEventListener(this),false);
		Event.observe($('tabclubmap'), 'click', this.ontab_clubmap_click.bindAsEventListener(this),false);
		Event.observe($('id_logoff'), 'click', this.logout.bindAsEventListener(this),false);
      
	},
   
	setTimeoutExpire: function(seconds) { 
		// hdsbldir._timeout = seconds;
		this._timeout = seconds;
	},
   
	onSSLComplete: function (response) {
   
		if (response.statusText == 'OK') {
			this.sendRequest("init");
		} else {
			alert("Failed to encrypt connection");
		}
	},
   
	startTimer: function( id_container ) {
		(!this._timeout ? this._countdownSecs = 120 : this._countdownSecs = this._timeout);
		this._idTimer = id_container;
		if (this._timer)
			clearInterval(this._timer);
		// hdsbldir._timer = setInterval("hdsbldir.prototype.displayTimeout('"+hdsbldir._idTimer+"')",1000);
		this._timer = setInterval(this.displayTimeout.bind(this),1000);
	},

	displayTimeout: function() {
		this._countdownSecs = this._countdownSecs - 1;
		$(this._idTimer).innerHTML = "Session will automatically logout in "+this._countdownSecs+" seconds.";
		if (this._countdownSecs == 0 ) 
			this.showLogon("Previous session has expired.");
	},
   
	stopTimer: function () {
		if (this._timer) { 
			clearInterval(this._timer);
			$(this._idTimer).innerHTML = "&nbsp;";
		}
	},

	showLogon: function( statusmessage ) {
		$('id_divStatusBar').hide();
		$('maincontent').hide();
		$('idclubname').innerHTML = '';
		$('idclubaddress').innerHTML = '';
		$('idclubparams').innerHTML = '';
		$('idclubrep').innerHTML = '';
		$('idteamdetails').innerHTML = '';
		$('idclubnotes').innerHTML = '';
		$('id_surnamehints').innerHTML = '';
/*
      if ( hdsbldir._clubmap  )
         GEvent.clearListeners(hdsbldir._clubmap);
      if ( hdsbldir._clubdirMap)
         GEvent.clearListeners(hdsbldir._clubdirMap);
*/
		$('idclubdetails').hide();
      // $('clubmap_canvas').innerHTML = 'Retrieving club maps. Please wait... &nbsp;<img src="images/greenbacked_ajax-loader.gif" alt="loading" />';
		$('frm_login').reset();
		$('login').show();
		$('frm_login').enable();
		$('frmsurname').activate();
		$('loginmessage').innerHTML = ( statusmessage ? statusmessage : '&nbsp;');
		$('loginmessage').show();
		this.stopTimer();
      // Event.observe($('frmlogonsubmit'),'click',this.login.bindAsEventListener(this),false);
	},

/*   
   decryptJSONParser: function( responseText ) {
     decryptedJSON = aSSL.decrypt(responseText);
     responseJSON = decryptedJSON.evalJSON(true);
      return responseJSON;      
   },
   
 */  


	sendRequest: function(params) {
      
		new Ajax.Request(this._connectURL, {
			method: 'post',
			parameters: (this._isEncrypted ? 'data='+this._assl.encrypt(params) : params),
			on500: function(transport) {
				alert("Error receiving a 500 Server error.");
			},
			onSuccess: this.controlBlock.bind(this),
            onFailure: function(transport) {
				alert("Failure : " + transport.responseJSON);
			}
		});
	},

	login: function(ev) {
		Event.stop(ev);
      
		var params = 'action=login&surname='+$F('frmsurname')+'&number='+$F('frmnumber');
		this.sendRequest(params);
	},
   
	logout: function(ev) {
		Event.stop(ev);
		var params = 'action=logout';
		this.sendRequest(params);
	},

	getClublist: function() {
		this.sendRequest('action=getclublist');
	},


	controlBlock: function( transport ) {
		( (this._isEncrypted == true) ? transport.responseJSON = 
								this._assl.decrypt(transport.responseText).evalJSON(true)
								: '');
		var json = transport.responseJSON;		
		
		switch (json.hdsbldirectory.status ) {
			case 'off':
				this.showLogon('');
				break;
			case 'invalid':
				this.showLogon('Invalid name or phone number entered');
				break;
			case 'timeout':
				this.showLogon('Previous session timed out.');
				break;
			default:
				$('login').hide();
				this.setTimeoutExpire(json.hdsbldirectory.timeout);
				this.startTimer('sessionstatus');
				$('id_signedname').innerHTML = "Signed in as : "+json.hdsbldirectory.username;
				$('id_divStatusBar').show();
				$('maincontent').show();
				// this.setTimeoutExpire(json.hdsbldirectory.timeout);
            
				// getClubList DropDown box
				if (typeof(json.hdsbldirectory.data.clublist) !== 'undefined') {
               
					if ( Object.isElement($('idselect_Club')) )
						$('idselect_Club').stopObserving('change',this.selectClubOnChange.bind(this));
				var clublist = $A(json.hdsbldirectory.data.clublist);
				var htmlClubList = '<select id="idselect_Club" name="combo_clubmenu"><option value="Select Club">Select Club</option>';
               
				clublist.each(function(item) {
					htmlClubList = htmlClubList + '<option value="' + item.value + '">' + item.name + '</option>';
				});
				htmlClubList = htmlClubList + '</select>';
				$('idspan_SelectClub').innerHTML = htmlClubList;
				$('id_img_selectclub').hide();
				$('idselect_Club').observe('change',this.selectClubOnChange.bind(this));
			}
            
			// club details
			if (typeof(json.hdsbldirectory.data.clubdirectory) !== 'undefined') {
				if( this._tabs.getCurrentTab() !== 'tabclub' ) { this._tabs.highlightTab(tabclub); }
				$('idclubname').innerHTML = json.hdsbldirectory.data.clubdirectory.name;
				$('idclubaddress').innerHTML = 	'<table id="idtbl_clubaddr" style="width:100%;"><tbody>'+
												'<tr class="playerrowalt"><td>'+json.hdsbldirectory.data.clubdirectory.address+'</td></tr>'+
												'<tr class="playerrow"><td>'+json.hdsbldirectory.data.clubdirectory.telephone+'</td></tr></tbody></table>';
				$('idclubparams').innerHTML = 	'<table id="idtbl_clubparams" style="width:100%;"><tbody>'+
												'<tr class="playerrowalt"><td>Match Tables :'+json.hdsbldirectory.data.clubdirectory.tables+'</td></tr>'+
												'<tr class="playerrow"><td>Minimum Age Limit :'+
												( (json.hdsbldirectory.data.clubdirectory.minage == '0') ? '&nbsp;' : json.hdsbldirectory.data.clubdirectory.minage)+
												'</td></tr></tbody></table>';
				$('idclubrep').innerHTML = 	'<table id="idtbl_clubrep" width="100%"><tbody>'+
											'<tr class="playerrowalt"><td>'+json.hdsbldirectory.data.clubdirectory.clubrep+'</td></tr>'+
											'<tr class="playerrow"><td>'+json.hdsbldirectory.data.clubdirectory.clubrepaddr+'</td></tr>'+
											'<tr class="playerrowalt"><td>'+json.hdsbldirectory.data.clubdirectory.clubreptel+'</td></tr></tbody></table>';
				var clubteams = $A(json.hdsbldirectory.data.clubdirectory.teams);   
				var clubteamshtml = '<table width="100%"><tbody>';
				clubteamshtml = clubteamshtml + '<tr><th id="idth_team">Team</th>' +
								'<th id="idth_captain">Team Captain</th><th id="idth_captel">Telephone Number</th></tr>';
				var i=0;
				clubteams.each(function(item) {
					clubteamshtml = clubteamshtml + '<tr class="'+ ( ((i % 2) != 0) ? "playerrow" : "playerrowalt")+'">'+
									'<td headers="idth_team">'+item.name+'</td><td headers="idth_captain">'+item.captain+
									'</td><td headers="idth_captel">'+item.telephone+"</td></tr>";
					i = i + 1;
				});
				clubteamshtml = clubteamshtml + "</tbody></table>";
				$('idteamdetails').innerHTML = clubteamshtml;
			   
				var clubnotes = $A(json.hdsbldirectory.data.clubdirectory.notes);
				if (clubnotes.size() > 0) {
					$('idclubnotesheader').innerHTML = "Club Notes";
				  
					var clubnoteshtml = '<table width="100%"><tbody>';
					j = 0; 
					clubnotes.each(function(item) {
						clubnoteshtml = clubnoteshtml + '<tr class="'+( ((j % 2) != 0) ? "playerrow" : "playerrowalt")+'">'+
										"<td>"+item.note+"</td></tr>";
						j = j + 1;
					});
					clubnoteshtml = clubnoteshtml + "</table>";
					$('idclubnotes').innerHTML = clubnoteshtml;
				} else {
					$('idclubnotesheader').innerHTML = "&nbsp;";
					$('idclubnotes').innerHTML = "&nbsp;";
				}
				  
				$('idclubdetails').show();
				
				this._clubdirMap = this.gmapDraw("mapdircanvas",
							json.hdsbldirectory.data.clubdirectory.latitude,
							json.hdsbldirectory.data.clubdirectory.longitude,
							json.hdsbldirectory.data.clubdirectory.zoom);

				var clubMarker = this.gmapCreateMarker( this._clubdirMap,
														json.hdsbldirectory.data.clubdirectory.latitude,
														json.hdsbldirectory.data.clubdirectory.longitude,
														json.hdsbldirectory.data.clubdirectory.name,
														'<div style="font-size:16px;width:270px">'+
														json.hdsbldirectory.data.clubdirectory.name+
														'</div><br><div style="font-size: 12px">'+
														json.hdsbldirectory.data.clubdirectory.address+
														'</div>');
				clubMarker.setMap(this._clubdirMap);

			}
			
			// Player Search System
			if (typeof(json.hdsbldirectory.data.playersearchhint) !== 'undefined') {

				// Following handles if the user refreshes or leaves pages will set it to the correct tab on return
				if( this._tabs.getCurrentTab() !== 'tabplayers' ) { this._tabs.highlightTab('tabplayers'); }

				var playerlists = $A(json.hdsbldirectory.data.playersearchhint.hints);
			   
			   
				if (playerlists.size() > 0 ) {
					var surnametablehtml =	'<table id="idtbl_playerdir"><thead><tr>'+
											'<th id="idth_player" style="width:220px;padding:0 4px 0 4px;">Player</th>'+
											'<th id="idth_tel" style="padding:0 4px 0 4px;">Telephone Number</th>'+
											'<th id="idth_email" style="width:220px;padding:0 4px 0 4px;">Email Address<span id="id_email_hprompt" style="color:red;display:none;">*</span></th>'+
											'</tr></thead><tbody>';
					var i = 0;
					var showEmailPrompt = false;
					playerlists.each( function(item) {
						surnametablehtml = 	surnametablehtml + "<tr class=\""+ ( ((i % 2) != 0) ? "playerrow" : "playerrowalt")+"\">"+
											"<td headers=\"idth_player\" class=\"playerdata\">"+item.name+"</td>"+
											"<td headers=\"idth_tel\" class=\"playerdata\">"+item.tel+"</td>"+
											"<td headers=\"idth_email\" class=\"playerdata\">"+item.email+"</td></tr>";
						if (!item.email) { showEmailPrompt = true; }
						i = i + 1;
					});
					surnametablehtml = 	surnametablehtml + "</tbody></table><div class=\"spacerline\" style=\"margin-top:16px;\"></div><span  id=\"id_email_txtprompt\" style=\"float:left;display:none;\">"+
										"<span style=\"color:red;\">*</span>If you wish to have your email address added please inform the Webmaster using the Contact Us page</span>";
					$('id_surnamehints').innerHTML = surnametablehtml;
					$('id_surnamehints').show();
					if ( showEmailPrompt == true ) {
						$('id_email_hprompt').show();
						$('id_email_txtprompt').show();
					}

				} else {
					$('id_surnamehints').hide();
				}
				
				this._hintRequest = null;
				$('id_img_playersearch').hide();			
			
			}
			
			// HDSBL ClubMap
			if (typeof(json.hdsbldirectory.data.clubmap) !== 'undefined' ) {
				// from data returned set up a marker for each club.
				// capture longitude and latitude and work out the mean figure
			   
				// Following handles if the user refreshes or leaves pages will set it to the correct tab on return
				if( this._tabs.getCurrentTab() !== 'tabclubmap' ) { this._tabs.highlightTab('tabclubmap'); }

				var clubmapjson = $A(json.hdsbldirectory.data.clubmap.venues);
				if (clubmapjson.size() > 0) {
					// therebe data
					this._clubmap = this.gmapDraw("clubmap_canvas",
									  json.hdsbldirectory.data.clubmap.centerLat,
									  json.hdsbldirectory.data.clubmap.centerLong, 11);
				  
					// hdsbldir._clubmap.addControl(new GLargeMapControl());
					// hdsbldir._clubmap.addControl(new GMapTypeControl());
				  
					// var clubPointArr = new Array(clubmapjson.size());
					// var clubMarkerArr = mew Array(clubmapjson.size());
					// var i = 0;
					var point = '';
					var marker = '';
					var htmltab1 = '';
					var htmltab2 = '';
					var clubnames ='';
					var iMarkerNumber = 0;
				  
					clubmapjson.each( function(venueitem) {
						iMarkerNumber++;
						var clubarray = $A(venueitem.venueattribs); // $A(json_response.hdsbldirectory.data.clubmap.venues);   
					 
						clubnames = '';
						htmltab2 = '';
						clubarray.each( function(clubitem) {
							clubnames = clubnames + clubitem.name + ' <br>';
							htmltab2 = 	htmltab2 + '<div style="border-bottom:1px solid;margin-bottom:6px;">'+clubitem.name  + '</div><div style="font-size:12px;">'+clubitem.clubrep+'<br>'+
										clubitem.clubrepaddr+'<br>'+
										clubitem.clubreptel+'<br>'+
										clubitem.clubrepemail+'<br></div>';
						
					 
					 
						});
						htmltab1 = '<div style="border-bottom:1px solid;margin-bottom:10px;width:280px;">'+clubnames+'</div><div style="font-size:12px;">'+venueitem.address+"</div><br><div>"+venueitem.telephone+"<br></div>";

						this.gmapCreateTabbedMarker(this._clubmap, 
													venueitem.latitude,
													venueitem.longitude,
													'Marker'+iMarkerNumber,
													clubnames.stripTags(),
													htmltab1, htmltab2, "Details", "Club Rep.");
					},this);
				}
			}
		}

		if (this._isShowingDialog == true ) {
			setTimeout("Dialog.closeInfo();",1250);
			this._isShowingDialog = false;
		}
			
		var viewportheight = document.viewport.getHeight();
		((  $('id_container').getHeight() < viewportheight ) ? 
			$('id_container').setStyle({height: viewportheight+'px'}) : 
			$('id_container').setStyle({height: 'auto'}) 
		);
	},

	selectClubOnChange: function(event) {
   
		if ( $F('idselect_Club') == "Select Club" ) { 
			alert("Please select a club from the drop down list.");
			return false;
		}
		var params = 'action=displayclubdetails&combo_club='+$F('idselect_Club');
		this.sendRequest(params);
	},

	playersearch: function(ev) {
      
		ev = ((ev) ? ev : window.event);
		var input = (( ev.srcElement) ? ev.srcElement : ev.target);
		var params = '';
      
		/* Is the client still already trying to get hints? */
		if (this._hintRequest) {
			this._hintRequest.onSuccess = Prototype.emptyFunction;
			this._hintRequest.onFailure = Prototype.emptyFunction;
		}
      
		if (input.value) {
			params = 'action=playersearchhint&searchString='+input.value;
			$('id_img_playersearch').show();
			this._hintRequest = new Ajax.Request(this._connectURL, {
				method: 'post',
				parameters: (this._isEncrypted ? 'data='+this._assl.encrypt(params) : params),
				onSuccess: this.controlBlock.bind(this),
				onFailure: function(transport) {
					this._hintRequest = null;
				}
			});
		} else {
			$('id_surnamehints').hide();
			$('id_img_playersearch').hide();

		}
      
		return (true);
  
	},

   ontab_clubmap_click: function(ev) {
   
		// send ajax call to retrieve all club information and points
		if ( this._clubmap == null ) {
			var params = 'action=clubmap';
			this.sendRequest(params);
		} else {
			// hdsbldir._clubmap.checkResize();
		}
	},
   
	ontab_clubdir_click: function(ev) {
   
		$('id_img_selectclub').show();
		var params = 'action=getclublist';
		this.sendRequest(params);
	},
   
	keepalive: function(ev) {
		var params = 'action=keepalive';
		this.startTimer('sessionstatus');
		this.sendRequest(params);
	},
   
	// Google Map Code
   
   
	gmapDraw: function(idmap, centerLatitude, centerLongitude, sZoom) {
		var latlng = new google.maps.LatLng(centerLatitude,centerLongitude);
		var mapOptions = { 	zoom: parseInt(sZoom),
							center: latlng,
							MapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		var gmapHandle = new google.maps.Map(document.getElementById(idmap), mapOptions);
		return gmapHandle;
	},
   
	gmapDrawV2: function(idmap, centerLatitude, centerLongitude, zoom) {
		if (GBrowserIsCompatible()) {
			var gmapHandle = new GMap2(document.getElementById(idmap));
         
			gmapHandle.setCenter(new GLatLng(centerLatitude, centerLongitude), parseInt(zoom));
			// gmapHandle.setUIToDefault();
			gmapHandle.clearOverlays();
			return gmapHandle;
         
		} else {
			// Not browser compatible
			$(idmap).innerHTML = "<center><b>Browser is not compatible with googlemaps</b></center>";
			return;
		}
	},
   
	gmapCreateMarker: function(oMapHandle, centerLatitude, centerLongitude, sTitle, sHTML) {
			var latlng = new google.maps.LatLng(centerLatitude,centerLongitude);
			var marker = new google.maps.Marker({
				position: latlng,
				animation: google.maps.Animation.DROP,
				title: sTitle
			});
			var infowindow = new google.maps.InfoWindow({
				content: sHTML
			});
		
			google.maps.event.addListener(marker,'click', function() {
				infowindow.open(oMapHandle,marker);
			});
			return marker;
	},
 
	gmapCreateTabbedMarker: function(oMapHandle, fLat, fLong, sMarkerID, sClubName, sHTML1, sHTML2, sLabel1, sLabel2) {
	
		// Created my own Tabbed Marker because Google has pulled
		// support for this in V3
		var glatlng = new google.maps.LatLng(fLat, fLong);
		var uID = sMarkerID.camelize();
		var sContent = '<div id="' + uID + 
					   'Tabmenu"><ul id="' + uID + 
					   'tablist" class="clubtablist"><li><a id="' + uID + 'tabclub" href="#" class="selected" tabindex="1">' +
					   sLabel1 + '</a></li>' +
					   '<li><a id="' + uID + 'tabnotes" href="#">' + sLabel2 + '</a></li><ul></div>' +
					   '<div id="' + uID + 'tabcontents" class="clubtabcontents">' +
					   '<div class="top-left"></div><div class="top-right"></div>' +
					   '<div class="insidetab">' +
					   '<div id="' + uID + 'tabclubContent">' + sHTML1 + '</div>' +
					   '<div id="' + uID + 'tabnotesContent" style="display:none;">' + sHTML2 + '</div></div>' +
					   '</div><div class="bottom-left"></div><div class="bottom-right"></div>';
		var marker = new google.maps.Marker({
			position: glatlng,
			animation: google.maps.Animation.DROP,
			title: sClubName
		});
		var tabbedInfoWindow = new google.maps.InfoWindow({
			content: sContent
		});
		
		google.maps.event.addListener(marker, 'click', function() {
			if (hdsbldir._tabbedMapInfoWindow) { 
				hdsbldir._tabbedMapInfoWindow.close(); 
			
			}
			
			google.maps.event.addListener(tabbedInfoWindow,'domready', function() {
				var tabs = new tabNavigation(uID + 'tablist', uID + 'tabclub');
			});
			
			tabbedInfoWindow.open(oMapHandle, marker);
			
			hdsbldir._tabbedMapInfoWindow = tabbedInfoWindow;
		});
		
		marker.setMap(oMapHandle);
		
	
	},
   
	gmapCreateMarkerV2: function(point, html) {
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindow(html);
			hdsbldir.prototype.keepalive(marker);         
		});
		return marker;
	},
   
	gmapCreateTabbedMarkerV2: function(point, html1, html2, label1, label2) {
   
		var marker = new GMarker(point);
      
		GEvent.addListener(marker, "click", function() {
         
			marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html1), new GInfoWindowTab(label2,html2)]);
			hdsbldir.prototype.keepalive(marker);            
      
		});
     
		return marker;
	}


});

try {
   Event.observe(window,"load",function() {
      
      
      hdsbl = new hdsbldir('cgi-bin/hdsbl_directory.php','cgi-bin/conn.php', false); 
      hdsbl.setTimeoutExpire(180);
      
      Event.observe(window,"unload", function() {
         // GUnload();
      });

      
   }, true);


} catch(ex) {}


