var search_results_div;
var search_results_container;
var location_details;
var tabbed_details_popup;
var add_place;

function SearchService()
{
	this.request = CreateAjaxRequest();

	this.Search = function()
	{
		FadeOut();

		var inputs = document.getElementsByTagName( "input" );

		var data = "?";

		for( var i = 0; i < inputs.length; i++ )
		{
			if( inputs[ i ].getAttribute( "type" ) == "checkbox" )
			{
				if( inputs[ i ].checked )
				{
					data += inputs[ i ].getAttribute( "id" ) + "=" + encodeURIComponent( inputs[ i ].value ) + "&";
				}
			}
			else if( inputs[ i ].getAttribute( "type" ) == "radio" )
			{
				if( inputs[ i ].checked )
				{
					data += inputs[ i ].name + "=" + encodeURIComponent( inputs[ i ].value ) + "&";
				}
			}
			else
			{
				data += inputs[ i ].getAttribute( "id" ) + "=" + encodeURIComponent( inputs[ i ].value ) + "&";
			}
		}

//		document.body.appendChild( document.createTextNode( "/Ajax/Search/" + data ) );

		this.request.open( "GET", "/Ajax/Search/" + data, true );
		this.request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
		this.request.send( null );
		this.request.onreadystatechange = CreateCallback( this );
	}

	this.MiniSearch = function()
	{
		var data = "?all_categories=1&search[content_type]=all&search[text]=" + encodeURIComponent( document.getElementById( 'add_place_place_name' ).value + ' ' + document.getElementById( 'add_place_location' ).value );

//		document.body.appendChild( document.createElement( "textarea" ).appendChild( document.createTextNode( "/Ajax/Search/" + data ) ) );

		this.request.open( "GET", "/Ajax/Search/" + data, true );
		this.request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
		this.request.send( null );
		this.request.onreadystatechange = CreateCallback( this );
	}

	this.AddPlace = function( data )
	{
//		alert( data );
		this.request.open( "GET", "/Ajax/AddPlace/" + data, true );
		this.request.send( null );
	}

	this.SetVars = function( data )
	{
		this.request.open( "GET", "/Ajax/SetVars/" + data, false );
		this.request.send( null );
	}

	this.GeoCode = function( id, latitude, longitude )
	{
		this.request.open( "GET", "/Ajax/GeoCode/" + id + "/" + latitude + "/" + longitude, true );
		this.request.send( null );
	}

	this.GetPage = function( url )
	{
		this.request.open( "GET", url, false );
		this.request.send( null );

		return this.request.responseText;
	}

	this.ProcessResults = function( obj )
	{
		var done_geocode = false;

		if( this.request.readyState  == 4 )
		{
//			alert( this.request.responseText );

			ClearSearchResults( search_results_div );

			results = eval( '(' + this.request.responseText + ')' );

			for( var i = 0; i < results.length; i++ )
			{
				AddResult( results[ i ], search_results_div, i + 1 );
			}

			document.getElementById( 'search_result_count' ).innerHTML = "" + i;

			var center = new google.maps.LatLng( 54.5, -7.0 );
			map.setCenter( center, 5 );

			HideAddPlace();
			HideDetails();

			if( !this.hide_results )
			{
				ShowSearchResults();
			}

//				ShowSearchResults();
			CancelFadeOut();
		}
	}
}

function FadeOut()
{
	document.getElementById( 'fade-div' ).style.display = "block";
}

function CancelFadeOut()
{
	document.getElementById( 'fade-div' ).style.display = "none";
}

function GeoCode( id, latlng )
{
	if( latlng != null )
	{
		var service = new SearchService();
		service.GeoCode( id, latlng.lat(), latlng.lng() );
	}
}

function Toggle( prefix, value )
{
	var nodes = document.getElementsByName( prefix );

	var current_state = null;

	if( value != null )
	{
		current_state = !value;
	}

	for( var i = 0; i < nodes.length; i++ )
	{
		if( current_state == null )
		{
			current_state = nodes[ i ].checked;
		}

		nodes[ i ].checked = !current_state;
	}
}

function ShowSearchResults()
{
	search_results_container.style.display = 'block';

	if( zero_results )
	{
		document.getElementById( 'search_results_alternative' ).style.display = 'block';
		document.getElementById( 'search_results_main' ).style.display = 'none';
	}
	else
	{
		document.getElementById( 'search_results_main' ).style.display = 'block';
		document.getElementById( 'search_results_alternative' ).style.display = 'none';
	}
}

function HideSearchResults()
{
	search_results_container.style.display = 'none';
}

