includeLibrary("/OpenForum/Javascript/field-formatter.js");
includeLibrary("/OpenForum/Javascript/ui.js");
includeLibrary("/OpenForum/Extensions/GoogleMap/googleMap.js");
includeLibrary("/OpenForum/Extensions/GoogleMap/locator.js");
includeInitFunction("initPage();");
includeUnloadFunction("googleMap.close();");

//RenSMART Search Functions

function initPage()
{
  term = getParameter("q");
  if(term.length>0)
  {
    document.getElementById("postcode").value=term;
    search();
  }

  initMap();

  lat = getParameter("lat");
  lng = getParameter("lng");
  if(lat.length>0 && lat.length>0)
  {
    query="";
    latitude = parseFloat(lat);
    longitude = parseFloat(lng);
    setLocation(latitude,longitude);
  }
}

var latitude = 51.255037;
var longitude = -1.391748;
function initMap()
{
  googleMap.init(latitude,longitude,6,true);

  GEvent.addListener(googleMap.map, "click", function(overlat,latlng) { setLocation( latlng.lat(),latlng.lng() ); });

  var newIcon = new GIcon(G_DEFAULT_ICON);
  newIcon.image = "http://www.rensmart.com/OpenForum/Images/rensmart-google-maps-dot.png";
  googleMap.dragMarker = new GMarker(new GLatLng(latitude, longitude), {draggable: true, icon: newIcon});
  googleMap.map.addOverlay(googleMap.dragMarker );
 
  GEvent.addListener(googleMap.dragMarker , "dragend", function() { setLocation(googleMap.dragMarker.getPoint().lat(),googleMap.dragMarker.getPoint().lng()); });
}

var searching = false;
function search()
{
  if(searching==true)
  {
    return;
  }
  searching=true;
  query = document.getElementById("postcode").value;
  document.getElementById("status").innerHTML = "<center><h2>Searching for results for "+query+"...</h2></center>";

  document.getElementById("results").innerHTML = "";

  findLocationForQuery(query,findResults);
}

function initLocation()
{
// To be implemented
}

function setLocation(lat,lng)
{
  latitude = lat;
  longitude = lng;
  googleMap.dragMarker.setPoint( new GLatLng(latitude,longitude) );
  document.getElementById("staticMap").src="http://maps.google.com/staticmap?size=200x200&center="+latitude+","+longitude+"&key=ABQIAAAAo63e8n5tWvbJNlSuvp5pXxSZbxR6CviL1RhPwCabq3nMZexA2BSXytBymes45O4t-hYnHoS03PYFIg&zoom=5&maptype=roadmap&frame=false&sensor=false&markers="+latitude+","+longitude+",green";

  document.getElementById("status").innerHTML = "<h1>Searching for results for lat:"+latitude+",lng:"+longitude+"...</h1>";
  document.getElementById("results").innerHTML = "";
  document.getElementById("postcode").value = "";

  findResults(lat,lng);
}

var localSearch=null;
function findLocationForQuery(query, callbackFunction) {
  
  if(localSearch==null)
  {
    localSearch = new google.search.LocalSearch();
  }

  localSearch.setSearchCompleteCallback(null,
    function() {
      
      if (localSearch.results[0]) {    
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        callbackFunction(resultLat,resultLng);
      }else{
        ui.showAlert(query+" not found!");
      }
    });  
    
  localSearch.execute(query+ ", UK");
}

var lat = null;
var lng = null;
function findResults(latitude,longitude)
{
  lat=latitude;
  lng=longitude;

  service = "/RenSMARTSystem/Servcies?service=/RenSMARTSystem/Search/Service&action=doSearch&latitude="+latitude+"&longitude="+longitude;
  //alert(service);

  data = ajax.doGet(service,true);
  result = eval( data ).result;

  displayLocationInformation(latitude,longitude,result)

  displaySolarInformation(latitude,longitude,result);

  displayWindInformation(latitude,longitude,result);

  prepareInfo();

  markAsFinished();
}

