var COG_dragQualident;
var COG_dragLabel;

function COG_dragStart(dragLabel, dragQualident) {
	COG_dragLabel = dragLabel;
	COG_dragQualident = dragQualident;
	return false;
}

function COG_dragEnd(aboveLabel){
	if (!COG_dragQualident || COG_dragLabel == aboveLabel) {
		return false;
	}
	
	CFC_orderAtom(aboveLabel, COG_dragQualident);
	return false;
}


/**
 * Orders container specified in orderAtom above container specified in orderAbove.
 * @param orderAtom full qualident (.Sub. separated) of the container to order.
 * @param orderAbove parNum of the container to order above.
 * @param qualident qualident of the container list containing both containers.
 * @return
 */
function COG_orderAtom(orderAtom, orderAbove, qualident) {
	CFC_orderAtom(orderAtom);
	CFC_orderAtom(orderAbove, qualident);
}

//////////////////////////////////////////////////////////
// COOKIE METHODS
//////////////////////////////////////////////////////////

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

//////////////////////////////////////////////////////////
// USER'S HISTORY/LIBRARY
//////////////////////////////////////////////////////////

// globals
var libDocsLimit;						// limit of saved documents displayed
var linkCookiePrefix = "INVESTEC_LIBLINK_";		// library document cookie's key prefix
var histCookiePrefix = "INVESTEC_HISTLINK_";		// history cookie's key prefix
var journeyCookiePrefix = "INVESTEC_JOURNEYLINK_";	// journey cookie's key prefix

/**
 * Returns most recent cookie starting index from <code>document.cookie</code>
 * that begins with given prefix.
 * 
 * @param idx - string index to begin search from (backwards)
 * @param prefix - cookie's key prefix
 * @return starting index of most recent cookie
 */
function getCookieIdx(idx, prefix) {
	return document.cookie.substring(0, idx).lastIndexOf(prefix);
}

/**
 * Adds specified page to history using cookies.
 * 
 * @param title - title of the page shown in history as link name
 * @param url - url of the page
 * @param histLimit - limit of pages saved in history
 */
function addToHistory(title, url, histLimit) {
	url = escape(url);
	// create cookie for page, overwrite if cookie already exists
	if (readCookie(histCookiePrefix+url) != null) {
		eraseCookie(histCookiePrefix+url);
	}
	if (title.length == 0) {
		var lastDotIdx = url.lastIndexOf(".");

		title = url.substring(url.substring(0,lastDotIdx).lastIndexOf("/")+1,lastDotIdx);
	} else {
		title = escape(title);
	}
	createCookie(histCookiePrefix+url, title, null);
	
	// remove all cookies that overrun the limit
	var histCookieIdx = getCookieIdx(document.cookie.length, histCookiePrefix);
	var histLinks = new Array();
	var count = 0;
	var start;
	var end;
									
	while (histCookieIdx > -1) {
		if (++count > histLimit) {
			start = histCookieIdx;
			end = document.cookie.indexOf("=", start);

			histLinks.push(document.cookie.substring(start, end));
		}
		histCookieIdx = getCookieIdx(histCookieIdx, histCookiePrefix);
	}

	for (count = 0; count < histLinks.length; ++count) {
		eraseCookie(histLinks[count]);
	}
}

/**
 * Adds specified page to journey using cookies.
 * 
 * @param title - title of the page shown in journey as link name
 * @param url - url of the page
 */
function addToJourney(title, url) {
	url = escape(url);
	// create cookie for page, overwrite if cookie already exists
	if (readCookie(journeyCookiePrefix+url) != null) {
		eraseCookie(journeyCookiePrefix+url);
	}
	if (title.length == 0) {
		var lastDotIdx = url.lastIndexOf(".");
		title = url.substring(url.substring(0,lastDotIdx).lastIndexOf("/")+1,lastDotIdx);
	} 
	else {
		title = escape(title);
	}
	
	createCookie(journeyCookiePrefix+url, title, null);
}



/**
 * Outputs HTML with fixed number of links to saved pages.
 * 
 * @param docsLimit - limit of link to display
 */
