//javascript functions for portal

//map stuff

function Borough( id, nm ) {
  this.id = id;
  this.nm = nm;
}

var boroughs = new Array();
boroughs["50"] = "Bromley";
boroughs["102"] = "Croydon";
boroughs["204"] = "Kingston upon Thames";
boroughs["208"] = "Lambeth";
boroughs["216"] = "Lewisham";
boroughs["237"] = "Merton";
boroughs["308"] = "Richmond upon Thames";
boroughs["377"] = "Sutton";
boroughs["408"] = "Wandsworth";

var debug_scripts = false;
var authorityId = 0;
var areas = new Array();
var all_areas = false;
var all_authorities = false;

function debug( msg ) {
  if( debug_scripts ) {
    alert( msg );
  }
}

function resetAreas() {
  areas = new Array();
}

function resetAuthority() {
  authorityId = 0;
  resetAreas();
}

function setAuthority( id ) {
  authorityId = id;
  debug( "Set authority as " + id );
}

function toggleAllAreas() {
  all_areas = true;
}

function toggleAllAuthorities() {
  all_authorities = true;
}

function toggleArea( areaId ) {
  var add_area = true;
  var tmpArray = new Array();
  for( var kk = 0; kk < areas.length; kk++ ) {
    if( areas[kk] != areaId ) {
      tmpArray[tmpArray.length] = areas[kk];
    } else {
      add_area = false;
      debug( "Removed area: " + areaId );
    }
  }

  if( add_area ) {
    tmpArray[tmpArray.length] = areaId;
    debug( "Added area: " + areaId );
  }
  areas = tmpArray;
}

function toggleAreaNameCheckboxes( on_off )
{
  var frm = document.forms['locationForm'];
  if( on_off == true )
  {
  	debug( "Toggling all areas on" );
		for ( var kk = 0; kk < frm.elements['area'].length; kk++ )
		{
			frm.elements['area'][kk].checked = true;
			toggleArea( frm.elements['area'][kk].value );
		}
	} 
	else
	{
  	debug( "Toggling all areas off" );
		for ( var kk = 0; kk < frm.elements['area'].length; kk++ )
		{
			frm.elements['area'][kk].checked = false;
			toggleArea( frm.elements['area'][kk].value );
		}
	}
	return false;
}

//form_url will be defined in the main template
function submitForm() 
{
  full_url = form_url + "&authority=" + authorityId;
  if( all_authorities ) 
  {
    full_url += "&all_authorities=true";
  }
  else if( all_areas ) 
  {
    full_url += "&all_areas=true";
  } 
  else 
  {
    if( areas.length == 0 ) 
    {
      bname = boroughs["" + authorityId];
      if( bname == "" )
      {
        bname = "the borough";
      }
			
      answer = confirm( "No districts selected.\n\nWould you like search across all districts in " + bname + "?" );
      
      if( answer ) 
      {
        full_url += "&all_areas=true";
      }
      else 
      {
        return;
      }
    }
    else 
    {
      full_url += "&name_mode=true";
      for( var kk = 0; kk < areas.length; kk++ ) 
      {
        full_url += "&area=" + areas[kk];
      }
    }
  }
  if (skin != ""){
    full_url += "&skin="+skin;
  }
  /*alert(full_url);*/
  location.href = full_url;
}

