// Enrico Simonetti 2009

var country_value = '';
var country_code_value = '';
var city_value = '';
var saved_latitude = '';
var saved_longitude = '';
var cities = '';
var top_country_match = '';
var top_city_match = '';

// only if the saved country is empty, execute google location, save loading time
if(saved_country_value.replace(/^\s+|\s+$/g, '') != '')
{
	presetSavedValues();
}
else
{
	google.load("search", "1");
	google.setOnLoadCallback(
		function()
		{
			if(google.loader.ClientLocation)
			{
				// found an address, the map is already initialized
				var country_name = google.loader.ClientLocation.address.country;
				saved_latitude = google.loader.ClientLocation.latitude;
				saved_longitude = google.loader.ClientLocation.longitude
				var country_code = google.loader.ClientLocation.address.country_code;
				var city_name = google.loader.ClientLocation.address.city;

				saved_country_value = country_name;
				saved_country_code_value = country_code;
				saved_city_name = city_name;
		
				// automatically save the value if comes from google
			
				if(saved_country_value != '' &&
					saved_country_code_value != '' &&
					saved_city_name != '' 
				)
				{
					var temp_city_name = saved_city_name;
					presetSavedValues();
					perfectCityMatch(temp_city_name);
				}
			}
			else
			{
				// not found, means we need to ask for the address and then detect the weather
			}
		}
	);
}

function presetSavedValues()
{
	// now if there is a value, set it in the right spot
	
	if(saved_country_value.replace(/^\s+|\s+$/g, '') != '')
	{
		$('country_input').value=saved_country_value.replace(/^\s+|\s+$/g, '').toLowerCase().capitalize();

		// and start the checking as well
		checkCountryValue();
	}
}

function checkCountryValue()
{
	if($('country_input').value.replace(/^\s+|\s+$/g, '')!=country_value)
	{
		cleanEventualCountryMatching();
		rebuildCountrySuggestions($('country_input').value.replace(/^\s+|\s+$/g, ''));
		country_value = $('country_input').value.replace(/^\s+|\s+$/g, '');
		// clean the city if the country changes... else the checking won't start
		city_value = '';
	}
	setTimeout('checkCountryValue()', 300);
}

function checkCityValue()
{
	if($('city_input')!=undefined)
	{
		if($('city_input').value.replace(/^\s+|\s+$/g, '')!=city_value)
	        {
	                cleanEventualCityMatching();
	                rebuildCitySuggestions($('city_input').value.replace(/^\s+|\s+$/g));
	                city_value = $('city_input').value.replace(/^\s+|\s+$/g, '');
	        }
	}
        setTimeout('checkCityValue()', 300);
}

function destroyCountrySuggestions()
{
	if($('suggested_countries') != undefined)
	{
		$('suggested_countries').parentNode.removeChild($('suggested_countries'));
	}
	
	if($('suggested_cities_row') != undefined)
	{
		$('suggested_cities_row').parentNode.removeChild($('suggested_cities_row'));
	}
	
	if($('suggested_countries_row') != undefined)
        {
                $('suggested_countries_row').parentNode.removeChild($('suggested_countries_row'));
        }

	if($('current_weather_image') != undefined)
        {
                $('current_weather_image').parentNode.removeChild($('current_weather_image'));
        }
}

function destroyCitySuggestions()
{
	if($('suggested_cities') != undefined)
        {
                $('suggested_cities').parentNode.removeChild($('suggested_cities'));
        }

        if($('suggested_cities_row') != undefined)
        {
                $('suggested_cities_row').parentNode.removeChild($('suggested_cities_row'));
        }

        if($('current_weather_image') != undefined)
        {
                $('current_weather_image').parentNode.removeChild($('current_weather_image'));
        }
}

function perfectCountryMatch(matching_string, matching_code)
{
	//$('suggested_match').setAttribute('class', 'valid');
	$('suggested_match').className = 'valid';
	$('country_input').value = matching_string;
	country_value = matching_string;

	country_code_value = matching_code;
	destroyCountrySuggestions();
	// ajax request the cities
	
	createCitiesForm();

	if(country_code_value!='')
	{
		var myRequest = new Request.JSON(
			{
				url: base_url + 'cities/' + country_code_value  +'/',
				method: 'post',
				autoCancel: 'true',
				onSuccess: function(txt)
				{
					//if(txt!='')
					//{
						//cities = eval(txt);
						cities = txt;
						//checkCityValue();
					//}
					checkCityValue();
				},
				onFailure: function(txt)
				{
				}
			}
		).get(
		);
	}
}

