//This stripes the list of houses under each price category
//Inspured by an A List Apart article "Zebra Tables" http://www.alistapart.com/articles/zebratables/
//It takes as a single parameter the ID of the list that will be striped
//@author: Terrill Dent

function Is() {
    agent  = navigator.userAgent.toLowerCase();
    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);
    this.ns    = ((agent.indexOf('mozilla')   !=   -1) && 
                 ((agent.indexOf('spoofer')   ==   -1) && 
                 (agent.indexOf('compatible') ==   -1)));
    this.ns4   = (this.ns && (this.major      ==    4));
    this.ns6   = (this.ns && (this.major      >=    5));
    this.ie    = (agent.indexOf("msie")       !=   -1);
    this.ie3   = (this.ie && (this.major      < 4));
    this.ie4   = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.0")   ==   -1));
    this.ie5   = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.0")   !=   -1));
    this.ie55  = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.5")   !=   -1));
    this.ie6   = (this.ie && (agent.indexOf("msie 6.0")!=-1) );
}

var is = new Is();

function stripe(id) {
	var even = false;
	
	//Here you can change the colour of the stripes, change the 6 digit hex values below
	//White
	var evenColor = "#ffffff";
	//Pinkish
	var oddColor = "#FEE3E2";

	var ul = document.getElementById(id);
	if (! ul) { return; }
	// find all the li elements... 
 	var lis = ul.getElementsByTagName("li");
 	// ... and iterate through them
	for (var i = 0; i < lis.length; i++) {
		lis[i].style.backgroundColor = even ? evenColor : oddColor;
		lis[i].style.fontWeight = 'normal';
		even =  ! even;
	}
}
function stripeAll() {
	for (var i = 1; i < 12; i++) {
		stripe('house_list_'+i);
	}
}
// One of the core functions which many others call on, the toggle function uses the CSS
// class names 'off' and 'on' to show and hide objects.
// The single Parameter is the id of the element you wish to toggle
function toggle(id) {
	obj = document.getElementById(id);
	if (obj.className == 'on') {
		obj.className = 'off';
	}
	else if (obj.className == 'off') {
		obj.className = 'on';
	}
}

//This function switches between the sidebar tabs. Rentals or Map Options
//It will basically change the CSS Class name of different sections to make them visible or hidden
function toggle_tab(tab) {
	if (tab == 'option_tab') {
		obj = document.getElementById(tab);
		obj.className = 'selected';
		obj = document.getElementById('rental_tab');
		obj.className = 'none';
		obj = document.getElementById('option_menu');
		obj.className = 'on';
		obj = document.getElementById('utility_menu');
		obj.className = 'off';
	}
	else if (tab == 'rental_tab') {
		obj = document.getElementById(tab);
		obj.className = 'selected';
		obj = document.getElementById('option_tab');
		obj.className = 'none';
		obj = document.getElementById('option_menu');
		obj.className = 'off';
		obj = document.getElementById('utility_menu');
		obj.className = 'on';
	}
}

// Called when a user clicks a price range.  This is where the bulk of work is initiated from
// @number: The Price Level Category
function toggleList(listNumber) {
	obj = document.getElementById('house_list_'+listNumber);
	
	//First condition is if the list is already visible "on"
	// If the list is on, it is turned off and each marker removed from map
	if (obj.className == 'on') {
		obj.className = 'off';
		//Get all the li's in the list
		var lis = obj.getElementsByTagName("li");
		// ... and iterate through them removing each from the map
		for (var i = 0; i < lis.length; i++) {
			id = lis[i].id;
		  	map.removeOverlay(houseMarker[id]);
		}
		//Resets the HTML in that list to be Null... just to be sure.
		document.getElementById('house_list_'+listNumber).innerHTML = null;
		
	}
	//If the list is not on, then it is initialized with a call to "Houses"
	else if (obj.className == 'off') {
		houses(listNumber);
		obj.className = 'on';
	}
}


