// JavaScript Document
var daysEnglish = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var monthsEnglish = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

var daysHawaiian = new Array("L&#257;pule", "Po'akahi", "Po'alua", "Po'akolu", "Po'ah&#257;", "Po'alima", "Po'aono");
var monthsHawaiian = new Array("Ianuali", "Pepeluali", "Malaki", "'Apelila", "Mei", "Iune", "Iulai", "'Aukake", "Kepakemapa", "'Okakopa", "Nowemapa", "K&#275;k&#275;mapa");

function setHeaderDate()
{
	var div = document.getElementById("headerDate");
	if (div != null)
	{
		var todayEnglish = getTodayEnglish(); //"Sunday, July 15, 2007";
		var todayHawaiian = getTodayHawaiian(); // "Lāpule, Iulai 15, 2007";
		div.innerHTML = todayEnglish + "<br /><span title=\"Today's Date in Hawaiian\">" + todayHawaiian + "</span>"; 
	}
}

function getTodayEnglish()
{
	var str = "";
	now = new Date();
	str += daysEnglish[now.getDay()];
	str += ", " + monthsEnglish[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear();
	return str;
}


function getTodayHawaiian()
{
	var str = "";
	now = new Date();
	str += daysHawaiian[now.getDay()];
	str += ", " + monthsHawaiian[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear();
	return str;
}

function getHTTPObject()
{
    var request = null;

    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (!request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    if(request)  
    {
	return request;
    }  
    else 
    {
        alert("Your browser does not permit the use of all of this application's features!");
    }
}

function loadFeeds_daily_content()
{
    load_tags("/inc_rss.php?id=1", "title", "wod", "description", "wod_def");
    load_tags("/inc_rss.php?id=2", "title", "pod", "description", "pod_def");
    load_tags("/inc_rss.php?id=3", "title", "fod");
}

function loadFeeds_climate(m, s, div)
{
	load_climate_averages("/climate_data.php?m=" + m + "&l=" + m + "&s=" + s, div);
}

function doChangeMonth(n)
{
	// assume month is the dropdown list
	var lst = document.getElementById("month");
	// get current index
	var index = lst.selectedIndex;
	// get count
	var count = lst.options.length - 1;
	// find next number
	var next = index;
	if (n == 1)
	{
		if (index == count) next = 0; else next = index + 1;
	}
	else if (n == -1)
	{
		if (index == 0) next = count; else next = index - 1;
	}
	// test
	//alert("Selected: " + index + " of " + count + " and next " + next);
	// change selection
	lst.selectedIndex = next;
	doUpdateAverages(lst);
}

function load_climate_averages(url, divName)
{
	var div = document.getElementById(divName);

	var httpreq = getHTTPObject();
	
    httpreq.open("GET", url, true);

    httpreq.onreadystatechange = function () {
			if (httpreq.readyState == 4)
			{
				var div = document.getElementById(divName);
		
				if (httpreq.responseXML)
				{
					last_xml_response = httpreq.responseXML;
					format_climate(last_xml_response, div);
				}
				else 
				{		
					div.innerHTML = "Data not available."; 
				}
			}
    }

    httpreq.send(null);		
}

function load_yweather(url)
{	
	var httpreq = getHTTPObject();
	
    httpreq.open("GET", url, true);

    httpreq.onreadystatechange = function () {
			if (httpreq.readyState == 4)
			{		
				if (httpreq.responseText)
				{
					last_text_response = httpreq.responseText;
					format_yweather(last_text_response);//, div);
				}
				else 
				{		
					//div.innerHTML = "Data not available."; 
				}
			}
    }

    httpreq.send(null);		
}

function format_climate(response, div)
{
    var doc = response.documentElement;
	var content = doc.getElementsByTagName('content')[0];
	var len = content.childNodes.length;
	if (len == 1) index = 0;
	if (len > 1) index = 1;
	div.innerHTML = content.childNodes[index].nodeValue;
}

function format_yweather(response) //, div)
{
	//alert(response);
	var func = new Function("return " + response);
	var obj  = func();
	var weather = obj.Weather;
	var divName = "yweather-conditions";
	var divOuter = document.getElementById(divName);
	
	//alert(weather);
	var count = weather.length;
	
	for(var i = 0; i < count; i++)
	{
		var loc = weather[i];
		
		var div = document.createElement("div");
		div.setAttribute("class", "wcc");
		div.setAttribute("className", "wcc");
		
		// display location with details
		var h = document.createElement("h3");
		h.appendChild(document.createTextNode(loc.City));
		div.appendChild(h);
		
		var p = document.createElement("p");
		p.setAttribute("class", "now");
		p.setAttribute("className", "now");

		var img = document.createElement("img");
		img.setAttribute("src", loc.ImageUrl);
		p.appendChild(img);
		p.appendChild(document.createTextNode(loc.Temp + "°F"));
		div.appendChild(p);


		p = document.createElement("p");
		p.setAttribute("class", "detail");
		p.setAttribute("className", "detail");
		p.appendChild(document.createTextNode("Currently: " + loc.Condition));
		p.appendChild(document.createElement("br"));
		p.appendChild(document.createTextNode("Wind: " + loc.Wind));
		p.appendChild(document.createElement("br"));
		p.appendChild(document.createTextNode("Humidity: " + loc.Humid + "%"));
		p.appendChild(document.createElement("br"));
		div.appendChild(p);
	
		p = document.createElement("p");
		p.setAttribute("class", "today");
		p.setAttribute("className", "today");
		p.appendChild(document.createTextNode("Today: " + loc.High + "° / " + loc.Low + "°"));
		div.appendChild(p);

		p = document.createElement("p");
		p.setAttribute("class", "sun");
		p.setAttribute("className", "sun");
		p.appendChild(document.createTextNode("Sunrise/Sunset: " + loc.Sunrise + " / " + loc.Sunset));
		div.appendChild(p);
		
		p = document.createElement("p");
		p.setAttribute("class", "as");
		p.setAttribute("className", "as");
		p.appendChild(document.createTextNode("Conditions as of " + loc.Time));
		div.appendChild(p);		

		divOuter.appendChild(div);
	}
	
	return;
}

function escapeHTML(str)
{
	var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

function unescapeHTML(str) {
    var div = document.createElement('div');
    div.innerHTML = stripTags(str);
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      inject($A(div.childNodes),'',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  }
  
 function stripTags(str) {
    return str.replace(/<\/?[^>]+>/gi, '');
  }
  
 function inject(arr, memo, iterator) {
    arr.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  }
  
  function setClass(obj, className)
  {
	  // set class name
	  obj.setAttribute("class", className);
	  obj.setAttribute("className", className);
  }
  
  
  // still used in func_howfar.js and func_photos.js
  function setWidthHeight(obj, width, height)
	{
		// check if there is a style element as an object (IE)
		if (obj.getAttribute("style") != null)
		{
			// IE
			//alert("Aloha IE, "+ width);
			obj.style.width = width;
			obj.style.height = height;
		}
		else
		{
			// Firefox
			//alert("Aloha Firefox");
			obj.setAttribute("style", "width: " + width + "; height: " + height + ";");
	
		}
	}
	
/* jquery replacements */	
	function loadBlogPosts()
	{
		$('#blog_list').each(function() {
			var $container = $(this);
			$container.empty();
			var $list = $('<ul></ul>');
			$.get('/inc_rss.php?id=35', function(data) {
				$('feed entry:lt(5)', data).each(function() {
					var $link = $('<a></a>')
						.attr('href', $('link[rel=alternate]', this).attr('href'))
						.text($('title', this).text());
					$('<li></li>')
						.append($link)
						.appendTo($list);
				});
			});
			$list.appendTo($container);
		});
	}
	
	function loadIsItMaui()
	{
		$('#isit_maui').each(function() {
			var $container = $(this);
			$container.empty();
			$.getJSON('/inc_isitmaui.php', function(data) {
				//alert(data);
				$.each(data, function(entryIndex, photo) {
					//alert(entry['ImageUrl']);
					
				// scale photo to max width of 180 if needed
				var pWidth = parseFloat(photo['Width']);
				var pHeight = parseFloat(photo['Height']);
				
			
				if (pWidth > 180)
				{
					var scale = 180 / pWidth;
					pWidth = scale * pWidth;
					pHeight = scale * pHeight;
				}
				
				var $frame = $('<div></div>')
					.addClass('photo-inline')
					.css({ 'width' : (pWidth + 10) + 'px', 'height' : (pHeight + 10) + 'px'})
					.appendTo($container);
					
				$('<img></img>')
					.attr('src', photo['ImageUrl'])
					.css({ 'width' : pWidth + 'px', 'height' : pHeight + 'px'})
					.appendTo($frame);
				});
			});
		});		
	}
	
	function load_tags(url, node1, tag1, node2, tag2)
	{
		$.get(url, function(data) {
			$('rss channel item:first', data).each(function() {
				$('#' + tag1).text($(node1, this).text());
				if (tag2)
					$('#' + tag2).text($(node2, this).text());
			});
		});	
	}
	
	function loadYWeather2(div)
	{
		$('#' + div).each(function() {
			var $container = $(this);
			$container.append('<p>Loading...</p>');
			$.getJSON('/inc_weather2.php', function(data) {
				$container.empty();
				//alert(data);
				$.each(data, function(entryIndex, weather) {
					loc = weather[0];
					
					$('<div></div>')
						.addClass('wcc')
						.appendTo($container);
						
					$('<p></p>')
						.addClass('now')
						.appendTo('div.wcc');
						
					$('<img></img>')
						.attr('src', loc['ImageUrl'])
						.appendTo('div.wcc p.now');
					
					$('div.wcc p.now').append(loc['Temp'] + '°F');
					
					$('<h3></h3>')
						.append(loc['City'])
						.appendTo('div.wcc');
						
					$('<p></p>')
						.addClass('detail')
						.append('Currently: ' + loc['Condition'])
						.append('<br />')
						.append('Today: ' + loc['High'] + '° / ' + loc['Low'] + '°')
						.appendTo('div.wcc');
						
					$('<p></p>')
						.addClass('as')
						.append('Current as of ' + loc['Time'])
						.appendTo('div.wcc');
				});
			});
		});		
	}	
