// 	===================================
//	Globals
// 	===================================
	window.div		=	'doitnw_xml';	// Target div for ouput
	window.featured =	'featuredTarget'; // Target div for featured restaurant
	window.sheet 	= 	1;				// Use first sheet of spreadsheet
	window.type		=	'list';			// JSON stream type 'list' calls listEntries(), 'cells' calls cellEntries()

// 	======================
//	Init
// 	======================
	//jQuery.noConflict(); // Safety first
	var $j = jQuery;
	
	// If our div exists and is ready, call the display function
	// We use DOM ready because it's more reliable than an onLoad call
	$j('#'+window.div).ready(function(){
		displayResults();	// displayResults calls the Google Data, which then refers to
							// a callback function. The callback interprets and outputs the data
	});
	
// 	======================
//	Identify City
// 	======================
	// The URLs fo the cities take a few different forms, so we make a few exceptions
	
	var url = location.href.split('/'); // Change request URL into an array
	var city = '';
	var cityIdx = 5;
	if (url[url.length - 2]=='seattle' || url[url.length - 2]=='spokane') {
		city = url[url.length - 2];
	}
	else {
		temp = url[url.length - 1].split('.');
		city = temp[0];
	}
	
// 	===================================
//	Associate Cities with Spreadsheets
// 	===================================

	var gDocKeys = {	// Google Doc Keys
		'seattle':'pq_jQhFesPXG8RA2zf4AYdA',
		'spokane':'prk-iuW2kbIFWqqze043vHQ',
		'Idaho':'pyQcoKmzL0WOsmRuIo-mmbw',
		'Utah':'pyQcoKmzL0WPS4v-fsEOqcg',
		'Oregon':'pyQcoKmzL0WMPTNCDJ97pbQ'
	}; 
	window.key		=	gDocKeys[city]; // Relevant Google Spreadsheet Key




// 	===================================
//	Spreadsheet Shortcut
// 	===================================
	// Make it so that if a user calls a restraunt listing page with ?edit in the URL,
	// they'll be forwarded to log-in to the spreadsheet to edit content
	if (getVar('edit')==1) {
		window.location = 'http://spreadsheets.google.com/ccc?key='+window.key;
	}

// 	===================================
//	Template - Main listing
// 	===================================
	// Separated into sections for easy access (JSON)
	window.template = {
		head:		'<div class="doitnw_neighborhood">'+
						'<a name="#{title}" class="doitnw_bookmark">#{title}</a>'+
					 '',
	
		titlehead:		'<div class="doitnw_restaurant">'+
						'<div class="doitnw_restaurant_title">',
					
		titlemid:		'	<a target="_rest" class="doitnw_restaurant_link" href="#{url}">'+
								'#{name}'+
							'</a>',
						
		titlefoot:		'	</div>'+
						'<table>'+
							'<tbody>',
						
		address:	'			<tr class="doitnw_restaurant_row">'+
									'<td class="doitnw_restaurant_head">Address: </td>'+
									'<td class="doitnw_restaurant_address">#{address}</td>'+
								'</tr>',
	
		phone:		'			<tr class="doitnw_restaurant_row">'+
									'<td class="doitnw_restaurant_head">Phone: </td>'+
									'<td class="doitnw_restaurant_phone">#{phone}</td>'+
								'</tr>',
	
		hours:		'			<tr class="doitnw_restaurant_row">'+
								'	<td class="doitnw_restaurant_head">Hours: </td>'+
								'	<td class="doitnw_restaurant_hours">#{hours}</td>'+
								'</tr>',
							
		desc:		'		</tbody>'+
						'</table>'+
						'<div class="doitnw_restaurant_desc">'+
							'#{desc}'+
						'</div>'+
					'</div>',
				
		close:		'</div>',
	
		titles:		'<li><a href="##{title}">#{title}</a></li>'
	};


