/**
 *
 * Copyright (c) 2007, RightNow Technologies, Inc
 *
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * -    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * -    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * -    Neither the name of the RightNow Technologies nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


var RNTFeed = {
    readers: null,
    rnt_ids: 0,
    callBack :  null,
    	
    onloadCallback:function (call){
        RNTFeed.callBack = call;
    },
    init: function (){
        if(RNTFeed.callBack)
            RNTFeed.callBack();
    },
	
    getReader:function(){
        var id = RNTFeed.rnt_ids++;
        var reader = new RNTReader();
        reader.id = id;
		
        if (!this.readers) { 
            RNTFeed.readers = new Object(); 
        }
        RNTFeed.readers[id] = reader;
        return reader;
    },
	
    getRSS:function(id){
        var feed = RNTFeed.readers[id];
        if(feed){
            feed.search();
        }
    },
	
    next:function(id){
        feed = RNTFeed.readers[id];
        feed.next();
    },
    prev:function(id){
        feed = RNTFeed.readers[id];
        feed.prev();
    },
	
    getRelated:function(id, searchTerms){
        var feed = RNTFeed.readers[id];
        if(feed.searchbox=='on'){
            feed.form.input.value = searchTerms;
        }
        feed.query = searchTerms;
        feed.getRSS();
    }

};

RNTFeed.div = function(clazz, id){
    var divElement = document.createElement("div");
    if(clazz){
        divElement.className = clazz;
    }
    if(id){
        divElement.id = id;
    }
    return divElement;
}

RNTFeed.ul = function(clazz, id){
    var divElement = document.createElement("ul");
    if(clazz){
        divElement.className = clazz;
    }
    if(id){
        divElement.id = id;
    }
    return divElement;
}

RNTFeed.table = function(space, pad, clazz){
    var element = document.createElement("table");
    element.setAttribute("cellSpacing", space?space:0);
    element.setAttribute("cellPadding", pad?pad:0);
    if(clazz){
        element.className = clazz
    }
    return element;
}



RNTFeed.row = function(table, n, clazz){
    var row = table.insertRow(-1);
    for(var i= 0; i < n;i++){
        RNTFeed.cell(row, clazz);
    }
    return row;
}

RNTFeed.cell = function(row, clazz){
    var cell= row.insertCell(-1);
    if(clazz)
    {
        cell.className = clazz
    }
    return cell;
}



RNTFeed.createButton = function(value, clazz, title){
    var input = document.createElement("input");
    input.type = "submit";
    input.value = value;
    input.title = title;
    input.name = value;
	
    if(clazz){
        input.className = clazz;
    }
    return input;
}

RNTFeed.createInput = function(value){
    var input = document.createElement("input");
    input.setAttribute("autoComplete","on");
    input.type = "text";
    if(value)
        input.value = value;
    return input;
}

RNTFeed.createForm = function(clazz, id){
    var form = document.createElement("form");
    form.className = clazz
    if(id){
        form.id = id;
    }
    return form;
}

RNTFeed.SearchForm = function (root, id, query){
    var form = RNTFeed.createForm("searchform", "searchform");
    form.action = "javascript:RNTFeed.getRSS("+id+")";
		
    this.searchButton = RNTFeed.createButton("Search", "searchButton", "RSS Search");
    this.searchButton.title = "RSS Search";
	
    this.input = RNTFeed.createInput(query);
    this.input.name = "q";
    var t = RNTFeed.table(0,0,"searcformtable"); 
    RNTFeed.appendChild(form, t);
    var r = RNTFeed.row(t, 0);
    var input = RNTFeed.cell(r, "searchinput");
    var search = RNTFeed.cell(r, "searchbutton");
    RNTFeed.appendChild(input, this.input);
    RNTFeed.appendChild(search, this.searchButton);
    RNTFeed.appendChild(root, form);
	
}
RNTFeed.NavigationForm = function (root, id){
    var form = RNTFeed.createForm("navigationform", "navigationform");
    form.action = "javascript:void(0)";

    this.prevButton = RNTFeed.createButton("<<Back", "prevBtn", "Previous Page");
    this.prevButton.onclick = function(){RNTFeed.prev(id);};
    this.nextButton = RNTFeed.createButton("Next>>", "nextBtn", "Next Page");
    this.nextButton.onclick = function(){RNTFeed.next(id);};
	
    var t = RNTFeed.table(0,2,"navigationtable"); 
    RNTFeed.appendChild(form, t);
    var r = RNTFeed.row(t, 0);
    var prev = RNTFeed.cell(r, "prevButton");
    var next = RNTFeed.cell(r, "nextButton");
    RNTFeed.appendChild(prev, this.prevButton);
    RNTFeed.appendChild(next, this.nextButton);
	
    this.navigation = RNTFeed.div("navigation", "navigation");
   		
    RNTFeed.appendChild(this.navigation, form);
    RNTFeed.appendChild(root, this.navigation);
}

RNTFeed.appendChild = function(root,child){
    root.appendChild(child)
    return child
};


RNTFeed.RNT_ajaxCall = function(url, id, page_next){

    var handler = RNTFeed.readers[id];
    Ajax.Responders.register({
        onException:handler.handleException,
        onCreate: function(request) {
            handler.timeoutId = window.setTimeout(function() {
                if (request.transport.readyState==1 || 
                    request.transport.readyState==2	|| 
                    request.transport.readyState==3) {
                    request.transport.abort();
				
                    handler.handleTimeout();
					
                }
            }, handler.TIMEOUT);
				
        },
        onComplete: function(request) {
            window.clearTimeout(handler.timeoutId);
        },
        onException:handler.handleException
    });
		
    function process(response){
        if (response.readyState == 4 && response.status == 200)
        {
            if (response.responseXML != null){
                if(page_next == 1){		
                    RNT_processChannel(handler, response.responseXML, false);
                }else{
                    handler.page = 1;
                    RNT_processChannel(handler, response.responseXML, true);
                }
            }else{
                handler.status = 'ERROR';
                handler.errorMessage = "Failed to receive RSS feed from the server.";
            }
        }else{
            handler.status = 'ERROR';
            handler.errorMessage = 	"Error code " + response.status + " received: " + response.statusText;
        }	
        handler.onFeedReady();
    }
 		
    new Ajax.Request(url, {method:'get', onSuccess:process, onFailure:handler.handleFailure, onException:handler.handleException});
};


RNTFeed.JSONCall = function(url, id, page_next){
    var handler = RNTFeed.readers[id];
    var head = document.getElementsByTagName("head").item(0);
    var script = document.createElement("script");
    RNTFeed.readers[id].onCompleteJSON = function (channel) {
    
    	if(page_next == 1)		
            handler.channel.item = handler.channel.item.concat(channel.item);			
        else
            handler.channel = channel;
        handler.session = handler.channel.session;
        handler.onFeedReady();
        
        //head.removeChild(script);
       	
        /*To Do:start close the spinner loading animation when the search is done
        */
        jQuery('#knowledgeBaseContent .purplespinner-loading').fadeOut(100, function(){
        	 	
			jQuery('#knowledgeBaseResults').css('height','auto');		
			
		});	
				
        return true;
    }
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", url+"/callback/RNTFeed.readers["+id+"].onCompleteJSON");
    head.appendChild(script);
};


