

function DestinationResultsManager(page_size, init_sort, map_only) {
	this.page_size = page_size ? page_size : 15;
	this.last_sort = init_sort ? init_sort : 'name';
	this.map_only = map_only ? map_only : false;
	this.full_results = null;
	this.map = null;
	this.result_overlays = {};
	this.loading_panels = [];
}

DestinationResultsManager.prototype.addLoadingPanel = function(panel) {
	this.loading_panels.push(panel);
}

DestinationResultsManager.prototype.showLoadingPanels = function() {
	for (var i=0; i<this.loading_panels.length; i++) {
		var panel = document.getElementById(this.loading_panels[i]);
		if (panel) { panel.style.display = "block"; }
	}
}

DestinationResultsManager.prototype.hideLoadingPanels = function() {
	for (var i=0; i<this.loading_panels.length; i++) {
		var panel = document.getElementById(this.loading_panels[i]);
		if (panel) { panel.style.display = "none"; }
	}
}


DestinationResultsManager.prototype.attachMap = function(map) {
	this.map = map;
}


DestinationResultsManager.prototype.clearMapResults = function(layer) {
	if (this.map && layer in this.result_overlays) {
		for (var i=0; i<this.result_overlays[layer].length; i++) {
			this.map.removeOverlay(this.result_overlays[layer][i]);
		}
	}
}


DestinationResultsManager.prototype.plotResult = function(result, layer, number) {
	if (this.map) {
		var marker = this.createResultMarker(result, number);
		this.map.addOverlay(marker);
		if (!(layer in this.result_overlays)) {
			this.result_overlays[layer] = [];
		}
		this.result_overlays[layer].push(marker);
	}
}


DestinationResultsManager.prototype.refresh_page_nav = function(num) {
	var results_range = document.getElementById('results_paging_range_bottom');
	var results_controls_bottom = document.getElementById('results_paging_controls_bottom');
	var results_controls_top = document.getElementById('results_paging_controls_top');

	if (!this.map_only && results_range && results_controls_bottom && results_controls_top) {
		results_range.innerHTML = '';
		if (this.full_results.length>0) {
			var start_index = (num-1)*this.page_size + 1;
			var end_index = Math.min(num*this.page_size, this.full_results.length);
			results_range.innerHTML = 'Results: ' + start_index + '-' + end_index + ' of ' + this.full_results.length;
		}
		else {
			results_range.innerHTML = 'Sorry. There are no results matching your criteria.';
		}
	
		var paging_controls = '';
		var max_page = this.full_results.length / this.page_size;
		if (num > 1) {
			paging_controls += "&laquo; <span id='page_" + (num-1) + "' class='result_control' onclick='resultsMgr.get_page(" + (num-1) + ");'>Prev</span> | ";
		}
		for (var i=1; i<max_page+1; i++) {
			var curr_id = 'page_' + i;
			if (i==num) {
				paging_controls += "<span id='" + curr_id + "' class='result_control_selected' onclick='resultsMgr.get_page(" + i + ");'>" + i + "</span>";
			}
			else {
				paging_controls += "<span id='" + curr_id + "' class='result_control' onclick='resultsMgr.get_page(" + i + ");'>" + i + "</span>";
			}
			if (i < max_page) {
				paging_controls += " | ";
			}
		}
		if (num < max_page) {
			paging_controls += " | <span id='page_" + (num+1) + "' class='result_control' onclick='resultsMgr.get_page(" + (num+1) + ");'>Next</span> &raquo;";
		}
		
		if (results_controls_top) {
			results_controls_top.innerHTML = paging_controls;
		}
		if (results_controls_bottom) {
			results_controls_bottom.innerHTML = paging_controls;
		}
		if (document.getElementById('result_count')) {
			document.getElementById('result_count').innerHTML = this.full_results.length;
		}
	}
}


DestinationResultsManager.prototype.resort = function(mode) {
	sort(mode, this.full_results);
	this.get_page(1, this.page_size);
	this.last_sort = mode;
	
	var sort_options = document.getElementById('results_sorting_controls').childNodes;
	for (var i=0; i<sort_options.length; i++) {
		var currNode = sort_options[i];
		if (currNode.id==('sort_'+mode)) {
			sort_options[i].className = 'result_control_selected';
		}
		else if (currNode.id != null && currNode.id.indexOf('sort_')==0) {
			sort_options[i].className = 'result_control';
		}
	}
}


DestinationResultsManager.prototype.get_page = function(num) {
	this.load_page(num);
	this.refresh_page_nav(num);
}

DestinationResultsManager.prototype.load_results = function(results, results_container, type) {
	this.full_results = results;
	this.clearMapResults('all');
    for (var i=0; i<this.full_results.length; i++) {
    	var destination = this.full_results[i];
    	if (!this.map_only) {
	    	var result = this.createResultSnapshot(destination);
	    	results_container.appendChild(result);
	    }
    	this.plotResult(destination, 'all', 99);
    }
    if (!this.map_only) {
		this.get_page(1);
	}
}

DestinationResultsManager.prototype.init_results = function(map,country,state,range)	{
	this.showLoadingPanels();

	var results_container = document.getElementById("results_list_hidden");
	var callback = {
		success : function(o) {
			try {
				// alert(o.responseText);
			    var response = YAHOO.lang.JSON.parse(o.responseText);
			    this.load_results(response.cities, results_container);
			    this.hideLoadingPanels();
			}
			catch (e) {
			    alert("Invalid destination results! [" + e + "]");
				results_container.innerHTML = "Failed to load hotels (error code=102). Please try again later.";
				this.full_results = [];
			    this.hideLoadingPanels();
			}
		},
		failure : function(o) {
			results_container.innerHTML = "Failed to load hotels (error code=101). Please try again later.";
			this.full_results = [];
			    this.hideLoadingPanels();
		},
		scope : this
	}

	this.attachMap(map);
	
	var bounds = this.map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var objectsUrl = '?lat1=' + southWest.lat() + '&lat2=' + northEast.lat() + '&lng1=' + southWest.lng() + '&lng2=' + northEast.lng();
	if (range) {
		objectsUrl = '/cluster/destination/' + range + '/' + objectsUrl;
	}
	else {
		objectsUrl = '/cluster/destination/' + objectsUrl;
	}
	if (country) {
		objectsUrl += '&c=' + country;
	}
	if (state) {
		objectsUrl += '&s=' + state;
	}
	
	var conn = YAHOO.util.Connect.asyncRequest("GET", objectsUrl, callback);
}


