/*
 * dFrame2 by Haoshiro
 * 2010-10-14r1
 * Simple jQuery plugin for iframe-like ajax, plus support for history
 * License: Take it, use it, love it.
 */
(function( $ ){
	// dFrame
	$.fn.extend(
	{
		dFrame: function()
		{
			return this.each( function()
			{
				var $this = $( this );
				var uri = $this.attr( "rel" );

				if ( uri )
				{
					$this.load( uri, function()
					{
						$this.trigger( "load" );
					});
				}
			});
		}
	});
	
	window.dFrame = function()
	{
		return {
			__initialMap: {},
			__lastURL: location.href,
			
			UpdateHistory: function( id, uri )
			{
				var map = this.GetMap();
				if ( id && uri ) map[id] = uri;
				this.UpdateLocation( map );
			},
	
			UpdateLocation: function( map )
			{
				var baseURL = location.href.substr(0, location.href.indexOf("#?")) || location.href;
				var qs = '';
				
				for ( i in map )
				{
					if ( i )
					{
						if ( qs ) qs = qs + "&";
						qs = qs + i + "=" + map[i];
					}
				}
				
				location.href = baseURL + "#?" + qs;
			},
	
			UpdateDOM: function( map )
			{
				for ( i in map )
				{
					if ( i )
					{
						$( "#"+i ).attr( "rel", map[i] );
					}
				}
			},
			
			GetMap: function()
			{
				if ( location.href.indexOf("#?") < 0 )
				{
					return {};
				}
				
				var item = [];
				var map = {};
				var qs = location.href.substr( location.href.indexOf("#?") + 2 ).split( "&" );
				
				for ( var i in qs )
				{
					item = qs[i].split("=");
					map[item[0]] = item[1];
				}
		
				return map;
			},
	
			MonitorLocation: function()
			{
				if ( location.href != this.__lastURL )
				{
					this.__lastURL = location.href;
					var map = this.GetMap();
					if ( $.isEmptyObject(map) ) map = this.__initialMap;
					this.UpdateDOM( map );
					for ( i in map )
					{
						$( "#"+i ).dFrame();
					}
				}
				
				setTimeout( "window.dFrame.MonitorLocation()", 100 );
			}
		};
	}();
	
	// Links
	$("a.dframe,a.dFrame").live("click", function()
	{
		var $this = $( this );
		var uri = $this.attr( "href" );
		var id = $this.attr( "rel" );
					
		if ( id && uri )
		{
			$("#"+id).load( uri );
		}
		else if ( uri )
		{
			var $parent = $this.parents(".dframe,.dFrame").not("a").first();
			id = $parent.attr("id");
			$parent.load( uri );
		}
		
		dFrame.UpdateHistory( id, uri );
		
		return false;
	});
	
	// Auto-start
	$( function()
	{
		dFrame.UpdateDOM( dFrame.GetMap() );
		
		// Default map
		$(".dframe,.dFrame").not("a").each( function()
		{
			dFrame.__initialMap[$(this).attr("id")] = $(this).attr("rel");
		});
		
		$(".dframe,.dFrame").not("a").dFrame();
		dFrame.MonitorLocation();
	});
})( jQuery );


