var mapviewer, geocoder, marker;
var pan_zoom_widget, map_type_widget, overview_widget;
var geocode_status, message, results_panel;
var max_results = 10;
var tdfromname, tdtoname, tdfroma, tdtob;
var hotelname, hotellat, hotellon, searchbtn;
var tdfrom = true;
var results, poibox, routesteps;
var max_zindex = 1000;
var searcher
var rfs = ['id', 'ihotelid', 'name', 'street', 'town', 'pc', 'lat', 'lon', 'istars'];
var resultspanel
var markers = new Array();
var stars5, stars4, stars3;
var filteredresults = new Array();


function showmap() {
	
	var mapwrap = document.getElementById('mapwrap');
	var viewmap = document.getElementById('viewmap');
	
	if (mapwrap) {
		mapwrap.style.display = 'block';
		
		//generatemap();
		
		if (viewmap) {
			viewmap.style.display = 'none';
		}
	}
	
	//**** added 03042009
	geocode_status = document.getElementById( 'geocodestatus' );
	updateGeocodeStatus('startGeocode');
	//*********************
	
	// setup some handles
	mapviewer = new MultimapViewer( document.getElementById( 'mapviewer' ) );
	mapviewer.setOption( 'units', 'km' );
	
	pan_zoom_widget = new MMPanZoomWidget(); 
  mapviewer.addWidget ( pan_zoom_widget );
    
  map_type_widget = new MMMapTypeWidget ();
  mapviewer.addWidget ( map_type_widget );
	
	resultspanel = document.getElementById('resultspanel');
	resultspanel.innerHTML = '';
	
	stars5 = document.getElementById('stars5');
	stars4 = document.getElementById('stars4');
	stars3 = document.getElementById('stars3');
	
	// Register 'open InfoBox' event
	mapviewer.addEventHandler( 'openInfoBox', highlightresult );
	mapviewer.addEventHandler( 'closeInfoBox', closeallresults );
	
	//Collect selected hotel data
	searcher = new MMSearchRequester(showLocs);
	
	search = new MMSearch(); 
  search.return_fields = rfs;
  search.order_by_fields = 'istars';
  search.order_by_order = 'desc';
  search.count = 500;
  search.data_source = 'mm.clients.chin';
    
  search.filters = new Array();
  search.logic = new Array();

    //for (var i=0; i < hotels.length; i++) {
    //	if (i != 0) {
    //		search.logic.push('OR');
    //	}
    //	search.filters.push( new MMSearchFilter('ihotelid', 'eq', hotels[i]) );
    //}
    
  search.filters.push( new MMSearchFilter('ihotelid', 'in', hotels.join(",")) );
  searcher.search( search );

}


function newsearch() {
	cleanUp();
	if (stars5.checked || stars4.checked || stars3.checked) {
		showLocs();
	}
}

function showLocs(){
    
    //**** uncommented 03042009 *******
    updateGeocodeStatus('endGeocode');
  
    // If an error code has been produced, display the explanation:
    if ( searcher.error_code ) {
        
        //processSearchGeocodingErrors(searcher, 'search');
        alert(searcher.error_code);
        return false;
    }
    if ( searcher.record_sets[0].records ) {
        var h2 = document.createElement ('h2');
        h2.appendChild(document.createTextNode('Hotel Results'));
        resultspanel.appendChild (h2);
        var scrolldiv = document.createElement ( 'div' );
        var ul = document.createElement ( 'ul' );
        ul.className = 'resultslist';
        var currentstars;
        var fcount = 0;
        for (var record_count = 0, rl = searcher.record_sets[0].records.length; record_count < rl; record_count++ ) {
            var record = searcher.record_sets[0].records[record_count];
            currentstars = parseFloat(record.istars);
            if ((stars5.checked && currentstars > 4) || (stars3.checked && currentstars < 3.5) || (stars4.checked && currentstars < 4.5 && currentstars > 3))
            {	
            	var filteredresult = record;
    					filteredresults.push(filteredresult);
            	        	
            	var li = handleRecord(filteredresult, fcount);
            	ul.appendChild ( li );
            	
            	fcount = fcount + 1;
            }
        }
        scrolldiv.appendChild (ul);
        resultspanel.appendChild (scrolldiv);
        // Display the results
        mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );
        
    } else {
        
        // No records have been returned. If a record count has been returned, display it,
        // otherwise display a message noting that no records were returned by the search:
        var h2 = document.createElement ( 'h2' );
        h2.appendChild ( document.createTextNode( 'No results returned' ) );
        resultspanel.appendChild ( h2 );
        results_returned = 0;
    }
    
    resultspanel.style.display = 'block';
    
    var cicon = new MMIcon('/images/regionmarker.gif');
    cicon.iconSize = new MMDimensions(30, 33);
    cicon.iconAnchor = new MMPoint(30, 3);
    cicon.textAnchor = new MMPoint(23, 21);
    cicon.infoBoxAnchor = new MMPoint(29, 0);
    
    mapviewer.declutterGroup( 'checkin', {'cluster_icon' : cicon}, MM_DECLUTTER_AGGREGATE );

}

