function toggleMapPanel(theLink){
  if (theLink.className == 'hwFabExpandMap') {
    theLink.className = 'hwFabShrinkMap';

    var allDivs = document.getElementsByName("hwFabMapPanel");;
    for (var i = 0; i < allDivs.length; i++) {
      allDivs[i].className = "hwFabShowMap";
    }

    document.getElementById('shownMap').value = true;
    document.getElementById('mapState').value = true;

    setMapState(true);
    loadMapData();
  } else if (theLink.className == 'hwFabShrinkMap') {
    theLink.className = 'hwFabExpandMap';

    var allDivs = document.getElementsByName("hwFabMapPanel");;
    for (var i = 0; i < allDivs.length; i++) {
      allDivs[i].className = "hwFabHideMap";
    }

    document.getElementById('mapState').value = false;
    setMapState(false);
  }
}

function GetCurrencyValue (currency) {
  for (var i = 0; i < document.theForm.elements.length; i++) {
    if (document.theForm.elements[i].name == 'FABCurrency') {
      for (var j = 0; j < document.theForm.elements[i].length; j++) {
        if (document.theForm.elements[i].options[j].value == currency) {
          document.theForm.elements[i].options[j].selected = true;
        }
      }
    }
  }
}

function registerCurrency (currency) {
  var rand = Math.random();

  if (document.images.currencyImage) document.images.currencyImage.src = '/getcurrency_img.php?Currency=' + currency + '&r=' + rand;
}

function setMapState (mapOpen) {
  var registerMap = new Image();
  var rand = Math.random();

  registerMap.src = '/ajax/setmapstatus.php?mapStatus=' + mapOpen + '&r=' + rand;
}

function processMapState() {
  var mapState = document.getElementById ("mapState");
  var checkMapState = getRequestResponse ();
  var theLink = document.getElementById ("hwFabMapBtn");

  // alert ("mapState: " + mapState.value);
  // alert ("checkMapState: " + checkMapState);
  // alert ("theLink: " + theLink.className);

  // current map state doesnt match expected
  if (mapState.value != checkMapState) {
    toggleMapPanel (theLink);
  // map says 'close' so is open, but map state is closed
  } else if (theLink.className == 'hwFabShrinkMap' && mapState.value == 'false') {
    toggleMapPanel (theLink);
  // map says 'open' so is closed, but map state is open
  } else if (theLink.className == 'hwFabExpandMap' && mapState.value == 'true') {
    toggleMapPanel (theLink);
  }

  return (false);
}

function SwitchTypes(element, option) {
  if (element.checked == true && option == 'all') {
    document.theForm.SelPropTypes_HOSTEL.checked = true;
    document.theForm.SelPropTypes_HOTEL.checked = true;
    document.theForm.SelPropTypes_GUESTHOUSE.checked = true;
    document.theForm.SelPropTypes_APARTMENT.checked = true;
    document.theForm.SelPropTypes_CAMPSITE.checked = true;
    document.theForm.SelPropTypes_FAVOURITES.checked = false;

    pageTracker._trackEvent("findabed refine", "property", "all-on");
  } else {
    document.theForm.SelPropTypes_HOSTEL.checked = false;
    document.theForm.SelPropTypes_HOTEL.checked = false;
    document.theForm.SelPropTypes_GUESTHOUSE.checked = false;
    document.theForm.SelPropTypes_APARTMENT.checked = false;
    document.theForm.SelPropTypes_CAMPSITE.checked = false;

    if (option == 'favourites') {
      pageTracker._trackEvent ("findabed refine", "property",  (option + "-" + ((element.checked) ? "on" : "off")));
      document.theForm.ShowAll.checked = false;
    } else {
      pageTracker._trackEvent("findabed refine", "property", "all-off");
    }
  }
}

function SwitchMainTypes(element, option) {
  if (element.checked == false) {
    document.theForm.ShowAll.checked = false;
  }

  pageTracker._trackEvent("findabed refine", "property", (option + "-" + ((element.checked) ? "on" : "off")));
}

