/**
 * @author scott
 */
var mapwidth = 680;
var mapheight = 220;
var containerId = "map";
var deflat = -33.83209212904;
var deflong = 151.184994183803;
var latlng;
var mapzoom = 12;
var geocoder;
var map;
var marker;
var infowindow;
var address, latitude, longitude, zoom, pname;
var streetView = false;
var photos = false;
var radius = 5;
var bounds;
var panorama;
var svposition;

/**
 * initGMap displays a Google Map for a specified address or lat/lon pair.
 * Optionally displays a Google StreetView for the map.
 * Optionally displays a photo widget for the local area.
 * 
 * @param {String} addressQ The street address of the property
 * @param {Float} latitudeQ The decimal latitude of the property
 * @param {Float} longitudeQ The decimal longitude of the property
 * @param {Integer} zoomQ The zoom level for the map. Range 0-20. Default 16
 * @param {String} pnameQ The name of the property
 * @param {Integer} widthQ The pixel width of the map. Default 640
 * @param {Integer} heightQ The pixel height of the map. Default 480
 * @param {Boolean} streetViewQ Display Google Street View for the property. Default true
 * @param {Boolean} photosQ Display Panoramia photos for the area. Default true
 * @param {Integer} radiusQ Radius (km) around property to gather photos from. Options: 5,10,20,40,80,160,320,640. Default 40
 * 
 * @returns A Google Map
 * @returns A Google StreetView
 * @returns A Panoramia Photo Widget
 */
function initGMap(addressQ, latitudeQ, longitudeQ, zoomQ, pnameQ, widthQ, heightQ, streetViewQ, photosQ, radiusQ){
  address = addressQ;
  latitude = latitudeQ;
  longitude = longitudeQ;
  zoom = zoomQ;
  pname = pnameQ;
  mapwidth = widthQ;
  mapheight = heightQ;
  streetView = streetViewQ ? true : false;
  photos = photosQ ? true : false;
  if(radiusQ)
    radius = radiusQ;
  setTimeout('initialise()',1000);
}

