// Array to hold all suppLinks in the book
// we make one attribute per page that has links...
var suppLinks = new Object();

function SuppLinkObjectIndex(fn) {
	// replace "-" with "dd", to make it a valid object 
	if (fn != null) {
		return "sl_" + fn.replace(/-/g, "dd");
	}
}

// Keep track of total number of supp links added as the ebook is loading
var numSuppLinks = 0;
function RegisterSuppLink(atts, suppLinkId) {
	// If we didn't get a suppLinkId, we're adding as the ebook is loading, so count up
	if (suppLinkId == null) {
		suppLinkId = numSuppLinks;
		++numSuppLinks;
	}
	
	// Get index value from sectionFn
	var index = SuppLinkObjectIndex(atts.sectionFn);
	
	// Create an array for this section if necessary
	var slarr;
	if (suppLinks[index] != null) {
		slarr = suppLinks[index];
	} else {
		slarr = suppLinks[index] = new Array();
	}
	
	// If the link already existed, replace it
	for (var i = 0; i < slarr.length; ++i) {
		if (slarr[i].suppLinkId == suppLinkId) {
			break;
		}
	}
	
	// If we made it all the way through the above loop, i = slarr.length, and this is a new sl
	// otherwise we want to replace slarr[i]
	var sl = slarr[i] = new Object();
	
	// And copy in the attributes
	for (var i in atts) {
		// except the "targ" attribute
		if (i != 'targ') {
			sl[i] = atts[i];
		}
	}
	
	// Add the suppLinkId (have to do this after the fact because -1 might be in atts)
	sl.suppLinkId = suppLinkId;
	
	// alert('Registered suppLink for ' + sl.sectionFn);
	
	// Change in toc if necessary?
	//AddSuppToTOC(sl, chaptercontentsF);
}

// This is called by ebookNavigation.js
function AddAllSuppsToTOC(frame) {
	for (var index in suppLinks) {
		var slarr = suppLinks[index];
		for (var i = 0; i < slarr.length; ++i) {
			AddSuppToTOC(slarr[i], frame);
		}
	}
}

function AddSuppToTOC(sl, frame) {
	var tocEntry = "<div class='suppLinkClass'><a href=\"" + SuppLinkURL(sl) + "\">"
		+ '<span class="sn"><b>&raquo;</b></span>&nbsp;<b><span id="SL_' + sl.suppLinkId + '_titleSpan">' + sl.category + '</span></b>&nbsp;'
		+ '</a></div>'
		;
	
	var itemFn = "SL_" + sl.suppLinkId;
	
	if (sl.link != 'mainonly') { // KT  this if() came in from ugly during server move... 
		AddToTOC(tocEntry, frame, itemFn, SectionNumberFromFilename(sl.sectionFn), 'after', 'suppLinkTD');
	}
	
	// Mark which ones we've put in the chaptercontentsF
	if (frame == chaptercontentsF) {
		sl.inTOC = true;
	}
}