function displayLimitedSavedDocs(docsLimit) {
	libDocsLimit = docsLimit; // make documents limit global
	
	var libLinks = new Array(); // place for holding library links
	var linkCookieIdx = document.cookie.length;

	var start;
	var end;
	
	var tmpend;
	var i;

	var addLink = false;

	// walk through cookies (from most recent) and add each valid cookie to libLinks
	for (i = 0; i < docsLimit; ++i) {
		linkCookieIdx = getCookieIdx(linkCookieIdx, linkCookiePrefix);
		if (linkCookieIdx != -1) {
			start = linkCookieIdx + linkCookiePrefix.length;
			tmpend = document.cookie.indexOf(";", start);
			end = (tmpend < 0) ? document.cookie.length : tmpend;

			// if below is false, cookie is malformed
			addLink = (start > 0 && end <= document.cookie.length) ? true : false;
		} else {
			break;
		}

		if (addLink) {
			libLinks.push(document.cookie.substring(start,end));
		}
	
		addLink = false;
	}

	var delim;

	var ret = "";

	// output HTML with links from libLinks
	if (libLinks.length > 0) {
		$("#savedDocsChunk #savedDocsContent").removeAttr("style");
		ret = ret + "<ul>";
	}
	for (i = 0; i < libLinks.length; ++i) {
		delim = libLinks[i].indexOf("=");
		if (delim != -1) { // if this is false, cookie is malformed
			ret = ret + "<li><a rel=\"a\" href=\""+unescape(libLinks[i].substring(0, delim))
				+"\" onclick=\"s_objectID='LIBRARY|" + unescape(libLinks[i].substring(0, delim)) + "';\">"+unescape(libLinks[i].substring(delim+1,libLinks[i].length))+"</a></li>";
		}
	}
	if (libLinks.length > 0) {
		ret = ret + "</ul>";
	}

	return ret;
}


/**
 * Refreshes library bookmark with recent pages.
 * 
 * @param recentLimit - limit of links to display
 */
function displayRecentPages(recentLimit) {
	var histCookieIdx = getCookieIdx(document.cookie.length, histCookiePrefix);

	if (recentLimit == null) {
		return;
	}
	
	var start;
	var end;
	
	var tmpend;
	var i = 0;	
			
	$("#recentPagesItemsContainer").empty();
	
	while (histCookieIdx > -1 && i < recentLimit) {
		start = histCookieIdx + histCookiePrefix.length;
		tmpend = document.cookie.indexOf(";", start);
		end = (tmpend < 0) ? document.cookie.length : tmpend;

		// if below is false, cookie is malformed
		if (start > 0 && end <= document.cookie.length) { // display library item
			cookie = document.cookie.substring(start,end);
			delim = cookie.indexOf("=");

			if (delim != -1) { // if this is false, cookie is malformed
				$("#recentPagesItemsContainer").append("<li><a rel=\"a\" class=\"libraryItem\" href=\""+unescape(cookie.substring(0, delim))
						+"\" onclick=\"s_objectID='HISTORY|"+ unescape(cookie.substring(0, delim)) + "';\">"+unescape(cookie.substring(delim+1,cookie.length))+"</a></li>");
			}
		}

		histCookieIdx = getCookieIdx(histCookieIdx, histCookiePrefix);
		++i;
	}
}

/**
 * Displays pages from history in the library.
 */
function displayHistoryPages() {
	var histCookieIdx = getCookieIdx(document.cookie.length, histCookiePrefix);
	
	var start;
	var end;
	
	var tmpend;	
			
	while (histCookieIdx > -1) {
		start = histCookieIdx + histCookiePrefix.length;
		tmpend = document.cookie.indexOf(";", start);
		end = (tmpend < 0) ? document.cookie.length : tmpend;

		// if below is false, cookie is malformed
		if (start > 0 && end <= document.cookie.length) { // display library item
			cookie = document.cookie.substring(start,end);
			delim = cookie.indexOf("=");

			if (delim != -1) { // if this is false, cookie is malformed

				$("#historyItemsContainer").append("<div class=\"libraryItemRow\">" 
				 + "<a class=\"libraryItem\" rel=\"a\" href=\""+unescape(cookie.substring(0, delim)) +"\" onclick=\"s_objectID='HISTORY|" + unescape(cookie.substring(0, delim)) + "';\">"+unescape(cookie.substring(delim+1,cookie.length))+"</a>"
				 + "</div>");

			}
		}

		histCookieIdx = getCookieIdx(histCookieIdx, histCookiePrefix);
	}
	
	$("div#historyItemsContainer div.libraryItemRow:nth-child(even)").addClass("shaded");
}