function RNTReader(){
    this.uri = 'opensearch.php?';
    this.status= 'SUCCESS';
    this.errorMessage=  null;
    this.searchbox= 'on';
    this.navigation= 'on';
    this.pagesize=  20;
    this.page=  1;
    this.query=  "";
    this.channel=  null;
    this.format=  'xml';
    this.proxy=  null;
    this.TIMEOUT= 20000;
    this.timeoutId=  null;
    this.root=  null;
    this.session = null;
	this.target = "_self"; 
	this.openAnswersWindow = 'off'; 
	this.answersWindowTarget = '_blank'; 
}
 
RNTReader.prototype.setQuery = function(parm){
    var q = this.getQuery("q");
    if (typeof parm != 'undefined' && parm != ""){
        this.query = parm;
        if(this.searchbox=='on')
            this.form.input.value = parm;
    }else if (this.searchbox=='on' && this.form && this.form.input.value != this.query){
        this.query = this.form.input.value;
    }else if(q != null){
        this.query = q;
        if(this.searchbox=='on')
            this.form.input.value = q;
    }		    
		    
};
 
     
RNTReader.prototype.search = function(parm){
    this.setQuery(parm);
    this.getRSS();
		    
};
    
    
RNTReader.prototype.render = function(divTag){
    this.root =  document.getElementById(divTag);
	
    if(this.searchbox=='on'){
        this.form = new RNTFeed.SearchForm(this.root, this.id, this.query);
    }
 		
    this.feedHeader = RNTFeed.div("feedHeader", "feedHeader");
    RNTFeed.appendChild(this.root, this.feedHeader);
 		
    this.correction = RNTFeed.div("correction", "correction");
    RNTFeed.appendChild(this.root, this.correction);
 		
    this.related = RNTFeed.div("related", "related");
    RNTFeed.appendChild(this.root, this.related);
 		
    this.topics = RNTFeed.div("topics", "topics");
    RNTFeed.appendChild(this.root, this.topics);
 		
    this.feedContent = RNTFeed.div("feedContent", "feedContent");
    RNTFeed.appendChild(this.root, this.feedContent);
    this.items = RNTFeed.ul("items", "items");
    RNTFeed.appendChild(this.feedContent, this.items);
 	
 		
    this.navigationForm = new RNTFeed.NavigationForm(this.root, this.id);
    this.navigationForm.navigation.style.display="none";
 	 	
    this.poweredBy = RNTFeed.div("pb", "pb");
    /* below line causes performance issue since image is not found and so it has been commented out */
    //this.poweredBy.innerHTML = '<a id="poweredByLink"	href="http://www.rightnow.com/poweredbyrnt.html" alt="Powered by RightNow Technologies"> <img src="http://yellowstone/rnt/rnw/img/rnt_pwr_btn.gif" /> </a>'
    RNTFeed.appendChild(this.root, this.poweredBy);
};
    