function trackRoomChanges(element, option) {
  pageTracker._trackEvent("findabed refine", "roomtypes", (option + "-" + ((element.checked) ? "on" : "off")));
}

function trackDistrictChanges(element, option) {
  pageTracker._trackEvent("findabed refine", "districts", (option + "-" + ((element.checked) ? "on" : "off")));
}

function trackFacilitiesChanges(element, option) {
  pageTracker._trackEvent("findabed refine", "facilities", (option + "-" + ((element.checked) ? "on" : "off")));
}

function toggleMoreRefineOptions(theLink, elemId1, elemId2, elemId3) {
  if (theLink.className == 'refineOff') {
    theLink.className = 'refineOn';

    document.getElementById(elemId1).className = 'showRefineOptions';  
    document.getElementById(elemId2).className = 'showRefineOptions';
    document.getElementById(elemId3).className = 'showRefineOptions';

    document.getElementById('advancedSet').value = "True";

    pageTracker._trackEvent("findabed refine", "facilities", "viewall-on");
  } else if (theLink.className == 'refineOn') {
    theLink.className = 'refineOff';

    document.getElementById(elemId1).className = 'hideRefineOptions';
    document.getElementById(elemId2).className = 'hideRefineOptions';
    document.getElementById(elemId3).className = 'showRefineOptions';

    document.getElementById('advancedSet').value = "False";

    pageTracker._trackEvent("findabed refine", "facilities", "viewall-off");
  }
}

function hasClass(target, theClass) {
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  if (target) {
    if (pattern.test(target.className)) {
      return true;
    }
  }

  return false;
}

function addClass(target, theClass) {
  if (!hasClass(target, theClass)) {
    if (target.className == "") {
      target.className = theClass;
    } else {
      target.className += " " + theClass;
    }
  }
}

function removeClass(target, theClass) {
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  target.className = target.className.replace(pattern, "$1");
  target.className = target.className.replace(/ $/, "");
}

function getHostelListing(obj) {
  do {
    obj = obj.parentNode;
  } while (!hasClass(obj, "hostelListing"));

  return obj;
}

function addPropertyAsFavourite(theLink, theID) {
  if (theLink) {
    var hostelListing = getHostelListing(theLink);
    var marker = markerArray[theID];

    if (hostelListing) {
      if (hasClass(hostelListing, "favOff")) {
        removeClass(hostelListing, "favOff");
        addClass(hostelListing, "favOn");
        theLink.title = "Remove from favourites";

        pageTracker._trackEvent("findabed refine", "favourites", "favourite-add");
        makeAjaxRequest('/ajax/favourites.php?a=a&id=' + theID);

        if (marker) {
          if (window.favHostels) {
            window.favHostels[theID] = theID;
          }

          marker.setImage("/images/icons/hw_icon_selected.png");
        }
      } else if (hasClass(hostelListing, "favOn")) {
        removeClass(hostelListing, "favOn");
        addClass(hostelListing, "favOff");
        theLink.title = "Add to favourites";

        pageTracker._trackEvent("findabed refine", "favourites", "favourite-delete");
        makeAjaxRequest('/ajax/favourites.php?a=d&id=' + theID);

        if (marker) {
          if (window.favHostels && window.favHostels[theID]) {
            delete window.favHostels[theID];
          }

          marker.setImage("/images/icons/hw_icon.png");
        }
      }
    }
  }

  return false;
}

var map;
var markerArray = new Array();
var markerHtml = new Array();
var initialCentre;