// This is where the AJAX happens. 
// A request is sent by building the .xml file URL out of the parameter that is passed in.
// The returned .xml is parsed and then added to the page via the HTML DOM. 
// @number: The Price Level Category
function houses(number) {
	var request = GXmlHttp.create();
	var points = [];
	//This is a random number that is used to append onto the end of the XML request in the form of a get.
	//Some browsers cache XML too long, and in order to ensure data is updated, the same file is always requested.
	var dontCache =Math.floor(Math.random()*100)
	//Generates the url to the data using the number provided, add the random number to the end
	request.open("GET", "data/price"+number+".xml?dontCache="+dontCache+"", true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		
		//An array of markers is formed from the XML Document
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		
		//This is the target UL which will hold our information
		ul = document.getElementById('house_list_'+number);
		 
		//Iterate through the markers[] array
		for (var i = 0; i < markers.length; i++) {
			
			//The getAttribute method gets information out of the XML which is stored in that array position
			var id = markers[i].getAttribute('id');
			var point = new GPoint(parseFloat(markers[i].getAttribute('lng')), parseFloat(markers[i].getAttribute('lat')));
			
			//This is a possible place for changes.  If you add new fields to the XML or remove fields then you 
			//will add or remove from this list.  This is the link between XML data and the Javascript variable
			//You will also have to change the parameters that createMarker accepts so that it can be called successfully
			var marker = createMarker(point, markers[i].getAttribute('add'), markers[i].getAttribute('price'), id, markers[i].getAttribute('term'), markers[i].getAttribute('utilities'), markers[i].getAttribute('heat'),  markers[i].getAttribute('furn'), markers[i].getAttribute('br'), markers[i].getAttribute('type'), markers[i].getAttribute('contact'), markers[i].getAttribute('phone'), markers[i].getAttribute('smoking'),markers[i].getAttribute('coast'), markers[i].getAttribute('miles'), markers[i].getAttribute('hcap'), markers[i].getAttribute('comments'), markers[i].getAttribute('pets'), number);
			
			//Add this property to the map
			map.addOverlay(marker);
				  
			//Now to add the house in the HTML. Create the new LI and give it an ID attribute
			new_li = document.createElement('li');
			new_li.setAttribute('id',id);
			
			//Create a link (A HREF) to go inside the LI
			new_a = document.createElement('a');
			new_a.href = "javascript:GEvent.trigger(houseMarker["+id+"],'click')";
			new_text = document.createTextNode(markers[i].getAttribute('add'));
		
			//Append the A HREF to the parent LI to the parent UL
			ul.appendChild(new_li);
			new_li.appendChild(new_a);
			new_a.appendChild(new_text);
		}
	}
	//Now that the full list has been added in the HTML, stripe it to make it look nice
	stripe('house_list_'+number);
  }
  request.send(null);
}

// Creates a marker whose info window displays the information about that house
// @point: a variable created containing a latitude and longitude (see houses for creation)
// @add: Address
// @price: The price of the rental/sublet
// @id: This is a unique ID assigned to the house
// @term: I used this to indicate the length of lease
// @utilities: Are you utilities included or not
// @number: this is the Price Level number.  NOT THE HOUSE NUMBER. It is used to make the correct colour of icon on the map 1-5
function createMarker(point, add, price, id, term, utilities, heat, furn, br, type, contact, phone, smoking, coast, miles, hcap, comments, pets, number) {
	baseIcon.image = "images/marker/step_"+number+".png";
	var marker = new GMarker(point, baseIcon);
	
	// IMPORTANT
	// This is the HTML that goes inside the thought bubbles when a house is clicked.
	//I Have formatted it as a list of items, but you can format it with any HTML that you like.
	//Remember to wrap it in the bubble div so that width problems are solved.
	var html = '<div class="bubble"><h3>'+add+'</h3>Contact: '+contact+' '+phone+'<table><tr><td><ul><li>Price/Month: $'+price+'</li><li>Availability: '+term+'</li><li>Smoking: '+smoking+'</li><li>Heat Incl: '+heat+'</li><li>Electric Incl: '+utilities+'</li><li><a href="more_info.asp?ID='+id +'" target=info_window>More Info</li></ul></td><td><ul><li>Type: '+type+'</li><li>Bedrooms: '+br+'</li><li>Furnished: '+furn+'</li><li>Bus Transit: '+coast+'</li><li>Miles to UNH: '+miles+'</li><li>Pets: '+pets+'</li></ul></td></tr></table></div>';
	
	GEvent.addListener( marker, "click", function() {
		marker.openInfoWindowHtml(html);
		stripeAll();
		//add a behaviour to the list items to 'select' them when the GPoint is selected
		li = document.getElementById(id);
		li.style.backgroundColor = selectColor;
		
	});
	houseMarker[id] = marker;
	return marker;
}


//*************************
// BUS ROUTE FUNCTIONS
//*************************
//@filename:  the name of the xml file with bus route data.  No extension
function route(file_name, color) {
	if (busRoutes[file_name]) {
		  map.removeOverlay(busRoutes[file_name]);
		  busRoutes[file_name] = null;
		  li = document.getElementById(file_name);
		  li.className = 'offRoute';
	}
	else {
		  var request = GXmlHttp.create();
		  var points = [];
		  request.open("GET", "bus_routes/"+file_name+".xml", true);
		  request.onreadystatechange = function() {
			if (request.readyState == 4) {
			  var xmlDoc = request.responseXML;
			  var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			 
			  for (var i = 0; i < markers.length; i++) {
					  points.push(new GPoint(parseFloat(markers[i].getAttribute('lng')), parseFloat(markers[i].getAttribute('lat'))));
			  }
			}
			busRoutes[file_name] = new GPolyline(points, color);
			map.addOverlay(busRoutes[file_name]);
			li = document.getElementById(file_name);
			li.className = 'onRoute';
		  }
		  request.send(null);
	}
}

function routeAll() {
	clearAll();
	for (var i = 1; i < 20; i++) {
		route(i);
	}
}

function clearAll() {
	for (var i = 0; i < 20; i++) {
		if(busRoutes[i]) { route(i);}
	}
}