function toggleresult(oResult, iResult) {
    if (oResult.className != 'long') {
        closeallresults();
        //oResult.className = 'long';
        //openresult(iResult);
        markers[iResult].openInfoBox();
    } else {
        closeallresults();
        //oResult.className = 'short';
        //closeResult(iResult);
        markers[iResult].closeInfoBox();
    }
}

function openresult(iResult) {
    var iR = document.getElementById('record'+iResult);
    if (iR) {
        iR.className = 'long';
    }
}

function cleanUp() {
    // Clean up the HTML containers
    while (resultspanel.firstChild) {
        resultspanel.removeChild(resultspanel.firstChild);
    }
    //remove any markers
    mapviewer.removeAllOverlays();
    markers = new Array();
    filteredresults = new Array();
}

function closeallresults() {
    var resultstoclose = document.getElementsByTagName('a');
    if (resultstoclose) {
        for (var i = 0; i < resultstoclose.length; i++) {
            if (resultstoclose[i].className == 'long') {
                resultstoclose[i].className = 'short';
            }
        }
    }
}

function highlightresult(eventType, eventTarget, arg1, arg2, arg3) {
    closeallresults();
    openresult(arg1.getAttribute('checkinrecord'));
}

function moveToResult (count) {
    //move the map specified location and open the info box
    mapviewer.goToPosition(results[count]);
    markers[count].openInfoBox();
}
function openResult (count) {
    //open the info box for the selected location
    markers[count].openInfoBox();
}
function closeResult (count) {
    //open the info box for the selected location
    markers[count].closeInfoBox();
}

function handleRecord( record, num ) {
  if ( record.point ) {

    var marker = createMarker( record, num );
    markers.push(marker);
  } 
  // Show the name in our records list. When the name is clicked, open
  //  our info box:
  var li = document.createElement ( 'li' );
  li.id = 'results_list_item_' + num

  
  var anchor = document.createElement ( 'a' );
  anchor.href = '#';
  //anchor.id = record.id;
  anchor.id = 'record'+num;
  anchor.className = 'short';
  anchor.result_count = num;
  anchor.onclick = function () { toggleresult(this, this.result_count); return false; };
  //anchor.onmouseover = function () { openResult(this.result_count); return false; };
  //anchor.onmouseout = function () { closeResult(this.result_count); return false; };
  
  var img = document.createElement('img');
  img.src = '/images/'+record.istars+'.gif';
  img.alt = record.istars+' Stars';
  anchor.appendChild(img);
  anchor.appendChild(document.createElement('br'));
  
  var strong = document.createElement ( 'strong' );
  var recordname = record.name;
  strong.appendChild(document.createTextNode(recordname));
  anchor.appendChild(strong);
  anchor.appendChild(document.createElement('br'));
  anchor.appendChild(document.createTextNode(record.street + ' ' + record.town + ', ' + record.pc));
  anchor.appendChild(document.createElement('br'));
  li.appendChild(anchor);
  return li;
}

