﻿/******DECLARATIONS***************************/
var textXmlMime = "text/xml";
var responseValueTagName = "string";
var HEAD_HTML, FOOT_HTML;
var req2;        //THE XML REQUEST OBJECT
var itemlist2;   //the list of strings to fill the dropdown
var _clientid;  //the client id to the aspx control
var _hiddenid;  //client id of the hiddenfield for the search term

var timerID = null; 
var timerOn = false; 
var timecount = 250;   // Change this to the time delay that you desire 
var ob = null;

function fteventcollection(num, topicnum)
{
    TabMe(ob, num);
    GetNextTopic(topicnum);
}

function fttimerstart(theob,num,topicnum)
{
    ob = theob;
	if (timerOn == false) { 
		timerID=setTimeout( "fteventcollection(" + num + "," + topicnum + ")" , timecount); 
		timerOn = true; 
	} 
}

function fttimerclear()
{
	if (timerOn) { 
		clearTimeout(timerID); 
		timerID = null; 
		timerOn = false; 
	} 
}

/**********string builders**************/

//create req2uest url to WCF service
function createAFRequestUrl2(topicid) {

    return "/webservices/FeaturedTopic.svc/GetRollOverTopicOnject?topicID=" + topicid;
}

//create the dropdown's div client id
function createDivId(clientid)
{
    return clientid + "_featuredTopic";
}

//create the SOAP envelope to the ASMX service
function createEnvelope(startswith,count)
{
    return '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><GetAutoFillList xmlns="http://tempuri.org/"><prefixText>' + startswith + '</prefixText><count>' + count + '</count></GetAutoFillList></soap12:Body></soap12:Envelope>';
}
/************UI FUNCTIONS******************/

//handle up, down and enter keys
function RegisterClient(clientid)
{
    _clientid = clientid;
}

/*************UTILS**********************/
function getElementsByClass(searchClass,tag) {
  
  var classElements = new Array();
  var els = document.getElementsByTagName(tag);
  var elsLen = els.length;
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( searchClass == els[i].className ) {
      classElements[j] = els[i];
      j++;
    }
  }
  
return classElements;

}

function TabMe(ob, fromleft)
{
    if(ob.className != "offbehind")
        return;
    var onbc = getElementsByClass("onbehind","*");
    for (var idx in onbc ) { onbc[idx].className = "offbehind"; }
    
    var onbcf = getElementsByClass("onbehindfirst","*");
    for (var idx in onbcf ) { onbcf[idx].className = "offbehind"; }
    
    var onbcl = getElementsByClass("onbehindlast","*");
    for (var idx in onbcl ) { onbcl[idx].className = "offbehind"; }
    
    var offbc = getElementsByClass("offbehind","*");
    if(offbc[0] == ob) { ob.className = "onbehindfirst"; }
    else if(offbc[9] == ob) { ob.className = "onbehindlast"; }
    else { ob.className = "onbehind"; }
    
    var tabbottom = getElementsByClass("bottomzone","span");
    if(tabbottom.length <= 0) { tabbottom = getElementsByClass("bottomzoneleft","span"); if(tabbottom.length <= 0) { tabbottom = getElementsByClass("bottomzoneright","span"); } }
    if(tabbottom.length <= 0) { alert("Something's wrong... Couldn't find the bottomzone"); }
    if(fromleft == 0) { tabbottom[0].className = "bottomzoneleft"; }
    else if(fromleft == 9) { tabbottom[0].className = "bottomzoneright"; }
    else { tabbottom[0].className = "bottomzone"; }
    var leftoffset = fromleft * 94;
    tabbottom[0].style.left = leftoffset + "px";
}

//get the event source (cross browser)
function getEventSource(ev)
{
	var res = null;
    if(ev && ev.target)			//Moz
    {
        res = ev.target;
    }
	
	if(!res && window.event)	//IE
    {
        res = window.event.srcElement;
    }
    
    return res;
}

//reset variables
function resetAutoFill()
{
    tbstr = "";
    req2 = null;
    pos = -1;
}

//create an XMLHTTPRequest (cross browser)
function createrequest2()
{
    var ua = navigator.userAgent.toLowerCase();
   if (!window.ActiveXObject)
     req2 = new XMLHttpRequest();
   else if (ua.indexOf('msie 5') == -1)
     req2 = new ActiveXObject("Msxml2.XMLHTTP");
   else
     req2 = new ActiveXObject("Microsoft.XMLHTTP");
}