// 	===================================
//	JSON - Callbacks
// 	===================================
	
	// cellEntries REQUIRES columns stay in the same order.
	// So, listEntries is prefered when non-techs may be editing spreadsheets
	function cellEntries(json) {
		//console.log(json);
		var div = $('#'+window.div);
		var ul = $('#catList');
	
		removeOldResults();
		var table = document.createElement('table');
		table.setAttribute('id', 'output');
		var tbody = document.createElement('tbody');
		var tr;
		var vals = {};
	

		// Iterate through rows... Skip header 
		for (var i= json.feed.gs$colCount.$t; i < json.feed.entry.length; i++) {
			var entry = json.feed.entry[i];
			var col =  entry.gs$cell.col * 1;
			
			// Based on the column number, do different things
			// Column number is literally from left to right
			// If a column moved position, things will mess up!
			switch(col) {
				case 1:
					// Neighborhood title
					if (entry.content.$t != window.title && $.tmpl != null) {
						window.title = entry.content.$t;
						vals.title = window.title;
					
						if (vals.title.indexOf(toProperCase(city)) != -1 && window[city] != 1) {
							window[city] = 1;
							vals.title = toProperCase(city);
							var list = $.tmpl(window.template.titles, vals);
							ul.append(list);
						} else if (vals.title.indexOf(toProperCase(city)) == -1){
							var list = $.tmpl(window.template.titles, vals);
							ul.append(list);
						}
						vals.title = window.title;
					
						var title = $.tmpl(window.template.head, vals);
					
						if (window.first == 1) {
							window.buffer += window.template.close;
						}else if (window.template.titles != null) {
							vals.title = 'All';
							var all = $.tmpl(window.template.titles, vals);
							ul.append(all);
							window.first = 1;
						}
						div.append(window.buffer);
					
					
						window.buffer = title;
					
					}

					break; 
				   
				case 2:
					// Restaurant name
					vals.name = entry.content.$t;
					break;
				
				case 3:
					// Website url
					vals.url = entry.content.$t;
				
					if (vals.url != '') {
						if (vals.url.search('http://') == '-1') {
							vals.url = 'http://'+vals.url;
						}
						var tmp = $.tmpl(window.template.titlemid, vals);
					
						window.buffer +=  window.template.titlehead + tmp + window.template.titlefoot;
					
					} else {
						window.buffer +=  window.template.titlehead + vals.name + window.template.titlefoot;
					}
				
					break;
				
				case 4:
					// Address
					vals.address = entry.content.$t;	
					if (vals.address != '') {
						window.buffer += $.tmpl(window.template.address, vals);
					}
					break;
				
				case 5:
					// Phone
					vals.phone = entry.content.$t;	
					if (vals.phone != '') {
						window.buffer += $.tmpl(window.template.phone, vals);
					}
					break;
					
				case 6:
					// Hours
					vals.hours = entry.content.$t;	
					if (vals.hours != '') {
						window.buffer += $.tmpl(window.template.hours, vals);
					}
					break;
				
				case 7:
					// Description
					vals.desc = entry.content.$t;
					window.buffer += $.tmpl(window.template.desc, vals);
						
					break;	
			} 
		
		} 
	
		// Call binding functions that allow
		// search and category (city) links to filter content
			catlinks();
			searchform();
	
	
	} // end cellEntries()
	
	
	// listEntries allows columns to be in any order,
	// but REQUIRES that column names don't change!
	// Also, way easier to work with
	function listEntries(json) {
		//console.log(json);
		var div = $('#'+window.div);
		var ul = $('#catList');
	
		removeOldResults();
		var table = document.createElement('table');
		table.setAttribute('id', 'output');
		var tbody = document.createElement('tbody');
		var tr;
		
		$j('#'+window.div).each(function(){
			// Iterate through the rows
			for (var i = 0; i < json.feed.entry.length; i++) {
			    var entry = json.feed.entry[i]; // Current row, containing all column values
				outputRow(entry, div, ul);		
		    }
		
			// Call binding functions that allow
			// search and category (city) links to filter content
			catlinks();
			searchform();
			
		});
		
		$j('#'+window.featured).each(function(){
			var randompick = rand(1, json.feed.entry.length);
			var div = $('#'+window.featured);
			var entry = json.feed.entry[randompick]; // Current row, containing all column values	
			outputRow(entry, div, ul);	
			div.append(window.buffer);
			
		});

	} // end listEntries
	
	// Outputs rowentry to HTML
	function outputRow(entry, div, ul){
		var vals = {};
	
		// Map column names into vals, which will be passed to the template
		// Note: the name of the vals keys corespond to {#tags} in the template,
		// while names in entry.gsx$_____.$t correspond to column headers in the spreadsheet,
		// lowercase and without spaces.
	    	vals.title = entry.gsx$neighborhood.$t;
			vals.name = entry.gsx$restaurantname.$t;
			vals.url = entry.gsx$website.$t;
			vals.phone = entry.gsx$phone.$t;
			vals.hours = entry.gsx$hours.$t;
			vals.desc = entry.gsx$description.$t;
			vals.address = entry.gsx$address.$t;
		
		// !!! Cuisine and menupricerange are commented out because they are in spokane only.
		// !!! For mapping to be valid, the column must exist in all spreadsheets!!! (else: failure.)
			// vals.cuisine = entry.gsx$cuisine.$t;
			// vals.menupricerange = entry.gsx$menupricerange.$t;
		
		vals.theclass = '';
		
		//	Neighborhood titles
		// 	-------------------------
		
			if (vals.title != window.title && $.tmpl != null) {
				window.title = vals.title;
		
				if (vals.title.indexOf(toProperCase(city)) != -1 && window[city] != 1) {
					window[city] = 1;
					vals.title = toProperCase(city);
					var list = $.tmpl(window.template.titles, vals);
					ul.append(list);
				} else if (vals.title.indexOf(toProperCase(city)) == -1){
					var list = $.tmpl(window.template.titles, vals);
					ul.append(list);
				}
				vals.title = window.title;
		
				var title = $.tmpl(window.template.head, vals);
		
				if (window.first == 1) {
					window.buffer += window.template.close;
				}else if (window.template.titles != null) {
					vals.title = 'All';
					var all = $.tmpl(window.template.titles, vals);
					ul.append(all);
					window.first = 1;
				}
				div.append(window.buffer);
		
				window.buffer = title;
		
			}
		
		//	Website URL
		// 	-------------------------
			if (vals.url != '') {
				if (vals.url.search('http://') == '-1') {
					vals.url = 'http://'+vals.url;
				}
				var tmp = $.tmpl(window.template.titlemid, vals);
			
				window.buffer +=  window.template.titlehead + tmp + window.template.titlefoot;
			
			} else {
				window.buffer +=  window.template.titlehead + vals.name + window.template.titlefoot;
			}
		
		//	Address
		// 	-------------------------	
			if (vals.address != '') {
				window.buffer += $.tmpl(window.template.address, vals);
			}
			
		//	Phone
		// 	-------------------------
				if (vals.phone != '') {
					window.buffer += $.tmpl(window.template.phone, vals);
				}

		//	Hours
		// 	-------------------------
				if (vals.hours != '') {
					window.buffer += $.tmpl(window.template.hours, vals);
				}
		
		//	Description
		// 	-------------------------
			window.buffer += $.tmpl(window.template.desc, vals);
	

	}
	
	