function buildPropIcon () {
  propIcon = new GIcon();
  propIcon.image            = 'http://www.hostelworld.com/images/icons/hw_icon.png';
  propIcon.shadow           = 'http://www.hostelworld.com/images/icons/hw_icon_shadow.png';
  propIcon.iconSize         = new GSize(30,32);
  propIcon.shadowSize       = new GSize(59, 32);
  propIcon.iconAnchor       = new GPoint(6, 18);
  propIcon.infoWindowAnchor = new GPoint(9, 6);
  propIcon.imageMap         = [1,1, 1,18, 6,18, 6,21, 10,18, 20,18, 20,1, 1,1];

  return propIcon;
}

function createMarker (map, point, propIcon, html, hostelName) {
  var marker = new GMarker(point, {icon: propIcon, title: hostelName});

  if (typeof(MochiKit) == 'undefined' || !MochiKit.DOM.$('microMapStreetContainer')) {  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });}

  return marker;
}

function addPlotCityHostelsMap(divID,centerLat,centerLng,zoomLevel) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById(divID));
    buildPropIcon();

    var centerPoint = new GLatLng(centerLat, centerLng);
    initialCentre = centerPoint;
    map.setCenter(centerPoint, zoomLevel);
  
    window.mapControls = {};
    window.mapControls['largeC'] = new GLargeMapControl(); 
    window.mapControls['menuC'] = new GMenuMapTypeControl();

    map.addControl(window.mapControls['largeC']); 
    map.addControl(window.mapControls['menuC']);

    // add marker for every hostel we have the co-ords of.
    var lat, lng, hnum, hname;
    var point;
    var html;
    for (var i = 4; i < arguments.length; ) {
      hnum  = arguments[i]; i++;
      hname = arguments[i]; i++;
      lat   = arguments[i]; i++;
      lng   = arguments[i]; i++;
      html  = arguments[i]; i++;

      point = new GLatLng(lat, lng);

      marker = createMarker(map, point, propIcon, html, hname);
      map.addOverlay(marker);

      markerArray[hnum] = marker;
      markerHtml[hnum] = html;

      if (window.favHostels && window.favHostels[hnum]) {
        marker.setImage ("/images/icons/hw_icon_selected.png");
      }
    }

    initStreetView();
  }
}

function MoveMap (xVal, yVal, hnum) {
  map.panTo(markerArray[hnum].getPoint(), 13);

  if (markerArray[hnum]) {
    markerArray[hnum].openInfoWindowHtml(markerHtml[hnum]);
  }
}

function initStreetView () {
  //check to see if we have street view in the area
  var client = new GStreetviewClient();

  client.getNearestPanoramaLatLng(initialCentre,
    function (latLng) {
      // if we havent got any near here
      if (!latLng) {
        return;
      };
                  
      showStreetviewControl();
      window.hasStreetView = true;

      MochiKit.Signal.connect(document, "streetview_from_bubble",
        function () {
          if (!window.streetviewOn) { 
            toggleStreetview();
          }

          updateManPosition(window.lastBubbleLatLng);
        }
      );

      GEvent.addListener(map, "infowindowbeforeclose",
        function() {
          if (window.streetViewObj) {
            map.addControl(window.mapControls['largeC']);
            window.streetViewObj.remove();  

            MochiKit.Style.setStyle("streetviewControl", {"display": "block"});
          }
        }
      );
    }
  );
}

function showStreetviewControl () {
  // show street view control and connect click to toggle
  // of blue overlay and mini me (little man on map)
  MochiKit.Style.setStyle("streetviewControl", {"display":"block"});
  MochiKit.Signal.connect("streetviewControl", "onclick", toggleStreetview);
}