RNTReader.prototype.getQuery =  function(name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if( results == null )
        return null;
    else   
        return results[1];
};
 
 
RNTReader.prototype.getRSS = function(){
    this.status= 'SUCCESS';
    var url = this.uri;
 
    var ln = url.length;
    
    if(url.charAt(ln-1)== '/')
        url += 'startIndex/'+0+'/count/'+this.pagesize;
    else
        url += '/startIndex/'+0+'/count/'+this.pagesize;
    
    if(this.query != null && this.query != "")
        url += '/q/'+escape(this.query);
    
    if(this.session){
             url += '/session/'+this.session;
    }
    
    if(this.format == "json" || this.proxy == null){
        this.page = 1;
        url += '/osmode/json';
        RNTFeed.JSONCall(url, this.id, 0);
    }else{
        if(this.proxy){
            url = this.proxy+"?url="+escape(url);
        }
        RNTFeed.RNT_ajaxCall(url, this.id, 0);
    }
};

  
RNTReader.prototype.next = function(){
    this.page++;
    var pStart = (this.page-1)*this.pagesize;
 		
    if(pStart >= this.channel.item.length){
        var url = this.uri;
        var ln = url.length;
 			
        if(url.charAt(ln-1)== '/')
            url += 'startIndex/'+pStart+'/count/'+this.pagesize;
        else
            url += '/startIndex/'+pStart+'/count/'+this.pagesize;

        if(this.query != null && this.query != "")
            url += '/q/'+escape(this.query);
 
        if(this.session){
             url += '/session/'+this.session;
        }
        
        if(this.format == "json" || this.proxy == null){
            url += '/osmode/json';
            RNTFeed.JSONCall(url, this.id, 1);
        }else{
            if(this.proxy){
                url = this.proxy+"?url="+escape(url);
            }
            RNTFeed.RNT_ajaxCall(url,  this.id, 1);
        }
    }else{
        this.onFeedReady();
    }
};
   
RNTReader.prototype.prev = function(){
    this.page--;
    this.onFeedReady(true);
};
   
RNTReader.prototype.trimStr = function(str){
    if(str == null)
   	return null;
    return str.replace(/^\s*|\s*$/g,'');
};


RNTReader.prototype.getRelated= function(searchTerms){
    if(this.searchbox=='on'){
        this.form.input.value = searchTerms;
    }else{
        this.query = searchTerms;
    }
    this.getRSS();
};
 