// 	===================================
//	JSON - initializer
// 	===================================
	/*
	Called to retrieve a spreadsheet's JSON feed.
	Creates a new script element in the DOM whose source is the JSON feed and specifies
	the callback function (above) is 'listEntries' for a list feed and 'cellEntries' for a cells feed.
	*/
	function displayResults() {
	
		var key 	= 	window.key;
		var sheet 	= 	window.sheet;
		var type	=	window.type;
	
		//removeOldJSONScriptNodes();
		//removeOldResults();
	
		// Show a "Loading..." indicator.
		var div = document.getElementById(window.div);
		if (div != null) {
			div.innerHTML = 'Loading...';
		}

		// Retrieve the JSON feed.
		var script = document.createElement('script');
	
		if (type == 'list') {
			script.setAttribute('src', 'http://spreadsheets.google.com/feeds/'
		         + type
		         + '/' + key
		         + '/' + sheet + '/public/values' +
		        '?alt=json-in-script&callback=listEntries');
		}
	
		if (type == 'cells') {
			script.setAttribute('src', 'http://spreadsheets.google.com/feeds/'
		         + type
		         + '/' + key
		         + '/' + sheet + '/public/values' +
		        '?alt=json-in-script&callback=cellEntries&return-empty=true');
		}
	
		script.setAttribute('id', 'jsonScript');
		script.setAttribute('type', 'text/javascript');
		document.documentElement.firstChild.appendChild(script);;
	}