function toggleStreetview () {
  // show the blue overlay
  if (!window.streetviewOverlay) {
    window.streetviewOverlay = new GStreetviewOverlay();

    GEvent.addListener(map, "click",
      function (overlay, latlng) {
        if (!latlng || !window.streetviewOn) {
          return;
        }

        updateManPosition (latlng);
      }

    );
  }

  if (!window.streetviewMiniMe) {
    // create the minime
    window.streetviewMiniMe = '';

    // get the default icon and create a new one based on it
    var miniMeIcon              = new GIcon();
    miniMeIcon.image            = "/images/minime.png";
    miniMeIcon.iconAnchor       = new GPoint(20, 20);
    miniMeIcon.infoWindowAnchor = new GPoint(25, 25);
    miniMeIcon.iconSize         = new GSize(49, 52);

    window.streetviewMiniMe = new GMarker (initialCentre, {title: 'Street View', icon: miniMeIcon, draggable: true, bouncy: true});
    GEvent.addListener(window.streetviewMiniMe, "dragend", onDragEnd);
    GEvent.addListener(window.streetviewMiniMe, "click",
      function () {
       openStreetviewAtPos(window.streetviewMiniMe.getLatLng());
      }
    );
  }

  if (!window.streetviewOn) {
    map.addOverlay(window.streetviewOverlay);
    map.addOverlay(window.streetviewMiniMe);
    window.streetviewOn = true;
  } else {
    map.removeOverlay(window.streetviewOverlay);
    map.removeOverlay(window.streetviewMiniMe);
    window.streetviewOn = false;
  }
}

function updateManPosition (latlng) {
  window.streetviewMiniMe.setLatLng(latlng);
  openStreetviewAtPos(latlng);
}

function cleanup () {
}

function openStreetviewAtPos (latlng) {
  map.openInfoWindowHtml(latlng, "<div id='microMapStreetContainer' style='position:relative;height:300px;width:340px;border: 1px solid #000;padding:3px;'><div id='microMapStreetView' style='height:300px;width: 340px;'></div></div>", {onCloseFn: cleanup});

  // hide the existing map controls
  MochiKit.Async.callLater(1,
    function() {
      // hide controls
      map.removeControl(window.mapControls['largeC']);

      if (window.streetViewObj) {
        window.streetViewObj.setContainer(document.getElementById("microMapStreetView"));  
      } else {
        window.streetViewObj = new GStreetviewPanorama(document.getElementById("microMapStreetView"));

        GEvent.addListener(window.streetViewObj, "initialized", onNewLocation);
        GEvent.addListener(window.streetViewObj, "yawchanged",  onYawChange);
        GEvent.addListener(window.streetViewObj, "error",
          function (errVal) {
            if (errVal == 600) {
              MochiKit.DOM.$("microMapStreetView").innerHTML = "There doesn't seem to be Streetview information available in this location. Place the marker on a street outlined with blue to load Google Streetview.";
            } else {
              MochiKit.DOM.$("microMapStreetView").innerHTML = "Your browser does not have Flash installed or does not support it. Please install Flash or change to a browser which supports Flash.";
            }
          }
        );
      }

      // show flash viewer
      window.streetViewObj.setLocationAndPOV(latlng);
    }
  );
}

function onNewLocation (location) {
  window.streetviewMiniMe.setLatLng(location.latlng);

  // Get the original x + y coordinates
  var iw = map.getPane(G_MAP_FLOAT_PANE).firstChild;
  var originalX = parseInt(iw.style.left);
  var originalY = parseInt(iw.style.top);

  // Move the infowindow 
  map.getInfoWindow().reposition(location.latlng, new GSize(10, -10));

  // Get the new x + y coordinates
  var iw = map.getPane(G_MAP_FLOAT_PANE).firstChild;
  var newX = parseInt(iw.style.left);
  var newY = parseInt(iw.style.top);

  // Re-position the map to show the infowindow in full
  map.getDragObject().moveBy(new GSize(-(newX - originalX), -(newY - originalY))); 
}

function onYawChange (newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;

  if (newYaw < 0) {
    newYaw += 360;
  }

  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";

  window.streetviewMiniMe.setImage(guyImageUrl);
}

function onDragEnd (latlng) {
  openStreetviewAtPos(latlng);  
}

function popup2(url) {
  window.open(url,"null","height=500,width=610,status=no,location=no,resizable=yes,scrollbars=yes,fullscreen=no,top=200,left=200");
}
