// Copyright 2005-2006 Stream2Peers,Inc.
// Dynamic Website UI (JavaScript)

/******** Dwui main class *********/
DynamicWebsiteUI = function(name) {
	this.name = name;
	this.menu;
	this.flash;
	this.tab;
	this.marquee;
	this.initMenu(this);
	this.initFlash(this);
}

DynamicWebsiteUI.prototype.initMenu = function(parentNode) {
	parentNode.menu = new Dwui_menu(parentNode);
}

DynamicWebsiteUI.prototype.initFlash = function(parentNode) {
	parentNode.flash = new Dwui_flash(parentNode);
}

DynamicWebsiteUI.prototype.initTab = function(parentNode) {
	var tabs = DT_getNodesByTagNameWithAttrValue(document, 'DIV', 'className', 'tab');
	if (tabs.length > 0) parentNode.tab = new Dwui_tab(parentNode, tabs);
}

DynamicWebsiteUI.prototype.initMarquee = function(parentNode) {
	var marquees = DT_getNodesByTagNameWithAttrValue(document, 'DIV', 'className', 'marquee');
	if (marquees.length > 0) parentNode.marquee = new Dwui_marquee(parentNode, marquees);
}


/******** Dwui menu package *********/
// Constructor
Dwui_menu = function(parent) {
	this.parent = parent;
}

// Add menu object
Dwui_menu.prototype.add = function(name, delay, showMenuFuncs, hideMenuFuncs) {
	var menuNode = DT_getNodesByTagNameWithAttrValue(document, 'DIV', 'className', name)[0];
	var id = menuNode.id;
	if (!id) return; // marquee object must have an ID!
	
	// init attributes
	this[id] = menuNode;
	this[id].parent = this;
	this[id].targetSubmenu;
	this[id].currentSubmenu = null;
	this[id].showTimer = null;
	this[id].hideTimer = null;
	this[id].menuDelay = delay;
	this[id].showMenuFuncs = showMenuFuncs.split(';');
	this[id].hideMenuFuncs = hideMenuFuncs.split(';');
	
	// init main menu
	this[id].main = DT_getNodesByTagNameWithAttrValue(this[id], 'UL', 'className', name + '-mainmenu')[0];
	this[id].main.parent = this[id];
	this[id].main.item = this[id].main.getElementsByTagName('A');
	for (var i = 0; i < this[id].main.item.length; i++) {
		this[id].main.item[i].parent = this[id].main;
		var mover = 'this.parent.parent.showWithTimer(' + i + ')';
		var mout = 'this.parent.parent.delShowTimer()';
		DT_setM2OHandlersOfNode(this[id].main.item[i], mover, mout);
	}

	// init sub menus
	this[id].subs = DT_getNodesByTagNameWithAttrValue(this[id], 'UL', 'className', name + '-submenu');
	for (var i = 0; i < this[id].subs.length; i++) {
		this[id].subs[i].parent = this[id];
		this.setPosition(id, i);
		this[id].subs[i].style.visibility = 'hidden';
	}
	
	// method for show submenu with a timer
	this[id].showWithTimer = function(subId) {
		this.targetSubmenu = subId;
		if (this.currentSubmenu != null) this.showTimer = window.setTimeout(this.parent.parent.name + ".menu." + id + ".showSubmenu()", this.menuDelay);
		else this.showSubmenu();
	}
	
	// method for delete menu show timer
	this[id].delShowTimer = function() {
		if (this.showTimer != null) {
			window.clearTimeout(this.showTimer);
			this.showTimer = null;
		}
	}
	
	// method for hide submenu with a timer
	this[id].hideWithTimer = function() {
		this.hideTimer = window.setTimeout(this.parent.parent.name + ".menu." + id + ".hideSubmenu()", this.menuDelay);
	}
	
	// method for delete menu hide timer
	this[id].delHideTimer = function() {
		if (this.hideTimer != null) {
			window.clearTimeout(this.hideTimer);
			this.hideTimer = null;
		}
	}
	
	// method for show submenu
	this[id].showSubmenu = function() {
		this.delShowTimer();
		if (this.currentSubmenu != null) this.hideSubmenu();
		if (this.subs[this.targetSubmenu]) this.subs[this.targetSubmenu].style.visibility = "visible";
		this.currentSubmenu = this.targetSubmenu;
		// run user defined functions
		for (var i = 0; i < this.showMenuFuncs.length; i++) eval(this.showMenuFuncs[i]);
	}
	
	// method for hide submenu
	this[id].hideSubmenu = function() {
		this.delHideTimer();
		if (this.subs[this.currentSubmenu]) {
			this.subs[this.currentSubmenu].style.visibility = 'hidden';
			this.currentSubmenu = null;
		}
		// run user defined functions
		for (var i = 0; i < this.hideMenuFuncs.length; i++) eval(this.hideMenuFuncs[i]);
	}
	
	this[id].onmouseover = this[id].delHideTimer;
	this[id].onmouseout = this[id].hideWithTimer;
}