function perfectCityMatch(matching_string)
{
	//$('city_suggested_match').setAttribute('class', 'valid');
	$('city_suggested_match').className = 'valid';
	$('container_picker').setStyle('display', '');
	$('save_button').setStyle('display', '');
	showSelectedSmiley(saved_smiley);

	// hide save location button
	if($('cities_empty_row1')!=undefined)
	$('cities_empty_row1').parentNode.removeChild($('cities_empty_row1'));
	$('city_input').value = matching_string;
	city_value = matching_string;
	destroyCitySuggestions();
	// save actual location

	if(country_code_value!='')
	{
		saveLocation();	
	}
}

function cleanEventualCountryMatching()
{
	//$('suggested_match').setAttribute('class', '');
	$('suggested_match').className = '';
	$('container_picker').setStyle('display', 'none');
	$('save_button').setStyle('display', 'none');
	destroySmileysList();
	
	country_code_value = '';
        if($('cities_row')!=undefined)
        {
                // remove it
                $('country_table_body').removeChild($('cities_row'));
		
		if($('cities_empty_row1')!=undefined)
		$('country_table_body').removeChild($('cities_empty_row1'));
        }

	// invalidate the form
}

function cleanEventualCityMatching()
{
	$('city_suggested_match').className = '';
	$('container_picker').setStyle('display', 'none');
	$('save_button').setStyle('display', 'none');
	destroySmileysList();
	
	// cleanup the previous save button cities_empty_row1
	if($('cities_empty_row1')!=undefined)
	$('country_table_body').removeChild($('cities_empty_row1'));

/*
        if($('cities_empty_row1') == undefined)// && $('cities_row') != undefined)
        {
                var mytable_body = $('country_table_body');
                var tr = document.createElement('tr');
                tr.setAttribute('id', 'cities_empty_row1');
                var td = document.createElement('td');
                tr.appendChild(td);
                var td = document.createElement('td');
                //td.textContent // this would be valid just for text, no links
		td.innerHTML = 'Press <a href="javascript:void(0);" onclick="perfectCityMatch($(\'city_input\').value)" >Save</a> if not suggested above...';
                tr.appendChild(td);
                var td = document.createElement('td');
                tr.appendChild(td);
		// this goes inserted before the suggestion row
                //mytable_body.insertBefore(tr, $('suggested_cities_row'));
		mytable_body.appendChild(tr);
		alert('added!');
	}
*/

	// invalidate the form
}

function rebuildCitySuggestions(value)
{
	// remove the table and rebuild it

	destroyCitySuggestions();

	var mytable_body = $('country_table_body');

	var mytable = document.createElement('table');
	mytable.setAttribute('id','suggested_cities');
	mytable.className = 'suggested_background';
	//mytable.cellpadding = 0;
	//mytable.cellspacing = 0;

	// guess what? ie requires the tbody for creating dinamic tables... crazy.
	var tbody = document.createElement('tbody');

	// this part goes for each country value

	var count = 1;
	var perfect_match = 0;

	top_city_match = '';

	if(value!='' && value.length>1 && cities != undefined && cities!='' && cities.length>0)
	{
		// if the string is at least 2 chars and is not empty
		cities.each(
			function(element)
			{
				if(count<=6)
				{
					if(element.city_name.toLowerCase().substring(0,value.length)==value.toLowerCase())
					{

						// if it is a complete match, replace it and remove the suggestions
				
						if(element.city_name.toLowerCase()==value.toLowerCase())
						{			
							perfectCityMatch(element.city_name.toLowerCase().capitalize());
							perfect_match = 1;
						}

						// add it only if matches the criteria
						var tr = document.createElement('tr');
						tr.className = 'sugg_line';
						tr.onclick = function() { perfectCityMatch(element.city_name.toLowerCase().capitalize()); }
						var td = document.createElement('td');
						td.className = 'sugg_city_name';
						td.innerHTML = element.city_name.toLowerCase().capitalize();

						if(top_city_match == '')
						{
							top_city_match = element.city_name.toLowerCase().capitalize();
						}

						tr.appendChild(td);
						tbody.appendChild(tr);
						count++;
					}
				}
			}
		);
	}
	
	mytable.appendChild(tbody);

	// only if there is an actual result, append the table
	if(count>1 && perfect_match==0)
	{
	        var tr = document.createElement('tr');
	        tr.setAttribute('id', 'suggested_cities_row');
        	var td = document.createElement('td');
	        tr.appendChild(td);
	        var td = document.createElement('td');
		td.appendChild(mytable);
	        td.setAttribute('id', 'suggested_cities_container');
	        tr.appendChild(td);
	        var td = document.createElement('td');
	        tr.appendChild(td);
	        mytable_body.appendChild(tr);
	}

	// and now show the save option, also if there is no match

	if($('cities_empty_row1') == undefined && perfect_match == 0 && value != '')
	{
		var mytable_body = $('country_table_body');
		var tr = document.createElement('tr');
		tr.setAttribute('id', 'cities_empty_row1');
		var td = document.createElement('td');
		tr.appendChild(td);
		var td = document.createElement('td');
		//td.textContent // this would be valid just for text, no links
		td.innerHTML = '<a href="javascript:void(0);" onclick="perfectCityMatch($(\'city_input\').value)" >Save</a> a new city if not suggested...';
		tr.appendChild(td);
		var td = document.createElement('td');
		tr.appendChild(td);
		mytable_body.appendChild(tr);
	}
}

