//create global GameManager

processMochiTAL = function (dom, data) {
	if (dom.nodeType != 1) {
		return;
	}
	
	var attr;
	
	// handle repeat tags
	attr = getAttribute(dom, "mochi:repeat");
	if (attr) {
		dom.removeAttribute("mochi:repeat");
		var parent = dom.parentNode;
		attr = attr.split(" ");
		var name = attr[0];
		var lst = valueForKeyPath(data, attr[1]);
		
		if (!lst) {	
			return;
		}
		
		for (var i=0; i<lst.length; ++i) {
			data[name] = lst[i];
			
			//if (valueForKeyPath(data, "item.round") == gameManager.selectedStage) {
				var newDOM = dom.cloneNode(true);
				processMochiTAL(newDOM, data);
				parent.insertBefore(newDOM, dom);
			//}
		}
		
		parent.removeChild(dom);
		return;
	}
	
	// handle content tags
	attr = getAttribute(dom, "mochi:content");
	if (attr) {
		dom.removeAttribute("mochi:content");
		replaceChildNodes(dom, valueForKeyPath(data, attr));
		return;
	}
	
	attr = getAttribute(dom, "mochi:formattedContent");
	if (attr) {
		dom.removeAttribute("mochi:formattedContent");
		var format = getAttribute(dom, "mochi:format");
		if (format) {
			replaceChildNodes(dom, 	numberFormatter(format)(valueForKeyPath(data, attr)));
		} else {
			replaceChildNodes(dom, 	numberFormatter("#%")(valueForKeyPath(data, attr)));
		}		
		return;
	}
	
	// handle custom link...
	attr = getAttribute(dom, "mochi:customLink");
	if (attr) {
		dom.removeAttribute("mochi:customLink");

		attr = attr.split(" ");

		var href = attr[0];
		var ref1 = attr[1];
		var ref2 = attr[2];
		
		//dom.href = href + "?" + ref1 + "=" + valueForKeyPath(data, "item.home") + "&" + ref2 + "=" + valueForKeyPath(data, "item.away");
		dom.href = href + "?" + ref1 + "=" + valueForKeyPath(data, "item.homeID") + "&" + ref2 + "=" + valueForKeyPath(data, "item.awayID");
	}
	
	// make a shallow copy of the child nodes - in case it changes due to repeat attr
	var nodes = list(dom.childNodes);
	
	// now iterate through them and continue the processing
	for (var i=0; i<nodes.length; ++i) {
		processMochiTAL(nodes[i], data);
	}	
};

ignoreEvent = function(ev) {
	if (ev && ev.preventDefault) {
		ev.preventDefault();
		ev.stopPropagation();
	} else if (typeof(event) != 'undefined') {
		event.cancelBubble = false;
		event.returnValue = false;
	}
};

var hiddenLinksGBL = null;
var subMenuHome = null;
var subMenuAway = null;

toggleDivTypeVisibility = function (ev) {
	ignoreEvent(ev);
	log ("toggle div vis");
	closeTeamPanels();
	var myListID = getAttribute(this, "mochi:listID");
	
	log ("list", myListID);
	
	for (var i=0; i<hiddenLinksGBL.length; ++i) {
		if(getAttribute(hiddenLinksGBL[i], "mochi:parentID") == myListID) {
			// now toggle the attribute...
			var vis = hiddenLinksGBL[i].style;

			if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
				vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
			vis.display = (vis.display==''||vis.display=='block')?'none':'block';			
		} else {
			setStyle(hiddenLinksGBL[i], {"display": "none"});
		}

	}
};

toggleDivMidTypeVisibility = function (ev) {
	ignoreEvent(ev);
	log ("toggle div mid vis");
	closeTeamPanels();
	var myListID = getAttribute(this, "mochi:listID");
	var myParentsID = getAttribute(this, "mochi:parentID");
	
	for (var i=0; i<hiddenLinksGBL.length; ++i) {
		log (getAttribute(hiddenLinksGBL[i], "mochi:parentID"), myListID, myParentsID);
		
		if (getAttribute(hiddenLinksGBL[i], "mochi:parentID") == myListID){
			// now toggle the attribute...
			var vis = hiddenLinksGBL[i].style;

			if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
				vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
			vis.display = (vis.display==''||vis.display=='block')?'none':'block';			
		} else if (getAttribute(hiddenLinksGBL[i], "mochi:parentID") == myParentsID) {
			var vis = hiddenLinksGBL[i].style;

			vis.display = 'block';			
		} else {
			setStyle(hiddenLinksGBL[i], {"display": "none"});
		}

	}

};


