//This file created by Barry Hunter www.nearby.org.uk (c) July 2007
// Modified for CNGPrices.com November 2007, credit to Barry and nearby.ork.uk

var addressMarker;

//the ajax request object
var request, req;

//the 'dafault' icon
// These are for cngprices.com only
var icons = new Array();
var freeIcons = new Array();

// The ID of the current info window
var infoWindowID = -1;

//array of markers so we can keep track of which to remove
var marks = new Array();

//shortcut to the message div
var m;
var route; // shortcut to route area (in route results)

//is the a fetch in progress?
var running = false;

// For directions
var startLatLng, endLatLng;

//these are for zoomin optimization (if prev zoom had all markers then no need to load them again for zooming in)
var prevZoom = -1;
var shownall = false;
var sentBounds = '';


function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(address,function(point) {
			if (!point) {
				alert("Your entry '" + address + "' could not be geocoded, please try again");
			} else {
				if (addressMarker) {
					map.removeOverlay(addressMarker);
				}
				addressMarker = new GMarker(point);
				map.setCenter(point, 12);
				map.addOverlay(addressMarker);
				}
			});
	}
}

function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
                num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + num + '.' + cents);
}

function createMarkerD(pointData, isRoute, whichStation ) {

	// Marker stuff
	myIcon = icons[pointData.primaryCategory];

	if( pointData.specialFree == 1 )
		myIcon = freeIcons[pointData.primaryCategory];
		
	if( pointData.priceTotal < 0.01 )
		labelText = "Free";
	else if( pointData.priceTotal < 10 )
		labelText = pointData.currency + formatCurrency(pointData.priceTotal);
	else
		labelText = pointData.currency + Math.round(pointData.priceTotal);
	
   	opts = {
   		"icon": myIcon,
   		"clickable": true,
   		"labelText": labelText,
   		"labelOffset": new GSize(-16, -26)
   	};

	var marker = new LabeledMarker( pointData, opts );

	// Info window text
	var textArray = new Array();
	var i=0;
	var finalString = '';
	
	textArray[i++] = '<div id="info-window">';
	
	textArray[i++] = '<h3><a href="venue.php?id=' + pointData.id  + '" target="_blank"' +
		' alt="Show more information about this activity, including reviews" ' + 
		' title="Show more information about this activity, including reviews" ' + 
		'>' + pointData.name + '</a>&nbsp;&nbsp;</h3>';

	if( pointData.website.length > 10 )
		textArray[i++] = '<p><a target="_blank" href="' + pointData.website + '"' + 
		' alt="Go to the web site for this activity" title="Go to the web site for this activity"' +
		'>Web site</a></p>';
		
	
	countryString = '';
	if( pointData.country.indexOf( 'USA' ) == -1 )
	{
		countryString = ' ' + pointData.country;
	}
	textArray[i++] =  '<p><a href="http://maps.google.com/maps?f=q&q=' +
        escape(pointData.address + countryString) + '" target="_blank" ' +
		'alt="Show on Google maps in a new window"' +
		'title="Show on Google maps in a new window">' +
		pointData.address + countryString + '</a></p>';

	if( pointData.phone.length > 3 )
		textArray[i++] = '<p>' + pointData.phone + '</p>';
	
	if( pointData.tags.length > 3 )
		textArray[i++] = '<p><span id="info-window-label">Features:</span> ' + pointData.tags + '</p>';
		
	var priceString = pointData.currency + formatCurrency(pointData.priceTotal);
	if( pointData.priceTotal < 0.01 )
		priceString = "Free";
		
	textArray[i++] = '<p><span id="info-window-label">Cost (2 adults, 2 children):</span> ' +
		priceString + '</p>';
	
	if( pointData.upcomingFreeDays.length > 0 )
		textArray[i++] = '<p><span id="info-window-label">Upcoming free days:</span> ' + pointData.upcomingFreeDays + '</p>';
		
	if( pointData.description.length > 5 )
		textArray[i++] = "<p>" + pointData.description + "</p>";
		
	var plural="", noReviewText = "";
	if( pointData.reviewCount > 1 ) plural = "s";

	if( pointData.ratingCount > 0 )
	{
		var tempText = "", ratingPlural = "";
		if( pointData.ratingAverage > 0.1 )
		{
			if( pointData.ratingCount > 1 ) ratingPlural = "s";
			
			// get the average review and put out some stars
			// divide by 2 and round to nearest half
			starReview = Math.round( parseFloat(pointData.ratingAverage) ) / 2;
			if( starReview < 1 ) starReview = 1;
			if( starReview > 5 ) starReview = 5;
			starReview = starReview + 0.00000001; // force the digits
			starReview = starReview.toString();
			starString = starReview.substring(0,3);
			starImage = "icons/stars_" + starString + ".gif";
			tempText = '<p><span id="info-window-label">Average rating:</span> ' + 
				'<img src="' + starImage + '" width="55" height="12"> (' + pointData.ratingCount + ' rating' +
				ratingPlural + ')</p>';
		}
				
			textArray[i++] = tempText;
	}
	
	tempText = "";
	if( pointData.reviewCount > 0 )
		tempText = 'Read <a href="venue.php?id='+pointData.id+'" target="_blank">' +
			pointData.reviewCount + ' Review' + plural + '</a> and ';
		
	textArray[i++] = '<p>' + tempText + '<a href="venue.php?id=' + pointData.id + '#review" target="_blank">' + 
		noReviewText + 'Add Your Review!</a></p>';
	
	textArray[i++] = '</div>';

	finalString = textArray.join('');
	
	GEvent.addListener(marker, "click", function() {
		infoWindowID = pointData.id;
		//finalString = finalString + '<p>' + Math.random() + '</p>';
		marker.openInfoWindowTabsHtml([new GInfoWindowTab('Location',finalString)], {maxWidth: "270"});
	});

	return marker;
} // end funciton createmarkerd

