﻿/*================================================================
 
    JavaScript routines written by Peter Deppe
 
================================================================== */

var _widgetid = '';
var inProcess = false;
var sortColumn1 = "column0";
var sortColumn2 = "column1";

/*---------------------------------------------------------------
name        : fst_InitDashboardWidgets
description : 
----------------------------------------------------------------- */
function fst_InitDashboardWidgets()
{
    // loop through each rss feed and fire off an async call to retrieve the details
	if($$('.rssfeed'))
	{
	    $$('.rssfeed').each(function(n)
		    {
			    fst_GetWidgetContent(n.id);
		    });
	}
}

/*---------------------------------------------------------------
name        : fst_DeleteUserDashboardWidget
description : 
----------------------------------------------------------------- */
function fst_DeleteUserDashboardWidget(userWidgetID)
{
    
    // are you sure?
    if(confirm("Are ou sure you want to remove this widget?"))
    {
        new Ajax.Request(URL_REMOVEUSERWIDGET,
	    {
	      method: 'post',
	      parameters: { wid: userWidgetID },
	      onSuccess: function(transport)
		    {
			    fst_DeleteUserDashboardWidgetSuccess(userWidgetID, transport.responseText)
		    },
	      onFailure: function()
		    {
			    alert('Error removing the widget');
		    }
	    });
    }    
}

/*---------------------------------------------------------------
name        : fst_DeleteUserDashboardWidget
description : 
----------------------------------------------------------------- */
function fst_DeleteUserDashboardWidgetSuccess(wid, retVal)
{
    if(retVal = 'success')
    {
        // get rid of the widget        
        if($('w' + wid) != null)
        {
            var parentObj = $('w' + wid).parentNode;
            
            if(parentObj != null)
            {
                Element.remove(parentObj);
                
                // tell the user what's happened
                fst_ShowWidgetActionMesage("widget was removed", false);
            }
        }
        else
        {
            fst_ShowWidgetActionMesage("couldn't locate the widget on your dashboard", true);
        }
    }
    else
    {
        fst_ShowWidgetActionMesage("unable to remove the widget from your dashboard", true);
    }
}

/*---------------------------------------------------------------
name        : fst_GetWidgetContent
description : 
----------------------------------------------------------------- */
function fst_GetWidgetContent(id)
{
    // ID is formatted like so: w1234_t1 so need to extract
    // the widget id and type from it
    var wigid = id.substring(1,id.indexOf('_'));    
    var type = id.substring(id.indexOf('_t')+2);
    
    new Ajax.Request(URL_GETWIDGET,
	{
	  method: 'post',
	  parameters: { wid: wigid, wt: type },
	  onSuccess: function(transport)
		{
			fst_ShowWidgetContent(id, transport.responseText)
		},
	  onFailure: function()
		{
			alert('Error retrieving widget content');
		}
	});	
}

/*---------------------------------------------------------------
name        : fst_ShowWidgetContent
description : 
----------------------------------------------------------------- */
function fst_ShowWidgetContent(id, content)
{
    if($(id))
    {
        // get a reference to the widget
        var widget = $(id);
        
        // grab a reference to the parent and replace it's content
        var feedItemParent = widget.up(0);
        feedItemParent.innerHTML = content;
    }
}

/*---------------------------------------------------------------
name        : fst_UpdateDashboardColumns
description : 
----------------------------------------------------------------- */
function fst_UpdateDashboardColumns()
{
    if(inProcess == true)
    {        
        return; // show a message and stop the event
    }
    
    fst_ShowLoader();
    
    // get the id list
    var col1 = fst_ObtainDashboardColumnOrder(sortColumn1);
    var col2 = fst_ObtainDashboardColumnOrder(sortColumn2);
        
    // set the flag so we don't try to process another one
    inProcess = true;
    
    new Ajax.Request(URL_UPDATE_DASHBOAD_COLS,
	{
	  method: 'post',
	  parameters: { col1List: col1, col2List: col2 },
	  onSuccess: function(transport)
		{
			fst_UpdateDashboardColumnsSuccess(transport.responseText)
		},
	  onFailure: function()
		{
			alert('Something went wrong, unable to update the sort order');
		}
	});	
}