function rebuildCountrySuggestions(value)
{
	// remove the table and rebuild it

	destroyCountrySuggestions();

	// create the suggestion row container
	mytable_body = $('country_table_body');
	var tr = document.createElement('tr');
        tr.setAttribute('id', 'suggested_countries_row');
        var td = document.createElement('td');
	//td.innerHTML = '&nbsp;';
        tr.appendChild(td);
        var td = document.createElement('td');
        td.setAttribute('id', 'suggested_countries_container');
        tr.appendChild(td);
        var td = document.createElement('td');
	//td.innerHTML = '&nbsp;';
        tr.appendChild(td);
        mytable_body.appendChild(tr);

	var mytable = document.createElement('table');
	mytable.setAttribute('id','suggested_countries');
	mytable.className = 'suggested_background';
	//mytable.cellpadding = 0;
	//mytable.cellspacing = 0;

	var tablebody = document.createElement('tbody');

	// this part goes for each country value

	var count = 1;
	var perfect_match = 0;

	top_country_match = '';

	if(value!='' && value.length>1)
	{
		// if the string is at least 2 chars and is not empty

		countries.each(
			function(element)
			{
				if(count<=6)
				{
					if(element.country_name.toLowerCase().substring(0,value.length)==value.toLowerCase())
					{

						// if it is a complete match, replace it and remove the suggestions
				
						if(element.country_name.toLowerCase()==value.toLowerCase())
						{			
							perfectCountryMatch(element.country_name.toLowerCase().capitalize(), element.country_code.toUpperCase());
							perfect_match = 1;
						}

						/*element.country_name.test(value, "i")*/						
						// add it only if matches the criteria
						var tr = document.createElement('tr');
						tr.className = 'sugg_line';
						tr.onclick = function() { perfectCountryMatch(element.country_name.toLowerCase().capitalize(), element.country_code.toUpperCase()); }

						if(top_country_match == '')
						{
							top_country_match = element.country_name.toLowerCase().capitalize();
						}
	
						var td = document.createElement('td');
						
						var div = document.createElement('div');
						div.className = 'sugg_country_name';
						div.innerHTML = element.country_name.toLowerCase().capitalize();
						td.appendChild(div);

						var div = document.createElement('div');
						div.className = 'sugg_country_code';
						div.innerHTML = element.country_code;
						td.appendChild(div);

						tr.appendChild(td);
						tablebody.appendChild(tr);
						count++;
					}
				}
			}
		);
	}
	
	mytable.appendChild(tablebody);

	// only if there is an actual result, append the table
	if(count>1 && perfect_match==0) $('suggested_countries_container').appendChild(mytable);
}

