



// Event.observe(window,   'load' ,          setupAllTabs ); // Done by channel.js
   Event.observe(document, 'refresh:after',  setupAllTabs);
   Event.observe(document, 'refresh:before', disposeAllTabs);
   Event.observe(window,   'unload',         disposeAllTabs);


// This function is used to define if the browser supports the needed
// features
function hasSupport() {

	if (typeof hasSupport.support != "undefined")
		return hasSupport.support;
	
	var ie5 = /msie 5\.[0-9]/i.test( navigator.userAgent );
	
	hasSupport.support = ( typeof document.implementation != "undefined" &&
			document.implementation.hasFeature( "html", "1.0" ) || ie5 )

/* Original code			
	// IE5 has a serious DOM1 bug... Patch it!
	if ( ie5 ) {
		document._getElementsByTagName = document.getElementsByTagName;
		document.getElementsByTagName = function ( sTagName ) {
			if ( sTagName == "*" )
				return document.all;
			else
				return document._getElementsByTagName( sTagName );
		};
	}
*/

/* Patch for the bug with IE55 and NT4
 if ( ie55 ) {
  document._getElementsByTagName = document.getElementsByTagName;
  document.getElementsByTagName = function ( sTagName ) {
   if ( sTagName == "*" )
    return document.all;
   else
    return document._getElementsByTagName( sTagName );
  };
 }
*/

  // will cause bug when ie55 patched, so rewrite above
  if ( ie5 ) {  
    document._getAllElements = function () {
      return document.all;
    }
  } else {
    document._getAllElements = function () {
      return document.getElementsByTagName("*");
    }   
  }


	return hasSupport.support;
}

var groups = new Array() ;
var ieMac = navigator.appVersion.indexOf("MSIE") >= 0 && navigator.appVersion.indexOf("Mac") >= 0 ;

/* --------------------------------------------------------------- */
/*  WebFX TAB PANE                                                 */
/* --------------------------------------------------------------- */


///////////////////////////////////////////////////////////////////////////////////
// The constructor for tab panes
//
// el : HTMLElement		The html element used to represent the tab pane
// bUseCookie : Boolean	Optional. Default is true. Used to determine whether to us
//						persistance using cookies or not
//
function WebFXTabPane( el, bUseCookie ) {
	if ( !hasSupport() || el == null ) return;
	
	JcmsLogger.debug('TabPane', 'New tab pane: ', el);
  
	this.element = el;
	this.element.tabPane = this;
	var cn = this.element.className ;
	this.group = cn.length>8 ? cn.substring(9,cn.length) : null;
	if (this.group) {
		if (!groups[this.group]) groups[this.group] = new Array() ;
		groups[this.group][groups[this.group].length]=this.element.id ;
	}
	this.pages = [];
	this.selectedIndex = null;
	this.useCookie = false; // :OD:NOTE: bug-jcms-4.0-148 (Form with many tabs may logout the user).  bUseCookie != null ? bUseCookie : true;
	
	// Add class name tag to class name
	// this.element.className = this.classNameTag + " " + this.element.className;
	// FIXME: This class seems not to be used and Slow IE6
	
	// add tab row
	this.tabRow = document.createElement( "div" );
	this.tabRow.className = "tab-row";
	if (ieMac) this.tabRow.style.height = "1px";
	el.insertBefore( this.tabRow, el.firstChild );

	var tabIndex = 0;
	//if ( this.useCookie ) { // :OD:NOTE: bug-jcms-4.0-148 vs. force tab to open (setSelectedTab())
		tabIndex = Number( WebFXTabPane.getCookie( "webfxtab_" + this.element.id ) );
		if ( isNaN( tabIndex ))
			tabIndex = 0;
	//}
	this.selectedIndex = tabIndex;
	
	
	// loop through child nodes and add them
	var n;
	var cs = el.childNodes;
	for (var i = 0; i < cs.length; i++) {
		if (cs[i].nodeType == 1 && cs[i].className == "tab-page") {
			this.addTabPage( cs[i] );
		}
	}
	
	if (this.selectedIndex >= this.pages.length)
		this.setSelectedIndex(0);
}

WebFXTabPane.prototype.classNameTag = "dynamic-tab-pane-control";

WebFXTabPane.prototype.setSelectedIndex = function ( n ) {
	if (n >= this.pages.length)
		n = 0;
	if (this.selectedIndex != n) {
		if (this.selectedIndex != null && this.pages[ this.selectedIndex ] != null )
			this.pages[ this.selectedIndex ].hide();
		this.selectedIndex = n;
		this.pages[ this.selectedIndex ].show();

	  // Fire a tabpane:change event for the current tab being displayed		
	  WebFXTabPane.fireChange(this.pages[this.selectedIndex].element);
		
		if (this.useCookie){
			WebFXTabPane.setCookie( "webfxtab_" + this.element.id, n );	// session cookie
		}
	}
};
	
