var portfolioBastUrl = "http://portfolio.bmj.com";
var pathName = window.location.href.split('/learning/')[0];
if(pathName.indexOf('sha.') > -1){
	pathName =  'http://test.learning-bmj-com.internal.bmjgroup.com' ;
}
if(pathName.indexOf('http://learning.internal')> -1){
	pathName =  'http://dev.learning-bmj-com.internal.bmjgroup.com' ;
}

//var portfolioBastUrl = pathName.replace("learning-bmj-com" , "portfolio-bmj-com." );
var portfolioBastUrl = pathName.replace("learning" , "portfolio" );

/* ===========================================================================
 *
 * jQuery BMJ Portfolio Widget
 * Version 1.0
 * Provides a a display of top five resouces from user's BMJ Portfolio to sit on
 * any intrenal or or external BMJ websites 
 *
 * Author: Zoe Azhdari Radkani
 * Author email: ZAzhdariRadkani@bmjgroup.com
 *
 * ---------------------------------------------------------------------------
 * 
 * EXAMPLES OF USE:
 *
 * Notice: These methods does not include bmj global css and reset css. for internal and external BMJ sites
 * these 2 files are included in the main decorator.
 * The widget gets the div that wraps it around.
 * 
 *
 * // include this plug in in header
 *   <script type="text/javascript" src="jquery.bmj.portfolio.widget_1.0.js"></script>
 *
 * //include this in your body of html
 * <div id="portfolio-widget-container"></div>
 *
 *
 * // this will customize the number of resources displayed in the widget
 *   jQuery(document).ready(function($) { 
 *    	$.fn.BmjPortfoiloWidget.defaults.widgetSize = 8;
 *});
 *------------------------------------------------------------------------------
 *SETTINGS:
 * 
 * Customise it by change the plugin setting but accessing the default options
 * 
 * $.fn.BmjPortfoiloWidget.defaults = {
 *               divContainer:   'div#portfolio-widget-container',
 *				widgetHome:     'bmjLeanrning',
 *				cssFile:	'http://dev.portfolio-bmj-com.internal.bmjgroup.com/portfolio/css/widget/portfolio-widget.css', // if specified, this class will be applied to all dialogs
 *				cssGlobal:      'http://group.bmj.com/repository/css/bmj-group-global.css',
 *				checkBox : "checkbox",
 *				statusFilter : "statusfilter",
 *				widgetSize: 5,
 *				_Classes :{    //class names
 *					"headerClass" : "action-bar",
 *					"bodyClass" : "widget-content",
 *					"footerClass" : "footer",
 *					"mainTableClass" : "widget-content",
 *					"loadingClass" : "loading",
 *					"clickAbleClass" : "clickable",
 *					"notclickAbleClass": "not-clickable",
 *					"oddClass" : "odd",
 *					"evenClass" : "even",
 *					"dropdownDivClass" : "item-status",
 *					"checkBoxDivClass" : "item-type"
 *					
 *					}		   
 *                };		
 *                
 *   
 *===========================================================================*/