function displayLocationInformation(latitude,longitude,result)
{
  document.getElementById("locationMap").style.display="block";
  googleMap.map.checkResize();
  googleMap.map.setCenter(new GLatLng(latitude,longitude));
  googleMap.map.setZoom(15);

  googleMap.latitude = latitude;
  googleMap.longitude = longitude;
  googleMap.dragMarker.setPoint( new GLatLng(googleMap.latitude, googleMap.longitude) );

  document.getElementById("location").innerHTML="<br/><h3>Results for "+query+"</h3>Location Latitude:"+latitude+" Longitude:"+longitude+" <input type=\"button\" value=\"Save\" onclick=\"saveLocation("+latitude+","+longitude+");return false;\"><br/>";
}

function displayWindInformation(latitude,longitude,result)
{
  var html = fileManager.loadFile("/Search","wind-template.wiki");

  projectLength = result.windInfo.financialProjectionHeader.years;
  
  html = html.replace(/&latitude;/g, latitude );
  html = html.replace(/&longitude;/g, longitude );

  html = html.replace(/&rensmartStars;/g, formatRensmartStars(result.windProfile.rensmartStars) );

  html = html.replace(/&windSpeed;/g, formatWindSpeed(result.windProfile.averageSpeed) );
  
  html = html.replace(/&windPower;/g, formatRenewableEnergy(result.windProfile.averagePower*24*365) );

  html = html.replace(/&annualwindPower;/g, formatPower(result.windProfile.averagePower*365) );

  html = html.replace(/&systemCost;/g, formatPounds(result.windInfo.financialProjectionHeader.systemInstallationCost) );

  html = html.replace(/&paybackTime;/g,result.windInfo.financialProjectionHeader.payBackYearNumber );

  html = html.replace(/&ROI;/g,formatPercentage(result.windInfo.financialProjectionHeader.ROI) );

  html = html.replace(/&carbon;/g, formatPower(result.windInfo.financialProjectionHeader.windEnergy*0.43) );

  html = html.replace(/&windGenerated;/g, formatPower(result.windInfo.financialProjectionHeader.windEnergy) );

  html = html.replace(/&tariff;/g, formatPence(result.windInfo.financialProjectionHeader.windFITariff) );

  html = html.replace(/&generated;/g,formatPower(result.windInfo.financialProjectionHeader.windEnergy) );

  html = html.replace(/&generatedYearly;/g,formatPower(result.windInfo.financialProjectionHeader.windEnergy/projectLength) );

  html = html.replace(/&exported;/g,formatPower(result.windInfo.financialProjectionHeader.exportedEnergy) );

  html = html.replace(/&exportedYearly;/g,formatPower(result.windInfo.financialProjectionHeader.exportedEnergy/projectLength) );

  html = html.replace(/&usedValue;/g,formatPounds(result.windInfo.financialProjectionHeader.usedValue) );

  html = html.replace(/&exportedValue;/g,formatPounds(result.windInfo.financialProjectionHeader.exportValue) );

  html = html.replace(/&tariffValue;/g,formatPounds(result.windInfo.financialProjectionHeader.windFITValue) );

  html = html.replace(/&years;/g,projectLength );

  html = html.replace(/&maintenanceCost;/g,formatPounds(result.windInfo.financialProjectionHeader.maintenanceCost) );
  html = html.replace(/&totalRevenue;/g,formatPounds(result.windInfo.financialProjectionHeader.accumulatedTotal) );

  appendResult(html);
}