/**
 * Displays saved pages in the library.
 */
function displaySavedDocs() {
	var linkCookieIdx = getCookieIdx(document.cookie.length, linkCookiePrefix);

	var start;
	var end;	

	while (linkCookieIdx > -1) {
		start = linkCookieIdx + linkCookiePrefix.length;
		var tmpend = document.cookie.indexOf(";", start);
		end = (tmpend < 0) ? document.cookie.length : tmpend;

		// if below is false, cookie is malformed
		if (start > 0 && end <= document.cookie.length) { // display library item
			var cookie = document.cookie.substring(start,end);
			var delim = cookie.indexOf("=");

			if (delim != -1) { // if this is false, cookie is malformed
	
				$("#libraryItemsContainer").append("<div class=\"libraryItemRow\">" 
				 + "<a class=\"libraryItem\" rel=\"a\" href=\""+unescape(cookie.substring(0, delim))+"\" onclick=\"s_objectID='LIBRARY|" + unescape(cookie.substring(0, delim)) + "';\">"+unescape(cookie.substring(delim+1,cookie.length))+"</a>"
				 + "<a class=\"removeLibraryItem\" href=\"#\">"	+"Remove</a>" 
				 + "</div>");

			}
		}

		linkCookieIdx = getCookieIdx(linkCookieIdx, linkCookiePrefix);
	}
	
	$("div#libraryItemsContainer div.libraryItemRow:nth-child(even)").addClass("shaded");
}

/**
 * Get saved pages as a name list separated with |
 */
function getSavedDocs() {
	var linkCookieIdx = getCookieIdx(document.cookie.length, linkCookiePrefix);

	var start;
	var end;	
	
	var list = "";

	while (linkCookieIdx > -1) {
		start = linkCookieIdx + linkCookiePrefix.length;
		var tmpend = document.cookie.indexOf(";", start);
		end = (tmpend < 0) ? document.cookie.length : tmpend;
		// if below is false, cookie is malformed
		if (start > 0 && end <= document.cookie.length) { // display library item
			var cookie = document.cookie.substring(start,end);
			var delim = cookie.indexOf("=");

			if (delim != -1) { // if this is false, cookie is malformed
				
				var pageUrl = unescape(cookie.substring(0, delim))
				var pageName = unescape(cookie.substring(delim+1,cookie.length));
				list = list + pageName + "|";

			}
		}

		linkCookieIdx = getCookieIdx(linkCookieIdx, linkCookiePrefix);
	}

	// strip the last "|"
	return list.substring(0, list.length-1);
}

function getRecent5SavedDocs() {
	var list = getSavedDocs();
	
	var temp = new Array();
	temp = list.split('|');
	
	if (temp.length < 5) {
		return list;
	}
	else {
		var limitedList = "";
		var i;
		for (i=0;i<5;i++) {
			if (temp[i] && temp[i] !="") {
				if (i == 4) {
					limitedList = limitedList + temp[i];
				}
				else {
					limitedList = limitedList + temp[i] + "|";
				}
			}	
		}

		return limitedList;
	}
}

/**
 * Setups saved documents entries (on library page).
 */