//create an XMLDocument (cross browser)
function createXmlDoc()
{
    var doc;
    
        try
        {
            doc = new DOMParser();
        }
        catch(e)
        {
            doc = new ActiveXObject("Microsoft.XMLDOM");
        }
        
        if(doc)
            doc.async=false;
        
    return doc;
}

//get event's keycode (cross browser)
function getKeyCode(e)
{
    var key;
    if(window.event)
        key = window.event.keyCode; 
    else
         key = e.which;
    return key;
}


//send the akax req2uest to update the list 
//based on the current searchbox value
function GetNextTopic(topicid)
{     
    //get req2uest
    createrequest2();
    
    if(!req2)
        return;
        
    //open the req2uest to the web service
    req2.open("GET",createAFRequestUrl2(topicid));
      
    //set up onreadystatechange event
    req2.onreadystatechange = handleReqProgress2;
    
    //send the req2uest
    req2.send(null);
    
    //hack for async calls in FF without firebug or when firebug's dissabled
    try //breaks in IE 
    {
        if(req2.onreadystatechange == null)
            handleReqProgress2();
    }
    catch(e)
    {}
}

//handle the onreadystatechange event of the xmlhttpreq2uest
function handleReqProgress2()
{
    //we only care when it's done
    if(!req2 || req2.readyState != 4 )
        return;
    
    //make sure there's response text
    if(req2.responseText)
    {
        //get the returned object from the response's json
        //the list is actually a member of the object
        var _list  = eval('(' + req2.responseText + ')');
        //make sure there's a list
        if(_list && _list.d)
            itemlist2 = _list.d; //assign to itemlist2
        else
            itemlist2 = null;    //or make sure its empty
    }
    
    //write results or hide the list
    if(itemlist2)
    {
        writeList2();
    }
}

//write contents of itemlist2 to the dropdown list
function writeList2()
{
    if(itemlist2)
    {
        SetHeroImage(itemlist2.HeroUrl, "Learn more about " + itemlist2.PreferredName);
        SetHeroLink(itemlist2.TopicUrl);
        SetHeroImageCaption(itemlist2.HeroTitle + ". " + itemlist2.HeroSource + " (" + itemlist2.HeroAttribution + ")");
        SetTopicTitle("<a href=\""+itemlist2.TopicUrl+"\">"+itemlist2.PreferredName+"</a>");
        
        var byline = "";
        if(itemlist2.DocPublication)
            byline += itemlist2.DocPublication;
        SetTopicText("<p><strong>" + byline + "&nbsp;</strong></p>" + itemlist2.Text + "  <a class=\"fwb\" href=\"" + itemlist2.DocUrl + "\">Read more</a>");
        SetRelatedTopicsList(itemlist2.RelatedTopics);
    }
}

/*-----     setting controls html --------------*/

function SetHeroImage(url, alt)
{
    var hi = document.getElementById(FT_IMG_HERO);
    if (!hi)
        return;
    hi.src = url + '&height=225&width=225';
    hi.alt = alt;
    hi.title = alt;
}

function SetHeroLink(url)
{
    var hl = document.getElementById(FT_LINK_HERO);
    if(!hl)
        return;
    hl.href = url;
}

function SetHeroImageCaption(text)
{
    var hic = document.getElementById(FT_P_HEROCAPTION);
    if(!hic)
        return;
    hic.innerHTML = text;
}

function SetTopicTitle(title)
{
    var ttl = document.getElementById(FT_DIV_TITLE);
    if (!ttl)
        return;
    ttl.innerHTML = title;
}

function SetTopicText(text)
{
    var txt = document.getElementById(FT_DIV_TEXT);
    if (!txt)
        return;
    txt.innerHTML = text;
}

function SetRelatedTopicsList(rtlist)
{
    var lst = document.getElementById(FT_DIV_RT);
    if (!lst)
        return;
    if (!rtlist)
    {
        lst.innerHTML = "";
        return;
    }
    var str = "";
    for(var x = 0; (x < rtlist.length) && (x < 5); x++)
    {
        if(0 == x)
        {
            str += "<h3 style=\"margin: 0 10px 0 0; padding: 0 0 0 0; line-height: 1; float: left;\">See also:</h3><ul id=\"featuredtopicsrelatedtopicslist\" style=\"list-style-type:none;\" >";
        }
        str += "<li><a href='";
        str += rtlist[x][1];
        str += "' >";
        str += rtlist[x][0];
        str += "</a></li> ";
    }
    /* The space after the closing </li> tag is vitally important to page layout. Don't remove it.*/
    str = str + "</ul>";
    lst.innerHTML = str;
}