/* - scroller.js - */
/**
 * User editable tabs for WYSIWYG HTML editors
 * 
 * Idea taken from form_tabbing.js.
 * 
 * @author Mikko Ohtamaa <mikko.ohtamaa@twinapex.com>
 * 
 * @copyright Twinapex Research
 * 
 * @license GPL
 * 
 * @version 1.0
 * 
 * http://www.twinapex.com - High quality Javascript hackers for hire
 * 
 */

// Declare namespace
scroller = {}

// Generated tab ids
scroller.idCounter = 0;

/**
 * Tab content container
 * 
 * @param {Object} title, non-html user visible name
 * @param {Object} content, htmlish content
 */
scroller.Tab = function(title, open) {
    this.id = null; // Generated later
    this.open = open;
    this.title = title;
    this.content = jq('<div class="scrollable-div"><!-- Dynamically generated tab --></div>');
}

/**
 * Bootstrap tab fixing when the page is loaded
 * 
 * Mutates DOM tree suitable for Javascript based tab viewing.
 */
scroller.collectTabs = function() {

    // List of tabs as Tab instances
    scroller.log("Creating tabs");
    
    // Walk through all content nodes which contain tab elements
    jq("h2.scroller-definer").parent().each(function() {

        var tabs = [];

        var collecting = false;
        var curTab = null;

        var parent = this;

        scroller.log("Scanning field " + jq(parent).attr("id"));

        // Walk through all HTML nodes and if we match a tab title
        // walk forward and put all content into a tab,
        // remove the content node from the orignal container
        jq(this).contents().each(function() {
            var t = jq(this);

            scroller.log("Walking " + t.attr("id"));

            if(t.hasClass("scroller-definer")) {
                // Create new tab
                var open = t.hasClass("kuputab-tab-definer-default");

                scroller.log("Making tab" + t.text());

                var tab = new scroller.Tab(t.text(), open)
                tabs.push(tab)
                curTab = tab;

                // Remove handler definers, 
                // so reruns of init won't double create them
                t.removeClass("scroller-definer");

                parent.removeChild(this);
            } else {

                // Add node part to the current tab
                if(curTab != null) {
                    parent.removeChild(this);	
                    curTab.content.append(this);
                }

            }

        });

        var container = scroller.constructContainer(tabs);
        jq(parent).append(container);
    });

    // TODO: Automatically detect open tab from # URL prefix

    scroller.log("Found tab count:" + scroller.idCounter);	
}

/**
 * Create DOM tree for a tab container
 */
scroller.constructContainer = function(tabs) {

    scroller.log("Constructing tab container for tabs " + tabs.length);

    var cont = jq('<div id="scrollable"><!-- Dynamically generated tab  container --></div>');
    var i;

    if(tabs.length == 0) {
        return;
    }

    var itemsdiv = jq('<div class="items"><!-- items container --></div>');
    // Create tab content
    for(i=0; i<tabs.length; i++) {
        var tab = tabs[i];
        var first = (i == 0);
        var last = (i == tabs.length - 1);

        // JQuery node containing content
        var content = tab.content;
        // content.attr({"id": "scrollable-div"});
        // if(tab.open) {
        //     // pass
        // } else {
        //     tab.content.addClass("hidden");
        // }

        itemsdiv.append(content);
    }

    

    cont.append(itemsdiv);
    return cont;
}


/**
 * Page on-load handler.
 */
scroller.init = function() {

    try {
        // Check if we are in edit or view mode
        if(document.designMode.toLowerCase() == "on") {
            // Edit mode document, do not tabify 
            // but let the user create the content
            return;
        } else {
            scroller.collectTabs();
        }
    } catch(e) {
        scroller._printStackTrace(e);
    }
}

scroller.log = function(msg) {
    // TODO: Optimze, overload this with a proper logger
    if(typeof(console) != "undefined") {
        if(typeof(console.log) != "undefined") {
            console.log(msg);
        }
    }
}

// Debug functions - copied from ecmaunit.js
scroller._printStackTrace = function(exc){

    function print(msg) {
        scroller.log(msg);
    }

    print(exc);

    if (!exc.stack) {
        print('no stacktrace available');
        return;
    };
    var lines = exc.stack.toString().split('\n');
    var toprint = [];
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        if (line.indexOf('ecmaunit.js') > -1) {
            // remove useless bit of traceback
            break;
        };
        if (line.charAt(0) == '(') {
            line = 'function' + line;
        };
        var chunks = line.split('@');
        toprint.push(chunks);
    };
    toprint.reverse();

    for (var i = 0; i < toprint.length; i++) {
        print('  ' + toprint[i][1]);
        print('    ' + toprint[i][0]);
    };
    print();
}

jq(scroller.init);


jq(document).ready(function(){
    var cont = jq("#scrollable")
    cont.before('<a class="prevPage browse left"></a>');
    cont.after('<a class="nextPage browse right"></a>');
    
    jq("#scrollable").scrollable({size:1, loop: true, circular:true}).autoscroll({autoplay: true, interval: 2000});
});


