/* DMR Javascript */
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.slice(0, str.length) == str;
  };
}

$(function () {
  if ($.fn.fullsize) {
    $('img').fullsize();
  }

  $('#ctl00_lstRegions').sb({
    fixedWidth: true
  });

  $('#region select').change(function () {
    var self = $(this)
    if (self.val().startsWith('http')) {
      window.location = self.val();
      return false;
    } else {
      var regionName = $('#region select option:selected').text();
      regionName = regionName.replace(/[\s\-]/gi, '').replace(/\//, '-');
      var loc = window.location;

      var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);

      pathName = '/';

      var fp = loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
      window.location = fp + "Regions/" + regionName + ".aspx?regionid=" + self.val();
      return false;
    }
  });

  if (location.href.indexOf("full=true") > -1) {
    $.cookie('dmrLanding', 'full', { expires: 99999 });
  }
  if ($('h1:first').text().trim() == 'Industry Information') {
    $('#mnuMobileAccess').addClass('selected');
  }
  $("#lnkQuick").click(function () {
    $.cookie('dmrLanding', 'quick', { expires: 999999 });
  });
  $("#aspnetForm").attr("action", $("#aspnetForm").attr("action").replace("/.aspx", "/"));
  $('.searchBox input:text').attr('title', 'Enter Keywords');
  $('#events,#conditions,#search-events').tabs();
  $('#accordion').accordion({ autoHeight: false });
  $('.watermark').focus(function () {
    var self = $(this);
    self.removeClass('watermark');
    if (self.val() == self.attr('title')) {
      self.val('').select();
    }
  }).
		blur(function () {
		  var self = $(this);
		  if ($.trim(self.val()) == '') {
		    self.addClass('watermark').val(self.attr('title'));
		  }
		}).
		each(function () {
		  var self = $(this);
		  self.val(self.attr('title'));
		});
});

function OnAliasReponse(result) {
  $(txtRoad).val(result);
}

function OnAliasReponseForTravelDate(result) {
  $(txtTravelRoad).val(result);
}
// Search for an event location and display it on the map
function ShowLocation() {

  if (!Page_ClientValidate('Location')) {
    return false;
  }

  var suburbLga = $(txtSuburb).val().split(' - ');

  var aliasRoad = $(txtRoad).val();
  if (aliasRoad.indexOf("[") > -1) {
    aliasRoad = aliasRoad.substring(aliasRoad.indexOf("[") + 1, aliasRoad.indexOf("]"));
  }

  if (aliasRoad.indexOf("(") > -1) {
    aliasRoad = aliasRoad.substring(0, aliasRoad.indexOf("(") - 1);
  }

  var service = new DMR.MapService();
  service.AliasMe(aliasRoad, suburbLga[0], OnAliasReponse);

  return HandleLocation(suburbLga[0], aliasRoad, suburbLga[1],
        function (pos) {
          if (pos) {
            decartamap.centerOnPosition(pos, function () {
              zoom.zoomToNewLevel(6);
              updateMapZoomAndPos();
              getClosureLines();
            });
          }
        });

}

// Search for an event location and display it on the events page
function GoLocation() {
  if (!Page_ClientValidate('Location')) {
    return false;
  }

  var suburbLga = $(txtSuburb).val().split(' - ');

  var aliasRoad = $(txtRoad).val();
  if (aliasRoad.indexOf("[") > -1) {
    aliasRoad = aliasRoad.substring(aliasRoad.indexOf("[") + 1, aliasRoad.indexOf("]"));
  }

  if (aliasRoad.indexOf("(") > -1) {
    aliasRoad = aliasRoad.substring(0, aliasRoad.indexOf("(") - 1);
  }

  var service = new DMR.MapService();
  service.AliasMe(aliasRoad, suburbLga[0], OnAliasReponse);

  return HandleLocation(suburbLga[0], aliasRoad, suburbLga[1],
        function (pos) {
          if (pos) {
            $(hidLat).val(pos.lat);
            $(hidLon).val(pos.lon);
            $(btnLocationGoHidden).click();
          }
        });
}

