

// constants and paths

var chromeConst = {
	JsonDataPath: "http://disney.ru/api/minichrome-data.js",
	XMLDataPath: "http://disney.ru/api/minichrome-data.xml",
	CSSPath: "http://disney.ru/api/minichrome.css",
	FlashMovie: "http://disney.ru/api/minichrome.swf",
	SwfObjectJs: "http://disney.ru/api/swfobject.js",
	defaultWidth:750,
	minimumWidth:750,
	defaultHeight:34,
	flashVersion:"8",
	defaultBgColor:"#1b3694"
}


//////////////////////////////////////////////////////////////////////////////////
// Utility functions for handling DOM events
function chrome_addEvent(obj, evType, fn){
   if (obj.addEventListener){
      obj.addEventListener(evType, fn, true);
      return true;
   } else if (obj.attachEvent){
      var r = obj.attachEvent("on"+evType, fn);
      return r;
   } else {
      return false;
   }
}



function chrome_Delegate(callerObj,func) {
	var _defaultArgs = [];
	if (arguments.length>2) {
		_defaultArgs= [];
		for (var i=2;i<arguments.length;i++) {
			_defaultArgs.push(arguments[i]);
		}
	}
	return function() {
		var argumentsToUse = [];
		for (var i=0;i<_defaultArgs.length;i++) {
			argumentsToUse.push(_defaultArgs[i]);
		}
		for (var i=0;i<arguments.length;i++) {
			argumentsToUse.push(arguments[i]);
		}
		return func.apply(callerObj,argumentsToUse);
	}
}
////////////////////////////////////////////////////////////////////////////////////
// Utility function for using URLs, downloading JS scripts , CSS files

function chrome_checkSSL(url) {
	if ((document.location.protocol=="http:") && (url.indexOf("https:")==0)) {
		url="http://"+url.substring(8,url.length);
	}
	if ((document.location.protocol=="https:") && (url.indexOf("http:")==0)) {
		url="https://"+url.substring(7,url.length);
	}
	return url;
}

function chrome_LoadCSS(url) {
		document.write('<link href="'+chrome_checkSSL(url)+'" type="text/css" rel="stylesheet" media="screen" />');
	
}

function chrome_LoadJS(url) {
		document.write('<script language="JavaScript" src="'+chrome_checkSSL(url)+'" type="text/javascript"></script>');
}

//////////////////////////////////////////////////////////////////////////////////
// Utility functions for changing DOM object styles (and reverting to the original Classes)
function chrome_addStyle(element,newStyle) 
{
	if(null != element)
	{
		if (element.originalClass==null || element.originalClass.length==0) {
			if (element.className.length>0) {
				element.originalClass=element.className;
			} else {
				element.originalClass=" ";
			}
			
		}
		if ((element.originalClass.length>0) && (element.originalClass != " ") ) {
			element.className = element.originalClass+" "+newStyle;
		} else {
			element.className = newStyle;
		}
	}
}

function chrome_revertToOriginalStyle(element) {
	if (element != null && null != element.originalClass && element.originalClass.length>0) {
		element.className =element.originalClass;
	}
}
////////////////////////////////////////////////////////////////////////////////////



