﻿/****************************************************
* jquery dropzone tabs plugin
* author: drousseau
* date: 6/16/2010
*
* Use:  $('div').dropzoneTabs([{options}]);
* Call on a dropzone div, and it will create a tab 
* for each widget within the dropzone.  To exclude a widget from 
* being 'tabbified', add a class of 'notab' to it.  
*
* Options:
* column: the column index within the dropzone to tabify
* displayTab: the default tab to display 
* rawUrl: the raw url of the page, used to get the tab parameter from the querystring
*****************************************************/

$.fn.dropzoneTabs = function(params) {

    var defaults = {
        column: -1,
        displayTab: 0,
        rawUrl: '',
        // Number of widget to wrap on each tab
        groupingPattern: ''
    };

    // Overwrite default options 
    // with user provided ones 
    // and merge them into "options".
    var options = $.extend({}, defaults, params);

    // Creates the tabs for each widget
    createTabsFromColumn = function(widgets) {
        //var widgets = $('ul.columnwidgetlist li.PBItem:not(:has(div.noTab))', column);
        var tabsMarkup = '';

        if (options.groupingPattern != '') {
            var groups = options.groupingPattern.split(',');
            var index = 0;

            for (i = 0; i < groups.length; i++) {
                var number = groups[i] * 1;

                var firstWidget = $(widgets).eq(index);
                var column = firstWidget.parents('div.PBViewing')[0];
                tabsMarkup += '<li><a class="tab" href="#tabWidget' + $(column).index() + '_' + index + '"><span>';
                if ($('div.TabTitle', firstWidget).length > 0) {
                    tabsMarkup += $('div.TabTitle', firstWidget).attr('title');
                } else {
                    tabsMarkup += "No Title";
                }
                tabsMarkup += '</span></a></li>';

                for (subindex = 1; subindex < number && index + subindex < $(widgets).length; subindex++) {
                    var currentWidget = $(widgets).eq(index + subindex);
                    firstWidget.html(firstWidget.html() + currentWidget.html());
                    currentWidget.html('');
                }

                var openDiv = '<div id="tabWidget' + $(column).index() + '_' + index + '" class="tab-wrap"/>';
                firstWidget.wrapInner(openDiv);

                index += number;
            }
        }
        else {
            $(widgets).each(function(i) {
                var column = $(this).parents('div.PBViewing')[0];
                var tabClass = '';
                if (i == 0) {
                    tabClass = 'tabs-text ui-corner-all sec-three-on';
                }
                else {
                    tabClass = 'tabs-text ui-corner-all sec-three-off';
                }
                tabsMarkup += '<li><a class="tab ' + tabClass + '" href="#tabWidget' + $(column).index() + '_' + i + '">';
                if ($('div.TabTitle', this).length > 0) {
                    tabsMarkup += $('div.TabTitle', this).attr('title');
                } else {
                    tabsMarkup += "No Title";
                }
                tabsMarkup += '</a></li>';
                // wrap each widget in a div
                $(this).wrapInner('<div id="tabWidget' + $(column).index() + '_' + i + '" class="tab-wrap" />');
            });
        }

        return tabsMarkup;
    }

    // Adds the click event to each tabs anchor
    addEventsToTabs = function(column) {
        $('div.tab-container ul.tab-menu li a', column).each(function() {

            $(this).bind('click', function() {

                $('ul.tab-menu a', column).removeClass('selected');
                $('ul.tab-menu a', column).removeClass('sec-three-on');
                $('ul.tab-menu a', column).addClass('sec-three-off');
                $(this).removeClass('sec-three-off');
                $(this).addClass('selected sec-three-on');

                $('ul.tab-menu li', column).removeClass('selected');
                $(this).parent('li').addClass('selected');

                $('div.tab-wrap', column).hide();

                var fullpath = $(this).attr("href");

                $('div' + fullpath.substring(fullpath.lastIndexOf('#'))).show();
                
                var parentli = $(this).parent('li');
                //                $('input.viewTabIndex').val($('li').index(parentli));
                //$('input.viewTabIndex').val($(this).parent('li').index());
                $('input.viewTabIndex').val($('ul.tab-menu li').index(parentli));
                
                return false;
            });
        });
    }

    // Determines which tab to display in the following order:
    // 1. Selects from the hidden input - means a tab has been clicked and the page has posted back
    // 2. The querystring parameter 'tab'
    // 3. The Default option
    setDisplayTab = function(dropzone) {

        var displayTabIndex = 0;
        if (parseInt($('input.viewTabIndex').val()) > -1) {

            // check if we are in a postback, the hidden input value will be set to 
            // the last tab checked
            displayTabIndex = parseInt($('input.viewTabIndex').val());
        } else if (getParameterByName('tab').length > 0) {

            // if not postback, and the tabIndex was passed in the qs
            displayTabIndex = parseInt(getParameterByName('tab'));
        } else {

            // default - set it to the options default setting
            displayTabIndex = options.displayTab;
        }

        // show the tab to display, and add a class of "selected" to it
        //alert("dropzone " +  $($('div.tab-wrap', dropzone)[displayTabIndex]));
        $($('div.tab-wrap', dropzone)[displayTabIndex]).show();
        $('div.tab-container ul.tab-menu li a').removeClass('sec-three-on').addClass('three-sec-off');
        $($('div.tab-container ul.tab-menu li:eq(' + displayTabIndex + ') a', dropzone)).addClass('selected').addClass('sec-three-on');
        $($('div.tab-container ul.tab-menu li:eq(' + displayTabIndex + ')', dropzone)).addClass('selected');
    }



    // retrieves a querystring parameter value.
    getParameterByName = function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1];
    }

    return this.each(function() {
        if ($('div[EditMode=true]').length <= 0) {
            var tabContainer = $(this);

            // get the dropzone that this widget is in
            var dropzone = $(this).parents('div.dropzone:first');

            var currentWidget = $(this).parents('li.PBItem')[0];

            // hide the dropzone so there's no flickering if the changes take long
            //$(dropzone).hide(); // uncomment later

            // determine which columns to get widgets from
            var columns = $('div.PBViewing', dropzone);
            var columnsToTab = $(options.column < 0 ? columns : $(columns[options.column]));

            // build the html for the tabs
            var tabsHtml = '<div class="tab-container"><ul class="tab-menu">';

            // hide all widgets that don't contain a <div class="noTab">
            $(currentWidget).nextAll($('li.PBItem:not(:has(div.noTab))', columnsToTab)).hide();
            var widgets = $(currentWidget).nextAll($('li.PBItem:not(:has(div.noTab))', columnsToTab));

            tabsHtml += createTabsFromColumn(widgets);
            tabsHtml += '</ul></div>';

            // add the tab-content div and the tabs html to the tab container
            $(tabContainer).prepend('<div class="tab-content"/>');
            $(tabContainer).prepend(tabsHtml);
            $('div.tab-wrap', dropzone).prependTo($('div.tab-content', tabContainer)).hide();
            $('div.tab-wrap').wrapInner('<div class="top"/>');

            // create the click events to the tabs
            addEventsToTabs(this);

            // set the display tab
            setDisplayTab(dropzone);

            // show the dropzone
            $(dropzone).show();
        }
    });

};