/*---------------------------------------------------------------
name        : fst_UpdateDashboardColumnsSuccess
description : 
----------------------------------------------------------------- */
function fst_UpdateDashboardColumnsSuccess(retVal)
{
    if(retVal == "success")
    {
        // hoorah
    }
    else
    {
        alert(retVal);    // somink went wrong
    }
    
    // perform post sort clean up
    fst_InitDashboardColumns();
    inProcess = false;
    fst_HideLoader();
}
/*---------------------------------------------------------------
name        : fst_ObtainDashboardColumnOrder
description : Instead of using Serialize, going to use own 
            : loop to extract the sort order 
----------------------------------------------------------------- */
function fst_ObtainDashboardColumnOrder(col)
{
    var orderList = '';
    
    orderedNodes = document.getElementById(col).getElementsByTagName("li");
    
    for (var i=0;i < orderedNodes.length;i++)
    {
        orderList += orderedNodes[i].getAttribute('id').substring(8,orderedNodes[i].getAttribute('id').length) + ' ';
    }
    
    return orderList;
}

/*---------------------------------------------------------------
name        : fst_InitDashboardColumns
description : 
----------------------------------------------------------------- */
function fst_InitDashboardColumns()
{
    if($(sortColumn1))
    {
        Sortable.create( sortColumn1, { dropOnEmpty:true, handle: 'handle', containment:[sortColumn1, sortColumn2], constraint:false, onUpdate:fst_UpdateDashboardColumns, hoverclass:'colHover' } ); 
    }
    
    if($(sortColumn2))
    {
        Sortable.create( sortColumn2, { dropOnEmpty:true, handle: 'handle', containment:[sortColumn1, sortColumn2], constraint:false, onUpdate:fst_UpdateDashboardColumns, hoverclass:'colHover' } ); 
    }
}


/*---------------------------------------------------------------
name        : fst_AddWidget
description : 
----------------------------------------------------------------- */
function fst_AddWidget()
{       
    // make sure I have a value in the _type param
    if(_widgetid != null && _widgetid != '')
    {   
        
        switch(_widgetid)
        {
            case '1':       // external rss feed
            case '2':       // ugc rss feed
                fst_AddRssFeedWidget()
                break;
                
            case '5':       // my messages
                fst_AddMessageWidget();
                break;
                
            case '9':
                
                
            default:
                numToShow = '5';
        }
    }
    else
    {
        // show an error
    }
}

/*---------------------------------------------------------------
name        : fst_AddRssFeedWidget
description : 
----------------------------------------------------------------- */
function fst_AddRssFeedWidget()
{
    // grab the max links and selected rss feed
    var numToShow = $('rssMaxLinks').value;
    var feedID = fst_GetSelectedRadioItem($("frmRssList").rdoFeed);
    
    if(numToShow == 0)
    {
        alert('Please select the maximum number of links to display');
        return;
    }
    
    if(!feedID)
    {
        alert('Please select the feed');
        return;
    }
    
    if(numToShow > 0 && feedID > 0)
    {
        new Ajax.Request(URL_ADDUSERRSSWIDGET,
        {
          method: 'post',
          parameters: { maxlinks: numToShow, fid: feedID  },
          onSuccess: function(transport)
	        {
	          fst_AddWidgetSuccess(transport.responseText);
	        },
          onFailure: function()
	        {
		        fst_ShowWidgetActionMesage("something went wrong", true);
                Modalbox.hide();
	        }
        });
    }
}

/*---------------------------------------------------------------
name        : fst_AddMessageWidget
description : 
----------------------------------------------------------------- */
function fst_AddMessageWidget()
{
    // grab the max links and selected rss feed
    if($('msgMaxLinks'))
    {
        var numToShow = $('msgMaxLinks').value;
        
        if(numToShow > 0)
        {
            new Ajax.Request(URL_ADDUSERMESSAGEWIDGET,
            {
              method: 'post',
              parameters: { maxlinks: numToShow },
              onSuccess: function(transport)
	            {
	              fst_AddWidgetSuccess(transport.responseText);
	            },
              onFailure: function()
	            {
		            alert('error');
	            }
            });
        }
    }
}

/*---------------------------------------------------------------
name        : fst_AddWidgetSuccess
description : 
----------------------------------------------------------------- */
function fst_AddWidgetSuccess(retVal)
{
    if(retVal == 'success')
    {
        // clear the input text
        $('rssMaxLinks').value = '';       
        
        // set the display message
        _widgetid = '';
        
        fst_ShowWidgetActionMesage("widget was successfully added to your dashboard", false);
        
        // hide the modal box
        Modalbox.hide();
        
    }
    else
    {
        alert(retVal);
    }
}