function MiniChrome() {
	
	// Public Variables
	this.UseFlash = true;
	this.Width = chromeConst.defaultWidth;
	this.BgColor = chromeConst.defaultBgColor;
	this.MenuIdSuffix = "";
	this.DataPath = null;
	this.fontSize = "1em";
	// private variables
	this._RenderHelper = null;
	// public functions 
	this.write = function(containerElementID) {
		if (isNaN(this.Width)) {
			throw "MiniChrome.Width must be a number";
		}
		if (this.BgColor == null) {
			this.BgColor = chromeConst.defaultBgColor;
		}
		// clip widths
		if (this.Width<chromeConst.minimumWidth) {
			this.Width=chromeConst.minimumWidth;
		}
		var containerElement = document.getElementById(containerElementID);
		if (containerElement == null) {
			throw "Could not render minichrome - could not find element "+containerElementID;
		}
		containerElement.style.display="block";
		containerElement.style.backgroundColor=this.BgColor;
		containerElement.style.width=this.Width+"px";
		containerElement.style.height=chromeConst.defaultHeight+"px";
		containerElement.innerHTML="&nbsp;";
		this.RenderHelper = this._CreateRenderHelper(containerElement);
		this.RenderHelper.Init();
	}
	// private functions
	
	
	// create a helper object to render the menu
	this._CreateRenderHelper = function(containerElement) {
		
		if (this.UseFlash) {
				// default data paths
			if (this.DataPath == null) {
				this.DataPath=chromeConst.XMLDataPath;
			}
			this.RenderHelper = new FlashChromeBuilder(this,containerElement);
		} else {
				// default data paths
			if (this.DataPath == null) {
				this.DataPath=chromeConst.JsonDataPath;
			}
			this.RenderHelper = new HtmlMinichromeBuilder(this,containerElement);
		}
		return this.RenderHelper;
	}
	
	
}

// call back when the JSON data is downloaded
// HtmlMinichromeBuilder.DataReady overrides this method
function minichromeDataLoaded(minichromeData) {
}

