/**
 * Init.js
 * 
 * This contains code that should run when the dom is loaded and ready. 
 * 
 * If depending on this file, make sure it is included on the page:
 * <com:TClientScript ScriptUrl=<%~ ../core-js/init.js %> />
 * If you use TClientScript, it should be placed at the bottom of the page (not in thead)
 * 
 * you can also register the script programmatically like this:
 * 
 * public function onPreInit($param){
 *    $this->Page->ClientScript->registerScriptFile("page_init", $this->publishAsset("../core-js/init.js"));
 * }
 * 
 */
document.observe("dom:loaded", function(){
 	hideExtraBookmarks();

	//fix quotes in ie7/ie6
	if(Prototype.Browser.IE){
		var ie6 = parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5), 10) == 6;
		var ie7 = parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5), 10) == 7;
		
		if(ie6 || ie7){
			fixIEQuotes();
		}
	}

 	/*
	 * This hides any extra bookmarks in the bookmarks panel
	 */
	function hideExtraBookmarks(){		
		var maxVisibleBookmarks = 15;
		
		var bookmarks = $$("#bookmarks li");
		if(bookmarks === null || bookmarks.length === 0) return;
		
		if(bookmarks.length > maxVisibleBookmarks){
			//hide extra bookmarks
			for(var x=maxVisibleBookmarks; x<bookmarks.length; x++){
				bookmarks[x].style.display = "none";
			}
			
			//add a link to make extra bookmarks visible
			var link = new Element("a", {
				id: "show_all_bookmarks_link",
				href: "#"
			}).insert("show all");
			
			link.observe("click", function(e){
				e.stop();
				bookmarks.each(function(bookmark){
					bookmark.style.display = "";
				});
				
				//hide this link
				this.style.display = "none";
			});
			
			$("bookmarks").insert(link);
		}
	}
	
	
	function fixIEQuotes(){
		var objQuotes = document.getElementsByTagName('q');
		var strOpen, strClose;
	
		for (var i=0; i<objQuotes.length; i++){
			if (isNested(objQuotes[i])){
		    	// Double-quotes
		      	strOpen = document.createTextNode('\u2018');
		      	strClose = document.createTextNode('\u2019');
	    	}
	    	else{
	      		// Single-quotes
	      		strOpen = document.createTextNode('\u201c');
	      		strClose = document.createTextNode('\u201d');
	    	}
	
	    	// Insert quotation marks around quote
	    	objQuotes[i].parentNode.insertBefore(strOpen, objQuotes[i]);
	    	objQuotes[i].appendChild(strClose);
	  	}
	  objQuotes = null;
	}
	
	function isNested(objElement){
		var objParent = objElement;
		do{ //check if nested quote
	    	objParent = objParent.parentNode;
	    	if(objParent.tagName && objParent.tagName.toLowerCase() == 'q'){
	      		return true;
			}
	  	}
		while(objParent.parentNode);
	
		return false;
	}	
});

