
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};

Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Ongoing'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Ongoing'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};


if (typeof com == 'undefined') { var com = {}; }
com.sapient = {};

com.sapient.ms = 
{
	classes : ['Credit','Equity','Rates','Collateral', 'Commodity', 'FX',],
	data : null,
	startingMonth : 3,
	totalMonths : 10,
	currentSelection : [1],
	currentCLS : null,	
	init : function()
	{
		com.sapient.ms.showCategory(null, 1);
		$("#all").click();
	},
	showCategory : function(t, i)
	{
	    
		var c = com.sapient.ms.currentSelection;
		if (i == 0)
		{
			if (t.checked)
			{
				com.sapient.ms.currentSelection = [0];
			}
			else
			{
				com.sapient.ms.currentSelection = [];
			}
			
			$("#categories input").each(function(i) {
				if (i != 0)
				{
					this.checked = false;
				}

			});
			
		}
		else
		{
			if ($.inArray(0,c) > -1)
			{
				com.sapient.ms.currentSelection = [i];
			}
			$("#categories input")[0].checked = false;
			if (t != null)
			{
				var k = $.inArray(i,c);
				if (t.checked)
				{
					if (k > -1)
					{
						c.splice(k,1);
					}
					c.push(i);
				}
				else
				{
					c.splice(k,1);
				}
			}
			else
			{
				var k = $.inArray(i,c);
				if (k > -1)
				{
					c.splice(k,1);
				}
				c.push(i);
			}
			
		}
			
		com.sapient.ms.loadData();
		
		document.getElementById('include').checked = true;
	},
	loadData : function()
	{
		$.ajax({
			type: "GET",
			url: "js/grid.js",
			data: "",
			dataType: "json",
			success: com.sapient.ms.dataLoaded
		});
		
	},
	changeTitle : function()
	{
		var cs = "";
		$(com.sapient.ms.currentSelection).each(function(i) {
			
			cs += com.sapient.ms.classes[this-1];
			if (cs.toString() == 'undefined')
			{
				cs = "All";
			}
			if (com.sapient.ms.currentSelection.length - 1 > i && com.sapient.ms.currentSelection.length - 2 != i)
			{
				cs += ", ";
			}
			else if (com.sapient.ms.currentSelection.length-2 == i)
			{
				cs += " & "
			}
		});
		
		$("#grid h2").html(cs + ' <em>Milestones</em>');
	},
	dataLoaded : function(json)
	{
		com.sapient.ms.data = json;
		var itemArr = json.grid.milestone.item;
		$(".expandedCalendar").html('');
		$("#month").html('');
		
		var oldMonth = 0, oldYear = 0, oldDay = 0, container, container2;
		
		
		
		com.sapient.ms.changeTitle();
		
		var current_month = null;
		
		// iterate items		
		$.each(itemArr, function(i) 
		{
		    
			if ($.inArray(parseInt(this.attr.category), com.sapient.ms.currentSelection) > -1 || $.inArray(0, com.sapient.ms.currentSelection) > -1) {
				
				var y = this.attr.date.substr(0,4);
				var m = this.attr.date.substr(4,2);
				var d = this.attr.date.substr(6,2);
				var dt = new Date( m + "/" + d + "/" + y);
				var cls = "all";
			
				if (com.sapient.ms.currentSelection.length == 1)
				{
					var z = parseInt(com.sapient.ms.currentSelection[0]);
					z--;
					if (z >= 0)
					{
						cls = com.sapient.ms.classes[z].toString();
					}					
				}
				
				com.sapient.ms.currentCLS = cls;			
				if(m != '00')
				{				    
				    if (parseInt(oldMonth,10) > 0 && parseInt(oldMonth,10) + 1 < parseInt(m,10))
				    {
					    for (var l = (parseInt(oldMonth,10) + 1); l < parseInt(m,10); l++)
					    {
						    var ddt = new Date(l +"/01/" + y);
						    $("#month").append('<li class="container"><div class="' + cls + '"><input type="checkbox" checked="checked" disabled /><label>' + ddt.format('F') + '</label><ul class="schedule"></ul></div></li>');       
					    }
				    }
				    // checkbox & month box
				    if (oldMonth != m || oldYear != y)
				    {	
					    container = "m_" + i;
					    $("#month").append('<li id="m_' + i + '" class="container"><div class="' + cls + '"><input type="checkbox" checked="checked" id="check_' + i + '"  onclick="com.sapient.ms.toggleMonth(this,' + m + ',' + y + ')"/><label for="check_' + i + '">' + dt.format('F') + '</label><ul class="schedule"></ul></div></li>');
					    oldMonth = m;
					    oldYear = y;
					    oldDay = 0;	
				    }
				}
				
				// date box
				var _flag_cls = "";
				switch(this.attr.category)
				{
					case "1":
						_flag_cls = "credit";
						break;
					case "2":
						_flag_cls = "equity";
						break;
					case "3":
						_flag_cls = "rates";
						break;
					case "4":
						_flag_cls = "colateral";
						break;
					case "5":
					    _flag_cls = "commodity";
						break;
					case "6":
						_flag_cls = "fx";
						break;
				}
		
		        	
				var _date_box = "";
				// work around to add a listed desc with dates
				var _descs_out = "";
				//var _ongoing_desc_out = "";
				var _descs = this.description.split("<br/><br/>");				

				
				for(var x = 0; x < _descs.length; x++)
				{
//				    if(m == 0)
//				    {
//				        alert(1);
//				        _ongoing_desc_out += '<div class="mm">';
//					    _ongoing_desc_out += '<h3 class="' + _flag_cls + '">' + ' ' + '</h3>';
//					    _ongoing_desc_out += '<p>' + _descs[x] + '</p>';
//					    _ongoing_desc_out += '</div>';
//				    }
//				    else
				    //{
						_descs_out += '<div class="mm">';
					    if(m != '00')
					    {
					    	_descs_out += '<h3 class="' + _flag_cls + '">' + dt.format('j') + '</h3>';   // date blocks in milestone
					    }
					    else
					    {
					    	_descs_out += '<h3 class="' + _flag_cls + '">' + ' ' + '</h3>';
					    }
					    
					    
					    
					    _descs_out += '<p>' + _descs[x] + '</p>';
					    _descs_out += '</div>';
					    if (m != '00') 
					    {					    	
					    	_date_box += '<li><a onmouseout="tooltip.hide();" onmouseover="tooltip.show(\'' + htmlEntities(_descs[x]) + '\');" class="' + _flag_cls + '">' + dt.format('j') + '</a></li>';  // date blocks in calendar
					    }
					    
					    //else _date_box += '<li><a class="s' + _flag_cls + '">' + ' ' + '</a></li>';
				    //}
				    
				}
				
				//if(m != 0)
				//{
				    $("#" + container + " .schedule").append(_date_box);
				    // marged insert to a single month block
				    var _ptt = "." + parseInt(m,10) + "_" + y;
				    if ($(_ptt).html() == null)
				    {
    					container2 = parseInt(m,10) + "_" + y + "_"+ i;
	    			    if(m != '00')$(".expandedCalendar").append('<li id="' + container2 + '" class="' + cls + ' ' + parseInt(m,10) + "_" + y + '"><h5>' +  dt.format('M') + '</h5><div class="_desc">');
	    		        else $(".expandedCalendar").append('<li id="' + container2 + '" class="' + cls + ' ' + parseInt(m,10) + "_" + y + '"><h5>' + 'Ongoing' + '</h5><div class="_desc">');
		    		}
				    //alert($(_ptt).html());
			    	$(_ptt + " ._desc").append(_descs_out);
				    }
			    //}
		});
		
		//$(".expandedCalendar").append('<li id="ongoing"><h5>Ongoing</h5><div class="_desc">');
		
		
		// noam: bug #2
		// node: filling out the blank month to the end of the row
		if ($(".container").length < com.sapient.ms.totalMonths) 							// the harcode show be relaxed
		{
			var cls = com.sapient.ms.currentCLS;
			var _to = com.sapient.ms.totalMonths - $(".container").length;
			if (oldMonth == 0 || !oldMonth)
			{
				var _m = com.sapient.ms.startingMonth;
			}
			else
			{
				var _m = ((oldMonth * 1) + 1 > 12) ? 1 : (oldMonth * 1) + 1;
			}
			for (var l = 0; l < _to; l++)
			{	
				var ddt = new Date(_m + "/01/" + oldYear);
				var _insert = '<li class="container"><div class="' + cls + '"><input type="checkbox" checked="checked" disabled /><label> ' + ddt.format('F') + ' </label><ul class="schedule"></ul></div></li>';
				$("#month").append(_insert);					
				if ((_m++) > 12)
				{
					_m = 1;
				}				
			}
		}
		
		// noam: bug #3
		// node: add custom att to the last node of the calendar
		var obj = $(".container")[$(".container").length - 1];
		obj.className += " last";
		
		
	},
	toggleMonth : function(t,m,y)
	{
		if (t.checked){
			$(".expandedCalendar ." + m +"_" + y).show();
		}
		else
		{
			$(".expandedCalendar ." + m +"_" + y).hide();
		}
	},
	printContent : function(obj)
	{
		var WindowObject = window.open('', "TrackHistoryData", "width=950,height=325,top=200,left=250,toolbars=no,scrollbars=yes,status=no,resizable=no");
		var cout = '<html><head><link rel="stylesheet" href="css/print.css" /></head>';
		cout += '<body><div class="grid">'
		cout += document.getElementById(obj).innerHTML;
		cout += '</div></body></html>';
		// alert(cout);
		WindowObject.document.writeln(cout);
		WindowObject.document.close();
		WindowObject.focus();
		WindowObject.print();
		WindowObject.close();
	}
};