RNTReader.prototype.onRNTAnswersPageReady = function(){
	var RSS  = this.channel;
	  	
    if ((typeof RSS == 'undefined' ||  RSS == null) || 
        ((typeof RSS.Query == 'undefined' || RSS.Query == null || RSS.Query.length==0) 
        && (typeof RSS.topic == 'undefined' || RSS.topic == null|| RSS.topic.length==0) 
        && (typeof RSS.item == 'undefined' || RSS.item == null || RSS.item.length==0)) ){
      
        return;
    }
	
    if(this.status == 'ERROR'){
        return;
    }
    
    if (typeof RSS.item != 'undefined' && RSS.item != null && RSS.item.length != 0){
		var iagAnswersUrl = 'https://assist.thebuzzinsurance.com.au/app/answers/list/kw/'+this.query+'/c/%20/r_id/100020/search/1';
		var params;
		params = 'width='+screen.width/2;
		params += ', height='+screen.height/2;
		params += ', status=yes,resizable=yes, toolbar=yes, menubar=yes, scrollbars=yes,location=yes';
		if(this.answersWindowTarget == '_blank') {
			 var myAnswers = window.open(iagAnswersUrl,'myAnswers',params);		
			 if (!myAnswers){
				var moreAnswersText = '<a target="_blank" href="' + iagAnswersUrl + '">Click here</a> to view more matched answers';
				jQuery("<div>").attr({id:"knowledgeBaseAnswersMore"})
						  .append(moreAnswersText)
						  .appendTo('#knowledgeBaseResults');	
			 }
		}
		else if (this.answersWindowTarget == '_self') {
			window.location.href = iagAnswersUrl;	
		}	
    }
   
};
	 	 	
