

/***** MODAL WINDOWS *****/
$(document).ready(function() { 
	$('#location_selector_modal').dialog(
		{ autoOpen: false, 
		  dialogClass: 'locations_modal',
		  draggable: false, 
		  modal: true, 
		  bgiframe: true,
		  autoResize:true,
		  resizable: false, 
    	  width: 440,
    	  height: 580,
		  title: 'Change your search location', 
		  buttons: { "Ok": function() { $(this).dialog("close"); } },
	   	  open: function() {
				$("#location_selector_modal").html("<p style=\"text-align:center; padding-top:20px;\"><img src=\"/images/spinner.gif\" /></p>");
				$("#location_selector_modal").load("/profile/get_location_modal", null, function() {
					
					/* once the page is loaded into the modal, do some stuff */
					$('#locations_search .location a').live('mouseover', function() { $(this).addClass('hover')}).live('mouseout', function() { $(this).removeClass('hover')});
					$('#current_location_search_results .location a').live('click', removeSearchLocation);
					$('#user_location_list input.location_checkbox').click(checkSearchLocation);		
					$('#user_default_location_list input.location_checkbox').click(checkSearchLocation);		
					$('#user_location_list input.location_parent_checkbox').click(checkSearchLocationParent);
					$('#user_default_location_list input.location_parent_checkbox').click(checkSearchLocationParent);		

					$('#location_ids').change(changeSearchLocation);		

					$("#locations_filter").searchTree("#user_location_list", "#search_locations");
					$("#default_locations_filter").searchTree("#user_default_location_list");
				});
			
		  }
	}); 
	
	$('#change_location').click(function() { $('#location_selector_modal').dialog('open'); return false;}); 	
});
		
location_search_update_timeout = null;
function changeSearchLocation() {
	if (location_search_update_timeout) {
		clearTimeout(location_search_update_timeout);
	}
	location_search_update_timeout = setTimeout(updateSearchLocations, 1500);
}

function updateSearchLocations() {
	$.ajax({ url: '/profile/update_locations', data: { location_ids: $('#location_ids').val() }, success: function() {
		// Any change in the location counter will cause that the regions are cleared out
		$.ajax({ url: '/profile/update_shapefiles', data: { shapefile_ids: '' }, success: function() {
			// Show the change message
			message = "<p>We've detected that you updated your search locations - <a href='#' onclick='location.reload(true);'>click here</a> to reload this page and have the changes take effect.</p>";
			if ($('#notice').length > 0)
				$('#notice').html(message);
			else {
				notice = $("<div id='notice'>" + message + "</div>");
				$('#content').prepend(notice);
			}
		} } );
	} } );

	clearTimeout(location_search_update_timeout);
}

/*
 * Adds a location link
 */
function addLocationLink(locationId, label) {
	var str = "<div class=\"location\" id=\"location_" + locationId + "\"><a href=\"#\" title=\"" + label + "\" rel=\"" + locationId + "\">" + label + "<span>x</span></a></div>";
	$('#current_location_search_results').append(str);
}

/*
 * Adds a location
 */
function addLocation(locationId, label) {
	// Add the location id value
	if (addHiddenLocationIdValue(locationId)) {
  	// Add location link
  	addLocationLink(locationId, label);
  	// Check it
  	selectSearchLocation(locationId);
	}
}

/*
 * Removes a location
 */
function removeLocation(locationId) {
	// Remove the location link
	removeLocationLink(locationId);
	// Remove the location id value
	removeHiddenLocationIdValue(locationId);
	// Uncheck it
	uncheckSearchLocation(locationId);
}

/*
 * Removes the location link 
 */
function removeLocationLink(locationId) {
	var location = $('#current_location_search_results a[rel=' + locationId + ']');
	if (location) {
		location.parent().remove();	
	}
}

/*
 * Checks/Unchecks the current search location
 */
function checkSearchLocation() {
	return toggleSearchLocation($(this).next().text(), $(this).attr('rel'), $(this).attr('checked'));
}

/*
 * Checks/Unchecks the current search location parent
 */
function checkSearchLocationParent() {
  var result = true;
  
  // Get the sub locations
  var parentLocation = $(this);
  var items = parentLocation.parent().next().children();
  
  // Add/Remove the checks one by one
  var inputElt;
  items.each(function(index) {
    inputElt = $(this).children(":first-child");
    if (!toggleSearchLocation(inputElt.next().text(), inputElt.attr('rel'), parentLocation.attr('checked'))) {
      // Toggle failed (min.one location must remain)
      // Note: immediate return is necessary because of jquery each() method
      result = false;
      return false;
    }
  });
  // return result;
  
  return true;
}

