function Rss() {
    this.init();

    this.cfg = {
        title: "Jaws RSS Reader",
        module: "Rss"
    }

    this.defaultProfile["newsCount"] = 8;
    this.defaultProfile["open_directly"] = 0;
    this.defaultProfile["url"] = "";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: "News count: "},
            { tag: "select", id: "news_count", className: "settings_control",
              options: [
                { value:"3", text: "3"},
                { value:"5", text: "5"},
                { value:"8", text: "8"},
                { value:"10", text: "10"},
                { value:"12", text: "12"},
                { value:"15", text: "15"},
                { value:"9999", text: "All"}
              ]
            },
            { tag: "input", type: "button", value: " Set ", events: {onclick: "setNewsCount()"}}
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: "Refresh every: "},
            { tag: "select", id: "period", className: "settings_control",
              options: [
                { value:"120", text: "2 min"},
                { value:"300", text: "5 min"},
                { value:"600", text: "10 min"},
                { value:"1200", text: "20 min"},
                { value:"1800", text: "30 min"},
                { value:"3600", text: "1 hour"},
                { value:"10800", text: "3 hours"}
              ]
            },
            { tag: "input", type: "button", value: " Set ", events: {onclick: "setPeriod()"}}
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: "Open directly on page: "},
            { tag: "input", type: "checkbox", id: "open_directly",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},
        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", innerHTML: "News url: ", className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control"},
            { tag: "input", type: "button", value: " Go ", events: {onclick: "setUrl()"}}
          ]}
    ]


    this.lastRefresh = null
    this.isLoading = false;


    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.newsCount;
        this.elements.open_directly.checked = this.profile.open_directly == 1;
        this.elements.content.style.padding = "6px";
        hideEl(this.elements.icon);
        this.elements["select_url"].value = this.profile["url"];
    }


    this.setUrl = function() {
        var url = trim(this.elements["select_url"].value);
        if(url != "") {
            if(url.indexOf("http://") == -1) {
                url = "http://" + url;
            }
            this.profile["url"] = url;
            this.save();
            this.iconLoaded = false;
            kernel.stopTimer(this.id);
            kernel.processTimer(this.id, this.profile.period * 1000, true);
            this.refresh();
        }
    }

    this.setOpenDirectly = function() {
        this.profile.open_directly = this.elements.open_directly.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.newsCount = this.elements.news_count.value;
        this.save();
        this.renderChannel();
    }

    this.setPeriod = function() {
        this.profile.period = this.elements.period.value;
        kernel.stopTimer(this.id);
        kernel.processTimer(this.id, this.profile.period * 1000, true);
        this.save();
    }


    this.onOpen = function() {
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        this.refresh();
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle("Loading...");

        var iconEl = this.elements.icon;

        var wid = this.id;

        
        var a = new Image();        
        if(this.profile.icon) {
            a.onload = function() {
                iconEl.src = this.src;
                showEl(iconEl);
            }
            a.src = this.profile.icon;
        } else if(!ie_nav) {
            a.url2 = /*getIcoSrc*/("http://"+getDomain(this.profile.url) + "/favicon.ico");
            a.onload = function() {
                iconEl.src = this.src;
                showEl(iconEl);
            }
            a.onerror = function() {
                if(this.url2 != null) {
                    iconEl.src = this.url2;
                    showEl(iconEl);
                    this.url2 = null;
                } else {
                    this.onerror = null;
                }
            }
            a.src = /*getIcoSrc*/(getDir(this.profile.url) + "/favicon.ico");
        }
        
      
        xmlRequest.send(this.profile.url, this, "showChannel");
        this.isLoading == true;
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.open_directly == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.openChannel(wid, feedId);
        }
    }

    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement && response.status==200) {
            //this.data = XMLParser.xml2hash(response.responseXML.documentElement);
	    this.data = new Feed(response);
	    //varpw(f.items[1].title);
            this.renderChannel();
        } else {
            this.showError();
        }
    }


    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data && this.data.title) {
            if(!this.iconLoaded) {
                var icons = [
                    this.profile.icon,
                    getDir(this.data.siteUrl) + "/favicon.ico",
                    getDomain(this.data.siteUrl) + "/favicon.ico",
                    getDir(this.profile.url) + "/favicon.ico",
                    getDomain(this.profile.url) + "/favicon.ico"
                ];
                loadIcon(this.elements["icon"], icons, true);
            }

            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                               createButtonDom("&nbsp;"+this.data.title.substring(0,35), "openSite()"));

            var count = Math.min(this.data.items.length, this.profile.newsCount);

            this.elements.content.innerHTML = '<ul class="rss"></ul>';
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content.firstChild, 
                                   { tag: "li",/* style: {width: "100%", padding: "0px 0px 0px 10px"},*/
                                     childs: [
                                       /*createButtonDom(this.data.items[i].title.wordWrap(30),
                                                       "openChannel("+this.id+","+i+")",
                                                       "img/li.gif")*/
					{tag: "a", href: "openChannel("+this.id+","+i+",'" + this.data.items[i].link + "')", innerHTML: this.data.items[i].title.wordWrap(30)}
                                     ]});
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = 'Error loading channel';
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.htmlUrl);
        }
    }
 
}