function update_mapD() {
	if (running) {
		request.abort();
		running = false;
	}
	if (shownall == false || map.getZoom() >= prevZoom) {
		var bounds = map.getBounds();

		var center = map.getCenter();
		var zoom = map.getZoom();
		
		sentBounds = bounds.toString()
		//alert( sentBounds );

		var postString = get_post_string();
		
		//setup links that utalise the current map location
/*		document.getElementById("datalink").innerHTML = '<a href="http://' +
			location.hostname + 
			'/index.php?bounds='+
			escape(sentBounds)+
			'">Link to this map</a>';
*/
		request = GXmlHttp.create();
		request.open("GET", "dynamicMaps.xml.php?bounds=" + sentBounds + postString, true);
		
//		tc_debug( "dynamicMaps.xml.php?bounds=" + sentBounds + postString );
			
		request.onreadystatechange = processXMLResponse;

		document.getElementById( "loading_status" ).style.display = 'inline';
		running = true;
		request.send(null);
	}
	prevZoom = map.getZoom();
}

function tc_debug( string )
{
		if( document.getElementById("debug") )
			document.getElementById("debug").innerHTML = "<p>" + string + "</p>";
}

function get_post_string()
{
	var postStringArray = new Array();
	var ps=0;
	var i, n=0;
	// Look for check boxes and stuff here
	var categories= new Array();
	for( i=0; i < document.type.category_list.length; i++ )
		if( document.type.category_list[i].checked == true )
			categories[n++] = document.type.category_list[i].value;
			
	postStringArray[ps++] = "&categories=" + categories.join(",");
	
	var priceLimit = document.spending.spending[document.spending.spending.selectedIndex].value;
	postStringArray[ps++] = "&price_limit=" + priceLimit;
	
	n = 0;
	var daysList = new Array();
	for( i=0; i < document.selector.price_checks.length; i++ )
		if( document.selector.price_checks[i].checked == true )
			daysList[n++] = i;
			
	postStringArray[ps++] = "&days=" + daysList.join(",");
	
	var date = new Date();
	
	postStringArray[ps++] = "&date=" + date.getFullYear() + "," + (date.getMonth()+1) + "," + date.getDate();
	
	postStringArray[ps++] = "&children=2";
	postStringArray[ps++] = "&adults=2";
	
	return postStringArray.join("");
}