toggleTeamVisibility = function (ev) {
	ignoreEvent(ev);
	
	var hiddenLinks = subMenuHome;
	
	var myListID = getAttribute(this, "mochi:listID");
	var parentID = getAttribute(this, "mochi:parentID");

	log("ToggleTeamVis2", parentID, myListID, hiddenLinks.length);
	
	var htmlStrArr = PHP_teamHTMLArr[parentID][myListID];	

	for (var i=0; i<hiddenLinks.length; ++i) {
		log ("==>", getAttribute(hiddenLinks[i], "mochi:listID"));
		if(getAttribute(hiddenLinks[i], "mochi:listID") == myListID) {
			// now toggle the attribute...
			var vis = hiddenLinks[i].style;

			if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
				vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
			vis.display = (vis.display==''||vis.display=='block')?'none':'block';			
			
			if (vis.display == 'block') {
				// now lets make the damned link
				for (var j=0; j<htmlStrArr[1].length; ++j) {
					// write to the DOM
					var newDOM = A(htmlStrArr[2][j], htmlStrArr[1][j]);
					// append the fricking thing to this...
					newDOM.onclick = selectTeam;
					hiddenLinks[i].appendChild(newDOM);
				}
			} else {
				// kill the children
				replaceChildNodes(hiddenLinks[i]);
			}
		} else {
			setStyle(hiddenLinks[i], {"display": "none"});
			replaceChildNodes(hiddenLinks[i]);
		}
	}
	
	// now for away
	var hiddenLinks = subMenuAway;
	
	for (var i=0; i<hiddenLinks.length; ++i) {
		if(getAttribute(hiddenLinks[i], "mochi:listID") == myListID) {
			// now toggel the attribute...
			var vis = hiddenLinks[i].style;

			if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
				vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
			vis.display = (vis.display==''||vis.display=='block')?'none':'block';			

			if (vis.display == 'block') {
				// now lets make the damned link
				for (var j=0; j<htmlStrArr[1].length; ++j) {
					// write to the DOM
					var newDOM = A(htmlStrArr[2][j], htmlStrArr[1][j]);
					// append the fricking thing to this...
					newDOM.onclick = selectTeamAndSimulate;
					hiddenLinks[i].appendChild(newDOM);
				}
			} else {
				// kill the children
				replaceChildNodes(hiddenLinks[i]);
			}

		} else {
			setStyle(hiddenLinks[i], {"display": "none"});
			replaceChildNodes(hiddenLinks[i]);
		}
	}	
	
};

closeTeamPanels = function() {
	for (var i=0; i<subMenuHome.length; ++i) {
		if (subMenuHome[i].style.display != 'none') {
			setStyle(subMenuHome[i], {"display": "none"});
			replaceChildNodes(subMenuHome[i]);
			
		}
	}

	for (var i=0; i<subMenuAway.length; ++i) {
		if (subMenuAway[i].style.display != 'none') {
			setStyle(subMenuAway[i], {"display": "none"});
			replaceChildNodes(subMenuAway[i]);
		}
	}
};


selectTeam = function(ev) {
	ignoreEvent(ev);
	
	var newTeamID = getAttribute(this, "mochi:homeTeamID");
	
	gameManager.setNewTeamID(newTeamID);
	
	closeTeamPanels();
}