// 	===================================
//	Behavior- Catlink filter
// 	===================================
	// When a city quick link is clicked, this filters the listings down
	function catlinks(){
		$('#catList li a').click(function(){
			var name = $(this).text();
			if (name == 'All') {
				$('#doitnw_xml a[name]').parent().show().children().show();
			}else {
				//$('#doitnw_xml a[name][name!='+name+']').parent().hide();
				//$('#doitnw_xml a[name][name='+name+']').parent().show().children().show();
				$('#doitnw_xml a.doitnw_bookmark:not(:contains("'+name+'"))').parent().hide();
				$('#doitnw_xml a.doitnw_bookmark:contains("'+name+'")').parent().show().children().show();
			}

			var searchform = $('.doitnw_breadcrumb .search input');
			searchform.val( searchform.attr('rel') );

			return false;
		});
	}

// 	===================================
//	Behavior- Search form filter
// 	===================================
	function searchform(){
		// Search box
		var searchform = $('.doitnw_breadcrumb .search input');
		searchform.val( searchform.attr('rel') );
	
		searchform.parent().submit(function(){return false;});
	
		searchform.keypress(function(){
			var text = $(this).val();
		
			$('#'+window.div+' .doitnw_restaurant').hide().parent().hide();
			$('#'+window.div+' .doitnw_restaurant:contains('+text.toLowerCase()+')').show().parent().show();
			$('#'+window.div+' .doitnw_restaurant:contains('+toProperCase(text)+')').show().parent().show();
		});
	
		searchform.click(function(){
			if ($(this).attr('rel') == $(this).val()) {
				$(this).val('');
			}
		});
	
		searchform.blur(function(){
			if ($(this).val() == '') {
				$(this).val( $(this).attr('rel') );
			}
		});
		
	}