var Feed = function(feed) {
	this.root = feed.responseXML.documentElement;
	this.type = (this.root.nodeName=="feed") ? 1 : 0;
	// htmlUrl
	var root = (this.type==1) ? this.root : this.root.getElementsByTagName("channel")[0];
	var link = Utils.getChildrenByTagName(root, "link");
	if (this.type==1) {
		for (var z=0; z<link.length; z++) {
			if (link[z].getAttribute("type")=="text/html" || link.length==1) {
				this.htmlUrl = link[z].getAttribute("href");
			}
		}
	} else {
		this.htmlUrl = (link && link[0] && link[0].firstChild) ? link[0].firstChild.nodeValue : "";
	}
	
	// title
	var title = Utils.getChildrenByTagName(root, "title")[0];
	//var title = this.root.getElementsByTagName("title")[0];
	this.title = (title && title.firstChild) ? title.firstChild.nodeValue : this.htmlUrl;
	
	// description
	var desc = (this.type==1) ? this.root.getElementsByTagName("tagline") : this.root.getElementsByTagName("description");
	this.description = (desc && desc.length>0) ? ((desc[0].firstChild) ? desc[0].firstChild.nodeValue : '') : '';

	this.items = [];
	var items = (this.type==1) ? this.root.getElementsByTagName("entry") : this.root.getElementsByTagName("item");
	var ln = items.length;

	this.getNode = function(index) {
		return items[index];
	}
	
	for (var z=0; z<ln; z++) {
		var obj = {};
		obj.node = items[z];
		obj.enclosures = items[z].getElementsByTagName("enclosure");
		
		//var title = items[z].getElementsByTagName("title")[0];
		var title = Utils.getChildrenByTagName(items[z], 'title')[0];
		if (title && title.firstChild) {
			obj.title = title.firstChild.nodeValue;
		} else {
			var d = items[z].getElementsByTagName("description");
			if (d[0] && d[0].firstChild) {
				//obj.title = items[z].getElementsByTagName("description")[0].firstChild.nodeValue.substring(0,40)+"...";
				var tmp = document.createElement("div");
				tmp.innerHTML = d[0].firstChild.nodeValue;
				obj.title = ((tmp.innerText)?tmp.innerText.substring(0,50):'')+"...";
			} else {
				obj.title = '[...]';
			}
		}
		//varpw(obj.title);
		var dcDate = (ie_nav) ? items[z].getElementsByTagName("dc:date")[0] : items[z].getElementsByTagName("date")[0];
		if (items[z].getElementsByTagName("pubDate")[0]) {
			obj.date = (items[z].getElementsByTagName("pubDate")[0].firstChild) ? items[z].getElementsByTagName("pubDate")[0].firstChild.nodeValue : "";
		} else if (dcDate) {
			obj.date = dcDate.firstChild.nodeValue;
		} else if (items[z].getElementsByTagName("issued")[0]) {
			obj.date = items[z].getElementsByTagName("issued")[0].firstChild.nodeValue;
		}
		
		var link = Utils.getChildrenByTagName(items[z], "link");
		if (link.length>0) {
			if (this.type==1) {
				for (var n=0; n<link.length; n++) {
					if (link[n].getAttribute("type")=="text/html" || link.length==1) {
						obj.link = link[n].getAttribute("href");
					}
				}
			} else {
				if (link[0] || link[0].firstChild) {
					obj.link = (link[0].firstChild) ? link[0].firstChild.nodeValue : '';
				} else if (items[z].getElementsByTagName("guid")[0].firstChild) {
					obj.link = items[z].getElementsByTagName("guid")[0].firstChild.nodeValue;
				}
			}
		} else {
			obj.link = this.htmlUrl;
		}
		
		//obj.hash = hex_md5(obj.date+obj.link+obj.title); // too slow
		if (obj.link!="" && obj.link!=this.htmlUrl) {
			var str = obj.link;
		} else {
			var str = obj.title+obj.date+obj.link;
		}
		obj.id = str.replace(/([^0-9a-zA-Z])/g,"");
		obj.id_old = (obj.title+obj.date+obj.link).replace(/([^0-9a-zA-Z])/g,"");
		
		if (this.type==1) {
			obj.content = items[z].getElementsByTagName("content")[0];
			obj.description = items[z].getElementsByTagName("summary")[0];
		} else {
			obj.content = (ie_nav) ? items[z].getElementsByTagName("content:encoded")[0] : items[z].getElementsByTagName("encoded")[0];
			obj.description = items[z].getElementsByTagName("description")[0];
		}
		this.items.push(obj);
	}
}