loadFromStageAnchor = function(ev) {
	ignoreEvent(ev);
	var stageID = this.getAttribute("mochi:stage");
	gameManager.selectedStage = stageID;
	
	gameManager.displayRows();
	// change the text for the divison label
	var tempDivisionLabel = this.firstChild.innerHTML;
	//swapDOM("divisionLabel", SPAN({id: "divisionLabel"}, tempDivisionLabel));
	
	//clear the other division anchors
	clearAnchorStyles("mochi:stage");
	
	
	//and set this one
	//this.setAttribute("style", "color:#000000;background-color:#f1f30a;");
	setStyle(this, {'color': '#000000', 'background-color': '#006600', color: 'white'});
};

clearAnchorStyles = function(key) {
	var anchors = getElementsByTagAndClassName("a", null);

	for (var i=0; i<anchors.length; ++i) {
		var node = anchors[i];

		var division = getAttribute(node, key);

		if (division) {
			//node.setAttribute("style", "");
			//setNodeAttribute(node, "style", "");
			//node.style = null;
			setStyle(node, {'color': null, 'background-color': null});
		}

	}

};

getAttribute = function (dom, key) {
	try {
		return dom.getAttribute(key);
	} catch (e) {
		return null;
	}
};

valueForKeyPath = function (data, keyPath) {
	var chunks = keyPath.split(".");
	while (chunks.length && data) {
		data = data[chunks.shift()];
	}
	return data;
};

SortTransforms = {
	"str": operator.identity,
	"isoDate": isoDate,
	"num": parseFloat
};

GameManager = function() {
	this.defaultDivId = 0;
	this.templates = [];
	this.deferred = null;
	this.data = null;
	this.loadingData = null;
	this.scriptName = "/cgi-bin/new_site/champLeague/GetTeamOpponents_cl.pl";
	this.sortState = {};
	this.selectedStage = "kn1";
	this.teamID = 0;
	bindMethods(this);
};