// Search for an event location and display it on the events page with a date
function GoTravelDate() {

  if (!Page_ClientValidate('Travel')) {
    return false;
  }
  var suburbLga = $(txtTravelSuburb).val().split(' - ');

  var aliasRoad = $(txtTravelRoad).val();
  if (aliasRoad.indexOf("[") > -1) {
    aliasRoad = aliasRoad.substring(aliasRoad.indexOf("[") + 1, aliasRoad.indexOf("]"));
  }

  if (aliasRoad.indexOf("(") > -1) {
    aliasRoad = aliasRoad.substring(0, aliasRoad.indexOf("(") - 1);
  }

  var service = new DMR.MapService();
  service.AliasMe(aliasRoad, suburbLga[0], OnAliasReponseForTravelDate);

  return HandleLocation(suburbLga[0], $(txtTravelRoad).val(), suburbLga[1],
        function (pos) {
          if (pos) {
            $(hidLat).val(pos.lat);
            $(hidLon).val(pos.lon);
            $(btnTravelDateHidden).click();
          }
        });
}

// Find the postcode for a suburb and geocode the result
function HandleLocation(suburb, road, lga, callback) {
  var service = new DMR.MapService();
  service.GetPostcodeBySuburb(suburb, function (postcode) {
    geocodeLocation(road, suburb, postcode, lga, 'location', callback);
  }, function (error, userContext, methodName) { $.log(error + '|' + userContext + '|' + methodName); });
  return false;
}

// Geocode the route start and end and process them
function GeocodeRoute(callback) {

  if (!Page_ClientValidate('Route')) {
    return false;
  }


  var startEnd = getStartEnd();

  $('#lblInfo').text('');
  geocodeLocation(startEnd.startRoad, startEnd.startSuburb, startEnd.startPostcode,
            startEnd.startLGA, 'starting point', function (startPos) {
              geocodeLocation(startEnd.endRoad, startEnd.endSuburb, startEnd.endPostcode,
                startEnd.endLGA, 'ending point', function (endPos) {
                  if (startPos && endPos) {
                    callback(startPos, endPos);
                  }
                });
            });
  return false;
};

// Find suburbs along the route and go to events page with these
function HandleRouteSearch(startPos, endPos) {

  var routePoints = [startPos, endPos];
  // Set rules of travel for determining the path of our route, and measurement.
  // Other options could be 'shortest', 'pedestrian', etc.
  var routePreference = new RoutePreference("Shortest", new UOM('KM'), "RMAN");

  routePreference.rule = "maneuver-rules";
  // Bounding box for route geometry - whole of Queensland
  routePreference.generalizationBBox =
        new BoundingBox(new Position(-10, 135), new Position(-30, 155));

  // Generalise by distance in kms
  routePreference.generalizationFactor = LatLon.distHaversine(startPos.lat, startPos.lon, endPos.lat, endPos.lon);
  // Generate our route

  // ************************************************************************************************** //
  // Call deCarta Web Service and generate a list of route points of a given route between two points   //
  // this function call, calls the webservice creates a new instance (routeResponse) type Route and     //
  // populates this response.                                                                           //
  // ************************************************************************************************** //
  new RouteQuery().query(routePoints, routePreference, function (routeResponse) {
    // Simple Error checking
    if (!routeResponse) {
      $('#lblInfo').text('No routes found');
      return;
    }
    var points = [];
    for (i = 0; i < routeResponse.RouteGeometry.length; i++) {
      points.push({ Lat: routeResponse.RouteGeometry[i].lat,
        Long: routeResponse.RouteGeometry[i].lon
      });
    };
    // Add end point back in as generalisation strips it out!?!
    points.push({ Lat: endPos.lat, Long: endPos.lon });
    //new LocationService().GetSuburbs(points, OnSuburbsComplete, OnSuburbsError);
    new DMR.TTIEventService().GetEventIds(points, OnEventIdsComplete, OnEventIdsError);
  });
}