//This class looks after rendering the HTML version of the minichrome
function HtmlMinichromeBuilder(minichromeObject, containerElement) {

	this.minichrome = minichromeObject;
	this.containerElement = containerElement;
	///@TODO - this should use a static counter to generate a unique ID suffix 
	///so that when the menu is added to the DOM the child elements will have a unique id
	this.MenuIdSuffix = "";
	this.minichromeData = null;
	this.mainMenuContentWidth = -1;
	this.mainMenuUL=null;
	this.Init = function () {
		window.minichromeDataLoaded = chrome_Delegate(this,this.DataReady);
		chrome_LoadCSS(chromeConst.CSSPath);
		chrome_LoadJS(this.minichrome.DataPath);
	}
	
	this.DataReady = function (minichromeData) {
		this.minichromeData = minichromeData;
		this._BuildHTML();
		this.getChildElementById("navContainer").style.fontSize=this.minichrome.fontSize;
		this._InitMainMenu();
		
		this.logoWidth=this.getChildElementById("chromeLeft").offsetWidth;
		this.rightPanelWidth=this.getChildElementById("chromeRight").offsetWidth;
		this.availableMenuWidth= (this.minichrome.Width-(this.logoWidth+this.rightPanelWidth));
		//set width of nav container 
		this.getChildElementById("navContainer").style.width=this.availableMenuWidth+"px";
		this._FixUpHTMLMenu();
	}
	
	this._buildHyperLinkHtml = function(linkClass,currentItem) {
		if (currentItem==null) {
			return "";
		}
		var tag = "a";
		var url = null;
		try {
			url=currentItem.url;
		} catch(exception) {
			url=null;
		}
		if (url == null || url.length==0) {
			tag="span ";
		}
		var LinkHtml="<"+tag+" class=\""+linkClass+"\"";
		if (tag=="a") {
			LinkHtml+=" href=\""+url+"\" ";
		}
		LinkHtml+=">";
		LinkHtml+=currentItem.text;
		LinkHtml+="<span><span>"+this.minichromeData.htmlDescriptionLink.start+"</span>"+currentItem.text+"<span>"+this.minichromeData.htmlDescriptionLink.end+"</span></span>";
		LinkHtml+="</"+tag+">";
		return LinkHtml;
		
	}
	
	this._buildNav = function() {
		var navHTML="\t<ul class=\"chrome middle\" id=\""+this.createElementId("topUL")+"\" >\n";
				
		for (var i=0;i<this.minichromeData.menuItems.length;i++) {
			var item=this.minichromeData.menuItems[i];
			if (item!=null) {
				var liClass = "left";
				if (i==this.minichromeData.menuItems.length-1) {
					liClass += " last";
				}
				navHTML+="\t\t<li class=\""+liClass+"\">";
				navHTML+=this._buildHyperLinkHtml("main",item);
				// sub menu render
				if (this.minichromeData.hasASubMenu && item.submenu != null && item.submenu.length>0) {
					navHTML+="\n\t\t\t<ul>\n";
					for (var j=0;j<item.submenu.length;j++) {
						navHTML+="<li";
						if (j==item.submenu.length-1) {
							navHTML+=" class=\"last\"";
						}
						navHTML+=">";
						navHTML+=this._buildHyperLinkHtml("",item.submenu[j]);
						navHTML+="</li>";
	
					}
					navHTML+="\n\t\t\t</ul>\n";
	
				}
				navHTML+="</li>\n";
			}
		}
		navHTML+="\t</ul>\n"; // end of navContainer
		return navHTML;
	}
	
	this._BuildRightPanel = function() {
		var panelHTML="<div>"; 
		if (true || this.minichromeData.isSearchVisible) {
			panelHTML+="<ul id=\""+this.createElementId("searchpanel")+"\"><li><div>\n";
			
			panelHTML+="<form action=\""+this.minichromeData.searchURL+"\" class=\"chrome_search\" id=\""+this.createElementId("chrome_search")+"\" method=\"GET\" >";
			var sText = this.minichromeData.searchText;
			panelHTML+="<input id=\"chrome_search_input\" type=\"text\" class=\"text\" name=\"keywords\" value=\""+sText+"\" title=\""+sText+"\" />";
			panelHTML+="<input type=\"submit\" class=\"submit\" value=\""+this.minichromeData.searchButton+"\" />";				
			panelHTML+="</form>";
			panelHTML+="</div></li></ul>";
		
		} 
		panelHTML+="</div>";
		return panelHTML;
	}
	
	this._BuildStyles = function() {
		var pstr=this.minichromeData.itemPadding+"px";
		var pstr1=(this.minichromeData.itemPadding+1)+"px;";
		document.write("<style type=\"text/css\">");
		document.write("ul.chrome.middle li a {padding-left:"+pstr+" !important; padding-right:"+pstr+" !important;}\n");
		document.write("ul.chrome.middle li span.main {padding-left:"+pstr+" !important; padding-right:"+pstr+" !important;}\n");
		document.write("ul.chrome.middle li a span {left:"+pstr1+" }\n");
		document.write("ul.chrome.middle li span.main span {left:"+pstr1+" }\n");

		if (this.minichromeData.hasASubMenu) {
			document.write("ul.chrome.middle li {margin-top:3px;}");
		} else {
			document.write("ul.chrome.middle li {margin-top:9px;}");
		}
		document.write("</style>");
	}
	
	this._BuildHTML = function() {
		this._BuildStyles();
		this.containerElement.className = "chrome_container";
		this.containerElement.style.width = this.minichrome.Width+"px";
		this.containerElement.style.backgroundColor = this.minichrome.BgColor;
		
		var classNames = "chrome_container";
		var searchPanelClassNames = "chrome right";
		var bgColorStyle="style=\"background-color:"+this.minichrome.BgColor+"\"";
		if (!this.minichromeData.isSearchVisible) {
			classNames+=" nosearch";
		}
		if (this.minichromeData.hasASubMenu) {
			classNames+=" double";
			searchPanelClassNames+="double";
		}
		this.containerElement.className = classNames;
		
		var innerHTML = "";
		innerHTML+="<div class=\"chrome left\" id=\""+this.createElementId("chromeLeft")+"\" "+bgColorStyle+" >\n";
		innerHTML+="\t<a href=\""+this.minichromeData.homeLink+"\"><span class=\"disney\">Disney</span></a>\n";
		innerHTML+="</div>\n";
		innerHTML+="<div class=\"nav_container\" id=\""+this.createElementId("navContainer")+"\">\n";
		innerHTML+=this._buildNav();
		innerHTML+="</div>\n"; // end of navContainer*/
		
		innerHTML+="<div class=\""+searchPanelClassNames+"\" id=\""+this.createElementId("chromeRight")+"\" "+bgColorStyle+" >";
		innerHTML+=this._BuildRightPanel();
		innerHTML+="</div>\n"; // end of chromeRight
		
		//alert(this._buildNav());
		//alert(this._BuildRightPanel());
		//alert(innerHTML);
		
		this.containerElement.innerHTML = innerHTML;
		
		//alert(this.containerElement.innerHTML);// all of the HTML
		//alert(this.getChildElementById("chromeLeft").innerHTML);
		//alert(this.getChildElementById("navContainer").innerHTML);
		//alert(this.getChildElementById("chromeRight").innerHTML);
	}
	
	
	
	// private functions
	this._InitMainMenu = function() {
		this.mainMenuUL=this.getChildElementById("topUL");
		
		this.mainMenuUL.style.width="100%";
		this.mainMenuContentWidth = this.getUlContentWidth(this.mainMenuUL);
		if (this.mainMenuContentWidth>=0) {
			//this.mainMenuUL.style.marginLeft="0px";
		}
	}
	
	// tidy up the text positions of the HTML menu
	this._FixUpHTMLMenu = function() {
		this.mainMenuContentWidth = this.getUlContentWidth(this.mainMenuUL);

		// the style on this element already has margin left and right set to auto 
		// simply setting the width on the element centres the menu
		this.mainMenuUL.style.width=this.mainMenuContentWidth+"px";
		if (this.minichromeData.hasASubMenu) {
			//////////////////////////////////////////////////////////////////////////////
			// now check each submenu and make sure it isnt positioned out of the menu

			var current = this.mainMenuUL.firstChild;
			while (current != null) {
				if (current.nodeName.toLowerCase()=="li") {
					var subMenus = current.getElementsByTagName("ul");
					if (subMenus.length>0) {
						var subMenu = subMenus[0];
						this._initialiseSubMenu(current,subMenu);
					}
				}
				current = current.nextSibling;
			}
		}
		if (this.minichromeData.isSearchVisible) {
			this._setUpSearchForm();
		}
	}
	
	this._setUpSearchForm = function() {
		var textBox = this.getChildElementById("chrome_search_input");
		chrome_addEvent(textBox, "focus", chrome_Delegate(this,this.onSearchInputFocus,textBox));
		chrome_addEvent(textBox, "blur", chrome_Delegate(this,this.onSearchInputBlur,textBox));
		chrome_addEvent(textBox, "click", chrome_Delegate(this,this.onSearchInputFocus,textBox));
		var searchForm=this.getChildElementById("chrome_search");
		chrome_addEvent(searchForm, "submit", chrome_Delegate(this,this.onSearchFormSubmit,textBox));
		
	}
	
	
	
	this._initialiseSubMenu = function(parentLi,subMenu) {

		var alignmentClass=parentLi.className;
		// get the actual width of the content in the submenu
		var subMenuContentWidth = this.getUlContentWidth(subMenu);
		// actually set this width on the style so we get accurate results 
		// for offsetWidth
		subMenu.style.width=subMenuContentWidth+"px";
		var subMenuLeftPos = parentLi.offsetLeft+subMenu.offsetLeft-this.logoWidth;
		var subMenuRightPos = subMenuLeftPos+subMenuContentWidth;
		if (subMenuRightPos>this.availableMenuWidth) {
			subMenu.style.left = (this.availableMenuWidth-subMenuRightPos)+"px";
		}
		
		// events for ie6 rollover code
		chrome_addEvent(parentLi, "mouseover", chrome_Delegate(this,this.subMenuRollover,parentLi));
		chrome_addEvent(parentLi, "mouseout", chrome_Delegate(this,this.subMenuRollout,parentLi));
	
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////
	/// DOM event handlers
	
	// called by DOM events when a sub menu is rolled over
	this.subMenuRollover = function (parentLi) {
		chrome_addStyle(parentLi,"hover");
	}
	this.subMenuRollout = function (parentLi) {
		chrome_revertToOriginalStyle(parentLi);
	}
	
	this.onSearchInputFocus = function(inputBox) 
	{
		if (inputBox==null) 
		{
				return;
		}
		if (inputBox.value == inputBox.getAttribute("title")) 
		{
				inputBox.value="";
		}
	 }
	  
	this.onSearchInputBlur = function(inputBox) 
	 {	
		if (inputBox.value == "" && inputBox.getAttribute("title") != "") 
		{
			inputBox.value=inputBox.getAttribute("title");
		}
  	}
  	
  	this.onSearchFormSubmit = function(inputBox, eventParameter) {
		if (inputBox.value == inputBox.getAttribute("title") || inputBox.value =="") 
		{
			// no text entered
			// cancel the form submission
			if (typeof(eventParameter.cancelable) != 'undefined') {
					eventParameter.preventDefault();
					eventParameter.preventDefault();
			} 
			return false;
		}
  	}
	
	////////////////////////////////////////////////////////////////////////////////////////////
	// Utility functions
	
	
		
	// appends the suffix to the passed id to create a unique DOM element id.
	this.createElementId = function(elementID) {
		return elementID+this.MenuIdSuffix;
	}
	// returns a DOM element adding the MenuIdSuffix to the 	
	this.getChildElementById = function(elementID) {
		var id = this.createElementId(elementID);
		var element = document.getElementById(id);
		if (element == null) {
			throw "Could not find element "+id;
		}
		return element;
	}
	
	
	// Utility function which measures the width of an UL element
	this.getUlContentWidth = function(ulElement) {
		// loop through to find the menu items and find the leftmost and rightmost;
		var leftCoord = 0;
		var rightCoord = 0;
		var firstItem = true;
		var current = ulElement.firstChild;
		while (current != null) {
			if (current.nodeName.toLowerCase()=="li") {
				if (firstItem || current.offsetLeft<leftCoord) {
					leftCoord=current.offsetLeft;
				}
				var currentRightPos = current.offsetLeft+current.offsetWidth;
				if (firstItem || currentRightPos>rightCoord) {
					rightCoord=currentRightPos;
				}
				firstItem=false;
			}
			current = current.nextSibling;
		}
		if (!firstItem) {
			return (rightCoord-leftCoord);
		} else {
			return -1;
		}
	}
}

function FlashChromeBuilder(minichromeObject, containerElement) {

	this.minichrome = minichromeObject;
	this.containerElement = containerElement;
	chrome_LoadJS(chromeConst.SwfObjectJs);
	this.attemptedDrawCounter=0;
	this.Init = function () {
		this._DrawFlashMovie();
	}
	
	this._DrawFlashMovie = function() {
		// need to check that the swfobject javascript has loaded
		if (typeof(SWFObject) == "function") {
			var containerId = this.containerElement.id;
			var c = this.minichrome.BgColor;
			var w = this.minichrome.Width;
			var so = new SWFObject(chrome_checkSSL(chromeConst.FlashMovie), "menuid",  w, chromeConst.defaultHeight, chromeConst.flashVersion,c);
			so.addParam("allowScriptAccess", "always");
			so.addParam("scale", "noscale");
			so.addParam("wmode", "opaque");
			so.addVariable("configXML", chrome_checkSSL(this.minichrome.DataPath));
			so.addVariable("bgColour", c);
			so.write(containerId);
		} else {
			this.attemptedDrawCounter++;
			if (this.attemptedDrawCounter>100) {
				throw "swfobject was not loaded from "+chrome.SwfObjectJs+" so the chrome could not be rendered";
			}
			// itas not loaded to try again
			setTimeout(chrome_Delegate(this,this._DrawFlashMovie),100);
		}
	}
}
// this checks if an object called synergynav has been defined	
var storedSynergyNav = null;
try {
	storedSynergyNav=synergyNav
} catch(e3) {
	storedSynergyNav = null;
}
if (storedSynergyNav != null) {
	// if it has then render the chrome - 
	// this is for backwards compatability with the synergy nav	js include files
	var chrome = new MiniChrome();
	chrome.UseFlash = true;
	if (!isNaN(synergyNav.widthToUse)) {
		chrome.Width = storedSynergyNav.widthToUse;
	}
	if (synergyNav.pagecolour) {
		chrome.BgColor="#"+storedSynergyNav.pagecolour;
	}
	chrome.write(storedSynergyNav.divid);
}
