//<![CDATA[
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 markers = new Array();
var filteredresults = new Array();
var rfs = ['id', 'ihotelid', 'name', 'street', 'town', 'pc', 'lat', 'lon', 'istars'];
var sSecond = false;
function findhotel() {
	//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 );
    
	// Collect selected hotel data
	searcher = new MMSearchRequester( showLocs );
	search = new MMSearch(); 
    search.return_fields = rfs;
    search.data_source = 'mm.clients.chin';
    
    search.filters = new Array();
    search.logic = new Array();

    search.filters.push( new MMSearchFilter('ihotelid', 'eq', ihotelid) );
    searcher.search( search );
}

function openpoi() {
	poicontainer = document.getElementById ('poibox');
    local_info_widget  = new MMLocalInfoWidget ( undefined, undefined, new MMBox () );
    local_info_widget.setContainer ( poicontainer );
    mapviewer.addWidget( local_info_widget );
    var openpoi = document.getElementById ('openpoi');
    openpoi.style.display = 'none';
    
    
    // Use a custom icon for Wikipedia:
    var newicon = new MMIcon( '/i/MapMarkerHotel.gif' );
    
    var wiki_icon = new MMIcon( '/i/MapMarkerHotel.gif' );
    wiki_icon.iconSize = new MMDimensions( 32, 32 );
    wiki_icon.iconAnchor = new MMPoint( 16, 16 );
    
    // Set custom options for the data source:
    //  - show Wikipedia between zoom factors 14 and 17 only (inclusive):
    var options = {'title':'Check-in', 'icon':newicon};
  //  local_info_widget.addDataSource('mm.poi.global.general.wikipedia', options); 
    local_info_widget.addDataSource('mm.clients.chin_api', options);
    local_info_widget.refreshData();
    local_info_widget.start();
}

function showLocs(){
    // If an error code has been produced, display the explanation:
    if ( searcher.error_code ) {     
        alert(searcher.error_code);
        return false;
    }
    if ( searcher.record_sets[0].records ) {
        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];
            

            
            var filteredresult = record;
    			filteredresults.push(filteredresult);
            	
            	
            	
            	handleRecord(filteredresult, fcount);
            	
            	fcount = fcount + 1;

        }
        // 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:
        alert( 'Hotel location not found' );
    }
}

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 = '/i/'+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('/i/MapMarkerHotel.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, 'checkinrecord': num });
  marker.setAttribute('checkinrecord', num);
  marker.setAttribute('result_id', num-1);
  var overviewText, moreInfoText;
  var recordname = record.name;
  overviewText = '<img src="/i/'+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 \/>';
  marker.setInfoBoxContent( overviewText );
  // Original infoBox line
  //marker.setInfoBoxContent('<p>' + record.name + '<' + '/p>');
  
  hotellat = record.point.lat;
  hotellon = record.point.lon;
  
  tdfromname.innerHTML = recordname;
  tdtoname.innerHTML = recordname;
  
  marker.openInfoBox();
  
  return marker; 
}

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].productname.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 cleanUp() {
    // Clean up the HTML containers
    message.innerHTML = '';
    while (results_panel.firstChild) {
        results_panel.removeChild(results_panel.firstChild);
    }
    var stepsContainer = document.getElementById('routesteps');
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    //remove any markers
    mapviewer.removeAllOverlays();
    markers = new Array();
}

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
        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 swaptd(sClass) {
	oTdform = document.getElementById('tdform');
	if (oTdform) {
		oTdform.className = sClass;
	}
	if (sClass == 'from') {
		tdfrom = true;
	} else {
		tdfrom = false;
	}
}

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 displayMarkers() {
  cleanUp();
  
  results = geocoder.result_set;
  var ol = document.createElement('ol');
  
  //loop through the result set
  for (var count=0; count < results.length; count++) {
    var address = results[count].address;
    var li = document.createElement('li');
    //add a link for each result
    var anchor = document.createElement('a');
  
    anchor.href = '#';
    anchor.result_count = count;
    anchor.onclick = function () { selectResult(this.result_count); return false; };
    anchor.appendChild(document.createTextNode(address.display_name));
    li.appendChild(anchor);
    ol.appendChild(li);
    
    // Create tabs
    var tabs = new Array();
    //var location_content = '<p>' + address.display_name + '<' + '/p>';
    var location_content = '<p>' + address.display_name + '</p><p><a href="#" onclick="selectResult('+count+')">Select this location</a></p>';
    //tabs.push(new MMInfoBoxTab('Location',location_content));
    //var mobile_content = '<img src=\"/i/mobile.png\" />';
    //tabs.push(new MMInfoBoxTab('Mobile',mobile_content));
    
    //add a marker for each result
    var marker = mapviewer.createMarker(results[count], { 'label' : address.display_name, 'text' : (count+1) });
    //add an infobox for each result
    marker.setInfoBoxContent(location_content);
    markers.push(marker);
  }
  var h2 = document.createElement('h2');
  h2.appendChild(document.createTextNode('Multiple Results found'));
  results_panel.appendChild(h2);
  
  var p = document.createElement('p');
  p.appendChild(document.createTextNode('Choose the best match below or search again'));
  results_panel.appendChild(p);
  
  results_panel.appendChild(ol);
  shrinkpoi();
  results_panel.style.display = 'block';
}

