/*
* Portlets.js
*/

//
// Portlet object
//
function Portlet(iframeId) {
}

//
// Remember the original URL for iframes
//
var iframeBaseUrls = new Array();

//
// Called on load of page, to start portlets loading
//
function StartLoadingPortlets() {
    //
    // Start loading iframe urls...
    //
    $("#portlet div.portletWrapper iframe").each(function() {
        var iframeObj = $(this);
        iframeObj[0].contentWindow.document.write("<html><head/><body>\r\n");
        iframeObj[0].contentWindow.document.write("<p style=\"font-family:Verdana,Arial,sans-serif;font-size:12px;color:#666;\">Loading...</p>\r\n");
        iframeObj[0].contentWindow.document.write("</html></body>\r\n");
        iframeObj.attr("src", iframeObj.attr("title"));
        iframeObj.attr("title", "");
    });
}

//
// Handle portlet action...
//
function HandleMenuAction(action, iframeId, aObj) {
    var iframeObj = $("#" + iframeId);

    if (iframeObj != null) {
        switch (action) {
            case 'Maximise':
                try {
                    var url = CreateMaximiseUrl(iframeId);
                    document.location = url;
                } catch (err) {
                    alert('Could not maximise this portlet');
                }
                break;
            case 'CopyToClipboard':
                try {
                    xcopy(iframeObj[0].contentWindow.document.body);
                    //test(iframeObj);
                    alert('Copied to clipboard');
                } catch (err) {
                    alert('Could not copy portlet contents to the clipboard' + err);
                }
                break;
            case 'Print':
                try {
                    iframeObj[0].contentWindow.focus();
                    iframeObj[0].contentWindow.print();
                } catch (err) {
                    alert('There was an error trying to print the portlet.');
                }
                break;
            case 'Refresh':
                try {
                    iframeObj[0].contentWindow.document.write("<p style=\"font-family:Verdana,Arial,sans-serif;font-size:12px;color:#666;\">Loading...</p>");
                    iframeObj[0].src = GetIframeBaseUrl(iframeId);
                    $(".portletHeader ul.tools li.settings ul.settingsmenu").css("top", "-1000px");
                    setTimeout('$(".portletHeader ul.tools li.settings ul.settingsmenu").css("top", "30px")', 100);
                } catch (err) {
                    alert('Could not refresh the portlet');
                }
                break;
            case 'Help':
                ShowHelp(iframeObj);
                break;
            case 'DownloadAsCsv':
                //iframeObj[0].src = GetCsvUrl(iframeObj[0].src);      
                iframeObj[0].src = CreateUrl(iframeId, "csv/", null);
                break;
            case 'DownloadAsImage':
                var extraParams = [{ name: 'download', value: 'true'}];
                iframeObj[0].src = CreateUrl(iframeId, GetChartName(iframeId) + '.png', extraParams);
                break;
            default:
                alert('Action not recognised');
                break;
        }
    }

    return false;
}

//
// Creates a url for a chart tool action.
//
function CreateUrl(iframeId, segment, parameters) {
    // get original url
    var origUrl = GetIframeBaseUrl(iframeId);
    // split into url and querystring
    var segments = origUrl.split("?");
    var path = segments[0];
    var queryString;

    var isFirstParameter = true;
    if (segments.length > 1) {
        queryString = segments[segments.length - 1];
        isFirstParameter = false;
    }
    // add segment to path
    path = path + segment;

    // create querystring adding existing parameters
    if (queryString != null || parameters != null) {
        queryString = '?' + ((queryString == null) ? "" : queryString);
    }

    if (parameters != null) {
        queryString = AddParameters(parameters, queryString, isFirstParameter);
    }

    path = path + ((queryString == null) ? "" : queryString);

    return path;
}


//
// Adds parameters to query string
//
function AddParameters(parameters, queryString, isFirstParameter) {
    if (parameters != null) {
        for (i = 0; i < parameters.length; i++) {
            queryString = queryString + ((isFirstParameter) ? '' : '&') + parameters[i].name + '=' + parameters[i].value;
        }
    }

    return queryString;
}

//
// Parses the Chart name from a chart URL
// Looks for the security context, and takes the next segment
//
function GetChartName(iframeId) {
  var origUrl = GetIframeBaseUrl(iframeId);
  var chartNameRegex = new RegExp('/(black|red|blue)/(\\w+)/','i');
  var match = chartNameRegex.exec(origUrl);
  var chartName = match[2];

  return chartName;
}

