﻿tilt.attachEvent(document, 'layout', function() {
	var body = document.body;
	if (body) {

// Build layout
		var areas = objectize(
			[
				"search",
				"titling",
				"content",
				"feeds",
				"navigation",
				"extensions",
				"legacy",
				"footer",
				"login",
				"properties",
				"spacer"
			]
		);

		var content = distribute(areas.content,
			[
				"banner",
				"scoreboard",
				"ads-lefttop",
				"ads-leftbottom",
				"ads-righttop",
				"ads-rightbottom",
				"main"
			]
		);

		var feeds = distribute(areas.feeds, 
			[
				"top-stories",
				"more-stories",
				"events",
				"announcements"
			]
		);

		var navigation = distribute(areas.navigation,
			[
				"children",
				"breadcrumbs"
			]
		);

		var safari = document.childNodes && !document.all && !navigator.taintEnabled;
		if (safari) {
			document.body.className = document.body.className + " l-safari"
		}

		var oPageTitle = null;
		foreach(map(areas["titling"]), function(oChild) {
			var oClass = oChild.className;
			if (oChild.getElementsByTagName("img").Length > 0) {
				if (oClass.indexOf("Site") >= 0) {
					var oNewDiv = document.createElement("div");
					oNewDiv.className = "Site";
					oChild.parentNode.replaceChild(oNewDiv, oChild);
				}
			} else {
				if (oClass.indexOf("page") >= 0) {
					oPageTitle = oChild;
				} else if (oClass.indexOf("Site") >= 0) {
					var oImg = first(getElements(oChild, "img", "*"));
					if (oImg) {
						oImg.parentNode.removeChild(oImg);
					}
				}
			}
		})

		// format site-search area
		if (areas["search"]) {
			var inputs = areas["search"].getElementsByTagName("input");
			searchBox = inputs[1];
			if (searchBox) {
				var defaultValue = "Search SDSM&T for...";
				var defaultClassName = searchBox.className;
				searchBox.value = defaultValue;
				tilt.attachEvent(searchBox, "focus", function(box) {
					if (searchBox.value == defaultValue) {
						searchBox.value = "";
						searchBox.className = defaultClassName + " active";
					}
				});
				tilt.attachEvent(searchBox, "blur", function(box) {
					if (searchBox.value.length === 0) {
						searchBox.value = defaultValue;
						searchBox.className = defaultClassName;
					}
				});
				// modify search box for Safari
				if (safari) {
					searchBox.type = "search";
				}
			}
			searchSubmit = inputs[2];
			if (searchSubmit) {
				searchSubmit.value = "";
				if (safari) {
					searchSubmit.type = "image";
				}
			}
			if (searchBox && searchSubmit) {
				tilt.attachEvent(searchBox, "keydown", function(searchBox, e) {
		         	 if (e.keyCode == 13) {
		            	window.setTimeout(function() {
		             		searchSubmit.click()
			       		}, 0);
            			return false;
          			}
         			return true;
        		});
			}
		}
		
		// Add formatting to breadcrumbs
		$('div.breadcrumbs li').each(function(idx) {
		  if (idx > 0) {
		    $(this).prepend('<span>' +String.fromCharCode(187) + '</span>');
		  }
		});

    var div = $(document.body).div().addClass('l-main-layout');

		// now build the layout
		//body.appendChild(tilt.createTable({
		div.append(tilt.createTable({
			"l-main": {
				"l-main" : [ tilt.createTable({
					"l-header": {
//						"l-logo": (areas.titling) ? tilt.createDiv([ areas.titling ], "l-logo") : null,
						"l-banner": (content.banner) ? tilt.createDiv([ content.banner ], "l-banner") : null
					},
					"l-scoreboard": {
						"l-scoreboard": (content.scoreboard) ? tilt.createDiv([ content.scoreboard ], "l-scoreboard") : null
					},
					"l-main-content": tilt.createTable({
						"l-main-content": {
							"l-left": [
								((first(content.ads_lefttop) || navigation.chidren || areas.search || content.ads_leftbottom ) ?
									tilt.createTable({
										"l-ads-left-top": {
											"l-ads-left-top": (content.ads_lefttop) ? tilt.createDiv([ content.ads_lefttop ], "l-ads-left-top") : null
										},
										"l-navigation": {
											"l-navigation": (navigation.children) ? tilt.createDiv([ navigation.children ], "l-navigation") : null
										},
										"l-ads-left-bottom": {
											"l-ads-left-bottom": (content.ads_leftbottom) ? tilt.createDiv([ content.ads_leftbottom ], "l-ads-left-bottom") : null
										}
									}) : null),
								/* this inserts a div.l-shim if there is no other content for l-left */
								((first(content.ads_lefttop) || navigation.children || areas.search || content.ads_leftbottom )
									? null
									: function() {
										var oShim = document.createElement("div");
										oShim.className = "l-shim";
										return oShim;
									}()
								)
							],
							"l-content": [
								((content.main || areas.legacy || feeds.top_stories || feeds.more_stories || areas.extensions ) ?
									tilt.createTable({
										"l-breadcrumbs": {
											"l-breadcrumbs": (navigation.breadcrumbs) ? tilt.createDiv([ navigation.breadcrumbs ], "l-breadcrumbs") : null
										},
										"l-main": {
											"l-main": (content.main || areas.legacy) ? tilt.createDiv([ content.main, areas.legacy ], "l-main-content") : null
										},
										"l-top-stories": {
											"l-top-stories": (feeds.top_stories) ? tilt.createDiv([ feeds.top_stories  ], "l-top-stories") : null
										},
										"l-more-stories": {
											"l-more-stories": (feeds.more_stories) ? tilt.createDiv([ feeds.more_stories  ], "l-more-stories") : null
										},
										"l-extensions": {
											"l-extensions": (areas.extensions) ? tilt.createDiv([ areas.extensions ], "l-extensions") : null
										}
									}) : null),
								
								/* this inserts a div.l-shim if there is no other content for l-content */
								((first(content.main) || areas.legacy || feeds.top_stories || feeds.more_stories || areas.extensions )
									? null
									: function() {
										var oShim = document.createElement("div");
										oShim.className = "l-shim";
										return oShim;
									}()
								)
							],
							"l-right": [
								((first(content.ads_righttop) || feeds.events || content.ads_rightbottom) ?
									tilt.createTable({
										"l-ads-right-top": {
											"l-ads-right-top": (content.ads_righttop) ? tilt.createDiv([ content.ads_righttop ], "l-ads-right-top") : null
										},
										"l-events": {
											"l-events": (feeds.events) ? tilt.createDiv([ feeds.events ], "l-events") : null
										},
										"l-ads-left-bottom": {
											"l-ads-right-bottom": (content.ads_rightbottom) ? tilt.createDiv([ content.ads_rightbottom ], "l-ads-right-bottom") : null
										}
									}) : null),
								/* this inserts a div.l-shim if there is no other content for l-right */
								((first(content.ads_righttop) || feeds.events || content.ads_rightbottom)
									? null
									: function() {
										var oShim = document.createElement("div");
										oShim.className = "l-shim";
										return oShim;
									}()
								)
							]
						}	
					}, "l-main-content"),
					"l-footer": (areas.footer  ? [ areas.footer ] : null)
				}, "l-primary")
				]
			}
		} , "l-main"));

		$.contentQuery();
		$('textarea.rich-text').tinyMceExt();

		if (areas.feeds && areas.feeds.parentNode) {
			areas.feeds.parentNode.removeChild(areas.feeds);
		}
		
		// mark first li as "first"
		foreach(body.getElementsByTagName("ul"), function(ul) {
			var items = ul.getElementsByTagName("li");
			if (items.length > 0) {
				var li = items[0];
				li.className = li.className + " first";
			}
		});
		
		// include script for datetime picker, if needed
		if (filter(document.getElementsByTagName("input"), function(input) {
			return input.className.indexOf("date") >= 0;
		}).length > 0) {
			tilt.addScript("datetime.js");	
		}
		if (content.content) {
			if (foreach(areas.content.getElementsByTagName("div"), function(div) {
				if (div.className == "visibility") {
					div.id = "grid-visibility";
					return true;
				}
			})) {
				tilt.addScript("grid.js");
			}
		}
		// include script for category-editor, if needed
		if (filter(document.getElementsByTagName("div"), function(div) {
			return div.className.indexOf("category-editor") >= 0;
		}).length > 0) {
			tilt.addScript("dynamictree.js");	
		}
	}	
	
	function distribute(col, classNames, defaultClassName) {
		var result = {};
		foreach(col, function(node) {
			push(getClassName());
			
			function push(className) {
				if (className) {
					className = className.replace('-', '_');
					var items = result[className];
					if (!items) {
						items = [];
						result[className] = items;
					}
					items.push(node);
				}
			}
			
			function getClassName() {
				var result = defaultClassName;
				foreach(classNames, function(className) {
					if (foreach(node.className.split(" "), function(nodeClassName) {
						return nodeClassName == className;
					})) {
						result = className;
						return true;
					}
				});
				return result;
			}

		});
		return result;
	}
	
	function htabulate(o) {
		var cells = {};
		foreach(o.getElementsByTagName("li"), function(li, i) {
			cells["l-cell-" + i] = first(li);
		});
		if (cells) {
			var firstChild = o.firstChild;
			var child = o.firstChild;
			while(child) {
				o.removeChild(child);
				child = o.firstChild;
			}
			o.appendChild(tilt.createTable({ "l-htable" : cells }, "l-htable"), o.firstChild);
		}
		return o;
	}
	
	function getElements(oElm, strTagName, strClassName)
	{
		var oElement;
		var arrReturnElements = [ ];
		var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
		for(var i=0;i<arrElements.length;i++) {
			oElement = arrElements[i];
			if((oElement.className && (oElement.className.indexOf(strClassName) >= 0)) || strClassName == "*") {
				arrReturnElements.push(oElement);
			}   
		}
		return (arrReturnElements)
	}

	function objectize(arrayOfIds)	{
		var result = {};
		foreach(arrayOfIds, function(item) {
			var o = document.getElementById(item);
			if (o) {
				result[item] = o;
			}
			else {
				result.complete = true;
			}
		})
		result.complete = !result.complete;
		result.contains = function(matches) {
			return foreach(matches, function(match) {
				if (result[match]) {
					return true;
				}
			});
		}
		return result;
	}
});