WebFXTabPane.prototype.getSelectedIndex = function () {
	return this.selectedIndex;
};
	
WebFXTabPane.prototype.addTabPage = function ( oElement ) {
	if ( !hasSupport() ) return;
	
	if ( oElement.tabPage == this )	// already added
		return oElement.tabPage;

	var n = this.pages.length;
	var tp = this.pages[n] = new WebFXTabPage( oElement, this, n );
	tp.tabPane = this;
	
	// move the tab out of the box
	this.tabRow.appendChild( tp.tab );
	
	if ( n == this.selectedIndex ){
		tp.tab.className = "tab_selected"; // tp.show();
	}	else {
		tp.hide();
  }
		
	return tp;
};
	
WebFXTabPane.prototype.dispose = function () {
	this.element.tabPane = null;
	this.element = null;		
	this.tabRow = null;
	
	for (var i = 0; i < this.pages.length; i++) {
		this.pages[i].dispose();
		this.pages[i] = null;
	}
	this.pages = null;
};



// Cookie handling
WebFXTabPane.setCookie = function ( sName, sValue, nDays ) {
	var expires = "";
	if ( nDays ) {
		var d = new Date();
		d.setTime( d.getTime() + nDays * 24 * 60 * 60 * 1000 );
		expires = "; expires=" + d.toGMTString();
	}

	document.cookie = sName + "=" + sValue + expires + "; path=/";
};

WebFXTabPane.getCookie = function (sName) {
	var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" );
	var res = re.exec( document.cookie );
	return res != null ? res[3] : null;
};

WebFXTabPane.removeCookie = function ( name ) {
	setCookie( name, "", -1 );
};


WebFXTabPane.fireChange = function ( tabPage ) {
  JcmsLogger.debug('TabPane', 'fireChange("', tabPage, '")');
  
  $(tabPage).fire('tabpane:change', { tabPage: $(tabPage).identify() });
  document.fire('tabpane:change', { tabPage: $(tabPage).identify() });
}

/* --------------------------------------------------------------- */
/*  WebFX TAB PAGE                                                 */
/* --------------------------------------------------------------- */


///////////////////////////////////////////////////////////////////////////////////
// The constructor for tab pages. This one should not be used.
// Use WebFXTabPage.addTabPage instead
//
// el : HTMLElement			The html element used to represent the tab pane
// tabPane : WebFXTabPane	The parent tab pane
// nindex :	Number			The index of the page in the parent pane page array
//
function WebFXTabPage( el, tabPane, nIndex ) {
	if ( !hasSupport() || el == null ) return;

  JcmsLogger.debug('TabPane', 'New tab page: ', el, ' for tab pane ', tabPane.element);

  // FIXME: Register a listener on all tag page in order to stop event bubbling of the custom 'tabpane:change' event
  Event.observe(el, 'tabpane:change', function(event) { Event.stop(event); }.bindAsEventListener(el));
  
	this.element = $(el);
	this.element.tabPage = this;
	this.index = nIndex;
	this.group = tabPane.group ;
	this.tab = el.fastChild('H2','tab');
	this.tab.tabPage = this;
	
	/*
	var cs = el.childNodes;
	for (var i = 0; i < cs.length; i++) {
		if (cs[i].nodeType == 1 && cs[i].className == "tab") {
			this.tab = cs[i];
			this.tab.tabPage = this;
			break;
		}
	}
	*/
	
	// insert a tag around content to support keyboard navigation	
	var a = document.createElement( "A" );
	this.aElement = a;
	a.href = "#";
	a.onclick = function () { return false; };
	a.hideFocus = true ;
	
	for (var child = this.tab.firstChild; child; ){
	  var next = child.nextSibling;
	  if (child.tagName != 'A'){
	    a.appendChild(child);
	  }
	  child = next;
	}
	
	//while ( this.tab.hasChildNodes() )
	//	a.appendChild( this.tab.firstChild );
	this.tab.appendChild( a );
	
	// hook up events, using DOM0
	var oThis = this;
	this.tab.onclick = function () { oThis.select(oThis.group); };
/* 
JALIOS: Commented to reduce jumper tab
	this.tab.onmouseover = function () { WebFXTabPage.tabOver( oThis ); };
	this.tab.onmouseout = function () { WebFXTabPage.tabOut( oThis ); }; 
*/
}

