/********************************* Menu Tab ***********************************/

// CSS helper functions
CSS = {
    // Adds a class to an element.
    AddClass: function (e, c) {
        if (!e.className.match(new RegExp("\\b" + c + "\\b", "i")))
            e.className += (e.className ? " " : "") + c;
    },

    // Removes a class from an element.
    RemoveClass: function (e, c) {
        e.className = e.className.replace(new RegExp(" \\b" + c + "\\b|\\b" + c + "\\b ?", "gi"), "");
    }
};

// Functions for handling tabs.
Tabs = {
    // Changes to the tab with the specified ID.
    GoTo: function (contentId) {
        // This variable will be true if a tab for the specified
        // content ID was found.
        var foundTab = false;

        // Get the menu_list element.
        var menu_list = document.getElementById("menu-list");
        if (menu_list) {
            var lis = menu_list.getElementsByTagName("li");
            for (var j = 0; j < lis.length; j++) {
                var li = lis[j];

                // Give the current tab link the class "current" and
                // remove the class from any other TOC links.
                var anchors = li.getElementsByTagName("a");
                for (var k = 0; k < anchors.length; k++) {
                    if (anchors[k].id == contentId + "-tab") {
                        CSS.AddClass(li, "active");
                        foundTab = true;
                        break;
                    } else {
                        CSS.RemoveClass(li, "active");
                    }
                }
            }
        }

        // Show the content with the specified ID.
        var divsToHide = [];
        var divs = document.getElementsByTagName("div");
        for (var i = 0; i < divs.length; i++) {
            var div = divs[i];

            if (div.className.match(/\menu-content\b/i)) {
                if (div.id == contentId + "_content")
                    div.style.display = "block";
                else
                    divsToHide.push(div);
            }
        }

        // Hide the other content boxes.
        for (var i = 0; i < divsToHide.length; i++)
            divsToHide[i].style.display = "none";
    }
};

function selectMenuTab(contentId) {
  if (contentId) Tabs.GoTo(contentId);
}


/********************************* Longdo Tab ***********************************/

var hash = false;

var $tabs;
// jQuery.noConflict();
$(document).ready(function() {
	// tabs init with a custom tab template and an "add" callback filling in the content
	$tabs = $('#longdotab > ul').tabs({
  	add: function(event, ui) {
      $(this).tabs('select', ui.index);
      resizeTab();
		},
    tabTemplate: '<li><span class="span-tab"><a href="#{href}"><span>#{label}</span></a> <div class="ui-tab-close"><img src="/mmmap/images/cross-red.png" /></div></span></li>',
    cache: true,
    cookie: { expires: 1 },
    ajaxOptions: { async: false, cache:true },
		show: function(event, ui) { //alert(ui.toSource());
		  if(mmmap) {
        if(ui.panel.id == "map_content") {
          mmmap.showControl();
        }
        else {
          mmmap.hideControl();
        }
      }
      
      if($('#'+ui.panel.id).children('iframe.iframe-ooitab').length>0) {
        if($('#'+ui.panel.id).children('iframe.iframe-ooitab-ajax').length>0 && !$('#'+ui.panel.id).children('iframe.iframe-ooitab-ajax').hasClass('iframe-loaded')) {
          $('#'+ui.panel.id).prepend("<div class='ajax-loading-img' style='width:100%; text-align:center; margin:10px; position:absolute;'><img src='/mmmap/images/loading.gif'></div>");        
        }
        
        $('#'+ui.panel.id+' iframe.iframe-ooitab').load(function() {
          $('.ajax-loading-img').remove();
          $(this).addClass("iframe-loaded");
        });
      }
	
    	$('#longdotab div.ui-tab-close').bind('click', function() {
    		var index = $('li',$tabs).index($(this).parent("span").parent("li"));
    		$tabs.tabs('remove', index);
    	});
        
      $('#longdotab ul.ui-tabs-nav li a')
        .mouseover(function(){
          $(this).parent("span").parent("li").addClass("ui-tabs-hover");
        })
      	.mouseout(function(){
      		$(this).parent("span").parent("li").removeClass("ui-tabs-hover");
      	})
      	
      $(".top-button-intab")
        .mouseover(function(){
      		$(this).css("backgroundPosition", "0 100%");
      	})
      	.mouseout(function(){
      		$(this).css("backgroundPosition", "0 0");
      	})
    },
    length: function() {
      return this.anchors.length;
    },    
    load: function(event, ui) {
      $('#longdomap a[@rel=showimage]').click(function() {
        showThickbox(this.href, 'image');
        return false;
      });
      $('#longdomap a[@rel=showtext]').click(function() {
        showThickbox(this.href, 'textbox');
        return false;
      });
      $('#longdomap a[@rel=showtag]').click(function() {
        showTag($(this).text());
        return false;
      });
      $('#longdomap a[@rel=showooitab]').click(function() {
        showOOITab($(this).text(), this.id.replace(/-link$/,''));
        return false;
      });
      $('#longdomap a[@rel=showobject]').click(function() {
        selectMapTab(this.id.replace(/-link$/,''));
        return false;
      });
      $("a[@href*='/login']").click(function(){
        jQuery(this).login_ajax_content();
        return false;
      });
      $("#longdomap a:not([@rel^=show],[@href^=#],[@rel=showmap_ooitag],[@href^=javascript],[@href*='/login'])").attr({ target: "_blank" });
      
      if(browser!='IE' || (browser=='IE' && version>7)) gapi.plusone.go();
      if((browser!='IE' && browser!='Safari') || (browser=='IE' && version>6)) {
        FB.XFBML.parse();
      }
      else {
        $("#fb-comment-header").css("display", "none");
        $("#fb-comment").css("display", "none");
      }
    }
	});     
  
  if($.cookie("longdotab_id_path_tab") && $.cookie("longdotab_title_tab")) { // open selected tab when login by ajax (set cookie @ longdo-jquery.js) 
    var title_tab = $.cookie("longdotab_title_tab");
    var title_id = $.cookie("longdotab_id_path_tab");
    $.cookie("longdotab_id_path_tab", null);
    $.cookie("longdotab_title_tab", null);
    setTimeout(function() {showOOITab(title_tab, title_id);}, 500);
  }
  
  $("#longdotab").css("display","block");
  mmmap_client_init();
  
  showRecentDiv();
  
  resizeTab();
  $("input#searchfor").focus();
  $("input#searchfor").select();
});