function ShowDetails()
{
	location_details.style.display = 'block';
}

function HideDetails()
{
	location_details.style.display = 'none';
}

function ClearSearchResults( div )
{
	div.innerHTML = "";
	map.clearOverlays();
}

function AddResult( result, div, number )
{
	AddResultToList( result, div, number );
	AddResultToMap( result, number );
}

function AddResultToMap( result )
{
//			var LocationIcon = new GIcon( G_DEFAULT_ICON );
//			LocationIcon.iconSize = new GSize( 20, 20 );
//			LocationIcon.image = "/resources/images/icons/food_shopping_icon.jpg";
//			LocationOptions = { icon:LocationIcon };

	if( result.longitude == null || result.latitude == null )
	{

		var geocoder = new google.maps.ClientGeocoder();
		geocoder.setBaseCountryCode( 'uk' );
		geocoder.location_id = result.id;

		address = "";

		if( result.address1 )
		{
			address += result.address1;
		}

//		if( result.address2 )
//		{
//			if( address != "" )
//			{
//				address += ", ";
//			}
//
//			address += result.address2;
//		}
//
//		if( result.county )
//		{
//			if( address != "" )
//			{
//				address += ", ";
//			}
//
//			address += result.county;
//		}
//
//		if( result.city )
//		{
//			if( address != "" )
//			{
//				address += ", ";
//			}
//
//			address += result.city;
//		}
//
		if( result.postcode )
		{
			if( address != "" )
			{
				address += ", ";
			}

			address += result.postcode;
		}

		geocoder.getLatLng( address, function( latlng ){ GeoCode( result.id, latlng ); } );
	}
	else
	{
		var point = new GLatLng( result.latitude, result.longitude );

//		marker = new GMarker( point, LocationOptions );
		marker = new GMarker( point );

		marker.id = result.id;
		marker.type = "Foods";
		marker.result = result;
		result.marker = marker;
		GEvent.addListener( marker, "click", ShowDetailsPopup );
		
		map.addOverlay( marker );
	}
}

var ids = new Array();
var current_index = 0;

function ChangeSelectedItem( direction )
{
	var new_index = current_index + direction;

	if( new_index >= ids.length )
	{
		new_index = 0;
	}
	else if( new_index < 0 )
	{
		new_index = ids.length - 1;
	}

	Choose( new_index );
}

function Choose( index )
{
	service = new SearchService();

	current_index = index;

	document.getElementById( "group_details_body" ).innerHTML = service.GetPage( "/Ajax/SmallDetails/" + ids[ current_index ] );
	document.getElementById( "marker-place-count" ).innerHTML = current_index + 1;
}


function ShowDetailsPopup()
{
	ShowDetailsPopup2( this, this.result );
}

var open_marker;

function ShowDetailsPopup2( marker, result )
{
	service = new SearchService();

	if( marker.result.cluster_items )
	{
		var sw = new GLatLngBounds( new google.maps.LatLng( parseFloat( marker.result.bounds.top ), parseFloat( marker.result.bounds.left ) ), new google.maps.LatLng( parseFloat( marker.result.bounds.bottom ), parseFloat( marker.result.bounds.right ) ) );
		zoom_level = map.getBoundsZoomLevel( sw );
		map.setCenter( new google.maps.LatLng( ( parseFloat( marker.result.bounds.top ) + parseFloat( marker.result.bounds.bottom ) ) / 2 , ( parseFloat( marker.result.bounds.left ) + parseFloat( marker.result.bounds.right ) ) / 2 ), zoom_level );
	}
	else
	{
		marker.openInfoWindowHtml( service.GetPage( "/Ajax/SmallDetails/" + result.id ), { maxWidth: 320 } );

		open_marker = marker;

		current_place_shown = result.id;
	}

	HideSearchResults();
}

function CloseCurrentMarker()
{
	if( open_marker )
	{
		open_marker.closeInfoWindow();
		open_marker = null;			
	}
}