//
// Gets the original URL for a chart portlet iframe to use for creating URLs for the portlet tools.
//
function GetIframeBaseUrl(iframeId) {

    // Get any stored URL
    var baseUrl = iframeBaseUrls[iframeId];  
    
    // If we have not stored the original URL,
    // use the frame source and store it too
    if (baseUrl == undefined)
    {
        var iframeObjs = $("#" + iframeId);
        if (iframeObjs.length > 0)
        {
            var url = iframeObjs[0].src;
            if ((url != undefined) && (url != ''))
            {
                baseUrl = url;
                SetIframeBaseUrl(iframeId, baseUrl);
            }
        }
    }
    
    return baseUrl;
}

//
// Sets or update the stored copy of the original URL for this portlet
// The URL is stored in an array in the outer page, so safe from portlet reloads
//
function SetIframeBaseUrl(iframeId, newUrl) {
    iframeBaseUrls[iframeId] = newUrl;
}

//
// xcopy
//
function xcopy(inElement) {
    if (inElement.createTextRange) {
        var range = inElement.createTextRange();
        var BodyLoaded = true;
        if (range && BodyLoaded == 1)
            range.execCommand('Copy');
    } else {
        var flashcopier = 'flashcopier';
        if (!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="/notion/site/EMC/flash/clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(inElement.value) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

function test() {
    debugger;
    var cp = document.body.createTextRange();
    document.body.focus();
    //document.body.select();
    cp.execCommand("Copy");
}

//
// Add Content - Move Previous Page
//
function ChartMovePreviousPage() {
    var portletList = $("div.chartHolder ul.modules");
    var top = parseInt(portletList.css("top"));
    if (isNaN(top)) {
        top = 0;
    }
    if (top < 0) {
        top += 342;
    }

    $("div.chartHolder ul.modules").css("top", top);

    return false;
}

//
// Add Content - Move Next Page
//
var addContentChartHeight = null;
function ChartMoveNextPage() {
    var portletList = $("div.chartHolder ul.modules");
    var top = parseInt(portletList.css("top"));
    if (isNaN(top)) {
        top = 0;
    }
    if (addContentChartHeight == null) {
        addContentChartHeight = $("div.chartHolder").height();
    }
    if (top + addContentChartHeight > 342) {
        top = top - 342;
    }

    $("div.chartHolder ul.modules").css("top", top);

    return false;
}

//
// Show Help (obj is iframe obj, jQuery)
//
function ShowHelp(obj) {
    //
    // Hide any already open help
    //
    $("div.portletContent2 div.portletHelp").css("display", "none");
    $("div.portletContent2").css("z-index", "0");

       var a = $(obj);

    var portletObj = a.parents("div.portletContent2")[0];
    var filterDiv = $(portletObj).find("div.portletHelp");
    $(filterDiv).css("z-index", "1001"); 

   $(portletObj).css("z-index", "1000");

    var iframeOffset = obj.offset();

    var leftX = iframeOffset.left;
    if (leftX > $(window).width() - 440) {
        leftX = -10;
    } else {
	leftX = 20;
    }


    filterDiv.css({ display: "block", left: leftX, top: 50 });

    return false;
}

//
// Show filter
//
function ShowFilter(obj) {
    //
    // Hide any already open filters
    //
    $("div.portletContent2 div.filter").css("display", "none");
    $("div.portletContent2 div.filter").css("z-index", "0");
    $("div.portletContent2").css("z-index", "0");

    var a = $(obj);

    var portletObj = a.parents("div.portletContent2")[0];
    $(portletObj).css("z-index", "1000");


    var iframeObj = $(portletObj).find("iframe");

    var filterDiv = a.parents("div.portletContent2").find("div.filter").css("z-index", "1001"); 

    var selectedArray = $(iframeObj).data('Selected');

    if (selectedArray != null) {
        if (selectedArray.length == 0) {
            // check if checkboxes are all unchecked, and check 'All' if true
            if (filterDiv.find("div.filter-inner input:checkbox:checked").length == 0) {

                var allCheckboxes = filterDiv.find("div.filter-inner input.allCheck");
                if (allCheckboxes.length > 0) {
                    allCheckboxes[0].checked = true;
                    $(iframeObj).data('Selected', 0);
                }
            }
        }
    } else {
        selectedArray = [0];
        $(iframeObj).data('Selected', selectedArray);
    }

    if (selectedArray != null) {
        if (selectedArray.length > 0) {
            var checkboxes = filterDiv.find("div.filter-inner input")
            for (j = 0; j < checkboxes.length; j++) {
                for (i = 0; i < selectedArray.length; i++) {
                    if (checkboxes[j].value == selectedArray[i]) {
                        checkboxes[j].checked = true;
                        break;
                    } else {
                        checkboxes[j].checked = false;
                    }
                }
            }
        }
    }


    var iframeOffset = a.offset();

    var leftX = iframeOffset.left;
    if (leftX > $(window).width() - 440) {
        leftX = -10;
    } else {
	leftX = 20;
    }


    filterDiv.css({ display: "block", left: leftX, top: 50 });


    return false;
}

//
// Create a url for this same screen but with a portlet maximised
//
function CreateMaximiseUrl(portletFrameId) {
    var portletId = portletFrameId.split('_')[1];
    var argument = ('maxpid=' + portletId);

    var url = document.location.href;
    url = url.replace(/#.*$/, '');
    if (url.indexOf('?') == -1) {
        url += ('?' + argument);
    } else {
        url += ('&' + argument);
    }

    return url;
}

//
// Remove the maximise from the current URL and load that
//
function UnMaximise() {
    var url = document.location.href;
    var newUrl = url.replace(/.maxpid=[0-9]+/i, '');
    document.location = newUrl;
    return false;
}

//
// Update the portlet search
//
function UpdatePortletSearch(url, category, obj) {
    var updateNode = $("#contentPanel div.content div.last");
    var searchWord = $("#contentSearchWord").val();

    $("div#contentPanel div.content ul.catmenu li").removeClass("selected");

    if (category != '') {
        searchWord = '';

        if (obj != null) {
            $(obj).parent().addClass("selected");
        }
    }

    updateNode.html("<p>&nbsp;</p>\r\n<p>Loading...</p>\r\n");

    // The url will be complete, except for searches where the search words must be added
    if (searchWord != '') {
        url = AddParameterToUrl(url, 'contentsearchword', encodeURIComponent(searchWord));
    }

    jQuery.ajax({
        type: 'GET',
        url: url,
        success: function(html) {
            updateNode.html(html);
            InitPortletModuleItems();
        }
    });

    return false;
}

//
// Apply the filter for an iframe
//
function ApplyFilter(applyBtn, iframeId) {
    var iframeObj = $("#" + iframeId);
    var applyBtnObj = $(applyBtn);
    var formObj = applyBtnObj.parent();

    try {
        //
        // For each input in the form do...
        //
        var selectedValues = new Array();
        var arrayCounter = 0;
        var paramStr = "?";
        var counter = 0;
        //      formObj.find("input, select, textarea").each(function() {
        //     formObj.find("input:radio:checked", "input:checkbox:checked").each(function() {
        formObj.find("input:checked").each(function() {

            var obj = $(this)

            counter++;
            var inputName = obj.attr("name");
            if (inputName != "") {
                //if (obj.attr("selected") == "selected") { 
                if (counter == 1) {
                    paramStr += inputName + "=" + GetVal(obj);
                } else {
                    paramStr += "&" + inputName + "=" + GetVal(obj);
                }

                selectedValues[arrayCounter] = GetVal(obj);
                //}	        
            }

            arrayCounter++;
        });

        //iframeObj[0].contentWindow.document.write("<p style=\"font-family:Verdana,Arial,sans-serif;font-size:12px;color:#666;\">Loading...</p>");
        var newUrl = GetIframeBaseUrl(iframeId).split('?')[0];  // Remove any existing params
        newUrl += paramStr;  // Add the filter parameters
        newUrl = AddContextParameterToUrl(newUrl, GetContext());  // Add any context parameter
        iframeObj[0].src = newUrl; // Reload the portlet with new filter applied
        
        // Remember the filter parameters for displaying the filter
        $(iframeObj[0]).data('Selected', selectedValues);

        // Remember this filtered URL as the new base URL for this portlet
        // So if the portlet is refreshed, the filter will still apply
        SetIframeBaseUrl(iframeId, newUrl);
    } catch (err) {
        alert('Could not apply filter!');
    }

    //
    // Close filter window and return false
    //
    formObj.parent().parent().css('display', 'none');

    return false;
}

//
// Get field value
//
function GetVal(obj) {
    switch (obj.attr("type")) {
        case "checkbox":
        case "radio":
            //if (obj.attr("selected") == "selected"){
            return obj.val();
            //} else {
            //  return "";
            //}    
            break;
        default:
            return obj.val();
    }
}

//
// Get the context argument from the page
//
function GetContext() {

  var sContextDiv = $('div#sContext');

  if ($(sContextDiv).find('.c').length) {
    var parameterDiv = $(sContextDiv).find('.c')[0];
    var parameter = $(parameterDiv).html();
    return parameter;
  }

  return undefined;
}

//
// Add the context argument
//
function AddContextParameterToUrl(url, context) {

  if (context == undefined) {
    context = GetContext();
  }
  
  if (context != undefined) {
    url = AddParameterToUrl(url, 'e', context);
  }

  return url;
}

// Add extra params to urls
$(document).ready(function() {

  // Get context parameter
  var context = GetContext();

  if (context != undefined) {
    // foreach portlet add extra parameter to the end of the iframe url. 
    $('.portletFrame').each(function() {
      var originalSource = $(this).attr('title');
      var newSource = AddContextParameterToUrl(originalSource, context);
      $(this).attr('title', newSource);
    });
  }
});
 
