//methods for handling the discover page
var gyzork =
{  
    debug : false,
    detailPageFormat : "modal",   // valid entries: inline (default) or modal
    
    modalWidthIndent : 90,  // Set modalWindow size to this number of pixels less than whole width
    modalHeightIndent : 90, // Set modalWindow size to this number of pixels less than whole height
    
    browseDisplayableLabel : "MOST RECENT",
    similarDisplayableLabel : "TOP RELATED",
    
    numberReturnedPerQuery : 40,
    scrollTrigger : 500,  // Number of pixels from bottom of scrollable area when more content will be requested.
    runStandalone : false,
    itemViewModeArea    : "", // leave blank
	itemViewModeCookieName :"itemViewMode",
    itemViewMode 		:  "list",
    noResultsMessage : "<h2>No Matches Found...</h2>",
    noGyzorksMessage : "<h2>No Gyzorks...</h2>",
    bookmarkIds : new Object,
    modalWindows : new Array(),
    currentModalDisplayed : -1,
    modalHandlingBackButton : false,
    closingModalWindow : false,
    numberResultsToDisplay : 5, // Numnber of results to display before allowing delay for scrolling to happen, before displaying more
    resultsDelay : 5,  // Number of milliseconds to wait before displaying next group of results

    numberToCount : 25,
    greenBulletCutoff : 0.9,
    yellowBulletCutoff : 0.7,
    redBulletCutoff : 0.4,
    findText : "",
    moreLikeThisUrl : "",
    
    // See bottom of this file for complete bookmarkServer description
    bookmarkServer : CTXT_ID + "/bookmarkQuery.html?queryOperation=BOOKMARK_IDS&format=JSON",
    
    wordCount : function(str)
    {
        str = str.trim();
        if (str.length == 0) {
            return 0;
        } else {
            var a = str.split(/\s+/g);
            return a.length;
        }
    },

	saveBulletStats : function(results)
	{
	    var greenTotal = 0;
        var yellowTotal = 0;
        var redTotal = 0;
        var keywordOnlyTotal = 0;
        var tsvOnlyTotal = 0;
        var tsvKeywordTotal = 0;
        var minScore = 0;
        var maxScore = 0;
	    
	    var numberFound = 0;
	    
		var lastItem = gyzork.numberToCount;
		if (lastItem > results.length)  lastItem = results.length;
		for (var i=0; i<lastItem; i++) {
		
            if ( (typeof results[i].combinedScore != "undefined") && (results[i].combinedScore > 0) ) {

                numberFound++;
                
            	var combinedScore = results[i].combinedScore.toString();
            	combinedScore = combinedScore.substring(0, combinedScore.indexOf(".")+5);

            	if (maxScore == 0) {
                	maxScore = combinedScore;
            	}
            	minScore = combinedScore;

            	if (combinedScore >= gyzork.greenBulletCutoff) {
					greenTotal++; 
				} else if (combinedScore >= gyzork.yellowBulletCutoff) {
                	yellowTotal++;
            	} else if (combinedScore >= gyzork.redBulletCutoff) {
                	redTotal++;
            	} 

            	if (results[i].tsvScore == 0) {
                	keywordOnlyTotal++;
            	} else if (results[i].keywordScore == 0) {
                	tsvOnlyTotal++;
            	} else {
            		tsvKeywordTotal++;
            	}
            }
        }
        
        var wordCount = gyzork.wordCount(parent.gyzork.findText);
        var type = getCookie("ccId");
        if ( type.indexOf("rss") == 0 ) 
        	type = type.substring(3);
        
        var sep = "\t";
        if (numberFound > 0) {
        	var prevStats = getCookie("bulletStats");
 	      	if (prevStats == null) {
 				prevStats = "";
//            	prevStats = "Type" + sep + "Green" + sep + "Yellow" + sep + "Red" + sep + "maxScore" + sep + "minScore" +                           
//                          sep + "findText" + sep + "findWordCount" + sep + "moreLikeThisUrl" + 
//                          sep + "KeywordOnly"+ sep + "tsvOnly" + sep + "tsv+keyword" + "\r\n"; 
            	setCookie("bulletStats", prevStats);
       		} else {
       		    prevStats = prevStats.substring(0, prevStats.length-2);
       		    setCookie("bulletStats", prevStats);
       		}
        	var stats = getCookie("bulletStats") + type + sep + greenTotal + sep + yellowTotal + sep + redTotal + sep + maxScore + sep + minScore +
                    	sep + parent.gyzork.findText + sep + wordCount + sep + parent.gyzork.moreLikeThisUrl + 
                    	sep + keywordOnlyTotal + sep + tsvOnlyTotal + sep + tsvKeywordTotal + "\r\n\r\n";

        	setCookie("bulletStats", stats);
        }
	},
    
	displayBulletStats : function()
	{
		var stats = getCookie("bulletStats");
		newWin = window.open ("", "statsWindow","status=1,toolbar=1,resizable=1");
		newWin.document.write("<html><body><pre>" + stats + "</pre></body></html>");
		newWin.document.close();
	},

	resizeDetailModalWindow : function()
	{
        if ( ! window.parent.modalWindow.showingDetailModal  )  return;
		
        var width = gyzork.getParentWindowWidth() - gyzork.modalWidthIndent;
        var height = gyzork.getParentWindowHeight() - gyzork.modalHeightIndent;

		window.parent.modalWindow.sizeIFrameToContent(height, width);
	},

	getParentWindowWidth: function() {
		var windowWidth=0;
		if (typeof(window.innerWidth) == 'number') {
			windowWidth = window.parent.innerWidth;
		}
		else if (window.parent.document.documentElement && window.parent.document.documentElement.clientWidth) {
			windowWidth = window.parent.document.documentElement.clientWidth;
		}
		else if (window.parent.document.body&&window.parent.document.body.clientWidth) {
			windowWidth = window.parent.document.body.clientWidth -15;  // fudge size to support IE
		}
		return windowWidth;
	},
	
	getParentWindowHeight: function() {
		var windowHeight=0;
		if (typeof(window.innerHeight) == 'number') {
			windowHeight = window.parent.innerHeight;
		}
		else if (window.parent.document.documentElement && window.parent.document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else if (window.parent.document.body&&window.parent.document.body.clientHeight){
			windowHeight = document.body.clientHeight;
		}
		return windowHeight;
	},
	
    showDetailAsModal : function(url)
    {
        var width = contentResizer.getWindowWidth() - gyzork.modalWidthIndent;
        var height = contentResizer.getWindowHeight() - gyzork.modalHeightIndent;
        
        var currentUrl = document.location.href;
		if (currentUrl.indexOf("modalDetail") == -1) {
			url += "&firstModalPage=true";
            var iframe = modalWindow.buildIFrame(width, height, url);
		    modalWindow.show(iframe,"#000000", width, height);
		    window.parent.modalWindow.showingDetailModal = true;
    		window.parent.gyzork.closingModalWindow = false;
    		window.parent.gyzork.modalHandlingBackButton = false;
    		window.parent.gyzork.modalWindows = new Array();
    		window.parent.gyzork.currentModalDisplayed = -1;
		} else {
			window.location.href = url
		}

		var pos = window.parent.gyzork.currentModalDisplayed + 1;
		window.parent.gyzork.modalWindows[pos] = url;
		window.parent.gyzork.currentModalDisplayed = pos;
		
		if (pos < (window.parent.gyzork.modalWindows.length-1) ) 
		    window.parent.gyzork.modalWindows = window.parent.gyzork.modalWindows.slice(0, pos+1);
    },

    updateModalWindowButtons : function()
    {
        var pos = window.parent.gyzork.currentModalDisplayed;
       
        var element = document.getElementById("previousModalWindow");
        if (typeof element != "undefined") {
        	if (pos > 0) {
            	element.href = "javascript:gyzork.displaySpecificModalWindow(" + (pos-1) + ");";
            	element.style.display = "block";
        	} else {
        		element.style.display = "none";
        	}
        }
        
        element = document.getElementById("nextModalWindow");
        if (typeof element != "undefined") {
        	if ( pos < (window.parent.gyzork.modalWindows.length-1) ) {
            	element.href = "javascript:gyzork.displaySpecificModalWindow(" + (pos+1) + ");";
            	element.style.display = "block";
        	} else {
        		element.style.display = "none";
        	}
        }
    },
    
    displaySpecificModalWindow : function(pos)
    {
    	if ( navigator.userAgent.toLowerCase().contains("safari") )  {
        	window.location.href = window.parent.gyzork.modalWindows[pos];
        	window.parent.gyzork.currentModalDisplayed = pos;
        } else {
        	if (pos < window.parent.gyzork.currentModalDisplayed) {
        		window.parent.gyzork.currentModalDisplay = pos;
        		history.go(-1);
        	} else {
        		window.parent.gyzork.currentModalDisplay = pos;
        		history.go(1);
        	}
        }
    },
    
    closeModalWindow : function()
    {
    	window.parent.gyzork.currentModalDisplayed = -1;
    	window.parent.gyzork.modalWindows = new Array();
        window.parent.modalWindow.close();        
		window.parent.modalWindow.showingDetailModal = false;
    },
    
    getQueryParameters : function()
    {
         var url = window.location.toString();
         
         var queryParameters = new Array();
         var queryString = "";
         
         if ( url.indexOf("?") > -1 ) {
             queryString = url.substring( url.indexOf("?")+1, url.length );
             queryString = queryString.replace(/#/g, "&");
         } else if ( url.indexOf("#") > -1 ) {
             queryString = url.substring( url.indexOf("#")+1, url.length );
         }
         
         if (queryString == "")  { return queryParameters; }
         
         var tmp = queryString.split("&");
         for (var i=0; i<tmp.length; i++) {
             var v = tmp[i];
             if (v.indexOf("=") > -1) {
                 var tmp2 = v.split("=");
                 queryParameters[tmp2[0]] = tmp2[1];
             }
         }
         
        return queryParameters;
    },
    
    toggleElement : function(id)
    {
        var element = document.getElementById(id);
        
        var indicator = "";
        
        if (! element ) {
            alert("toggleElement: Error getElementById for " + id);
        } else {
    
            if ( gyzork.isHidden( element ) ) {
                element.style.display = "block";
                indicator = "-";
            } else {
                element.style.display = "none";
                indicator = "+";
            }
        }
    
        var titleId = id + "-label";
        var titleElement = document.getElementById(titleId);
        if (typeof titleElement != "undefined") {
            titleElement.innerHTML = indicator
        }
    },
    
    removeAllChildren : function(id)
    {
        var cell = document.getElementById(id);
    
        if ( (typeof cell != "undefined") && ( cell.hasChildNodes() ) )
        {
            while ( cell.childNodes.length >= 1 )
            {
                cell.removeChild( cell.firstChild );       
            } 
        }
    },
    
    updateContent : function(node, id, field, value)
    {

		var content = document.getElementById(id);
		if (typeof content == "undefined")  return;
		
//        var content = new gyzork.findChild(node, id);

        try {
            if (typeof content != "undefined") {
                if (field == "innerHTML") 
                    content.innerHTML = value;
                else if (field == "style.display") 
                    content.style.display = value;
                else if (field == "onclick")
                    content.onclick= Function(value);
	            else if (field == "onmouseover") 
                   content.onmouseover = Function(value);
                else
                   content.setAttribute(field, value);
            }
        } 
        
        catch (e)
        {
//            alert("udpateContent: Content not found for id = " + id); 
        }
    },
    
    updateElement : function(elementId, value)
    {
        var element = document.getElementById( elementId );
        if (typeof element == "undefined") { return; }
        
        var i=0;
        
        element.innerHTML = value;   
    },

    isHidden : function(element) 
    {
        var status = false;
        
        if ( (typeof element != "undefined") && (element.style) ) {
            if ( (element.style.display == "none") || (element.style.display == "") )
                status = true;
        }
        
        return status;
    },
    
    
    findChild : function(container, id)
    {
    

	    if(container==null)
	    	return;
	    	
	    if(container.childNodes==null)
		    return;

	    if(container.id==id)   
		    return container;
	
	    for (var i = 0; i < container.childNodes.length; i++)
	    {  
		    if(id == container.childNodes[i].id)
			    return container.childNodes[i];
		}  

   	    for (var i = 0; i < container.childNodes.length; i++)
	    {
		    var cNode = gyzork.findChild(container.childNodes[i],id);
		    if(cNode!=null)
			    return cNode;
		}
	},
	
	displayLeftGutterCategoryInfo : function(pageView, breadcrumbs)
    {
	    var currentLocation = "";
        for(var i=0;i<breadcrumbs.length;i++)   
        {
            if (i > 0)  currentLocation += "&nbsp;&gt;&nbsp;\n";
        
            if ((i+1) == breadcrumbs.length)
                currentLocation += "      " + breadcrumbs[i].nodeLabel + "\n";
            else 
                currentLocation += "      <a href=\"javascript:void(0);\" onclick=\"" + pageView + ".navigationChange(" + 
            	                          breadcrumbs[i].categoryId + ")\">" + breadcrumbs[i].nodeLabel + "</a>\n";
        }
	    document.getElementById('currentNavLocation').innerHTML = currentLocation;


        var children = breadcrumbs[breadcrumbs.length-1].children;
        var childrenWithArticles = new Array();
        var currentNode = "";
        var k = 0;
        for (var i=0; i<children.length; i++) 
            if (children[i].count > 0)  childrenWithArticles[k++] = children[i];
     
        // If you are at the end of the node, move up one level and display children (with the current node un-selectable), if there is more than 1 child at this level.
        if ( (childrenWithArticles.length == 0) && (breadcrumbs.length > 1) ) {
    
            children = breadcrumbs[breadcrumbs.length-2].children;
            currentNode = breadcrumbs[breadcrumbs.length-1].nodeLabel;
    
            childrenWithArticles = new Array();
            var k = 0;
            for (var i=0; i<children.length; i++) 
                if (children[i].count > 0)  childrenWithArticles[k++] = children[i];
              
            if (childrenWithArticles.length <= 1) {
                childrenWithArticles = new Array();
                currentNode = "";
            }
        }
    
        // clear past navigation
        var navChildren = document.getElementById('list').childNodes;
	    // element 0 is the template, don't delete it
	    for(var x=navChildren.length;x>1;x--)
	    {
    		var item = navChildren[x-1];
		    item.parentNode.removeChild(item);
	    }    
        for (var i=0; i<childrenWithArticles.length; i++) 
        {
            var child = childrenWithArticles[i];
            
            // If you moved up one level, then display current node but make "un-selectable"
		    var template= navChildren[0];
            var navItem = template.cloneNode(true);
            navItem.id='';
		    navItem.className='';
		    var navHTML = "";
            if ( currentNode == child.nodeLabel ) {
//                navHTML += child.nodeLabel + " (" + child.count + ")";
                navHTML += child.nodeLabel;
            } else { 
//                navHTML+= '<a href="javascript:void(0);" onclick="' + pageView + '.navigationChange(' + 
//               		 	  child.contentId + ')">' + child.nodeLabel + ' (' + child.count + ')</a>';
                navHTML+= '<a href="javascript:void(0);" onclick="' + pageView + '.navigationChange(' + 
               		 	  child.categoryId + ')">' + child.nodeLabel + '</a>';
            }
		    navItem.innerHTML = navHTML;
		    template.parentNode.appendChild(navItem);
        }
    },
    
    createCategoryData : function(pageView, cats)
    {
	    var htmlCats = new Array();
        if(cats!=null)
        {
		    for(var i=0;i<cats.length;i++)
		    {
		        var label = "";
		        var id = -1;
		        
		        if (typeof cats[i].label == "undefined") {
                            // Used on discover page
		            label = cats[i].fullLabel;
		            id = cats[i].categoryId;
		        } else {
                            // used on bookmarks page
		            label = cats[i].label;
		            id = cats[i].dimensionId;
		        }

		        var html = "<a style='color:#993399' href='javascript:" + pageView + ".selectCategory(" + id + ");'>" + label + "</a>";
			    htmlCats.push(html);
		    }
		    
		    return htmlCats.join("&nbsp;&nbsp;|&nbsp;&nbsp;")
        }
        
        return "";
    },
    
    createResultItemElement : function(pageView, result, itemNumber,node)
    {
        if ( typeof result == "undefined" ) { return ""; }

        bulletString = "";
        bulletKeywordString = "";
        if ( (typeof result.combinedScore != "undefined") && (result.combinedScore > 0) ) {

            var combinedScore = result.combinedScore.toString();
            combinedScore = combinedScore.substring(0, combinedScore.indexOf(".")+5);

            if (combinedScore >= gyzork.greenBulletCutoff) {
	        	bulletString = "<a href=\"javascript:void(0);\" title=\"Score = " + combinedScore + "\"><img src=\"theme/images/circle-green.jpg\" border=\"0\" /> ";
            } else if (combinedScore >= gyzork.yellowBulletCutoff) {
	        	bulletString = "<a href=\"javascript:void(0);\" title=\"Score = " + combinedScore + "\"><img src=\"theme/images/circle-yellow.jpg\" border=\"0\" /> ";
            } else if (combinedScore >= gyzork.redBulletCutoff) {
	        	bulletString = "<a href=\"javascript:void(0);\" title=\"Score = " + combinedScore + "\"><img src=\"theme/images/circle-red.jpg\" border=\"0\" /> ";
            } else {
	        	bulletString = "<a href=\"javascript:void(0);\" title=\"Score = " + combinedScore + "\"><img src=\"theme/images/circle-black.jpg\" border=\"0\" /> ";
            }

            if (result.tsvScore == 0) {
                bulletKeywordString = "-";
            }
        }

        node.id = "results-item-" + itemNumber;
        node.style.display = "block";
		if(typeof result.read != "undefined"  && ! result.read)
		{
    	    node.className = "resultsItemContainerNotRead";
			node.onclick   = Function("gyzork.markAsRead(this,"+result.contentId+");");
		}

		gyzork.updateContent(node, "results-title-container-X", "id", "results-title-container-" + itemNumber);

		var element = document.getElementById("results-data-toggler-X");
		if (typeof element != "undefined") {
        	element.onclick = "gyzork.slideOut(this);";
        	element.id = "results-data-toggler-" + itemNumber;
        }

        gyzork.updateContent(node, "results-data-label-X", "id", "results-data-label-" + itemNumber);

 		element = document.getElementById("results-data-title-X");
 		if (typeof element != "undefined") {
           	element.onclick = "gyzork.slideOut(this);";
        	element.innerHTML = result.title + '<span class="titleDescriptionText" >'+ ' -' + bulletKeywordString + " "  +result.snippet+'</span>';
        	element.id = "results-data-title-" + itemNumber;
        }

		element = document.getElementById("results-article-age-X");
		if (typeof element != "undefined") {
			element.onclick = "gyzork.slideOut(this);";
        	element.innerHTML = bulletString + result.articleAgeLabel;
        	element.id = "results-article-age-" + itemNumber;
        }
		
		element = document.getElementById("results-data-chevron-X");
		if (typeof element != "undefined") {
        	element.href = result.link;
        	element.id = "results-data-chevron-"+ itemNumber;
        }

        gyzork.updateContent(node, "results-data-X", "id", "results-data-" + itemNumber);

		element = document.getElementById("results-data-categories-X");
		if (typeof element != "undefined") {
			element.innerHTML = gyzork.createCategoryData( pageView, result.category );
        	element.id = "results-data-categories-"+itemNumber;
        }

		element = document.getElementById("results-data-url-X");
		if (typeof element != "undefined") {
			element.innerHTML = result.link;
        	element.href = result.link;
        	element.id = "results-data-url-" + itemNumber;
        }

		element = document.getElementById("results-data-source-X");
		if (typeof element != "undefined") {
			element.href = result.sourceLink;
        	element.innerHTML = result.source;
        	element.id = "results-data-source-"+itemNumber;
        }

		element = document.getElementById("results-data-updated-X");
		if (typeof element != "undefined") {
			element.innerHTML = result.updated;
        	element.id = "results-data-updated-"+ itemNumber;
        }

        gyzork.updateContent(node, "results-data-menu-X", "id", "results-data-menu-"+itemNumber);

		element = document.getElementById("results-data-related-X");
		if (typeof element != "undefined") {
        	var href = CTXT_ID + "/detail.html?contentId=" + result.contentId;
        	if (gyzork.detailPageFormat == "modal") 
            	href = "javascript:gyzork.showDetailAsModal('" + CTXT_ID + "/modalDetail.html?contentId=" + result.contentId + 
            		   "&SOURCE_CC_ID=" + gyzork.getContentCollectionId() + "');";
        	element.href = href;

	        var label = "More " + gyzork.getContentCollectionLabel() + " like this...";
    	    element.innerHTML = label;
        	element.id = "results-data-related-"+itemNumber;
        }
        
        element = document.getElementById("gzorkItContainer-X");
        if (typeof element != "undefined") {
        	var html = "";        
        	if ( discover.alreadyGyzorkd(result.contentId) ) 
           		html = "       <span class=\"gyzorkbutton\" id=\"off\">Gyzork'd</span>\n";
        	else if (authenticated) 
            	html = 	"       <span class=\"gyzorkbutton\" id=\"on\">\n" +
                   		"          <a href='javascript:void(0)' id='gyzorkButton-" + itemNumber + "' onclick=\"bookmark.doIt(this,'" + result.contentId + "', false, false, 'gyzorkButton-" + itemNumber + "');\">Gyzork-it</a>\n" +
                   		"       </span>\n";
        	else 
            	html =  "       <span class=\"gyzorkbutton\" id=\"on\">\n" +
                  		"          <a href='javascript:void(0)' id='gyzorkButton-" + itemNumber + "' onclick=\"bookmark.doIt(this," + result.contentId + ", false, false, 'gyzorkButton-" + itemNumber + "');\">Gyzork-it</a>\n" +
                  		"       </span>\n";
        	element.innerHTML = html;
        	element.id = "gzorkItContainer-"+itemNumber;
        }      
  
        return node;
    },
    
    createBookmarkResultItemElement : function(pageView, template, bm, itemNumber)
    {
        if (typeof itemNumber == "undefined")  itemNumber = bm.bookmarkId;
        
	    template.style.display='block';		

	    template.id = "results-item-" + itemNumber;

	    var source = document.getElementById("results-data-source-X");		
	    source.innerHTML = bm.contentSource;
    	source.href = bm.contentSourceLink;
    	source.id='results-data-source-'+itemNumber;

        var date = document.getElementById("results-data-bookmarked-X");
        date.innerHTML=bm.bookmarkDate;
	    date.id='results-data-bookmarked-'+itemNumber;
  
  		var element = document.getElementById("results-data-categories-X");
  		if (typeof element != "undefined") {
  			element.innerHTML = gyzork.createCategoryData( pageView, bm.categories );
        	element.id = "results-data-categories-"+itemNumber;
        }
	    
	    element = document.getElementById("results-data-toggler-X");
	    if (typeof element != "undefined") {
	    	element.onclick = "gyzork.slideOut(this);";
        	element.id = "results-data-toggler-" + itemNumber;
        }

        gyzork.updateContent(template, "results-data-label-X", "id", "results-data-label-" + itemNumber);

		element = document.getElementById("results-data-url-X");
		if (typeof element != "undefined") {
			element.innerHTML = bm.url;
        	element.href = bm.url;
        	element.id = "results-data-url-" + itemNumber;
        }
       
       	element = document.getElementById("results-data-title-X");
       	if (typeof element != "undefined") {  
           	element.onclick = "gyzork.slideOut(this);";        
        	element.innerHTML = bm.title + '<span class="titleDescriptionText" >'+ ' - ' +bm.notes+'</span>';
        	element.id = "results-data-title-" + itemNumber; 
        } 
         
        gyzork.updateContent(template, "results-title-container-X", "id", "results-title-container-" + itemNumber);    

		element = document.getElementById("results-data-chevron-X");
		if (typeof element != "undefined") {
			element.href = bm.url;
        	element.id = "results-data-chevron-"+ itemNumber;
        }
                
        gyzork.updateContent(template, "results-data-X", "id", "results-data-" + itemNumber);

		element = document.getElementById("results-data-related-X");
		if (typeof element != "undefined") {       
        	var href = CTXT_ID + "/detail.html?bookmarkId=" + bm.bookmarkId + "&contentId=" + bm.contentId;
        	if (gyzork.detailPageFormat == "modal") 
            	href = "javascript:gyzork.showDetailAsModal('" + CTXT_ID + "/modalDetail.html?bookmarkId=" + bm.bookmarkId + 
                       "&contentId=" + bm.contentId + "&SOURCE_CC_ID=" + bm.contentCollectionId + "');";
        	element.href = href;
        	
        	var label = "View Related " + bm.contentCollectionId;
        	element.innerHTML = label;
        	element.id = "results-data-related-"+itemNumber;
        }
        	
        var contentCollectionId = bm.contentCollectionId;
		if (window.location.href.indexOf("modalDetail.html") > -1)  contentCollectionId = gyzork.getContentCollectionId();
		
		element = document.getElementById('results-rss-X');		
		if (typeof element != "undefined") {
			// i did this since the interface expected a param here - the bm defines the collectionid, not the url
	    	element.href = gyzorkBaseUrl + "bookmark/" + contentCollectionId + "/" + bm.bookmarkId + "?format=rss";
	    	element.id = "results-rss-"+ itemNumber;
	    }
	    
	    return template;   
    },
    
    
    handleItemDisplay :  function(node)
    {
    	if(gyzork.itemViewMode == 'detail')
    		gyzork.slideOut(node,50);		
    	else
    		gyzork.slideIn(node,50);		
    },
    
    checkNumberOfResults : function(type) 
    {       
        var resultsContainer = document.getElementById("resultsContainer");
        if (typeof resultsContainer != "undefined") {
            if (resultsContainer.scrollHeight <= resultsContainer.offsetHeight) 
                eval(type + ".getMoreResults()");
        }
    },

    hideAll : function()
    {
        var cell = document.getElementById("results");
        if ( cell.hasChildNodes() )
        {
            for (var i=0; i<cell.childNodes.length; i++)
            {
				if(typeof cell.childNodes[i].id =="undefined")
					continue;
				gyzork.slideIn(cell.childNodes[i],50);					
            } 
        }   
        if(document.getElementById('detailView'))document.getElementById('detailView').style.textDecoration= 'none';
        if(document.getElementById('listView'))document.getElementById('listView').style.textDecoration= 'underline';

        gyzork.itemViewMode = 'list';
        setCookie(this.itemViewModeCookieName+this.itemViewModeArea,'list',365); 
    },

    showAll : function()
    {  
        var cell = document.getElementById("results");
        if ( cell.hasChildNodes() )
        {
            for (var i=0; i<cell.childNodes.length; i++)
            {
				if(typeof cell.childNodes[i].id =="undefined")
					continue;
				gyzork.slideOut(cell.childNodes[i],50);					
            } 
        }  
        if(document.getElementById('detailView'))document.getElementById('detailView').style.textDecoration= 'underline';
        if(document.getElementById('listView'))document.getElementById('listView').style.textDecoration= 'none';
        
		setCookie(this.itemViewModeCookieName+this.itemViewModeArea,'detail',365);
        gyzork.itemViewMode = 'detail';
    },
    
    slideOut : function(area,delay)
    {
        if (typeof area == "undefined")  return;
     	if(typeof delay =="undefined")
     		delay=200;
     		
        var items = area.id.split("-");
	    var id = items[items.length-1];

		var node = document.getElementById("results-item-"+id);
		if (typeof node != "undefined") {
        	gyzork.updateContent(node, "results-data-toggler-" + id, "onclick", "gyzork.slideIn(this);");
        	gyzork.updateContent(node, "results-data-label-" + id, "innerHTML", "-");
        	gyzork.updateContent(node, "results-data-title-" + id, "onclick", "gyzork.slideIn(this);");
        	gyzork.updateContent(node, "results-article-age-" + id, "onclick", "gyzork.slideIn(this);");
        }
        
        // show the description - unfortunately we need to do it this way since we are altering specific values
        node = new gyzork.findChild(node,"results-title-container-"+id);
		if (typeof node != "undefined")
		{
		    try {
	            node.style.height="auto";
	            node.style.overflow="visible";
	            node.style.whiteSpace="inherit";
	        }
	        catch (e) { }
		} 	    
	    $("#results-data-" + id).slideDown(delay);
	    area.mouseover=null;
    },
    
    slideIn : function(area,delay,page)
    {
        if (typeof area == "undefined")  return;
     	if(typeof delay =="undefined")
     		delay=200;
     		
     	if (typeof page == "undefined")  page = "gyzork";
        
        var items = area.id.split("-");
	    var id = items[items.length-1];

		var node = document.getElementById("results-item-"+id);
		if (typeof node != "undefined") {
        	gyzork.updateContent(node, "results-data-toggler-" + id, "onclick", page + ".slideOut(this);");
        	gyzork.updateContent(node, "results-data-label-" + id, "innerHTML", "+");
        	gyzork.updateContent(node, "results-data-title-" + id, "onclick", page + ".slideOut(this);");
        	gyzork.updateContent(node, "results-article-age-" + id, "onclick", "gyzork.slideOut(this);");
        }
        
        node = new gyzork.findChild(node,"results-title-container-"+id);
		if (typeof node != "undefined")
		{
		    try {
	        	// the following need to match .singleLineContainer within global.css
	            node.style.height="1.5em";
	            node.style.overflow="hidden";
	        }
	        catch (e) {}
		} 	    
	    $("#results-data-" + id).slideUp(delay);
	     
    },
    showBookmarks : function() 
    {  
         if (authenticated) {
             document.location.href = CTXT_ID +'/gyzorks.html';
         } else {
             authentication.showLogin(this, "document.location.href = '"+CTXT_ID +"/gyzorks.html'");
         }
    },
    establishItemViewMode : function(area, defaultMode)
    {
	 	gyzork.itemViewModeArea = area;
	 
	    // initialize the list view
	    if(typeof defaultMode =='undefined' || defaultMode==null)
	    	defaultMode = "list";
	    
		gyzork.itemViewMode = getCookie(gyzork.itemViewModeCookieName+""+ gyzork.itemViewModeArea);
    	if(typeof gyzork.itemViewMode =='undefined' || gyzork.itemViewMode ==null)
    		gyzork.itemViewMode = defaultMode;
    	
    	if(gyzork.itemViewMode=="detail")
    		gyzork.showAll();
		else
			gyzork.hideAll();
    },
    
    selectType : function(type)
    {
        parent.gyzork.findText = "";

        if (type == "find") 
        {
            gyzork.updateContent(document, "browse-selector", "style.display", "block");
            gyzork.updateContent(document, "find-selector", "style.display", "none");
            gyzork.updateContent(document, "search-box-container", "style.display", "block");
        } 
        else 
        {
            gyzork.updateContent(document, "browse-selector", "style.display", "none");
            gyzork.updateContent(document, "find-selector", "style.display", "block");
            gyzork.updateContent(document, "search-box-container", "style.display", "none");
        }
    },
    
    updateResultCounts : function(type, count)
    {
        if (type == "count")  {
            gyzork.updateContent(document, "displayedCount", "innerHTML", count);
       
        	var element = document.getElementById("displayableCount");
        	var currentTotal = element.innerHTML;
        	if (currentTotal < count)  element.innerHTML = count;    
        }
        
        if (type == "total")
            gyzork.updateContent(document, "displayableCount", "innerHTML", count);
    },
    
    markAsRead : function(container, contentId)
    {
    	container.className="resultsItemContainer";
		container.onclick=null;
    	// just fire and forget for this call
    	var call = CTXT_ID + '/articleInteraction.html?format=json&contentId='+contentId+'&collectionId='
    			+gyzork.getContentCollectionId();
    	new XHR( {method: 'get', async: true } ).send(call);    
    },
    
    setContentCollection : function(ccId)
    {
    	setCookie("ccId",ccId,365);

		gyzork.setupContentCollectionControl(); 	
    },
    
    handleContentChange : function(selectBox)
    {
    	var ccId = selectBox.value;
    	setCookie("ccId",ccId,365);
    	
    	var location = window.location.href;
    	var pos = location.indexOf("#");
    	if (pos > -1) 
    		location = window.location.href.substring(0, pos);

    	if (location.indexOf("modalDetail") > -1)
    		location += "&TARGET_CC_ID=" + ccId;
    	
   		window.location.href = location;
    },
    
    getContentCollectionLabel : function(id) 
    {
    	if (typeof id == "undefined")  id = gyzork.getContentCollectionId();
    	
    	var ccLabels = Json.evaluate(CC_LABELS);
    	
    	return ccLabels[id];
    },
    
    getContentCollectionId : function()
    {
 		var ccId = getCookie("ccId");
 		if(typeof ccId =='undefined' || ccId==null)
 		{
 			ccId = DEFAULT_CC_ID;		
 			setCookie("ccId",ccId,365);
 		}
		return ccId;
    },
    
 	setupContentCollectionControl : function()
 	{
		var control = document.getElementById("contentCollections");
		var ccId = gyzork.getContentCollectionId();
		var setSelected = false;
		for(var x=0;x<control.options.length;x++)
		{
			if(control.options[x].value==ccId){
				control.options[x].selected = true;
				setSelected = true;
			}
		}
		if(!setSelected) // default to the first which was set within 
		{
			setCookie("ccId",DEFAULT_CC_ID,365);
		}
    },
    
    searchBoxOnFocus : function()
    {
    	var element = document.getElementById("findSimilarId");
    	if (element.value == "Enter words or phrases...")
    		element.value = "";
    }
}

function getCookie(name)
{
	if (document.cookie.length==0)
		return null;
	var start=document.cookie.indexOf(name + "=");

  	if(start==-1)
  		return null;  	

    start= start + name.length+1; 
    var end =document.cookie.indexOf(";",start);
    if (end==-1) 
    	end=document.cookie.length;

	var val = unescape(document.cookie.substring(start,end));
	return val
}

function setCookie(name,value,expiredays)
{

	var expires =new Date();
	expires.setDate(expires.getDate()+expiredays);
	var cookie = name + "=" +escape(value) + 
					((expiredays==null) ?"" :";expires="+expires.toGMTString())+ ";path=/"; 
	
	document.cookie= cookie;
}




