/**
 * jQuery wrapper function
 */
( function( $ ) {
    /**
     * Creates a namespace specified by the arguments
     * of the function
     */
    $.createNamespace = function() {
        var a=arguments, o=null, i, j, d;
        for (i=0; i<a.length; i=i+1) {
            d=a[i].split(".");
            o=window;
            for (j=0; j<d.length; j=j+1) {
                o[d[j]]=o[d[j]] || {};
                o=o[d[j]];
            }
        }
        return o;
    };
})( jQuery );

var SCIBUFF = jQuery.createNamespace( 'com.scibuff.astroevents' );
var TREEMAP = jQuery.createNamespace( 'com.scibuff.astroevents.treemap' );

( function( $ ) {

	TREEMAP.Options = function(){
		var tmp = {};
		var pub = {};
		pub.lightbox = {
			download_link: true,
			show_linkback: false,
			show_helper_text: false			
		};
		pub.dataManager = {
			COUNT_PER_PAGE: 100
		}
		
		return pub;
	}();

	TREEMAP.DataManager = function(){
		var tmp = {};
		tmp.query = null;
		tmp.photos = {};
		tmp.refresh = false;
		
		
		/**
		 * Returns the current query
		 */
		tmp.getQuery = function(){
			if ( tmp.query == null || tmp.query == '' ){
				// add the hash tag
				var s = TREEMAP.USER + ' ' + TREEMAP.HASH_TAGS;
				//var s = TREEMAP.HASH_TAGS;
				tmp.query = '?q=' + escape( s );
			}
			return tmp.query;
		}
		
		/**
		 * Process the data returns from the data request
		 * @param {Object} data
		 */
		tmp.processData = function( data ){
			tmp.query = data.refresh_url;
			var results = [];
			
			$.each( data.results, function( i, item ) {
				results.push({
					"from_user": item.from_user,
					"created_at": item.created_at,
					"text": item.text,
					"id": item.id
				});
			});			
			
			$.post( 'treemap-utils.php', {
					query: $.base64Encode( data.refresh_url ),
					data: $.base64Encode( $.toJSON( results ) )
				},
				function(data) {
					tmp.createTreemap( data );
				}
			);				
		}		
		
		tmp.createTreemap = function( data ){

			var o = eval("(" + data + ")");

			TREEMAP.Treemap.initialize();
			TREEMAP.Treemap.TM.loadJSON( o );
			tmp.showUpdate( false );
			
		}
		
		/**
		 * Displays the loading graphics
		 * @param {Object} value
		 */
		tmp.showUpdate = function( value ){
			/*
			if ( value ){
				$('#loading').show().slideDown('slow');
			}
			else {
				$('#loading').slideUp('slow').hide();
			}
			*/
		}
		
		var pub = {};
		
		/**
		 * Sets the query value
		 * @param String query	the new query
		 */
		pub.setQuery = function( query ){
			tmp.query = query;
		}
		
		/**
		 * Requests data
		 */
		pub.requestData = function( refresh ){
			tmp.showUpdate( true );
			tmp.refresh = refresh;

		    var url = 'http://search.twitter.com/search.json';
			url += tmp.getQuery();
			url += '&page=1';
			url += '&rpp='+TREEMAP.Options.dataManager.COUNT_PER_PAGE;
			url += '&callback=?';
			$.getJSON( url, function(data) {
				tmp.processData( data );
			});	
		}
		
		return pub;
	}();



/*
 * http://thejit.org/tutorials/treemap/
 * http://thejit.org/docs/files/Treemap-js.html#TM.setColor
 * http://thejit.org/docs/files/Treemap-js.html
 */

	TREEMAP.Treemap = function(){
		// private fields
		var tmp = {};
		// public fields
		var pub = {};
		
		/**
		 * Initializes The Tree Map 
		 */
		pub.initialize = function(){
			
			if ( pub.TM ){ pub.TM.destroyElements(); }

			pub.TM = new TM.Squarified({  
				//Where to inject the Treemap  
				rootId: 'content-treemap',
				titleHeight: 22,
				addLeftClickHandler: true,
				Color: {  
					//Allow coloring  
					allow: true,  
					//Select a value range for the $color  
					//property. Default's to -100 and 100.  
					minValue: -100,  
					maxValue: 100,  
 
					maxColorValue: TREEMAP.MAX_COLOR,  
					minColorValue: TREEMAP.MIN_COLOR  
				},
		        //Allow tips
		        Tips: {
					allow: true,
					//add positioning offsets
					offsetX: 20,
					offsetY: 20,
					//implement the onShow method to
					//add content to the tooltip when a node
					//is hovered
					onShow: function(tip, node, isLeaf, domElement){
						if ( node && "text" in node.data && node.data.text != '') {
							tip.innerHTML = "<div class=\"tip-container\"><div class=\"tip-title\">@" + node.name + "</div>" +
							"<div class=\"tip-text\">" +
							this.makeHTMLFromData(node.data) +
							"</div></div>";
						}
						else {
							tip.innerHTML = "";
						}
					},
					
					//Build the tooltip inner html by taking each node data property
					makeHTMLFromData: function(data){
						var html = '';
						html += "<span class=\"tip-text-shaded\">tweep score:</span> " + data.$area + '<br />';
						if ("text" in data) 
							html += "<span class=\"tip-text-shaded\">last tweep:</span> " + data.text + "";
						return html;
					}
				}
			});

			TM.Squarified.implement({  
				'onLeftClick': function(elem) {  
					var user = elem.innerHTML;
					var ids = $(elem).parent().attr('id').split('-');
					var hash = ids[1];
					window.open( 'http://search.twitter.com/search?from='+user+'&q='+hash );
				}  
			});
			
		}
		
		return pub;
	}();
	
})( jQuery );