//Creating closure
(function($) {
	
	//current_href = $(location).attr('href');


         //plug-in definition
	$.fn.BmjPortfoiloWidget = function(settings) {
                // Extend our default options with those provided.
                var options = $.extend({},$.fn.BmjPortfoiloWidget.defaults, settings);
		//populate and add events each matched element
                return this.each(function() {
			var type = "";
			var $this = $(this);
			var $checkBoxText = "";
			var $resourceType = getResourceType();
			var $icsId = 0;
			//var $icsId = "id235410";
			var $widgetBody;

			
			_initialize();
			
		
			
			function _initialize() {
				
				/*
				
				
				
				var css_global = $("<link>", { 
				    rel: "stylesheet", 
				    type: "text/css", 
				    href: options.cssGlobal
				});
				css_global.appendTo('head');
				
				var css_link = $("<link>", { 
				    rel: "stylesheet", 
				    type: "text/css", 
				    href: options.cssFile
				});
				*/
				var css_link = '<link rel="stylesheet" type="text/css" href="' + portfolioBastUrl + options.cssFile + '" />';
				$('head').append(css_link);
				
			        _builder();
				
				$('input#portfolio-widget-checkbox:checkbox').live('click' , function () {
					_reload(options.checkBox , $('select#status-widget').val() );
					
				});
								
				$('select#status-widget').change( function () {
					
					_reload(options.statusFilter , $(this).val());
					
				});
				_load($widgetBody  , '' );
				
				
				/*$('table#portfolio-widgetTable tr').live( 'click' , function() {
					var href = $(this).find("input#resourceUrl").attr("value");
					var resType = $(this).find("input#resourceType").attr("value");
					
					
					if(href) {
						if (href.indexOf('http') < 0)
						{
							href = 'http://' + href;	
						} 
						
						 if( type == resType){
							 window.location = href;
						 }else{
							 window.open( href , '_blank' );
						 }
					}
				});*/
				
			}
		        
			
			
			function getResourceType(){
				var url = location.href;
				if(url.indexOf('bmj') > -1){
					if(url.indexOf('learning') > -1){
						$checkBoxText = 'BMJ Learning items only';
						type = 'lmodule';
					}
					else if(url.indexOf('bestpractice') > -1){
						$checkBoxText = 'BMJ Best practice items only';
						type = 'bp';
					}
				}
				return type;	
			}
			
			function _builder(){
				
				var widgetHeader = document.createElement( 'div' );
				widgetHeader.className = options._Classes.headerClass;
				var _title = '<h2><span>BMJ Portfolio</span></h2>';
				var _link = '<a target="_blank" href="' + portfolioBastUrl + '">Go to my portfolio</a>';
				widgetHeader.innerHTML = _title + _link ;
				
				$widgetBody = document.createElement( 'div' );
				$widgetBody.className = options._Classes.bodyClass;
				var loadingTable = _getLoadingTable();
				$widgetBody.innerHTML = '<div class="loading"><img src="' + options.loadingImg + '"/></div>' + loadingTable;
				
				var widgetFooter = document.createElement( 'div' );
				widgetFooter.className = options._Classes.footerClass;
				var _dropDown = '<div class="' + options._Classes.dropdownDivClass + '"> <p>Status</p><select id="status-widget"><option value=""> all </option><option value=" not-started ">' +
					'Not started</option><option value=" in-progress ">In progress</option><option value=" completed ">' +
					'Completed</option></select></div>';
				var _tickBox = "";
				if($checkBoxText != ""){
					
					 _tickBox  = '<div class="' + options._Classes.checkBoxDivClass + '"><input type="checkbox" id="portfolio-widget-checkbox" value="' + $checkBoxText + '" checked=""><p>' + $checkBoxText + '</p></div>';
				}				
				widgetFooter.innerHTML =  '<div class="footer-content">' + _dropDown + _tickBox  + '</div>';
				
				
				$this.append( widgetHeader );
				$this.append( $widgetBody );
				$this.append( widgetFooter );
				
			}
			
			function _load( dataCon ,  resourceStatus ){
				var sOut = '<table id="portfolio-widgetTable">';
				sOut += '<thead><tr><th class="status sorting"><strong><span>Status</span></strong></th>'; 
				sOut += '<th class="title sorting">Title</th><th class="date-added sorting">Date added</th>';
				sOut += '</tr></thead><tbody><tr class="extra"></tr></tbody>';
				sOut += '</table>';
				var jsonp_url = portfolioBastUrl + "/portfolio/rest/api/resources/" + $icsId + "/" + $resourceType + "?callback=?";
				
				var counter = 0 ;
				var trClass = '';
				$.ajax(
				{
					 url:jsonp_url, 
					 dataType: 'jsonp',	
					 data: {resourceStatus : resourceStatus, resourceType: $resourceType, maxSize: "5"},
					 success: (function(data){
						 var HtmlString = "";	
							if(data.length > 0 ){
								$(data).each(function(index){
									   if (counter < options.widgetSize){
										 if(counter % 2 == 0){ trClass = options._Classes.oddClass;}
										 else{trClass = options._Classes.evenClass;}
										 var statusVal = "not-started";
										 var urlVal = "";
										 var linkData = "";
										 var dateValue = _formatDate(data[index].dateAdded);
										 $(data[index].properties._items).each(function(i){
											$(data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList).each(function(x){
												if(data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._name == 'status'){
												   if(data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._value != ""){
													statusVal = data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._value;
												   }
												}
												if(data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._name == 'url'){
												   if(data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._value != ""){
													urlVal = data[index].properties._items[i]._resourceType._propertiesList[0]._propertyList[x]._value;
												   }
												}
											});
										 });
							    
								 var trClickable = "";
								 var isLink = false;
								 if( urlVal != ""){
											trClickable = options._Classes.clickAbleClass;
											if (urlVal.indexOf('http') < 0)
											{
												urlVal = 'http://' + urlVal;	
											} 
											isLink = true;

								 }else{
											trClickable = options._Classes.notclickAbleClass;
								 }							    
								 switch(resourceStatus)
									{
									case '': 
										var rowData = '<tr class="PERSONAL ' + ' ' + trClass + ' ' + trClickable + '">';
										var statusData = '<td><strong class="' + statusVal + '"><span>' + statusVal + '</span></strong></td>';
										var titleData = '<td><span class="overflow"><a href=' + urlVal + ' id= "resourceUrl">'  + data[index].name + '</a></span></td>';
										if (!isLink)
										{
											titleData = '<td><span class="overflow">'+ data[index].name + '</span></td>';
										}										
										var dateData = '<td><span class="overflow">' + _formatDate(data[index].dateAdded) + '</span></td>';									
										HtmlString += rowData + statusData + titleData + dateData + linkData + '</tr>';
										counter += 1;
									break;
									
									default:
									 if(resourceStatus.indexOf(statusVal) > -1 ){
										var rowData = '<tr class="PERSONAL ' + ' ' + trClass + ' ' + trClickable +  '">';
										var statusData = '<td><strong class="' + statusVal + '"><span>' + statusVal + '</span></strong></td>';
										var titleData = '<td><span class="overflow"><a href=' + urlVal + ' id="resourceUrl">'  + data[index].name + '</a></span></td>';
										if (!isLink)
										{
											titleData = '<td><span class="overflow">' + data[index].name + '</span></td>';
										}										
										var dateData = '<td><span class="overflow">' + _formatDate(data[index].dateAdded) + '</span></td>';									
										HtmlString += rowData + statusData + titleData + dateData + linkData + '</tr>';
										counter += 1; }
									 
									}
										 
								} 
									   dataCon.innerHTML = sOut;
										 //alert(HtmlString);
										 $('table#portfolio-widgetTable  tr:last').before(HtmlString);
										 $('table#portfolio-widgetTable  tr.extra').remove();
										 _resizeTable();										
										  $('table#portfolio-widgetTable tr').not('.not-clickable').hover(
											function () {
											
											 $(this).addClass('hover'); 
											}, 
											function () {
											  
											  $(this).removeClass('hover');
											}
										      );
								
								
								});   
							  		   
							}else{
								dataCon.innerHTML = sOut;
								$('table#portfolio-widgetTable  tr.extra').remove();
								_resizeTable();
							}	
					 })
				});
			} // end _load
			
			function _resizeTable(){
				var trCount = $('table#portfolio-widgetTable tbody tr').size();
				if(trCount < 5 ){
					var extraRaw = options.widgetSize - trCount;
					for(i=trCount+1 ; i<options.widgetSize+1 ; i++ ){
						var tClass = "";
						if(i % 2 != 0){ tClass = options._Classes.oddClass;}
						else{tClass = options._Classes.evenClass;}
						var insertRaw = '<tr class="PERSONAL ' + ' ' + tClass + '"><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
						if( trCount == 0 ){
							$('table#portfolio-widgetTable tbody').append(insertRaw);
						}else{
						$('table#portfolio-widgetTable  tr:last').after(insertRaw);
						}
					}
				}
			}
			
			function _formatDate(dateStr)
			{
					var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
					// sometimes comes in the form 30-Mar-2011 00:00:00,
					// other times as Apr 6, 2011 12:00:00 AM
					var result = new Date();
					if (dateStr.indexOf('-') != -1)
					{
						dateStr = dateStr.split(' ')[0];
						var date = dateStr.split('-');
						result = new Date(date[1] + ' ' + date[0] + ', ' + date[2]);
					}
					else 
					{
						//alert(dateStr);
						var date = dateStr.split(' ');
						//alert(date);
						result = new Date((date[1].split(','))[0] + ' ' + date[0] + ', ' + date[2]);
					}
					
					var day = result.getDate();
					if (result.getDate() < 10)
						day = '0'+result.getDate();
					var month = monthNames[result.getMonth()];
					
					return day + '-' + month + '-' + result.getFullYear();
			}
			
			
			function _reload( filter , statusValue ){
				var loadingTable = _getLoadingTable();
				$widgetBody.innerHTML = '<div class="loading"><img src="' + options.loadingImg + '"/></div>' + loadingTable;
				if ( filter == 'checkbox'){
					if ($('input#portfolio-widget-checkbox:checked').length)
					{
					    $resourceType = getResourceType();
					    _load($widgetBody , statusValue );
					}
					else
					{
					    $resourceType ="";
					    _load($widgetBody , statusValue);
					}
				}
				if ( filter == 'statusfilter'){
					
					 _load($widgetBody , statusValue );
					
				}
			}
			
			function _getLoadingTable(){
				var tableStr = '<table id="portfolio-widgetTable"><thead><tr class=""><th class="status sorting"><strong>' + 
				'<span>Status</span></strong></th><th class="title sorting">Title</th><th class="date-added sorting">' + 
				'Date added</th></tr></thead><tbody>';
				var loop = options.widgetSize;
				for( i=0 ; i<loop ; i++){
					var trClass = "";
					if(i % 2 != 0){ trClass = options._Classes.evenClass; }
					else{ trClass = options._Classes.oddClass; }
					tableStr += '<tr class="PERSONAL ' + trClass + '"><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
				} 
				tableStr += '</tbody></table>';
				return tableStr;
			}
			
		});
	};
        
        $.fn.BmjPortfoiloWidget.defaults = {
                divContainer:   'div#portfolio-widget-container',
				widgetHome:     'bmjLeanrning',
				cssFile:	'/portfolio/css/widget/portfolio-widget.css', // if specified, this class will be applied to all dialogs
				cssGlobal:      'http://group.bmj.com/repository/css/bmj-group-global.css',
				loadingImg: 'http://group.bmj.com/repository/images/loading.gif',
				checkBox : "checkbox",
				statusFilter : "statusfilter",
				widgetSize: 5,
				_Classes :{
					"headerClass" : "action-bar",
					"bodyClass" : "widget-content",
					"footerClass" : "footer",
					"mainTableClass" : "widget-content",
					"loadingClass" : "loading",
					"clickAbleClass" : "clickable",
					"notclickAbleClass": "not-clickable",
					"oddClass" : "odd",
					"evenClass" : "even",
					"dropdownDivClass" : "item-status",
					"checkBoxDivClass" : "item-type"
					
					}		   
                 };
	
	
		
	$(window).load(function (){	
		$('div#portfolio-widget-container').BmjPortfoiloWidget();
	});

})(jQuery);