$(document).ready(function(showCategory){
	com.sapient.ms.init();
	
	
	var monthBoxes = $('li.container');
	for (var i = 0; i < $('li.container').length; i++)
	{
		alert($('li.container')[i]);	
	}
	
	
});


function htmlEntities(txt)
{
	var str = new String(txt);
	str = str.replace(/\"/gi, unescape('%22'));
	str = str.replace(/\&/gi, unescape('%26'));
	str = str.replace(/\</gi, unescape('%3C'));
	str = str.replace(/\>'/gi, unescape('%3E'));
	str = str.replace(/\'/gi, unescape('%A0'));
	str = str.replace(/¡'/gi, unescape('%A1'));
	str = str.replace(/¢'/gi, unescape('%A2'));
	str = str.replace(/£'/gi, unescape('%A3'));
	str = str.replace(/¥'/gi, unescape('%A5'));
	str = str.replace(/¦'/gi, unescape('%A6'));
	str = str.replace(/§'/gi, unescape('%A7'));
	str = str.replace(/¨'/gi, unescape('%A8'));
	str = str.replace(/©'/gi, unescape('%A9'));
	str = str.replace(/ª'/gi, unescape('%AA'));
	str = str.replace(/«'/gi, unescape('%AB'));
	str = str.replace(/¬'/gi, unescape('%AC'));
	str = str.replace(/­'/gi, unescape('%AD'));
	str = str.replace(/®'/gi, unescape('%AE'));
	str = str.replace(/¯'/gi, unescape('%AF'));
	str = str.replace(/°'/gi, unescape('%B0'));
	str = str.replace(/±'/gi, unescape('%B1'));
	str = str.replace(/²'/gi, unescape('%B2'));
	str = str.replace(/³'/gi, unescape('%B3'));
	str = str.replace(/´'/gi, unescape('%B4'));
	str = str.replace(/µ'/gi, unescape('%B5'));
	str = str.replace(/¶'/gi, unescape('%B6'));
	str = str.replace(/·'/gi, unescape('%B7'));
	str = str.replace(/¸'/gi, unescape('%B8'));
	str = str.replace(/¹'/gi, unescape('%B9'));
	str = str.replace(/º'/gi, unescape('%BA'));
	str = str.replace(/»'/gi, unescape('%BB'));
	str = str.replace(/¼'/gi, unescape('%BC'));
	str = str.replace(/½'/gi, unescape('%BD'));
	str = str.replace(/¾'/gi, unescape('%BE'));
	str = str.replace(/¿'/gi, unescape('%BF'));
	return str;
}
