/**
 * @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;
var markerImagePath;

var $tabs, this_tab_title, this_tab_content;
var tab_counter = 2;

/**
 * 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, markerImagePathQ ){
  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;
  }
  if ( markerImagePathQ ) {
	  markerImagePath = markerImagePathQ;  
  }
  
  setTimeout('initialiseMap()',1000);
}

function initialiseMap() {
  var container = document.getElementById(containerId);
  container.style.width = mapwidth+"px";
  container.style.height = mapheight+"px";
  container.style.border = "1px solid #000";
  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.replace(/\+/g, ' '); + '</p>'+
        '</div>';

  infowindow = new google.maps.InfoWindow({
      content: contentString,
      maxWidth: 200
  });
  var icon = new google.maps.MarkerImage( 
	    markerImagePath + '/roundpin-image.png',
	    new google.maps.Size(20,34),
	    new google.maps.Point(0,0),
	    new google.maps.Point(10,34)
	  );
	
	  var shadow = new google.maps.MarkerImage(
	    markerImagePath + '/roundpin-shadow.png',
	    new google.maps.Size(40,34),
	    new google.maps.Point(0,0),
	    new google.maps.Point(10,34)
	  );
  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({
    	icon: icon,
    	shadow: shadow,
        map: map, 
        position: latlng,
        title: pname
    });
  }
  
  if (streetView == true) setTimeout('addStreetView()',850);
  
  if (photos == true) setTimeout('addPanaramio()',2500);
  
  setTimeout('addEars()',2000);
  
  // tabs init with a custom tab template and an "add" callback filling in the content
  $tabs = $('#' + containerId)
  .parent()
  .parent()
  .tabs({
			tabTemplate: "<li><a href='#{href}'>#{label}</a></li>",
			add: function( event, ui ) {
				var tab_content = this_tab_content;
				$( ui.panel ).append( tab_content );
			}
		});
  
}

function addStreetView(){
  // do the streetview thing
  var svtab = $('<div id="tab-'+tab_counter+'" />');
  $('#' + containerId)
  .parent()
  .parent()
  .append(svtab);
  
  $(svtab)
  .append('<div id="pano" style="width:' + mapwidth + 'px;height:' + mapheight + 'px;border:1px solid #000;margin:0 auto;"></div>')
  .append('<p id="auto_pan_pano"><input type="checkbox" /> Auto rotate street view</p>')
  .append('<p class="mapnotes" style="width:' + mapwidth + 'px;margin:10px auto;padding:0;font-size:12px;">Please note that the Street View provided by Google may not be an accurate or current representation of the accommodation. The photos provided in the property listing will be more accurate and current.');
  $('#pano, #auto_pan_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, #auto_pan_pano, .mapnotes').show();
      panorama.setVisible(true);
    } 
  });
  //map.setStreetView(panorama);
  var f;
  f = window.setInterval(function(){if($("#auto_pan_pano input").is(":checked")){var i=panorama.getPov();i.heading+=2;panorama.setPov(i)}},200);
  // add the tab
  this_tab_title = "Street View";
  this_tab_content = svtab;
  addTab();
  
}

function addPanaramio(){
  var panotab = $('<div id="tab-pano" />');
  $('#' + containerId)
  .parent()
  .parent()
  .append(panotab);
  
  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>';
  $(panotab).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);
  
  // add the tab
  this_tab_title = "Image View";
  this_tab_content = panotab;
  addTab();
}

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];
}

// actual addTab function: adds new tab using the title input from the form above
function addTab() {
  var tab_title = this_tab_title;
  $tabs.tabs( "add", "#tabs-" + tab_counter, tab_title );
  tab_counter++;
}
