var mktTrackerJS = function(){ };

mktTrackerJS.prototype.inRibbon					= MarketTrackerRibbon || 0;
mktTrackerJS.prototype.TRACKER_BOTTOM_MARGIN	= 20;
mktTrackerJS.prototype.BUCKETS	= ["U.S. Stocks","European Markets","Asian Markets","Commodities","Currencies","Bonds & Rates"];
mktTrackerJS.prototype.DATA_URL	= "http://money.cnn.com/.element/script/3.0/data/boxes.json";
mktTrackerJS.prototype.DEFAULTS = [599362, 579435, 593933, 572094, 1070572, 617254];

jQuery.ajaxSetup( {cache:true} );

mktTrackerJS.prototype.initializeStorageManager = function() {
	var tracker = this;
	var trackerInitialize = function(){ tracker.initialize(); };
	StorageManager.getInstance().addOnLoad(trackerInitialize);
	this.storageManager = StorageManager.getInstance().getStorage();
	this.storageManager.load();
};

mktTrackerJS.prototype.getLastTrade = function(id) {
	return jQuery.grep(_MarketTrackerOptions.marketMeter.meters.meter, function(a) { return (a.streamSymbol == id); });
};

mktTrackerJS.prototype.initialize = function() {
	console.log("Storage Method is: ", this.storageManager.name);

	var usersSelections = this.storageManager.get("marketTrackerSelections");
	console.log("userSelections loaded from StorageManager: ", usersSelections );

	if(!usersSelections || jQuery.isArray(usersSelections) == -1 || usersSelections.length != 6) {
		usersSelections = this.DEFAULTS;
		console.log("Resetting userSelections to default: ", usersSelections);
	}

	var validSymbols = jQuery.map(_MarketTrackerOptions.marketMeter.meters.meter, function(a) { return Number(a.streamSymbol); });
	
	for(var i = 0; i < usersSelections.length; i++) {
		if(jQuery.inArray(usersSelections[i], validSymbols) == -1) {
			console.log("Bad Symbol: ", usersSelections[i]);
			usersSelections = this.DEFAULTS;
			console.log("Resetting userSelections to default: ", usersSelections);
			break;
		}
	}

	// Put the values back, to keep them fresh
	this.storageManager.put("marketTrackerSelections", usersSelections);
	this.storageManager.save();

	this.SAVED_HTML = jQuery("#MarketTrackerContainer").html();
	var build = function(obj) {
		jQuery("ul.wsod_firstRow").empty();
		for(var i = 0; i < usersSelections.length; i++) {
				jQuery("ul.wsod_firstRow").append(obj[usersSelections[i]]);
		}

		var latestTime = 0;
		jQuery("ul.wsod_firstRow li").each(function (i) {
				if ( jQuery(this).attr("lastTrade") ) {
						var time = new Number( jQuery(this).attr("lastTrade") );
						if ( time && time > latestTime ) { latestTime = time; }
				}
		});
		var date = new Date()
		date.setTime(latestTime);
		jQuery(".myStreamClass").html(date.format("mm/dd h:MM:sstt 'ET'"));
		var fixed = 'time_' + usersSelections.join("|");
		jQuery(".myStreamClass").attr("stream", fixed);

		jQuery("#MarketTrackerContainer").show();
		if(!ipadCheck) { jQuery("#wsod_customizeTrackerLink").show(); }

		wsod_js.streaming.restartStream();
	};
	jQuery.getJSON(this.DATA_URL, build);
};