function displaySolarInformation(latitude,longitude,result)
{
  var html = fileManager.loadFile("/Search","solar-template.wiki");

  projectLength = result.solarInfo.financialProjectionHeader.years;
  
  html = html.replace(/&latitude;/g, latitude );
  html = html.replace(/&longitude;/g, longitude );

  html = html.replace(/&rensmartStars;/g, formatRensmartStars(result.solarProfile.rensmartStars) );

  html = html.replace(/&solarPower;/g, formatRenewableEnergy(result.solarProfile.averagePower) );

  html = html.replace(/&annualSolarPower;/g, formatPower(result.solarProfile.averagePower*365) );

  html = html.replace(/&systemCost;/g, formatPounds(result.solarInfo.financialProjectionHeader.systemInstallationCost) );

  html = html.replace(/&paybackTime;/g,result.solarInfo.financialProjectionHeader.payBackYearNumber );

  html = html.replace(/&ROI;/g,formatPercentage(result.solarInfo.financialProjectionHeader.ROI) );

  html = html.replace(/&carbon;/g, formatPower(result.solarInfo.financialProjectionHeader.solarEnergy*0.43) );

  html = html.replace(/&solarGenerated;/g, formatPower(result.solarInfo.financialProjectionHeader.solarEnergy) );

  html = html.replace(/&tariff;/g, formatPence(result.solarInfo.financialProjectionHeader.solarFITariff) );

  html = html.replace(/&generated;/g,formatPower(result.solarInfo.financialProjectionHeader.solarEnergy) );

  html = html.replace(/&generatedYearly;/g,formatPower(result.solarInfo.financialProjectionHeader.solarEnergy/projectLength) );

  html = html.replace(/&exported;/g,formatPower(result.solarInfo.financialProjectionHeader.exportedEnergy) );

  html = html.replace(/&exportedYearly;/g,formatPower(result.solarInfo.financialProjectionHeader.exportedEnergy/projectLength) );

  html = html.replace(/&usedValue;/g,formatPounds(result.solarInfo.financialProjectionHeader.usedValue) );

  html = html.replace(/&exportedValue;/g,formatPounds(result.solarInfo.financialProjectionHeader.exportValue) );

  html = html.replace(/&tariffValue;/g,formatPounds(result.solarInfo.financialProjectionHeader.solarFITValue) );

  html = html.replace(/&years;/g,projectLength );

  html = html.replace(/&maintenanceCost;/g,formatPounds(result.solarInfo.financialProjectionHeader.maintenanceCost) );
  html = html.replace(/&totalRevenue;/g,formatPounds(result.solarInfo.financialProjectionHeader.accumulatedTotal) );

  appendResult(html);
}

function markAsFinished()
{
 searching=false;
 document.getElementById("status").innerHTML = "<center><hr/><br/><h2>Search Complete. Thank you for using RenSMART search</h2></center>"
}

function appendResult(html)
{
  document.getElementById("results").innerHTML += html+"<br/>";
}

function saveLocation(latitude,longitude)
{
  user = ajax.doGet("/OpenForum/Actions/GetUser","pageName=dummy");
  if(user.toLowerCase()=="anon")
  {
    ui.showAlert("","You need to be a RenSMART member to save locations.<br/>Registration is FREE and simple. Please register <a href=\"/Register\">here</a>.");
  }

  siteName = prompt("Enter a name for this location",document.getElementById("postcode").value);
  if(siteName==null || siteName=="")
  {
    return;
  }

  data = ajax.doCall("/RenSMARTSystem/Servcies?service=/Projects/Service&action=addSiteToPool&name="+siteName+"&latitude="+latitude+"&longitude="+longitude,true);

  if(data.result=="OK")
  {
    ui.showAlert("Saved","Location "+siteName+" has been saved for you.<br/> You will see it listed on your home page <href=\"/MyHomePage\">here</a>");
  }
  else
  {
    ui.showAlert("Error","Location "+siteName+" failed to be saved.");
  }
}

var infoRenSMARTStarRatingLoaded = false;
var infoEstimatedSolarPowerLoaded = false;
var infoCleanEnergyCashBackLoaded = false;
var infoReturnOnInvestmentLoaded = false;
var infoKWHToCO2ConversionLoaded = false;
var infoGridTieConnectionLoaded = false;
var infoEstimatedWindPowerLoaded = false;

function prepareInfo()
{
}

function openSolarPlanner()
{
  window.location = "/Tools/SolarPlanner?longitude="+lng+"&latitude="+lat+"&query="+document.getElementById("postcode").value;
}