function createStepMarker(location, instruction, text, zindex) {
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}  

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';
    }
//    var walking = document.getElementById('walking').checked;
//    if (walking == true) {
//        route.mode = 'walking';
//    } else {
//        route.mode = 'driving'; 
//    }
	
        
    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 );
}

function displayStages(route) {
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById('routesteps');

    var h2 = document.createElement('h2');
    h2.appendChild(document.createTextNode('Travel directions'));
    container.appendChild(h2);
    
    var summary = '';
    // Show the total route distance in miles:
    summary += 'Total Distance: ' + route.distance.km + ' km)';
    // Show the total duration of trip. Note that we display the days, hours, and minutes by
    //  accessing each property: 
    summary += '<br />Estimated Total Time: ';
    if (route.duration.days > 0) { summary += route.duration.days + ' day(s) '; }
    if (route.duration.hours > 0) { summary += route.duration.hours + ' hour(s) '; }
    if (route.duration.minutes > 0) { summary += route.duration.minutes + ' minute(s) '; }
    var p = document.createElement('p');
    p.innerHTML = summary;
    container.appendChild(p);
    
    // The route will be returned in stages. Each stage goes from one specified 'location' to the next:
    for (var count=0; count < stages.length; count++) {
        // Show some summary information about each stage:
        var stage_summary = '';
  //      stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
        // Show the stage distance, in miles:
  //      stage_summary += '<br />Stage Distance: ' + stages[count].distance.km + ' km';
        // Show the stage duration, in days, hours and minutes:
 //       stage_summary += '<br />Estimated Stage Time: ';
 //       if (stages[count].duration.days > 0) { stage_summary += stages[count].duration.days + ' day(s) '; }
 //       if (stages[count].duration.hours > 0) { stage_summary += stages[count].duration.hours + ' hour(s) '; }
 //       if (stages[count].duration.minutes > 0) { stage_summary += stages[count].duration.minutes + ' minute(s) '; }
 //       var p = document.createElement('p');
 //       p.innerHTML = stage_summary;
 //       container.appendChild(p);
        
        var ol = document.createElement('ol');
        ol.id = 'stage_' + count;
        ol.start = curr_step;

        var steps = stages[count].steps;
    
        // Now we will display each step instruction within this stage:
        for (var stepCount=0; stepCount < steps.length; stepCount++) {
            // Label the current marker with the step number:
            var text = curr_step;
            // Make the higher numbered step markers appear 'on top of' lower ones:
            var zindex = max_zindex - curr_step + 1;
            
            // Use 'S' as marker text if this is the first step of the entire route:
            if (count == 0 && stepCount  == 0) {
                text = 'S';
            }        
            // Use 'F' as marker text if this is the last step of the entire route:      
            if (count == stages.length - 1 && stepCount  == steps.length - 1) {
                text = 'F';
                zindex = max_zindex; 
           }                
            // Create a written 'instruction' using the roadname and/ or roadnumber:
            var instruction = steps[stepCount].instruction;
            var roadname = steps[stepCount].road_name;
            var roadnumber = steps[stepCount].road_number; 

            if (roadname && roadnumber) {
                instruction += ' ' + roadname + ' (' + roadnumber + ') ';
            } else if (roadname) {
                instruction += ' ' + roadname + ' ';
            } else if (roadnumber) {
                instruction += ' ' + roadnumber + ' ';
            }
            
            // Show the distance of this particular step:
            var distance = '';                    
            if (steps[stepCount].distance.miles > 0) { distance += steps[stepCount].distance.km + ' km '; }
            if (distance != '') { distance = ' - ' + distance };
            
            var li = document.createElement('li');
            li.innerHTML = instruction + distance;
            ol.appendChild(li);
            
            // Create the step marker, using the instruction and marker text we previously created:
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            
            ++curr_step;
        }
        container.appendChild(ol);
    }            
    shrinkpoi();
    container.style.display = 'block'; 
    
    // Add copyright and disclaimer, as required:
    var copyright = '';
    if (route.copyright) {copyright += 'Copyright: ' + route.copyright; }
    if (route.disclaimer)  {copyright += '<br /><a href="' + route.disclaimer +'">Disclaimer<' + '/a>'; }
    
    var p = document.createElement('p');
    p.innerHTML = copyright;
    container.appendChild(p);
    updateGeocodeStatus('endGeocode');
}

function starttd() {
	cleanUp();
	if (tdfrom) {
		// From hotel
		callGeocoder({'qs' : tdtob.value});
	} else {
		// To hotel
		callGeocoder({'qs' : tdfroma.value});
	}
	
}

// MMAttachEvent( window, 'load', onLoad );