// 	===================================
//	General Utility Functions
// 	===================================

	// String trim
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	};
	
	// String to Proper Case
	function toProperCase(s) {
	  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
	          function($1) { return $1.toUpperCase(); });
	}

	// Allow javascript to access variables passed through http GET array
	function getVar(name) {
		get_string = document.location.search;         
		return_value = '';
	
		do { //This loop is made to catch all instances of any get variable.
		name_index = get_string.indexOf(name + '=');
		var name_index2 = get_string.indexOf('?' + name);
	
		if(name_index != -1 || name_index2 != -1)
		  {
		  get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
	  
		  end_of_value = get_string.indexOf('&');
		  if(end_of_value != -1)                
		    value = get_string.substr(0, end_of_value);                
		  else                
		    value = get_string;                
	    
		  if(return_value == '' || value == '')
		    //	 return_value += value;
		      return_value += 1;
		  else
		     return_value += ', ' + value;
		  }
		} while(name_index != -1)
	
		//Restores all the blank spaces.
		space = return_value.indexOf('+');
		while(space != -1)
		  { 
		  return_value = return_value.substr(0, space) + ' ' + 
		  return_value.substr(space + 1, return_value.length);
					 
		  space = return_value.indexOf('+');
		  }
	
		return(return_value);        
	}
	

	//	Removes the script element from the previous JSON result.
	function removeOldJSONScriptNodes() {
	  var jsonScript = document.getElementById('jsonScript');
	  if (jsonScript) {
	    jsonScript.parentNode.removeChild(jsonScript);
	  }
	}

	//	Removes the output generated from the previous result.
	function removeOldResults() {
	  var div = document.getElementById(window.div);
	  if (div != null)
		  div.innerHTML = '';
	}
	
	
	// Random number
	function rand( min, max ) {
	    // http://kevin.vanzonneveld.net
	    // +   original by: Leslie Hoare
	    // +   bugfixed by: Onno Marsman
	    // *     example 1: rand(1, 1);
	    // *     returns 1: 1
	    var argc = arguments.length;
	    if (argc == 0) {
	        min = 0;
	        max = 2147483647;
	    } else if (argc == 1) {
	        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
	    }
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}




//// !! References to the below code need to be removed from the region home pages!
//// !! loadFeatured needs to be replaced and removed from the HTML

/*	---------------------------------

	NATE'S CODE... DEPRECIATED. 

--------------------------------- 	*/

