var recentHash = "";
var drawMap = false;

//url parsing
String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};

String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}


$(window).load(function(){
	recentHash = window.location.hash;
	if (recentHash == "") {
		recentHash = "#02about";
		window.location.hash = "02about";
	}
	
	if ((recentHash == "locationtest") || (recentHash == "02locations")) {
		GUnload();
	}
	gotoArticle(recentHash);
});

function pollArticle() {
	if (window.location.hash==recentHash) {
		return; // Nothing's changed since last polled.
	}
	recentHash = window.location.hash;

	// URL has changed, update the UI accordingly.
	gotoArticle(recentHash);
}

function mapsLoaded() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(1.369915, 103.849670), 12);
		map.setUIToDefault();

		var artIcon = new GIcon(G_DEFAULT_ICON);
		artIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_star.png";
		artIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		artIcon.iconSize = new GSize(12, 20);
		artIcon.shadowSize = new GSize(22, 20);
		artIcon.iconAnchor = new GPoint(6, 20);
		artIcon.infoWindowAnchor = new GPoint(6, 1);
		artOptions = {icon:artIcon};
		
		var cbdIcon = new GIcon(G_DEFAULT_ICON);
		cbdIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_blue.png";
		cbdIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		cbdIcon.iconSize = new GSize(12, 20);
		cbdIcon.shadowSize = new GSize(22, 20);
		cbdIcon.iconAnchor = new GPoint(6, 20);
		cbdIcon.infoWindowAnchor = new GPoint(6, 1);
		cbdOptions = {icon:cbdIcon};
		
		var crIcon = new GIcon(G_DEFAULT_ICON);
		crIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_green.png";
		crIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		crIcon.iconSize = new GSize(12, 20);
		crIcon.shadowSize = new GSize(22, 20);
		crIcon.iconAnchor = new GPoint(6, 20);
		crIcon.infoWindowAnchor = new GPoint(6, 1);
		crOptions = {icon:crIcon};
		
		var erIcon = new GIcon(G_DEFAULT_ICON);
		erIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_pink.png";
		erIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		erIcon.iconSize = new GSize(12, 20);
		erIcon.shadowSize = new GSize(22, 20);
		erIcon.iconAnchor = new GPoint(6, 20);
		erIcon.infoWindowAnchor = new GPoint(6, 1);
		erOptions = {icon:erIcon};
		
		var nrIcon = new GIcon(G_DEFAULT_ICON);
		nrIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_yellow.png";
		nrIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		nrIcon.iconSize = new GSize(12, 20);
		nrIcon.shadowSize = new GSize(22, 20);
		nrIcon.iconAnchor = new GPoint(6, 20);
		nrIcon.infoWindowAnchor = new GPoint(6, 1);
		nrOptions = {icon:nrIcon};
		
		var nerIcon = new GIcon(G_DEFAULT_ICON);
		nerIcon.image = "http://www.farm.sg/bank/common/farm_mapmarker_red.png";
		nerIcon.shadow = "http://www.farm.sg/bank/common/farm_mapmarker_small_shadow.png";
		nerIcon.iconSize = new GSize(12, 20);
		nerIcon.shadowSize = new GSize(22, 20);
		nerIcon.iconAnchor = new GPoint(6, 20);
		nerIcon.infoWindowAnchor = new GPoint(6, 1);
		nerOptions = {icon:nerIcon};
		
		var counter = 0
		$.get('/bank/stamp/stamp.rss', function(data) {
			$(data).find('item').each(function(){
				counter++;
				var xy = jQuery.trim($(this).children("[nodeName=georss:point]").text()).split(' ');
				var title = jQuery.trim($(this).children("title").text());
				// split the title into code and place name
				var code = title.substr(0, title.indexOf(' ')); 
				var place = title.substr(title.indexOf(' ') + 1);
				var desc = '<div style="width: 300px; height 300px;"><b>'+ code + ' ' + place +'</b><br />' + jQuery.trim($(this).children("description").text()) + '</div>';
				var point = new GLatLng(xy[0], xy[1]);
										
				if (title.indexOf("ART") == 0) {
					var marker = new GMarker(point, artOptions);
					$("#artlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				} else if (title.indexOf("CBD") == 0) {
					var marker = new GMarker(point, cbdOptions);
					$("#cbdlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				} else if (title.indexOf("CR") == 0) {
					var marker = new GMarker(point, crOptions);
					$("#crlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				} else if (title.indexOf("ER") == 0) {
					var marker = new GMarker(point, erOptions);
					$("#erlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				} else if (title.indexOf("NR") == 0) {
					var marker = new GMarker(point, nrOptions);
					$("#nrlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				} else {
					var marker = new GMarker(point, nerOptions);
					$("#nerlinks").append('<a id="maplink' + counter + '" title="' + place + '">' + code + ' ' + place + '</a><br />');
				}
				GEvent.addListener(marker, "click", function() {
					this.openInfoWindowHtml(desc);
				});
				
				var maplink = document.getElementById("maplink" + counter);
				GEvent.addDomListener(maplink, "click", function(){
					map.setCenter(marker.getLatLng(), 17);
					marker.openInfoWindowHtml(desc);
				});
				
				map.addOverlay(marker);
			});
			var resetmap = document.getElementById("resetmap");
			GEvent.addDomListener(resetmap, "click", function(){
				map.setCenter(new GLatLng(1.369915, 103.849670), 12);
			});
		}, 'xml');
	}
}

function gotoArticle(article) {
	//figure out the title
	var title = article.substr(3);
	switch(title)
	{
		case 'process':
  			title = 'Process';
  			break;
		case 'locations':
  			title = 'Locations';
  			break;
  		case 'win':
  			title = 'Win!';
  			break;
  		case 'vote':
  			title = 'Vote';
  			break;
  		case 'team':
  			title = 'Team';
  			break;
  		case 'faq':
  			title = 'FAQ';
  			break;
  		case 'artists':
  			title = 'Artists';
  			break;
		default:
  			title = '';
	}
	
	// if title not found, redirect to #02about
	
	if (title == '' && article != '#02about' && article != '#01about' &&  !(article.startsWith('#gallery')) &&  !(article.startsWith('#locationtest'))) {
		article = "#02about";
	}
	
	if (article.startsWith('#locationtest') || article.startsWith('#02locations')) {
		drawMap = true;
	} else {
		drawMap = false;
	}
	
	$('#content').load('/stamp/' + article.substr(1) + ' div#content >*', contentCallback);
		
	// fix menu transparency
	var prefix = article.substr(1, 2);
	$('div.sectionbar div.sect').removeClass('current');
	//put back the background color
	$('#content').css('background-color','white');
	if (prefix == 'ga') {
		//change the menu
		$('#gallerysection').addClass('current');
		//change the header links
		$('#stampheaderlinks ~ div').remove();
		$('#stampheaderlinks').html("STAMP Gallery").addClass('last');
		//change the title
		document.title = 'FARM | STAMP Gallery';
		//remove the background color, else got a line
		$('#content').css('background-color','transparent');
	} else {
		//change the menu
		$('#stamp' + prefix + 'section').addClass('current');
		
		//change the header links
		if (title == '') {
			$('#stampheaderlinks ~ div').remove();
			$('#stampheaderlinks').html("STAMP " + prefix).addClass('last');
		} else {
			$('#stampheaderlinks').html("<a href='/stamp/#" + prefix + "about'>STAMP " + prefix + "</a>").removeClass('last');
			$('#stampheaderlinks ~ div').remove();
			$('#stampheaderlinks').after("<div class='last parts'>" + title + "</div>");
		}
				
		//change the title
		document.title = 'FARM | STAMP ' + prefix;
		if (title != '') document.title = document.title + ' | ' + title;
	}
}

var page = 1;
var totalpages;

function prevNews() {
	page = page + 1;
	$.get("http://twitter.com/statuses/user_timeline.json", {id: "99864853", count: "1", page: page}, function(data){
		$('#message').html(data[0].text.parseURL());
		$('#date').text('Posted on ' + Date.parse(data[0].created_at).toString('dd.MM.yyyy'));
		//totalpages = data[0].user.statuses_count;
		if (page == totalpages) {
			$('#prevNews').css('display', 'none');
		}
	
		if (page != 1) {
			$('#nextNews').css('display', 'inline');
		}
	}, 'jsonp');
}

function nextNews() {
	if (page > 1) {
		page = page - 1;
		$.get("http://twitter.com/statuses/user_timeline.json", {id: "99864853", count: "1", page: page}, function(data){
			$('#message').html(data[0].text.parseURL());
			$('#date').text('Posted on ' + Date.parse(data[0].created_at).toString('dd.MM.yyyy'));
			//totalpages = data[0].user.statuses_count;
			if (page < totalpages) {
				$('#prevNews').css('display', 'inline');
			}
		
			if (page == 1) {
				$('#nextNews').css('display', 'none');
			}
		}, 'jsonp');
	} 
}

function contentCallback() {
	$('div.item div.pictures img').fadeIn('1500');
	
	//squares effects
	$(".item").hover(
		function () {
			$(this).addClass("selected");
			// fix for IE cleartype
			//$(this).find(".details").fadeIn("normal", function(){if ($.browser.msie){this.style.removeAttribute('filter');}});
			$(this).find(".pictures").fadeOut("normal");
			if ($.browser.msie) {
				$(this).find(".details").css('display', 'block');
			} else {
				$(this).find(".details").fadeIn("normal");
			}
		}, 
		function () {
			$(this).removeClass("selected");
			$(this).find(".pictures").fadeIn("normal");
			if ($.browser.msie) {
				$(this).find(".details").css('display', 'none');
			} else {
				$(this).find(".details").fadeOut("normal");
			}
		}
   );
   
   $('div.article div.section:not(current)').click(function(){
		var address = $(this).attr('id');
		window.location.hash = address;
	});
	
	if (drawMap) {
		//google.load("maps", "2", {"callback" : mapsLoaded, "other_params" : "sensor=false"});
		mapsLoaded();
	}
}

function stampDetails(title) {
	$('#postbox div.content').load('/stamp/postbox/' + title, {}, function(){
		$('#postbox').dialog('open');
		$('div#postboxdetails').height($("div#postboxbody").height() - $('div#postboxtitle').outerHeight() - $('div#postboxfields').outerHeight() - $('div#postboxviews').outerHeight() - 15);
		$('#postboxdetails').jScrollPane();
	});
}

function randomFeatured() {
	//$('#featured').load('/stamp/featured');
	
	$('#featured').fadeOut('fast').load('/stamp/featured', function(){
		$('#featured').fadeIn('slow');
		$('div.item div.pictures img').fadeIn('1500');
		$(".item").hover(
			function () {
				$(this).addClass("selected");
				// fix for IE cleartype
				//$(this).find(".details").fadeIn("normal", function(){if ($.browser.msie){this.style.removeAttribute('filter');}});
				$(this).find(".pictures").fadeOut("normal");
				if ($.browser.msie) {
					$(this).find(".details").css('display', 'block');
				} else {
					$(this).find(".details").fadeIn("normal");
				}
			}, 
			function () {
				$(this).removeClass("selected");
				$(this).find(".pictures").fadeIn("normal");
				if ($.browser.msie) {
					$(this).find(".details").css('display', 'none');
				} else {
					$(this).find(".details").fadeOut("normal");
				}
			}
   		);
	});
}

function showTellAFriend() {
	$("#email div.preview").css("background-image", "url('/bank/stamp/farm_stamp_bg01.gif')")
	$("#email div.preview img").attr('src', '/bank/stamp/farm_stamp_popup_email.gif');
	$('div.body h1').html('Join<br />STAMP<br />with me!');
	$("div.emailform").load("/stamp/tellafriend/1189", '', function(){
		$("#email").dialog('open');
	});	
}

function openVoteWindow() {
	if ( $.browser.msie && (parseInt(jQuery.browser.version) <= 7) ) {
		vote=window.open('http://www.forecepts.com/stamp2/votes/register.php');
	} else {
		vote=window.open('http://www.forecepts.com/stamp2/votes/register.php');
	}
}
	
$(document).ready(function() {
	$("#postbox").dialog({
		autoOpen : false,
		bgiframe: true,
		height: 450,
		width: 850,
		modal: true,
		resizable: false,
		draggable: false
	});
	$('.ui-dialog').css({position:"fixed"});
	
	$('div.article div.section:not(current)').click(function(){
		var address = $(this).attr('id');
		//$('#content').load(address + ' div#content >*', contentCallback);
		window.location.hash = address;
	});
	
	$.get("http://twitter.com/statuses/user_timeline.json", {id: "99864853", count: "1"}, function(data){
		$('#message').html(data[0].text.parseURL());
		$('#date').text('Posted on ' + Date.parse(data[0].created_at).toString('dd.MM.yyyy'));
		totalpages = data[0].user.statuses_count;
		if (page == totalpages) {
			$('#prevNews').css('display', 'none');
		}
	}, 'jsonp');
	
	$('#stamp01section').click(function(){
		$('div.sectionbar div.sect').removeClass('current');
		$('#stamp01section').addClass('current');
		window.location.hash = '01about';
	});
	
	$('#stamp02section').click(function(){
		$('div.sectionbar div.sect').removeClass('current');
		$('#stamp02section').addClass('current');
		window.location.hash = '02about';
	});
	
	$('#gallerysection').click(function(){
		$('div.sectionbar div.sect').removeClass('current');
		$(this).addClass('current');
		window.location.hash = 'gallery';
	});
	
	$('img#appleorange').hover(function(){
		$('img#appleorange').attr('src', '/bank/stamp/farm_stamp02_vote_button_mouseover.gif');
	}, function(){
		$('img#appleorange').attr('src', '/bank/stamp/farm_stamp02_vote_button_now.gif');
	});
	
	$('div.sectionbar div.sect:not(current)').hover(
		function(){$(this).addClass('hover');}, function() {$(this).removeClass('hover');})
	.mousedown(function(){ 
      $(this).addClass('click');
    }).mouseup(function(){
      $(this).removeClass('click');
    });
	
	featureId = setInterval(randomFeatured, 15000);
	pollId = setInterval(pollArticle, 500);
});