define(['hp/core/EventDispatcher',
                                'hp/core/Localizer',
                                'jquery',
                                'hp/lib/jquery.hpStatus',
                                'lib/jquery.dataTables',
                                'hp/lib/jquery.hpCollapsible',
                                'hp/lib/jquery.hpToggle',
                                'hp/lib/jquery.hpGridPanels'],
function (EventDispatcher, Localizer) {
    "use strict";
    (function ($) {
        // Create the defaults once
        var pluginName = "overviewContentsAsTabs",
defaults = {
    nodeItem: null
};
        var l_data = null;
        var l_el = null;
        var l_nodeItem = null;        
        var sortDirection = 'desc', sortColumn = 0;
        // The actual plugin constructor
        function Plugin(element, options) {
            this.element = element;

            // jQuery has an extend method which merges the contents of two or
            // more objects, storing the result in the first object. The first object
            // is generally empty as we don't want to alter the default options for
            // future instances of the plugin
            this.options = $.extend({}, defaults, options);
            this._defaults = defaults;
            this._name = pluginName;

            this.init();
        }

        
        Plugin.prototype = 
		{
		    init: function (item) {
		        
		        $(this.element).addClass('overviewContentsAsTabs');
		        this.initialize(this.element, item);
		    },

		    initialize: function (el, item) {
		        var plugin = this;
		        plugin.populateTabsContents(el, item);
		    },

		    rePopulateOverviewContents: function (item) {
		        if (item == undefined) {
		            window.console.error("No data is available");
		            return;
		        }
		        var plugin = this;
		        plugin.populateTabsContents(this.element, item);
		    },
		   
		    initPowerSupplyUnitTable : function() {
		        return $('#hpsum-overview-powersupply-table').dataTable({
		            oLanguage: {
		                sEmptyTable: Localizer.getString('hpsum.node.nodeInfoNotAvailable'),
		                sSearch: Localizer.getString('hpsum.common.search'),
		                sZeroRecords: Localizer.getString('hpsum.node.noPSDeviceFound')
		            },
		            bPaginate : false,
		            bProcessing : true,
		            bFilter : false,
		            bSort : true,
		            bAutoWidth : true,
		            bInfo : false,
		            bRetrieve : false,
		            bDestroy : true,
		            aoColumns : [
                        {mDataProp: 'location'},
                        { mDataProp: 'description' },
                        {mDataProp: 'firmware_version'},
                        {mDataProp: 'serialnumber'},
                        {mDataProp: 'model'}
		            ],
		            aaSorting: [[ 0, "asc" ]],
		        });				
		    },

		    initStorageTable: function () {
		        return $('#hpsum-overview-storage-table').dataTable({
		            oLanguage: {
		                sEmptyTable: Localizer.getString('hpsum.node.nodeInfoNotAvailable'),
		                sZeroRecords: Localizer.getString('hpsum.server.noSupportedStorageArraysFound')
		            },
		            bPaginate : false,
		            bProcessing : true,
		            bFilter : false,
		            bSort : true,
		            bAutoWidth : true,
		            bInfo : false,
		            bRetrieve : false,
		            bDestroy : true,
		            aoColumns : [
                        {mDataProp: 'controller'},
                        {mDataProp: 'location'},
                        {mDataProp: 'description'},
                        {mDataProp: 'disk_firmware_version'},
                        {mDataProp: 'controller_firmware_version'}
		            ],
		            fnCreatedRow: function (nRow, aData, iDataIndex) {
		                nRow.className += aData.name;
		            },
		            fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
		                return nRow;
		            },
		            "fnDrawCallback": function (oSettings) {
		                if (oSettings.aiDisplay.length == 0) {
		                    return;
		                }
		            },
		            "aaSorting": [[0, 'asc']],
		            "sDom": 'lfr<"giveHeight"t>ip'
		        });
		    },
			
		    initConnectionTable: function () {
		        return $('#hpsum-overview-nicfchbacna-table').dataTable({
		            oLanguage: {
		                sEmptyTable: Localizer.getString('hpsum.node.nodeInfoNotAvailable'),
		                sZeroRecords: Localizer.getString('hpsum.server.noSupportedNicFcHbaCnaFound')
		            },
		            bPaginate : false,
		            bProcessing : true,
		            bFilter : false,
		            bSort : true,
		            bAutoWidth : true,
		            bInfo : false,
		            bRetrieve : false,
		            bDestroy : true,
		            aoColumns : [
                        {mDataProp: 'type'},
                        { mDataProp: 'description' },
                        {mDataProp: 'driver_version'},
                        {mDataProp: 'firmware_version'}
		            ],
		            fnCreatedRow: function (nRow, aData, iDataIndex) {
		                nRow.className += aData.name;
		            },
		            fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
		                return nRow;
		            },
		            "fnDrawCallback": function (oSettings) {
		                if (oSettings.aiDisplay.length == 0) {
		                    return;
		                }
		            },
		            "aaSorting": [[0, 'asc']],
		            "sDom": 'lfr<"giveHeight"t>ip'
		        });
				
		    },

		    showPowerSupplyInfo: function (item) {

		        var powerSupplyTable = this.initPowerSupplyUnitTable();
		        powerSupplyTable.fnClearTable();
		        var tabType = '#hpsum-overview-powersupply-table tr';
		        var tableItem = [];
		        powerSupplyTable.fnAddData(tableItem);
		        if (item.devices === undefined || item.devices.psu_devices === undefined || item.devices.psu_devices.length === 0) {
		            this.showEmptyTableMsg(item, tabType);
		            return;
		        }

		        powerSupplyTable.fnClearTable();
		        
		        for (var nPSU = 0; nPSU < item.devices.psu_devices.length; nPSU++) {
		           tableItem = [{
		                location: Localizer.getString('hpsum.server.bay') + item.devices.psu_devices[nPSU].baynumber,
		                description: item.devices.psu_devices[nPSU].name,
		                firmware_version: item.devices.psu_devices[nPSU].installed_version,
		                serialnumber: item.devices.psu_devices[nPSU].serialnumber,
		                model: item.devices.psu_devices[nPSU].model
		            }];
		            powerSupplyTable.fnAddData(tableItem);
		        }
		    },

		    showEmptyTableMsg: function (item, TableName) {

		        var msgString = Localizer.getString('hpsum.node.nodeInfoNotAvailable');
		        if (!item.node_state.match(/idle/i)) {
		            if (TableName.indexOf('hpsum-overview-storage-table') != -1)
		            {
		                msgString = Localizer.getString('hpsum.server.noSupportedStorageArraysFound');
		            }
		            else if (TableName.indexOf('hpsum-overview-nicfchbacna-table') != -1)
		            {
		                msgString = Localizer.getString('hpsum.server.noSupportedNicFcHbaCnaFound');
		            }
		            else if (TableName.indexOf('hpsum-overview-powersupply-table') != -1)
		            {
		                msgString = Localizer.getString('hpsum.node.noPSDeviceFound');
		            }		            
		        }
		        $(TableName)[1].cells[0].innerHTML = msgString;
		    },
		    
		    showStorageInfo: function (item) {
		        var storageTable = this.initStorageTable();
		        if (storageTable.length > 0) {
		            storageTable.fnClearTable();
		        }
		        var tableItem = [];
		        storageTable.fnAddData(tableItem);
		        var TableName = '#hpsum-overview-storage-table tr';

		        if (item.devices === undefined || item.devices.storage_devices === undefined || item.devices.storage_devices.controllers === undefined || item.devices.storage_devices.controllers.length === 0) {
		            this.showEmptyTableMsg(item, TableName);
		            return;
		        }

		        var i;
		        

		        for (i = 0; i < item.devices.storage_devices.controllers.length; i++) {
		            var j;
		            var loc = "";
		            var desc = "No disks found";
		            var disk_firm = "";
		            if (item.devices.storage_devices.controllers[i].hasOwnProperty("drives")) {
		                for (j = 0; j < item.devices.storage_devices.controllers[i].drives.length; j++) {
		                    loc = item.devices.storage_devices.controllers[i].drives[j].type;
		                    desc = item.devices.storage_devices.controllers[i].drives[j].additional_description;
		                    disk_firm = item.devices.storage_devices.controllers[i].drives[j].firmware_version;


		                    tableItem = [{
		                        controller: item.devices.storage_devices.controllers[i].marketing_name,
		                        location: loc,
		                        description: desc,
		                        disk_firmware_version: disk_firm,
		                        controller_firmware_version: item.devices.storage_devices.controllers[i].firmware_version
		                    }];
		                    storageTable.fnAddData(tableItem);
		                }
		            }
		            else {
		                tableItem = [{
		                    controller: item.devices.storage_devices.controllers[i].marketing_name,
		                    location: loc,
		                    description: desc,
		                    disk_firmware_version: disk_firm,
		                    controller_firmware_version: item.devices.storage_devices.controllers[i].firmware_version
		                }];
		                storageTable.fnAddData(tableItem);
		            }
		        }

		    },
            
		    showConnectionInfo: function (item) {
		       
		        var connectionTable = this.initConnectionTable();
		        if (connectionTable.length > 0) {
		            connectionTable.fnClearTable();
		        }
		        var tableItem = [];
		        connectionTable.fnAddData(tableItem);
		        var TableName = '#hpsum-overview-nicfchbacna-table tr';
		        if (item.devices === undefined) {
		            this.showEmptyTableMsg(item, TableName);
		            return;
		        }
		        if (item.devices.fchba_devices === undefined && item.devices.nic_devices === undefined) {
		            this.showEmptyTableMsg(item, TableName);
		            return;
		        }
		        if ((item.devices.fchba_devices.fchba && item.devices.fchba_devices.fchba.length === 0) && (item.devices.nic_devices.nic && item.devices.nic_devices.nic.length === 0)) {
		            this.showEmptyTableMsg(item, TableName);
		            return;
		        }
		        if (item.devices.fchba_devices.length != 0) {
		            var i;
		            
		            for (i = 0; i < item.devices.fchba_devices.fchba.length; i++) {
		                if (!item.devices.fchba_devices.fchba[i].type && !item.devices.fchba_devices.fchba[i].additional_description) {
		                    continue;
		                }
		                tableItem = [{
		                    type: item.devices.fchba_devices.fchba[i].type,
		                    description: item.devices.fchba_devices.fchba[i].additional_description,
		                    firmware_version: item.devices.fchba_devices.fchba[i].firmware_version,
		                    driver_version: item.devices.fchba_devices.fchba[i].driver_version
		                }];
		                connectionTable.fnAddData(tableItem);
		            }

		        }
		        if (item.devices.nic_devices.length != 0) {
		            var i;
		            for (i = 0; i < item.devices.nic_devices.nic.length; i++) {
		                if (!item.devices.nic_devices.nic[i].type && !item.devices.nic_devices.nic[i].additional_description) {
		                    continue;
		                }
		                var tableItem = [{
		                    type: item.devices.nic_devices.nic[i].type,
		                    description: item.devices.nic_devices.nic[i].additional_description,
		                    firmware_version: item.devices.nic_devices.nic[i].firmware_version,
		                    driver_version: item.devices.nic_devices.nic[i].driver_version
		                }];
		                connectionTable.fnAddData(tableItem);
		            }


		        }

		    },
            
		   
		    showMemoryInfo: function (item) {
		        //TBD
		    },
		
		    populateTabsContents: function(id, item) {
		        
		        $(id).empty();		        
		        if ((item != undefined) && item.hasOwnProperty("node_id"))
		        {
		            var nodeItemId = item.node_id;
		            var storageDivContents = ('<div id="hpsum-overview-show-storage-' + nodeItemId + '" class="hp-panel-contents" style="overflow: hidden;"><table id="hpsum-overview-storage-table"><thead><tr style="background-color:lightgrey;"><td><b>' +
                       Localizer.getString('hpsum.server.controller') + '</b></td><td><b>' +
                       Localizer.getString('hpsum.common.locationStr') + '</b></td><td><b>' +
                       Localizer.getString('hpsum.common.description') + '</b></td><td><b>' +
                       Localizer.getString('hpsum.server.diskFV') + '</b></td><td><b>' +
                       Localizer.getString('hpsum.server.controllerFV') + '</b></td><td></td></tr></thead></table></div>');

		            var connectionDivConetnts = ('<div id="hpsum-overview-show-nicfchbacna-' + nodeItemId + '" class="hp-panel-contents" style="overflow: hidden;"><table id="hpsum-overview-nicfchbacna-table"><thead><tr style="background-color:lightgrey;"><td><b>' +
                         Localizer.getString('hpsum.common.locationStr') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.description') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.server.driverVersion') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.firmwareVersion') + '</b></td><td></td></tr></thead></table></div>');

		            var powerSuppyDivConetnts = ('<div id="hpsum-overview-show-powersupply-' + nodeItemId + '" class="hp-panel-contents" style="overflow: hidden;"><table id="hpsum-overview-powersupply-table"><thead><tr style="background-color:lightgrey;"><td><b>' +
                       Localizer.getString('hpsum.common.type') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.description') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.firmwareVersion') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.server.serialNumber') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.model') + '</b></td><td></td></tr></thead></table></div>');

		            /*var memoryDivConetnts = ('<div id="hpsum-overview-show-memory-' + nodeItemId + '" class="hp-panel-contents" style="overflow: hidden;"><table id="hpsum-overview-memory-table"><thead><tr style="background-color:lightgrey;"><td><b>' +
                        Localizer.getString('hpsum.common.type') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.description') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.server.driverVersion') + '</b></td><td><b>' +
                        Localizer.getString('hpsum.common.firmwareVersion') + '</b></td><td></td></tr></thead></table></div>'); */

		            $(id).append('<div style="overflow: hidden;"><ol id="overview-tabs-' + nodeItemId + '"><div id="hpsum-tabs-show-panel-selector-' + nodeItemId +
                        '" class=" hp-panel-selector hp-contents hp-details-nav" style="margin-left: -10px; overflow: hidden;"><ol class="hp-options" id="overview-ind-tabs-' +
                        nodeItemId + '"><li class="hp-stacked-panel" id="li-show-storage-details-' + nodeItemId +
                        '"><a class="hp-anchor-uri" id="show-storage-details-' + nodeItemId + 
                        '" data-panel-id="hpsum-overview-show-storage-' + nodeItemId + 
                        '" href="#/node/show" rel="localize[hpsum.server.storage]">' +
                        Localizer.getString('hpsum.server.storage') + '</a></li><li class="hp-stacked-panel" style="padding-left:30px;" id="li-show-nicFcHbaCna-details'
                        + nodeItemId + '"><a class="hp-anchor-uri" id="show-nicFcHbaCna-details-' + nodeItemId + 
                        '" data-panel-id="hpsum-overview-show-nicfchbacna-' + nodeItemId + 
                        '" href="#/node/show" rel="localize[hpsum.server.nicFcHbaCna]">' +
                        Localizer.getString('hpsum.server.nicFcHbaCna') + '</a></li><li class="hp-stacked-panel" style="padding-left:30px;" id="li-show-powersupply-details'
                        + nodeItemId + '"><a class="hp-anchor-uri" id="show-powersupply-details-' + nodeItemId +
                        '" data-panel-id="hpsum-overview-show-powersupply-' + nodeItemId +
                        '" href="#/node/show" rel="localize[hpsum.server.powerSupplyUnit]">' +
                        Localizer.getString('hpsum.server.powerSupplyUnit') + 
                        //'</a></li><li class="hp-stacked-panel" style="padding-left:30px;" id="li-show-memory-details'
                        //+  + '"><a class="hp-anchor-uri" id="show-memory-details-' + nodeItemId + 
                        //'" data-nodeItemIdpanel-id="hpsum-overview-show-memory-' + nodeItemId + 
                        //'" href="#/node/show" rel="localize[hpsum.server.memory]">' +
                        //Localizer.getString('hpsum.server.memory') + 
                        '</a></li></ol></div></ol><ol id="overview-tab-contents-' + nodeItemId +
                        '"><li class="hp-stacked-panel" id="li-hpsum-overview-show-storage-' + nodeItemId + '"> ' + storageDivContents +
                        '</li><li class="hp-stacked-panel" id="li-hpsum-overview-show-nicfchbacna-' + nodeItemId + '">  ' + connectionDivConetnts +
                        '</li><li class="hp-stacked-panel" id="li-hpsum-overview-show-powersupply-' + nodeItemId + '">  ' + powerSuppyDivConetnts +
                        //'</li><li class="hp-stacked-panel" id="li-hpsum-overview-show-memory-' + nodeItemId + '">  ' + memoryDivConetnts +
                        '</li></ol></div>');

		            var storageDivId = "#hpsum-overview-show-storage-"  + nodeItemId;
		            var connectionDivId = "#hpsum-overview-show-nicfchbacna-" + nodeItemId;
		            var powerSupplyDivId = "#hpsum-overview-show-powersupply-" + nodeItemId;
		            //var memoryDivId = "#hpsum-overview-show-memory-" + nodeItemId;
		        
		            $(storageDivId).html(this.showStorageInfo(item));
		            $(connectionDivId).html(this.showConnectionInfo(item));
		            $(powerSupplyDivId).html(this.showPowerSupplyInfo(item));
		           // $(memoryDivId).html(this.showMemoryInfo(item));

		            var storageTab = "#show-storage-details-" + nodeItemId;
		            var connectionTab = "#show-nicFcHbaCna-details-" + nodeItemId;
		            var powerSupplyTab = "#show-powersupply-details-" + nodeItemId;
		            //var memoryTab = "#show-memory-details-" + nodeItemId;

		            var plugin = this;
                
		            $(storageTab).click(function () {
		                plugin.handleTabClickAction(this, nodeItemId);
		                return false;
		            });
		            $(connectionTab).click(function () {
		                plugin.handleTabClickAction(this, nodeItemId);
		                return false;
		            });
		            $(powerSupplyTab).click(function () {
		                plugin.handleTabClickAction(this, nodeItemId);
		                return false;
		            });
		            //$(memoryTab).click(function () {
		              //  plugin.handleTabClickAction(this, nodeItemId);
		               // return false;
		            //});

		            //default first tab will be selected. 
		            $(storageTab).trigger('click');
		        }
            },
           
		    handleTabClickAction: function (tab, nodeItemId)
		    {
		        var overTabsId = "#overview-tab-contents-" + nodeItemId;
		        for (var eleCount = 0; eleCount < $(overTabsId)[0].children.length; eleCount++)
		        {
		            $('#' + $(overTabsId)[0].children[eleCount].id).hide(); //hide all the contents
		        }
		        for (var optCount = 0; optCount < $('#overview-ind-tabs-' + nodeItemId)[0].children.length; optCount++)
		        {
                    //unset all the tabs to default.
					var child = $('#overview-ind-tabs-' + nodeItemId)[0].children[optCount].children[0];
		            $('#overview-ind-tabs-' + nodeItemId)[0].children[optCount].children[0].style.color = "#00B388";
					$(child).addClass('company-a');
                    $(child).removeClass('company-background');
		        }
			 
		        $('#li-' + tab.getAttribute("data-panel-id")).show();//show the tab's content.
		        tab.style.color= "#000";// set the tab selection.
		        $(tab).addClass('company-background');
		        $('.hp-panel-contents-container').addClass('sum-unset-dimensions');
		    },

		    

            destroy: function (el) {
                $(this.element).removeClass('overviewContentsAsTabs');
                $.removeData(this.element, "plugin_" + pluginName);
            }           
        };

      

		// A really lightweight plugin wrapper around the constructor,
        // preventing against multiple instantiations
        $.fn[pluginName] = function (options) {
            var instance;
            if (typeof options === 'string') {
                if (options.match(/init/i)) {
                    return this.each(function () {
                        if (!$.data(this, "plugin_" + pluginName)) {
                            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
                        }
                    });
                }
            }   
            var argument, args;
            if (typeof options === 'string') {
                argument = options;
                args = Array.prototype.slice.call(arguments, 1);
            }
            else {
                argument = options.command;
                args = options.item;
            }
            // call method
            this.each(function () {
                instance = $.data(this, "plugin_" + pluginName);
                if (!instance) {
                    if (!options.match(/destroy/i)) {
                        if (window.console) {
                            window.console.error("cannot call methods on overviewContentsAsTabs prior to initialization; " +
                                "attempted to call method '" + argument + "'");
                        }
                    }
                    return;
                }
                if (!$.isFunction(instance[argument]) || argument.charAt(0) === "_") {
                    if (window.console) {
                        window.console.error("no such method '" + argument + "' for overviewContentsAsTabs instance");
                    }
                    return;
                }
                // apply method
                instance[argument].call(instance, args);
            });
        };


    } (jQuery));
});