function initialise() {
  container = document.getElementById(containerId);
  container.style.width = mapwidth+"px";
  container.style.height = mapheight+"px";
  if (zoom)
    mapzoom = zoom;
  var myOptions = {
    zoom: mapzoom,
    center: new google.maps.LatLng(deflat, deflong),
    scaleControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(container, myOptions);
  
  var contentString = '<div id="infowindowContent" style="height:90px;">'+
        '<h2>' + pname + '</h2>'+
        '<p>' + address + '</p>'+
        '</div>';

  infowindow = new google.maps.InfoWindow({
      content: contentString,
      maxWidth: 200
  });
  
  if(latitude.length == 0 || longitude.length == 0){
    if (address.length > 0) {
      geocoder = new google.maps.Geocoder();
      if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            svposition = results[0].geometry.location;
            map.setCenter(svposition);
            marker = new google.maps.Marker({
                map: map, 
                position: svposition,
                title: pname
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }
    }
  } else {
    svposition = latlng = new google.maps.LatLng(latitude, longitude);
    map.setCenter(latlng);
    marker = new google.maps.Marker({
        map: map, 
        position: latlng,
        title: pname
    });
  }
  
  if (streetView == true) setTimeout('addStreetView()',850);
  
  if (photos == true) setTimeout('addPanaramio()',2500);
  
  setTimeout('addEars()',2000);
  
}

function addStreetView(){
  // do the streetview thing
  $('#' + containerId)
  .parent()
  .append('<div id="pano" style="width:' + mapwidth + 'px;height:' + mapheight + 'px;border:1px solid #000;margin:0 auto;"></div>')
  .append('<p class="mapnotes" style="width:' + mapwidth + 'px;margin:5px auto;padding:0;font-size:1em;">Please note that the Street View provided by Google may not be an accurate or current representation of the accommodation.<br />The photos provided in the property listing will be more accurate and current.');
  $('#pano, .mapnotes').hide();
  var panoramaOptions = {
    position: svposition
  };
  panorama = new  google.maps.StreetViewPanorama(document.getElementById("pano"), panoramaOptions);
  google.maps.event.addListener(panorama, 'pano_changed', function() { 
    if (panorama.getPano()) { 
      $('#pano, .mapnotes').show();
      panorama.setVisible(true);
    } 
  });
  //map.setStreetView(panorama);
}

function addPanaramio(){
  var panoImg = '<div id="div_attr_ex" style="height:430px;"><div id="div_attr_ex_list"><a href="http://www.panoramio.com">Panoramio - Photos of the World</a></div>';
  panoImg += '<div id="div_attr_ex_photo"><a href="http://www.panoramio.com">Panoramio - Photos of the World</a></div>';
  panoImg += '<div id="div_attr_ex_attr"></div><div class="panoramio-wapi-tos">AccommodationGuru does not control these photos and their titles.</div></div>';
  $('#' + containerId).parent().append(panoImg);
  // set the lat/lng bounds
  // need to funck up the zooms to get the bounds
  map.setZoom(radToZoom(radius));
  bounds = map.getBounds();
  map.setZoom(mapzoom);
  
  boundsArr = bounds.toUrlValue(2).split(',');
  var thearea = {'sel': 'panoramio.PhotoSet.ALL','rect': {'sw': {'lat': boundsArr[0], 'lng': boundsArr[1]}, 'ne': {'lat': boundsArr[2], 'lng': boundsArr[3]}}};
  //var thearea = {'tag': 'sydney'};
  var attr_ex_photo_options = {
    'width': 540,
    'height': 400,
    'attributionStyle': panoramio.tos.Style.HIDDEN};
  var attr_ex_photo_widget = new panoramio.PhotoWidget(
      'div_attr_ex_photo', thearea, attr_ex_photo_options);

  var attr_ex_list_options = {
    'width': 100,
    'height': 400,
    'columns': 1,
    'rows': 5,
    'croppedPhotos': true,
    'disableDefaultEvents': [panoramio.events.EventType.PHOTO_CLICKED],
    'orientation': panoramio.PhotoListWidgetOptions.Orientation.VERTICAL,
    'attributionStyle': panoramio.tos.Style.HIDDEN};
  var attr_ex_list_widget = new panoramio.PhotoListWidget(
    'div_attr_ex_list', thearea, attr_ex_list_options);
  
  var attr_ex_attr_options = {'width': 540};
  var attr_ex_attr_widget = new panoramio.TermsOfServiceWidget(
    'div_attr_ex_attr', attr_ex_attr_options);
 
  function onListPhotoClicked(event) {
    var position = event.getPosition();
    if (position !== null) attr_ex_photo_widget.setPosition(position);
  }
  panoramio.events.listen(
    attr_ex_list_widget, panoramio.events.EventType.PHOTO_CLICKED,
    function(e) { onListPhotoClicked(e); });
  attr_ex_photo_widget.enablePreviousArrow(false);
  attr_ex_photo_widget.enableNextArrow(false);
 
  attr_ex_photo_widget.setPosition(0);
  attr_ex_list_widget.setPosition(0);
  
  setTimeout('showPhotos()',5000);
}

function showPhotos(){
  if ($('.panoramio-wapi-loaded-img').length == 0) {
    $('#div_attr_ex').hide();
  }
}

function addEars(){
  google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
  google.maps.event.addListener(infowindow, 'closeclick', function() {
      map.setCenter(marker.getPosition());
    });
}

function radToZoom(rad) {
  // converts supplied radius to mapzoom
  var zoomArr = new Array();
  zoomArr['5'] = 14;
  zoomArr['10'] = 13;
  zoomArr['20'] = 12;
  zoomArr['40'] = 11;
  zoomArr['80'] = 10;
  zoomArr['160'] = 9;
  zoomArr['320'] = 8;
  zoomArr['640'] = 7;
  
  return zoomArr[rad];
}