mktTrackerJS.prototype.customize = function(el,$container){

	if (jQuery("#wsod_interactionContainer").length){ return; }
	
	var self = this;
	this.$container = this.$marketTracker = $container;
	this.$parentContainer = this.$container.parent();
	this.parentContainerId = this.$parentContainer.attr("id");
	this.who = this.$container.attr("location");//inPage or inRibbon
	
	//hide customize link
	jQuery(el).hide();

	//get position
	var containerOffset = this.$marketTracker.offset();
	var moveUpDistance = ("inRibbon" == this.who) ? 0 : this.TRACKER_BOTTOM_MARGIN;
	
	//create container for all interactions
	this.$interactionContainer = jQuery("<div />")
									.attr("id","wsod_interactionContainer")
									.css({top: containerOffset.top - moveUpDistance, left: containerOffset.left})
									.addClass(this.who)
									.appendTo("body")
								;
	
	//clone existing market tracker so it can be interacted with
	var $mtClone = this.$marketTracker.clone();
		$mtClone.addClass("wsod_clonedMarketTracker");
		
	//add clone to new "interaction container"
	$mtClone.appendTo(this.$interactionContainer);
	
	//remove OLD market tracker (pre-clone)
	this.$marketTracker.empty();
	
	//set variable to CLONED market tracker
	this.$marketTracker = $mtClone;
		
	//create customize pane
	this.$pane = jQuery("<div />")
					.attr("id","wsod_marketTrackerCustomizePane")
					.addClass(this.who)
					.addClass("wsodContent")
					.appendTo(this.$interactionContainer)
				;
	
	//fill pane with content
	jQuery("<div />")
		.addClass("intro")
		.text("Click and drag items from this area to the bar above to see them appear each time you visit the site.")
		.appendTo(this.$pane)
	;
	
	//...add 6 horizontal buckets
	this.$trackerBuckets = jQuery("<div />").addClass("clearfix").addClass("trackerBuckets").appendTo(this.$pane);
	
	//container for the row labels
	this.$bucketLabels = jQuery("<div />").addClass("bucketLabels").addClass("wsod_fLeft").appendTo(this.$trackerBuckets);
	
	//add the row labels themselves
	jQuery(this.BUCKETS).each(function(i){
		jQuery("<div />").html(self.BUCKETS[i]).appendTo(self.$bucketLabels);
	});
	
	//container for the row options
	this.$trackerOptions = jQuery("<div />")
							.addClass("bucketOptions")
							.addClass("wsod_fLeft")
							.html("<div class='meterLoading'>loading...</div>")
							.appendTo(this.$trackerBuckets)
						;
	
	self.buildTrackerOptions(_MarketTrackerOptions);
	
	//finally show it
	this.$pane.slideDown('fast');
};

mktTrackerJS.prototype.buildTrackerOptions = function(data){
	//jQuery.log(data.marketMeter)
	
	var self = this;
	var options = data.marketMeter.meters.meter; //grab JSON
	
	//find all the spans with data, hide them and insert a grey label beneath the name
	jQuery("#wsod_marketTrackerItems li").each(function(){
		var $el = jQuery(this);
		//disable Market Tracker (it'll eventually be sortable)
		$el.addClass("sortReady");
		//now empty out quote data and make buckets look sortable
		var $spans = $el.find("span");
		if($spans.length < 1){
			/**
			 * quote must've failed or something because we don't have a "format" span to grab
			 * ...instead create a span and use that as $spans
			 */
			var $divs = $el.find("div.wsod_fRight.wsod_bold").each(function(){
				jQuery(this).html("<span>--</span>");
			});
			
			$spans = $divs.find("span");
		}
		var who = $el.find("a").text();
		var $whoMeasureDiv = $el.find(".measure");
		var measureLabel = $whoMeasureDiv.text();
		var measure = self.getOptionMeasurement(who,measureLabel,options);
		//replace actual link with just text 
		var anchorText = $el.find("a").text();
		$el.find("a").replaceWith(anchorText);
		$spans.fadeOut('fast',function(){
			var measureDivData = $whoMeasureDiv.html();
			$whoMeasureDiv.data("data",measureDivData).addClass("wsod_grey").css("fontWeight","normal").html(measure).fadeIn('fast');
		});
	});
	
	//create list -- all possible options
	var $trackerOptionList = jQuery("<ul />").attr("id","marketTrackerOptions").addClass("clearfix");
	for (var i = 0; i < options.length; i++) {
		var $optionBox = jQuery("<li />").html("<div class='wsod_bold'>" +options[i].label+ "</div><div class='wsod_grey'>" + options[i].measurement + "</div>").attr("wsodissue",options[i].streamSymbol).appendTo($trackerOptionList);
	}
	
	this.$trackerOptions.empty();//remove "loading..."
	$trackerOptionList.appendTo(this.$trackerOptions);
	
	//red "Save" button and "restore" link
	var $saveButtonContainer = jQuery('<div />').addClass("clearfix");
	var $wsodButton = jQuery('<div />')
						.addClass("wsod_button")
						.hover(
							function(){
								jQuery(this).addClass("hovered");
							},
							function(){
								jQuery(this).removeClass("hovered");
							}
						)
					;
	var $saveLink = jQuery('<a href="javascript:void(0);" />')
						.text("Save & Close")
						.bind("click",function(){
							self._saveMarketMeterSelections(jQuery(this));
						})
					;
						
	$wsodButton.append($saveLink).appendTo($saveButtonContainer);
	
	//add button to pane		
	this.$pane.append($saveButtonContainer);
	
	this.setAvailableOptionsAndInitialize();
};