function createMarker(record, num) {
  var location = record.point
  var icon = new MMIcon('/images/regionmarker.gif');

  icon.iconSize = new MMDimensions(30, 33);
  icon.iconAnchor = new MMPoint(15, 13);
  icon.textAnchor = new MMPoint(4, 4);
  icon.infoBoxAnchor = new MMPoint(14, 0);
  //icon.groupName = resultsgroup;
  var marker = mapviewer.createMarker(location, { 'icon': icon, 'text': num+1, 'checkinrecord': num });
  marker.setAttribute('checkinrecord', num);
  marker.setAttribute('result_id', num-1);
  var overviewText, moreInfoText;
  var recordname = record.name;
  overviewText = '<img src="/images/'+record.istars+'.gif" alt="'+record.istars+' Stars" /><br \/><strong>'+recordname+' </strong><br \/><img src="http://www.check-in.com.au/images/Homepagehotel/'+record.ihotelid+'.jpg" alt="'+recordname+'" style="float:right;margin-left:5px;" /><br \/>'+record.street+'<br \/>'+record.town + ', ' + record.pc + '<br \/>';
  overviewText = overviewText + '<br \/><a href="http:\/\/www.check-in.com.au/rg-2-hoteldetails.asp?iHotelId='+record.ihotelid+'">Bookings and more info<\/a>';
  marker.setInfoBoxContent( overviewText );
  // Original infoBox line
  //marker.setInfoBoxContent('<p>' + record.name + '<' + '/p>');
  return marker;
}

function generatemap() {
    //Add the map 
    //mapviewer = MMFactory.createViewer(document.getElementById('mapviewer'), MM_WORLD_MAP );
    mapviewer = new MultimapViewer( document.getElementById( 'mapviewer' ) );
    mapviewer.setOption( 'units', 'km' );
    
    // Add a new event handler
	// to trigger the marker to be placed
	// after the search is complete:
	mapviewer.addEventHandler( 'endSearchRequest', endSearch );
	  
	// Change your selected iproductid to show map of that location:
	mapviewer.goToPosition( new MMLocation (new MMSearch(new MMSearchFilter('iproductid','eq', productid) ) ) );
    
    // Pan/Zoom widget
    pan_zoom_widget = new MMPanZoomWidget ();
    mapviewer.addWidget ( pan_zoom_widget );
    
    // Map type widget
    map_type_widget = new MMMapTypeWidget ();
    mapviewer.addWidget ( map_type_widget );
    
    // Overview widget
    overview_widget = new MMOverviewWidget ();
    mapviewer.addWidget ( overview_widget );
    
    // Setup some references that will be useful later.
    tdfromname = document.getElementById( 'tdfromname' );
    tdtoname = document.getElementById( 'tdtoname' );
    tdfroma = document.getElementById( 'tdfroma' );
    tdtob = document.getElementById( 'tdtob' );
    
    searchbtn = document.getElementById( 'searchbtn' );
	
    geocode_status = document.getElementById( 'geocodestatus' );
    routesteps = document.getElementById( 'routesteps' );
    message = document.getElementById('message');
    results_panel = document.getElementById('resultspanel');
    poibox = document.getElementById('poibox');

    //Create a new geocoder object specifying a callback function
    geocoder = new MMGeocoder(processResults);
    
    // Construct the route requester with our callback function:
    var funcRef = resultsLoaded;
    route_finder = MMFactory.createRouteRequester( funcRef, mapviewer );
}

function shrinkpoi() {
	if (poibox) {
		poibox.className = 'small';
	}
	routesteps.style.display = 'none';
	message.style.display = 'none';
	results_panel.style.display = 'none';
}

