/* Pre-require: mootools-core.js */
WF = {
	container: null,
	Tab:null,
	loadingImg:null,
	isWebApp:location.search.toLowerCase().indexOf("mode=webapp")>=0,
	viewSource:false,
	source:null,
	scriptURL: function() {
		var scripts = $$("script");
		for (var i=0; i<scripts.length; i++) {
			var s = scripts[i];
			if (s.getAttribute("src")&&s.getAttribute("src").indexOf("iphone.js")>=0) {
				WF.scriptURL = function(){return this.getAttribute("src")}.bind(s);
				return s.getAttribute("src");
			}
		}
		return "";
	},

	/* state */
	map:null,
	titleTag:null,
	header:null,
	hasTab:false,
	footer:null,
	commands:null,
	activePageLink:"http://"+location.host+location.pathname,
	sourceDiv:null,
	warningDiv:null,
	warningCounter:0,
	bodyStyle:null,
	
	/* views stack */
	views: [],
	initIPhone:function() {
		if (window.top!==window.self) return; // do not load in iframe
		
		if (typeof MooTools == "undefined") {
			alert("Please load the mootools script first");
			return;
		}
		
		WF.source = document.body.innerHTML;		
		WF.container = $(document.body);
		if (Browser.Platform.ipod) {
			WF.container.setStyle("minHeight", "416px");
		}

		if (!Browser.Platform.ipod) {
			var div = new Element("div", {
				"styles": {
					"width":"320px",
					"height":WF.isWebApp?"416px":"460px",
					"left":"40px",
					"top":"154px",
					"position":"absolute",
					"overflow":"auto",
					"overflowX":"hidden"					
				}
			});
			
			if (document.body.hasAttribute("bgcolor")) {
				div.setStyle("backgroundColor",document.body.getAttribute("bgcolor"));
			}

			while (document.body.firstChild&&document.body.firstChild!==div) {
				div.appendChild(document.body.firstChild);
			}
			div.injectInside(document.body);
			WF.container = div;
			
			if (!WF.isWebApp)
				__gap = true;
			
			$(document.body).addClass("simulator");
			
			if (location.search.toLowerCase().indexOf("viewsource=yes")>=0) {
				WF.viewSource = true;
			}
		}
		
        // Search for wf_style in body
        var bodyStyle = {};
        var styles = document.body.getAttribute("wf_style");
        if (!styles) styles = "";
        styles = styles.split(" ");
        for (var i=0; i<styles.length; i++) {
            var s = styles[i].trim();
            if (!s) continue;
            s = s.split(":");
            if (s.length==1) {
                bodyStyle[s[0]] = "";
            }
            else {
                bodyStyle[s[0]] = s[1].trim();
            }
        }
        WF.bodyStyle=bodyStyle;
				
		var tabSelectedIndex = WF.initIPhoneView();
		
		if (!WF.isWebApp) {
			WF.fixScroll();	
		}
		
		// Load default Tab Page
		if (WF.Tab&&WF.Tab.items.length) {
			WF.loadTabContent(WF.Tab.items[tabSelectedIndex]);
		}
				
		setTimeout(WF.scrollToTop, 500);
		
		setTimeout(function() {
			if (typeof __gap!="undefined"&&__gap) {
				$(WF.container).addClass("gap");
			}
		}, 500);

		window.addEvent("unload", function(){
			if (typeof GUnload!="undefined")
				GUnload();
		});
	},
	
	scrollToTop: function() {
		if (Browser.Platform.ipod) {
			scrollTo(0, 1);	
		}
		else {
			WF.container.scrollTop = 0;	
		}				
	},
	
	initIPhoneView:function(div) {
		if (typeof div == "undefined") {
			div = null;
		}
		
		WF.removeCSSStyle(div);
		WF.removeJavascriptEvent(div);
		
		var tabSelectedIndex = 0;
		if (!div) {
			WF.buildHeader();
			tabSelectedIndex = WF.buildTab();
			WF.initIPhoneContent();
			WF.initBackButton();
			WF.clearFloat();
			WF.fixIE();
			WF.fixHeaderAndTab();
		}
		else {
			WF.initIPhoneContent(div);
		}

		if ($$("table[wf_style=fullscreen]").length||$$("body[wf_style~=fullscreen]").length) {
			WF.container.id = "normal";
			if (document.body.hasAttribute("bgcolor")) {
				WF.container.setStyle("backgroundColor", document.body.getAttribute("bgcolor"));
			}
			else {
				WF.container.setStyle("backgroundColor", "white");
			}
		}
		else {
			WF.container.setStyle("background", "");
			WF.container.id = "nothing";
		}
		
		
		// Fix the margin with id = nothing
		if (WF.container.id=="nothing") {
			var child = WF.container.firstChild;
			while(child) {
				if (child.nodeType === 1 &&
				    child.id!="header" &&
					child.id!="tab" &&
					child.id!="optionpanel" &&
					(!$(child).hasClass("wf_map")) &&
					child.id!="wf_popup") {
					$(child).addClass("margin");
				}
				child = child.nextSibling;
			}
		}
		
		if (div) return tabSelectedIndex; // no need to do anything else when do things recursively

		if (WF.viewSource) {
			WF.showViewSource();
		}
		else if (!WF.isWebApp&&!Browser.Platform.ipod){
			var sourceDiv = null;
			
			if (WF.sourceDiv)
			{
				sourceDiv = WF.sourceDiv;
				sourceDiv.innerHTML = "";
			}
			else 
		    {
	            sourceDiv = new Element("div", {
	                "styles": {
	                    "marginLeft":"400px"
	                }
	            }).inject(WF.container, "before");
		    }
            WF.sourceDiv = sourceDiv;
			
			var viewSourceBtn = new Element("button").injectInside(sourceDiv);
			viewSourceBtn.appendText("View source");
			viewSourceBtn.addEvent("click",
			    WF.showViewSource
			);
		}

		// Some commands
		if (WF.commands===null) return tabSelectedIndex;
		if (typeof WF.commands["removeTabInfo"]!="undefined") {
			var args = WF.commands["removeTabInfo"];
			var tabIndex = parseInt(args[0]);
			if (WF.Tab.items[tabIndex].infoDiv) {
				$(WF.Tab.items[tabIndex].infoDiv).dispose();
				WF.Tab.items[tabIndex].infoDiv = null;
			}
		}
		else if (typeof WF.commands["updateTabInfo"]!="undefined") {
			var args = WF.commands["removeTabInfo"];
			var tabIndex = parseInt(args[0]);
			var tabitem = WF.Tab.items[tabIndex];
			if (!tabitem.infoDiv) {
				var infoDiv = new Element("div", {"wf_type":"info"});
				infoDiv.injectInside(tabitem.div);
				tabitem.infoDiv = infoDiv;
			}
			tabitem.infoDiv.innerHTML = args[1];
		}
		
		return tabSelectedIndex;
	},
	
	removeCSSStyle: function(div) {
		if (!div) div = WF.container;
		var styledThings = $(div).getElements("*[style]");
		for (var i=0; i<styledThings.length; i++) {
			styledThings[i].setAttribute("style", "");
			if (i===0)
				WF.addWarning("css is not supported!");
		}
	},
	
	removeJavascriptEvent: function(div) {
		if (!div) div = WF.container;
		var styledThings = $(div).getElements("*[onclick]","*[onmouseover]","*[onmouseout]"
		                                      ,"*[onfocus]","*[onblur]","*[onkeyup]","*[onkeydown]","*[onkeypress]");
		for (var i=0; i<styledThings.length; i++) {
			var el = styledThings[i];
			if (el.hasAttribute("onclick")) el.removeAttribute("onclick");
			if (el.hasAttribute("onmouseover")) el.removeAttribute("onmouseover");
			if (el.hasAttribute("onmouseout")) el.removeAttribute("onmouseout");
			if (el.hasAttribute("onfocus")) el.removeAttribute("onfocus");
			if (el.hasAttribute("onblur")) el.removeAttribute("onblur");
			if (el.hasAttribute("onkeyup")) el.removeAttribute("onkeyup");
			if (el.hasAttribute("onkeydown")) el.removeAttribute("onkeydown");
			if (el.hasAttribute("onkeypress")) el.removeAttribute("onkeypress");
			if (i===0)
				WF.addWarning("on[click|mouseover|mouseout|focus|blur|keydown|keyup|keypress] javascript is not supported!");
		}
	},
	
	addWarning: function(str) {
		if (!WF.isWebApp&&!Browser.Platform.ipod&&!WF.warningDiv)
		{
			WF.warningDiv = new Element("div", {
					"class" : "warning",
	                "styles": {
	                    "marginLeft":"400px"
	                }
	            }).inject(WF.container, "before");
			WF.warningCounter = 0;
		}
		
		if (!WF.warningDiv) return;
		if (WF.warningCounter===0) {
			new Element("div", {"class":"heading"}).appendText("Warning:").injectInside(WF.warningDiv);
		}
		var lineDiv = new Element("div", {"class":"line"}).appendText((WF.warningCounter+1).toString()+". "+str).injectInside(WF.warningDiv);
		WF.warningCounter++;		
	},
	
	showViewSource: function() {
        var myAjax = new Request( {
            url: WF.activePageLink,
            method: "get"           
        });
		
        myAjax.addEvent('onSuccess',
            function(text, xml) {
                if (WF.sourceDiv) {
                    WF.sourceDiv.dispose();
                    WF.sourceDiv = null;
                }
                var sourceDiv = new Element("div", {
                    "styles": {
                        "marginLeft":"400px"
                    }
                }).inject(WF.container, "before");
                WF.sourceDiv = sourceDiv;
                
                if (WF.Tab) {
                    new Element("div", {"styles":{"fontWeight":"bold"}}).appendText("Tab source").injectInside(WF.sourceDiv);
                    var pre = new Element("pre", {
                        "name":"code",
                        "class":"html:nocontrols"
                    }).injectInside(WF.sourceDiv);
                    var t = WF.source.stripScripts();
                    t = t.replace(/<script[^>]*SyntaxHighlighter[^>]*>([\s\S]*?)<\/script>/gi,"");
                    t = t.replace(/<link[^>]*SyntaxHighlighter[^>]*>([\s\S]*?)<\/link>/gi,"");
                    pre.appendText(t);
                }
                
                new Element("div", {"styles":{"fontWeight":"bold"}}).appendText("Page source").injectInside(WF.sourceDiv);
                var pre = new Element("pre", {
                    "name":"code",
                    "class":"html:nocontrols"
                }).injectInside(WF.sourceDiv);
                text = text.replace(/<script[^>]*SyntaxHighlighter[^>]*>([\s\S]*?)<\/script>/gi,"");
                text = text.replace(/<link[^>]*SyntaxHighlighter[^>]*>([\s\S]*?)<\/link>/gi,"");
                pre.appendText(text);
                
                WF.syntaxHighlight();
				
				WF.viewSource = true;
            } 
        );
        myAjax.send();
	},
	
	fixIE: function() {
		if (!Browser.Engine.trident) return;
		var els = $$("*[wf_style=align_right]","*[wf_style=rounded]"
		             ,"*[wf_style=icon]","*[wf_style=prompt]"
					 ,"*[wf_style=center]","*[wf_style=alert]"
					 ,"*[wf_style=header]","*[wf_style=fullscreen]");
		for (var i=0; i<els.length; i++) {
			var el = els[i];
			var s = el.getAttribute("wf_style").split(" ");
			for (var j=0; j<s.length; j++) {
				el.addClass("wf_style_"+s[j]);				
			}
		} 
	},
	
	initIPhoneContent:function(div) {
		if (typeof div=="undefined") div=WF.container;
		
        WF.buildSearchBox(div);
        WF.buildHeaderBar(div);
		WF.buildFooterBar(div);
        WF.buildArrowLink(div);
        WF.buildEmbeddedToolbar(div);
        WF.buildNavLinks(div);
        WF.buildTable(div);
        WF.buildForms(div);
        WF.buildListImage(div);
		WF.buildiPhonePicker(div);
		WF.buildiFrame(div);
		
		if (div==WF.container) {
            WF.buildMaps();
		}
        WF.buildToolbar(div);
        WF.fixTableColors(div);
		
		if (typeof iPhoneInited!="undefined") {
			setTimeout(iPhoneInited, 1500);
		}
	},
	
	clearFloat:function() {/*
		var floatItems = $$("img[wf_style=icon]", "*[wf_style=prompt]");
		for (var i=0; i<floatItems.length; i++) {
			var floatItem = floatItems[i];
			var next = floatItem.nextSibling;
			while(next && (
			      (next.nodeType!==1) || 
			      (next.nodeType===1&&(next.tagName.toLowerCase()!="div"&&next.tagName.toLowerCase()!="span"))
				 ))
				next = next.nextSibling;
			if (next) {
				next.setAttribute("wf_style", "align_right");
			}
			//floatItems[i].nextSilbing.setAttribute("wf_style","align_right");
			new Element("div", {"styles":{"clear":"both"}}).injectInside(floatItems[i].parentNode);
		}*/
	},
	
	initBackButton:function(needRefresh) {
		if (WF.views.length&&(!$$("a[wf_style~=toolbar_back]","input[wf_style~=toolbar_back][type=submit]").length)) {
			var backButton = new Element("a", {
				id:"backButton",
				"class":"nav",
				"href":"#",
				"events": {
					"click": function(e) {
						new Event(e).stop();
						if (WF.loading) return;
						var level = 1;
						if (WF.commands && typeof WF.commands["back"]!="undefined") {
							level = parseInt(WF.commands["back"]);
							level = level>0?level:1;
						}
						
						var needRefresh = false;
						if (WF.commands && typeof WF.commands["refresh_parent"] != "undefined") {
							needRefresh = true;
						}
						
						for (var i=0; i<level; i++) {
							WF.popLastView();	
						}
						
						if (needRefresh) {
							WF.commands["refresh_parent"] = [];
							WF.loadLinkContent(WF.activePageLink, false);
						}
					}
				}
			});
			backButton.appendText("Back");
			backButton.injectInside($("header"));
            if (typeof WF.bodyStyle["toolbar_back_button_color"]!="undefined") {
                var toolbarButtonColor = WF.bodyStyle["toolbar_back_button_color"];
                backButton.setStyle("backgroundColor", toolbarButtonColor);
            }
		}
	},
	
	joinURL: function(url) {
		if (url.indexOf("http://")===0) { // Full Path
			return url;
		}
		
		if (url.indexOf("/")===0) { // Absolute Path
			return "http://" + location.host + url;
		}
		
		// Relative path
		return "http://" + location.host + WF.dirName(location.pathname) + url;
	},
	
	dirName: function(pathname) {
		if (pathname.indexOf("/")===pathname.length-1) return pathname;
		var s = pathname.split("/");
		return s.slice(0, s.length-1).join("/") + "/";
	},
	
	strService: function(str, viewsource) {
		if (typeof viewsource=="undefined") viewsource = true;
		if (str.indexOf("[wf:gps]")>=0||str.indexOf("%5Bwf:gps%5D")>=0) {
			str = str.replace("%5Bwf:gps%5D", "[wf:gps]");
			if (typeof google.loader.ClientLocation != "undefined") {
				str = str.replace("[wf:gps]", google.loader.ClientLocation.latitude + "," + google.loader.ClientLocation.longitude);
			}
			else {
				str = str.replace("[wf:gps]", "22.374629,114.115097");
			}
		}
		
        if (str.indexOf("[wf:device_id]")>=0||str.indexOf("%5Bwf:device_id%5D")>=0) {
            str = str.replace("%5Bwf:device_id%5D", "[wf:device_id]");
            str = str.replace("[wf:device_id]", "normal_desktop_browser");
        }
		
        if (str.indexOf("[wf:map_center]")>=0||str.indexOf("%5Bwf:map_center%5D")>=0) {
            str = str.replace("%5Bwf:map_center%5D", "[wf:map_center]");
            if (WF.map) {
				var center = WF.map.getCenter();
                str = str.replace("[wf:map_center]", center.lat().toFixed(6) + "," + center.lng().toFixed(6));
            }
            else {
                str = str.replace("[wf:map_center]", "0,0");
            }
        }
		
        if (str.indexOf("[wf:map_zoom]")>=0||str.indexOf("%5Bwf:map_zoom%5D")>=0) {
            str = str.replace("%5Bwf:map_zoom%5D", "[wf:map_zoom]");
            if (WF.map) {
                str = str.replace("[wf:map_zoom]", WF.map.getZoom().toString());
            }
            else {
                str = str.replace("[wf:map_zoom]", "-1");
            }
        }

		if (WF.viewSource&&viewsource) {
			if (str.indexOf("?")>=0) {
				str += "&viewsource=yes";				
			}
			else {
				str += "?viewsource=yes";
			}
		}

        if (WF.isWebApp&&viewsource) {
            if (str.indexOf("?")>=0) {
                str += "&mode=webapp";               
            }
            else {
                str += "?mode=webapp";
            }
        }
		
		return str;
	},
	
	fixHeaderAndTab: function() {
		if (Browser.Engine.gecko) {
			$("header").setStyle("height","24px");
		}
		
		$("header").addEvent("click", WF.scrollToTop);
		
		if (!Browser.Platform.ipod) {
			var tab = $("tab");
			if (tab) {
				tab.setStyle("width", "320px");	
			}
		}
		
		if ($("tab")&&(!WF.isWebApp)) {
			new Element("div", {"styles":{height:"44px"}}).injectInside(WF.container);
		}

        if (WF.footer&&(!WF.isWebApp)) {
            var totalHeight = WF.footerHeight();
			new Element("div", {"styles":{"height":totalHeight +"px"}}).injectInside(WF.container);
        }
	},
	
	oldPageYOffset: 0,
	fixScroll:function() {
		var oldOrientation = -1;
		
		setInterval(
			function() {
				var offset = window.pageYOffset;
				if (!Browser.Platform.ipod) {
					offset = WF.container.scrollTop;
				}
				var header = $("header");
				var topbar = $("topbar");
				if (!header) return;

				var orientation = window.orientation;
			
				if (WF.oldPageYOffset==offset&&oldOrientation==orientation) return;
				
				header.setStyle("top", offset + "px");
				if (topbar) topbar.setStyle("top", offset+"px");
				
				var gap = typeof __gap!="undefined"&&__gap;
				var heightOffset = 480-(gap?0:44)-20;
				switch (orientation) {
					
					// If we're horizontal
					case 90:
					case -90:
						heightOffset = 320-(gap?0:32)-20;
					
						// Set orient to landscape
						document.body.setAttribute("orient", "landscape");
						break;	
					
					// If we're vertical
					default:
						// Set orient to portrait
						document.body.setAttribute("orient", "portrait");
						break;
				}

				var tab = $("tab");
				if (tab) {
					tab.setStyle("top", (offset + heightOffset - tab.offsetHeight) + "px");	
				}
				
                var footerHeight = WF.footerHeight();
				if (WF.footer) {
					WF.footer.setStyle("height", footerHeight +"px");
					WF.footer.setStyle("top", (offset+heightOffset-footerHeight-(tab?tab.offsetHeight:0))+"px");
				}
				
				if ($("wf_popup")&&$("wf_popup").hasClass("popup_bottom")) {
					$("wf_popup").setStyle("top", (offset+heightOffset-footerHeight-(tab?tab.offsetHeight:0))-(WF.popupHeight())+"px");
				}

                if ($("wf_popup")&&$("wf_popup").hasClass("popup_center")) {
                    $("wf_popup").setStyle("top", (offset+(heightOffset/2)-(WF.popupHeight()/2))+"px");
                }
				
				/* Button Panel */
				WF.fixOptionPanel("optionpanel");
				
				WF.oldPageYOffset = offset;
				oldOrientation = orientation;
			}, 50
		);		
	},
	
	footerHeight: function() {
		if (!WF.footer) return 0;
        var child = WF.footer.firstChild;
		var totalHeight = 0;
        while(child) {
            if (child.offsetHeight) totalHeight += child.offsetHeight;
            child = child.nextSibling;
        }
		return totalHeight>160?160:totalHeight;
	},
	
	popupHeight: function() {
		if(!$("wf_popup")) return 0;
        var child = $("wf_popup").firstChild;
        var totalHeight = 0;
        while(child) {
            if (child.offsetHeight) totalHeight += child.offsetHeight;
            child = child.nextSibling;
        }
        return totalHeight>160?160:totalHeight;
	},
	
	fixOptionPanel: function(id) {
		var optionPanel = $(id);
		if (optionPanel && optionPanel.offsetHeight===0) {
			setTimeout(function(){
				WF.fixOptionPanel(id);
			}, 50);
			return;
		}
		else if (optionPanel===null) {
			return;
		}

		var offset = window.pageYOffset;
		if (!Browser.Platform.ipod) {
			offset = WF.container.scrollTop;
		}
		var orientation = window.orientation;
		
		var gap = typeof __gap!="undefined"&&__gap;
		var heightOffset = 480-(gap?0:44)-20;
		switch (orientation) {
			
			// If we're horizontal
			case 90:
			case -90:
				heightOffset = 320-(gap?0:32)-20;
			
				// Set orient to landscape
				document.body.setAttribute("orient", "landscape");
				break;	
			
			// If we're vertical
			default:
				// Set orient to portrait
				document.body.setAttribute("orient", "portrait");
				break;
		}
		
		optionPanel.setStyle("top", (offset + heightOffset - optionPanel.offsetHeight) + "px");
	},
	
	buildHeader:function() {
		var header = new Element("div", {id:"header"});
		if (!WF.isWebApp) {
			header.setStyle("position", "relative");
		}
		var h1 = new Element("h1").appendText(document.title).injectInside(header);
		if (WF.container.firstChild) {
			WF.container.insertBefore(header, WF.container.firstChild);
		}
		else {
			header.injectInside(WF.container);	
		}
		WF.titleTag = h1;
		WF.header = header;
		
		if (typeof WF.bodyStyle["toolbar_color"]!="undefined") {
			var toolbarColor = WF.bodyStyle["toolbar_color"];
			header.setStyle("background", toolbarColor + " url(" + WF.dirName(WF.scriptURL()) + "images/bgHeader.png" + ") repeat-x top");
		}
	},
	
	buildListImage:function(div) {
		/*var images = div.getElements("img[wf_type=item_img]");
		for (var i=0; i<images.length; i++) {
			var img = images[i];
			img.setStyles({
				"marginLeft":"-90px"	
			});
			$(img.parentNode).setStyle("paddingLeft", "100px")
		}*/
	},
	
	buildSearchBox:function(div) {
        var textInputs = div.getElements("input[type=text][wf_style~=search]");
        for (var j=0; j<textInputs.length; j++) {
            var textInput = textInputs[j];
            var div = new Element("div", {"styles":{"position":"relative"}}).inject(textInput, "before");
            div.addClass("toolbar");
            div.setStyle("padding", "8px 5px 0px 5px");
            if (Browser.Engine.gecko) {
                div.setStyle("height","36px");
            }
            textInput.injectInside(div);
            var cross = new Element("div", {"class":"search_cross"}).injectInside(div);
            cross.addEvent("click", WF.searchCrossClicked.bind(textInput));
			WF.grayTextInputBox(textInput, textInput.hasAttribute("title")?textInput.getAttribute("title"):"Search");
			
	        if (typeof WF.bodyStyle["toolbar_color"]!="undefined") {
	            var toolbarColor = WF.bodyStyle["toolbar_color"];
	            div.setStyle("background", toolbarColor + " url(" + WF.dirName(WF.scriptURL()) + "images/bgHeader.png" + ") repeat-x top");
	        }
        }
	},
	
	// make the text box has gray text if empty
	grayTextInputBox:function(textInput, text) {
		textInput.addEvent("focus",
		    function() {
				if (textInput.hasClass("input_gray")) {
					textInput.removeClass("input_gray");
					textInput.value="";
				}
			} 
		);
		
		var blur = function() {
            if (textInput.value=="") {
                textInput.addClass("input_gray");
                textInput.value = text;
            }
		};
		
		textInput.addEvent("blur", blur);
		blur();
	},
	
	/* Header Bar */
	buildHeaderBar:function(div) { // run after buildHeader
		var headerBarDivs = div.getElements("div[wf_style=header]");
		
		if (headerBarDivs.length) {
			var topbar = new Element("div", {id:"topbar"});
			
			topbar.inject(WF.header, "after");	

			if (!WF.isWebApp) {
				topbar.setStyle("position", "relative");
			}
			
			// only consider the first div
			headerBarDiv = headerBarDivs[0];
            if (headerBarDiv.hasAttribute("bgcolor")) {
                topbar.setStyle("backgroundColor", headerBarDiv.getAttribute("bgcolor"));
            }
						
			var child = headerBarDiv.firstChild;
			while (child) {
				var tmpChild = child.nextSibling;
				topbar.appendChild(child);
				child = tmpChild;
			}
			
			for (var i=0; i<headerBarDivs.length; i++) {
				headerBarDivs[i].setStyle("display", "none");
			}
			
			/*
			for (var i=0; i<searchForms.length; i++) {
				var searchForm = searchForms[i];
				topbar.appendChild(searchForm);
				
				var textInputs = searchForm.getElements("input[type=text]");
				for (var j=0; j<textInputs.length; j++) {
					var textInput = textInputs[j];
					var div = new Element("div", {"styles":{"position":"relative"}}).inject(textInput, "before");
					textInput.injectInside(div);
					var cross = new Element("div", {"class":"search_cross"}).injectInside(div);
					cross.addEvent("click", WF.searchCrossClicked.bind(textInput));
				}
			}
			*/
					
			// WF.header.setStyle("display", "none");
		}
	},
	
	/* Footer Bar */
	buildFooterBar: function(div){
		var footerBarDivs = div.getElements("div[wf_style=footer]");
		
		if (footerBarDivs.length) {
			var footerbar = new Element("div", {
				id: "footerbar"
			});
			
			footerbar.injectInside(WF.container);
			
            if (!WF.isWebApp) {
                footerbar.setStyle("position", "absolute");
            }
            
			// only consider the first div
			footerBarDiv = footerBarDivs[0];
			if (footerBarDiv.hasAttribute("bgcolor")) {
				footerbar.setStyle("backgroundColor", footerBarDiv.getAttribute("bgcolor"));
			}
			/*var child = footerBarDiv.firstChild;
			while (child) {
				var tmpChild = child.nextSibling;
				footerbar.appendChild(child);
				child = tmpChild;
			}*/
			footerBarDiv.inject(footerbar);
			
			var textInputs = footerbar.getElements("input[type=text]");
			for (var j = 0; j < textInputs.length; j++) {
				var textInput = textInputs[j];
				var div = new Element("div", {
					"styles": {
						"position": "relative"
					}
				}).inject(textInput, "before");
				textInput.injectInside(div);
				var cross = new Element("div", {
					"class": "search_cross"
				}).injectInside(div);
				cross.addEvent("click", WF.searchCrossClicked.bind(textInput));
			}
			
			for (var i = 0; i < footerBarDivs.length; i++) {
				if (footerBarDiv!==footerBarDivs[i])
				footerBarDivs[i].setStyle("display", "none");
			}
			
			if ($("tab")) {
				footerbar.setStyle("bottom", "44px");
			}
			
			WF.footer = footerbar;
		}
	},
	
	searchCrossClicked: function(e) {
		this.value = "";
		this.form.fireEvent("submit",e);
	},
	
	buildEmbeddedToolbar: function(div) {
        var toolbarBarDivs = div.getElements("div[wf_type=toolbar_embedded]");
        
        if (!toolbarBarDivs.length) return;
		
		for (var i=0; i<toolbarBarDivs.length; i++) {
			toolbarBarDivs[i].addClass("toolbar");
	        if (Browser.Engine.gecko) {
	            toolbarBarDivs[i].setStyle("height","34px");
	        }
            if (typeof WF.bodyStyle["toolbar_color"]!="undefined") {
                var toolbarColor = WF.bodyStyle["toolbar_color"];
                toolbarBarDivs[i].setStyle("background", toolbarColor + " url(" + WF.dirName(WF.scriptURL()) + "images/bgHeader.png" + ") repeat-x top");
            }

            if (typeof WF.bodyStyle["toolbar_button_color"]!="undefined") {
                var toolbarButtonColor = WF.bodyStyle["toolbar_button_color"];
	            var buttons = toolbarBarDivs[i].getElements("a");
	            for (var j=0; j<buttons.length; j++) {
					buttons[j].setStyle("backgroundColor", toolbarButtonColor);
	            }           
            }
		}
		
	},
	
	/* build search form */
	buildForms:function(div) {
		var forms = div.getElements("form");
		for (var i=0; i<forms.length; i++) {
			var f = forms[i];
			WF.bindForm(f);
			
			if (f.getAttribute("wf_type")=="searchbar") {
				continue;
			}
			
		}
		
		// Submit buttons
		var buttons = div.getElements("form input[type=submit]");
		for (var i=0; i<buttons.length; i++) {
			WF.buildSubmitButton(buttons[i]);
		}
		
		// Label with input
		var labeledInputs = div.getElements("label>input[type=text],label>input[type=password]");
		for (var i=0; i<labeledInputs.length; i++) {
			var input = labeledInputs[i];
		    var parent = input.parentNode;
			var node = $(parent.firstChild);
			while (node&&input!=node) {
				var tmpnode = $(node.nextSibling);
				parent.removeChild(node);
				node = tmpnode;				
			}
		}
		
		/* options
		var options = div.getElements("option");
		for (var i=0; i<options.length; i++) {
			options[i].value = WF.strService(options[i].value, false);
		}*/
		
		// popup select box
		var popupSelects = div.getElements("select[wf_style~=popup]");
		for (var i=0; i<popupSelects.length; i++) {
			popupSelects[i].setStyle("display", "none");
		}
	},
	
	buildSubmitButton:function(btn) {
		/*if (btn.form.parentNode.id!="topbar"&&
		   ((btn.getAttribute("wf_style")&&btn.getAttribute("wf_style").indexOf("toolbar")<0)||!btn.getAttribute("wf_style"))) {
			btn.setStyle("display", "none");
            var atag = new Element("a", {
                href:"#",
                "class":"button white",
                "events": {
                    click: function(e) {
                        new Event(e).preventDefault();
                        if (document.body.getAttribute("wf_type")=="no_back") {
				            for (var i=0; i<btn.form.elements.length; i++) {
				                var el = btn.form.elements[i];
				                if (el.tagName.toLowerCase()=="input" &&
				                    (el.type=="text"||el.type=="hidden")) {
				                    el.value = WF.strService(el.value, false);                  
				                }
				            }
                            btn.form.submit();              
                            return; 
                        }
                        $(btn.form).fireEvent("submit", e);
                    }
                }
            }).inject(btn, "after");
            atag.appendText(btn.value);
		}*/
		if (btn.parentNode.tagName.toLowerCase()=="div") {
			$(btn.parentNode).setStyle("text-align", "center");
		}
	},
	
	bindForm:function(f) {
		var popupSelectStatus = 0;
		var popupSelects = f.getElements("select[wf_style~=popup]");
		if (popupSelects.length) {
			$(document.body).addEvent("click", function(e){
				var optionPopup = $("wfPopupSelect");
				if (optionPopup) {
					optionPopup.dispose();
				}
				popupSelectStatus = 0;
			});
		}
		
		$(f).addEvent("submit", function(e) {
			new Event(e).preventDefault();
			
			if (popupSelectStatus<popupSelects.length) {
				var selectBox = popupSelects[popupSelectStatus];
				WF.showSelectPanel(selectBox,
				    function(selectedIndex) {
						selectBox.selectedIndex = selectedIndex;
						popupSelectStatus += 1;
						f.fireEvent("submit", e);
					}
				);
				return;
			}
			
			popupSelectStatus = 0;

            for (var i=0; i<this.elements.length; i++) {
                var el = this.elements[i];
                if (el.tagName.toLowerCase()=="input" &&
                    (el.type=="text"||el.type=="hidden")) {
                    el.value = WF.strService(el.value, false);                  
                }
				else if (el.tagName.toLowerCase()=="select") {
					for (var j=0; j<el.options.length; j++) {
                        el.options[j].value = WF.strService(el.options[j].value, false);
					}
				}
            }

			if (document.body.getAttribute("wf_type")=="no_back" || 
			    f.getAttribute("wf_style")=="newscreen" || 
				f.getAttribute("wf_style")=="navigation_reset") {
				this.submit();				
				return;	
			}
			
			var samelevel = true;
			if (this.getAttribute("wf_style")=="navigation_pushed") {
				samelevel = false;
			}

			var action = WF.joinURL(this.action);
			new iframe(this, 
				{
					onComplete:function() {
						// this.transport == iframe
						if (!samelevel) {
							if (Browser.Platform.ipod) {
								this.transport.dispose();	
							}
							// Push Current Status
							WF.pushCurrentView();
							if (Browser.Platform.ipod) {
								this.transport.injectInside(document.body);	
							}
						}
						WF.activePageLink = this.transport.contentWindow.location.toString();
						WF.initLinkedPage(this.transport);
						setTimeout(WF.scrollToTop, 500);
					}
				}
			);
		});
	},
	
	/* popup select */
	showSelectPanel: function(selectBox, feedback) {
        var optionPopup = $("wfPopupSelect");
        if (optionPopup) {
            optionPopup.dispose();
        }

        var optionPanel = new Element("div", {
            "class": "optionpanel",
			"id": "wfPopupSelect"
        }).injectInside(WF.container);
        var p = new Element("p").injectInside(optionPanel);
        
        for (var i=0; i<selectBox.options.length; i++) {
            var option = selectBox.options[i];

            var atag = new Element("a", {
                "class":"white button",
                "href":"#"
            }).injectInside(p);
			
			atag.appendText(option.innerHTML);
			WF.bindSelectOption(atag, i, feedback);
        }
		WF.fixOptionPanel("wfPopupSelect");
	},
	
	bindSelectOption: function(atag, i, feedback) {
		atag.addEvent("click",
		    function(e) {
				new Event(e).stop();
		        var optionPopup = $("wfPopupSelect");
		        if (optionPopup) {
		            optionPopup.dispose();
		        }
				feedback(i);
			} 
		);
	},
	
	/* Table */
	buildTable:function(div) {
		var tables = div.getElements("table");
		/* all default table is rounded */
		var warning = true;
		for (var i=0; i<tables.length; i++) {
			if (!tables[i].getAttribute("wf_style")) {
				tables[i].setAttribute("wf_style", "rounded");
			}
			
			if (warning) {
				if (tables[i].getElements("table").length) {
					WF.addWarning("nested table is not supported");
					warning = false;
				}
			}
		}
		
		/* play with the table to fit content */
		warning = true;
		for (var i=0; i<tables.length; i++) {
			if (warning) {
				if (tables[i].getElements("tr[align]").length) {
					WF.addWarning("align attribute in <tr> is not supported");
					warning = false;	
				}
			}
			
			WF.fitTableContent(tables[i]);
		}
		
		/* scroll through the table with title */
        for (var i=0; i<tables.length; i++) {
			var t = tables[i];
			if (t.getAttribute("wf_style")=="fullscreen"&&t.title!="") {
				var tr = new Element("tr", {"class":"wf_style_header"});
				var firstTr = t.getElements("tr")[0]; 
				var td = new Element("td", {"colSpan":firstTr.getElements("td").length}).appendText(t.title).injectInside(tr);
				tr.inject(firstTr, "before");								
			}
        }
		
		/* td with only one image should be no padding */
		/*if (div.id!="wf_popup") {
	        tds = div.getElements("td");
	        for (var i=0; i<tds.length; i++) {
	            var imgCount = 0;
	            var noPadding = true;
	            var td = tds[i];
	            var child = td.firstChild;
	            while(child) {
	                if (child.nodeType===3&&child.nodeValue&&child.nodeValue.trim()) { // have text
	                    noPadding = false;
	                    break;
	                }
	                else if (child.nodeType===1&&child.tagName.toLowerCase()=="img") {
	                    if (imgCount===0) {
	                        imgCount += 1;
	                    }
	                    else {
	                        noPadding = false;
	                        break;
	                    }
	                }
	                else if (child.nodeType===1) {
	                    noPadding = false;
	                    break;
	                }
	                child = child.nextSibling;
	            }
	            if (noPadding) {
	                td.setStyle("padding", "0px");
	            }
	        }
		}*/
	},
	
	fitTableContent:function(table) {
		var trs = $(table).getElements("tr");
		if (!trs.length) return;
		
		// get/calculate the fit order
		var noCols = 1;
		for (var i = 0; i < trs.length; i++) {
			if (trs[i].getElements("td").length>noCols) {
				noCols = trs[i].getElements("td").length;
			}
		} // assume no recursive table
		
		if (table.getAttribute("fit_order")) {
			var fit_order = table.getAttribute("fit_order").split(",");
			fit_order.each(parseInt);
		}
		else {
			var fit_order = [];
			for (var i=0; i<noCols; i++) {
				fit_order.push(i);
			}
		}
		
		// fit the content to the column
		// the last column in the order is omitted
		for (var i=0; i<fit_order.length-1; i++) {
			var width = WF.maxWidthCellInCol(trs, fit_order[i]);
			if (width===0) { // haven't rendered anything....
				setTimeout(WF.fitTableContent, 500, table);
				return;
			}
			
			var tds = null;
			for (var j=0; j<trs.length; j++) {
				tds = trs[j].getElements("td");
				if (tds.length===noCols) {
					break;
				}
			}
			if (tds===null) continue;
			tds[fit_order[i]].setStyle("width", width+"px");
		}
	},
	
	maxWidthCellInCol:function(trs, col) {
		var maxWidth = 0;
		for (var i=0; i<trs.length; i++) {
			var tds = trs[i].getElements("td");
			if (col>=tds.length) continue;
			if (tds[col].colSpan && parseInt(tds[col].colSpan)>1) continue;
			
			var width = WF.getCellContentWidth(tds[col]);
			if (width>maxWidth) {
				maxWidth = width;
			}
		}
		return maxWidth;
	},
	
	getCellContentWidth:function(cell) {
		// assume each child is fit in one row
		var maxWidth = 0;
		var child = cell.firstChild;
		while(child) {
			if (child.offsetWidth>maxWidth) {
				maxWidth = child.offsetWidth;
			}
			child = child.nextSibling;
		}
		return maxWidth;
	},
	
	/* Navigation Links */
	buildNavLinks:function(div) {
		var noBack = false;
		if (document.body.getAttribute("wf_type")=="no_back") {
			noBack = true;	
		}
		var links = div.getElements("a");
		for (var i=0; i<links.length; i++) {
			if(links[i].id=="backButton") continue;
			if (noBack) {
				links[i].href = WF.strService(links[i].href);
			}
			else {
				WF.bindNavLink(links[i]);
			}
		}
	},
	
	bindNavLink:function(atag) {
		var wfStyle = atag.getAttribute("wf_style");
		if (atag.getElements("img").length && (wfStyle && wfStyle.indexOf("button")>=0)) {
			atag.setAttribute("wf_style", wfStyle.replace("button", ""));
		}		

		if (document.body.getAttribute("wf_type")=="no_back" ||
		    (wfStyle && (wfStyle.indexOf("newscreen") >= 0||wfStyle.indexOf("navigation_reset") >= 0))) {
			atag.href = WF.strService(atag.href);
			return;	
		}
		
        var isSameDomain = true;
        if ((atag.href.indexOf("http://")===0&&atag.href.indexOf(location.host)<0)||  // outside domain
		     atag.href.endsWith(".mp4")||
			 atag.href.endsWith(".mp3")||
			 atag.href.endsWith(".mov")||
			 atag.href.endsWith(".doc")||
             atag.href.endsWith(".pdf")||
             atag.href.endsWith(".xls")||
			 (wfStyle&&wfStyle.indexOf("browser")>=0)){  
            isSameDomain = false;
        }

        if (Browser.Platform.ipod) {
            if (atag.href.indexOf("mailto:")===0) {
                atag.href = atag.href.replace("//", "");
				$(atag).addEvent("click", function(e) {
					new Event(e).stopPropagation();
				});
                return;
            }
        }

        
		$(atag).addEvent("click", function(e){
            var e = new Event(e);
            e.stop();
			
			if (this.hasAttribute("disabled")) {
				return;
			}
			
			var wfStyle = this.getAttribute("wf_style") ? this.getAttribute("wf_style") : "";
			if (wfStyle.indexOf("disabled")>=0) return;
			
            if (isSameDomain) {
				WF.loadLinkContent(this.href, (wfStyle.indexOf("noback") < 0&&wfStyle.indexOf("navigation_unchanged") < 0), wfStyle.indexOf("popup")>=0?(wfStyle.indexOf("popup_bottom")>=0?1:2):0);
                if ($("optionpanel")) {
                    $("optionpanel").setStyle("display", "none");
                }
			}
			else {
				window.open(this.href);
			}
		});
	},
	
	loadLinkContent:function(url, needPush, popupType) {
        if (Browser.Platform.ipod) {
            if (url.indexOf("tel:")===0) {
				window.open(url);
                return true;
            }
            else if (url.indexOf("mailto:")===0) {
                window.open(url.replace("//", ""));
                return true;
            }
            else if (url.indexOf("sms:")===0) {
                window.open(url.replace("//", ""));
                return true;
            }
        }

        if (url.indexOf("tel:")===0) {
            alert("phone call to "+url.replace("tel://",""));
            return;
        }
        else if (url.indexOf("mailto:")===0) {
            alert("mail to "+url.replace("mailto://",""));
            return;
        }
        else if (url.indexOf("sms:")===0) {
            alert("sms to "+url.replace("sms://",""));
            return;
        }
		
		if (WF.loading) return;
		if (!WF.loadingImg) WF.loadingImg = new Element("div", {id:"loading"});
		if (typeof needPush=="undefined") needPush=true;
		var myAjax = new Request( {
			url: WF.strService(url),
			async: true,
			method: "get"			
		});
		myAjax.addEvent('onSuccess', WF.loadLinkComplete.bind({
			url: WF.strService(url),
			needPush: needPush,
			popupType: popupType
		}));
		myAjax.addEvent('onFailure', WF.loadLinkError);
		 
		WF.loading = true;
		WF.container.appendChild(WF.loadingImg);
		return myAjax.send();
	},
	
	loadLinkComplete:function(text, xml) {
		WF.loadingImg.dispose();
		
		if (this.needPush&&!this.popupType) {
			// Push Current Status
			WF.pushCurrentView();
		}

		// use iframe
		var iframe = new Element("iframe", {
			"styles": {
				position:"absolute",
				left:"-10000px",
				top:"0px"
			}
		}).injectInside(document.body);

		if (Browser.Engine.webkit) {
			var doc = iframe.contentDocument;
		}
		else {
			var doc = iframe.contentWindow.document;
		}
		doc.open();
		doc.write(text.stripScripts(false));
		doc.close();
		WF.loading = false;
		
		if (this.popupType) {
			WF.initPopupPage(iframe, this.popupType);
		}
		else {
	        WF.activePageLink = WF.joinURL(this.url);
	        WF.initLinkedPage(iframe);
	        setTimeout(WF.scrollToTop, 500);
		}
	},

	initLinkedPage:function(iframe) {
		var title = iframe.contentWindow.document.title;
		var html = iframe.contentWindow.document.body.innerHTML;
		var wf_commands = {};
		
		// Propagate the back refresh to the prev level
		if (WF.commands && typeof WF.commands["refresh_parent"] != "undefined") {
			wf_commands["refresh_parent"] = [];
		}
		
		// Search for wf_style in body
		var bodyStyle = {};
		var styles = iframe.contentWindow.document.body.getAttribute("wf_style");
		if (!styles) styles = "";
		styles = styles.split(" ");
		for (var i=0; i<styles.length; i++) {
			var s = styles[i].trim();
			if (!s) continue;
			s = s.split(":");
			if (s.length==1) {
				bodyStyle[s[0]] = "";
			}
			else {
				bodyStyle[s[0]] = s[1].trim();
			}
		}
		WF.bodyStyle=bodyStyle;
		
		// Search for wf_action meta tags
		var metas = iframe.contentWindow.document.documentElement.getElementsByTagName("meta");
		var wfActions = [];
		for (var i=0; i<metas.length; i++) {
			var meta = metas[i];
			if (meta.getAttribute("name")=="wf_action") {
				wfActions.push(meta.getAttribute("content"));
			}
		}
		wfActions = wfActions.join(" ");
		
		if (wfActions) {
			// commands are space delimited
			var commands = wfActions.split(" ");
									
			// extract the command and arguments
			for (var i=0; i<commands.length; i++) {
				var command = commands[i];
				var tmp = command.split("(");
				var action = tmp[0];
				if (tmp.length>1) {
					var arguments = tmp[1].split(")")[0].split(",");	
				}
				else {
					var arguments = [];
				}
				wf_commands[action] = arguments;
			}
		}
		WF.commands = wf_commands;
		/*var isModal = false;
		if (iframe.contentWindow.document.body.getAttribute("wf_type")) {
			isModal = iframe.contentWindow.document.body.getAttribute("wf_type")=="modal";
		}*/
		$(iframe).dispose();
		// document.body.removeChild(iframe);
		
		var child = WF.container.firstChild;
		while(WF.container.firstChild) {
			WF.container.removeChild(WF.container.firstChild);
		}
		WF.container.innerHTML = html;
		WF.hasTab = WF.Tab; // && (!isModal);

		WF.initIPhoneView();
		
		WF.titleTag.innerHTML="";
		WF.titleTag.appendText(title);
	},
	
	initPopupPage:function(iframe, popupType) {
        var html = iframe.contentWindow.document.body.innerHTML;
		
		var popupDiv = $("wf_popup");
		if (!popupDiv) {
			popupDiv = new Element("div", {"id":"wf_popup"}).injectInside(WF.container);
			popupDiv.addEvent("click", function(e) {
				new Event(e).stop();
			});
			var maskDiv = new Element("div", {"styles":{"position":"absolute","left":"0px", "top":"0px", "width":"100%","height":"100%","zIndex":"9999"}}).injectInside(WF.container);
			maskDiv.addEvent("click", function(e) {
				popupDiv.dispose();
				maskDiv.dispose();
				this.removeEvent("click", arguments.callee);
			});
		}
		popupDiv.removeClass("popup_center");
		popupDiv.removeClass("popup_bottom");
		if (popupType===1) {
			popupDiv.addClass("popup_bottom");
			WF.oldPageYOffset = -1;
		}
		else {
			popupDiv.addClass("popup_center");
			WF.oldPageYOffset = -1;
		}
		
		popupDiv.innerHTML = html;
		WF.initIPhoneView(popupDiv);
	},
	
	loadLinkError:function() {
		WF.loadingImg.dispose();
		alert("Error loading");
		WF.loading = false;
	},
	
	pushCurrentView:function() {
		var div = new Element("div");
		if (WF.Tab&&WF.hasTab) {
			WF.Tab.div.dispose();
		}
		
		while(WF.container.firstChild) {
			div.appendChild(WF.container.firstChild);
		}
		
		// Push the states
		WF.views.push(
			{
				div: div,
				hasTab: WF.hasTab,
				titleTag: WF.titleTag,
				header: WF.header,
				footer: WF.footer,
				map: WF.map,
				activePageLink: WF.activePageLink,
				container_id: WF.container.id,
				commands: WF.commands,
				sourceDiv: WF.sourceDiv,
				warningDiv: WF.warningDiv,
				warningCounter: WF.warningCounter,
				bgcolor: WF.container.getStyle("backgroundColor"),
				bodyStyle: WF.bodyStyle
			}
		);
		
		WF.titleTag = null;
		WF.header = null;
		WF.footer = null;
		WF.map = null;
		WF.commands = null;
		if (WF.warningDiv) {
			WF.warningDiv.dispose();
			WF.warningDiv = null;			
		}
		if (WF.sourceDiv) {
			WF.sourceDiv.dispose();
			WF.sourceDiv = null;
		}
	},
	
	popLastView:function() {
		while(WF.container.firstChild) {
			WF.container.removeChild(WF.container.firstChild);
		}
		if (WF.sourceDiv) {
			WF.sourceDiv.dispose();
		}
		if (!WF.views.length) return;
		v = WF.views.pop();
		while(v.div.firstChild) {
		   WF.container.appendChild(v.div.firstChild);
		}
		
		// Pop the states
		WF.titleTag = v.titleTag;
		WF.map = v.map;
		WF.hasTab = v.hasTab;
		WF.header = v.header;
		WF.activePageLink = v.activePageLink;
		WF.container.id = v.container_id;
		WF.commands = v.commands;
		WF.sourceDiv = v.sourceDiv;
		WF.footer = v.footer;
		WF.bodyStyle = v.bodyStyle;
		WF.warningDiv = v.warningDiv;
		WF.warningCounter = v.warningCounter;
		
		if (v.bgcolor) {
			WF.container.setStyle("backgroundColor", v.bgcolor);
		}
		
		if (WF.hasTab&&WF.Tab) {
			WF.Tab.div.inject(WF.header, "after");
		}
		
		var height = parseInt($("header").getStyle("top"));
		if (Browser.Platform.ipod) {
			window.scrollTo(0, height);
		}
		else {
			WF.container.scrollTop = height;
		}
		
		if (WF.warningDiv) {
			WF.warningDiv.injectInside(document.body);
		}

		if (WF.sourceDiv) {
			WF.sourceDiv.injectInside(document.body);
		}
	},
	
	/* ToolBar */
	_totalWidth:function(btn1, btn2) {
		var w = 0;
		if (btn1.tagName.toLowerCase()=="input") {
			w += btn1.value.length;
		}
		else {
			w += btn1.innerHTML.length;
		}
		
        if (btn2.tagName.toLowerCase()=="input") {
            w += btn2.value.length;
        }
        else {
            w += btn2.innerHTML.length;
        }
		return w;
	},
	
	_getToolbarText:function(toolbarBtn) {
        var text = "";
        if (toolbarBtn.getAttribute("wf_icon")) {
            text += '<img src="' + toolbarBtn.getAttribute("wf_icon") + '"/>';
        }
        if (toolbarBtn.getAttribute("wf_style").indexOf("up_arrow") >= 0) 
            text = "▲";
        else 
            if (toolbarBtn.getAttribute("wf_style").indexOf("down_arrow") >= 0) 
                text = "▼";
            else 
                if (toolbarBtn.getAttribute("wf_style").indexOf("left_arrow") >= 0) 
                    text = "◀";
                else 
                    if (toolbarBtn.getAttribute("wf_style").indexOf("right_arrow") >= 0) 
                        text = "▶";
                    else 
                        if (toolbarBtn.tagName.toLowerCase() == "input") {
                            text += toolbarBtn.value;
                        }
                        else {
                            text += toolbarBtn.innerHTML;
                        }
        return text;
	},
	
	buildToolbar:function(div) {
		// Back button first
        var backButton = $$("a[wf_style~=toolbar_back]", "input[wf_style~=toolbar_back][type=submit]");
        if (backButton.length) {
            backButton = backButton[0];
			var text = WF._getToolbarText(backButton);
			if (backButton.tagName.toLowerCase()=="a") {
	            backButton.id = "backButton";
	            backButton.injectInside($("header"));
				backButton.innerHTML = text;
	            if (typeof WF.bodyStyle["toolbar_back_button_color"]!="undefined") {
	                var toolbarButtonColor = WF.bodyStyle["toolbar_back_button_color"];
	                backButton.setStyle("backgroundColor", toolbarButtonColor);
	            }           
			}
			else {
				var atag = new Element("a", {id:"backButton", "href":"#"}).injectInside($("header"));
                WF.bindToolbarForm(atag, backButton.form);
                atag.innerHTML = text;
	            if (typeof WF.bodyStyle["toolbar_back_button_color"]!="undefined") {
	                var toolbarButtonColor = WF.bodyStyle["toolbar_back_button_color"];
	                atag.setStyle("backgroundColor", toolbarButtonColor);
	            }           
				backButton.setStyle("display", "none");
			}
        }
		
		var upArrowButton = $$("a[wf_style~=toolbar_up_arrow],input[wf_style~=toolbar_up_arrow][type=submit]");
		var downArrowButton = $$("a[wf_style~=toolbar_down_arrow],input[wf_style~=toolbar_down_arrow][type=submit]");
		var leftArrowButton = $$("a[wf_style~=toolbar_left_arrow],input[wf_style~=toolbar_left_arrow][type=submit]");
		var rightArrowButton = $$("a[wf_style~=toolbar_right_arrow],input[wf_style~=toolbar_right_arrow][type=submit]");
        var toolbarBtns = div.getElements("a[wf_style~=toolbar],input[wf_style~=toolbar][type=submit]");
		
		var countToolbarBtns = toolbarBtns.length +
		                   (upArrowButton.length?1:0) +
						   (downArrowButton.length?1:0) +
						   (leftArrowButton.length?1:0) +
						   (rightArrowButton.length?1:0);
	    var countArrowToolbarBtns = (upArrowButton.length?1:0) +
	                           (downArrowButton.length?1:0) +
	                           (leftArrowButton.length?1:0) +
	                           (rightArrowButton.length?1:0);
 
		
        if (countToolbarBtns===0) return;
		
		if (countToolbarBtns==1) { // only one button
			var toolbarBtn = null;
			if (toolbarBtns.length) toolbarBtn = toolbarBtns[0];
			else if (upArrowButton.length) toolbarBtn = upArrowButton[0];
			else if (downArrowButton.length) toolbarBtn = downArrowButton[0];
			else if (leftArrowButton.length) toolbarBtn = leftArrowButton[0];
			else if (rightArrowButton.length) toolbarBtn = rightArrowButton[0];
			
            var atag = new Element("a", {
                "class":"nav Action",
                "href":"#",
                "wf_style":toolbarBtn.getAttribute("wf_style")
            }).injectInside($("header"));
			if (toolbarBtn.hasAttribute("disabled"))
			    atag.setAttribute("disabled", "disabled");
			
			var text = WF._getToolbarText(toolbarBtn);

			if (toolbarBtn.tagName.toLowerCase()=="input") {
				WF.bindToolbarForm(atag, toolbarBtn.form);
				atag.innerHTML = text;
			}
			else {
				atag.href = toolbarBtn.href;
				atag.innerHTML = text;
				WF.bindNavLink(atag);
			}
			
            if (typeof WF.bodyStyle["toolbar_button_color"]!="undefined") {
                var toolbarButtonColor = WF.bodyStyle["toolbar_button_color"];
                atag.setStyle("backgroundColor", toolbarButtonColor);
            }
						
			toolbarBtn.setStyle("display", "none");			
		}
		else if (countToolbarBtns==2 &&
		         countArrowToolbarBtns==2) {
		    var lrHolder = new Element("div", {"id":"lrButtonHolder"}).injectInside($("header"));
			
			var btns = [];
            if (upArrowButton.length) btns.push(upArrowButton[0]);
            if (downArrowButton.length) btns.push(downArrowButton[0]);
            if (leftArrowButton.length) btns.push(leftArrowButton[0]);
            if (rightArrowButton.length) btns.push(rightArrowButton[0]);
			
			for (var i = 1; i >= 0; i--) {
				var toolbarBtn = btns[i];
				
				var atag = new Element("a", {
					"class": "nav Action",
					"href": "#",
					"id": i==1?"rightButton":"leftButton",
					"wf_style": toolbarBtn.getAttribute("wf_style")
				}).injectInside(lrHolder);
	            if (toolbarBtn.hasAttribute("disabled"))
	                atag.setAttribute("disabled", "disabled");

	            var text = WF._getToolbarText(toolbarBtn);

	            if (toolbarBtn.tagName.toLowerCase()=="input") {
	                WF.bindToolbarForm(atag, toolbarBtn.form);
	                atag.innerHTML = text;
	            }
	            else {
	                atag.href = toolbarBtn.href;
	                atag.innerHTML = text;
	                WF.bindNavLink(atag);
	            }
				
	            if (typeof WF.bodyStyle["toolbar_button_color"]!="undefined") {
	                var toolbarButtonColor = WF.bodyStyle["toolbar_button_color"];
	                atag.setStyle("backgroundColor", toolbarButtonColor);
	            }
				
				toolbarBtn.setStyle("display", "none");
			}

			new Element("div", {"styles":{"clear":"both"}}).injectInside(lrHolder);
		}
		else if (countToolbarBtns){
            var btns = [];
            if (upArrowButton.length) btns.push(upArrowButton[0]);
            if (downArrowButton.length) btns.push(downArrowButton[0]);
            if (leftArrowButton.length) btns.push(leftArrowButton[0]);
            if (rightArrowButton.length) btns.push(rightArrowButton[0]);
			if (toolbarBtns.length) btns = btns.concat.apply(btns, toolbarBtns);
            
            var atag = new Element("a", {
                "class":"nav Action",
                "href":"#",
                "events":{
                    "click":function(e) {
                        new Event(e).preventDefault();
                        $("optionpanel").setStyle("display", "");
                        WF.fixOptionPanel("optionpanel");
                    }
                }
            }).injectInside($("header")).appendText("More");
            if (typeof WF.bodyStyle["toolbar_button_color"]!="undefined") {
                var toolbarButtonColor = WF.bodyStyle["toolbar_button_color"];
                atag.setStyle("backgroundColor", toolbarButtonColor);
            }
            
            var optionPanel = new Element("div", {
                id: "optionpanel",
                "styles":{display:"none"}               
            }).injectInside(WF.container);
            var p = new Element("p").injectInside(optionPanel);
            
            for (var i=0; i<btns.length; i++) {
                var toolbarBtn = btns[i];

                var atag = new Element("a", {
                    "class":"white button",
                    "href":"#"
                }).injectInside(p);
	            if (toolbarBtn.hasAttribute("disabled"))
	                atag.setAttribute("disabled", "disabled");
				
                var text = WF._getToolbarText(toolbarBtn);

                if (toolbarBtn.tagName.toLowerCase()=="input") {
                    WF.bindToolbarForm(atag, toolbarBtn.form);
                    atag.innerHTML = text;
                }
                else {
                    atag.href = toolbarBtn.href;
                    atag.innerHTML = text;
                    WF.bindNavLink(atag);
                }
				
				toolbarBtn.setStyle("display", "none"); 
            }
            
            var atag = new Element("a", {
                "class":"red button",
                "href":"#",
                "events":{
                    "click":function(e) {
                        new Event(e).preventDefault();
                        $("optionpanel").setStyle("display", "none");
                    }
                }
            }).injectInside(p).appendText("Hide me");			
		}
	},
	
	bindToolbarForm: function(atag, form) {
		atag.addEvent("click", 
			function(e) {
				new Event(e).preventDefault();
				if ($("optionpanel")) {
					$("optionpanel").setStyle("display", "none");
				}
				$(form).fireEvent("submit", e);				
			}
		);
	},
	
	/* Tab */
	buildTab:function() {
		var tabDivs = $$("div[wf_type=tabbar]");
		var selectedIndex = 0;
		if (tabDivs.length&&(!WF.Tab)) {
			// Only build one map
			var tabDiv = tabDivs[0];
			for (var i=1; i<tabDivs.length; i++) {
				$(tabDivs[i]).dispose();
			}
			
			var atabs = tabDiv.getElements("a");
			var tabitems = [];
			for (var i=0; i<atabs.length; i++) {
				var atab = atabs[i];
				var infos = atab.getElements("span[wf_type=info]");
				if (infos.length) {
					for (var j=0; j<infos.length; j++) infos[j].dispose();
				}
				
				var tabitem = {
					img: atab.getAttribute("wf_tab_img")?atab.getAttribute("wf_tab_img"):null,
					img_on: atab.getAttribute("wf_tab_img_active")?atab.getAttribute("wf_tab_img_active"):null,
					url: atab.href,
					title: atab.get('text'),
					info: null,
					infoDiv: null
				};
				
				var wfStyle = atab.getAttribute("wf_style");
				if (wfStyle && wfStyle.indexOf("selected")>=0) {
					selectedIndex = i;
				}

				if (infos.length) tabitem.info = infos[0].innerHTML;
				tabitems.push(tabitem);
			}
			
			tabDiv.inject(WF.header, "after");
			tabDiv.innerHTML = "";
			tabDiv.id = "tab";
			tabDiv.addClass("tab");
			tabDiv.addClass("tab_"+tabitems.length);
			
			if (!WF.isWebApp) {
				tabDiv.setStyle("position", "absolute");
			}
			
			for (var i=0; i<tabitems.length&&i<5; i++) {
				var tabitem = tabitems[i];
				var div = new Element("div", {
					"class": "tabitem",
					title: tabitem.title
				}).injectInside(tabDiv);
				
				var img = new Element("img", {
					src: tabitem.img,
					title: tabitem.title
				}).injectInside(div);
				
				var textDiv = new Element("div", {
					"class":"title"
				}).appendText(tabitem.title).injectInside(div);
				
				if (tabitem.info!==null) {
					var infoDiv = new Element("div", {"wf_type":"info"});
					infoDiv.appendText(tabitem.info);
					infoDiv.injectInside(div);
					tabitem.infoDiv = infoDiv;
				}
				
				WF.bindTabItem(div, tabitem);
				tabitem.imgtag = img;
				tabitem.div = div;
			}
			
			new Element("div", {
				"styles":{"clear":"both"}
			}).injectInside(tabDiv);
			
			new Element("div", {
				id: "content",
				"styles": {
					"marginBottom":"44px"
				}
			}).injectInside(WF.container);
						
			WF.Tab = {
				div: tabDiv,
				items: tabitems,
				active: null
			};
			
			WF.hasTab = true;
			
			if (tabitems.length>5) {
				alert("Some tabs are ignored.");
			}
			
		}
		else if (WF.Tab&&WF.hasTab) {
			WF.Tab.div.inject(WF.header, "after");
		}
		return selectedIndex;
	},
	
	bindTabItem:function(img, tabitem) {
		img.addEvent("click", function() {
			while(WF.views.length) { // Pop to the top 
				WF.popLastView();
			}
			WF.loadTabContent(tabitem);
		});
	},
	
	loadTabContent:function(tabitem) {
		if (WF.loading) return;
		if (WF.Tab.active===tabitem) return;
		if (!WF.loadingImg) WF.loadingImg = new Element("div", {id:"loading"});
		
		var myAjax = new Request( {
			url: WF.strService(tabitem.url),
			async: true,
			method: "get"			
		});
		myAjax.addEvent('onSuccess', WF.loadTabComplete.bind(tabitem));
		myAjax.addEvent('onFailure', WF.loadTabError);
		 
		WF.loading = true;
		return myAjax.send();
	},
	
	loadTabComplete:function(text, xml) {
		// use iframe
		var iframe = new Element("iframe", {
			"styles": {
				position:"absolute",
				left:"-10000px",
				top:"0px"
			}
		}).injectInside(document.body);
		if (Browser.Engine.webkit) {
			var doc = iframe.contentDocument;
		}
		else {
			var doc = iframe.contentWindow.document;
		}
		doc.open();
		doc.write(text.stripScripts(false));
		doc.close();
		WF.loadingImg.dispose();
		WF.loading = false;
		
		WF.activePageLink = WF.joinURL(WF.strService(this.url)); 
		WF.initLinkedPage(iframe);
		
		// highlight tab image
		var tabitem = this;
		tabitem.imgtag.src = tabitem.img_on;
		$(tabitem.imgtag.parentNode).addClass("on");
		if (WF.Tab.active&&WF.Tab.active!==tabitem) {
			WF.Tab.active.imgtag.src = WF.Tab.active.img;
			$(WF.Tab.active.imgtag.parentNode).removeClass("on");
		}
		WF.Tab.active = tabitem;

		setTimeout(WF.scrollToTop, 500);
	},
	/*
	initTabPage:function(iframe) {
		if ($("topbar")) {
			$("topbar").dispose();
			WF.header.setStyle("display","");
		}
		var actions = $$("div#header a.Action");
		for (var i=0; i<actions.length; i++) {
			actions[i].dispose();
		}
		var c = $("content");
		WF.titleTag.innerHTML="";
		WF.titleTag.appendText(iframe.contentWindow.document.title);
		c.innerHTML = iframe.contentWindow.document.body.innerHTML;
		WF.initIPhoneContent();
		document.body.removeChild(iframe);
	},*/
	
	loadTabError:function() {
		WF.loadingImg.dispose();
		alert("Error!");
		WF.loading = false;
	},
	
	/* Link in Item */
	buildArrowLink:function(div) {
		var trs = div.getElements("tr");
		for (var i=0; i<trs.length; i++) {
			var tr = trs[i];
			var els = tr.getElements("td");
			var count = 0;
			var link = null;
			
	        for (var j=0; j<els.length; j++) {
	            var el = els[j];
	            var atags = el.getElements("a");
	            var rootLinks = [];
	            for (var k=0; k<atags.length; k++) {
					var atag = atags[k];
					var wfStyle = atag.hasAttribute("wf_style")?atag.getAttribute("wf_style"):"";
					
	                if (atag.parentNode===el&&wfStyle.indexOf("button")<0&&wfStyle.indexOf("toolbar")<0) {
	                    rootLinks.push(atags[k]);
	                }
	            } 
	            
	            if (rootLinks.length===1) {
					count++;
					link = rootLinks[0];
	            }
	        }

            if (count===1) {
                var child = link;
                $(child).addClass("arrow");
                $(tr).addClass("arrow");
                WF.bindRowLink($(tr), child, child.href);
                if (!child.innerHTML.trim()) {
                    child.setStyle("display", "none");
                }
            }
		}
	},
	
	bindRowLink:function(tr, atag, url) {
        var wfStyle = atag.getAttribute("wf_style");
        if (document.body.getAttribute("wf_type")=="no_back" ||
            (wfStyle && (wfStyle.indexOf("newscreen") >= 0||wfStyle.indexOf("navigation_reset") >= 0))) {
            return; 
        }
		
		var isSameDomain = true;
        if ((url.indexOf("http://")===0&&url.indexOf(location.host)<0)||  // outside domain
             url.endsWith(".mp4")||
             url.endsWith(".mp3")||
             url.endsWith(".mov")||
             url.endsWith(".doc")||
             url.endsWith(".pdf")||
             url.endsWith(".xls")||
             (wfStyle&&wfStyle.indexOf("browser")>=0)){  
            isSameDomain = false;
        }
		
		
		$(tr).addEvent("click", function(e){
            var e = new Event(e);
            e.stop();
			if (isSameDomain) {
	            var wfStyle = atag.getAttribute("wf_style")?atag.getAttribute("wf_style"):"";
	            WF.loadLinkContent(url, wfStyle.indexOf("noback")<0, wfStyle.indexOf("popup")>=0);
			}
			else {
				window.open(url);
			}
		});
	},
	
	/* Map */
	buildMaps:function() {
		var mapDivs = $$("div[wf_type=map]");
		
		if (mapDivs.length) {
			GMap2 = google.maps.Map2;
			if (typeof GMap2 == "undefined" || typeof LabeledMarker == "undefined") {
				alert("Please import map javascript");
				return;
			}

			// Only build one map
			setTimeout(function() {
				WF.buildMap(mapDivs[0]);
				for (var i=1; i<mapDivs.length; i++) {
					$(mapDivs[i]).dispose();
				}
			},500);
			
			WF.header.setStyle("position", "relative");
			if (WF.Tab&&WF.Tab.div) {
				if (WF.isWebApp) {
					WF.Tab.div.setStyle("position", "relative");	
				}
				else {
					WF.Tab.div.setStyle("position", "absolute");	
				}				
			}
		}
	},
	
	buildMap:function(mapNode) {
		mapNode = $(mapNode);
		
		/* Parse map information */
		var center = mapNode.getAttribute("wf_map_center").split(",");
		center[0] = parseFloat(center[0]);
		center[1] = parseFloat(center[1]);
		
		var zoom = mapNode.getAttribute("wf_map_zoom");
		if (!zoom) zoom = "17";
		
		var amaps = mapNode.getElements("a");
		var flags = [];
		for (var i=0; i<amaps.length; i++) {
			var amap = amaps[i];
			var wfStyle = amap.getAttribute("wf_style")?amap.getAttribute("wf_style"):"";
			var flag = {
				location: amap.getAttribute("wf_geo_location").split(","),
				description: "",
				title: amap.get("text"),
				url: amap.href,
				style: amap.getAttribute("wf_style"),
				icon: wfStyle.indexOf("hide_flag")>=0?"transparent":(amap.getAttribute("wf_icon")?amap.getAttribute("wf_icon"):amap.getAttribute("wf_flag_icon"))
			};

			var imgs = amap.getElements("img");
			if (imgs.length) {
				flag.icon = imgs[0].src;
			}
			flags.push(flag);
		}
		/*
		while (child) {
			if (child.nodeType===1&&child.getAttribute("wf_type")=="map_flag") {
				var flag = {
					location: child.getAttribute("wf_map_flag_location").split(","),
					description: child.getAttribute("wf_map_flag_description"),
					title: child.getAttribute("wf_map_flag_title"),
					url: child.getAttribute("wf_map_flag_target_url")
				};
				$(child).appendText(flag.title);
				flags.push(flag);
			}
			child = child.nextSibling;
		}
		*/
		mapNode.innerHTML="";
		mapDiv = new Element("div").injectInside(mapNode.parentNode);
		mapNode.dispose();
		mapDiv.addClass("wf_map");
		if (WF.isWebApp) {
			if (WF.Tab) {
	            mapDiv.setStyle("top", "88px");
	            mapDiv.setStyle("height", "328px");
			}
		}
		
		if (GBrowserIsCompatible()){
			map = new GMap2(mapDiv);
			/*yslider = new YSliderControl();
	    		yslider.initialize(map);
	    		var ttop= Math.round((YSLIDERLENGTH/MAXZOOM*12));
	    		yslider.slide.top =  ttop;
	    		yslider.knob.style.top = ttop+"px";*/
			map.addMapType(G_NORMAL_MAP);
			map.setCenter(new GLatLng(center[0], center[1]), parseInt(zoom), G_NORMAL_MAP);
            // map.addControl(new GSmallZoomControl());
            
			if (!Browser.Platform.ipod) {
				map.enableScrollWheelZoom()
			}
			var imap = new WF.iPhoneGMap(map);
			
			for (var i=0; i<flags.length; i++) {
				var flag = flags[i];
				WF.buildMarker(map, flag);
			}
			
			var atags = mapDiv.getElements("a");
			for (var i=0; i<atags.length; i++) {
				if (atags[i].id=="backButton") continue;
				WF.bindNavLink(atags[i]);
			}
			
			WF.map = map;
			
			var ctl = new Element("div",{"class":"zoomCtl", "styles":{"width":"34px", "height":"70px", "position":"absolute", "left":"7px", "top":"7px", "zIndex":"10005"}}).injectInside(mapDiv);
			ctl.innerHTML = '<div onclick="WF.map.zoomIn();" title="Zoom In" style="position: absolute; left: 0px; top: 0px; width: 34px; height: 35px; cursor: pointer;"></div>' +
            '<div onclick="WF.map.zoomOut();" title="Zoom Out" style="position: absolute; left: 0px; top: 35px; width: 34px; height: 35px; cursor: pointer;"></div>';

		}		
	},
	
	buildMarker: function(map, flag) {
        var labelOptions = {
            "clickable": true,
            "title": flag.title?flag.title:"empty",
            "labelOffset": new GSize(-50, 0),
            "labelClass": "wf_map_flag_label"
        };
        
        if (flag.title) {
            labelOptions["labelText"] = flag.url?'<a href="' + flag.url + '"' + (flag.style?' wf_style="'+flag.style+'"':'') + '>' +
                            flag.title + '</a>':flag.title;
        }
        
        if (flag.icon) {
	        var imgLoader = new Image();
			var icon = flag.icon=="transparent"?WF.dirName(WF.scriptURL())+"transparent.png":flag.icon;
	        imgLoader.onload = function() {
	            var width = parseInt(this.width);
	            var height = parseInt(this.height);

	            var baseIcon = new GIcon(G_DEFAULT_ICON);
	            baseIcon.shadow = "";
	            baseIcon.image = icon;

	            baseIcon.iconSize = new GSize(width, height);
	            
	            var anchor_x = baseIcon.iconSize.width/2;
	            var anchor_y = baseIcon.iconSize.height;
	            baseIcon.iconAnchor = new GPoint(anchor_x, anchor_y);
	            labelOptions["icon"] = baseIcon;
				
                WF.buildMarkerWithOptions(map, flag, labelOptions);
	        };
	        imgLoader.src = icon;
        }
		else {
            var baseIcon = new GIcon(G_DEFAULT_ICON);
            baseIcon.shadow = "";
            baseIcon.image = WF.dirName(WF.scriptURL())+"pin.png";
            baseIcon.iconSize = new GSize(38, 38);
            
            var anchor_x = 38/2;
            var anchor_y = -22; // baseIcon.iconSize.height; 
            baseIcon.iconAnchor = new GPoint(anchor_x, anchor_y);
            labelOptions["icon"] = baseIcon;
			WF.buildMarkerWithOptions(map, flag, labelOptions);
		}
    },
	
	buildMarkerWithOptions: function(map, flag, labelOptions) {
        var marker = new LabeledMarker(new GLatLng(parseFloat(flag.location[0]), parseFloat(flag.location[1])), 
                        labelOptions);
        map.addOverlay(marker);
        WF.bindMarker(marker, flag);
	},
	
	bindMarker: function(marker, flag) {
		if (!flag.url) return;
        var wfStyle = flag.style;
        if (document.body.getAttribute("wf_type")=="no_back" ||
            (wfStyle && (wfStyle.indexOf("newscreen") >= 0||wfStyle.indexOf("navigation_reset") >= 0))) {
            flag.url = WF.strService(flag.url);
            return; 
        }

        var isSameDomain = true;
        if ((flag.url.indexOf("http://")===0&&flag.url.indexOf(location.host)<0)||  // outside domain
             flag.url.endsWith(".mp4")||
             flag.url.endsWith(".mp3")||
             flag.url.endsWith(".mov")||
             flag.url.endsWith(".doc")||
             flag.url.endsWith(".pdf")||
             flag.url.endsWith(".xls")||
             (wfStyle&&wfStyle.indexOf("browser")>=0)){  
            isSameDomain = false;
        }
        
        GEvent.addListener(marker, "click", function() {
            if (isSameDomain) {
                var wfStyle = flag.style ? flag.style : "";
				WF.loadLinkContent(flag.url, wfStyle.indexOf("noback") < 0, wfStyle.indexOf("popup")>=0?(wfStyle.indexOf("popup_bottom")>=0?1:2):0);
                if ($("optionpanel")) {
                    $("optionpanel").setStyle("display", "none");
                }
            }
            else {
                window.open(flag.url);
            }
        });
		
	},
	/* iFrame */
	buildiFrame: function(div) {
		var iframes = div.getElements("iframe");
		try {
	        for (var i=0; i<iframes.length; i++) {
	            var iframe = iframes[i];
	            var html = iframe.contentWindow.document.body.innerHTML;
	            if (!html) {
	                setTimeout(function(){WF.buildiFrame(div);});
	                return;
	            }
	        }
		}
		catch(e) {
            setTimeout(function(){WF.buildiFrame(div);});
            return;
		}

        for (var i=0; i<iframes.length; i++) {
            var iframe = iframes[i];
            var html = iframe.contentWindow.document.body.innerHTML;
			var div = new Element("div");
			div.innerHTML = html;
			div.inject(iframe, "after");
			WF.initIPhoneView(div);
			iframe.dispose();
        }
	},
	
	/* Table Color */
	fixTableColors: function(div) {
		var bgcolorElements = div.getElements("table[bgcolor],tr[bgcolor],td[bgcolor]");
		for (var i=0; i<bgcolorElements.length; i++) {
			bgcolorElements[i].setStyle("backgroundColor", bgcolorElements[i].getAttribute("bgcolor"));
		}
		
        if (typeof WF.bodyStyle["separator_color"]!="undefined") {
            var sepColor = WF.bodyStyle["separator_color"];
			var tableElements = div.getElements("table[wf_style~=fullscreen],table[wf_style~=rounded]");
			for (var i=0; i<tableElements.length; i++) {
				var t = tableElements[i];
				var tds = t.getElements("td");
				for (var j=0; j<tds.length; j++) {
					var td = tds[j];
					if (parseInt(td.getStyle("borderTopWidth"))) {
						td.setStyle("borderTopColor", sepColor);
					}
				}
			}			
        }           
		
	},
	
	/* iPhone Picker */
	buildiPhonePicker: function(div) {
		var divs = div.getElements("div[wf_style~=iphone_picker][wf_style~=inplace],div[wf_style~=iphone_picker_embedded]");
		for (var i=0; i<divs.length; i++) {
			var d = divs[i];
			var selects = d.getElements("select");
			var count = selects.length;
			for (var j=0; j<selects.length; j++) {
			    selects[j].setStyle("width", (95/count) + "%");	
			}
		}
	},
	
	/* from dyasdesigns */
	iPhoneGMap:function(mapvar, mapdiv) {
		this.map = mapvar;
		if(typeof mapdiv == "undefined"){
			this.mapDiv = this.map.getContainer();
		}
		else this.mapDiv = mapdiv;
		
		this.touchPositionX = 0;
		this.touchPositionY = 0;
		this.isZooming = false;
		this.webkitTranslateX = 0;
		this.webkitTranslateY = 0;
		var centerPoint = this.map.fromLatLngToDivPixel(this.map.getCenter());
		this.mapCenterX = centerPoint.x;
		this.mapCenterY = centerPoint.y;
		var that = this;
		
		this.mapDiv.ongestureend = function(e) {
			that.isZooming = false;
			that.webkitTranslateX = 0;
			that.webkitTranslateY = 0;
		};
		
		this.mapDiv.ongesturechange = function(e) {
			e.preventDefault();
			if(!that.isZooming){
				var z = Math.log(e.scale)/Math.log(2)*2.0;
				var oldZoom = that.map.getZoom();
				var zoom = parseInt(that.map.getZoom() + z);
				if (oldZoom!=zoom) {
					that.map.setZoom(zoom);
					that.isZooming = true;
				}
			}
		};
	},
    
    syntaxHighlight: function() {
        if (typeof dp!="undefined") {
            dp.SyntaxHighlighter.HighlightAll('code');
            return; 
        }
        
        // load css
        if(document.createStyleSheet) {
            setTimeout( function(){
                document.createStyleSheet("http://wwwjs.willflow.com/code/src/dp.SyntaxHighlighter/Styles/SyntaxHighlighter.css");}, 0 );
        }
        else {
            styles = "@import url('" + "http://wwwjs.willflow.com/code/src/dp.SyntaxHighlighter/Styles/SyntaxHighlighter.css" + "');";
            newSS=document.createElement('link');
            newSS.rel='stylesheet';
            newSS.href='data:text/css,'+encodeURI(styles);
            document.getElementsByTagName("head")[0].appendChild(newSS);
        }
                
        // load script
        var headTag = document.getElementsByTagName('head')[0]; 
        var script = document.createElement('script'); 
        script.type = 'text/javascript'; 
        script.src = "http://wwwjs.willflow.com/code/src/dp.SyntaxHighlighter/Scripts/shCore.js";
        headTag.appendChild(script);
        
        setTimeout(function() {
            if (typeof dp == "undefined") {
                setTimeout(arguments.callee, 50);
                return;
            }
            
            var headTag = document.getElementsByTagName('head')[0]; 
            var script = document.createElement('script'); 
            script.type = 'text/javascript'; 
            script.src = "http://wwwjs.willflow.com/code/src/dp.SyntaxHighlighter/Scripts/shBrushXml.js";
            headTag.appendChild(script);
            
            setTimeout(function() {
                if (typeof dp.sh.Brushes.Xml == "undefined") {
                    setTimeout(arguments.callee, 50);
                    return;
                }
                dp.SyntaxHighlighter.HighlightAll('code');
            }, 50);
        }, 50);
    }
};