/*
function displayRestaurants(ml)
{

	
	var xmlDoc=null;
	try
	  {//try IE first
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	   }
	catch(e)
	  {
	  try
	    {//try Mozilla, Firefox, Opera, etc.
	    xmlDoc=document.implementation.createDocument("","",null);
	    }
	  catch(e)
	    {
	    alert(e.message);
	    return;
	    }
	  }

	if (xmlDoc!=null)
	{
	
		xmlDoc.async=false;
		xmlDoc.load("restaurants/" + ml);
		
	
		
		var doitx = xmlDoc.getElementsByTagName("neighborhood");
		var nList = "";
		
		for (i=0;i<doitx.length;i++)
		{ 
	
			document.write("<div class='doitnw_neighborhood'><a class='doitnw_bookmark' name=\"" + doitx[i].getAttribute('id') + "\">" + doitx[i].getAttribute('id') + "</a></div>");
			nList += "<div class='doitnw_nlist_item'>&#149;&nbsp;&nbsp;<a class='doitnw_nlist_link' href='#" + doitx[i].getAttribute('id')  + "'>" + doitx[i].getAttribute('id')  + "</a></div>";
			var y=doitx[i].getElementsByTagName("restaurant");
			for (j=0;j<y.length;j++)
			{ 
				
				document.write(restaurantOutput(y[j]));
			}
			document.write("<div class=\"doitnw_neighborhood_div\"></div>");
		
			
		}
document.getElementById("catList").innerHTML += nList;		
		
	}
	
}

function displayRestaurantsSea(ml)
{

	var xmlDoc=null;
		try
		  {//try IE first
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		   }
		catch(e)
		  {
		  try
		    {//try Mozilla, Firefox, Opera, etc.
		    xmlDoc=document.implementation.createDocument("","",null);
		    }
		  catch(e)
		    {
		    alert(e.message);
		    return;
		    }
		  }
	
		if (xmlDoc!=null)
		{
		
			xmlDoc.async=false;
			xmlDoc.load("restaurants/" + ml);
			
		
			
			var doitx = xmlDoc.getElementsByTagName("neighborhood");
			var nList = "";
			
			for (i=0;i<doitx.length;i++)
			{ 
		
				//document.write("<div class='doitnw_neighborhood'><a class='doitnw_bookmark' name=\"" + doitx[i].getAttribute('id') + "\">" + doitx[i].getAttribute('id') + "</a></div>");
				//nList += "<div class='doitnw_nlist_item'>&#149;&nbsp;&nbsp;<a class='doitnw_nlist_link' href='#" + doitx[i].getAttribute('id')  + "'>" + doitx[i].getAttribute('id')  + "</a></div>";
				var y=doitx[i].getElementsByTagName("restaurant");
				for (j=0;j<y.length;j++)
				{ 
					document.write(restaurantOutput(y[j]));
						
				}
				//document.write("<div class=\"doitnw_neighborhood_div\"></div>");
			
				
			}
	//document.getElementById("catList").innerHTML += nList;		
			
		}
		

	
}

function loadFeatured(ml)
{
	var featuredList = new Array();
	var xmlDoc=null;
	try
	  {//try IE first
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	   }
	catch(e)
	  {
	  try
	    {//try Mozilla, Firefox, Opera, etc.
	    xmlDoc=document.implementation.createDocument("","",null);
	    }
	  catch(e)
	    {
	    alert(e.message);
	    return;
	    }
	  }

	if (xmlDoc!=null)
	{
	
		xmlDoc.async=false;
		xmlDoc.load("restaurants/" + ml);
		
		var doitx = xmlDoc.getElementsByTagName("restaurant");
		for (i=0;i<doitx.length;i++)
		{
			if (getValue(doitx[i], 'featured') == "true")
			{
				featuredList[featuredList.length] = doitx[i];
			}
		}
		
		var output;
		if (featuredList.length > 0)
		{
			var rando = Math.random();
			rando = rando * (featuredList.length-1);
			rando = Math.ceil(rando);
			
			disp = featuredList[rando];
			output = restaurantOutput(disp);
					
		}
		else
		{
			output = "<p>There are currently no featured restaurants.</p>";
		}
		
		document.getElementById("featuredTarget").innerHTML = output;
		
	}
}






function restaurantOutput(disp)
{

	var output = "";
	xtitle = getValue(disp, 'title');
	xaddress = getValue(disp, 'address');
	xphone = getValue(disp, 'phone');
	xhours = getValue(disp, 'hours');
	xdesc = getValue(disp, 'description');
	xcategory = getValue(disp, 'category');
	xurl = getValue(disp, 'url');

	output += "<div class='doitnw_restaurant'>";
	output += "<div class='doitnw_restaurant_title'>";


	if (xurl != "")
		output += "<a href='http://" + xurl + "' class='doitnw_restaurant_link' target='_rest'>" + xtitle + "</a>";
	else
		output += xtitle;
	output += "</div>";			

	output +="<table>";
	if (xcategory != "")
	{
	output += "<tr class='doitnw_restaurant_row'><td class='doitnw_restaurant_head'>Category: </td><td class='doitnw_restaurant_category'>" + xcategory + "</td></tr>";
	}
	if (xaddress != "")
	{				
	output += "<tr class='doitnw_restaurant_row'><td class='doitnw_restaurant_head'>Address: </td><td class='doitnw_restaurant_address'>" + xaddress + "</td></tr>";
	}
	if (xphone != "")
	{
	output += "<tr class='doitnw_restaurant_row'><td class='doitnw_restaurant_head'>Phone: </td><td class='doitnw_restaurant_phone'>" + xphone + "</td></tr>";
	}
	if (xhours != "")
	{
	output += "<tr class='doitnw_restaurant_row'><td class='doitnw_restaurant_head'>Hours: </td><td class='doitnw_restaurant_hours'>" + xhours + "</td></tr>";
	}
	output += "</table>";				
	if (xdesc != "")
	{
	output += "<div class='doitnw_restaurant_desc'>" + xdesc + "</div>";
	}

	output += "</div>";
	return output;
}



function getValue(el, tit)
{
	if (el.getElementsByTagName(tit).length == 0)
	{
	return "";
	}
		
	if (el.getElementsByTagName(tit)[0].hasChildNodes())
	{
		return el.getElementsByTagName(tit)[0].childNodes[0].nodeValue;
	}
	
	return "";

}
*/