// This function adds the marker and the infobox
// from the search results:
function endSearch( type, target, searchresults, error_code ) {
	if( error_code ) {
		alert( 'There was a problem performing this search: '+error_code );
		return;
	}
	mapviewer.removeOverlay( marker );
	
	hotellat = searchresults[0].records[0].point.lat;
	hotellon = searchresults[0].records[0].point.lon;
	
	marker = mapviewer.createMarker( searchresults[0].records[0].point, {'label' : searchresults[0].records[0].name.toString() } );
	var html = '<h1>' + searchresults[0].records[0].productname.toString() + '</h1>';
	hotelname = searchresults[0].records[0].productname.toString();
	
	tdfromname.innerHTML = searchresults[0].records[0].productname.toString();
	tdtoname.innerHTML = searchresults[0].records[0].productname.toString();

	marker.setInfoBoxContent( html );
	marker.openInfoBox () ;
}

function updateGeocodeStatus( type ) {
    if( type == 'startGeocode' ) {
        // if the geocode is starting, disable the form inputs and inform the user
        
        geocode_status.style.display = 'block';
        disableFields(true);
    
    } else {
        // if the geocode is ending, enable the form inputs and inform the user
        
        //*** uncommented 03042009  
        geocode_status.style.display = 'none';    
        disableFields(false);
    }
}

function disableFields( bool ) {
    //disable the user input fields
    //tdfroma.disabled = bool;
    //tdtob.disabled = bool;
    //searchbtn.disabled = bool;
}


function callGeocoder( fields ) {
    // create a new address object
    var address = new MMAddress();
    address.country_code = 'AU';
    address.qs = fields.qs;
    
    // clear any existing items from previous geocoding requests
    cleanUp();

    // inform the user a geocode is occurring
    updateGeocodeStatus('startGeocode');

    // perform the geocode
    geocoder.count = max_results;
    geocoder.geocode(address);
}

function processResults() {
  // callback function registered with the geocoder to handle geocoding results
  // inform the user a geocode has finished
  updateGeocodeStatus('endGeocode');
  // if an error occurred, inform the user
  if (geocoder.error_code && geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
      message.innerHTML = 'We are sorry - the following error occurred: <' + '/br><' + 'em>' + geocoder.error_code + '<' + '/em>';
      shrinkpoi();
      return false;
  }

  results = geocoder.result_set;
  
  

  if (geocoder.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
    //if there were multiple matches, display all the results
    displayMarkers();
    var location = mapviewer.getAutoScaleLocation( markers );
    mapviewer.goToPosition( location ); 
  } else {
    //otherwise show the only match at the optimal zoom factor
    //console.log('Moving to ' + results[0].coords);
    selectresult( 0 );
    // For some reason the above method positions slightly offset, so reposition to correct position...
    //setTimeout('mapviewer.goToPosition(results[0].coords);', 100);
  }
}

function selectresult (count) {
    //move the map specified location and open the info box
//    mapviewer.goToPosition(results[count].coords, results[count].zoom_factor );
//    markers[count].openInfoBox();

	//results = geocoder.result_set;
	
	updateGeocodeStatus('startGeocode');
	
	results_panel.style.display = 'none';
	disableFields(true);
	
	// Show route
	var locations = new Array();
	if (tdfrom) {
		locations.push(new MMLocation(new MMLatLon(hotellat, hotellon)));
		locations.push(new MMLocation(results[count].coords));
	} else {
		locations.push(new MMLocation(results[count].coords));
		locations.push(new MMLocation(new MMLatLon(hotellat, hotellon)));
	}
	
	
	
	route = new MMRoute( locations );
	
	var shortest = document.getElementById('shortest').checked;
    if (shortest == true) {
        route.optimize_for = 'distance';
    } else {
        route.optimize_for = 'time';
    }

	
        
    route_finder.request(route);
}

function resultsLoaded() {
    if (route.error_code) {
        // Display an error message, if applicable:
        alert(route.error_code + ': ' + route.error_explanation);
    } else {
        // use getAutoScaleLocation to show the entire route on the map, with the route bounds:
        mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
        displayStages(route);
        // Show the route on the map with PolyLines, by adding each polyline returned:
        for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
          
          mapviewer.addOverlay(route.polyLine[i]);
        }
    }
    disableFields( false );
}