/*
 * Checks/Unchecks a specific search location  
 */
function toggleSearchLocation(label, locationId, chked) {
	if(chked) {
		// Add location
		addLocation(locationId, label);
	}
	else {
		// Remove location
		if ($('#current_location_search_results a').length > 1) {
			// Remove location
			removeLocation(locationId);
		} else { 
			$('#location_validation').show();
			setTimeout(function() { $('#location_validation').fade() }, 2500);
			return false;
		}
	}
	// Update the counter
	updateLocationCounter();
	
	return true;
}

function uncheckSearchLocation(id) {
	$('#user_location_list input[rel=' + id + ']').attr('checked', false);
	$('#user_default_location_list input[rel=' + id + ']').attr('checked', false);
}

function selectSearchLocation(id) {
	$('#user_location_list input[rel=' + id + ']').attr('checked', true);
	$('#user_default_location_list input[rel=' + id + ']').attr('checked', true);
}

function updateLocationCounter() {
	// Get the list of location elements
	var locationElts = $('#current_location_search_results a');
	if (locationElts.length > 1) {
		// Multiple locations
		// Toggle the location display
		$('#single_location').hide();
		$('#multiple_location').show();
		
		// Update the location count
		$('#search_location_count').text( locationElts.length );	
	}
	else {
		// Single location
		// Toggle the location display
		$('#single_location').show();
		$('#multiple_location').hide();
		
		// Update the location name
		$('#search_location_name').text( locationElts[0].title.length > 20 ? locationElts[0].title.substring(0,20) + " .." : locationElts[0].title);
	}
	
	// Modify the region selection (gets called in shapefile_search.js)
	showNoShapefileSelectedState();
		
}

function removeSearchLocation() {
	if ($('#current_location_search_results a').length > 1) {
		$(this).removeClass('hover').effect('highlight');
		$(this).parent().remove();
		updateLocationCounter();
		removeHiddenLocationIdValue($(this).attr('rel'));

		uncheckSearchLocation($(this).attr('rel'));
	} else { 
		$('#location_validation').show();
		setTimeout(function() { $('#location_validation').fade() }, 2500);
	}
	return false;
}

/*
 * Adds the hidden location id value and retrieves TRUE if it was not added before
 */
function addHiddenLocationIdValue(id) {
  var result = true;
	var inputElt = $('#location_ids');
  // Get the ids
	var ids = inputElt.val().split(',');
	// Get the index of the id
	var index = jQuery.inArray(id, ids);
	if (index == -1) { 
	  // id not found
  	if (inputElt.val() == '') {
  		inputElt.val(id);
  	} else {
  		inputElt.val(inputElt.val() + ',' + id);
  	}
  	inputElt.change();
	}
  else {
    // id has been already added
    result = false;
  }
	return result;
}

/*
 * Removes the hidden location id value
 */
function removeHiddenLocationIdValue(id) { 
	var inputElt = $('#location_ids');
	
  // Get the ids
	var ids = inputElt.val().split(',');
	// Get the index of the id
	var index = jQuery.inArray(id, ids);
	if (index != -1) { 
	  // Delete it
		ids.splice(index, 1).toString();
		// Insert the changed value
		inputElt.val(ids);
		inputElt.change();
	}			
}

/*
 * Checks/Unchecks all additional locations
 * @param checkAll TRUE if the additional locations should be checked
 */
function toggleAllAdditionalLocations(checkAll) {
	// Process all locations one by one	
	$("#user_location_list input").each(function() {
		// Get the parameters
		if (checkAll && !this.checked) {
			// Add location
			addLocation($(this).attr('rel'), $(this).next().text());
		}
		if (!checkAll && this.checked) {
			// Remove location
			removeLocation($(this).attr('rel'));
		}			
	});
	
	if (!checkAll) {
		// We need to add a default one
		var firstDefaultLocation = $('#user_default_location_list input:first');
		// Add location
		addLocation(firstDefaultLocation.attr('rel'), firstDefaultLocation.next().text());
	}
	
	// Update the counter
	updateLocationCounter();
}