function createCitiesForm()
{
	var mytable_body = $('country_table_body');
	var tr = document.createElement('tr');
	tr.setAttribute('id', 'cities_row');
	var td = document.createElement('td');
	td.innerHTML = 'City:';
	tr.appendChild(td);
	var td = document.createElement('td');
	var input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('id', 'city_input');
	input.className = 'location_input';

	if(disabled)
	{
		input.setAttribute('readony', 'readonly');
		input.setAttribute('disabled', 'disabled');
	}
	
	if(saved_city_name.replace(/^\s+|\s+$/g, '') != '' &&
		saved_country_value.toLowerCase()==country_value.toLowerCase())
	{
		// load the saved city if any
		input.setAttribute('value', saved_city_name.replace(/^\s+|\s+$/g, '').toLowerCase().capitalize());
		// in this case run the save location automatically
		// now drop the saved city name

		saved_city_name = '';
	}

	td.appendChild(input);
	tr.appendChild(td);
	var td = document.createElement('td');
	td.setAttribute('id', 'city_suggested_match');
	tr.appendChild(td);
	mytable_body.appendChild(tr);

        // add the keyup event for checking for enter key
        $('city_input').addEvent('keyup',
                function(e)
                {
                        if(e.key == 'enter')
                        {
                                if(top_city_match != undefined && top_city_match != '')
                                {
                                        $('city_input').value = top_city_match;
                                }
                        }
                }
        );

	$('city_input').focus();
}

function saveLocation()
{
	// retrieve google location for the city, if not present already
	// save the city, if not in the database already

	if($('city_input').value.replace(/^\s+|\s+$/g, '')!='')
	{
		if(saved_city_name.replace(/^\s+|\s+$/g, '')=='' ||
			saved_city_name.replace(/^\s+|\s+$/g, '')!= $('city_input').value.replace(/^\s+|\s+$/g, '')!=''
		)
		{
			var address = $('city_input').value.replace(/^\s+|\s+$/g, '') + ','+ country_code_value;

			geocoder = new GClientGeocoder();
			if(geocoder)
			{
				geocoder.getLocations(address,
					function(response)
					{
						if(response == undefined || response.Status.code != 200)
						{
							alert("Sorry the city '" + $('city_input').value.replace(/^\s+|\s+$/g, '')  + "' couln't be found, can you please try again?");
			                                $('city_input').value = '';
						}
						else
						{
							var place = response.Placemark[0];
							saved_latitude = place.Point.coordinates[1];
							saved_longitude = place.Point.coordinates[0];

							// save only if it is a real city...
							if(saved_latitude && saved_longitude)
							{
								var myRequest = new Request(
									{
										url: base_url + 'save_city/',
										method: 'post',
										autoCancel: 'true',
										onSuccess: function(txt)
										{
											if(txt!='')
											{
												var img = document.createElement('img');
										                img.setAttribute('title', 'Weather');
												img.setAttribute('src', google_weather_url+txt);
												img.setAttribute('id', 'current_weather_image');
										                $('current_weather').appendChild(img);

												//alert(txt);
												// no need to alert the "Saved!" there is already the green circle
											}
										},
										onFailure: function(txt)
										{
										}
									}
								).send(
									'city_name=' + $('city_input').value.replace(/^\s+|\s+$/g, '') +
									'&country_code=' + country_code_value +
									'&latitude=' + saved_latitude +
									'&longitude=' + saved_longitude
								);
							}
						}
					}
				);
			}
		}
	}
}

window.addEvent('domready',
	function()
        {
		if(!disabled)
		{
			$('country_input').addEvent('keyup',
				function(e)
				{
					// start the checking only on the first keyup
					setTimeout('checkCountryValue()', 300);
					if(e.key == 'enter')
					{
						if(top_country_match != undefined && top_country_match != '')
						{
							$('country_input').value = top_country_match;
						}
					}
				}
			);
			
			if($('save_button')!=undefined)
			{
				$('save_button').addEvent('click',
					function(e)
					{
						notify_on_unload = true;	
						$('save_button').setStyle('display', 'none');
						var myRequest = new Request(
							{
								url: base_url + 'save_color/',
								method: 'post',
								autoCancel: 'true',
								onSuccess: function(txt)
								{
									notify_on_unload = false;
									if(txt!='')
									{
										alert(txt);
										$('save_button').setStyle('display', '');
										showSelectedSmiley(saved_smiley);	
									}
									else
									{
										document.location.reload();	
									}
								},
								onFailure: function(txt)
								{
									notify_on_unload = false;
								}
							}
						).send(
							'rgb=' + $('color_value').value.replace(/^\s+|\s+$/g, '')
						);
					}
				);
			}
		}
	}
);