function processXMLResponse() {
			if (request.readyState == 4 && running) {
				var routeTextArray = new Array();
				
				var whichStation = 0;

				//alert(request.responseText);

				//m.innerHTML = "Parsing XML..";
				var xmlDoc = GXml.parse(request.responseText);
				if( !xmlDoc ) {
					m.innerHTML = "Error: no XML doc";
					running = false;
					return;
				}

				if (!xmlDoc.documentElement) {
					m.innerHTML = "Error: Unable to Parse XML";
					running = false;
					return;
				}
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				// m.innerHTML = "Marker count: " + markers.length;

				var tooManyMessage = '';
				var validCount = 0;
				var noStations;
				var hasSpecialFree = 0, isSpecialFree;
				
				var countMain = xmlDoc.documentElement.getElementsByTagName("count");
                if( countMain && countMain[0] && countMain.length > 0 )
                	validCount = parseFloat(countMain[0].getAttribute("value"));

				noStations = "No items, please try moving the map around LA/OC";
				
				var mapDescription = "";
				var mapDescriptionXML = xmlDoc.documentElement.getElementsByTagName("mapDescription");
				if( mapDescriptionXML && mapDescriptionXML[0] && mapDescriptionXML.length > 0 )
					mapDescription = mapDescriptionXML[0].getAttribute("value");
					
// 				var dXML = xmlDoc.documentElement.getElementsByTagName("d");
// 				if( dXML && dXML[0] && dXML.length > 0 )
// 					tc_debug( dXML[0].getAttribute("value") );

				if( validCount > 150 ) { tooManyMessage = "Too many items to list. Zoom in for more detail."; }
				//alert("Count: "  +countMain.length + ' Valid count: ' + validCount );

				//flag all current markers as old
				for (i in marks) 
					if (marks[i] != null) 
						marks[i].old = true;

				if( validCount == 0 )
				{
//					document.getElementById( 'map_error' ).style.display = 'inline';
//					document.getElementById( 'map_error' ).innerHTML = noStations;
					tooManyMessage = noStations;
					//running = false;
					//return;
				}
				else
				{
				//	m.innerHTML = "Adding Markers2...";
					var lastLatLng, maxDistance = 0;

					if( startLatLng ) { lastLatLng = startLatLng; }

					for (var i = 0; i < markers.length; i++)
					{
						id = markers[i].getAttribute("id");
						
						isSpecialFree = markers[i].getAttribute("specialFree");
						
						// m.innerHTML = "ID: " + id;
						if (marks[id] && marks[id] != null && isSpecialFree == marks[id].isSpecialFree )
						{
							if( isSpecialFree == 1 ) hasSpecialFree = 1;
							
							//we have this one so lets flag it as valid
							marks[id].old = false;
						}
						else
						{
							// Erase it if it was there and the "special" flag has changed
							if( marks[id] && marks[id] != null )
							{
								map.removeOverlay(marks[id]);
								marks[id] = null;
							}
							
							lat = markers[i].getAttribute("lat");
							lng = markers[i].getAttribute("lng");
							var point = new GLatLng(parseFloat(lat), parseFloat(lng));

							point.id = markers[i].getAttribute("id");
							point.name = markers[i].getAttribute("name");
							point.directions = markers[i].getAttribute("directions");
							point.address = markers[i].getAttribute("address");
							point.phone = markers[i].getAttribute("phone");
							point.country = markers[i].getAttribute("country");
							point.currency = markers[i].getAttribute("currency");
							point.reviewCount = markers[i].getAttribute("reviewCount");
							point.ratingAverage = markers[i].getAttribute("ratingAverage");
							point.ratingCount = markers[i].getAttribute("ratingCount");
							point.priceAdult = markers[i].getAttribute("adultPrice");
							point.priceChild = markers[i].getAttribute("childPrice");
							point.priceTotal = markers[i].getAttribute("totalPrice");
							point.priceBase = markers[i].getAttribute("priceBase");
							point.hours = markers[i].getAttribute("hours");
							point.website = markers[i].getAttribute("website");
							point.tags = markers[i].getAttribute("tags");
							point.description = markers[i].getAttribute("description");
							point.primaryCategory = markers[i].getAttribute("primaryCategory");
							point.d = markers[i].getAttribute("d");
							point.specialFree = markers[i].getAttribute("specialFree");
							point.upcomingFreeDays = markers[i].getAttribute("upcomingFreeDays");

							if( point.specialFree == 1 ) hasSpecialFree = 1;
							
							//add any extra fields to this line
							isRoute = 0;

							marks[id] = createMarkerD( point, isRoute, whichStation+1 );
							marks[id].isSpecialFree = point.specialFree;
							map.addOverlay(marks[id]);
							
						}
					} // end for var i=0
				} // end else validCount > 0
				
				// m.innerHTML = "Removing Old Markers...";
				for (i in marks) 
					if (marks[i] != null) 
						if (marks[i].old == true && i != infoWindowID) {
							map.removeOverlay(marks[i]);
							marks[i] = null; //marks.splice(i,1);
						}

				if( hasSpecialFree == 1 && document.getElementById( "spending_info" ) )
					document.getElementById( "spending_info" ).innerHTML = 
						'<table border="0" cellpadding="0" cellspacing="3"><tr><td valign="center"><img align="left" src="icons/icon_free_blank.png" width="34" height="38" style="margin-right:5px;margin-bottom:9px;"></td><td style="font-size:9px;">Icons with a <span style="color:green;">green background</span> ' +
						'are free only on certain days. Click on the acitivity\'s icon on the map for dates.</td></tr></table>';
				else
					document.getElementById( "spending_info" ).innerHTML = '';
				
				if( document.getElementById( "map_description" ) )
					document.getElementById( "map_description" ).innerHTML = mapDescription;
				
				if( tooManyMessage.length > 0 )
				{
					document.getElementById( 'map_error' ).innerHTML = tooManyMessage;
					document.getElementById( 'map_error' ).style.display = 'inline';
				}
				else
					document.getElementById( 'map_error' ).style.display = 'none';
				
				document.getElementById( "loading_status" ).style.display = 'none';


	} // end if readystate && running
	
}//end function