DestinationResultsManager.prototype.load_page = function(num) {
	var visible = document.getElementById('results_list');
	var hidden = document.getElementById('results_list_hidden');

	for (var i=visible.childNodes.length-1; i>=0; i--) {
		var destination_tile = visible.childNodes[i];
		visible.removeChild(destination_tile);
		hidden.appendChild(destination_tile);
	}
	this.clearMapResults('page');

	var resultNumber = 1;
	for (var i=(num-1)*this.page_size; i<num*this.page_size && i<this.full_results.length; i++) {
		var result = this.full_results[i];
		this.plotResult(result, 'page', resultNumber);
		
		var destination_tile = document.getElementById('destination_' + result.id);
		if (destination_tile) {
			// Don't plot results if there is no map attached!
			if (this.map) {
				var destination_tile_icon = document.getElementById('resultIcon_' + result.id);
				if (destination_tile_icon) {
					destination_tile_icon.innerHTML = '<img src="' + this.getResultIconImage(resultNumber) + '" />';
				}
			}
		
			hidden.removeChild(destination_tile);
			visible.appendChild(destination_tile);
			
			resultNumber++;
		}
		else {
			alert("Error: Invalid destination id [" + result.id + "]");
		}
	}
}

DestinationResultsManager.prototype.getResultIconImage = function(number) {
	var image;
	if (number > 0 && number <= 15) {
		image = "/site_media/images/marker_" + "abcdefghijklmno".charAt(number-1) + ".png";
	}
	else {
		image = "/site_media/images/cluster1.png";
	}
	return image;
}

DestinationResultsManager.prototype.getResultIcon = function(number) {
	var icon = new GIcon();
	if (number && number > 0 && number <= 15) {
		icon.image = this.getResultIconImage(number);
		icon.iconSize = new GSize(16, 16);
		icon.iconAnchor = new GPoint(8, 8);
		icon.infoWindowAnchor = new GPoint(8, 8);
	}
	else {
		icon.image = this.getResultIconImage(number);
		icon.iconSize = new GSize(10, 10);
		icon.iconAnchor = new GPoint(5, 5);
		icon.infoWindowAnchor = new GPoint(5, 5);
	}
	return icon;
}


DestinationResultsManager.prototype.createResultMarker = function(item, number) {
	var icon = this.getResultIcon(number);
	var point = new GLatLng(item.latitude, item.longitude);
	var marker = new GMarker(point, { icon:icon,
									  zIndexProcess:function(){ return 9999-number; } } );

	GEvent.addListener(marker, "click", function() {
		var html = "<div class='mapInfo'>";
		if (item.image != '') { 
			html += "<img src='" + item.image + "'/><div class='details'>"; 
		}
		else {
			html += "<div class='details' style='width:100%'>";
		}
		html += "<h1><a href='/destination/city/" + item.slug + "/' target='_blank'>" + item.name + "</a></h1>" + item.description + "</div></div>";
		marker.openInfoWindowHtml(html,{maxWidth:270});
	});

	return marker;
}


DestinationResultsManager.prototype.createResultSnapshot = function(city) {
	var snapshot = document.createElement('div');
	snapshot.id = 'destination_' + city.id;
	snapshot.className = 'object_snapshot';
	snapshot.setAttribute('name',city.name);
	snapshot.setAttribute('popularity',city.popularity);
	
	var photo = document.createElement('div');
	photo.className = "photo";
	if (city.image != null && city.image != '') {
		photo.innerHTML = '<div class="photo_inner"><a href="/destination/city/' + city.slug + '/" target="_blank"><img src="' + city.image + '"/></a></div>';			
	}
	snapshot.appendChild(photo);

	var info = document.createElement('div');
	info.className = 'info';
	infoContents = '<h2><a href="/destination/city/' + city.slug + '/" target="_blank">' + city.name + '</a>';
	infoContents += '<div id="resultIcon_' + city.id + '" class="resultMarkerIcon"></div></h2>';
	infoContents += city.description;
	infoContents += '<div class="links"><a href="/destination/city/' + city.slug + '/" target="_blank">Overview</a> | ';
	infoContents += '<a href="/lodging/city/' + city.slug + '/" target="_blank">Hotels</a> | ';
	infoContents += '<a href="/attraction/city/' + city.slug + '/" target="_blank">Attractions</a> | ';
	infoContents += '<a href="/restaurant/city/' + city.slug + '/" target="_blank">Restaurants</a> | ';
	infoContents += '<a href="/resource/city/' + city.slug + '/" target="_blank">Services</a>';
	infoContents += '</div>';
	info.innerHTML = infoContents;
	snapshot.appendChild(info);

	var rate = document.createElement('div');
	rate.className = 'rate';
	rate.innerHTML = '<a href="/destination/city/' + city.slug + '/" target="_blank" class="button">LEARN MORE</a>';
	info.appendChild(rate);

	var bottom_edge = document.createElement('div');
	bottom_edge.className = "bottom_edge";
	snapshot.appendChild(bottom_edge);
	return snapshot;
}