// Set a submenu's position depends on mainmenu
Dwui_menu.prototype.setPosition = function(objId, subId) {
	var subMenuWidth = this[objId].subs[subId].offsetWidth;
	// computer the submenu's typical position
	var parentNode = this[objId].main.item[subId].parentNode;
	var posLeft = 0;
	while (parentNode != this[objId]) {
		posLeft += parentNode.offsetLeft;
		parentNode = parentNode.parentNode;
	}
	posLeft += this[objId].main.item[subId].offsetWidth / 2 -  subMenuWidth / 2;
	// adjust this position if it make submenu outside of menu object
	if (posLeft + subMenuWidth > this[objId].offsetWidth) posLeft = this[objId].offsetWidth - subMenuWidth;
	if (posLeft < 0) posLeft = 0;
	posLeft = Math.round(posLeft);
	// set submenu's new position
	this[objId].subs[subId].style.left = posLeft;
}


/******** Dwui flash package *********/
// Constructor
Dwui_flash = function(parent) {
	this.parent = parent;
	this.flashCanPlay = false;
	this.flashPluginDetection();
}

// Detecte flash plugin version
Dwui_flash.prototype.flashPluginDetection = function() {
	if (isIE && isWin && !isOpera) {
		document.writeln('<script language="VBScript"\>');
    document.writeln('on error resume next');
    document.writeln('flashCanPlay = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & requiredFlashVersion)))');
    document.writeln('</script\>');
		this.flashCanPlay = flashCanPlay;
	} else {  // NS and Opera
		var swVer;
		if (navigator.plugins && navigator.plugins.length > 0 && (navigator.plugins[swVer = "Shockwave Flash 2.0"] || navigator.plugins[swVer = "Shockwave Flash"])) {
			var words = navigator.plugins[swVer].description.split(" ");
			for (var i = 0; i < words.length; ++i) {
				if (isNaN(parseInt(words[i]))) continue;
				var pluginVersion = words[i];
			}
			this.flashCanPlay = (pluginVersion >= requiredFlashVersion);
		} else this.flashCanPlay = false;
	}
}

// Display error message when wrong version of flash player
Dwui_flash.prototype.enableNotice = function(className) {
	if (!this.flashCanPlay) {
		var nodes = DT_getNodesByTagNameWithAttrValue(document, 'DIV',  'className', className);
		for (var i = 0; i < nodes.length; i++) nodes[i].style.display = 'block';
	}
}

