﻿function agahSystems_tabHistory_init(tabSelect) {
    function load(initUrl) {
        $(tabSelect).tabs();
        
        $(tabSelect).find("ul:first").find(">li>a").bind('click', function(e) {
            var parent = $(this).closest(tabSelect).attr('id');
            var cur = $(this).attr('href');
            cur = cur.replace(/^.*#/, '');

            //
            var hash = window.location.hash;
            hash = hash == null ? "" : hash;
            hash = hash.replace("#", "");
            var prefix = ("__" + parent + "_").toLowerCase();

            var p = hash.toLowerCase().indexOf(prefix);
            if (p == -1) {
                hash += prefix + cur;
            } else {

                var e = hash.indexOf("_", p + prefix.length);
                if (e == -1)
                    e = hash.length;
                var t = hash.substring(p, e);
                hash = hash.replace(t, prefix + cur);
            }

            //
            $.history.load(hash);
           
            return false;
        });


        $(tabSelect).each(function() {
            var tab = $(this).attr('id');
            var val = $(this).find("ul:first>li>a").first().attr('href');          
            if (initUrl != null && initUrl != "") {                
                var prefix = ("__" + tab + "_").toLowerCase();
                var p = initUrl.toLowerCase().indexOf(prefix);
              
                if (p != -1) {
                    var e = initUrl.indexOf("_", p + prefix.length);
                    if (e == -1)
                        e = initUrl.length;
                    var t = initUrl.substring(p + prefix.length, e);
                    val = '#' + t;
                }
            }

            $('#' + tab).tabs('select', val);
        });
    };

    $.history.init(function(url) {
        load(url);
    });
}