RNTReader.prototype.onFeedReady = function(prev){
	
    var RSS  = this.channel;

    this.correction.style.display="none";
    this.related.style.display="none";
    this.topics.style.display="none";
   	
    if ((typeof RSS == 'undefined' ||  RSS == null) || 
        ((typeof RSS.Query == 'undefined' || RSS.Query == null || RSS.Query.length==0) 
        && (typeof RSS.topic == 'undefined' || RSS.topic == null|| RSS.topic.length==0) 
        && (typeof RSS.item == 'undefined' || RSS.item == null || RSS.item.length==0)) ){
        document.getElementById("topics").style.visibility='hidden';
		
        this.feedContent.innerHTML = "There are no results for this query. Please try another search";
        return;
    }
	
    if(this.status == 'ERROR'){
        this.feedContent.innerHTML = this.errorMessage;
        return;
    }
	
	   
    var header = '<table><tr><td align="left"><div id="channelTitleSection"><a href="'+RSS.link+'" alt="">';
    //Firefox is not removing whitespaces.
    var title = this.trimStr(RSS.title);
    var description = this.trimStr(RSS.description);
	
    if(title != null && title != ""){
       	header += title;
    }
	
    //only adding description if it is not the same as title. 
    if(description != null && description != "" && description != title){
	
        if(title != null && title != "")
            header += ': '+description;
        else
            header += description;
    }
    header += "</a></div></td>";
   
    if(RSS.image != null && RSS.image.url != null && this.trimStr(RSS.image.url) != ""){
       	var img = '<td align="right"><div id="channelImageSection"><a href="'+RSS.link+'" alt="">';
       	img += '<img id="channelImage"  border="0" src="'+this.trimStr(RSS.image.url)+'"/></div></td>';
       	header += img;
    }
	
    //header closing tag
    header += "</div></table>";
	
    this.feedHeader.innerHTML = header; 
	
	
    if (typeof RSS.Query != 'undefined' && RSS.Query != null && RSS.Query.length != 0){	
		
        var correctionHtml = "";
        var relatedHtml = "";
        var c = false;
        var r = false

        for (var i = 0; i < RSS.Query.length; i++){
            var query = RSS.Query[i];
            if(query.role == "correction"){
                if(c){
                    correctionHtml += ", <a  href='#' onclick=\"RNTFeed.getRelated("+this.id+",'"+query.searchTerms+"')\">"+query.searchTerms+"</a>";
                } else {
                    correctionHtml += "<a 	href='#' onclick=\"RNTFeed.getRelated("+this.id+",'"+query.searchTerms+"')\">"+query.searchTerms+"</a>";
                    c = true;
                }
            } 
            if(query.role == "related"){
                if(r){
                    relatedHtml += ", <a 	href='#' onclick=\"RNTFeed.getRelated("+this.id+",'"+query.searchTerms+"')\">"+query.searchTerms+"</a>";
                } else {
                    relatedHtml += "<a 	href='#' onclick=\"RNTFeed.getRelated("+this.id+",'"+query.searchTerms+"')\">"+query.searchTerms+"</a>";
                    r = true;
                }
            } 
        }
	
        if(correctionHtml != ""){
            this.correction.style.display="";
            this.correction.innerHTML = "Did you mean <strong>"+correctionHtml+"</strong>?";
        }
        if(relatedHtml != ""){
            this.related.style.display="";
            this.related.innerHTML = "Related Searches: <strong>"+relatedHtml+"</strong>";
        }
    }
	
	
    this.topics.innerHTML = "";
    if (typeof RSS.topic != 'undefined' && RSS.topic != null && RSS.topic.length != 0){	
		
        this.topics.style.display="";
	
        var topicStr = '<div id="topicsContent"><b>Recommended Documents:</b>'
        for (var i = 0; i < RSS.topic.length; i++)
        {
            var topic = RSS.topic[i];
		
            var i_link = this.trimStr(topic.link)
            var i_title = this.trimStr(topic.title);
            var i_description = this.trimStr(topic.description);
		
		
            if(i_link != null && i_link != ""){
                topicStr += '<li><a href="'+i_link+'">'+i_title+'</a></li>';
            }	
		
        }
        topicStr += '</div><div class="clearboth"></div>';
	
        if(RSS.topic.length > 0)
            this.topics.innerHTML += topicStr;		
    }else
        this.topics.style.display="none";
		
	
    this.items.innerHTML = "";

    //TODO: logic for paging should move to a different function. Header information should not refreshed for each
    //page
    if (typeof RSS.item != 'undefined' && RSS.item != null && RSS.item.length != 0){
		
        //widget page size should never be bigger than server pagesize. 
        //gracefully accept it.
        if((RSS.itemsPerPage < this.pagesize && RSS.itemsPerPage < RSS.totalResults) && (!prev && this.page==1))
            this.pagesize = RSS.itemsPerPage; 


        var pStart = (this.page-1)*this.pagesize;
        var pEnd = this.page*this.pagesize;
	
		
		
        if(pEnd > RSS.item.length)
            pEnd  = RSS.item.length;
	
        for (var i = pStart; i < pEnd; i++)
        {
            var item = RSS.item[i];
		
            var i_link = this.trimStr(item.link);
            if( i_link.indexOf("http") > -1 && i_link.indexOf("https") <= -1){
				i_link = i_link.replace("http","https");
            }
            
            var i_title = this.trimStr(item.title);
            var i_description = this.trimStr(item.description);
            var i_image_url = this.trimStr(item.url);
	
            var itemStr="";
		
            if(i_link != null && i_link != ""){
                itemStr += '<li><a target="'+this.target+'" href="'+i_link+'">'+i_title+'</a>';
            }
            if(i_description != null && i_description != ""){
                itemStr += '<div class="itemContent"><P>'+i_description+'</P></div>';
            }
            if(i_link != null && i_link != ""){
                itemStr += '</li>';
            }
		
			
            this.items.innerHTML += itemStr;
		
        }
        if(RSS.totalResults <= this.pagesize){
            this.navigationForm.navigation.style.display="none";
            this.navigationForm.nextButton.disabled = true;
            this.navigationForm.prevButton.disabled= true;
        }
        //enable or disable buttons
        //we could also check if itemsPerPage <= pagesize
        if(pEnd <  RSS.item.length || pEnd < RSS.totalResults ){ 
            if(this.navigation=='on'){
                this.navigationForm.navigation.style.display="block";
            }
   		
            this.navigationForm.nextButton.disabled = false;
		
        }
        else //if not this pagination
        {
            this.navigationForm.nextButton.disabled = true;
        }
	
        if(this.page > 1){
            this.navigationForm.prevButton.disabled= false;
   	
        }
        else {
            this.navigationForm.prevButton.disabled= true;
        }
    }else{
		this.feedContent.innerHTML = "There are no results for this query. Please try another search";
        this.navigationForm.navigation.style.display="none";
        this.navigationForm.nextButton.disabled = true;
        this.navigationForm.prevButton.disabled= true;
    }
	
	
};