function rebuildSmileysList(value)
{
        destroySmileysList();

	notify_on_unload = true;
	
	$('container_picker').setStyle('display', 'none');
	$('save_button').setStyle('display', 'none');

	var div_smileys = $('smileys');

	var table = document.createElement('table');
        table.setAttribute('id','suggested_smileys');
        table.className = 'suggested_background';

        var tbody = document.createElement('tbody');

        var count = 1;
	var total_el = 1;
	var col = 4;

	var tr = document.createElement('tr');
	var td = document.createElement('td');
	td.setAttribute('colspan', col);
	// now the usual IE stuff...
	td.colspan = col;
	td.colSpan = col;
	td.className = 'image_text_content';
	td.innerHTML = 'Please select your current mood!';
	tr.appendChild(td);
	tbody.appendChild(tr);	

	// new line for the first loop
	tr = document.createElement('tr');

        if(smileys.length>0)
        {
                smileys.each(
                        function(element)
                        {
				if(count > col)
				{
					// change row
					count = 1;
					tr = document.createElement('tr');
				}

				var description = element.description.toLowerCase().capitalize();
				var td = document.createElement('td');
				td.onclick = function() { saveSmiley(element.id); }

				if(element.id == value)
                                {
                                        // selected option
                                        td.className = 'image_selected_line image_line';
                                }
                                else
                                {
                                        td.className = 'image_line';
                                }

				var img = document.createElement('img');
				img.setAttribute('src', base_url  + element.image);
				img.setAttribute('alt', description);
				img.setAttribute('title', description);
				td.appendChild(img);
				tr.appendChild(td);

				if(smileys.length == total_el)
				{
					// if it is the last element, fill the row
					for(var gap = count; gap < col; gap++)
					{
						var td = document.createElement('td');
						td.innerHTML = '&nbsp;';
						tr.appendChild(td);
						count++;
					}
				}

				if(count == col)
				{
					// if it is the last element of the row, add the row
					tbody.appendChild(tr);
				}

				total_el++;
                                count++;
                        }
                );
        }

        table.appendChild(tbody);
	div_smileys.appendChild(table);
}

function saveSmiley(id)
{
	var myRequest = new Request(
		{
			url: base_url + 'save_smiley',
			method: 'post',
			autoCancel: 'true',
			onSuccess: function(txt)
			{
				// show the item of the right id
				saved_smiley = id;
				showSelectedSmiley(id);
				notify_on_unload = false;
			},
			onFailure: function(txt)
			{
				notify_on_unload = false;
			}
		}
	).send(
        	'smiley_id=' + id
	);
}

function showSelectedSmiley(id)
{
	destroySmileysList();

	if(typeof(id) == 'undefined' || id == '')
	{
		// if there is no smiley saved
		rebuildSmileysList();
	}
	else
	{
		var div_smileys = $('smileys');

		var table = document.createElement('table');
		table.setAttribute('id','suggested_smileys');
		table.className = 'single_smiley';
		//table.setAttribute('cellpadding', 2);
		//table.setAttribute('cellspacing', 2);

		var tbody = document.createElement('tbody');

		var tr = document.createElement('tr');

		tr.onclick = function(){ rebuildSmileysList(id); }
		tr.setAttribute('class', 'image_line');

		var div = document.createElement('div');
		div.innerHTML = 'Current mood:';
		div.className = 'float_left padding_top_7 padding_left_right_4';
		var td = document.createElement('td');
		td.appendChild(div);

		var div = document.createElement('div');
		div.className = 'float_right padding_left_right_4';

		// now find back the right element
		if(smileys.length>0)
		{
			smileys.each(
				function(element)
				{
					if(element.id==id)
					{
						var description = element.description.toLowerCase().capitalize();
						var img = document.createElement('img');
						img.setAttribute('src', base_url  + element.image);
						img.setAttribute('alt', description);
						img.setAttribute('title', description);
						div.appendChild(img);
						td.appendChild(div);
						tr.appendChild(td);
						tbody.appendChild(tr);
						table.appendChild(tbody);
						div_smileys.appendChild(table);
					}
				}
			);
		}

		// display again color picker and button
		$('container_picker').setStyle('display', '');
		$('save_button').setStyle('display', '');
	}
}

function destroySmileysList()
{
        if($('smileys') != undefined && $('suggested_smileys') != undefined)
        {
                //$('smileys').parentNode.removeChild($('suggested_smileys'));
		$('smileys').removeChild($('suggested_smileys'));
        }
}