function AddResultToList( result, div, number )
{
	var result_node = document.createElement( 'div' );
	result_node.className = "search-result";
	var result_name = document.createElement( 'div' );
	var result_name_link = document.createElement( 'a' );

	result_name_link.setAttribute( "href", "#" );
	result_name_link.setAttribute( "onclick", "return false;" );

	result_name_link.appendChild( document.createTextNode( number + ". " + result.name ) );
	result_name_link.style.fontSize = "10pt";

	result_name.appendChild( result_name_link );

	result_node.appendChild( result_name );

	var address = document.createElement( 'div' );
	address.style.margin = "5px 5px 5px 20px";
	address.style.fontSize = "9pt";

	if( result.address1 )
	{
		address.appendChild( document.createTextNode( result.address1 ) );
		address.appendChild( document.createElement( "br" ) );
	}

	if( result.address2 )
	{
		address.appendChild( document.createTextNode( result.address2 ) );
		address.appendChild( document.createElement( "br" ) );
	}

	if( result.city )
	{
		address.appendChild( document.createTextNode( result.city ) );
	}

	if( result.county )
	{
		address.appendChild( document.createTextNode( result.county ) );
		address.appendChild( document.createElement( "br" ) );
	}

	result_node.appendChild( address );

	var review_link = document.createElement( "a" );
	review_link.setAttribute( "href", "#" );
	review_link.setAttribute( "onclick", "return false;" );
	review_link.style.paddingLeft = "25px";
	review_link.style.backgroundImage = "url(/resources/images/link-arrow.png)";
	review_link.style.backgroundRepeat = "no-repeat";
	review_link.style.backgroundPosition = "12px 2px";
	review_link.appendChild( document.createTextNode( "Tell us why you love it" ) );

	result_node.appendChild( review_link );

	result_node.className = "search_result";

	review_link.result = result;
	review_link.tab = 'upload_review_tab';
	GEvent.addDomListener( review_link, "click", ShowTabbedDetailsPopup );
	
	result_name_link.result = result;
	GEvent.addDomListener( result_name_link, "click", ShowDetailsPopup );

	div.appendChild( result_node );
}

function CreateCallback( object )
{
	return function() { object.ProcessResults(); };
}


function CreateAjaxRequest()
{
	// create IE, firefox, et al compatible HTTP Request object
	try
	{
		return new XMLHttpRequest();
	}
	catch( e )
	{
		try
		{
			return new ActiveXObject( "Msxml2.XMLHTTP" );
		}
		catch( e )
		{
			try
			{
				return new ActiveXObject( "Microsoft.XMLHTTP" );
			}
			catch( e )
			{
				return null;
			}
		}
	}
}

function ShowTabbedDetailsPopup()
{
	result = this.result;
	tab = this.tab;

	return ShowTabbedDetailsPopup2( result, tab );
}

function ShowTabbedDetailsPopup2( result, tab )
{
	HideSearchResults();
	HideDetails();
	HideAddPlace();
	CloseCurrentMarker();

	tabbed_details_popup.style.display = 'block';

	PageView( "Detailed View", "event31" );

	service = new SearchService();

	tabbed_details_popup.innerHTML = service.GetPage( "/Ajax/TabbedDetailsPopup/" + result.id );
	tabbed_details_popup.result = result;
	SelectTab( tab );

	HideAnnoyingThings();

	FadeOut();

	current_place_shown = result.id;
	return false;
}

function HideTabbedDetailsPopup()
{
	if( search_done )
	{
		ShowSearchResults();
	}

	tabbed_details_popup.style.display = 'none';
	ShowAnnoyingThings();
	CancelFadeOut();
}

function SelectTab( tab )
{
	document.getElementById( 'user_reviews_tab' ).className = "tab";
	document.getElementById( 'upload_review_tab' ).className = "tab";
	document.getElementById( 'images_tab' ).className = "tab";

	document.getElementById( tab ).className = "selected_tab";

	document.getElementById( 'user_reviews_tab_content' ).style.display = "none";
	document.getElementById( 'upload_review_tab_content' ).style.display = "none";
	document.getElementById( 'images_tab_content' ).style.display = "none";

	document.getElementById( tab + "_content" ).style.display = "block";

	if( tab == 'upload_review_tab' )
	{
		document.getElementById( tab + "_iframe" ).src = "/Ajax/UploadReview/" + tabbed_details_popup.result.id;
	}
}


function HideAnnoyingThings()
{
	document.getElementById( 'annoying1' ).style.visibility = 'hidden';
	document.getElementById( 'annoying2' ).style.visibility = 'hidden';
}

function ShowAnnoyingThings()
{
	document.getElementById( 'annoying1' ).style.visibility = 'visible';
	document.getElementById( 'annoying2' ).style.visibility = 'visible';
}

function HideAddPlace()
{
	add_place.style.display = 'none';
	CancelFadeOut();
}

function ShowAddPlace()
{
	HideTabbedDetailsPopup();
	HideSearchResults();
	HideDetails();

	document.getElementById( 'add_place_place_name' ).value = "";
	document.getElementById( 'add_place_location' ).value = "";

	add_place.style.display = 'block';
	FadeOut();
}