RNTReader.prototype.handleFailure = function(o){
    this.status = 'ERROR';
    this.errorMessage = "Failed to request RSS feed from the server";
    this.feedContent.innerHTML = this.errorMessage;
};

RNTReader.prototype.handleException = function(o, exception){
    this.status = 'ERROR';
    this.errorMessage = "Failed to receive RSS feed from the server: <font color=red>"+exception+"</font>";
    this.feedContent.innerHTML = this.errorMessage;
};


RNTReader.prototype.handleTimeout = function(){
    this.status = 'ERROR';
    this.errorMessage = "Call to server didn't return. Make sure you have appropriate timeout set";
    this.feedContent.innerHTML = this.errorMessage;
};
   


window.onload = RNTFeed.init; 

/*
 * RNT RSS Parser
 *
 *
 */
function RNT_processChannel(handler, rssDom, newSearch){

    var channel = null;
	
    var cElement = rssDom.getElementsByTagName("channel")[0];
	
    if(newSearch)
        handler.channel = new RNT_Channel(rssDom);

    var itemList = rssDom.getElementsByTagName("item");
    for (var i = 0; i < itemList.length; i++)
    {
        var item = new RNT_Item(itemList[i]);
        handler.channel.item.push(item);
    }
    //Firefox bug:https://bugzilla.mozilla.org/show_bug.cgi?id=206053
    if (Prototype.Browser.Gecko){
        handler.channel.totalResults =  RNT_elementValue(rssDom, 'totalResults') ? RNT_elementValue(rssDom, 'totalResults'):itemList.length;
        handler.channel.startIndex =    RNT_elementValue(rssDom, 'startIndex')   ? RNT_elementValue(rssDom, 'startIndex')  :0;
        handler.channel.itemsPerPage =  RNT_elementValue(rssDom, 'itemsPerPage') ? RNT_elementValue(rssDom, 'itemsPerPage'):itemList.length;
    }else{
        handler.channel.totalResults =  RNT_elementValue(rssDom, 'opensearch:totalResults') ? RNT_elementValue(rssDom, 'opensearch:totalResults'):itemList.length;
        handler.channel.startIndex =    RNT_elementValue(rssDom, 'opensearch:startIndex')   ? RNT_elementValue(rssDom, 'opensearch:startIndex')  :0;
        handler.channel.itemsPerPage =  RNT_elementValue(rssDom, 'opensearch:itemsPerPage') ? RNT_elementValue(rssDom, 'opensearch:itemsPerPage'):itemList.length;
    }
    handler.session = handler.channel.session;	
    
}  
  
function RNT_Channel(rssDom)
{


    var cElement = rssDom.getElementsByTagName("channel")[0];

    //required channel elements
    this.title       = RNT_elementValue(cElement, 'title');
    this.link        = RNT_elementValue(cElement, 'link');
    this.description = RNT_elementValue(cElement, 'description');

	
    //optional elements
    this.language       = RNT_elementValue(cElement, 'language');
    this.copyright      = RNT_elementValue(cElement, 'copyright');
    this.managingEditor = RNT_elementValue(cElement, 'managingEditor');
    this.webMaster      = RNT_elementValue(cElement, 'webMaster');
    this.pubDate        = RNT_elementValue(cElement, 'pubDate');
    this.lastBuildDate  = RNT_elementValue(cElement, 'lastBuildDate');
    this.generator      = RNT_elementValue(cElement, 'generator');

    this.Query = new Array();
    this.topic = new Array();
	
    
    var queryList = null;
    //Firefox bug:https://bugzilla.mozilla.org/show_bug.cgi?id=206053
    if (Prototype.Browser.Gecko){
        queryList = cElement.getElementsByTagName("Query");
        this.session = RNT_elementValue(cElement, 'session');
   
    }else{
        queryList = cElement.getElementsByTagName("opensearch:Query");
        this.session = RNT_elementValue(cElement, 'related:session');
   
    }
	
    for (var i = 0; i < queryList.length; i++)
    {
        var query = new RNT_Query(queryList[i]);
        this.Query.push(query);
    }
	
    this.category = new Array();
    var children = cElement.childNodes;       
	
    for(var i = 0; i < children.length; i++) {    
        var childElement = children[i];    
    	if(childElement.tagName =="category"){
            var cat = new RNT_Category(childElement);
            this.category.push(cat);
        }
    }
    //HT: IE requires namespace
    var topicList = null;
    //Firefox bug:https://bugzilla.mozilla.org/show_bug.cgi?id=206053
    if (Prototype.Browser.Gecko){
        topicList = cElement.getElementsByTagName("topic");
    }else{
        topicList = cElement.getElementsByTagName("related:topic");
    }
	
    for (var i = 0; i < topicList.length; i++)
    {
        var topic = new RNT_Topic(topicList[i]);
        this.topic.push(topic);
    }
	
	
    this.docs           = RNT_elementValue(cElement, 'docs');
    this.ttl            = RNT_elementValue(cElement, 'ttl');
    this.image          = new RNT_Image(cElement.getElementsByTagName("image")[0]);
    this.rating         = RNT_elementValue(cElement, 'rating');
	
    //just for completeness: no need for these elements in order to view
    this.skipHours      = RNT_elementValue(cElement, 'skipHours');
    this.skipDays       = RNT_elementValue(cElement, 'skipDays');


    //items
    this.item = new Array();
	
}