mktTrackerJS.prototype.initInteractions = function(){
	
	var self = this;
	var $selections = this.$marketTracker;
	var $selectionsLI = $selections.find("li");
	var $options = jQuery("#marketTrackerOptions");	
	
	//INTERACTIONS (DRAG, DROP, SORT)
	
	//destroy, if already initialized
	$options.find("li").draggable('destroy');
	$selections.sortable('destroy');
	$selectionsLI.droppable('destroy');
	
	//SORT -- let the market tracker selections be sortable amongst themselves
	$selections
		.sortable({
			items: 'li',
			containment: 'parent',
			placeholder: 'ui-sortable-highlight',
			revert: true,
			tolerance: 'pointer',
			receive: function(event, ui) {
				
			},
			start: function(event,ui){
				//disable drop, we're sorting
				_disableDroppable();
			},
			stop: function(event,ui) {
				//done sorting, enable drop
				_enableDroppable();
			}
		})	
		.disableSelection();
	
	//DROP -- let the selections be droppable, accepting the options
	$selectionsLI
		.droppable({
			activate: function(event,ui){
				//moving options around, disable sortable since we're now dropping
				_disableSortable();
				//keep track if this has been dropped
				self.hasBeenDropped = false;
			},
			hoverClass: 'drophover',
			over: function(event,ui){
				//as helper is moved around, highlight drop-zone...only when it can be dropped
				//jQuery(ui.helper).css("background","lime none");
				jQuery(this).addClass("ui-sortable-highlight");
			},
			out: function(event,ui){
				//as helper is moved around, remove highlight when it CANNOT be dropped
				//jQuery(ui.helper).css("background","red none");
				jQuery(this).removeClass("ui-sortable-highlight");
			},
			drop: function(event,ui){
				
				//now we've dropped, remove drop-zone highlight
				jQuery(this).removeClass("ui-sortable-highlight");
				
				//keep track if this has been dropped
				self.hasBeenDropped = true;
				
				//who is helper being dragged around?
				var $helper = jQuery(ui.helper);
				var whoIsHelper = $helper.attr("wsodissue"); 
				
				//who is ready to accept dropped helper?
				var $accepting = jQuery(this);
				
				//replace new option with dropped item
				var newItem = $helper.html();
				var newWho = whoIsHelper; //wsodissue					
				$accepting.html(newItem).attr("wsodissue",newWho);
				
				//highlight new item				
				$accepting.css("background","#ffff99").animate({backgroundColor:'#ffffff'},500,"",function(){ jQuery(this).removeAttr("style"); });
				
				//grey out old item and remove it's draggability since it's already in the Tracker
				self.setAvailableOptionsAndInitialize();
				
				//done moving options around, re-enable sortable on selections
				_enableSortable();
			}
		});
	
	//DRAG -- possible selections are draggable, not sortable	
	$options
		.find("li:not(.notAvailableForDrag)")
		.draggable({
			//do NOT use the "stack:{}" draggable option (breaks IE and it's not needed)
			helper: 'clone',
			//cursorAt: { top:15, right:10 },
			containment: self.$interactionContainer,
			revert: 'invalid',
			revertDuration: 200,
			start: function(event,ui) {
				//moving options around, disable sortable since we're now dropping
				_disableSortable();
				//leave a grey-shaded empty box behind (instead of original) 
				jQuery(this).addClass("ui-sortable-highlight").html("");
			},
			stop: function(event,ui) {
				//put option back together when drag stops
				jQuery(this).removeClass("ui-sortable-highlight");
				//Put the item back together on-drop
				var helperHTML = jQuery(ui.helper).html();
				jQuery(this).html(helperHTML);
				//done moving options around, re-enable sortable on selections
				_enableSortable();
			}
		})
		.disableSelection();
	
	/*helpers*/
	function _disableDroppable(){
		$selectionsLI.droppable("disable");
	}
	function _enableDroppable(){
		$selectionsLI.droppable("enable");
	}
	function _disableSortable(){
		$selections.sortable('disable');
	}
	function _enableSortable(){
		$selections.sortable('enable');
		//refresh sortables, recognizing new items
		$selections.sortable('refresh');
	}
	function _disableDraggable(){
		$options.find("li").draggable('disable');
	}
	
};

/**
 * Loop over selections in the Market Tracker and disable any options already in the Tracker
 */
