var online = new String(document.location).indexOf("http://") > -1;
var debug = false;
var main = {
	init: function(data){
		this.contentXML = data;
		this.currentPageNodeIndex = null;
		this.currentChecklist = "";
		this.renderNav("Workbook");
		
		var sa_value = SWFAddress.getValue();
		if (sa_value != "/"){
			this.gotoPageId(sa_value.substr(1).split("_").join(" "));
		} else {
			this.renderContent(0);
		}
		
		YAHOO.util.Event.on( document,'click',this.checkClick);
		
	},
	
	checkClick:function(e){
		var targ = YAHOO.util.Event.getTarget(e);
		var leafNodes = $("li",$(targ).parent().next());
		$(leafNodes).each(function(i){
			if (i==0){
				//main.gotoPageId($(this).attr("id"));
				SWFAddress.setValue($(this).attr("id").split(" ").join("_"));
			}
		});
	},
	
	handleChange: function(event){
		this.gotoPageId(event.value.substr(1).split("_").join(" "));
	},
	
	renderNav: function(section_id){
		// container
		$("div#leftNav").append('<dl class="accordion-menu" id="menu_AddbyCategory"></dl>');
		
		// repeat starts here
		$('section',this.contentXML).each(function(){
			
			// match section
			if ($(this).attr('id') == section_id){
				$('subsection',this).each(function(){
					// heading
					var headingLabel = $(this).attr('id');
					$("dl.accordion-menu").append('<dt class="a-m-t" id="'+headingLabel.toLowerCase().split(' ').join('_')+'"><span class="categoryTitle">'+headingLabel.toUpperCase()+'</span></dt>');
					
					
					var leafNodesString = '<dd class="a-m-d">';
					leafNodesString += '<div class="bd">';
					leafNodesString += '<ul>';
					
					$('page',this).each(function(){
						// page
						var pageId = $(this).attr('id');
						var tempArray = pageId.split(" - ");
						var pageLabel = tempArray[0];
						leafNodesString += '<li id="'+pageId+'">'+pageLabel+'</li>';
					});
					
					leafNodesString += '</ul>';
					leafNodesString += '</div>';
					leafNodesString += '</dd>';
					$("dl.accordion-menu").append(leafNodesString);
				});
			}			
		});
		
		//set up leaf node events
		$("dd.a-m-d div.bd ul li").mouseup(function(){
			SWFAddress.setValue($(this).attr('id').split(" ").join("_"));
		});
	},
	
	renderContent: function(index){
		window.scrollTo(0,0);
		
		var pages = $("page",this.contentXML);
		trace("this.contentXML:"+this.contentXML);
		
		if (index == 0){
			$(".backBtn").css("display","none");
			$(".nextBtn").css("display","block");
		} else if (index == pages.length - 1){
			$(".backBtn").css("display","block");
			$(".nextBtn").css("display","none");
		} else {
			$(".backBtn").css("display","block");
			$(".nextBtn").css("display","block");
		}
		
		this.currentPageNodeIndex = index;
		this.currentPageId = $(pages[index]).attr("id");
		SWFAddress.setTitle(this.currentPageId);
		
		if (online){
			var nodeText = $(pages[index]).text();
			$("div#content").text('');
			$("div#content").append(nodeText);
		} else {
			var nodeText = $(pages[index]).text();
			$("div#content").text('');
			$("div#content").append(nodeText);
		}
		
		
		trace("this.currentPageId:"+this.currentPageId);
		trace("index:"+index);
		trace("nodeText:"+nodeText);
		
		// did the user change the body text size
		if (this.newSizeP){
			$("div#content p").css("fontSize",this.newSizeP);
			$("div#content h2").css("fontSize",this.newSizeH2);
		}
		
		var h1test = $("div#content h1").text();
		$("div#content h1").remove();
		$("div#content").prepend("<h1>"+h1test+"</h1>");
		
		//positioning
		//var gap = parseInt($("div#content h1").css("height"));
		var gap = $("div#content h1").innerHeight();
		if ($("div#content h2").text()){
			$("div#content h2").css("top",Math.round(60-(gap*.4)));
			$("div#content p").css("top",parseInt($("div#content h2").css("top"))+10);
			//$("div#content img").css("top",parseInt($("div#content img").css("top"))+10);
			$("div#content ul.non-answer").css("top",parseInt($("div#content p").css("top"))+8);
			// spacing isn't needed within answer box
		} 	else {
			$("div#content p").css("top",60-(gap*.4));
		}
		
		/*
		if ($.browser.msie){
			//$("div#content img.balance").after("<table border='0' cellpadding='0' cellspacing='0' width='618' height='397' class='balance'><tr><td background='images/balanceSheet.jpg' width='618' height='397'> </td></tr></table>");
			//$("div#content img.balance").remove();
		} 
		*/
		$("div.mainContent_hr").css("top",gap-18);
		$("div.backNextBtn_container").css("top",gap-18);
		$("div.textSizeContainer").css("top",gap-13);
		$("div.mainContentBanner").css("top",gap-18);
		
		//change out rt column image -- callout
		$("div.mainContentBanner").text('');
		if ($(pages[index]).attr("callout") != ""){
			trace("creating callout");
			var calloutImg = "<img src='"+$(pages[index]).attr("callout")+"' />";
			$("div.mainContentBanner").append(calloutImg);
		}
		
		// -- checklist
		if ($(pages[index]).attr("checkList") != ""){
			trace("creating checklist");
			var checkListImg = "<img src='"+$(pages[index]).attr("checkList")+"' border='0' />";
			var checkListComplete = "<a href='javascript:main.openCheckList(\""+this.currentPageId.split(" ").join("_")+"_checklist\")'>" + checkListImg + "</a>"
			$("div.mainContentBanner").append(checkListComplete);
		}
		
		var printButtonText = '<a href="javascript:main.printPage();"><img src="images/btn_printpage.jpg" class="print" width="143" height="35" border="0"/></a>';
		$("div.mainContentBanner").append(printButtonText);
		
		// page indicator
		var realSiblings = $(pages[index]).parent().children();
		var numSiblings = realSiblings.length;
		var siblingIndex;
		realSiblings.each(function(i){
			if (main.currentPageId == $(this).attr("id")){
				siblingIndex = i+1;
			}
		});
		
		$('#pageNumber').css('display','none');
		$('#pageNumber2').css('display','none');
		var pageNumberText = 'Page '+siblingIndex+' of '+numSiblings;
		
		// section indicator
		var sectionName = $(pages[index]).parent().attr("id");
		$('#pageTitle').text('');
		$('#pageTitle').append('<h3>'+sectionName+' '+pageNumberText+ '</h3>');
		
		// open accordion to correct section
		var parent = $(pages[index]).parent();
		var dtId = $(parent).attr("id").toLowerCase();
		new AccordionMenu.openDtById(dtId.split(" ").join("_"));
		
		// highlight
		if (main.currentSelectedLi){
			$(main.currentSelectedLi).css("font-weight","normal");
		}
		
		$("dd.a-m-d div.bd ul li").each(function(){
			if ($(this).attr("id") == main.currentPageId){
				$(this).css("font-weight","bold");
				main.currentSelectedLi = this;	
			}
		});
		
		this.closeCheckList(this.currentChecklist);
		if ($.browser.msie && $.browser.version < 7){
			if ($(pages[index]).attr("id") == "Accounting Principles"){
				$("div#content").css("top",-110);
			} else {
				$("div#content").css("top",-70);
			}
		}
	},
	
	openCheckList: function(checklist_id){
		this.currentChecklist = checklist_id;
		$("div#"+checklist_id).css("display","block");
		$("div#"+checklist_id+" input#"+checklist_id+"_close").click(function(){
			main.closeCheckList(checklist_id);														   
		});
		window.scrollTo(0,1);
	},
	
	closeCheckList: function(checklist_id){
		if (checklist_id == "") return;
		$("div#"+checklist_id).css("display","none");
	},
	
	gotoPageId: function(id){
		$("page",this.contentXML).each(function(i){
			if ($(this).attr("id") == id){
				main.renderContent(i);
			}
		});
	},
	
	gotoPage: function(pageNum){
		var pages = $("page",this.contentXML);
		
		if (pageNum < 0 || pageNum >= pages.length){
			pageNum = 0;
		}
		SWFAddress.setValue($(pages[pageNum]).attr("id").split(" ").join("_")); 
	},
	
	gotoPageFromBody: function(rawId){
		var realId = rawId.split(" ").join("_");
		SWFAddress.setValue(realId); 
	},
	
	next: function(){
		var pages = $("page",this.contentXML);
		if (this.currentPageNodeIndex + 1 == pages.length){
			this.currentPageNodeIndex = 0;
		} else {
			this.currentPageNodeIndex++;
		}
		SWFAddress.setValue($(pages[this.currentPageNodeIndex]).attr("id").split(" ").join("_")); 
	},
	
	previous: function(){
		var pages = $("page",this.contentXML);
		if (this.currentPageNodeIndex - 1 < 0){
			this.currentPageNodeIndex = pages.length-1;
		} else {
			this.currentPageNodeIndex--;
		}
		SWFAddress.setValue($(pages[this.currentPageNodeIndex]).attr("id").split(" ").join("_"));
	},
	
	resizeText: function(multiplier){
		var currentSizeP = parseFloat($("div#content p").css("fontSize"));
		this.newSizeP = currentSizeP + multiplier + "px";
		$("div#content p").css("fontSize",this.newSizeP);
		
		var currentSizeH2 = parseFloat($("div#content h2").css("fontSize"));
		this.newSizeH2 = currentSizeH2 + multiplier + "px";
		$("div#content h2").css("fontSize",this.newSizeH2);
		
		var currentSizeLI = parseFloat($("#content li").css("fontSize"));
		newSizeLI = currentSizeLI + multiplier + "px";
		$("#content li").css("fontSize",newSizeLI);
		
		var currentSizeCS = parseFloat($("span#casestudyCopy").css("fontSize"));
		newSizeCS = currentSizeCS + multiplier + "px";
		$("span#casestudyCopy").css("fontSize",newSizeCS);
		
		var currentSizeAns = parseFloat($(".answer #casestudyCopy").css("fontSize"));
		newSizeAns = currentSizeAns + multiplier + "px";
		$(".answer #casestudyCopy").css("fontSize",newSizeAns);
		
		var currentSizePUC = parseFloat($(".popupCopy").css("fontSize"));
		newSizePUC = currentSizePUC + multiplier + "px";
		$(".popupCopy").css("fontSize",newSizePUC);
		
		var currentSizePUCH1 = parseFloat($(".popupCopy H1").css("fontSize"));
		newSizePUCH1 = currentSizePUCH1 + multiplier + "px";
		$(".popupCopy H1").css("fontSize",newSizePUCH1);
		
		var currentSizeLabel = parseFloat($(".popupChecklist label").css("fontSize"));
		newSizeLabel = currentSizeLabel + multiplier + "px";
		$(".popupChecklist label").css("fontSize",newSizeLabel);
	},
	
	printPage: function(){
		var printable = window.open("printable.html?id="+this.currentPageId.split(" ").join("_"),"printable");
		//return false;
	},
	
	showAnswer: function(){
		$(".answer").css("display","block");
	}
};

function trace(msg){
	if (debug) console.log(msg);
}

// initialize main
$(document).ready(function(){
	//if (($.browser.safari ||  && !online){
	if (!online){
		$.ajax({
			type: "GET",
			url: "xml/content.xml",
			processData: false,
			async: false,
			dataType: "xml",
			success: function(data,txtStatus){
				trace("ready");
				main.init(data);
				SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function(evt){main.handleChange(evt)});
			}
		});
	} else {
		$.get("xml/content.xml",function(data){
			trace("ready");
			main.init(data);
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function(evt){main.handleChange(evt)});
		});
	}
});