/*
based on prototype's && moo.fx's ajax class
to be used with prototype.lite, in conjunction with moo.AJAX
this submits an iframe invisibly to the server, and expects a JSON object in return
handy, so that you do not have to care about posting forms, urlencoding, file uploads etc.
usage: <form method='post' onsubmit='new iframe(this); return false;'>

changelog:
17-01-06: initial release
18-01-06: added options initiator
          added IE5 support
		  added Opera support
01-03-06: added WORKING safari support! Major thanks to Charles Hinshaw and Phil Barrett!

*/
document.iframeLoaders = {};

iframe = new Class({
	initialize: function(form, options){
		if (!options) options = {};
		this.form = form;
		this.uniqueId = new Date().getTime();
		document.iframeLoaders[this.uniqueId] = this;
		this.transport = this.getTransport();
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.updateMultiple = options.multiple || false;
		form.target= 'frame_'+this.uniqueId;
		form.setAttribute("target", 'frame_'+this.uniqueId); // in case the other one fails.
		form.submit();
	},

	onStateChange: function(){
		this.transport = $('frame_'+this.uniqueId);
		try {   var doc = this.transport.contentDocument.document.body.innerHTML; this.transport.contentDocument.document.close(); }	// For NS6
		catch (e){ 
			try{ var doc = this.transport.contentWindow.document.body.innerHTML; this.transport.contentWindow.document.close(); } // For IE5.5 and IE6
			 catch (e){
				 try { var doc = this.transport.document.body.innerHTML; this.transport.document.body.close(); } // for IE5
					catch (e) {
						try	{ var doc = window.frames['frame_'+this.uniqueId].document.body.innerText; } // for really nasty browsers
						catch (e) { } // forget it.
				 }
			}
		}
		this.transport.responseText = doc;
		if (this.onComplete) setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
		if (this.update) setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
		if (this.updateMultiple){ setTimeout(function(){ // JSON support!
				try	{ var hasscript = false; eval("var inputObject = "+this.transport.responseText);	// we're expecting a JSON object, eval it to inputObject
					for (var i in inputObject) { if (i == 'script') { hasscript = true; } // check if we passed some javascript along too
						else {if ( elm = $(i)) { elm.innerHTML = inputObject[i]; } else { alert("element "+i+" not found!"); } } // if it's not script, update the corresponding div
					} if (hasscript) eval(inputObject['script']); // some on-the-fly-javascript exchanging support too
				} catch (e) { alert('There was an error processing: '+this.transport.responseText); } // in case of an error					
			}.bind(this), 10);
		}	
	},

	getTransport: function() 
	{
		var divElm = document.createElement('DIV');
	    divElm.style.position = "absolute";
        divElm.style.top = "0";
        divElm.style.marginLeft = "-10000px";
		if (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) {// switch to the crappy solution for IE
		 divElm.innerHTML = '<iframe name=\"frame_'+this.uniqueId+'\" id=\"frame_'+this.uniqueId+'\" src=\"about:blank\" onload=\"setTimeout(function(){document.iframeLoaders['+this.uniqueId+'].onStateChange()},20);"></iframe>';
		} else {
			var frame = document.createElement("iframe");
			frame.setAttribute("name", "frame_"+this.uniqueId);
			frame.setAttribute("id", "frame_"+this.uniqueId);
			frame.addEventListener("load", 	function(){	this.onStateChange(); }.bind(this), false);
			divElm.appendChild(frame);
		}
		document.getElementsByTagName("body").item(0).appendChild(divElm);
	}
});

String.implement({
    endsWith: function(pat) {
        return (this.lastIndexOf(pat)==this.length-pat.length);
    }
});
