// ===== tabs, by lith ==============
// if any li has the class "selected", that tab will open by default. Otherwise the default open tab => first tab
/*
Modified by Hoi on 20110503
Added debug information, comment and description
*/

var activeControl = false;
var initHashChange = function () {

    $(window).bind("hashchange", function (e) {
        console.warn("initHashChange: (%o) %o", activeControl, e);
        if (!activeControl) {
            $(".tabinited").removeClass("tabinited").each(function () {
                $(this).attr("title", $(this).attr("hook"));
            });
            anchor.read();
            init_tabs("body");
        }
        activeControl = false;

    });

    $(window).trigger("hashchange");

}

function init_tabs(scope) {
    console.info("Init_tabs (%s)", scope);
    $("body").find("div.tabs, ul.tabs, a.tabs").each(function () {
        tabs.init.apply(this);
    });
    $("a.tabs").each(function () {
        $(this).unbind("click").click(function () {
            console.warn("init_tabs: Calling settab %o", $(this).attr("href"));
            tabs.settab($(this).attr("href"), this);
            $.scrollTo(".main_container");
            return (false);
        });
    });
}

var tabs = {
    init: function () {



        console.info("Tabs.init started: %o", this);

        if (this == null) return (false);
        if ($(this).length == 0) return (false);

        var mytab = $(this);
        console.info("Tabs.init: mytab became %o", mytab);

        // Forgot ?
        if (anchor.isHashFree) {
            console.debug("Anchor is hash free.");
            if (anchor.defaultTabs != null && anchor.defaultTabs != undefined) anchor.defaultTabs.each(function () {
                try {
                    $(this).addClass("selected").siblings().removeClass('selected');
                } catch (e) { }
            })
        }

        // Skipped tab with class: no_init and tabinited
        if (mytab.hasClass("no_init")) return (false);
        if (mytab.hasClass("tabinited")) return (false);
        mytab.addClass("tabinited");

        // Adding hook attribute to the element that have title with title_content
        var title = mytab.attr("title");
        if (title != "") {
            console.debug("Adding hook: %o", title);
            mytab.attr({ "title": "", "hook": title });
            $("[title='" + title + "_content']").attr({ "title": "", "hook": title + "_content" });
        }

        var cnt = 0;
        var selected = null;
        var mytabitem;

        // Finding selected element by the anchor paremeter and add 'selected' class into it
        if (!mytab.hasClass("no_propagate")) {
            console.debug("Finding selected by Anchor parameter: %o", anchor.parameter);
            if (typeof (anchor.parameter["tab"]) != "undefined") {
                selected = mytab.find("li a[href$='" + anchor.parameter["tab"] + "']");
            } else {
                if (typeof (anchor.parameter[title]) != "undefined") {
                    selected = mytab.find("a[href$='" + anchor.parameter[title] + "']");
                }
            }
            if (selected != null && selected.length) {
                console.info("Found Selected: %o and add class 'selected'", selected);
                selected.parents("li:eq(0)").addClass("selected").siblings().removeClass('selected');
            }
        }

        // Use the first element of mytab to be the default selected if no other selected element
        if (!mytab.hasClass("no-default")) {
            if (mytab.find(".selected").length > 0) {
                if (selected == null) {
                    selected = mytab.find(".selected a:eq(0)");
                    if (selected != null && selected.length) {
                        console.debug("Use the first element of mytab to be the default: %o", selected);
                    }
                    /*
                    if (selected != null && selected.length) {
                    // Trying to load the content from the selected href
                    tabs.settab(selected.attr("href"));
                    }
                    */
                }
            }
        }

        // Looping each tab item
        if (mytab.find("li a").length > 0) {
            mytab.find("li a").each(function () {
                mytabitem = $(this);
                var href = mytabitem.attr("href"); //.toString().replace("#","");
                if (selected == null) {
                    if (mytabitem.parents("li:eq(0)").hasClass("selected")) {
                        selected = mytabitem;
                    } else {
                        if (!mytab.hasClass("no-default")) {
                            selected = mytabitem;
                        }
                    }
                }
                // Add background image on the tab if found any img inside
                if ((!mytab.hasClass("no-background")) && (mytabitem.find("img").length > 0)) {
                    console.debug("Adding background image on %o", mytabitem);
                    mytabitem.css({ "background-image": "url('" + mytabitem.find("img").attr("src") + "')" });
                }
                // Bind click for the tab item
                mytabitem.click(function () {
                    // Skipped if found target attribute
                    if ($(this).attr('target')) {
                        return true;
                    }
                    anchor.isHashFree = false;
                    tabs._settab($(this).attr("href"));
                    if ($(this).parents(".tabscontent").length > 0) $.scrollTo(".main_container");
                    return (false);
                });
            });
            mytabitem.parents("li:eq(0)").addClass("last");


            // Trying to load content of selected element (Important in default tab loading)
            
            if (!mytab.hasClass("no-default")) {
                if (selected !== null && selected.length) {
                   tabs.settab(selected.attr("href"));
                }
            }
            

        }

        // ??
        if (this.tagName.toLowerCase() == "a") mytab.click(tabs._settab);

        // Unbind click event if target attribute found in mytab
        if (mytab.find("a[target]").length) {
            console.debug("Unbind click event on %o (have target)", mytab.find("a[target]"));
            mytab.find("a[target]").unbind("click");
        }

        // Loading settab from selected element finally
        if (!mytab.hasClass("no-default")) {
            if (mytab.find(".selected").length > 0) {
                console.warn("Loading settab from the selected element: %o", selected);
                tabs.settab(selected.attr("href"));
            }
        }

        // ?? dunno isHashFree set from where yet
        if (anchor.isHashFree) {
            console.warn("Anchor is hash free, saving selected element: %o to defaultTabs", mytab.find(".selected"));
            anchor.defaultTabs = mytab.find(".selected");
        }

        // Loading content by take value from anchor, according to the tab title
        console.debug("Taking value from anchor %o : %o", title, anchor);
        if (!mytab.hasClass("no_propagate")) {
            if (typeof (anchor.parameter["tab"]) != "undefined") {
                mytab.find("li a[href$='" + anchor.parameter["tab"] + "']").parents("li:eq(0)").addClass("selected").siblings().removeClass('selected');
            } else {
                if (typeof (anchor.parameter[title]) != "undefined") {
                    if (typeof (anchor.parameter[title + "_default"]) != "undefined" && !mytab.find("li a[href$='" + anchor.parameter[title] + "']").length) {
                        mytab.find("li a[href$='" + anchor.parameter[title + "_default"] + "']").parents("li:eq(0)").addClass("selected").siblings().removeClass('selected');
                    }
                    console.warn("Calling settab from anchor title parameter: %o", anchor.parameter[title]);
                    tabs.settab(anchor.parameter[title]);
                }
            }
        }
    },
    // child tabs in anchor deletion process of settab when corresponding tab is clicked.
    _settab: function () {
        var me = $(this);
        console.group("_settab started: %o (%o)", arguments, anchor);
        if (typeof (arguments[0]) == "string") {
            me = $(".tabs li a[href='" + arguments[0] + "']");
        }

        $("[hook=" + me.parents(".tabs:eq(0)").attr("hook") + "_content]").find(".tabs, .tabscontent").each(function () {
            // kill child tabs
            var t = $(this).attr("hook") || $(this).attr("title");
            delete (anchor.parameter[t]);
            delete (anchor.parameter[t.replace("_content", "")]);
        })
        if (me.length) {
            var href = me.attr("href");
            console.warn("_settab: calling settab %o %o", href, this);
            tabs.settab(href, this);
        }
        console.debug(anchor);
        console.groupEnd();
        return (false);
    },
    settab: function () {
        //var target=[$("div[title="+groupid+"_content]"), $(".right_column p>ul")];

        console.group("settab started with arguments: %o", arguments);

        var me = $(this);

        if (typeof (arguments[0]) == "string") {
            me = $(".tabs li a[href='" + arguments[0] + "']:eq(0)");
        }

        // Using hook as groupid
        var groupid = (me.parents(".tabs:eq(0)").length > 0) ? me.parents(".tabs:eq(0)").attr("hook") : null;
        var tabsrc = me.attr("href") ? me.attr("href") : arguments[0];

        try {
            for (var i in anchor.parameter) {
                if (anchor.parameter[i] == arguments[0]) {
                    var groupid = i;
                    var tabsrc = arguments[0];
                }
            }
        } catch (e) { }


        if (typeof (arguments[1]) != "undefined") {
            if ($(arguments[1]).hasClass("tabs")) {
                var groupid = $(arguments[1]).attr("hook") || $(arguments[1]).attr("title");
                var tabsrc = $(arguments[1]).attr("href");
            }
        }

        //        console.log(me);

        //        console.log("settab " + arguments[0] + "[" + groupid + "]>[" + tabsrc + "]");
        if (!groupid) {
            console.groupEnd();
            return ("");
        }

        //		alert("debug: calling fn-settab with "+groupid+" "+tabsrc);



        var srcary = tabsrc.split("::");

        if (latesttab == groupid + " " + srcary[0]) {
            console.groupEnd();
            return false;
        }
        latesttab = groupid + " " + srcary[0];
        activeControl = true;
        delete (anchor.parameter.tab);
        anchor.parameter[groupid] = srcary[0];
        console.debug("Anchor going to rebuild: %o", anchor);
        if (!anchor.isHashFree) anchor.rebuild();


        //		var uncachedURL=(srcary[0].indexOf("?")>-1)?srcary[0]+"&ran="+Math.random():srcary[0]+"?ran="+Math.random(); 

        $("div[hook=" + groupid + "_content]").find('#photos .slideshow').cycle("destroy");
        /*.load(uncachedURL, function(){
        afterload("div[hook="+groupid+"_content]");
        });*/
        console.warn("Calling AJAX to %o on div hook of %o", srcary[0], $("div[hook=" + groupid + "_content]"));
        $.ajax({
            url: srcary[0],
            cache: false,
            context: $("div[hook=" + groupid + "_content]"),
            success: function (text) {
                console.warn("Ajax onSuccess of %o on div hook of %o", srcary[0], $("div[hook=" + groupid + "_content]"));
                $("div[hook=" + groupid + "_content]").addClass("tabscontent").html(text);
                afterload("div[hook=" + groupid + "_content]");
            },
            mode: "queue"
        });



        me.parents("li:eq(0)").addClass("selected").siblings().removeClass('selected');

        var showrightpanel = null;
        var showtextlink = null;
        for (var i = 1; i < srcary.length; i++) {
            var tmp = srcary[i].split("->", 2);
            switch (tmp[0]) {
                case "show_rightpanel": showrightpanel = (showrightpanel !== null) ? showrightpanel : (tmp[1] == "true"); break;
                case "show_textlink": showtextlink = (showtextlink !== null) ? showtextlink : (tmp[1] == "true"); break;
                case "textlink":
                    showrightpanel = true;
                    showtextlink = true;
                    $.getJSON(tmp[1], textlink.render);
                    break;
            }
        }

        if (showrightpanel !== null) {
            if (showrightpanel) {
                $(".main_container").removeClass("no_rightpanel");
            } else {
                $(".main_container").addClass("no_rightpanel");
            }
        }
        if (showtextlink !== null) {
            if (showtextlink) {
                $(".right_column").removeClass("no_textpanel");
            } else {
                $(".right_column").addClass("no_textpanel");
            }
        }
        console.groupEnd();
        return (false);
    }

}