//if tag is defined returns the value of the element in dom.
//else it returns the value of element
function RNT_elementValue(dom, tag)
{
    if (dom == null || (typeof dom == 'undefined'))
        return null;
	

    if (typeof tag == 'undefined' ) element = dom;
    else   
        element = dom.getElementsByTagName(tag)[0];
	
    if(element == null || (typeof element == 'undefined'))
        return null;
    else{
        if(element.childNodes.length > 0)
            return 	element.childNodes[0].nodeValue;
        else
            return "";
    }
}


function RNT_getAttr(element, attribute)
{
    if(element == null)
        return null;
    else
        return element.getAttribute(attribute);
}


function RNT_Item(element)
{
    //All elements of an item are optional, however at least one of title or description must be present.
    this.title       = RNT_elementValue(element, 'title');
    this.link        = RNT_elementValue(element, 'link');
    this.description = RNT_elementValue(element, 'description');
    this.author      = RNT_elementValue(element, 'author');
	
	
    //this.category       = new Category(cElement.getElementsByTagName("category")[0]);
	
    this.category = new Array();
    var categoryList = element.getElementsByTagName("category");
    for (var i = 0; i < categoryList.length; i++)
    {
        var cat = new RNT_Category(categoryList[i]);
        this.category.push(cat);
    }
	
    //this.category    = new Category(element.getElementsByTagName("category")[0]);
	
	
    this.comments    = RNT_elementValue(element, 'comments');
    this.enclosure   = new RNT_Enclosure(element.getElementsByTagName("enclosure")[0]);
    this.guid        = new RNT_Guid(element.getElementsByTagName("guid")[0]);
    this.pubDate     = RNT_elementValue(element, 'pubDate');
    this.source      = new RNT_Source(element.getElementsByTagName("source")[0]);
}

//Describes a media object that is attached to the item. 
function RNT_Enclosure(element)
{
    this.url    = RNT_getAttr(element, "url");
    this.length = RNT_getAttr(element, "length");
    this.type   = RNT_getAttr(element, "type");
}

function RNT_Guid(element)
{
    this.isPermaLink = RNT_getAttr(element, "isPermaLink");
    this.value       = RNT_elementValue(element);
}

//The RSS channel that the item came from
function RNT_Source(element)
{
    this.url   = RNT_getAttr(element, "url");
    this.value = RNT_elementValue(element);
}

//categorization taxonomy
function RNT_Category(element)
{
    this.domain = RNT_getAttr(element, "domain");
    this.value  = RNT_elementValue(element);
}

function RNT_Image(element)
{
    this.url         = RNT_elementValue(element, "url");
    this.link        = RNT_elementValue(element, "link");
    this.width       = RNT_elementValue(element, "width");
    this.height      = RNT_elementValue(element, "height");
    this.description = RNT_elementValue(element, "description");
}

//OpenSearch element
function RNT_Query(element)
{
    this.role       = RNT_getAttr(element, "role");
    this.title      = RNT_getAttr(element, "title");
    this.searchTerms= RNT_getAttr(element, "searchTerms");
}
//RNT extension
function RNT_Topic(element)
{
    this.title       = RNT_elementValue(element, 'title');
    this.link        = RNT_elementValue(element, 'link');
    this.description = RNT_elementValue(element, 'description');

}