function AddPlaceWizard()
{
	this.name = "";
	this.address1 = "";
	this.address2 = "";
	this.city = "";
	this.county = "";
	this.postcode = "";
	this.telephone = "";
	this.link = "";
	this.review = "";

	this.latitude = null;
	this.longitude = null;

	this.image_path = null;

	this.first_name = "";
	this.last_name = "";
	this.display_name = "";
	this.email = "";
	this.c4_communication = "";
	this.ford_communication = "";


	this.category = "";
	this.recommended = "";

	this.stage = null;

	this.Start = function()
	{
		this.SetStage( 1 );
		PageView( "Add New Step 1", "event31" );
		HideTabbedDetailsPopup();
		HideSearchResults();
		HideDetails();
		HideAddPlace();
		HideAnnoyingThings();
		FadeOut();
	}

	this.End = function()
	{
		document.getElementById( 'add_place_wizard_' + this.stage ).style.display = 'none';

		this.name = "";
		this.address1 = "";
		this.address2 = "";
		this.city = "";
		this.county = "";
		this.postcode = "";
		this.telephone = "";
		this.link = "";
		this.review = "";

		this.latitude = null;
		this.longitude = null;

		this.image_path = null;

		this.first_name = "";
		this.last_name = "";
		this.display_name = "";
		this.email = "";
		this.c4_communication = "";
		this.ford_communication = "";

		this.category = "";
		this.recommended = "";

		

		document.getElementById( 'wizard_name' ).value = "";
		document.getElementById( 'wizard_address1' ).value = "";
		document.getElementById( 'wizard_address2' ).value = "";
		document.getElementById( 'wizard_city' ).value = "";
		document.getElementById( 'wizard_county' ).value = "";
		document.getElementById( 'wizard_postcode' ).value = "";
		document.getElementById( 'wizard_telephone' ).value = "";
		document.getElementById( 'wizard_link' ).value = "";
		document.getElementById( 'wizard_review' ).value = "";

		document.getElementById( 'wizard_first_name' ).value = "";
		document.getElementById( 'wizard_last_name' ).value = "";
		document.getElementById( 'wizard_display_name' ).value = "";
		document.getElementById( 'wizard_email' ).value = "";
		document.getElementById( 'c4_communication' ).checked = false;
		document.getElementById( 'ford_communication' ).checked = false;

		var nodes = document.getElementsByName( 'wizard_category' );

		for( var i = 0; i < nodes.length; i++ )
		{
			nodes[ i ].checked = false;
		}

		var nodes = document.getElementsByName( 'wizard_recommended' );

		for( var i = 0; i < nodes.length; i++ )
		{
			nodes[ i ].checked = false;
		}

		document.getElementById( 'textbox_initial_text' ).style.display = "inline";

		ShowSearchResults();
		ShowAnnoyingThings();
		CancelFadeOut();
	}

	this.SetStage = function( stage )
	{
		if( this.stage != null )
		{
			document.getElementById( 'add_place_wizard_' + this.stage ).style.display = 'none';
		}

		this.stage = stage;
		
		document.getElementById( 'add_place_wizard_' + stage ).style.display = 'block';

		window.scrollTo( 0, 0 );
	}

	this.Stage1 = function()
	{
		this.SetStage( 1 );
	}

	this.Stage2 = function()
	{
		PageView( "Add New Step 2", "event31" );

		this.name = document.getElementById( 'wizard_name' ).value;
		this.address1 = document.getElementById( 'wizard_address1' ).value;
		this.address2 = document.getElementById( 'wizard_address2' ).value;
		this.city = document.getElementById( 'wizard_city' ).value;
		this.county = document.getElementById( 'wizard_county' ).value;
		this.postcode = document.getElementById( 'wizard_postcode' ).value;
		this.telephone = document.getElementById( 'wizard_telephone' ).value;
		this.link = document.getElementById( 'wizard_link' ).value;

		this.postcode = this.postcode.replace( /([a-z]{1,2}[0-9]{1,2}[a-z]?) ?([0-9]{1}[a-z]{2})/i, "$1 $2" ).toUpperCase();
		document.getElementById( 'wizard_postcode' ).value = this.postcode;

		this.latitude = null;
		this.longitude = null;

		this.review = document.getElementById( 'wizard_review' ).value;

		this.category = "";

		var nodes = document.getElementsByName( 'wizard_category' );

		for( var i = 0; i < nodes.length; i++ )
		{
			if( nodes[ i ].checked )
			{
				this.category += nodes[ i ].getAttribute( 'id' ) + ",";
			}
		}

		this.recommended = "";

		var nodes = document.getElementsByName( 'wizard_recommended' );

		for( var i = 0; i < nodes.length; i++ )
		{
			if( nodes[ i ].checked )
			{
				this.recommended += nodes[ i ].getAttribute( 'id' ) + ",";
			}
		}

		if( this.name != "" && this.city != "" && this.review != "" && this.category != "" )
		{
			window.frames[ 'add_place_photo_upload_iframe' ].location = "/AddPlacePhotoUpload" + ( this.image_path ? "?path=" + this.image_path : "" );
			this.SetStage( 2 );
		}
		else
		{
			alert( "Please tell us the name of the place, what it is, where it is and why you love it" );
		}
	}

	this.Stage3 = function( image_path )
	{
		if( image_path )
		{
			this.image_path = image_path;
		}

		this.SetStage( 3 );
	}

	this.Stage4 = function()
	{
		PageView( "Add New Step 4", "event31" );

		this.first_name = document.getElementById( 'wizard_first_name' ).value;
		this.last_name = document.getElementById( 'wizard_last_name' ).value;
		this.display_name = document.getElementById( 'wizard_display_name' ).value;
		this.email = document.getElementById( 'wizard_email' ).value;
		this.c4_communication = document.getElementById( 'c4_communication' ).checked;
		this.ford_communication = document.getElementById( 'ford_communication' ).checked;


		if( this.display_name != "" )
		{
			obj = this;

			MultiGeoCode( this.address1, this.address2, this.city, this.county, this.postcode, obj );
	
			this.SetStage( 4 );
		}
		else
		{
			alert( "Please let us know what name you would like to use" );
		}
	}

	this.Stage5 = function()
	{
		PageView( "Add New Submitted", "event31,event32" );

		var service = new SearchService();

		var data = "?";

		data += "place[name]=" + encodeURIComponent( this.name ) + "&";
		data += "place[address1]=" + encodeURIComponent( this.address1 ) + "&";
		data += "place[address2]=" + encodeURIComponent( this.address2 ) + "&";
		data += "place[city]=" + encodeURIComponent( this.city ) + "&";
		data += "place[county]=" + encodeURIComponent( this.county ) + "&";
		data += "place[postcode]=" + encodeURIComponent( this.postcode ) + "&";
		data += "place[telephone]=" + encodeURIComponent( this.telephone ) + "&";
		data += "place[link]=" + encodeURIComponent( this.link ) + "&";
		data += "review[review]=" + encodeURIComponent( this.review ) + "&";

		data += "place[latitude]=" + encodeURIComponent( this.latitude ) + "&";
		data += "place[longitude]=" + encodeURIComponent( this.longitude ) + "&";

		data += "user[first_name]=" + encodeURIComponent( this.first_name ) + "&";
		data += "user[last_name]=" + encodeURIComponent( this.last_name ) + "&";
		data += "user[display_name]=" + encodeURIComponent( this.display_name ) + "&";
		data += "user[email]=" + encodeURIComponent( this.email ) + "&";
		data += "user[c4_communication]=" + encodeURIComponent( this.c4_communication ) + "&";
		data += "user[ford_communication]=" + encodeURIComponent( this.ford_communication ) + "&";


		data += "category=" + encodeURIComponent( this.category ) + "&";
		data += "recommended=" + encodeURIComponent( this.recommended ) + "&";

		data += "image_path=" + encodeURIComponent( this.image_path ) + "&";

		service.AddPlace( data );

		this.SetStage( 5 );
	}


	this.Locate = function( latlng )
	{
		var map2 = new google.maps.Map2( document.getElementById( "map2" ) );
		var point = new google.maps.LatLng( 51.50002, -0.12618 );
		var zoom = 10;

		if( latlng != null )
		{
			point = latlng;
			zoom = 14;
		}

		map2.setCenter( point, zoom );
		marker = new GMarker( point, {draggable: true} );

		obj = this;
		GEvent.addListener( marker, "dragend", function(){ obj.UpdatePosition( marker ); } );

		map2.addOverlay( marker );

		map2.addControl( new google.maps.SmallMapControl() );
		map2.addControl( new google.maps.MapTypeControl() );

		this.latitude = point.lat();
		this.longitude = point.lng();
	}

	this.UpdatePosition = function( marker )
	{
		var position = marker.getLatLng();
		this.latitude = position.lat();
		this.longitude = position.lng();
	}

}