// Add flash object
Dwui_flash.prototype.add = function(flaPath, id, width, height, fscom, imgPath, imgLink) {
	if (this.flashCanPlay) {
		document.writeln('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '" height="' + height + '" id="' + id + '">'); 
		document.writeln('<param name="movie" value="' + flaPath + '">');
		document.writeln('<param name="allowScriptAccess" value="always">');
    document.writeln('<param name="quality" value="high">');
		document.writeln('<param name="menu" value="false">');
		document.writeln('<param name="bgcolor" value="#ffffff">');
    document.writeln('<embed src="' + flaPath + '" quality="high" menu="false" bgcolor="#ffffff" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '" id="' + id + '-embed" name="' + id + '" swLiveConnect="true"></embed>');
 		document.writeln('</object>');
		this.buildObject(id, fscom);
	}	else if (imgPath) {
		if (imgLink == 'default') var imgLink = 'http://www.macromedia.com/go/getflashplayer';
		if (imgLink) document.writeln('<a href="' + imgLink + '" target="_blank">');
		document.writeln('<img src="' + imgPath + '" width="' + width + '" height="' + height + '">');
		if (imgLink) document.writeln('</a>');
	}
}

// Build flash object
Dwui_flash.prototype.buildObject = function(id, fscom) {
	if (id) {
		this[id] = document.getElementById(id);
		this[id].embed = document.getElementById(id + '-embed');
		this[id].parent = this;
	}
	
	if (fscom) {
		// Enable fscommand in IE
		if (isIE && isWin) {
			document.writeln('<script language="VBScript"\>');
			document.writeln('On Error Resume Next');
			document.writeln('Sub ' + id + '_FSCommand(ByVal command, ByVal args)');
			document.writeln('Call ' + id + '_DoFSCommand(command, args)');
			document.writeln('End Sub');
			document.writeln('</script\>');
		}
		// Redirect all fscommand events to each flash object's own doFsCommand method
		document.write('<script language="javascript"\>');
		document.write('function ' + id + '_DoFSCommand(command, args) {');
		document.write(this.parent.name + '.flash.' + id + '.doFsCommand(command, args);\n}');
		document.write('</script\>');
		
		// Define the doFsCommand method for flash object
		this[id].doFsCommand = function(command, args) {
			var main, i, commandLine, targetPath = command.split('.');
			// Check if the target is exist
			try { main = eval(targetPath[0]) }
			catch (err) { main = document.getElementById(targetPath[0]) }
			// if target exist, do the command then do the command for target.embed if necessary
			if (main) for (i = 0, commandLine = "main"; i < 2; i++, commandLine = "main.embed") {
				if (i == 1 && !main.embed) break;
				for (var j = 1; j < targetPath.length; j++) commandLine += "." + targetPath[j];
				commandLine += " = args";
				eval(commandLine);
			}
		}
	}
}


/******** Dwui tab package *********/
// Constructor
Dwui_tab = function(parent, tabs) {
	this.parent = parent;
	for (var i = 0; i < tabs.length; i++) this.buildObject(tabs[i]);
}

// Build tab object
Dwui_tab.prototype.buildObject = function(tabNode) {
	var id = tabNode.id;
	if (!id) return; // tab object must have an ID!
	// init contents
	tabNode.parent = this;
	tabNode.content = DT_getNodesByTagNameWithAttrValue(tabNode, 'DIV', 'className', 'tab-content');
	// init labels
	var nav = DT_getNodesByTagNameWithAttrValue(tabNode, 'UL', 'className', 'tab-nav');
	tabNode.label = DT_getNodesByTagNameWithAttrValue(nav[0], 'A', 'className', 'tab-label');
	for (var i = 0; i < tabNode.label.length; i++) {
		var cLabel = tabNode.label[i];
		cLabel.target = i;
		cLabel.parent = tabNode;
		cLabel.state = 'off';
		cLabel.link = cLabel.getAttribute('href');
		cLabel.link = (cLabel.link == '') ? '#' : cLabel.link;
		cLabel.onclick = this.doTabEvent;
		cLabel.getElementsByTagName('SPAN')[0].onclick = null;
		// save content tag's orginal css class name
		var content = tabNode.content[i];
		content.css = content.className;
	}
	// switch default tab
	var def = tabNode.getAttribute('default');
	var defIdx = parseInt(def);
	defIdx = (defIdx && defIdx < tabNode.label.length) ? defIdx : 0;
	this.doSwitch(tabNode.label[defIdx]);
	
	this[id] = tabNode;
}

// Detect event target and verify its state
Dwui_tab.prototype.doTabEvent = function(evt) {
  var node = DT_getEventTarget(evt);
	if (node && node.parentNode.state) node = node.parentNode;
  if (node && node.state == 'off') node.parent.parent.doSwitch(node);
}

// Do tab switch action
Dwui_tab.prototype.doSwitch = function(tarNode) {
	for (var i = 0; i < tarNode.parent.label.length; i++) {
		var cLabel = tarNode.parent.label[i];
		var content = tarNode.parent.content[i];
		// change label's state
    if (cLabel == tarNode) {
      DT_removeAttrInNode(cLabel, 'href');
      cLabel.state = "on";
    } else if (cLabel.state == "on") {
			DT_setAttrInNode(cLabel, 'href', cLabel.link);
      cLabel.state = "off";
    }
		// change class name of tag 'LI'
		cLabel.parentNode.className = cLabel.state;
		// change class name of content 'DIV' tag
    content.className = content.css + ((content.css.length > 0) ? " " : "") + cLabel.state;
  }
}


/******** Dwui marquee package *********/
// Constructor
Dwui_marquee = function(parent, marquees) {
	this.parent = parent;
	for (var i = 0; i < marquees.length; i++) this.buildObject(marquees[i]);
}

// Build marquee object
Dwui_marquee.prototype.buildObject = function(marqueeNode) {
	var id = marqueeNode.id;
	if (!id) return; // marquee object must have an ID!
	
	// init contents
	this[id] = marqueeNode;
	this[id].parent = this;
	this[id].navUp = DT_getNodesByTagNameWithAttrValue(this[id], 'A', 'className', 'marquee-nav-up')[0];
	this[id].navUp.parent = this[id];
	this[id].navDown = DT_getNodesByTagNameWithAttrValue(this[id], 'A', 'className', 'marquee-nav-down')[0];
	this[id].navDown.parent = this[id];
	this[id].panel = DT_getNodesByTagNameWithAttrValue(this[id], 'DIV', 'className', 'marquee-panel')[0];  // marquee panel to scroll
	this[id].panel.parent = this[id];
	this[id].panel.contentHeight = parseInt(DT_removeAttrInNode(this[id], 'contentheight'));  // marquee content's height
	this[id].panel.show = parseInt(DT_removeAttrInNode(this[id], 'show'));  // # of marquee content will be showed
	this[id].panel.style.height = this[id].panel.contentHeight * this[id].panel.show - 1;  // set marquee's css height
	this[id].panel.delay = parseInt(DT_removeAttrInNode(this[id], 'delay'));  // time to wait before scrolling to the next marquee content
	this[id].panel.speed = parseInt(DT_removeAttrInNode(this[id], 'speed'));  // speed of scrolling
	this[id].panel.direction = 1;  // direction of scrolling (>0 : up, <0 : down)
	this[id].panel.auto = true;  // tell if marquee will be controlled automaticly
	this[id].panel.content = DT_getNodesByTagNameWithAttrValue(this[id].panel, 'DIV', 'className', 'marquee-content');  // marquee contents
	for (var i = 0; i < this[id].panel.content.length; i++) 
		this[id].panel.content[i].style.height = (isIE && isWin && !isOpera) ? this[id].panel.contentHeight : this[id].panel.contentHeight - 1;  // set marquee content's css height
	this[id].panel.innerHTML += this[id].panel.innerHTML;  // double the marquee contents
	
	// method for start marquee scrolling
	this[id].panel.startMarquee = function() {
		clearInterval(this.showInterval);
		this.showInterval = setInterval(this.parent.parent.parent.name + ".marquee." + id + ".panel.showNext()", this.delay + this.speed * this.contentHeight);
	}
	this[id].panel.onmouseout = this[id].panel.startMarquee;
	
	// method for stop marquee scrolling
	this[id].panel.stopMarquee = function() {
		clearInterval(this.showInterval);
	}
	this[id].panel.onmouseover = this[id].panel.stopMarquee;
	
	// method for scroll to the next marquee content
	this[id].panel.showNext = function() {
		clearInterval(this.scrollInterval);
		this.scrollInterval = setInterval(this.parent.parent.parent.name + ".marquee." + id + ".panel.scrollMarquee()", this.speed);
	}
	
	// method for scrolling
	this[id].panel.scrollMarquee = function() {
		var preScrollTop = this.scrollTop;
		this.scrollTop += this.direction;
		// if end of scroll content set a new start scroll position
		if (this.scrollTop == preScrollTop) {
			if (this.direction > 0) this.scrollTop = this.contentHeight * (this.content.length - this.show);
			else this.scrollTop = this.contentHeight * this.content.length;
			this.scrollTop += this.direction;
		}
		// if scroll over one marquee content stop scrolling
		if (this.scrollTop % this.contentHeight == 0 && this.auto) {
			clearInterval(this.scrollInterval);
			this.direction = 1;
		}
	}
	
	// method for manually control the marquee
	this[id].panel.startScroll = function() {
		this.auto = false;
		clearInterval(this.showInterval);
		this.showNext();
	}
	
	// method for stop manually control
	this[id].panel.stopScroll = function() {
		this.auto = true;
		this.startMarquee();
	}
	
	// mouse event handlers
	this[id].navUp.onmouseover = function() {
		this.parent.panel.direction = 1;
		this.parent.panel.startScroll();
	}
	this[id].navUp.onmouseout = function() {
		this.parent.panel.stopScroll();
	}
	this[id].navDown.onmouseover = function() {
		this.parent.panel.direction = -1;
		this.parent.panel.startScroll();
	}
	this[id].navDown.onmouseout = function() {
		this.parent.panel.stopScroll();
	}
	
	// start marquee scrolling
	this[id].panel.startMarquee();
}