mktTrackerJS.prototype.setAvailableOptionsAndInitialize = function(){
	var self = this;
	var $selections = jQuery("#wsod_marketTrackerItems").find("li");
	var $options = jQuery("#marketTrackerOptions").find("li");

	$options.each(function(){
		var $option = jQuery(this);
		var wsodIssueOfOption = jQuery(this).attr("wsodissue");
		//remove all
		$option.removeClass("notAvailableForDrag");
		//don't let options in the Tracker be dragged
		$selections.each(function(){
			var wsodIssueOfSelection = jQuery(this).attr("wsodissue");
			if (wsodIssueOfSelection == wsodIssueOfOption){
				$option.addClass("notAvailableForDrag");
			}
		});
	});
	
	//let elements drop and settle before re-initializing the interactions
	window.setTimeout(function(){
		self.initInteractions();
	},150);
	
};

/**
 * Gets measurement (or label) beneath main label
 *
 * @param who {String} name of option
 * @param options {Object} json object of all options
 */
mktTrackerJS.prototype.getOptionMeasurement = function(who,label,options){
	
	for(var i = 0; i < options.length; i++) {
		//since we have multiple Dollars and Treasuries, 
		//be sure we're returning the correct measurement
		if ((/Dollar|Treasury/).test(who)){
			if (options[i].label == who && label == options[i].measurement){
				return options[i].measurement;
			}
		} else if (options[i].label == who){
			return options[i].measurement;
		}
	}
	return "";
};

mktTrackerJS.prototype._saveMarketMeterSelections = function($button){
	var self = this;

	//change button state as indicator...
	var txtColor = "#92abc7";
	var txtLabel = "Saving...";
	$button.unbind("click").text(txtLabel).css({"color":txtColor,"text-decoration":"none"});
	
	//user's new choices
	this.newMeters = [];
	
	//get choices 
    jQuery('#marketTracker li', this.$interactionContainer).each(function(){
        var wsodissue = Number(jQuery(this).attr("wsodissue"));
        self.newMeters.push(wsodissue);
        //re-stream
    });

	var usersSelections = this.newMeters;
	this.storageManager.put("marketTrackerSelections", usersSelections);
	this.storageManager.save();
	console.log("Saved userSelections: ", usersSelections);

    if (common.quirksMode) {
        this.$interactionContainer.hide().remove();
    } else {
        this.$interactionContainer.slideUp('fast',function(){ jQuery(this).remove(); });
    }

	jQuery("#MarketTrackerContainer").html(this.SAVED_HTML);
	var update = function(obj) {
		jQuery("ul.wsod_firstRow").empty();
		for(var i = 0; i < usersSelections.length; i++) {
				jQuery("ul.wsod_firstRow").append(obj[usersSelections[i]]);
		}

		var latestTime = 0;
		jQuery("ul.wsod_firstRow li").each(function (i) {
				if ( jQuery(this).attr("lastTrade") ) {
						var time = new Number( jQuery(this).attr("lastTrade") );
						if ( time && time > latestTime ) { latestTime = time; }
				}
		});
		var date = new Date()
		date.setTime(latestTime);
		jQuery(".myStreamClass").html(date.format("mm/dd h:MM:sstt 'ET'"));
		var fixed = 'time_' + usersSelections.join("|");
		jQuery(".myStreamClass").attr("stream", fixed);

		jQuery("#MarketTrackerContainer").show();
		if(!ipadCheck) { jQuery("#wsod_customizeTrackerLink").show(); }

		wsod_js.streaming.restartStream();
	};
	jQuery.getJSON(this.DATA_URL, update);
};

/**
 * check if Market Meter customize is open, and re-position it if user adjusts window size.
 */
mktTrackerJS.prototype.observeResize = function(){
	var self = this;
	jQuery(window).bind("resize",function(evt){
		if (self.$interactionContainer){
			var moveUpDistance = ("inRibbon" == self.who) ? 0 : self.TRACKER_BOTTOM_MARGIN;
			var containerOffset = self.$marketTracker.offset();
			self.$interactionContainer.css({top: containerOffset.top - moveUpDistance, left: containerOffset.left});
		}
	});	
};

(function(__global){
  if (!__global.console || (__global.console && !__global.console.log)) {
    __global.console = {
      log: (__global.opera && __global.opera.postError)
        ? __global.opera.postError
        : function(){ }
    }
  }
})(this);

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

cnnMarketTracker = new mktTrackerJS();

jQuery(document).ready(function() {
	cnnMarketTracker.observeResize();
	cnnMarketTracker.initializeStorageManager();
});