/*---------------------------------------------------------------
name        : fst_DeleteWidget
description : 
----------------------------------------------------------------- */
function fst_DeleteWidget(widgetToDelete)
{
    alert('Delete the widget from the dashboard');
}

/*---------------------------------------------------------------
name        : fst_GetRssFeeds
description : 
----------------------------------------------------------------- */
function fst_GetRssFeeds()
{
    // 1 is system, 2 is external
    new Ajax.Request(URL_GETRSSFEEDS,
    {
      method: 'post',
      parameters: { rssType: '1' },
      onSuccess: function(transport)
	    {
	      fst_GetRssFeedsSuccess('1',transport.responseText);
	    },
      onFailure: function()
	    {
		    alert('error');
	    }
    });	
}

/*---------------------------------------------------------------
name        : fst_GetSystemRssFeeds
description : 
----------------------------------------------------------------- */
function fst_GetSystemRssFeeds()
{
    // 1 is system, 2 is external
    new Ajax.Request(URL_GETRSSFEEDS,
    {
      method: 'post',
      parameters: { rssType: '2' },
      onSuccess: function(transport)
	    {
	      fst_GetRssFeedsSuccess('2',transport.responseText);
	    },
      onFailure: function()
	    {
		    alert('error');
	    }
    });	
}

/*---------------------------------------------------------------
name        : fst_GetRssFeedsSuccess
description : 
----------------------------------------------------------------- */
function fst_GetRssFeedsSuccess(type,retVal)
{
    if($('rssFeedList'))
    {
        var listDiv = $('rssFeedList');
        listDiv.innerHTML = retVal;
        Modalbox.resizeToContent();
    }
}

/*---------------------------------------------------------------
name        : fst_GetExternalGadgets
description : 
----------------------------------------------------------------- */
function fst_GetExternalGadgets()
{
    // 1 is system, 2 is external
    new Ajax.Request(URL_GETEXTERNALGADGETS,
    {
      method: 'post',
      onSuccess: function(transport)
	    {
	      fst_GetExternalGadgetsSuccess(transport.responseText);
	    },
      onFailure: function()
	    {
		    alert('error');
	    }
    });	
}

/*---------------------------------------------------------------
name        : fst_GetExternalGadgetsSuccess
description : 
----------------------------------------------------------------- */
function fst_GetExternalGadgetsSuccess(retVal)
{
    if($('ExternalGadgetList') && retVal != '')
    {
        var listDiv = $('ExternalGadgetList')
        listDiv.innerHTML = retVal;
        Modalbox.resizeToContent();
    }
}


/*---------------------------------------------------------------
name        : fst_AddExternalWidget
description : 
----------------------------------------------------------------- */
function fst_AddExternalWidget()
{
    // grab the max links and selected rss feed
    var gadgetID = fst_GetSelectedRadioItem($("frmGadgetList").rdoGadget);
    
    if(!gadgetID)
    {
        alert('Please select a gadget to add');
        return;
    }
    
    if(gadgetID > 0)
    {
        new Ajax.Request(URL_ADDEXTERNALGADGET,
        {
          method: 'post',
          parameters: { gid: gadgetID  },
          onSuccess: function(transport)
	        {
	          fst_AddExternalWidgetSuccess(transport.responseText);
	        },
          onFailure: function()
	        {
		        fst_ShowWidgetActionMesage("something went wrong", true);
                Modalbox.hide();
	        }
        });
    }
}

/*---------------------------------------------------------------
name        : fst_AddExternalWidgetSuccess
description : 
----------------------------------------------------------------- */
function fst_AddExternalWidgetSuccess(retVal)
{
    if(retVal == 'success')
    {
        // set the display message
        _widgetid = '';
        
        fst_ShowWidgetActionMesage("widget was successfully added to your dashboard", false);
        
        // hide the modal box
        Modalbox.hide();
        
    }
    else
    {
        alert(retVal);
    }
}


/*---------------------------------------------------------------
name        : fst_ShowWidgetActionMesage
description : 
----------------------------------------------------------------- */
function fst_ShowWidgetActionMesage(msg,isError)
{
    var msgObj = $('WidgetActionMsg');

    if(msgObj != null)
    {
        msgObj.innerHTML = '';  // must clear it down first
        
        var msgText = document.createElement('span');
        
        if(isError == true)
        {
            msgText.innerHTML = msg;
            msgText.className = "error";
        }
        else
        {
            msgText.innerHTML = msg;
            msgText.className = "success";
        }

        msgObj.appendChild(msgText);
        msgObj.style.visibility = 'visible';
    }
}