WebFXTabPage.prototype.show = function () {
	var el = this.tab;
	el.className = "tab_selected";
	
	if (Prototype.Browser.IE){
	  this.element.style.display  = ""; 
	  return; 
	}
	
  if (this.element._tabWidth){
    this.element.style.display  = ""; 
    return; 
  }
  this.element._tabWidth = true;
  
  var tr = $(el.parentNode);
  
  // var tWidth = tr.childElements().inject(0,function(acc, elm){ return acc + elm.getWidth() + 4; });
  // var tWidth = parseInt(tr.getStyle('width'));
  var tWidth = 0; tr.fastEach('H2',false, function(elm, idx){ tWidth += parseInt(elm.getStyle('width')) +18; });
  var tMax   = 600 > tWidth ? 600 : tWidth;
  
  var eWidth = parseInt(this.element.getStyle('width')); 
  var eMax   = !eWidth || tMax > eWidth ? tMax : eWidth;
  
  this.element.style.minWidth = tMax+"px";  
  this.element.style.display  = "";
  this.element.style.width    = eMax+"px";
};

WebFXTabPage.prototype.hide = function () {
	var el = this.tab;
	el.className = "tab";

	this.element.style.display = "none";
};
	
WebFXTabPage.prototype.select = function (group) {
	if (group) {
		var g=groups[group];
		for(var i=0 ; i<g.length ; i++) {
			var el = document.getElementById(g[i]) ;
			if (el) {
				if (this.index<el.tabPane.pages.length)
				  el.tabPane.setSelectedIndex( this.index ) ;
			}
		}
	}
	else this.tabPane.setSelectedIndex( this.index );
};


WebFXTabPage.prototype.dispose = function () {
	this.aElement.onclick = null;
	this.aElement = null;
	this.element.tabPage = null;
	this.tab.onclick = null;
	this.tab.onmouseover = null;
	this.tab.onmouseout = null;
	this.tab = null;
	this.tabPane = null;
	this.element = null;
};

WebFXTabPage.tabOver = function ( tabpage ) {
	var el = tabpage.tab;
	var s = el.className + " hover";
	s = s.replace(/ +/g, " ");
	el.className = s;
};

WebFXTabPage.tabOut = function ( tabpage ) {
	var el = tabpage.tab;
	var s = el.className;
	s = s.replace(/ hover/g, "");
	el.className = s;
};

// -----------------------------------------------------------------------------
//  INITIALISE
// -----------------------------------------------------------------------------

function disposeAllTabs(event) {
  if (!hasSupport()) return;
  
  // Retrieve fragment from event
  var fragment = $(document.body);
  if (event && event.memo && event.memo.wrapper){
    fragment = $(event.memo.wrapper);
    if (!fragment){ return; }
  }
  
  var tabPanes = $A([]);
  fragment.select('DIV.tab-pane').each(function(el) {
    if (el.tabPane){ tabPanes.push(el.tabPane); }
    el.tabPane = null;
  });
  
  tabPanes.invoke('dispose');
}

// This function initializes all uninitialized tab panes and tab pages
function setupAllTabs(event) {
	if (!hasSupport()) return;
	if (!event && document.TabPaneSetupAllTabsDone) { return; }
	if (!event) { document.TabPaneSetupAllTabsDone = true; }
  
  var t0 = new Date().getTime();
  
  // Retrieve fragment from event
  var fragment = $(document.body);
  if (event && event.memo && event.memo.wrapper){
    fragment = $(event.memo.wrapper);
    if (!fragment){ return; }
  }
  
  // Setup fragments
  var firstTabPage = setupTabFragment(fragment);
  
  // Fire change
  WebFXTabPane.fireChange(firstTabPage ? firstTabPage : document.body);
  
  var t1 = new Date().getTime();
  JcmsLogger.info('TabPane', 'Setup all tabs', ' in '+(t1-t0)+' ms');
}

function setupTabFragment(fragment) {
  var firstTabPage;
  // document.getElementsByTagName( "*" );
  // will cause bug when ie55 patched , so rewrite above

  fragment.select('DIV.tab-pane').reverse().each(function(el) {
    if (el.tabPane ) { return; }
    var pane = new WebFXTabPane( el );
    // track first tabpane to fire event
    if (!firstTabPage && pane.pages[0]) {
      firstTabPage = pane.pages[0].element;
    }
  });

  fragment.select('DIV.tab-page').reverse().each(function(el) {
    if (el.tabPage ) { return; }
    el.parentNode.tabPane.addTabPage( el );
  });

  fragment.select('H2.tab_selected').reverse().each(function(el) {
    el.tabPage.show();
  });
}

function setSelectedTab(tabPaneId, index) {
  document.cookie = "webfxtab_" + tabPaneId + "=" + index + "; path=/";
  
  var elt = $(tabPaneId); if (!elt){ return;  }
  var tabpane = elt.tabPane; if (!tabpane){ return;  }
  tabpane.setSelectedIndex(index);
}
