/**
 * Aris April 2010
 * I don't want Weebly's fly-out menus, so this is the minimum JavaScript needed to prevent that.
 */
 
(function() {
	
	var moreItemHTML;
	var activeLiId;
	var currentPageId;
    var stylePrefix = window.STYLE_PREFIX || 'weebly';
	
	// called from a published page
	window.initPublishedFlyoutMenus = function(topLevelSummary, cpid, moreItemHTML, aLiId, isPreview) {
		currentPageId = cpid;
		
		if (topLevelSummary.length > 0) {
			var go = function() {
				activeLiId = aLiId;
				var container = document.createElement('div');
				container.id = stylePrefix+'-menus';
				$(document.body).insert(container);
				var firstItem = navElm(topLevelSummary[0].id);
				if (firstItem) {
					window.navFlyoutMenu = new FlyoutMenu(firstItem.up(), {
						relocate: container,
						aLiId: aLiId,
						slideDuration: 0.0001,
						delay: 0.0001
					});
					
					// We won't use "More..." so no need condenseNav
					//condenseNav(topLevelSummary, moreItemHTML);
				}
			}
			if (isPreview) {
				go(); // css has been written in html <style> tag, no need to check if loaded
			}else{
				whenThemeCSSLoaded(go);
			}
		}
	};
	
	function navElm(id) { // todo: rename to getHandle()
		var elm = $('pg'+id);
		if (elm) return elm;
		if (activeLiId) return $(activeLiId);
	}
	
	/************************** helpers for theme-css-loaded detection ***********************/
	
	function isThemeCSSLoaded() {
		for (var i=0; i<document.styleSheets.length; i++) {
			try {
				if (document.styleSheets[i].title == stylePrefix+'-theme-css') {
					var sheet = document.styleSheets[i];
					var rules = sheet.cssRules || sheet.rules;
					return rules && rules.length > 0;
				}
			}
			catch (err) {}
		}
		return false;
	}
	
	function whenThemeCSSLoaded(callback) {
		if (isThemeCSSLoaded()) {
			callback();
		}else{
			var iters = 0;
			var maxIters = 10;
			var intervalID = setInterval(function() {
				if (++iters > maxIters) {
					clearInterval(intervalID);
				}
				else if (isThemeCSSLoaded()) {
					clearInterval(intervalID);
					callback();
				}
			}, 200);
		}
	}

})();