function showOOITab(title, id, hash) {
  var id_path = id;
  id = id.replace(/\//g, "_");
  if($("#longdotab a[href^=#"+id+"-]").length > 0) {
    var tabindex = $('#longdotab ul li span a').index($("a[href^='#"+id+"-']"));
    $tabs.tabs('select', tabindex);
    
    var panel_id = $("a[href^='#"+id+"-']").attr('href');
    if(typeof hash != 'undefined')  {
      slideToHash(panel_id, hash);
    }
  }
  else {
    checkloadjscssfile("/themes/longdo/style-ooi.css", "css");

  	$tabs.tabs("option", "idPrefix", id+'-');
//     $tabs.tabs("spinner", "Loading...");
    $tabs.bind("tabsload", function(event, ui) {
      $("#comment-controls").remove();      
    });
      
//     label = title.length > 20 ? title.substring(0,18) + "..." : title;
//     $tabs.tabs('label', $tabs.tabs('option', 'selected'), label);

    $tabs.bind("tabsshow", function(event, ui) {
      if(hash && typeof hash != 'undefined')  {
        slideToHash(ui.panel.id, hash);
        hash = false;
      }
    });
    
    $tabs.tabs("add","/p/"+id_path+"/tab", title);
  }
}

function slideToHash(id, hash) {
  if(! /^#/.test(id)) id = "#"+id; 
  if(! /^#/.test(hash)) hash = "#"+hash;
  
  if($(hash).length>0 && $(id).length>0 ) {
    var divOffset = $(id).scrollTop();
    var hashOffset = $(hash).offset().top;
    var hashScroll = divOffset + hashOffset - 170;        
    $(id).animate({ 'scrollTop': hashScroll }, 'slow');
  }
}

function selectTab(index) {
  $tabs.tabs('select', index);
}
function selectMapTab(ooiid) {
  selectTab(0);
  if(typeof(ooiid) != 'undefined' && (/^(A|G|M|H)/.test(ooiid)) ) {
    mmmap.showObject(ooiid);
  }
}

function resizeTab() {
  var pageheaderH = $("#pageheader") ? $("#pageheader").height() : 0;
  var menuH = $("#menu_area") ? $("#menu_area").height() : 0;
  var tabheaderH = $("ul#tablist") ? $("ul#tablist").height() : 0;
  var tab_content_height = wh - pageheaderH - menuH - tabheaderH - (browser=='IE' ? 8 : 23);
  
  var rightpanelW = $("#right_panel") ? $("#right_panel").width() : 0;
  var tab_content_width = ww - rightpanelW - (browser=='IE' ? 4 : 6);
  
  if(tab_content_height > 0) $("#longdotab .ui-tabs-panel").css( {height:tab_content_height+"px"});
  if(tab_content_width > 0) $("#longdotab").css( {width:tab_content_width+"px"});
}