// Note: this should be added like this: 
// "<a href=\"" + SuppLinkURL(sl) + "\"'>"
function SuppLinkURL(sl) {
	// KC: 3 cases
	// 1. portal pageId supplied for DCTM resource
	// 2. no portal pageId supplied, no quiz session ID supplied: 'bcs'-type link
	// 3. quiz (session ID supplied) 
	if (sl.pageId == '' || sl.pageId == null) {
		if (sl.quizId == '' || sl.quizId == null) {
			return "JavaScript:top.OpenSupp('bcs','" + sl.category.replace(/'/g, "\\'") + "','" + sl.url + "')"
		} else {
			return "JavaScript:top.OpenSupp('onlinequiz','" + sl.quizId + "','" + sl.url + "')"
		}
	} else {
		return "JavaScript:top.OpenSupp('pageid','" + sl.pageId + "','" + sl.category.replace(/'/g, "\\'") + "','" + sl.url + "')"
	}

}

function DrawSuppLinks() {
	// get current section's index
	var index = SuppLinkObjectIndex(CurrentSectionFilename());

	// If we have any for this section...
	var slarr = suppLinks[index];
	if (slarr != null) {
		// First find the places ...
		for (var i = 0; i < slarr.length; ++i) {
			var sl = slarr[i];
			
			// Get all els of the target type
			var els;
			if (sl.containerType == "P") {
				els = main.document.getElementsByTagName("P");
			} else {
				els = main.document.getElementsByTagName("DIV");
			}
			
			// Then go through each of these els
			for (var j = 0; j < els.length; ++j) {
				var el = els[j];
				if (sl.containerType == "P" || (sl.containerType == "caption" && el.className.indexOf("caption") > -1)) {
					// get transformed innerhtml of the div
					var ih = ContainerLocatorTransform(el.innerHTML);
					
					// if it starts with the containerLocator text, we've found the target
					if (ih.indexOf(sl.containerLocator) == 0) {
						sl.targ = el;
						break;
					}
				}
			}
			
			if (j == els.length) {
				//alert('couldn\'t find supplemental link: ' + sl.containerLocator);
			}
		}
		
		// Then insert the innerHTML (we can't do this in one step, because of the possibility of having
		// multiple supplementals attached to the same paragraph
		var cl_array = new Object;
    		var suppLinkNum;
		for (var i = 0; i < slarr.length; ++i) {
			var sl = slarr[i];


			// calculate suppLinkId
        		if (cl_array[sl.containerLocator] == undefined) {
            			cl_array[sl.containerLocator] = 1;
        		} else {
            			cl_array[sl.containerLocator]++;
        		}
        		suppLinkNum = cl_array[sl.containerLocator];

			// KC: we want to be able to support multiple icon types; we can change the filenames
			// based on the link category
			var iconClass = sl.category;
			//alert("iconClass = " + iconClass);
			iconClass = iconClass.replace(/ /ig, "");
			//alert("iconClass = " + iconClass);

			// construct innerHTML for item
			// This is the div we want to insert into the page
			var new_el = main.document.createElement('div');

			// We've introduced a suppLinksRightMargin variable to config.js, to account for (mostly stats') use of 
			// supp links in right margin, as opposed to float left
			if (suppLinksRightMargin == "1") {
				new_el.setAttribute('class',"modMarker suppLink" + suppLinkNum);
        			new_el.setAttribute('className', "modMarker suppLink" + suppLinkNum);
			} else {
				new_el.setAttribute('class','modMarker');
				new_el.setAttribute('className','modMarker');
			}
			//new_el.innerHTML = "<a id='suppLink_" + sl.suppLinkId + "' class='modLink' href=\"" + top.SuppLinkURL(sl) + "\" title='" + sl.title.replace(/'/g, "\\'") + "'><img src='../pics/modicon" + iconClass + ".gif' border='0'><br>" + sl.category + "</a>";
			var newInner = "<a id='suppLink_" + sl.suppLinkId + "' class='modLink' href=\"" + top.SuppLinkURL(sl) + "\" title='" + sl.title.replace(/'/g, "\\'") + "'><img src='../pics/modicon" + iconClass + ".gif' border='0'>";
			if (showSuppCategory == null || showSuppCategory == false) {
                                newInner += "</a>";
                        } else {
                                newInner += "<br>" + sl.category + "</a>";
                        }
		
			//alert(newInner);

			new_el.innerHTML = newInner;

//			var s = "<div class='modMarker'><a id='suppLink_" + sl.suppLinkId + "' class='modLink' href=\"" + top.SuppLinkURL(sl) + "\" title='" + sl.title.replace(/'/g, "\\'") + "'><img src='../pics/modicon" + iconClass + ".gif' border='0'><br>" + sl.category + "</a></div>";

			// DataSets will have a different url than the rest of the resources.
        		// DataSets call ShowDataSets(), defined in config.js.  All other resources can use
        		// SuppLinkURL() to get there url.        
			var link_url;
        		if (top.angelStyle == 1) {
            			link_url = SuppLinkURL(sl);
        		} else {
            			link_url = top.SuppLinkURL(sl);
        		}
    
        		if (sl.category.match(/DataSet/i)) {
            			link_url = "JavaScript:top.ShowDataSets('" + sl.title + "','" + sl.pageId + "','" + sl.url + "')";
        		}
      
			newInner = "";
        		if (link_url != "") {	
				newInner = "<a class='modLink' href=\"" + link_url + "\" title='" + sl.title.replace(/'/g, "\\'") + "'><img class='modImg' src='../pics/modicon" + iconClass + ".gif'>";
				if (showSuppCategory == null || showSuppCategory == false) {
                                        newInner += "</a>";
                                } else {
                                        newInner += "<br>" + sl.category + "</a>";
                                }

			
			}

			new_el.innerHTML = newInner;
			// If we couldn't find a place for it above...
			if (sl.targ == null) {

			} else {
			    // we want to add it directly in front of the target element
			    // unless "link" attribute is "leftonly" (default is "normal")
				if (sl.link == 'leftonly') {

				} else {
                	
                	var parent_node = sl.targ.parentNode;
  					parent_node.insertBefore(new_el, sl.targ);
  					
  				}
			}
			
			sl.targ = null;
		}

	}
}

function SupplementLinkOptionText() {
	var optionText = "";

	optionText += '<div style="padding-top:3px; margin-top:3px; border-top:1px solid #000000">'
		+ '&raquo;&nbsp;<a class="ba" href="JavaScript:top.AddSupplementalLinkStart()">Supplemental Links</a>'
		+ '<br>&raquo;&nbsp;<a class="ba" href="../../../production_console/manageSuppLinks.php?bookId=' + bookId + '" target="_blank">Link Manager</a>'
		+ '</div>'
	
	return optionText;
}

function AddSupplementalLinkStart() {
	// show directions to the user
	ShowPopInWindow("Initiate Supplemental Link", "Click on a paragraph or figure caption on the page to initiate a new supplemental link. Click an existing link to edit or delete it. You will be given the option to have a link appear only in the left TOC, without having an icon appear in the main frame (in which case, where you click is irrelevant).", null, null, null, null, null, CancelStickyNoteEventHandler);

	main.document.body.onclick = PlaceSuppLink;
}

function CancelSuppLinkEventHandler() {
	main.document.body.onclick = null;
}

var suppLinkBeingPlaced = null;
function PlaceSuppLink(e) {
	// close pop-in window with instructions, if open
	if (PopInShowing() == "Initiate Supplemental Link") {
		ClosePopInWindow();
	}
	
	// Cancel the event handler
	CancelSuppLinkEventHandler();

	// Find the element we're in
	
	// Get the target of the mouse click (from quirksmode)
	var targ;
	if (!e) var e = main.window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	var originalTarg = targ;
	
	// We can only attach a supp link to paragraph or caption node
	// so look for such a node.
	var levelsUp = 0;
	// move up while...
	while (
			(targ != null && targ.tagName != "BODY") 	// we haven't gotten to BODY (we should never get to null)
			&& !(targ.tagName == "P" || 				// and the target isn't (a pargraph OR 
				(targ.tagName == "DIV" && targ.className == "caption"))		// a caption div)
	) {
		targ = targ.parentNode;
		++levelsUp;
	}
	
	// If we didn't find a P or caption div, tell the user
	if (targ == null || targ.tagName == 'BODY') {
		alert('The text you clicked on doesn\'t appear to be a paragraph or figure caption.  Try again, or close the pop-in window to cancel the operation.');

		// Return false to cancel further event bubbling
		return false;
	}
	
	// text and buttons for pop-in
	var text = "";
	var buttons = "";
	
	// If this is an existing supp link, we want to edit
	var id = originalTarg.id;
	if (id.indexOf("suppLink_") > -1) {
		var suppLinkId = id.replace(/suppLink_/, "");
		
		// Get suppLinks array for this section
		var slarr = suppLinks[SuppLinkObjectIndex(CurrentSectionFilename())];
		
		// find this link
		for (var i = 0; i < slarr.length; ++i) {
			suppLinkBeingPlaced = slarr[i];
			if (suppLinkBeingPlaced.suppLinkId == suppLinkId) {
				break;
			}
		}
		
		if (i == slarr.length) {
			alert("Couldn't find suppLink to edit");
		}
		
		text += "Change anything you wish below, then click 'Update Link' below to save changes. Click the 'Delete Link' button to delete the link.";
		
		buttons = "<input type='button' onclick='top.SubmitSuppLink()' value='Update Link'> &nbsp; <input type='button' onclick='top.DeleteSuppLink()' value='Delete Link'> &nbsp; <input type='button' onclick='top.ClosePopInWindow()' value='Cancel'>";

	// Otherwise we're making a new one
	} else {	
		// Initiate the object for this new item
		suppLinkBeingPlaced = new Object();
		
		// set suppLinkId to -1, since this is a new guy
		suppLinkBeingPlaced.suppLinkId = -1;
		
		// set the sectionFn to the current section
		suppLinkBeingPlaced.sectionFn = CurrentSectionFilename();

		// Determine what type the container is
		if (targ.tagName == "P") {
			suppLinkBeingPlaced.containerType = "P";
	
		} else if (targ.tagName == "DIV" && targ.className == "caption") {
			suppLinkBeingPlaced.containerType = "caption";
	
		} else {
			alert ('unknown error');
		}
		
		// Get the first 25 non-tag chars of the container, to locate it later
		var ih = ContainerLocatorTransform(targ.innerHTML);
		ih = ih.substr(0,25);
		suppLinkBeingPlaced.containerLocator = ih;
		
		suppLinkBeingPlaced.category = "";
		suppLinkBeingPlaced.title = "";
		suppLinkBeingPlaced.pageId = "";
		suppLinkBeingPlaced.url = "http://";
		suppLinkBeingPlaced.link = "";
		suppLinkBeingPlaced.quizId = "";
		suppLinkBeingPlaced.platform = "";

		text += "Enter the following information and click 'Create Link' to create a new supplemental link.";

		buttons = "<input type='button' onclick='top.SubmitSuppLink()' value='Create Link'> &nbsp; <input type='button' onclick='top.ClosePopInWindow()' value='Cancel'>";
	}
	
	// record the target el, so we can place later
	suppLinkBeingPlaced.targ = targ;
	
	// get the true background color, then set to yellow temporarily
	suppLinkBeingPlaced.backgroundColor = targ.style.backgroundColor;
	targ.style.backgroundColor = "#ff9";
	
	// KC: use dummyform for radio buttons
	text += '<form name=\"dummyform\">'
		+ '<table border="0" cellspacing="0" cellpadding="3">'
		+ "<tr><td style='font-size:12px; white-space:nowrap'>Category:</td><td style='font-size:12px; white-space:nowrap'><input type='text' style='width:200px' id='supp_category' value='" + suppLinkBeingPlaced.category + "'></td></tr>"
		+ "<tr><td style='font-size:12px; white-space:nowrap'>Title:</td><td style='font-size:12px; white-space:nowrap'><input type='text' style='width:350px' id='supp_title' value='" + suppLinkBeingPlaced.title + "'></td></tr>"
		+ "<tr><td style='font-size:12px; white-space:nowrap'>Portal PageId:</td><td style='font-size:12px; white-space:nowrap'><input type='text' style='width:200px' id='supp_pageId' value='" + suppLinkBeingPlaced.pageId + "'></td></tr>"
		+ "<tr><td style='font-size:12px; white-space:nowrap'>URL:</td><td style='font-size:12px; white-space:nowrap'><input type='text' style='width:350px' id='supp_url' value='" + suppLinkBeingPlaced.url + "'></td></tr>"
		+ "<tr><td style='font-size:12px; white-space:nowrap'>Quiz Session ID (if applicable):</td><td style='font-size:12px; white-space:nowrap'><input type='text' style='width:350px' id='supp_quizId' value='" + suppLinkBeingPlaced.quizId + "'></td></tr>"
		+ "<tr><td stle='font-size:12px; white-space:nowrap'>Links:</td><td style='font-size:12px; white-space:nowrap'><input type='radio' name='supp_link' id='supp_link' value='normal'";
	if (suppLinkBeingPlaced.link == 'normal' || suppLinkBeingPlaced.link == '') { // make this the default
		text += " checked";
	}
	text += "> Main frame, left TOC <input type='radio' name='supp_link' id='supp_link' value='leftonly'";
	if (suppLinkBeingPlaced.link == 'leftonly') {
		text += " checked";
	}
	text += "> Left TOC only  <input type='radio' name='supp_link' id='supp_link' value='mainonly'";
	if (suppLinkBeingPlaced.link == 'mainonly') {
		text += " checked"; 
	}
	text += "> Main only</td></tr>";
	
	// whether link should go in both ebook and portal, ebook only or portal only
	text += "<tr><td stle='font-size:12px; white-space:nowrap'>(Under construction) Should go in:</td><td style='font-size:12px; white-space:nowrap'><input type='radio' name='supp_platform' id='supp_platform' value='normal'";
	if (suppLinkBeingPlaced.platform == 'normal' || suppLinkBeingPlaced.platform == '') { // default for now will be ebook and portal
		text += " checked";
	}
	text += "> eBook and portal <input type='radio' name='supp_platform' id='supp_platform' value='ebook'";
	if (suppLinkBeingPlaced.platform == 'ebook') {
		text += " checked";
	}
	text += "> eBook only <input type='radio' name='supp_platform' id='supp_platform' value='portal'";
	if (suppLinkBeingPlaced.platform == 'portal') {
		text += " checked";
	}

	text += "> portal only</td><td>"
		+ "</table>"
		+ "<b>Note:</b> These input fields will be replaced with a Documentum item chooser soon"
		+ "<br><br>"
		+ buttons
		;

	text += "</form>";
	
	ShowPopInWindow("Supplemental Link Specs", text, null, 500, null, null, null, CancelSuppLink);
	
	// Return false to cancel further event bubbling
	return false;
}

function CancelSuppLink() {
	suppLinkBeingPlaced.targ.style.backgroundColor = suppLinkBeingPlaced.backgroundColor;
	
	suppLinkBeingPlaced = null;
}

function DeleteSuppLink() {
	// Set containerType to "delete", which will tell textfn.php to delete the link
	suppLinkBeingPlaced.containerType = "delete";
	SubmitSuppLink();
}

function SubmitSuppLink() {
	suppLinkBeingPlaced.category = main.document.getElementById('supp_category').value;
	suppLinkBeingPlaced.title = main.document.getElementById('supp_title').value;
	suppLinkBeingPlaced.pageId = main.document.getElementById('supp_pageId').value;
	suppLinkBeingPlaced.url = main.document.getElementById('supp_url').value;
	suppLinkBeingPlaced.quizId = main.document.getElementById('supp_quizId').value;
	var link =  main.document.dummyform.supp_link;
	var platform = main.document.dummyform.supp_platform;

	for (var i = 0; i < link.length; i++) {
   		if (link[i].checked) {
      			suppLinkBeingPlaced.link = link[i].value;
		}
      	}

	for (var i = 0; i < platform.length; i++) {
   		if (platform[i].checked) {
      			suppLinkBeingPlaced.platform = platform[i].value;
		}
      	}
	
	var s = "createSuppLink"
		+ "&suppLinkId=" + suppLinkBeingPlaced.suppLinkId
		+ "&sectionFn=" + suppLinkBeingPlaced.sectionFn
		+ "&containerType=" + suppLinkBeingPlaced.containerType
		+ "&containerLocator=" + escape(suppLinkBeingPlaced.containerLocator)
		+ "&category=" + escape(suppLinkBeingPlaced.category)
		+ "&title=" + escape(suppLinkBeingPlaced.title)
		+ "&pageId=" + escape(suppLinkBeingPlaced.pageId)
		+ "&url=" + escape(suppLinkBeingPlaced.url)
		+ "&link=" + suppLinkBeingPlaced.link
		+ "&quizId=" + suppLinkBeingPlaced.quizId
		+ "&platform=" + suppLinkBeingPlaced.platform
		;
	
	Servercom(s);
}

// This fn is called by textfn once the createSuppLink fn has been executed
function SubmitSuppLinkCallback(suppLinkId) {
	// Register the link
	RegisterSuppLink(suppLinkBeingPlaced, suppLinkId);
	
	// If we just deleted a link, we need to reload to get the ids right
	if (suppLinkBeingPlaced.containerType == 'delete') {
		alert("You will need to reload your browser now. Click OK and it'll reload.");
		top.location = urlStart + bookId + ".php";
		return;

	// Else we just need to redraw the page to draw the link
	} else {
		// Also we have to add it to the TOC
		// but only if "link" is "normal" or "leftonly", not "mainonly"
		if (suppLinkBeingPlaced.link != 'mainonly') {
			AddSuppToTOC(suppLinkBeingPlaced, chaptercontentsF);
		}
		
		// and set suppLinkBeingPlaced to null
		suppLinkBeingPlaced = null;
		
		LoadSection('reload');
	}
}

function RemoveSupplementalLinkStart() {

}

function ContainerLocatorTransform(s) {
	// take out other supp marker tags
	s = s.replace(/<div class=.modMarker.>.*?<\/div>/ig, "");
	s = s.replace(/<[\s\S]*?>/g, "");
	s = s.replace(/\W/g, "");
	s = s.toLowerCase();
	
	return s;
}

// For some reason IE doesn't like to let us set innerHTML sometimes
function SwapInnerHTMLForSupp(oldChild, InnerHTML) {        

	if (oldChild == null) {
	//	alert("oldChild is null");
	}

	// Get the parentNode
	var parentNode;
	if (oldChild != null) {
        	parentNode = oldChild.parentNode;                
	}

        // Create and insert a placeholder node before the oldChild
        var phNode = main.document.createElement('P');
        phNode.id = 'placeHolderXXX';
        phNode = parentNode.insertBefore(phNode, oldChild)

        // Remove the oldChild; stick it in newChild
        var newChild = parentNode.removeChild(oldChild);

	// The SwapInnerHTML upon which this function is based (eBookNotesAPI.js) does
	// some other stuff, that doesn't seem to be working in this case
	// So we'll just stick InnerHTML into the new phNode and call it quits -- this works in IE, Safari, FF
        phNode.innerHTML = InnerHTML;

}