////////////////
/*
Copyright 2005-2006 Netvibes Ltd.
All rights reserved.
*/

var Utils = new Object();

function getElementsByClassName(node, className) {
	var children = node.getElementsByTagName('*');
	var elements = new Array();
	for (var i=0; i<children.length; i++) {
		var child = children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}

function getNodeID(parent, id) {
	var ln = parent.childNodes.length;
	for (var z=0; z<ln; z++) {
		if (parent.childNodes[z].id == id) return parent.childNodes[z];
	}
	return null;
}


Utils.getChildrenByTagName = function(node, tagName) {
	var ln = (node && node.childNodes) ? node.childNodes.length : 0;
	var arr = [];	
	for (var z=0; z<ln; z++) {
		if (node.childNodes[z].nodeName==tagName) arr.push(node.childNodes[z]);
	}
	return arr;
}

Utils.getColonTag = function(node, tag, name) {
	return (Browser.isIE) ? node.getElementsByTagName(tag+":"+name)[0] : node.getElementsByTagName(name)[0];
}

var Browser = new Object();

var ua = navigator.userAgent.toLowerCase();
Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (ua.indexOf("firefox")!=-1);
Browser.isSafari = (ua.indexOf("safari")!=-1);
Browser.isOpera = (typeof window.opera != 'undefined');

if (Browser.isMozilla) {
	HTMLElement.prototype.removeNode = function() {
		this.parentNode.removeChild(this);
	}
}

Browser.version = 1;
if (Browser.isFirefox) {
	Browser.version = parseFloat(ua.substr(ua.indexOf("firefox")+8, 3));
} else if (Browser.isOpera) {
	if (window.opera.version) {
		Browser.version = parseFloat(window.opera.version());
	} else {
		Browser.version = 7.5; // support for version from 7.55 on 
	}
} else if (Browser.isIE) {
	var re  = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null) {
		Browser.version = parseFloat(RegExp.$1);
	} else {
		Browser.version = 3;
	}
} else if (Browser.isSafari) {
	var kitName = "applewebkit/";
	var kitVersion = ua.substring(ua.indexOf(kitName) + kitName.length, ua.length);
	kitVersion = parseInt(kitVersion.substring(0,kitVersion.indexOf(" ")));
	Browser.version =
		kitVersion >= 400 ? 2.0 :
		kitVersion >= 300 ? 1.3 :
		kitVersion > 100 ? 1.2 :
		/* kitVersion <= 100 */ 1.0;
}

Utils.htmlEncode = function(text) {
  return text.escapeHTML(); // prototype.js
}

/*
<!--[if IE]>
	<a href onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.netvibes.com');">Make Netvibes your homepage</a>
<![endif]-->
*/

function isEmailValid(e) {
	var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.+@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(var i=0; i<e.length; i++){
		if (ok.indexOf(e.charAt(i))<0) {
			return false;
		}
	}
	if (document.images) {
		var re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		var re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,8}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return -1;
		}
	}
}


var notspace = /\S/;
Utils.cleanWhitespace = function(node){
	for (var x=0; x<node.childNodes.length; x++) {
		var child = node.childNodes[x];
		//if it's a whitespace text node
		if ((child.nodeType == 3) && (!notspace.test(child.nodeValue)))	{
			node.removeChild(node.childNodes[x]);
			//node.childNodes[x].removeNode();
			x--;
		}
		//elements can have text child nodes of their own
		if(child.nodeType == 1) {
			Utils.cleanWhitespace(child);
		}
	}
}


String.prototype.trim = function() {
	return this.replace(/^\s*|\s*$/g,"");
};

String.prototype.s = function() {
	var str = this;
	if (arguments.length < 1) return str;
	var re = /([^%]*)%s(.*)/;
	var a = [], numSubstitutions = -1;
	while (a = re.exec(str)) {
		var leftpart = a[1], rightPart = a[2];
		if (++numSubstitutions >= arguments.length) {
			break;
		}
		str = leftpart + arguments[numSubstitutions] + rightPart;
	}
	return str;
}


function xmlToString(thexml){
	if(thexml.xml){
		// MSIE
		xmlString = thexml.xml;
	}else{
		// Gecko
		xmlString = (new XMLSerializer).serializeToString(thexml);
	}
	return xmlString;
}

///////////////
Rss.prototype = new Widget();