function setupSavedDocs() {	
		$(".removeLibraryItem").unbind("click").click(function() {
			var name = $(this).siblings(".libraryItem").attr("href");			
			var cookieName = name.substring(name.indexOf(invjs.jspath), name.length); ;			
			var siblings = $(this).parent(".libraryItemRow").siblings(".libraryItemRow");
			
			eraseCookie(linkCookiePrefix+escape(cookieName));
		
			$(this).parent(".libraryItemRow").remove();
			siblings.removeClass("shaded");
			siblings.filter(":nth-child(even)").addClass("shaded");;
			$("#savedDocsChunk div#savedDocsContent ul li a[href='"+name+"']").parent("li").remove();
			
			// try to refill saved documents list in library menu
			var liCount = 0; // counter for <li> elements
			$("#savedDocsChunk div#savedDocsContent ul li").each(function(){
				++liCount;
			});

			if (liCount == 0) {
				$("#savedDocsChunk div#savedDocsContent").attr("style" ,"font-size:0px;line-height:0px");
			}

			if (liCount < libDocsLimit) {
				var count = libDocsLimit - liCount; // number of latest saved documents to display
				var i;

				// retrieve links from cookies
				var libLinks = new Array();
				var linkCookieIdx = document.cookie.length;
				
				var start;
				var end;

				var addLink = false;

				// skip first liCount cookies
				for (i = 0; i < liCount; ++i) {
					linkCookieIdx = getCookieIdx(linkCookieIdx, linkCookiePrefix);
				}

				for (i=0;i<count;++i) {
					linkCookieIdx = getCookieIdx(linkCookieIdx, linkCookiePrefix);
					if (linkCookieIdx != -1) {
						start = linkCookieIdx + linkCookiePrefix.length;
						var tmpend = document.cookie.indexOf(";", start);
						end = (tmpend < 0) ? document.cookie.length : tmpend;

						// if below is false, cookie is malformed
						addLink = (start > 0 && end <= document.cookie.length) ? true : false;
					} else {
						break;
					}

					if (addLink) {
						libLinks.push(document.cookie.substring(start, end));
					}
				
					addLink = false;
				}

				// display library links
				var delim;

				for (i = 0; i < libLinks.length; ++i) {
					delim = libLinks[i].indexOf("=");
					if (delim != -1) { // if this is false, cookie is malformed
						$("#savedDocsChunk div#savedDocsContent ul").append('<li><a rel="a" href="'+unescape(libLinks[i].substring(0, delim))+'" onclick="s_objectID=\'LIBRARY|' + unescape(libLinks[i].substring(0, delim)) + '\';">'
								+unescape(libLinks[i].substring(delim+1,libLinks[i].length))+'</a></li>');
					}
				}
															
			}
		});
}

/*
 * Cuts title to maximum number of characters. Can handle strings
 * with html entities.
 */
function shortenTitle(title) {
	var maxTitleLength = 24;
	var htmlEntityRegExp = new RegExp("&.+?;", "g");
	var entities = new Array();
	
	// get all HTML entities
	var result;
	while ((result=htmlEntityRegExp.exec(title))!=null) {
		entities.push(result);
	}
	
	if (entities.length == 0) {
		if (title.length > maxTitleLength) {
			return title.substring(0, maxTitleLength) + "...";
		}
		return title;
	}
	
	// strip title from HTML entities and shorten if limit exceeded
	var titleCopy = title.replace(/&.+?;/g,"&");
	
	if (titleCopy.length > maxTitleLength) {
		titleCopy = titleCopy.substring(0, maxTitleLength);
	}
	
	// fill stripped title with HTML entities
	var fromIdx = 0;
	var foundIdx = -1;
	var entityIdx = 0;
	var resultTitle = "";
	while((foundIdx=titleCopy.indexOf("&",fromIdx))>=0) {
		resultTitle += (titleCopy.substring(fromIdx,foundIdx) + entities[entityIdx++]);
		fromIdx=foundIdx+1;

	}
	
	resultTitle += titleCopy.substring(fromIdx, titleCopy.length) + "...";
	
	return resultTitle;
}

function trackDartDownload(link, dartSrc, dartType, dartCat) {
  var spotpix = new Image();
  spotpix.src = "http://fls.doubleclick.net/activityi;src=" + dartSrc + ";type=" + dartType+ ";cat=" + dartCat + ";ord=" + Math.random() * 1000000000000000000;  
  /*
	$(spotpix).ready(function () {
      if (link.target == "_blank") {
        setTimeout("window.open('" + link.href +"')",100);
      }
      else {
        setTimeout("document.location = '" + link.href +"'",100);
      }
  }); 
  */
}