GameManager.prototype = {
	"initialize": function() {
		log("initializing");
		
		// grab the template divs, and then remove their temp class
		var templates = getElementsByTagAndClassName(null, "mochi-template");
		
		for (var i=0; i<templates.length; ++i) {;
			var template = templates[i];
			var proto = template.cloneNode(true);
			removeElementClass(proto, "mochi-template");
			this.templates.push({"template": proto, "node": template});
		}
				
		log ("Sort out globals");
		hiddenLinksGBL = new Array();

		log ("G: subMenus");
		subMenuHome = new Array();
		subMenuAway = new Array();
		var ul_items = getElementsByTagAndClassName("ul");

		log ("G: " + ul_items.length);		
		for (var i=0; i<ul_items.length; ++i) {
			if (ul_items[i].className == "submenu2h")
				subMenuHome[subMenuHome.length] = ul_items[i];
			else if (ul_items[i].className == "submenu2")
				subMenuAway[subMenuAway.length] = ul_items[i];
		}
				
		// catch the links to select the type of match
		var anchors = getElementsByTagAndClassName("a",null);
		
		for (var i=0; i<anchors.length; ++i) {
			var node = anchors[i];
			
			if (anchors[i].className == "mochi-visList_top") {
				var listID = getAttribute(anchors[i], "mochi:listID");

				if (listID) {
					anchors[i].onclick = toggleDivTypeVisibility;
				}	
			} else if (anchors[i].className == "mochi-visList_middle") {
				hiddenLinksGBL[hiddenLinksGBL.length] = anchors[i];

				var listID = getAttribute(anchors[i], "mochi:listID");

				if (listID) {
					anchors[i].onclick = toggleDivMidTypeVisibility;
				}			
				
			} else if (anchors[i].className == "mochi-visList_bottom") {
				hiddenLinksGBL[hiddenLinksGBL.length] = anchors[i];

				var listID = getAttribute(anchors[i], "mochi:listID");

				if (listID) {
					anchors[i].onclick = toggleTeamVisibility;
				}				
			}
	
	/*		
			var homeTeamID = getAttribute(anchors[i], "mochi:homeTeamID");
			
			if (homeTeamID || awayTeamID) {
				links[i].onclick = selectTeamAndSimulate;
			}				
	*/	
			var stage = getAttribute(node, "mochi:stage");
			
			if (stage) {
				node.onclick = loadFromStageAnchor;
			}
			
		}
		
		// catch the table header, and set for sorting
		
		var thead = getElement("tabletop");
		var tempThead = thead.cloneNode(true);
		
		var headers = tempThead.getElementsByTagName("div");
		for (var i=0; i<headers.length; ++i) {
			var header = headers[i];
			var attr = getAttribute(header, "mochi:sortcolumn");
			if (attr) {
				var sortinfo = attr.split(" ");
				var sortkey = sortinfo[0];
				header.onclick = this.onSortClick(sortkey);
			}		
		}
		swapDOM(thead, tempThead);
				
		this.sortkey = "pct_kn1";
		this.sortStyle = "num";
		this.sortState["pct_kn1"] = true;
		this.loadFromURL(this.scriptName, {teamID: this.teamID});
	},
	
	"setNewTeamID": function(newID) {
		this.teamID = newID;
		this.loadFromURL(this.scriptName, {teamID: this.teamID});
	},
	
	"loadFromURL": function(url, vars) {
		log("loadFromURL", url, vars.divID);
		var d;
		if (this.deferred) {
			this.deferred.cancel();
		}
		
		this.displayLoading();
		
		d = loadJSONDoc(url, vars);
		
		this.deferred = d;
		var self = this;
		
		d.addBoth(function (res) {
			self.deferred = null;
			log('loadFromURL success');
			return res;
		});
		
		d.addCallback(this.initWithData);
		
		d.addErrback(function(err) {
			if (err instanceof CancelledError) {
				return;
			}
			
			logError(err);
		});
		return d;
	},
	
	"initWithData": function(data) {
		log("initWithData", data);
		// store data for later
		this.data = data;
		
		// sort loading data

		var order = this.sortState[this.sortkey];
		if (typeof(order) == 'undefined') {
			order = true;
		}
		
		// display the rows
		this.displaySortedRows(this.sortkey, order, false);
	},
	
	"onSortClick": function(name) {
		var self = this;
		
		return function () {
			log('onSortClick', name);
			var order = self.sortState[name];
			if (typeof(order) == 'undefined') {
				order = true;
			} else if (self.sortkey == name) {
				order = !((typeof(order) == 'undefined')? false : order);
			}
			self.displaySortedRows(name, order, true);
		}
	},
		
	"displayRows": function () {
		log("displayRows");
		for (var i=0; i<this.templates.length; ++i) {
			var template = this.templates[i];
			log('template', i, template);
			var dom = template.template.cloneNode(true);
			processMochiTAL(dom, this.data);
			template.node = swapDOM(template.node, dom);
		}
	},
	
	"displaySortedRows": function (key, forward, clicked) {
		log("displaySortedRows", key, forward, clicked);
		
		this.sortState[key] = forward;
		this.sortkey = key;
		var sortstyle;
		
		// sort out the sort columns
		
		// apply sort transform to imaginary column
		// then do the sort
		if(!sortstyle) {
			sortstyle = "str";
		}
		
		var sortfunc = SortTransforms[sortstyle];
		if (!sortfunc) {
			throw new TypeError("unsupported sort style" + repr(sortstyle));
		}
		
		var games = this.data.opponents;
		for (var i=0; i<games.length; ++i) {
			var game = games[i];
			game.__sort__ = sortfunc(game[key]);
		}
				
		// now do the sort
		var cmp = (forward? reverseKeyComparator: keyComparator);
		games.sort(cmp("__sort__"));
		
		for (var i=0; i<this.templates.length; ++i) {
			var template = this.templates[i];
			log('template', i, template);
			var dom = template.template.cloneNode(true);
			processMochiTAL(dom, this.data);
			template.node = swapDOM(template.node, dom);
		}
	},
	
	"displayLoading": function() {
		log("Display loading text");
		
		for (var i=0; i<this.templates.length; ++i) {
			var template = this.templates[i];
			log('template', i, template);
			var dom = template.template.cloneNode(true);
			processMochiTAL(dom, this.loadingData);
			template.node = swapDOM(template.node, dom);
		}		
	}

};

gameManager = new GameManager();
addLoadEvent(gameManager.initialize);

