

opera_nav = (navigator.userAgent.indexOf('Opera') != -1) ? true : false;
ie_nav = (navigator.userAgent.indexOf('MSIE') != -1 && !opera_nav) ? true : false;
mozilla_nav = (navigator.userAgent.indexOf('Gecko') != -1) ? true : false;


ua = window.navigator.userAgent
msie = ua.indexOf ( "MSIE " );
ie6_nav = false;
if(msie > 0 && parseInt (ua.substring (msie+5, ua.indexOf (".", msie ))) == '6') {
	ie6_nav = true;
} 

function preloadImg(imgEl, src) {
    var img = document.createElement("img");
    img.setAttribute("src", src);
//    img.src = src;
    img.onload = function() {
        imgEl.setAttribute("src", img.src);
        imgEl.onload = null;
    };
    imgEl.style.display = 'inline';
}

function loadImg(src) {
    var img = new Image();
    img.src = src;
}


function deleteEl(el) {
    if(el && el.parentNode) {
        el.parentNode.removeChild(el);
    }
}

function clone(obj) {
    if((typeof(obj) != 'object') || (obj == null)) {
        return obj;
    }

    if(obj.length == undefined) {
        var newObj = {}
        for(var i in obj) {
            newObj[i] = clone(obj[i]);
        }
    } else {
        var newObj = []
        for(var i=0; i<obj.length; i++) {
            newObj[i] = clone(obj[i]);
        }
    }
    return newObj;
}

function swap(a, b) {
    var tmp = a;
    a = b;
    b = tmp;
}


 
function elById(id) {
    return document.getElementById(id);
}

function showEl(el) {
	jQuery(el).slideDown("slow");
  // el.style.display = 'block';
}

function hideEl(el) {
	jQuery( el).slideUp("slow");
    //el.style.display = 'none';
}

function showEl2(el) {
	//jQuery(el).slideDown("slow");
   el.style.display = 'block';
}

function hideEl2(el) {
//	jQuery( el).slideUp("slow");
    el.style.display = 'none';
}

function clearEl(el) {
    el.innerHTML = '';
}

function info(txt) {
    document.getElementById("info").innerHTML = txt;
}



function px2int(px) {
    return parseInt(px.substring(0,px.length-2));
}

function getMousePos(e) {
    var px; 
    var py; 
    if (mozilla_nav) {
        px = e.pageX;
        py = e.pageY;
    } else {
        px = event.clientX + document.body.scrollLeft;
        py = event.clientY + document.body.scrollTop;
    }    
    return {left:px, top:py};
}


function isPosInObj(pos, obj) {

    var left = getLeft(obj);
    var top = getTop(obj);

    if((pos.left > left) &&
       (pos.left < obj.offsetWidth + left) &&
       (pos.top > top) &&
       (pos.top < obj.offsetHeight + top)) {
        return true;
        }    
       
    return false;
}


function getLeft(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) curleft += obj.x;
    return curleft;
}

function getTop(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    } else if (obj.y) curtop += obj.y;
    return curtop;
}


function getElPos(el) {
    var left = 0;
    var top = 0;
    if (el.offsetParent) {
        while (el.offsetParent) {
            left += el.offsetLeft;
            top += el.offsetTop;
            el = el.offsetParent;
        }
    } else 
        if (el.y) {
            left += el.x;
            top += el.y;
        }
    return {left:left, top:top};
}


function setElPos(el, pos) {
    el.style.left = pos.left + "px";
    el.style.top = pos.top + "px";
}







function trim(s) {
    if(s && s.replace) {
        return s.replace(/^\s*(.+?)\s*$/, "$1").replace(/'/g, "").replace(/"/g, "");
    } else {
        return "";
    }
}


function arraySearch(needle, data) {
    for(var i = 0; i<data.length; i++) {
        if(data[i] == needle) {
            return i;
        }
    }
    return undefined;
}

function arrayFirstFree(data) {
    var id = arraySearch(undefined, data);
    if(id != undefined) {
        return id;
    } else {
        return data.length;
    }
}



function getDir(url) {
    if(url) {
        return url.substring(0, url.lastIndexOf("/"));
    } else {
        return "";
    }
}

function getDomain(url) {
    if(url) {
        var tmp = url.split("//");
        return (tmp[1] != undefined) ? tmp[1].split("/")[0] : tmp[0].split("/")[0];
    } else {
        return "";
    }
}

function wordWrap(txt) {
    var w = txt.split(" ");
    var r = [];
    for(var i=0; i<w.length; i++) {
        if(w[i].length>40) {
            var stops = Math.ceil(w[i].length / 40) + 1;
            for(var j=0; j<stops; j++) {
                r[i] += w[i].substr(stops, 40) + "&shy;";
            }
        } else {
            r[i] = w[i];
        }
    }
    return r.join(" ");
}


function urlencode( txt ) {
    // URL-encodes string
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_urlencode/
    // +       version: 804.1715
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'                                    
    var ret = txt;
    
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');

    return ret;
}



function loadIcon(v_img, v_urls) {
    var el = new Image();
    var img = v_img;
    var urls = v_urls;
    var f = function() {
        if(urls.length > 0) {
            el.urls = urls;
            el.onload = function() {
                this.onerror = null;
                img.setAttribute("src", this.src);
    //            el = null;
            }
            el.onerror = function() {
                if(this.urls.length > 0) {

                    var url = "";
                    while(!url && (this.urls.length > 0) && (trim(url) == "")) {
                        url = urls.shift();
                    }

                    if(url) {
                        if(url.indexOf("http://") == -1) {
                            url = "http://" + url;
                        }
                        this.setAttribute("src", url);
                    }
                } else {
                    this.onerror = null;
                }
            }
            el.onerror();
        }
    }

    setTimeout(f, 100);
}


function fix_event(event) {
    if (!event) {
        event = window.event;
    }
    if (event.target) {
	    if (event.target.nodeType == 3) event.target = event.target.parentNode;
    } else if (event.srcElement) {
	    event.target = event.srcElement;
    }
    var tg = event.target;
    while(tg && (tg.entityInfo == undefined) && (tg != document.body)) {
        tg = tg.parentNode;
    }
    event.target.entityInfo = tg.entityInfo;
    return event;
}



function stopPropagation(anEvent) {
    if(!anEvent) anEvent = window.event;
    if(anEvent) {
       if(anEvent.stopPropagation) anEvent.stopPropagation(); else anEvent.cancelBubble = true;
    }
}

function preventDefault(anEvent) {
    if(!anEvent) anEvent = window.event;
    if(anEvent) {
        if (anEvent.preventDefault) anEvent.preventDefault(); else anEvent.returnValue = false;
    }
}

function killEvent(anEvent) {
    if(anEvent) {
        stopPropagation(anEvent);
        preventDefault(anEvent);
    }
    return false;
}




/*********************************************
 *    
 *   DEBUG
 *
 ********************************************/

function varp(v) {
    alert(Dump(v));
}


function varpw(v) {
    win = open("", "varp", "width=900,toolbar=no,status=no,titlebar=no,scroollbars=yes");
    win.document.write("<html><body><pre style='font-family: Tahoma, Verdana, Arial; font-size: 11px;'>"+Dump(v)+"</pre></body></html>");
}


function info(v) {
    var s ='';
    for(var i in v) {
        s+=i + '; ';
    } 
    alert(s);
}

function Dump(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        s += " {\n";
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + Dump(d[k],l+1);
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}\n"
    } else if(typeof(d) != "function"){
        s += "" + d + "\n";
    }
    return s;
}


function toCode(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        var items = [];
        var i = 0;
        if(d) {
            var isList = d.length != undefined;
        } else {
            var isList = false;
        }
        for(var k in d) {
            switch(typeof(d[k])) {
                case "integet":
                    var v = parseInt(d[k]);
                    break;
                case "string":
                    var v = "'" + d[k] + "'";
                    break;
                case "function":
                    continue;
                    break;
                default:
                    var v = toCode(d[k],l+1);
                    break;
            } 
            items[i] = isList ? v : (k + ":" + v);
            i++;
        }
        if(isList) {
            s += "[" + items.join(",") + "]";
        } else {
            s += "{" + items.join(",") + "}";
        }

    } else if(typeof(d) != "function") {
        s += "" + d;
    }
    return s;
}


function toValue(str) {
    if(str) {
        eval("var r = "+str);
        return r;
    } else {
        return {}
    }
}





/*********************************************
 *    
 *   COOKIES
 *
 ********************************************/


function getCookie(name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = "";
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset)
            if (end == -1) {
                end = cookie.length;
            }
        setStr = unescape(cookie.substring(offset, end));
        }
    }

    return(setStr);
}


function setCookie(name, value) {
    var today = new Date(); 
    today.setTime(today.getTime()); 
    var expires_date = new Date(today.getTime() + 31536000000); 
    document.cookie = name + "=" + escape(value) + ";expires=" + expires_date.toGMTString(); 
}


function delCookie(name) {
    if(getCookie(name)) {
        document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT"; 
    }
}









/*********************************************
 *    
 *   STRINGS
 *
 ********************************************/

function text2html(txt) {
    txt = txt.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>");
    return txt;
}


function html2text(html) {
    html = html.replace(/<br>/g,"\n").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">");
    return html;
}


String.prototype.addSlashes = function() {
    return this.replace(/\\/g,'\\\\').replace(/\"/g,"\\\"").replace(/\'/g,"\\\'");
}

String.prototype.stripSlashes = function() {
    return this.replace(/\\'/g,'\'').replace(/\\"/g,'"').replace(/\\\\/g,'\\');
}


String.prototype.wordWrap = function(w) {
    var i, j, s, r = this.split("\n");
    if(w > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > w;
                r[i] += s.substr(0, w) + ((s = s.substr(w)).length ? "&shy;" : "")
            );
        r[i] += s;
    }
    return r.join("\n");
}
String.prototype.urlencode = function() {
    // URL-encodes string
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_urlencode/
    // +       version: 804.1715
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'                                    
    var ret = this;
    
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');

    return ret;
}
String.prototype.strip_tags = function() {
        // What a tag looks like
        var matchTag = /<(?:.|\s)*?>/g;
        // Replace the tag
        return this.replace(matchTag, "");
}
String.prototype.jsEscape = function() {
    return this.replace(/\%/g, "%jcp").replace(/\n/g, "%jcn").replace(/\r/g, "%jcr").replace(/"/g, "%jcqq").replace(/'/g, "%jcq").replace(/\\/g, "%jcbs");
}

String.prototype.jsUnescape = function() {
    return this.replace(/\%jcr/g, " ").replace(/\%jcn/g, "\n").replace(/\%jcqq/g, "\"").replace(/\%jcq/g, "'").replace(/\%jcbs/g, "\\").replace(/\%jcp/g, "%");
}

String.prototype.parseUrl = function(){
	var lines = this.split("<br>");
	for(var z=0; z<lines.length; z++){
		var tmp = lines[z].split(" ");
		for(var i=0; i<tmp.length; i++){
			if(tmp[i].indexOf("www.")!=-1 && tmp[i].indexOf("http://")==-1){
				tmp[i] = "<a href='http://"+tmp[i]+"' target='_blank'>"+tmp[i]+"</a>";
			} else if(tmp[i].indexOf("http://")!=-1 || tmp[i].indexOf("ftp://")!=-1 || tmp[i].indexOf("https://")!=-1){
				tmp[i] = "<a href='"+tmp[i]+"' target='_blank'>"+tmp[i]+"</a>";
			} else if (tmp[i].indexOf("@") != -1 && tmp[i].charAt(0) != "@" && tmp[i].charAt(tmp[i].length-1) != "@") {
				tmp[i] = "<a href='mailto:"+tmp[i]+"'>"+tmp[i]+"</a>";
			}
		}
		lines[z] = tmp.join(" ");
	}
	return lines.join("<br>");
}

//Truncate the text by the lenght returned
String.prototype.truncate = function(length){	
	if (!length) {
		length = 100; 
	}
	if(this.length > length) {	
		trunc = this.substring(0, length);
	    trunc = this.replace(/\w+$/, '');
	    if (trunc.length > length) {
	    	return trunc + "...";
	    }
	    return trunc;
    } else {
    	return this;
    }
    
}

requests_counter = 0;


function updateLoadingIcon(ofs) {

	requests_counter += ofs;
	if(requests_counter <= 0) {
		hideEl(elById("loading_spinner"));
	} else {
		showEl(elById("loading_spinner"));
	}
	//    elById("dbg").innerHTML = requests_counter;
}



function Request() {

	this.controllerURL = "controller.php";

	this.convertParams = function(hash) {
		var res = [];
		for(k in hash) {
			res.push(k + "=" + encodeURIComponent(hash[k]));
		}
		return res.join("&");
	}


	this.getNoCache = function() {
		return ("" + Math.random()).slice(2, 8);
	}



	this.getTransportObj = function() {
		var req;
		if (window.XMLHttpRequest) {
			try { req = new XMLHttpRequest() } catch(e) {}
		} else if (window.ActiveXObject) {
			try { req = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
			if (!req) {
				try { req = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
			}
		}
		return req;
	}


	this.send = function(params, widget, method) {
		var req = this.getTransportObj();

		if(!req) {
			return false;
		}

		var widgetId = widget.id;
		params.module = widget.cfg.module;

		//        if(!mozilla_nav) {
		var date = new Date();
		params["_nc"] = this.getNoCache();
		//        }

		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if ((req.status < 400) && req.responseText) {
					updateLoadingIcon(-1);
					try {
						eval("if(kernel.getWidget(widgetId)) { kernel.getWidget(widgetId).dispatchMsg("+req.responseText+")}");
					} catch(e) {
						//                        alert("Error in \n"+e.fileName+"\nat line: "+e.lineNumber+"\n"+e.message);
					}
				} else {
					//    				alert(req.statusText);
				}
			}
		}

		if (method == "POST") {
			req.open("POST", this.controllerURL, false);
			req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8;');
			req.send(this.convertParams(params));
		} else {
			req.open("GET", this.controllerURL + "?" + this.convertParams(params), true);
			req.send(null);
		}

		updateLoadingIcon(1);
		return req;
	}




	this.getXML = function(url, obj, callback , cache) {
		var req = this.getTransportObj();
		var o = obj
		var cb = callback;

		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.status < 400) {
					updateLoadingIcon(-1);
					if(req.responseXML) {
						o[cb](req.responseXML.documentElement);
					}
				} else {
					o[cb](null);
				}
			}
		}


		if(url.indexOf("http:") != -1) {
			req.open("GET", "xmlproxy.php?url=" + escape(url) + "&_nc=" + this.getNoCache(), true);
		} else {
			if(cache){
				req.open("GET", url , true);
			}else{
				req.open("GET", url + "?_nc=" + this.getNoCache(), true);
			}
		}
		updateLoadingIcon(1);
		req.send(null);
		return req;
	}


	this.getUWA = function(url, obj, callBack) {
		var req = this.getTransportObj();
		req.onreadystatechange = function() {
			if(req.readyState == 4) {
				if(req.status < 400) {
					updateLoadingIcon(-1);
					obj[callBack](req.responseXML);
				} else {
					callBack(null);
				}
			}
		}
		if(url.indexOf("http://") == -1) {
			url = "http://" + url;
		}
		req.open("GET", "uwaproxy.php?url=" + encodeURIComponent(url) + "&_nc=" + this.getNoCache(), true);
		req.send(null);
	}



	this.getFeed = function(url, widget, method) {
		var req = this.getTransportObj();
		var widgetId = widget.id;
		req.onreadystatechange = function() {
			if(req.readyState == 4) {
				if(req.status < 400) {
					updateLoadingIcon(-1);
					if(kernel.getWidget(widgetId)) { kernel.getWidget(widgetId)[method](toValue(req.responseText)); }
				}
			}
		}
		if(url.indexOf("http://") == -1) {
			url = "http://" + url;
		}
		req.open("GET", "xmlproxy.php?url=" + encodeURIComponent(url) + "&type=feed&_nc=" + this.getNoCache(), true);
		req.send(null);
		updateLoadingIcon(1);
	}


	this.commonRequest = function(url, callBack, type) {
		var req = this.getTransportObj();
		req.onreadystatechange = function() {
			if(req.readyState == 4) {
				if(req.status < 400) {
					updateLoadingIcon(-1);
					switch(type) {
						case "xml":
						callBack(req.responseXML);
						break;

						case "uwa":
						callBack(req.responseXML);
						break;

						case "feed":
						case "json":
						callBack(toValue(req.responseText));
						break;

						default:
						callBack(req.responseText);
						break;
					}
				} else {
					callBack(null);
				}
			}
		}
		if(url.indexOf("http://") == -1) {
			url = "http://" + url;
		}
		req.open("GET", "xmlproxy.php?url=" + encodeURIComponent(url) + "&type=" + type + "&_nc=" + this.getNoCache(), true);
		req.send(null);
		updateLoadingIcon(1);
	}

}








function XMLRequest() {

	this.send = function(url, widget, callback, params, noProxy) {
		var req;
		if (window.XMLHttpRequest) {
			try { req = new XMLHttpRequest() } catch(e) {}
		} else if (window.ActiveXObject) {
			try { req = new ActiveXObject("MSXML2.XMLHttp") } catch (e) {}
			if (!req) {
				try { req = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
			}
		}

		if(!req) {
			return false;
		}

		//        if(!mozilla_nav) {
		var date = new Date();
		noCache = '&_nc='+ request.getNoCache();
		//        } else {
		//            noCache = '';
		//        }

		var paramStr = "";
		if(params) {
			for(var i in params) {
				paramStr += "&"+i+"="+escape(params[i]);
			}
		}

		var widgetId = widget.id;
		var cf = callback;
		req.onreadystatechange = function() {
			updateLoadingIcon(-1);
			if (req.readyState == 4) {
				if (req.status == 200) {
					updateLoadingIcon(-1);
					try {
						if(kernel.getWidget(widgetId)) {
							kernel.getWidget(widgetId)[cf](req);
						}
					} catch(e) {
						if(console){
							console.log("Exception Here "+ typeof(e));
						}
						//                        alert("Error in \n"+e.fileName+"\nat line: "+e.lineNumber+"\n"+e.message);
					}
				} else {
					//    				alert(req.statusText);
				}
			}
		}

		if(noProxy == true) {
			req.open("GET", url+"?"+noCache, true);
		} else {
			req.open("GET", "xmlproxy.php?url="+escape(url)+paramStr+noCache, true);
		}
		req.send(null);

		updateLoadingIcon(1);
		return req;
	}


}

var XMLParser = {

    xml2hash: function(xmlDocElem, tagItemName) {
        var self = XMLParser;
        var xmlElemArray = new Array;
        var xmlElemRow;
        var objArray = [];
        if(!tagItemName) {
            tagItemName = 'item';
        }
        
        if (xmlDocElem.hasChildNodes()) {
            xmlElemArray = xmlDocElem.getElementsByTagName(tagItemName);
            if(xmlElemArray && xmlElemArray.length == 0) {
                xmlElemArray = xmlDocElem.getElementsByTagName('entry');
            }
            xmlElemRow = xmlElemArray[0];
            for (var j = 0; j < xmlElemArray.length; j++) {
                xmlElemRow = xmlElemArray[j];
                objArray[j] = self.xmlElem2Obj(xmlElemArray[j]);
            }
        }

        var linkEl = xmlDocElem.getElementsByTagName("link")[0];
        if(linkEl) {
            if(linkEl.firstChild) {
                var siteUrl = linkEl.firstChild.nodeValue;
            } else if(linkEl.attributes["href"]) {
                var siteUrl = linkEl.attributes["href"].nodeValue;
            } 
        }

        var title = "";
        if(xmlDocElem.getElementsByTagName("title")[0]) {
            title = xmlDocElem.getElementsByTagName("title")[0].firstChild.nodeValue;
        }

        var updated = "";
        if(xmlDocElem.getElementsByTagName("updated")[0]) {
            updated = xmlDocElem.getElementsByTagName("updated")[0].firstChild.nodeValue;
        } else if(xmlDocElem.getElementsByTagName("pubDate")[0]) {
            updated = xmlDocElem.getElementsByTagName("pubDate")[0].firstChild.nodeValue;
        }


        return title ? { title: title, siteUrl: siteUrl, items: objArray, updated: updated} : {siteUrl: siteUrl, items: objArray, updated: updated};
    },

    parseBookmarks: function(node) {
        var self = XMLParser;
        var res = [];
        var tags = [];
        self.parseBookmarksNode(res, tags, node.getElementsByTagName("DL")[0]);
        return res ? res : null;
    },



    parseBookmarksNode: function(res, tags, node) {
        var self = XMLParser;
        switch(node.tagName) {
            case "A":
                var curTags = clone(tags);
                res.push({ title: node.firstChild.nodeValue, 
                           url: node.getAttribute("HREF"), 
                           tags: curTags.length>0 ? curTags : null});
                break;
            case "H3":
                tags.push(node.firstChild.nodeValue);
                break;
            case "DL":
                for(var i=0; i<node.childNodes.length; i++) {
                    if(node.childNodes[i].nodeType == 1 && node.childNodes[i].firstChild) {
                        self.parseBookmarksNode(res, tags, node.childNodes[i]);
                    }
                }
                tags.pop();
                break;                
        }
        return res;
    },

    
    xmlElem2Obj: function(xmlElem) {
        var self = XMLParser;
        var ret = new Object();
        self.setPropertiesRecursive(ret, xmlElem);
        return ret;
    },
    
    setPropertiesRecursive: function(obj, node) {
        var self = XMLParser;
        if (node.childNodes.length > 0) {
            for (var i = 0; i < node.childNodes.length; i++) {
                if(node.childNodes[i].nodeName == "content") {
                    obj["content"] = self.toHTML(node.childNodes[i].firstChild.nodeValue);
                } else if(node.childNodes[i].nodeName == "content:encoded") {
                    obj["content"] = node.childNodes[i].firstChild.nodeValue;
                } else if(node.childNodes[i].nodeType == 1) {
                    if(node.childNodes[i].firstChild) {
                        if(node.childNodes[i].childNodes.length == 1) {
                            obj[node.childNodes[i].tagName] = node.childNodes[i].firstChild.nodeValue;
                        }
                        else {
                            obj[node.childNodes[i].tagName] = [];
                            self.setPropertiesRecursive(obj[node.childNodes[i].tagName], node.childNodes[i]);
                        }
                    } else if (node.childNodes[i].attributes.length>0) {
                        var attrs = {};
                        for(var a = 0; a < node.childNodes[i].attributes.length; a++) {
                            attrs[node.childNodes[i].attributes[a].nodeName] = node.childNodes[i].attributes[a].nodeValue;
                        }
                        obj[node.childNodes[i].tagName] = attrs;
                    } 
                }
            }
        }
    },
    
    cleanXMLObjText: function(xmlObj) {
        var self = XMLParser;
        var cleanObj = xmlObj;
        for (var prop in cleanObj) {
            cleanObj[prop] = cleanText(cleanObj[prop]);
        }
        return cleanObj;
    },
    
    cleanText: function(str) {
        var self = XMLParser;
        var ret = str;
        ret = ret.replace(/\n/g, '');
        ret = ret.replace(/\r/g, '');
        ret = ret.replace(/\'/g, "\\'");
        ret = ret.replace(/\[CDATA\[/g, '');
        ret = ret.replace(/\]]/g, '');
        return ret;
    },

    toHTML: function(str) {
        var html = str;
        html = html.replace(/\&lt\;/, '<');
        html = html.replace(/\&gt\;/, '>');
        return html;
    },
    
    rendered2Source: function(str) {
        var self = XMLParser;
        var proc = str;    
        proc = proc.replace(/</g, '&lt;');
        proc = proc.replace(/>/g, '&gt;');
        return '<pre>' + proc + '</pre>';
    },

    getXMLDocElem: function(xmlDivId, xmlNodeName) {
        var self = XMLParser;
        var xmlElemArray = [];
        var xmlDocElem = null;
        if (document.all) {
                var xmlStr = document.getElementById(xmlDivId).innerHTML;
                var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.loadXML(xmlStr);    
                xmlDocElem = xmlDoc.documentElement;
          }
          else {
            xmlElemArray = window.document.body.getElementsByTagName(xmlNodeName);
            xmlDocElem = xmlElemArray[0]; ;
          }
          return xmlDocElem;
    }
}

function plog(info) {
    if(DEBUG) {
        desktop.elements.debug_info.innerHTML = info + "<br>" + desktop.elements.debug_info.innerHTML;
    }
}



colorsChart = [
    ["#FFEEEE", "#FFCCCC", "#FFAAAA", "#FF8888", "#FF6666", "#FF4444", "#FF2222", "#FF0000", "#EE0000", "#CC0000", "#AA0000", "#880000", "#770000", "#660000", "#550000", "#440000", "#330000"],
    ["#EEFFEE", "#CCFFCC", "#AAFFAA", "#88FF88", "#66FF66", "#44FF44", "#22FF22", "#00FF00", "#00EE00", "#00CC00", "#00AA00", "#008800", "#007700", "#006600", "#005500", "#004400", "#003300"],
    ["#EEEEFF", "#CCCCFF", "#AAAAFF", "#8888FF", "#6666FF", "#4444FF", "#2222FF", "#0000FF", "#0000EE", "#0000CC", "#0000AA", "#000088", "#000077", "#000066", "#000055", "#000044", "#000033"],
    ["#FFFFEE", "#FFFFCC", "#FFFFAA", "#FFFF88", "#FFFF66", "#FFFF44", "#FFFF22", "#FFFF00", "#EEEE00", "#CCCC00", "#AAAA00", "#888800", "#777700", "#666600", "#555500", "#444400", "#333300"],
    ["#FFEEFF", "#FFCCFF", "#FFAAFF", "#FF88FF", "#FF66FF", "#FF44FF", "#FF22FF", "#FF00FF", "#EE00EE", "#CC00CC", "#AA00AA", "#880088", "#770077", "#660066", "#550055", "#440044", "#330033"],
    ["#FFF0D0", "#FFEECC", "#FFEEBB", "#FFDDAA", "#FFCC99", "#FFC090", "#EEBB88", "#DDAA77", "#CC9966", "#BB8855", "#AA7744", "#886633", "#775522", "#664411", "#553300", "#442200", "#331100"],
    ["#EEFFFF", "#CCFFFF", "#AAFFFF", "#88FFFF", "#66FFFF", "#44FFFF", "#22FFFF", "#00FFFF", "#00EEEE", "#00CCCC", "#00AAAA", "#008888", "#007777", "#006666", "#005555", "#004444", "#003333"],
    ["#FFFFFF", "#EEEEEE", "#DDDDDD", "#CCCCCC", "#BBBBBB", "#AAAAAA", "#A0A0A0", "#999999", "#888888", "#777777", "#666666", "#555555", "#444444", "#333333", "#222222", "#111111", "#000000"]
];


// make interface
function createButtonDom(title, action, icon, id, img_id) {
    if((icon != false) && (icon != null) && (icon != undefined)) {
        if(title) {
        
            var button = 
                { tag: "span", 
                  childs: [
                    { tag: "img", id: img_id, src: icon, 
                      style: { margin: "0px 4px 0px 0px", verticalAlign: "middle"}},
                    { tag: "a", href: "void", events: {onclick: action}, innerHTML: "&nbsp;"+title+"&nbsp;" }
                  ]}
            
            if(id) button.childs[1].id = id;
        } else {
            var button = { tag: "a", href: "void", events: {onclick: action}, 
                           childs: [
                             { tag: "img", id: img_id, src: icon}
                           ]};
            if(id) button.id = id;
        }
    } else {
        var button = { tag: "a", href: "void", events: {onclick: action}, innerHTML: title};
        if(id) button.id = id;
    }

    return button;
}



// tds: [{content:dom, width: ""}]
function createTableDom(tds, width) {
    var table = { tag: "table", width: (width ? width : "95%"), 
                  childs: {
                    tr: { tag: "tr",
                          childs: {} }
                  }
                };
    for(var i=0; i<tds.length; i++) {
        if(typeof(tds[i].content) == "string") {
            table.childs.tr.childs[i] = { tag: "td", width: tds[i].width, innerHTML: tds[i].content };
        } else {
            table.childs.tr.childs[i] = { tag: "td", width: tds[i].width, 
                                          childs: [tds[i].content] };
        }
    }
    return table;
}


//content: array of doms. will be closed with panel sections
function createPanelDom(name, title, content) {
    var m = 
        { tag: "div", className: "panel",
          display: false,
          id: "panel_" + name,
          childs: [
            { tag: "div", className: "panel_header",
              childs: [
                { tag: "div", className: "panel_title",
                  innerHTML: title },
                { tag: "div", className: "panel_close_icon",
                  events: { onclick: "hideElement('panel_" + name + "')"} }
              ]}
          ]}

    for(var i in content) {
        m.childs.push({ tag: "div", className: "panel_section", childs: content[i] });
    }

    return m;
}








// CRC32
(function() { 
    var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";     
 
    /* Number */ 
    crc32 = function( /* String */ str, /* Number */ crc ) { 
        if( crc == window.undefined ) crc = 0; 
        var n = 0; //a number between 0 and 255 
        var x = 0; //an hex number 
        crc = crc ^ (-1); 
        for( var i = 0, iTop = str.length; i < iTop; i++ ) { 
            n = ( crc ^ str.charCodeAt( i ) ) & 0xFF; 
            x = "0x" + table.substr( n * 9, 8 ); 
            crc = ( crc >>> 8 ) ^ x; 
        } 
        return crc ^ (-1); 
    }; 
})();

///////////////////////////////////////////////
//
//  Internal widget
//
///////////////////////////////////////////////

function Widget() {

	this.defaultProfile = {
		title: ""
	}



	this.domModel =
	{ tag: "div", className: "window", id: "window",
	childs: [
	{ tag: "div", id : "window_title" ,
	childs: [
	{ tag: "table", className: "plan_table", style: { width: "100%"},
	childs: [
	{ tag: "tr",
	childs: [
	{ tag: "td", className: "window_caption_left" },
	{ tag: "td", className: "window_caption_middle",
	childs: [
	{ tag: "div", className: "window_caption",
	id: "caption" }
	]},
	{ tag: "td", className: "window_caption_right" }
	]}
	]}
	]},

	{ tag: "div", className: "window_setting", id: "settings"},

	{ tag: "div", className: "window_content",
	id: "content" },

	{ tag: "div", className: "window_footer", id: "footer",
	childs: [
	{ tag: "table", className: "plan_table", style: {width: "100%"},
	childs: [
	{ tag: "tr",
	childs: [
	{ tag: "td", className: "window_footer_left" },
	{ tag: "td", className: "window_footer_middle", innerHTML: "&nbsp;"},
	{ tag: "td", className: "window_footer_right" }
	]}
	]}
	]}
	]}// domModel






	this.init = function() {
		this.elements = {};
		this.id = null;
		this.isReduced = false;
		this.isSettingsReduced = true;
		this.profile = {};
		this.isPreview = false;
	}

	this.init();




	this.open = function(parent, id, profile) {
		this.buildWindow(parent);
		this.buildInterface();
		if(this.elements.window) {
			this.elements.window.wid = this.id;
		}

		this.onOpen();
	}


	this.setParent = function(parentEl) {
		this.elements.window.parentNode.removeChild(this.elements.window);
		parentEl.appendChild(this.elements.window);
	}



	this.buildWindow = function(parent) {
		this.domModel.display = !this.cfg.isOpenHidden;
		if(this.cfg.hasDrag) {
			this.domModel.events = { onmouseover: "checkMouseInOut(1)", onmouseout: "checkMouseInOut(0)"}
		}

		this.buildDomModel(parent, this.domModel);

		if(this.isPreview) {
			this.elements.settings.style.display = "block";
		}

		var m = [];

		if(this.cfg.hasSizeBtn) {
			m.push(
			{ tag: "div",
			className: "caption_left_element",
			display: false,
			id: "showhide_div",
			childs: [
			{ tag: "div", id: "btn_hide", className: "btn_hide",
			title: loc.text("wbtn_hide"),
			events: {onclick: "switchSize()"} },
			{ tag: "div", id: "btn_show", className: "btn_show",
			title: loc.text("wbtn_show"),
			events: {onclick: "switchSize()"},
			display: false}
			]}
			);
		}



		if(this.cfg.hasIcon) {
			m.push(
			{ tag: "div", id: "icon_div",
			className: "caption_left_element",
			childs: [
			{ tag: "img", id: "icon", src: images_url+"widgets/"+this.cfg.module.toLowerCase()+"/ico.gif",
			//			style: { width: "16px", height: "16px"}}
			style: {height: "16px"}}
			]}
			);
		}





		if(this.cfg.hasCloseBtn) {
			m.push(
			{ tag: "a", href: "void",
			title: loc.text("wbtn_close"),
			className: "btn_close",
			display: true ,
			events: {onclick: "close()"},
			id: "btn_close" }
			);
		}


		if(this.cfg.hasSettingsBtn) {
			m.push(
			{ tag: "a", href: "void",
			title: loc.text("wbtn_settings"),
			className: "btn_settings",
			display:false,
			events: {onclick: "switchSettings()"},
			id: "btn_settings" }
			);
		}


		if(this.cfg.hasRefreshBtn) {
			m.push(
			{ tag: "a", href: "void",
			title: loc.text("wbtn_refresh"),
			className: "btn_refresh",
			display: false,
			events: {onclick: "refresh()"},
			id: "btn_refresh" }
			);
		}

		m.push(
		{ tag: "div", id: "title", className: "caption_title" }
		);

		this.buildDomModel(this.elements["caption"], m);
	}



	this.initDtagAndDrop = function() {
		if(this.cfg.hasDrag) {
			this.elements.caption.style.cursor = 'move';
			if(this.cfg.hasColor) {
				this.elements.caption.style.background = this.cfg.colorValue;
			}

			this.elements.window.drag = new Drag(this.elements.window, this.elements.caption);
		}
	}


	this.buildInterface = function() {
		if(!this.isPreview) {
			this.initDtagAndDrop();
		}
		if(this.cfg.hasTitle) {
			this.buildDomModel(this.elements.settings,
			{ tag: "div", className: "settings_section",
			childs: [
			{tag: "span", innerHTML: loc.text("inp_title"), className: "settings_label"},
			{tag: "input", id: "input_title", type: "text", size: "13", className: "settings_control"},
			{tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "settingsSetTitle()"}, className: "settings_control button"}
			]}
			);
		}
		this.onBuildInterface();
	}


	this.disableOnClosePrompt = false;
	this.isForceClose = false;

	this.forceClose = function() {
		this.isForceClose = true;
		this.disableOnClosePrompt = true;
		this.close();
	}
	this.hideConfirmPopUp = function() {
		desktop.hideActivePopup()
	}
	
	this.close = function() {
				
		confirmCloseDiv.innerHTML = '';
		var closeDiv = [
		{tag: "div", className: "alert",
		childs:[
			{tag: "table", width:"100%", border:"0", cellspacing:"0", cellpadding:"12",
				childs: [
					{tag: "tr",
						childs: [
							{tag: "td", className: "ttl",
								childs: [
									{tag: "strong", className: "fr", innerHTML: this.elements.title.innerHTML.strip_tags()},
									{tag:"img", src: images_url+"static/client/close_tools.gif", className: "fl", events:{onclick:"hideConfirmPopUp()"}}
								]
							}
						]
					},
					{tag: "tr",
						childs: [
							{tag: "td", className:"fr", innerHTML: loc.text("desktop_confirm_widget_remove")}
						]
					},
					{tag: "tr",
						childs: [
							{tag: "td",id: 'confirmBtnDiv', 			
								childs:[			
									{tag: "input", type: "button",className: "btns", value:"نعم", events:{onclick: "closeWidget()"}},
									{tag: "input", type: "button",className: "btns", value:"لا", events:{onclick: "hideConfirmPopUp()"}}
								]
							}
						]
					}
			]
		}
		]
		}
		];
		
		//confirmCloseDiv.innerHTML = loc.text("desktop_confirm_widget_remove");
        
                   		
		var flag = (this.cfg.hasOnCloseConfirm && !this.disableOnClosePrompt) ? false : true;
				
		if(flag) {
				
			this.closeWidget;
		} else {
		this.buildDomModel(confirmCloseDiv,closeDiv);
		desktop.showPopup('closeDiv', {top: "30%"});					
		}
	}



	this.closeWidget = function () {		
			this.onClose();
			
			kernel.freeWidget(this.id);
			if(this.elements.window) {
				deleteEl(this.elements.window);

				this.elements.window.innerHTML = '';
				this.elements.window = null;
			}

			this.profile = false;
			this.save();

			if(this.cfg.hasDrag && !this.isForceClose) {
				desktop.savePanels();
			}	
			this.hideConfirmPopUp();	
	}
	this.setTitle = function(html) {
		this.elements.title.innerHTML = html.truncate(22);
	}
	this.checkMouseInOut = function(mouse_in) {
		if (mouse_in==1 || this.isSettingsReduced==false) {
			if(this.cfg.hasCloseBtn && !this.isPreview)    this.elements.btn_close.style.display = 'block';
			if(this.cfg.hasSettingsBtn) this.elements.btn_settings.style.display = 'block';
			if(this.cfg.hasRefreshBtn)  this.elements.btn_refresh.style.display = 'block';
			if(this.cfg.hasSizeBtn){
				this.elements.showhide_div.style.display = 'block';
				if(this.cfg.hasIcon) this.elements.icon_div.style.display = 'none';
			}

		}
		else {
			if(this.cfg.hasCloseBtn)    this.elements.btn_close.style.display = 'none';
			if(this.cfg.hasSettingsBtn) this.elements.btn_settings.style.display = 'none';
			if(this.cfg.hasRefreshBtn)  this.elements.btn_refresh.style.display = 'none';
			if(this.cfg.hasSizeBtn){
				this.elements.showhide_div.style.display = 'none';
				if(this.cfg.hasIcon) this.elements.icon_div.style.display = 'block';
			}
		}
	}


	this.switchSize = function() {
		if(this.isReduced) {
			this.show();
		} else {
			this.hide();
		}
	}


	this.show = function() {
		hideEl(this.elements.btn_show);
		showEl(this.elements.btn_hide);

		if(this.elements.content) {
			showEl(this.elements.content);
		}
		this.onShow();
		this.isReduced = false;
	}


	this.hide = function() {
		hideEl(this.elements.btn_hide);
		showEl(this.elements.btn_show);

		if(this.elements.content) {
			hideEl(this.elements.content);
		}

		this.hideSettings();
		this.onHide();
		this.isReduced = true;
	}



	this.switchSettings = function() {
		if(this.isSettingsReduced) {
			this.showSettings();
		} else {
			this.hideSettings();
		}
	}


	this.showSettings = function() {
		this.onShowSettings();
		showEl(this.elements.settings);
		this.isSettingsReduced = !this.isSettingsReduced;
	}


	this.hideSettings = function() {
		if(this.elements.settings) {
			hideEl(this.elements.settings);
			this.isSettingsReduced = !this.isSettingsReduced;
		}
	}


	this.attachEvent = function(el, e, cmd) {
		var wid = this.id;
		if(mozilla_nav) {
			el.setAttribute(e, "kernel.getWidget("+wid+")."+cmd+";");
		} else {
			el[e] = new Function("kernel.getWidget("+wid+")."+cmd+";");
		}
	}


	this.attachClickEvent = function(el, e, cmd) {
		var code = "kernel.getWidget(" + this.id + ")." + cmd + ";"
		var f = function(e) {
			this.blur();
			eval(code);
			return killEvent(e);
		}
		el[e] = f;
	}


	this.buildDomModel = function(parentEl, data) {
		if(data["tag"]) {
			var el = document.createElement(data.tag);
			for (p in data) {		
				switch(p) {
					case null, "tag", "childs": break;

					case "cn":
					el.className = data.cn;
					break;

					case "id":
					this.elements[data.id] = el;
					break;

					case "style":
					for(var s in data.style) {
						el.style[s] = data.style[s];
					}
					break;


					// [{},...] || {start,end,step}
					case "options":
					if(data.options.start != undefined) {
						var step = data.options.step || 1;
						var options = [];
						for(var i = data.options.start; i <=data.options.end; ) {
							options.push( { text: i, value: i });
							i += step;
						}
					} else {
						var options = data.options;
					}
					if(options.length) {
						for(var i=0; i<options.length; i++) {
							el.options.add(new Option(options[i].text, options[i].value));

							if(options[i].isBold) {
								el.options[el.options.length - 1].style.fontWeight = "bold";
							}
						}
					}
					break;

					case "src":
					var src = data.src;
					if(src.indexOf("http") == -1) {
						src = images_url+src;

					}

					if(ie_nav) {
						var setSrc = function() { el.src = src }
						setTimeout(setSrc, 200);
					} else {
						el.src = src;
					}
					break;

					case "display":
					if(!data[p]) {
						el.style.display = 'none';
					}
					break;

					case "href":
					if(data.href == "void") {
						el.href = "javascript:void(0);";
					} else if(data.tag == "a") {
						this.attachClickEvent(el, "onclick", data.href);
						el.href = "javascript:void(0);";
					} else {
						el.href = data.href;
					}
					break;


					case "html":
					el.innerHTML = data.html;
					break;

					case "sysHref":
					el.href = data.sysHref;
					break;

					case "events":
					var wid = this.id;
					if(typeof(data.events) == "object") {
						for(var e in data.events) {
							switch(e) {
								case "onenter":
								var wid = this.id;
								el.onkeyup = function(event) {
									event = fix_event(event);
									if(event.keyCode == 13) {
										eval("kernel.getWidget(wid)."+data.events[e]+";");
									}
								}
								break;
								default:
								this.attachEvent(el, e, data.events[e]);
								break;
							}
						}
					}
					break;

					case "sysEvents":
					if(typeof(data.sysEvents) == "object") {
						for(var e in data.sysEvents) {
							el.setAttribute(e, data.sysEvents[e]+";");
						}
					}
					break;
					case "colspan" :
					el.colSpan = data.colspan;
					break;
					case "cellspacing" :
					el.cellSpacing = data.cellspacing;
					break;
					case "cellpadding" :
					el.cellPadding = data.cellpadding;
					break;
					default:
					el[p] = data[p];
					break;
				}
			}

			parentEl.appendChild(el);

			if(data.tag == "table") {
				parentEl = el;
				var el = document.createElement("tbody");
				if(data.id) {
					this.elements[data.id+"_tbody"] = el;
				}
				parentEl.appendChild(el);
			}

			if(data.childs) {
				this.buildDomModel(el, data.childs);
			}

		} else if (typeof data == "object") {
			//            for(var i=0; i<data.length; i++) {
			for(var i in data) {
				this.buildDomModel(parentEl, data[i]);
			}
		}

	}





	this.settingsSetTitle = function() {
		var t = trim(this.elements.input_title.value);
		if(t != this.profile.title) {
			this.profile.title = t
			this.setTitle(t);
			this.save();
		}
	}



	this.save = function() {
		if(!this.isPreview) {
			profiler.saveProfile(this);
		}
	}



	this.onOpen = function() {}
	this.onBuildInterface = function() {}
	this.onClose = function() {}
	this.onShow = function() {}
	this.onHide = function() {}
	this.onShowSettings = function() {}
	this.onDrag = function() {}

	this.timerHandler = function() {}
	this.refresh = function() {}
	this.dispatchMsg = function() {}




	// SYS

	this.hideElement = function(id) {
		if(this.elements[id]) {
			//	jQuery( this.elements[id]).hide("slow");
			this.elements[id].style.display = 'none';
		}
	}


	this.showElement = function(id, display) {

		if(this.elements[id]) {

			//	jQuery( this.elements[id]).show("slow");
			this.elements[id].style.display = display ? display : 'block';
		}
	}


	this.deleteElement = function(id) {
		if(this.elements[id].parentNode) {
			this.elements[id].parentNode.removeChild(this.elements[id]);
		}
		this.elements[id] = null;
	}


	//////////////////////////////////////////////////////////////
	// Interface elements
	//////////////////////////////////////////////////////////////

	this.ieIdCounter = 0;

	this.getExpanderModel = function(title, content) {
		this.ieIdCounter++;
		var id = "_ie" + this.ieIdCounter;
		var tid = id + "_title";
		var cid = id + "_content";
		var m =
		{ tag: "div", className: "expander_box",
		childs: [
		{ tag: "div", className: "title_closed",
		id: tid,
		html: title,
		isExtended: false,
		events: { onclick: "switchExtender('" + id + "')" }},
		{ tag: "div", className: "content",
		id: cid,
		display: false,
		childs: content }
		]}
		return m;
	}


	this.switchExtender = function(id) {
		var tid = id + "_title";
		var cid = id + "_content";
		if(this.elements[tid].isExtended) {
			this.hideElement(cid);
			this.elements[tid].className = "title_closed";
		} else {
			this.showElement(cid);
			this.elements[tid].className = "title_opened";
		}
		this.elements[tid].isExtended = !this.elements[tid].isExtended;
	}
}

DRAG_NONE = 0;
DRAG_MOVE = 1;
DRAG_ANIM = 1;

Drag = function(win, caption) {

    var div = win;
    var action = DRAG_NONE;
    var dragging = false;
    var targetPos = {left: 0, top: 0};
    var animSteps = 5;
    var animFrame = 0;
    
    var offset = {left: 0, top: 0};
    var tid = null;


    function calcOffset(event) {
        event = fix_event(event);

        var pos = getElPos(div);
        offset.left = event.clientX - pos.left;
        offset.top = event.clientY - pos.top;
    }

    function drag(event) {
        event = fix_event(event);
    	
        if(action == DRAG_MOVE) {
            var l = event.clientX - offset.left;
            var h = event.clientY - offset.top;

            div.style.left = l + "px";
            div.style.top = h + "px";

            desktop.processArea({left: l + Math.ceil(div.offsetWidth / 2), 
                                 top: h + 16});
        }
    }


    function processAnimation() {
        var f = function() {
            clearTimeout(tid);
            animFrame ++;

            if(animFrame < animSteps) {
                var dPos = { 
                    left: div.offsetLeft, 
                    top: div.offsetTop 
                }

                var newPos = {
                    left: Math.floor(dPos.left + (targetPos.left - dPos.left) / animSteps),
                    top: Math.floor(dPos.top + (targetPos.top - dPos.top) / animSteps)
                }

                div.style.left = newPos.left + "px";
                div.style.top = newPos.top + "px";
                tid = setTimeout(f, 50); 
            } else {
                placeWindow();
            }
        }
        tid = setTimeout(f, 50); 
    }


    function stopDrag(event) {
        event = fix_event(event);

        document.onmousemove = null;
        document.onmouseup = null;
        document.ondrag = null;
        document.body.onselectstart = null;
        document.onselectstart = null;

        targetPos = getElPos(desktop.elements.area);
        targetPos.top -= 14;
        animFrame = 0;

        action = DRAG_ANIM;
        processAnimation();
    }


    function placeWindow() {
        clearTimeout(tid);
        
        div.style.position = 'static';
        desktop.elements.area.parentNode.insertBefore(div, desktop.elements.area);

        div.style.width = 'auto';
        desktop.stopArea();
        desktop.savePanels();
        action = DRAG_NONE;
    }



    function startDrag(event) {
        event = fix_event(event);
        if(action != DRAG_NONE) {
            return false;
        }

        document.ondrag = function () { return false; }
        document.body.ondrag = function () { return false; }
        document.onselectstart = function () { return false; }
        document.body.onselectstart = function () { return false; }   
        
        action = DRAG_MOVE;

        calcOffset(event);
        
        document.onmousemove = function(event) { drag(event) }
        document.onmouseup = function(event) { stopDrag(event) }

        putEl(div);
    }


    function putEl(el) {
        var left = getLeft(el);
        var top = getTop(el);
        var width = el.offsetWidth;

        desktop.startArea(el);

        el.parentNode.removeChild(el); 
        document.body.appendChild(el);

        el.style.position = 'absolute';
        el.style.left = left + "px";
        el.style.top = top + "px";
        el.style.width = width + "px";
    } 


    caption.onmousedown = function(event) { 
        event = fix_event(event);
        if(action == DRAG_MOVE) {
            stopDrag(event);
        } else {
            var e = event.target;
            
            while(e.onclick == null && e != this) {
                e = e.parentNode;
            }
            if(e == this) startDrag(event); 
        }
    }

    function fix_event(event) {
        if (!event) {
            event = window.event;
        }
        if (event.target) {
    	    if (event.target.nodeType == 3) event.target = event.target.parentNode
        } else if (event.srcElement) {
    	    event.target = event.srcElement
        }
        return event
    }

}







// events: onstart, onover, onstop
// mode: drag, menu, all
EntityHandler = function(el, mode, events) {
    var div = el;
    var divClone = null;
    var dragging = false;

    var offset = {left: 0, top: 0};
    var startPos = {left: 0, top: 0};
    var events = events ? events : {};
    var belongElement = null;

    function waitForDrag(event) {
        event = fix_event(event);
        if( (Math.abs(event.clientX - startPos.left) > 4) || (Math.abs(event.clientY - startPos.top) > 4)) {
//            desktop.isFileDrag = true;
            
            dragging = true;

            offset = {left: div.offsetWidth + 2,
                      top: div.offsetHeight + 2};

            document.onmousemove = function(e) { drag(e) }
            document.onmouseup = function(e) { stopDrag(e) }

            divClone = div.cloneNode(true);
            divClone.style.cssText = divClone.style.cssText + ";opacity: 0.75; -moz-opacity: 0.75; -khtml-opacity: 0.75; filter: alpha(opacity=75);";
            document.body.appendChild(divClone);
            divClone.style.position = 'absolute';
            divClone.style.width = div.offsetWidth + "px";
            divClone.style.height = div.offsetHeight + "px";

            if(events.onDragStart) {
                events.onDragStart(div.entityInfo);
            }
            if(event.target.entityInfo && events.onElementOver) {
                events.onElementOver(event.target.entityInfo);
            }
        }
    }


    function drag(event) {
        if(dragging) {
            event = fix_event(event);

            divClone.style.left = event.clientX + 2 + "px";
            divClone.style.top = event.clientY + 2 + "px";

            if(event.target.entityInfo && events.onElementOver) {
                events.onElementOver(event.target.entityInfo);
            }
 
        }
    }



    function startDrag(event) {
        event = fix_event(event);
        document.ondrag = function () { return false; }
        document.body.ondrag = function () { return false; }
        document.onselectstart = function () { return false; }
        document.body.onselectstart = function () { return false; }   
        
        document.onmousemove = function(e) { waitForDrag(event) }
        document.onmouseup = function(e) { stopDrag(event) }

        startPos = {left: event.clientX, top: event.clientY};
        return false;
    }


    function stopDrag(event) {
        event = fix_event(event);

        document.onmousemove = null;
        document.onmouseup = null;
        document.ondrag = null;
        document.body.onselectstart = null;
        document.onselectstart = null;

        desktop.isFileDrag = false;

        if(div.onmouseout) {
            div.onmouseout();
        }

        if(divClone) {
            deleteEl(divClone);
        }

        if(events.onDragStop && dragging) {
            events.onDragStop(div.entityInfo);
        }

        dragging = false;
    }

 


    switch(mode) {
        case "tabs_drag":
            div.onmousedown = function(event) { 
                desktop.hideTabOptions();
                event = fix_event(event);
                if(dragging) {
                    stopDrag(event);
                } else {
                    startDrag(event);
                }
                    if (event.stopPropagation) {
                        event.stopPropagation();
                        event.preventDefault();
                    } else if(window.event) {
                        window.event.cancelBubble = true;
                        window.event.returnValue = false;			
                    }
                return false;
            }
    }


}




// Tracker

Tracker = function(gripper, params) {

    var dragging = false;
    var offset;
    var gripperOffset = - 3;
    var gripperPos = Math.round(params.width * params.value / (params.end - params.start));

    gripper.parentNode.style.width = params.width + "px";
    setGripperPos();


    function setGripperPos() {
        gripper.style.marginLeft = gripperPos + gripperOffset + "px";
    }

    function getValue() {
        return params.start + Math.round( (gripperPos / params.width) * (params.end - params.start));
    }


    function calcOffset(event) {
        event = fix_event(event);
        offset = event.clientX - gripperPos;
    }


    function drag(event) {
        event = fix_event(event);
        gripperPos = event.clientX - offset;
        if(gripperPos < 0) {
            gripperPos = 0;
        } else if(gripperPos > params.width) {
            gripperPos = params.width;
        }
        setGripperPos();
        if(params.onchange) {
            params.onchange(getValue());
        }
    }


    function stopDrag(event) {
        event = fix_event(event);

        document.onmousemove = null;
        document.onmouseup = null;
        document.ondrag = null;
        document.body.onselectstart = null;
        document.onselectstart = null;

        if(params.onstop) {
            params.onstop(getValue());
        }
        dragging = false;
    }


    function startDrag(event) {
        event = fix_event(event);
        if(dragging) {
            return false;
        }
        document.ondrag = function () { return false; }
        document.body.ondrag = function () { return false; }
        document.onselectstart = function () { return false; }
        document.body.onselectstart = function () { return false; }   
        calcOffset(event);
        document.onmousemove = function(event) { drag(event) }
        document.onmouseup = function(event) { stopDrag(event) }
        dragging = true;
    }


    gripper.onmousedown = function(event) { 
        event = fix_event(event);
        if(dragging) {
            stopDrag(event);
        } else {
            var e = event.target;
            while(e.onclick == null && e != this) {
                e = e.parentNode;
            }
            if(e == this) startDrag(event); 
        }
    }


    function fix_event(event) {
        if (!event) {
            event = window.event;
        }
        if (event.target) {
    	    if (event.target.nodeType == 3) event.target = event.target.parentNode
        } else if (event.srcElement) {
    	    event.target = event.srcElement
        }
        return event
    }

}




function startPage() {

    request = new Request();
    xmlRequest = new XMLRequest();
    kernel = new Kernel();
    loc = new Loc();

    loc.onLoad = function() {
    	
        auth = new Auth();
        auth.id = kernel.getUniqueId(auth);
        kernel.addWidget(auth);

        auth.onLoad = function() {
        		
            profiler = new Profiler();
            profiler.id = kernel.getUniqueId(profiler);
            kernel.addWidget(profiler);

            profiler.onLoad = function() {
            	
                desktop = kernel.runWidget("Desktop", elById("desktop_body"));
                window.onresize = desktop.onWindowResize;

                auth.open(desktop.addPopup("auth"));

                //settings = kernel.runWidget("Settings", desktop.addPopup("settings"));
                settings = kernel.runWidget("Settings", desktop.getSettingsCont());
                menu = kernel.runWidget("Menu", desktop.getMenuCont());
                feedback = kernel.runWidget("Feedback", desktop.addPopup("feedback"));
                custompage = kernel.runWidget("Custompage", desktop.addPopup("custompage"));
                sendtofriend = kernel.runWidget("SendToFriend", desktop.addPopup("sendtofriend"));
                rssreader = kernel.runWidget("RssReader", desktop.addPopup("rssreader"));
                flashPlayer = kernel.runWidget("FlashPlayer", desktop.addPopup("flashplayer"));
                confirmCloseDiv = desktop.addPopup('closeDiv');								
                desktop.wakeUp();
                if(auth.firstTime != "0" && auth.isLogged()){
                	menu.showWizard();
                }
            }
            profiler.loadProfile();
        }
        auth.start();
    }
    loc.start();
}



SYS_WIDGETS_ID = 1;
USER_WIDGETS_ID = 100;


cfgWidget = {
    hasIcon: true,
    hasSizeBtn: true,
    hasCloseBtn: true,
    hasRefreshBtn: true,
    hasSettingsBtn: true,
    hasDrag: true,
    hasOnCloseConfirm: true,
    hasProfile: true,
    isOpenHidden: false,
    isSystem: false,
    title: "",
    module: "base",
    uniqueId: false,
    hasTitle: true,
    hasColor: false,
    colorValue: '#555555',
    saveMethod: "GET"
}

function Kernel() {

    this.widgets = [];        

    this.getUniqueId = function(w) {
        if(w.cfg.uniqueId) {
            return w.cfg.uniqueId;
        } else {
            var newId = USER_WIDGETS_ID;
            while(this.widgets[newId]) newId++;
            return newId;
        }
    }


    this.getWidget = function(id) {
        return this.widgets[id];
    }

    this.addWidget = function(widget) {
        this.widgets[widget.id] = widget;
    }
    
    
    this.freeWidget = function(id) {
        this.widgets[id] = null;
    }


    this.runWidget = function(className, parent, id, profile, objvars) {
        var code = 'var w = new ' + className + '();';
        try {
            eval(code);
        } catch(e) { 
            // Debug info
//            alert("Can't run '" + className + "' widget.\n" + e.message); 
        }
        if(w) {
            profile = profile || false;

            w.id = id || w.cfg.uniqueId || this.getUniqueId(w);

            if(typeof(objvars) == "object") {
                for(var i in objvars) {
                    w[i] = objvars[i];
                }
            }

            kernel.addWidget(w);
            for(var c in cfgWidget) {
                if(typeof(w.cfg[c]) == "undefined") {
                    w.cfg[c] = cfgWidget[c];
                }
            }

            if(w.cfg.hasProfile) {
                profiler.registerWidget(w);
                if(profile) {
                    for(var p in profile) {
                        w.profile[p] = profile[p];
                    }
                }
            }
           
            w.open(parent, false, profile);
            return w;
        }
    }


 
    this.timers = [];
    this.processTimer = function(widgetId, period, noAction) {
        if(kernel.widgets[widgetId]) {
            if(noAction != true) {
                kernel.getWidget(widgetId).timerHandler();
            }
            kernel.timers[widgetId] = setTimeout("kernel.processTimer("+widgetId+","+period+")", period);
        }
    }

    this.stopTimer = function(widgetId) {
        if(this.timers[widgetId] != undefined) {
            clearTimeout(this.timers[widgetId]);
            this.timers[widgetId] = undefined;
        }
    }

}




/*******************************************
 *
 *   Languages data
 *
 *******************************************/

function Loc() {


    this.data = {};


    this.start = function() {
        this.lang = getCookie("lng");
        if(this.lang == "") {
            this.lang = "AR";
        }
        request.getXML("lang/" + this.lang.toLowerCase() + ".xml", this, "parseLangXML" , true);
    }


    this.swapLang = function(lang) {
        setCookie('lng', lang);
        window.location.reload(true);
    }

    this.parseLangXML = function(xml) {
        this.data = this.getHashList(xml, "string", "id");
        this.onLoad();
    }


    this.text = function(id, param) {
        var text = this.data[id] ? this.data[id] : "loc:" + id;

        if(param && text != '') {
            if(typeof(param) == "object") {
                for(var i in param) {    
                    var mask = new RegExp("%"+i+"%", "ig");
                    text = text.replace(mask, param[i]);
                }
                return text;
            } else {
                return text.replace(/(%\w*%)/ig, param);
            }
        }
        return text;
    }


    this.getHashList = function(node, tagName, key) {
        var hash = {};
        if(node) {
            var nodes = node.getElementsByTagName(tagName);
            for(var i=0; i<nodes.length; i++) {
                hash[nodes[i].getAttribute(key)] = nodes[i].firstChild ? nodes[i].firstChild.nodeValue : "";
            }
        }
        return hash;
    }


    this.onLoad = function() {}
}

function Desktop() {

    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasCloseBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasOnCloseConfirm: false,
        isSystem: true,
        title: "",
        module: "desktop",
        uniqueId: SYS_WIDGETS_ID + 1,
        saveMethod: "POST"
    }


    this.defaultProfile["title"] = "";
    this.defaultProfile["theme"] = "default";
    this.defaultProfile["background"] = { top: false, bottom: false };
    this.defaultProfile["header_size"] = 0;
    
    this.defaultProfile["tabs"] = []; // [ {t: title, c: columner_id, i }, ...]
    this.defaultProfile["order"] = []; // array of tab indexes

if(!auth.isLogged()) {
	this.nonUserDiv = [
		{tag: "div", className: "startNow", innerHTML: '<a href="javascript:checkLogin()" ><img src="static/images/spacer.gif" border="0" alt="" width="229" height="55" /></a>'}
	];
} else {
	this.nonUserDiv = [];
}
	 
    this.domModel = [
        { tag: "div", display: false, id: "tmp" },

        { tag: "div", cn: "desktop_header",
          id: "header",
          childs: [
            // top links
            { tag: "div", id: "top_line",
              cn: "top_line",
              childs: [
                { tag: "div", cn: "float_left", id :"page_custom_btns" , 
                  childs: [
                  {tag: "table", style:{direction: "rtl"}, border: "0", cellpadding: "5", cellspacing: "0",
                  	childs: [
                  		{tag: "tr",
                  			childs: [
                  				{tag: "td"  , id : "_menu_btn",
                  					childs: [
                  						//createButtonDom(loc.text("menu_title"), "switchMenu()", "widgets/menu/ico.gif")
                  						createButtonDom(false, "switchMenu()", "static/images/addwidget.gif")
                  						//createButtonDom(false, "showPrevPhoto()", "widgets/flickr/img/previous.gif")
                  						
                  					]
                  				},
                  				{tag: "td" , id : "_skin_btn",
                  					childs: [
                  						//createButtonDom(loc.text("desktop_lnk_settings"), "switchSettings()", "static/client/settings.gif")
                  						createButtonDom(false, "switchSettings()", "static/images/skin.gif")
                  					]
                  				
                  				}
                  			]
                  		}
                  	]
                  }                    
                  ]},
                { tag: "div", cn: "float_right",                
                	childs:[
                		{tag: "table", cn: "btnsMini", dir: "rtl", border: "0", cellspacing: "0", cellpadding: "0",
                			childs: [
                				{tag: "tr",
                					childs: [                						                				
                						{tag: "td", width: "35", cn: "b1", innerHTML: "&nbsp;"},
                						{tag: "td", id: "wizardBtn"},
                						{tag: "td", width: "35", cn: "b0", innerHTML: "&nbsp;"},
                						{tag: "td",innerHTML : '<a target="_blank" href="http://ecare.m3com.com.sa/index.php?_m=knowledgebase&_a=view&parentcategoryid=33&pcid=0&nav=0">أسئلة شائعة</a>'},                						                				
                						{tag: "td", width: "35", cn: "b2", innerHTML: "&nbsp;"},
                						{tag: "td",
                							childs: createButtonDom(loc.text("desktop_show_all"), "showAll()")
                						},                				
                						{tag: "td", width: "35", cn: "b3", innerHTML: "&nbsp;"},
                						{tag: "td",
                							childs: createButtonDom(loc.text("desktop_hide_all"), "hideAll()")
                						}                				
                					]
                				}
                			]
                		}
                	]   
                },
                { tag: "span", id: "authButton"},
				 ]},
            // title
            { tag: "div", cn: "title_section",
              id: "title_section",
              childs: [
                { tag: "div", className: "title",
                  childs:[
                    { tag: "span", id: "title_box", className: "desktop_title_box", events:{onmouseover:"mouseOvr('title_box','desktop_title_box_hover')", onmouseout:"mouseOvr('title_box','desktop_title_box')"}},
                    { tag: "input", id: "title_input", className: "desktop_title_input", display: false}
                  ]},
                { tag: "div", className: "section", style: {height: "1px", overflow: "hidden"},
                  childs:[
                    { tag: "span", id: "title_box_tmp", className: "desktop_title_box"}
                  ]}
              ]},
              this.nonUserDiv
              ,
             //Menu --- Moutaz Addition
             { tag:"div" , style:(ie_nav ?  {width: "975px" ,  margin:"auto"} : {}) , id : "menu_containter"} ,
             //Settings
             { tag:"div" , style:(ie_nav ?  {width: "975px" ,  margin:"auto"} : {}) , id : "settings_containter"} ,
             
            

            // tabs
            { tag: "div", className: "tabs_panel",display:false  ,
              id: "tabs",
              childs: [
                { tag: "div", id: "add_page_button",
                  className: "tab_box",
                  events: {onclick: "addNewTab()"}, 
                  childs: [
                    { tag: "div", className: "tab_left" },
                    { tag: "div", className: "tab_middle",
                      childs: [
                        { tag: "div", className: "tab_add_icon" }
                      ]},
                    { tag: "div", className: "tab_right" }
                  ]}
              ]}            
          ]},

        // widgets
        { tag: "div", cn: "desktop_columns",
          id: "desktop_columns" },
          
        { tag: "div", id: "area", className: "area", name: "area", display: false},
        { tag: "div", id: "tab_area", className: "tab_area", name: "area", display: false},

        // Tabs menu
        createPanelDom("tab", loc.text("desktop_tab_options"), [
          [ { tag: "span", innerHTML: "Title: "},
            { tag: "input", type: "text", id: "input_tab_title" },
            { tag: "input", type: "button", value: loc.text("btn_set"),
              events: { onclick: "renameTab()" }} ],

          [ { tag: "div", innerHTML: loc.text("desktop_select_tab_icon")},
            { tag: "div", id: "tab_icons_box" },
            { tag: "div", 
              childs: [
                { tag: "a", href: "void",
                  innerHTML: loc.text("desktop_delete_tab_icon"),
                  events: { onclick: "deleteTabIcon()"}}
              ]}],

          [ { tag: "span", innerHTML: loc.text("desktop_panels_count") },
            { tag: "input", type: "button", value: " 1 ",
              events: { onclick: "setPanelsCount(1)" }},
            { tag: "input", type: "button", value: " 2 ",
              events: { onclick: "setPanelsCount(2)" }},
            { tag: "input", type: "button", value: " 3 ",
              events: { onclick: "setPanelsCount(3)" }},
            { tag: "input", type: "button", value: " 4 ",
              events: { onclick: "setPanelsCount(4)" }} ]
        ])
    ]


    this.newFeedUrl = null;


    this.onOpen = function() {
        this.buildDomModel(document.body, { tag: "link", id: "themes_loader", rel: "stylesheet", media: "screen"});
        this.recentWidgetsStorage = kernel.runWidget("RecentWidgetsStorage", document.body);
        this.applyTheme();
        this.applyHeaderSize();
        this.elements["panel_tab"].style.position = "absolute";
        this.elements["panel_tab"].style.width = "250px";

        if (customPagesHTML != '') {
            this.elements["custom_pages_links"].innerHTML += "&nbsp;|&nbsp;"+customPagesHTML;
        }

        this.buildDomModel(document.body, [
            { tag: "div", id: "popups",
              display: false,
              cn: "popups_box" },
            { tag: "div", id: "overlay",
              events: { onclick: "hideActivePopup()"},
              display: false,
              cn: "page_overlay" }
        ]);
    }



    this.applyHeaderSize = function() {
        var s = this.profile["header_size"];
        this.elements["title_section"].style.margin = "0" + s + "px 0 " + s + "px";
    }


    this.applyBackgrounds = function() {
        var pt = this.profile["background"].top;
        if(pt) {
            var bgTop = pt["mode"] ? (pt.value + " " + pt.mode + " " + pt.align) : pt;
        } else {            
            var bgTop = "url(themes/" + this.profile["theme"] + "/images/bg_top.jpg) repeat-x";
        }
        this.elements["header"].style.background = bgTop;
		/*
        var pb = this.profile["background"].bottom;
        if(pb) {
            var bgDoc = pb["mode"] ? (pb.value + " " + pb.mode + " " + (pb.fix ? "fixed" : "")) : pb;
        } else {
            var bgDoc = "url(themes/" + this.profile["theme"] + "/images/bg_doc.jpg) repeat";
        }
        document.body.style.background = bgDoc;
        */
    }



    this.applyTheme = function() {
        this.elements["themes_loader"].href = "themes/" + this.profile["theme"] + "/theme.css?v=" + (Math.random() * 1000000);
        this.applyBackgrounds();
    }

    ////////////////////////////
    // Recent UWA widgets

    this.getRecentWidgetsList = function() {
        return this.recentWidgetsStorage.profile["list"];
    }


    this.addRecentWidget = function(info) {
        var rw = this.recentWidgetsStorage;
        for(var i=0; i<rw.profile["list"].length; i++) {
            if(rw.profile["list"][i].url == info.url) {
                rw.profile["list"].splice(i, 1);
                break;
            }
        }
        if(rw.profile["list"].length > 15) {
            rw.profile["list"].pop();
        }
        rw.profile["list"].unshift(info);
        rw.save();
    }


    ////////////////////////////
    // Main menu

	this.mouseOvr = function ( id, cName ) {		
		this.elements[id].className = cName;
	}
    this.isMenuShow = false;

    this.switchMenu = function() {
    if(auth.isLogged()) {
        if(this.isMenuShow) {
            menu.hide();
        } else {
            menu.show();
        }    
    } else {
    	//Portal function
		checkLogin();    
    }   
    }

    this.isSettingsShow = false;

    this.switchSettings = function() {
        
        if(this.isSettingsShow) {
            settings.hide();
        } else {
            settings.show();
        }         
    }
	
	this.buildClosePopUp = function() {
	//<strong class="fr">البريد</strong><a href="#"><img onclick="hideActivePopup()" class="fl" src="static/client/close_tools.gif" border="0" alt="" width="11" height="11" /></a>
	}
    // Popups

    this.popupsHistory = [];
	this.custom_shadowbox;	
    this.showPopup = function(name, params) {
        var l = this.popupsHistory.length;
        if(this.popupsHistory[l-1] == name) return;
        if(l) {
            this.hideElement("popup_" + this.popupsHistory[l-1]);
        } else {
            this.showElement("overlay");
            this.showElement("popups");
        }
        
        this.popupsHistory.push(name);
        this.showElement("popup_" + name);
        
        var height = document.body.clientHeight || document.documentElement.clientHeight;
        this.elements["overlay"].style.height = height + "px";
        this.elements["popups"].style.position = 'fixed';
        var top = '30%';
        if(params.length != 0) {
        	if(params.top != '') {
        		top = params.top; 
        	} else {
        		top = '30%';
        	}
        }
        
        
        if(ie6_nav) {
        	this.elements["popups"].style.position = 'absolute';
        	var top = document.documentElement.scrollTop || document.body.scrollTop;
        	this.elements["popups"].style.top = 50 + top + "px";        
        } else {
        	this.elements["popups"].style.top = top;
        }
        
        
        this.updatePopupPosition();
        
		//this.custom_shadowbox  = new ShadowBox(this.elements["popup_" + name].innerHTML, {boxWidth:"400px" , transHoldTime:500 , maxOpacity: 70});
		//this.custom_shadowbox.show();        
    	}


    this.hideActivePopup = function() {
        if(!this.popupsHistory.length) return;        
        var name = this.popupsHistory.pop(); 
        //this.custom_shadowbox.hide();
        //return;
        this.hideElement("popup_" + name);
        if(!this.popupsHistory.length) {
            this.hideElement("popups");
            this.hideElement("overlay");
        }
    }


    this.addPopup = function(name) {
        this.buildDomModel(this.elements["popups"],
            { tag: "div", id: "popup_" + name, display: false });
        return this.elements["popup_" + name];
    }
    
    this.getMenuCont = function(){         
        return this.elements["menu_containter"];
    }
    //Settings
    this.getSettingsCont = function(){         
        return this.elements["settings_containter"];
    }


    this.updatePopupPosition = function() {
        var dw = document.body.clientWidth || document.documentElement.clientWidth;
        var pw = this.elements["popups"].offsetWidth;
        this.elements["popups"].style.left = Math.ceil(0.5 * (dw - pw)) + "px";
    }

    this.onWindowResize = function() {
        if(!desktop.popupsHistory.length) return;
        desktop.updatePopupPosition();
    }


        
    ///////////////////////////
    // System
    this.buildWindow = function(parent) {
    	
        this.buildDomModel(parent, this.domModel);
    }


    this.buildInterface = function() {
        //title
        if(this.profile["title"] == "") {
            this.profile["title"] = loc.text("desktop_title_prompt");
        }

        with(this.elements) {
            var t = this.profile["title"].jsUnescape();
            if(t == "") {
                t = this.defaultProfile.title;
            }
            if(t == loc.text("desktop_title_prompt")) {
            	document.title = loc.text("desktop_title_m3com");	
            } else {
            	document.title = t;
            }
            
            title_box.innerHTML = text2html(t);

            title_box.onclick = function() { desktop.editTitle(); };
            title_box_tmp.innerHTML = text2html(t);
            title_input.value = t;
        }
    }






    // TITLE EDITING

    this.editTitle = function() {
        with(this.elements) {
            var w = title_box_tmp.offsetWidth;
            title_box.style.display = 'none';
            title_input.style.display = 'inline';
            title_input.style.width = (w+4)+"px";
            title_input.focus();
            title_input.select();

            title_input.onkeyup = function(e) {
                e = fix_event(e);
                if(e.keyCode == 13) {
                    this.onblur();
                } else {
                    document.title = this.value;
                    desktop.elements.title_box_tmp.innerHTML = this.value;
                    this.style.width = (desktop.elements.title_box_tmp.offsetWidth+4) + "px";
                }
     		}

            title_input.onblur = function() {
                text = trim(this.value.replace(/\\/g, ""));
                if(text == "") {
                    text = desktop.defaultProfile["title"];
                }
                this.onblur = null;
                this.style.display = 'none';
                with(desktop.elements) {
                    title_box.innerHTML = text2html(text);
                    title_box.style.display = 'inline';
                    title_box.onclick =  function() { desktop.editTitle(); };
                }
				
				document.title = text;
//                var t = escape(text);
                if(text != desktop.profile["title"]) {
                    desktop.profile["title"] = text.jsEscape();
                    desktop.save();
                }
    		}
        }
    }



  

    // TABS
    this.columners = [];

    this.tabOptionsShown = false;



    this.getNewTabNumber = function() {
        return this.profile["order"].length + 1;
    }


    this.addNewTab = function() {
        var title = loc.text("desktop_tab_title") + this.getNewTabNumber();
        var idx = arrayFirstFree(this.profile.tabs);

        this.columners[idx] = kernel.runWidget("Columner", document.body);
        this.columners[idx].profile["pcount"] = this.defaultPanelsCount;
        this.columners[idx].save();


        this.profile.tabs[idx] = {
            t: title,
            i: "",
            cid: this.columners[idx].id
        }
        this.profile["order"][idx] = idx;
        this.save();

        this.buildDomModel(this.elements["desktop_columns"],
            this.getPanelsDom(idx, this.defaultPanelsCount));

        this.renderTab(idx, title);
        this.showTab(idx);

//        this.showDebug();
    }

 


    this.getTabIconSrc = function(icon) {
        return "static/tab_icons/" + icon + ".gif";
    }


    this.renderTab = function(n, title, icon) {
        var icon_src = icon ? this.getTabIconSrc(icon) : "";

        this.buildDomModel(this.elements.tmp, 
            { tag: "div", id: "tab_"+n, 
              className: "tab_box",
                  entityInfo: { type: "tab", idx: n},
              events: {onclick: "showTab('"+n+"')"}, 
              childs: [
                { tag: "div", className: "tab_left" },
                { tag: "div", className: "tab_middle",
                  childs: [
                    { tag: "div", className: "tab_icon",
                      childs: [
                        { tag: "img", id: "tab_icon_" + n, 
                          src: icon_src, 
                          display: (icon_src != "") }
                      ]},

                    { tag: "div", className: "tab_title",
                      id: "tab_title_" + n,
                      innerHTML: title },
                    { tag: "div", className: "tab_controls",
                      childs: [
                        { tag: "div", className: "tab_close_btn",
                          events: { onclick: "closeTab('" + n + "')" }},
                        { tag: "div", className: "tab_options_btn",
                          events: { onclick: "showTabOptions('" + n + "')" }}
                      ]}
                  ]},
                { tag: "div", className: "tab_right" }
              ]});

        this.elements["tabs"].insertBefore(this.elements["tab_"+n], this.elements["add_page_button"]);
        var eh = new EntityHandler(this.elements["tab_"+n], "tabs_drag", 
                                   { onDragStart: desktop.onTabDragStart, 
                                     onElementOver: desktop.onTabDragOver,
                                     onDragStop: desktop.onTabDragStop});
    }




    // Drag&drop tabs
    this.belongTabInfo = null;

    this.onTabDragStart = function(info) {
    }

    this.onTabDragOver = function(info) {
        if(info.type == "tab") {
            desktop.belongTabInfo = info;
            desktop.showElement("tab_area");
            //dimk
            desktop.elements["tab_" + info.idx].parentNode.insertBefore(desktop.elements["tab_area"], desktop.elements["tab_" + info.idx]);
        }
    }

    this.onTabDragStop = function(info) {
        if((desktop.belongTabInfo != null) && 
           (desktop.belongTabInfo.type == "tab") && 
           (desktop.belongTabInfo.idx != info.idx)) {

            desktop.elements["tab_" + info.idx].parentNode.insertBefore(
                desktop.elements["tab_" + info.idx],
                desktop.elements["tab_area"]);

            for(var i=0; i< desktop.profile["order"].length; i++) {
                if(desktop.profile["order"][i] == desktop.belongTabInfo.idx) {
                    var belongIdx = i;
                }

                if(desktop.profile["order"][i] == info.idx) {
                    var dragIdx = i;
                }
            }


            desktop.profile["order"].splice(
                belongIdx - (belongIdx > dragIdx ? 1 : 0), 
                0, 
                desktop.profile["order"].splice(dragIdx, 1)[0]);

            desktop.save();
        }
        this.belongTabInfo = null;
        desktop.hideElement("tab_area");
    }




    // show/hide tabs 
    this.activeTab = null;


    this.hideTab = function(idx) {
        this.hideTabOptions();
        this.elements["tab_" + idx].className = "tab_box";
    }


    this.showTab = function(idx) {
        if(this.activeTab != null && this.activeTab != idx) {
            this.hideTab(this.activeTab);
            this.hideElement("tab_container_" + this.activeTab);
        }
        this.activeTab = idx;
        if(this.elements["tab_" + idx]) {
            this.elements["tab_" + idx].className = "tab_box_selected";        
            this.showElement("tab_container_" + idx);
        }
    }



    // tab options


    this.showTabOptions = function(idx) {
        this.elements["input_tab_title"].value = this.profile.tabs[idx].t;
        var pos = getElPos(this.elements["tab_" + idx]);
        this.showElement("panel_tab");
        this.elements["panel_tab"].style.left = Math.min(pos.left, (document.body.clientWidth - 255)) + "px";
        this.elements["panel_tab"].style.top = (pos.top + this.elements["tab_" + idx].offsetHeight + 4) + "px";
        this.elements["panel_tab"].style.zIndex = 5000;

        if(!this.tabOptionsShown) {
            this.tabOptionsShown = true;
            for(var i=0; i< this.tabIcons.length; i++) {
                this.buildDomModel(this.elements["tab_icons_box"],
                   { tag: "a", href: "void",
                     events: { onclick: "setTabIcon('" + this.tabIcons[i] + "')"},
                     innerHTML: "<img src='" + this.getTabIconSrc(this.tabIcons[i]) + "' style='margin: 1px;'>"});
            }
        }
    }


    this.hideTabOptions = function() {
        this.hideElement("panel_tab");
    }



    // tab managment

    this.renameTab = function() {
        var t = trim(this.elements["input_tab_title"].value);
        this.profile.tabs[this.activeTab].t = t;
        this.elements["tab_title_" + this.activeTab].innerHTML = t;

//        this.showDebug();
        this.save(); 
    }

    this.setTabIcon = function(icon) {
        this.showElement("tab_icon_" + this.activeTab);
        this.elements["tab_icon_" + this.activeTab].src = this.getTabIconSrc(icon);
        this.profile.tabs[this.activeTab].i = icon;

//        this.showDebug();
        this.save(); 
    }


    this.deleteTabIcon = function() {
        this.hideElement("tab_icon_" + this.activeTab);
        this.profile.tabs[this.activeTab].i = "";

//        this.showDebug();
        this.save(); 
    }




    this.closeTab = function() {
        if(confirm(loc.text("desktop_close_page_prompt"))) {
            this.hideTabOptions();

            var widgets = this.columners[this.activeTab].profile["widgets"];
            for(var i in widgets) {
                var w = kernel.getWidget(widgets[i].id);
                if(w) {
                    w.forceClose();
                }
            }
            this.columners[this.activeTab].close();
            deleteEl(this.elements["tab_" + this.activeTab]);
            deleteEl(this.elements["tab_container_" + this.activeTab]);
            delete this.profile["tabs"][this.activeTab];


            for(var o in this.profile["order"]) {
                if(this.profile["order"][o] > this.activeTab) {
                    this.profile["order"][o] --;
                }
            }

            for(var o in this.profile["order"]) {
                if(this.profile["order"][o] == this.activeTab) {
                    this.profile["order"].splice(o, 1);
                    break;
                }
            }

//            this.showDebug();            
            this.save(); 

            this.activeTab = null;
            for(var i=0; i<this.profile.tabs.length; i++) {
                if(this.profile.tabs[i] != undefined) {
                    this.activeTab = i;
                    continue;
                }
            }
            
            if(this.activeTab != null) {
                this.showTab(this.activeTab);
            }
        }
    }



    /* PANELS */
    this.defaultPanelsCount = 3;


    this.setPanelsCount = function(n) {
        if(n == this.columners[this.activeTab].profile["pcount"]) {
            return;
        }

        for(var p=0; p<this.getPanelsCount(); p++) {
            var panel = this.getPanel(p);
            for(; panel.childNodes.length>0; ) {
                var wid = panel.childNodes[0].wid;
                this.elements["tmp"].appendChild(kernel.getWidget(wid).elements.window);
            }
        }

        for(var i=0; i<this.getPanelsCount(); i++) {
            deleteEl(this.elements["panel_" + this.activeTab + "_" + i]);
        }
        deleteEl(this.elements["tab_container_" + this.activeTab]);

        this.buildDomModel(this.elements["desktop_columns"], this.getPanelsDom(this.activeTab, n));

        this.columners[this.activeTab].profile["pcount"] = n;
        this.columners[this.activeTab].save();

        for(;this.elements["tmp"].childNodes.length > 0;) {
            this.getTinyPanel().appendChild(this.elements["tmp"].childNodes[0]);
        }
        this.savePanels();
    }




    this.getPanelsDom = function(tab_idx, count) {
        var p = [];
        var pwidth = Math.round(100 / count) + "%";

        for(var i=0; i<count; i++) {
            p.push(
                { tag: "td", 
                  width: pwidth, 
                  style: {width: pwidth, verticalAlign: "top"},
                  id: "panel_" + tab_idx + "_" + i });
        }

        var m =         
            { tag: "div", id: "tab_container_" + tab_idx,
              childs: [
                { tag: "table", 
                  className: "panels_table",
                  width: "100%",
                  cellspacing : "15"  , 
                  childs: [
                    { tag: "tr", childs: p }
                  ]}
              ]}

        return m;
    }




    // Panels managment
    this.getPanel = function(n) {
        if(n > this.getPanelsCount()-1) {
            n = this.getPanelsCount()-1;
        }
        return this.elements["panel_" + this.activeTab + "_" + n];
    }

    this.getPanelsCount = function() {
        return this.columners[this.activeTab] ? this.columners[this.activeTab].profile["pcount"] : -1;
    }


    this.getTinyPanel = function() {
        if(this.activeTab == null) {
            this.addNewTab();
        }

        var p = 0;
        var minh = 100000;
        for(var i = this.getPanelsCount()-1; i>=0; i--) {
            var h = 0;
            panel = this.getPanel(i);
            for(var j=0; j<panel.childNodes.length; j++) {
                h += panel.childNodes[j].offsetHeight;
            }

            if(h <= minh) {
                minh = h;
                p = i;
            }
        }
        return this.getPanel(p);
    }


    ////////////////////////////////
    // Drag and drop
    this.getBelongPanel = function(pos) {
        for(var i=0; i<this.getPanelsCount(); i++) {
            if(isPosInObj(pos, this.getPanel(i))) {
                return this.getPanel(i);
            }
        }
        return null;
    }


    this.getWindowAtPos = function(panel, pos) {
        for(var i=0; i<panel.childNodes.length; i++) {
            if(isPosInObj(pos, panel.childNodes[i])) {
                return panel.childNodes[i];
            }
        }
        return null;
    }


    this.startArea = function(el) {
        with(this.elements) {
            area.style.position = 'relative';
            el.parentNode.insertBefore(area, el);
            area.style.height = el.offsetHeight + "px";
            area.style.display = 'block';
        }
    }


    this.stopArea = function() {
        with(this.elements) {
            area.style.height = 0;
            area.style.display = 'none';
            area.parentNode.removeChild(area);
        }
    }


    this.processArea = function(pos) {
        p = this.getBelongPanel(pos);
        if(p) { 
            if(p.hasChildNodes()) {
                w = this.getWindowAtPos(p, pos);
                if(w) {
                    if(w.name != 'area') {
                        w = this.getWindowAtPos(p, pos);
                        p.insertBefore(this.elements.area, w);
                    }
                } else {
                    this.elements.area.parentNode.removeChild(this.elements.area);
                    p.appendChild(this.elements.area);
                }
            } else {
                this.elements.area.parentNode.removeChild(this.elements.area);
                p.appendChild(this.elements.area);
            }
        }
    }


    this.putWindow = function(pos) {
        if(this.activeTab == null) {
            this.addNewTab();
        }
        panel = this.getBelongPanel(mpos);        

        if(panel) {
            drag.el.parentNode.removeChild(drag.el); 
            panel.insertBefore(drag.el, this.elements.area);
        }
    }



    this.showAll = function() {
        for(var p=0; p<this.getPanelsCount(); p++) {
            for(var i=0; i<this.getPanel(p).childNodes.length; i++) {
                var wid = this.getPanel(p).childNodes[i].wid;
                if(wid) {
                    kernel.getWidget(wid).show();
                }
            }
        }
    }



    this.hideAll = function() {
        for(var p=0; p<this.getPanelsCount(); p++) {
            for(var i=0; i<this.getPanel(p).childNodes.length; i++) {
                var wid = this.getPanel(p).childNodes[i].wid;
                if(wid) {
                    kernel.getWidget(wid).hide();
                }
            }
        }
    }









    // SAVE/LOAD DESKTOP
    this.savePanels = function() {
        var n = 0;
        var panelsCount = this.getPanelsCount();

        if(this.columners[this.activeTab]) {
            this.columners[this.activeTab].profile["widgets"] = [];

            for(var p=0; p<panelsCount; p++) {
                for(var i=0; i<this.getPanel(p).childNodes.length; i++) {
                    var wid = this.getPanel(p).childNodes[i].wid;
                    if(wid) {
                        this.columners[this.activeTab].profile["widgets"].push(
                            { m: kernel.getWidget(wid).cfg.module, 
                              id:wid, 
                              p: p});
                    }
                }
            }
            this.columners[this.activeTab].save();
        }
    }

 
 

    this.wakeUp = function() {
        hideEl(elById("loading_note"));
        for(var o=0; o<this.profile["order"].length; o++) {
            var i = this.profile["order"][o];
            if(this.profile.tabs[i] == undefined) {
                continue;
            }
            this.renderTab(i, this.profile.tabs[i].t, this.profile.tabs[i].i);

            this.columners[i] = kernel.runWidget("Columner", document.body, this.profile.tabs[i].cid);

            this.buildDomModel(this.elements["desktop_columns"],
                this.getPanelsDom(i, this.columners[i].profile["pcount"]));
            this.showTab(i);

            var widgets = this.columners[i].profile["widgets"];
            for(var j=0; j<widgets.length; j++) {
                kernel.runWidget(widgets[j].m,
                                 this.getPanel(widgets[j].p),
                                 widgets[j].id);
            }
        }

        for(var o in this.profile["order"]) {
            var i = this.profile["order"][o];
            if(this.profile.tabs[i] != undefined) {
                this.showTab(i);
                break;
            }
        }

        if(_GET["add_url"]) {
            url = _GET["add_url"];
            if(url.indexOf("http://") == -1) {
                url = "http://"+url;
            }

            if(_GET["type"] == "api")  {
                var w = kernel.runWidget("Browser", this.getTinyPanel(), false, {home_page: url});
                w.save();

                this.savePanels();
            } else {
                this.newFeedUrl = url;
                xmlRequest.send(url, this, "addFeedDispatch");
            }
        }
        this.showElement("content");
        showEl(elById("page_header"));
        showEl(elById("page_footer"));
    }





    this.addFeedDispatch = function(response) {
        if(response.responseXML.documentElement) {
            var channel = XMLParser.xml2hash(response.responseXML.documentElement);
            if(channel) {
                menu.registerFeed(channel.title, this.newFeedUrl);
                var w = kernel.runWidget("Rss", this.getTinyPanel(), false, {url: this.newFeedUrl});
                w.save();
                this.savePanels();
                return;
            }
        }
    }




    this.showDebug = function() {
        elById("DEBUG").innerHTML = "<pre>" + Dump(this.profile.tabs) + "</pre>";
    }




    this.addToFavorites = function() {
        var url = "http://" + baseUrl;
        if(mozilla_nav) {  
            window.sidebar.addPanel(this.profile["title"], url, "");
        } else if(ie_nav) {  
            window.external.AddFavorite(url, this.profile["title"]);  
        }
    }


}
Desktop.prototype = new Widget();




/* columner */

function Columner() {

    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasCloseBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasOnCloseConfirm: false,
        isSystem: true,
        title: "",
        module: "columner"
    }


    this.defaultProfile["widgets"] = [];
    this.defaultProfile["pcount"] = 3;
    this.defaultProfile["config"] = "";


    this.buildWindow = function(parent) {}
    this.buildInterface = function() {}

}
Columner.prototype = new Widget();





/* recent widgets */
function RecentWidgetsStorage() {

    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasCloseBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasOnCloseConfirm: false,
        isSystem: true,
        title: "",
        module: "RecentWidgetsStorage",
        uniqueId: SYS_WIDGETS_ID + 10
    }


    this.defaultProfile["list"] = [];

    this.buildWindow = function(parent) {}
    this.buildInterface = function() {}

}
RecentWidgetsStorage.prototype = new Widget();




Desktop.prototype.tabIcons = [
"anchor",
"attach",
"basket",
"bomb",
"book",
"book_addresses",
"book_open",
"brick",
"briefcase",
"bug",
"cake",
"calendar_view_day",
"calendar_view_month",
"camera",
"car",
"cd",
"chart_bar",
"chart_curve",
"chart_organisation",
"chart_pie",
"clock",
"clock_red",
"cog",
"coins",
"color_swatch",
"comment",
"computer",
"connect",
"creditcards",
"door",
"door_open",
"drink",
"drink_empty",
"email",
"email_open",
"email_open_image",
"emoticon_evilgrin",
"emoticon_grin",
"emoticon_happy",
"emoticon_smile",
"emoticon_surprised",
"emoticon_tongue",
"emoticon_unhappy",
"emoticon_waii",
"emoticon_wink",
"exclamation",
"eye",
"feed",
"flag_blue",
"flag_green",
"flag_orange",
"flag_pink",
"flag_purple",
"flag_red",
"flag_yellow",
"folder",
"heart",
"hideMod",
"house",
"image",
"info",
"information",
"ipod",
"keyboard",
"layout",
"lightbulb",
"lightbulb_off",
"lock",
"lock_open",
"lorry",
"lorry_flatbed",
"magnifier",
"money",
"money_dollar",
"money_euro",
"money_pound",
"money_yen",
"monitor",
"mouse",
"music",
"new",
"note",
"note_002",
"page",
"page_copy",
"page_white",
"page_white_acrobat",
"page_white_code",
"page_white_compressed",
"page_white_excel",
"page_white_flash",
"page_white_php",
"page_white_picture",
"page_white_powerpoint",
"page_white_text",
"page_white_word",
"page_white_world",
"palette",
"paste_plain",
"pencil",
"phone",
"photo",
"picture",
"printer",
"printer_empty",
"rainbow",
"rosette",
"server",
"shield",
"sport_8ball",
"sport_basketball",
"sport_football",
"sport_golf",
"sport_raquet",
"sport_shuttlecock",
"sport_soccer",
"sport_tennis",
"star",
"stop",
"tag_blue",
"tag_green",
"tag_orange",
"tag_pink",
"tag_purple",
"tag_red",
"tag_yellow",
"telephone",
"television",
"thumb_down",
"thumb_up",
"trash",
"tux",
"user",
"user_female",
"user_gray",
"user_green",
"user_orange",
"user_red",
"user_suit",
"vcard",
"weather_clouds",
"weather_cloudy",
"weather_lightning",
"weather_rain",
"weather_snow",
"weather_sun",
"world",
"zoom"
]

//MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools = {
	version: '1.11'
};

function $defined(obj){
	return (obj != undefined);
};

function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

function $merge(){
	var mix = {};
	for (var i = 0; i < arguments.length; i++){
		for (var property in arguments[i]){
			var ap = arguments[i][property];
			var mp = mix[property];
			if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap);
			else mix[property] = ap;
		}
	}
	return mix;
};

var $extend = function(){
	var args = arguments;
	if (!args[1]) args = [this, args[0]];
	for (var property in args[1]) args[0][property] = args[1][property];
	return args[0];
};

var $native = function(){
	for (var i = 0, l = arguments.length; i < l; i++){
		arguments[i].extend = function(props){
			for (var prop in props){
				if (!this.prototype[prop]) this.prototype[prop] = props[prop];
				if (!this[prop]) this[prop] = $native.generic(prop);
			}
		};
	}
};

$native.generic = function(prop){
	return function(bind){
		return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1));
	};
};

$native(Function, Array, String, Number);

function $chk(obj){
	return !!(obj || obj === 0);
};

function $pick(obj, picked){
	return $defined(obj) ? obj : picked;
};

function $random(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

function $time(){
	return new Date().getTime();
};

function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

var Abstract = function(obj){
	obj = obj || {};
	obj.extend = $extend;
	return obj;
};

var Window = new Abstract(window);
var Document = new Abstract(document);
document.head = document.getElementsByTagName('head')[0];

window.xpath = !!(document.evaluate);
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if (document.getBoxObjectFor != null) window.gecko = true;

window.khtml = window.webkit;

Object.extend = $extend;

if (typeof HTMLElement == 'undefined'){
	var HTMLElement = function(){};
	if (window.webkit) document.createElement("iframe");
	HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {};
}
HTMLElement.prototype.htmlElement = function(){};

if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};

var Class = function(properties){
	var klass = function(){
		return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;
	};
	$extend(klass, this);
	klass.prototype = properties;
	klass.constructor = Class;
	return klass;
};

Class.empty = function(){};

Class.prototype = {

	extend: function(properties){
		var proto = new this(null);
		for (var property in properties){
			var pp = proto[property];
			proto[property] = Class.Merge(pp, properties[property]);
		}
		return new Class(proto);
	},

	implement: function(){
		for (var i = 0, l = arguments.length; i < l; i++) $extend(this.prototype, arguments[i]);
	}

};

Class.Merge = function(previous, current){
	if (previous && previous != current){
		var type = $type(current);
		if (type != $type(previous)) return current;
		switch(type){
			case 'function':
				var merged = function(){
					this.parent = arguments.callee.parent;
					return current.apply(this, arguments);
				};
				merged.parent = previous;
				return merged;
			case 'object': return $merge(previous, current);
		}
	}
	return current;
};

var Chain = new Class({

	chain: function(fn){
		this.chains = this.chains || [];
		this.chains.push(fn);
		return this;
	},

	callChain: function(){
		if (this.chains && this.chains.length) this.chains.shift().delay(10, this);
	},

	clearChain: function(){
		this.chains = [];
	}

});

var Events = new Class({

	addEvent: function(type, fn){
		if (fn != Class.empty){
			this.$events = this.$events || {};
			this.$events[type] = this.$events[type] || [];
			this.$events[type].include(fn);
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	removeEvent: function(type, fn){
		if (this.$events && this.$events[type]) this.$events[type].remove(fn);
		return this;
	}

});

var Options = new Class({

	setOptions: function(){
		this.options = $merge.apply(null, [this.options].extend(arguments));
		if (this.addEvent){
			for (var option in this.options){
				if ($type(this.options[option] == 'function') && (/^on[A-Z]/).test(option)) this.addEvent(option, this.options[option]);
			}
		}
		return this;
	}

});

Array.extend({

	forEach: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this);
	},

	filter: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) results.push(this[i]);
		}
		return results;
	},

	map: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this);
		return results;
	},

	every: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (!fn.call(bind, this[i], i, this)) return false;
		}
		return true;
	},

	some: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) return true;
		}
		return false;
	},

	indexOf: function(item, from){
		var len = this.length;
		for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
			if (this[i] === item) return i;
		}
		return -1;
	},

	copy: function(start, length){
		start = start || 0;
		if (start < 0) start = this.length + start;
		length = length || (this.length - start);
		var newArray = [];
		for (var i = 0; i < length; i++) newArray[i] = this[start++];
		return newArray;
	},

	remove: function(item){
		var i = 0;
		var len = this.length;
		while (i < len){
			if (this[i] === item){
				this.splice(i, 1);
				len--;
			} else {
				i++;
			}
		}
		return this;
	},

	contains: function(item, from){
		return this.indexOf(item, from) != -1;
	},

	associate: function(keys){
		var obj = {}, length = Math.min(this.length, keys.length);
		for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
		return obj;
	},

	extend: function(array){
		for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
		return this;
	},

	merge: function(array){
		for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
		return this;
	},

	include: function(item){
		if (!this.contains(item)) this.push(item);
		return this;
	},

	getRandom: function(){
		return this[$random(0, this.length - 1)] || null;
	},

	getLast: function(){
		return this[this.length - 1] || null;
	}

});

Array.prototype.each = Array.prototype.forEach;
Array.each = Array.forEach;

function $A(array){
	return Array.copy(array);
};

function $each(iterable, fn, bind){
	if (iterable && typeof iterable.length == 'number' && $type(iterable) != 'object'){
		Array.forEach(iterable, fn, bind);
	} else {
		 for (var name in iterable) fn.call(bind || iterable, iterable[name], name);
	}
};

Array.prototype.test = Array.prototype.contains;

String.extend({

	test: function(regex, params){
		return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this);
	},

	toInt: function(){
		return parseInt(this, 10);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	camelCase: function(){
		return this.replace(/-\D/g, function(match){
			return match.charAt(1).toUpperCase();
		});
	},

	hyphenate: function(){
		return this.replace(/\w[A-Z]/g, function(match){
			return (match.charAt(0) + '-' + match.charAt(1).toLowerCase());
		});
	},

	capitalize: function(){
		return this.replace(/\b[a-z]/g, function(match){
			return match.toUpperCase();
		});
	},

	trim: function(){
		return this.replace(/^\s+|\s+$/g, '');
	},

	clean: function(){
		return this.replace(/\s{2,}/g, ' ').trim();
	},

	rgbToHex: function(array){
		var rgb = this.match(/\d{1,3}/g);
		return (rgb) ? rgb.rgbToHex(array) : false;
	},

	hexToRgb: function(array){
		var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		return (hex) ? hex.slice(1).hexToRgb(array) : false;
	},

	contains: function(string, s){
		return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1;
	},

	escapeRegExp: function(){
		return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
	}

});

Array.extend({

	rgbToHex: function(array){
		if (this.length < 3) return false;
		if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
		var hex = [];
		for (var i = 0; i < 3; i++){
			var bit = (this[i] - 0).toString(16);
			hex.push((bit.length == 1) ? '0' + bit : bit);
		}
		return array ? hex : '#' + hex.join('');
	},

	hexToRgb: function(array){
		if (this.length != 3) return false;
		var rgb = [];
		for (var i = 0; i < 3; i++){
			rgb.push(parseInt((this[i].length == 1) ? this[i] + this[i] : this[i], 16));
		}
		return array ? rgb : 'rgb(' + rgb.join(',') + ')';
	}

});

Function.extend({

	create: function(options){
		var fn = this;
		options = $merge({
			'bind': fn,
			'event': false,
			'arguments': null,
			'delay': false,
			'periodical': false,
			'attempt': false
		}, options);
		if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments];
		return function(event){
			var args;
			if (options.event){
				event = event || window.event;
				args = [(options.event === true) ? event : new options.event(event)];
				if (options.arguments) args.extend(options.arguments);
			}
			else args = options.arguments || arguments;
			var returns = function(){
				return fn.apply($pick(options.bind, fn), args);
			};
			if (options.delay) return setTimeout(returns, options.delay);
			if (options.periodical) return setInterval(returns, options.periodical);
			if (options.attempt) try {return returns();} catch(err){return false;};
			return returns();
		};
	},

	pass: function(args, bind){
		return this.create({'arguments': args, 'bind': bind});
	},

	attempt: function(args, bind){
		return this.create({'arguments': args, 'bind': bind, 'attempt': true})();
	},

	bind: function(bind, args){
		return this.create({'bind': bind, 'arguments': args});
	},

	bindAsEventListener: function(bind, args){
		return this.create({'bind': bind, 'event': true, 'arguments': args});
	},

	delay: function(delay, bind, args){
		return this.create({'delay': delay, 'bind': bind, 'arguments': args})();
	},

	periodical: function(interval, bind, args){
		return this.create({'periodical': interval, 'bind': bind, 'arguments': args})();
	}

});

Number.extend({

	toInt: function(){
		return parseInt(this);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	limit: function(min, max){
		return Math.min(max, Math.max(min, this));
	},

	round: function(precision){
		precision = Math.pow(10, precision || 0);
		return Math.round(this * precision) / precision;
	},

	times: function(fn){
		for (var i = 0; i < this; i++) fn(i);
	}

});

var Element = new Class({

	initialize: function(el, props){
		if ($type(el) == 'string'){
			if (window.ie && props && (props.name || props.type)){
				var name = (props.name) ? ' name="' + props.name + '"' : '';
				var type = (props.type) ? ' type="' + props.type + '"' : '';
				delete props.name;
				delete props.type;
				el = '<' + el + name + type + '>';
			}
			el = document.createElement(el);
		}
		el = $(el);
		return (!props || !el) ? el : el.set(props);
	}

});

var Elements = new Class({

	initialize: function(elements){
		return (elements) ? $extend(elements, this) : this;
	}

});

Elements.extend = function(props){
	for (var prop in props){
		this.prototype[prop] = props[prop];
		this[prop] = $native.generic(prop);
	}
};

function $(el){
	if (!el) return null;
	if (el.htmlElement) return Garbage.collect(el);
	if ([window, document].contains(el)) return el;
	var type = $type(el);
	if (type == 'string'){
		el = document.getElementById(el);
		type = (el) ? 'element' : false;
	}
	if (type != 'element') return null;
	if (el.htmlElement) return Garbage.collect(el);
	if (['object', 'embed'].contains(el.tagName.toLowerCase())) return el;
	$extend(el, Element.prototype);
	el.htmlElement = function(){};
	return Garbage.collect(el);
};

document.getElementsBySelector = document.getElementsByTagName;

function $$(){
	var elements = [];
	for (var i = 0, j = arguments.length; i < j; i++){
		var selector = arguments[i];
		switch($type(selector)){
			case 'element': elements.push(selector);
			case 'boolean': break;
			case false: break;
			case 'string': selector = document.getElementsBySelector(selector, true);
			default: elements.extend(selector);
		}
	}
	return $$.unique(elements);
};

$$.unique = function(array){
	var elements = [];
	for (var i = 0, l = array.length; i < l; i++){
		if (array[i].$included) continue;
		var element = $(array[i]);
		if (element && !element.$included){
			element.$included = true;
			elements.push(element);
		}
	}
	for (var n = 0, d = elements.length; n < d; n++) elements[n].$included = null;
	return new Elements(elements);
};

Elements.Multi = function(property){
	return function(){
		var args = arguments;
		var items = [];
		var elements = true;
		for (var i = 0, j = this.length, returns; i < j; i++){
			returns = this[i][property].apply(this[i], args);
			if ($type(returns) != 'element') elements = false;
			items.push(returns);
		};
		return (elements) ? $$.unique(items) : items;
	};
};

Element.extend = function(properties){
	for (var property in properties){
		HTMLElement.prototype[property] = properties[property];
		Element.prototype[property] = properties[property];
		Element[property] = $native.generic(property);
		var elementsProperty = (Array.prototype[property]) ? property + 'Elements' : property;
		Elements.prototype[elementsProperty] = Elements.Multi(property);
	}
};

Element.extend({

	set: function(props){
		for (var prop in props){
			var val = props[prop];
			switch(prop){
				case 'styles': this.setStyles(val); break;
				case 'events': if (this.addEvents) this.addEvents(val); break;
				case 'properties': this.setProperties(val); break;
				default: this.setProperty(prop, val);
			}
		}
		return this;
	},

	inject: function(el, where){
		el = $(el);
		switch(where){
			case 'before': el.parentNode.insertBefore(this, el); break;
			case 'after':
				var next = el.getNext();
				if (!next) el.parentNode.appendChild(this);
				else el.parentNode.insertBefore(this, next);
				break;
			case 'top':
				var first = el.firstChild;
				if (first){
					el.insertBefore(this, first);
					break;
				}
			default: el.appendChild(this);
		}
		return this;
	},

	injectBefore: function(el){
		return this.inject(el, 'before');
	},

	injectAfter: function(el){
		return this.inject(el, 'after');
	},

	injectInside: function(el){
		return this.inject(el, 'bottom');
	},

	injectTop: function(el){
		return this.inject(el, 'top');
	},

	adopt: function(){
		var elements = [];
		$each(arguments, function(argument){
			elements = elements.concat(argument);
		});
		$$(elements).inject(this);
		return this;
	},

	remove: function(){
		return this.parentNode.removeChild(this);
	},

	clone: function(contents){
		var el = $(this.cloneNode(contents !== false));
		if (!el.$events) return el;
		el.$events = {};
		for (var type in this.$events) el.$events[type] = {
			'keys': $A(this.$events[type].keys),
			'values': $A(this.$events[type].values)
		};
		return el.removeEvents();
	},

	replaceWith: function(el){
		el = $(el);
		this.parentNode.replaceChild(el, this);
		return el;
	},

	appendText: function(text){
		this.appendChild(document.createTextNode(text));
		return this;
	},

	hasClass: function(className){
		return this.className.contains(className, ' ');
	},

	addClass: function(className){
		if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
		return this;
	},

	removeClass: function(className){
		this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean();
		return this;
	},

	toggleClass: function(className){
		return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
	},

	setStyle: function(property, value){
		switch(property){
			case 'opacity': return this.setOpacity(parseFloat(value));
			case 'float': property = (window.ie) ? 'styleFloat' : 'cssFloat';
		}
		property = property.camelCase();
		switch($type(value)){
			case 'number': if (!['zIndex', 'zoom'].contains(property)) value += 'px'; break;
			case 'array': value = 'rgb(' + value.join(',') + ')';
		}
		try {
			this.style[property] = value;
		} catch (e) {
			
		}
		return this;
	},

	setStyles: function(source){
		switch($type(source)){
			case 'object': Element.setMany(this, 'setStyle', source); break;
			case 'string': this.style.cssText = source;
		}
		return this;
	},

	setOpacity: function(opacity){
		if (opacity == 0){
			if (this.style.visibility != "hidden") this.style.visibility = "hidden";
		} else {
			if (this.style.visibility != "visible") this.style.visibility = "visible";
		}
		if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
		if (window.ie) this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")";
		this.style.opacity = this.$tmp.opacity = opacity;
		return this;
	},

	getStyle: function(property){
		property = property.camelCase();
		var result = this.style[property];
		if (!$chk(result)){
			if (property == 'opacity') return this.$tmp.opacity;
			result = [];
			for (var style in Element.Styles){
				if (property == style){
					Element.Styles[style].each(function(s){
						var style = this.getStyle(s);
						result.push(parseInt(style) ? style : '0px');
					}, this);
					if (property == 'border'){
						var every = result.every(function(bit){
							return (bit == result[0]);
						});
						return (every) ? result[0] : false;
					}
					return result.join(' ');
				}
			}
			if (property.contains('border')){
				if (Element.Styles.border.contains(property)){
					return ['Width', 'Style', 'Color'].map(function(p){
						return this.getStyle(property + p);
					}, this).join(' ');
				} else if (Element.borderShort.contains(property)){
					return ['Top', 'Right', 'Bottom', 'Left'].map(function(p){
						return this.getStyle('border' + p + property.replace('border', ''));
					}, this).join(' ');
				}
			}
			if (document.defaultView) result = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate());
			else if (this.currentStyle) result = this.currentStyle[property];
		}
		if (window.ie) result = Element.fixStyle(property, result, this);
		if (result && property.test(/color/i) && result.contains('rgb')){
			return result.split('rgb').splice(1,4).map(function(color){
				return color.rgbToHex();
			}).join(' ');
		}
		return result;
	},

	getStyles: function(){
		return Element.getMany(this, 'getStyle', arguments);
	},

	walk: function(brother, start){
		brother += 'Sibling';
		var el = (start) ? this[start] : this[brother];
		while (el && $type(el) != 'element') el = el[brother];
		return $(el);
	},

	getPrevious: function(){
		return this.walk('previous');
	},

	getNext: function(){
		return this.walk('next');
	},

	getFirst: function(){
		return this.walk('next', 'firstChild');
	},

	getLast: function(){
		return this.walk('previous', 'lastChild');
	},

	getParent: function(){
		return $(this.parentNode);
	},

	getChildren: function(){
		return $$(this.childNodes);
	},

	hasChild: function(el){
		return !!$A(this.getElementsByTagName('*')).contains(el);
	},

	getProperty: function(property){
		var index = Element.Properties[property];
		if (index) return this[index];
		var flag = Element.PropertiesIFlag[property] || 0;
		if (!window.ie || flag) return this.getAttribute(property, flag);
		var node = this.attributes[property];
		return (node) ? node.nodeValue : null;
	},

	removeProperty: function(property){
		var index = Element.Properties[property];
		if (index) this[index] = '';
		else this.removeAttribute(property);
		return this;
	},

	getProperties: function(){
		return Element.getMany(this, 'getProperty', arguments);
	},

	setProperty: function(property, value){
		var index = Element.Properties[property];
		if (index) this[index] = value;
		else this.setAttribute(property, value);
		return this;
	},

	setProperties: function(source){
		return Element.setMany(this, 'setProperty', source);
	},

	setHTML: function(){
		this.innerHTML = $A(arguments).join('');
		return this;
	},

	setText: function(text){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') this.styleSheet.cssText = text;
				else if (tag ==  'script') this.setProperty('text', text);
				return this;
			} else {
				this.removeChild(this.firstChild);
				return this.appendText(text);
			}
		}
		this[$defined(this.innerText) ? 'innerText' : 'textContent'] = text;
		return this;
	},

	getText: function(){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') return this.styleSheet.cssText;
				else if (tag ==  'script') return this.getProperty('text');
			} else {
				return this.innerHTML;
			}
		}
		return ($pick(this.innerText, this.textContent));
	},

	getTag: function(){
		return this.tagName.toLowerCase();
	},

	empty: function(){
		Garbage.trash(this.getElementsByTagName('*'));
		return this.setHTML('');
	}

});

Element.fixStyle = function(property, result, element){
	if ($chk(parseInt(result))) return result;
	if (['height', 'width'].contains(property)){
		var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'];
		var size = 0;
		values.each(function(value){
			size += element.getStyle('border-' + value + '-width').toInt() + element.getStyle('padding-' + value).toInt();
		});
		return element['offset' + property.capitalize()] - size + 'px';
	} else if (property.test(/border(.+)Width|margin|padding/)){
		return '0px';
	}
	return result;
};

Element.Styles = {'border': [], 'padding': [], 'margin': []};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
	for (var style in Element.Styles) Element.Styles[style].push(style + direction);
});

Element.borderShort = ['borderWidth', 'borderStyle', 'borderColor'];

Element.getMany = function(el, method, keys){
	var result = {};
	$each(keys, function(key){
		result[key] = el[method](key);
	});
	return result;
};

Element.setMany = function(el, method, pairs){
	for (var key in pairs) el[method](key, pairs[key]);
	return el;
};

Element.Properties = new Abstract({
	'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan',
	'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength',
	'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value',
	'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected'
});
Element.PropertiesIFlag = {
	'href': 2, 'src': 2
};

Element.Methods = {
	Listeners: {
		addListener: function(type, fn){
			if (this.addEventListener) this.addEventListener(type, fn, false);
			else this.attachEvent('on' + type, fn);
			return this;
		},

		removeListener: function(type, fn){
			if (this.removeEventListener) this.removeEventListener(type, fn, false);
			else this.detachEvent('on' + type, fn);
			return this;
		}
	}
};

window.extend(Element.Methods.Listeners);
document.extend(Element.Methods.Listeners);
Element.extend(Element.Methods.Listeners);

var Garbage = {

	elements: [],

	collect: function(el){
		if (!el.$tmp){
			Garbage.elements.push(el);
			el.$tmp = {'opacity': 1};
		}
		return el;
	},

	trash: function(elements, unload){
		for (var i = 0, j = elements.length, el; i < j; i++){
			if (!(el = elements[i]) || !el.$tmp) continue;
			if (el.$events) el.fireEvent('trash', [!!(unload)]).removeEvents();
			for (var p in el.$tmp) el.$tmp[p] = null;
			for (var d in Element.prototype) el[d] = null;
			if (!unload) Garbage.elements[Garbage.elements.indexOf(el)] = null;
			el.htmlElement = el.$tmp = el = null;
		}
		if (!unload) Garbage.elements.remove(null);
	},

	empty: function(){
		Garbage.collect(window);
		Garbage.collect(document);
		Garbage.trash(Garbage.elements, true);
	}

};

window.addListener('beforeunload', function(){
	window.addListener('unload', Garbage.empty);
	if (window.ie) window.addListener('unload', CollectGarbage);
});

var Event = new Class({

	initialize: function(event){
		if (event && event.$extended) return event;
		this.$extended = true;
		event = event || window.event;
		this.event = event;
		this.type = event.type;
		this.target = event.target || event.srcElement;
		if (this.target.nodeType == 3) this.target = this.target.parentNode;
		this.shift = event.shiftKey;
		this.control = event.ctrlKey;
		this.alt = event.altKey;
		this.meta = event.metaKey;
		if (['DOMMouseScroll', 'mousewheel'].contains(this.type)){
			this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
		} else if (this.type.contains('key')){
			this.code = event.which || event.keyCode;
			for (var name in Event.keys){
				if (Event.keys[name] == this.code){
					this.key = name;
					break;
				}
			}
			if (this.type == 'keydown' || event.keyCode > 0){
				var fKey = this.code - 111;
				if (fKey > 0 && fKey < 13) this.key = 'f' + fKey;
			}
			this.key = this.key || String.fromCharCode(this.code).toLowerCase();
		} else if (this.type.test(/(click|mouse|menu)/)){
			this.page = {
				'x': event.pageX || event.clientX + document.documentElement.scrollLeft,
				'y': event.pageY || event.clientY + document.documentElement.scrollTop
			};
			this.client = {
				'x': event.pageX ? event.pageX - window.pageXOffset : event.clientX,
				'y': event.pageY ? event.pageY - window.pageYOffset : event.clientY
			};
			this.rightClick = (event.which == 3) || (event.button == 2);
			switch(this.type){
				case 'mouseover': this.relatedTarget = event.relatedTarget || event.fromElement; break;
				case 'mouseout': this.relatedTarget = event.relatedTarget || event.toElement;
			}
			this.fixRelatedTarget();
		}
		return this;
	},

	stop: function(){
		return this.stopPropagation().preventDefault();
	},

	stopPropagation: function(){
		if (this.event.stopPropagation) this.event.stopPropagation();
		else this.event.cancelBubble = true;
		return this;
	},

	preventDefault: function(){
		if (this.event.preventDefault) this.event.preventDefault();
		else this.event.returnValue = false;
		return this;
	}

});

Event.fix = {

	relatedTarget: function(){
		if (this.relatedTarget && this.relatedTarget.nodeType == 3) this.relatedTarget = this.relatedTarget.parentNode;
	},

	relatedTargetGecko: function(){
		try {Event.fix.relatedTarget.call(this);} catch(e){this.relatedTarget = this.target;}
	}

};

Event.prototype.fixRelatedTarget = (window.gecko) ? Event.fix.relatedTargetGecko : Event.fix.relatedTarget;

Event.keys = new Abstract({
	'enter': 13,
	'up': 38,
	'down': 40,
	'left': 37,
	'right': 39,
	'esc': 27,
	'space': 32,
	'backspace': 8,
	'tab': 9,
	'delete': 46
});

Element.Methods.Events = {

	addEvent: function(type, fn){
		this.$events = this.$events || {};
		this.$events[type] = this.$events[type] || {'keys': [], 'values': []};
		if (this.$events[type].keys.contains(fn)) return this;
		this.$events[type].keys.push(fn);
		var realType = type;
		var custom = Element.Events[type];
		if (custom){
			if (custom.add) custom.add.call(this, fn);
			if (custom.map) fn = custom.map;
			if (custom.type) realType = custom.type;
		}
		if (!this.addEventListener) fn = fn.create({'bind': this, 'event': true});
		this.$events[type].values.push(fn);
		return (Element.NativeEvents.contains(realType)) ? this.addListener(realType, fn) : this;
	},

	removeEvent: function(type, fn){
		if (!this.$events || !this.$events[type]) return this;
		var pos = this.$events[type].keys.indexOf(fn);
		if (pos == -1) return this;
		var key = this.$events[type].keys.splice(pos,1)[0];
		var value = this.$events[type].values.splice(pos,1)[0];
		var custom = Element.Events[type];
		if (custom){
			if (custom.remove) custom.remove.call(this, fn);
			if (custom.type) type = custom.type;
		}
		return (Element.NativeEvents.contains(type)) ? this.removeListener(type, value) : this;
	},

	addEvents: function(source){
		return Element.setMany(this, 'addEvent', source);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type){
			for (var evType in this.$events) this.removeEvents(evType);
			this.$events = null;
		} else if (this.$events[type]){
			this.$events[type].keys.each(function(fn){
				this.removeEvent(type, fn);
			}, this);
			this.$events[type] = null;
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].keys.each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	cloneEvents: function(from, type){
		if (!from.$events) return this;
		if (!type){
			for (var evType in from.$events) this.cloneEvents(from, evType);
		} else if (from.$events[type]){
			from.$events[type].keys.each(function(fn){
				this.addEvent(type, fn);
			}, this);
		}
		return this;
	}

};

window.extend(Element.Methods.Events);
document.extend(Element.Methods.Events);
Element.extend(Element.Methods.Events);

Element.Events = new Abstract({

	'mouseenter': {
		type: 'mouseover',
		map: function(event){
			event = new Event(event);
			if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseenter', event);
		}
	},

	'mouseleave': {
		type: 'mouseout',
		map: function(event){
			event = new Event(event);
			if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseleave', event);
		}
	},

	'mousewheel': {
		type: (window.gecko) ? 'DOMMouseScroll' : 'mousewheel'
	}

});

Element.NativeEvents = [
	'click', 'dblclick', 'mouseup', 'mousedown',
	'mousewheel', 'DOMMouseScroll',
	'mouseover', 'mouseout', 'mousemove',
	'keydown', 'keypress', 'keyup',
	'load', 'unload', 'beforeunload', 'resize', 'move',
	'focus', 'blur', 'change', 'submit', 'reset', 'select',
	'error', 'abort', 'contextmenu', 'scroll'
];

Function.extend({

	bindWithEvent: function(bind, args){
		return this.create({'bind': bind, 'arguments': args, 'event': Event});
	}

});

Elements.extend({

	filterByTag: function(tag){
		return new Elements(this.filter(function(el){
			return (Element.getTag(el) == tag);
		}));
	},

	filterByClass: function(className, nocash){
		var elements = this.filter(function(el){
			return (el.className && el.className.contains(className, ' '));
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterById: function(id, nocash){
		var elements = this.filter(function(el){
			return (el.id == id);
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterByAttribute: function(name, operator, value, nocash){
		var elements = this.filter(function(el){
			var current = Element.getProperty(el, name);
			if (!current) return false;
			if (!operator) return true;
			switch(operator){
				case '=': return (current == value);
				case '*=': return (current.contains(value));
				case '^=': return (current.substr(0, value.length) == value);
				case '$=': return (current.substr(current.length - value.length) == value);
				case '!=': return (current != value);
				case '~=': return current.contains(value, ' ');
			}
			return false;
		});
		return (nocash) ? elements : new Elements(elements);
	}

});

function $E(selector, filter){
	return ($(filter) || document).getElement(selector);
};

function $ES(selector, filter){
	return ($(filter) || document).getElementsBySelector(selector);
};

$$.shared = {

	'regexp': /^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,

	'xpath': {

		getParam: function(items, context, param, i){
			var temp = [context.namespaceURI ? 'xhtml:' : '', param[1]];
			if (param[2]) temp.push('[@id="', param[2], '"]');
			if (param[3]) temp.push('[contains(concat(" ", @class, " "), " ', param[3], ' ")]');
			if (param[4]){
				if (param[5] && param[6]){
					switch(param[5]){
						case '*=': temp.push('[contains(@', param[4], ', "', param[6], '")]'); break;
						case '^=': temp.push('[starts-with(@', param[4], ', "', param[6], '")]'); break;
						case '$=': temp.push('[substring(@', param[4], ', string-length(@', param[4], ') - ', param[6].length, ' + 1) = "', param[6], '"]'); break;
						case '=': temp.push('[@', param[4], '="', param[6], '"]'); break;
						case '!=': temp.push('[@', param[4], '!="', param[6], '"]');
					}
				} else {
					temp.push('[@', param[4], ']');
				}
			}
			items.push(temp.join(''));
			return items;
		},

		getItems: function(items, context, nocash){
			var elements = [];
			var xpath = document.evaluate('.//' + items.join('//'), context, $$.shared.resolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
			for (var i = 0, j = xpath.snapshotLength; i < j; i++) elements.push(xpath.snapshotItem(i));
			return (nocash) ? elements : new Elements(elements.map($));
		}

	},

	'normal': {

		getParam: function(items, context, param, i){
			if (i == 0){
				if (param[2]){
					var el = context.getElementById(param[2]);
					if (!el || ((param[1] != '*') && (Element.getTag(el) != param[1]))) return false;
					items = [el];
				} else {
					items = $A(context.getElementsByTagName(param[1]));
				}
			} else {
				items = $$.shared.getElementsByTagName(items, param[1]);
				if (param[2]) items = Elements.filterById(items, param[2], true);
			}
			if (param[3]) items = Elements.filterByClass(items, param[3], true);
			if (param[4]) items = Elements.filterByAttribute(items, param[4], param[5], param[6], true);
			return items;
		},

		getItems: function(items, context, nocash){
			return (nocash) ? items : $$.unique(items);
		}

	},

	resolver: function(prefix){
		return (prefix == 'xhtml') ? 'http://www.w3.org/1999/xhtml' : false;
	},

	getElementsByTagName: function(context, tagName){
		var found = [];
		for (var i = 0, j = context.length; i < j; i++) found.extend(context[i].getElementsByTagName(tagName));
		return found;
	}

};

$$.shared.method = (window.xpath) ? 'xpath' : 'normal';

Element.Methods.Dom = {

	getElements: function(selector, nocash){
		var items = [];
		selector = selector.trim().split(' ');
		for (var i = 0, j = selector.length; i < j; i++){
			var sel = selector[i];
			var param = sel.match($$.shared.regexp);
			if (!param) break;
			param[1] = param[1] || '*';
			var temp = $$.shared[$$.shared.method].getParam(items, this, param, i);
			if (!temp) break;
			items = temp;
		}
		return $$.shared[$$.shared.method].getItems(items, this, nocash);
	},

	getElement: function(selector){
		return $(this.getElements(selector, true)[0] || false);
	},

	getElementsBySelector: function(selector, nocash){
		var elements = [];
		selector = selector.split(',');
		for (var i = 0, j = selector.length; i < j; i++) elements = elements.concat(this.getElements(selector[i], true));
		return (nocash) ? elements : $$.unique(elements);
	}

};

Element.extend({

	getElementById: function(id){
		var el = document.getElementById(id);
		if (!el) return false;
		for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
			if (!parent) return false;
		}
		return el;
	}/*compatibility*/,

	getElementsByClassName: function(className){ 
		return this.getElements('.' + className); 
	}

});

document.extend(Element.Methods.Dom);
Element.extend(Element.Methods.Dom);

Element.extend({

	getValue: function(){
		switch(this.getTag()){
			case 'select':
				var values = [];
				$each(this.options, function(option){
					if (option.selected) values.push($pick(option.value, option.text));
				});
				return (this.multiple) ? values : values[0];
			case 'input': if (!(this.checked && ['checkbox', 'radio'].contains(this.type)) && !['hidden', 'text', 'password'].contains(this.type)) break;
			case 'textarea': return this.value;
		}
		return false;
	},

	getFormElements: function(){
		return $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea'));
	},

	toQueryString: function(){
		var queryString = [];
		this.getFormElements().each(function(el){
			var name = el.name;
			var value = el.getValue();
			if (value === false || !name || el.disabled) return;
			var qs = function(val){
				queryString.push(name + '=' + encodeURIComponent(val));
			};
			if ($type(value) == 'array') value.each(qs);
			else qs(value);
		});
		return queryString.join('&');
	}

});

Element.extend({

	scrollTo: function(x, y){
		this.scrollLeft = x;
		this.scrollTop = y;
	},

	getSize: function(){
		return {
			'scroll': {'x': this.scrollLeft, 'y': this.scrollTop},
			'size': {'x': this.offsetWidth, 'y': this.offsetHeight},
			'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight}
		};
	},

	getPosition: function(overflown){
		overflown = overflown || [];
		var el = this, left = 0, top = 0;
		do {
			left += el.offsetLeft || 0;
			top += el.offsetTop || 0;
			el = el.offsetParent;
		} while (el);
		overflown.each(function(element){
			left -= element.scrollLeft || 0;
			top -= element.scrollTop || 0;
		});
		return {'x': left, 'y': top};
	},

	getTop: function(overflown){
		return this.getPosition(overflown).y;
	},

	getLeft: function(overflown){
		return this.getPosition(overflown).x;
	},

	getCoordinates: function(overflown){
		var position = this.getPosition(overflown);
		var obj = {
			'width': this.offsetWidth,
			'height': this.offsetHeight,
			'left': position.x,
			'top': position.y
		};
		obj.right = obj.left + obj.width;
		obj.bottom = obj.top + obj.height;
		return obj;
	}

});

Element.Events.domready = {

	add: function(fn){
		if (window.loaded){
			fn.call(this);
			return;
		}
		var domReady = function(){
			if (window.loaded) return;
			window.loaded = true;
			window.timer = $clear(window.timer);
			this.fireEvent('domready');
		}.bind(this);
		if (document.readyState && window.webkit){
			window.timer = function(){
				if (['loaded','complete'].contains(document.readyState)) domReady();
			}.periodical(50);
		} else if (document.readyState && window.ie){
			if (!$('ie_ready')){
				var src = (window.location.protocol == 'https:') ? '://0' : 'javascript:void(0)';
				document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
				$('ie_ready').onreadystatechange = function(){
					if (this.readyState == 'complete') domReady();
				};
			}
		} else {
			window.addListener("load", domReady);
			document.addListener("DOMContentLoaded", domReady);
		}
	}

};

window.onDomReady = function(fn){ 
	return this.addEvent('domready', fn); 
};

window.extend({

	getWidth: function(){
		if (this.webkit419) return this.innerWidth;
		if (this.opera) return document.body.clientWidth;
		return document.documentElement.clientWidth;
	},

	getHeight: function(){
		if (this.webkit419) return this.innerHeight;
		if (this.opera) return document.body.clientHeight;
		return document.documentElement.clientHeight;
	},

	getScrollWidth: function(){
		if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
		if (this.webkit) return document.body.scrollWidth;
		return document.documentElement.scrollWidth;
	},

	getScrollHeight: function(){
		if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
		if (this.webkit) return document.body.scrollHeight;
		return document.documentElement.scrollHeight;
	},

	getScrollLeft: function(){
		return this.pageXOffset || document.documentElement.scrollLeft;
	},

	getScrollTop: function(){
		return this.pageYOffset || document.documentElement.scrollTop;
	},

	getSize: function(){
		return {
			'size': {'x': this.getWidth(), 'y': this.getHeight()},
			'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()},
			'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()}
		};
	},
	getPosition: function(){return {'x': 0, 'y': 0};}

});
///////////////////////////////////////////////
//
//  UWA widget support
//
///////////////////////////////////////////////


// Funcs

function $(el){
//    var e = document.getElementById(el);
	return document.getElementById(el);
};

document.getElementsBySelector = document.getElementsByTagName;


// Elements extensions
function createElementEx(tagName) {
    var el = document.createElement(tagName);
    UWA.$element(el);
    return el;
}


// Objects ext
String.prototype.escapeHTML = function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
}

String.prototype.unescapeHTML = function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
}

String.prototype.stripTags = function() {
    return this.replace(/<\/?[^>]+>/gi, '');
}

String.prototype.stripScripts = function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
}

String.prototype.extractScripts = function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
        return (scriptTag.match(matchOne) || ['', ''])[1];
    });
}

String.prototype.truncate = function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
        this.slice(0, length - truncation.length) + truncation : this;
};

String.prototype.toArray = function() {
    return this.split(''); 
}


Array.prototype.each = function(f) { 
    for(var i=0; i<this.length; i++) {
        f(this[i]); 
    }
}

var $A = function(iterable) {
    if (!iterable)
        return [];
    if (iterable.toArray) {
        return iterable.toArray();
    } else {
        var results = [];
        for (var i = 0; i < iterable.length; i++)
           results.push(iterable[i]);
        return results;
    }
}


Function.prototype.bind = function() {
    var __method = this, 
        args = $A(arguments), 
        object = args.shift();
    return function() {
        return __method.apply(object, args.concat($A(arguments)));
    }
}

// Browser

Browser = {}
Browser.isIE = ie_nav;


// UWA adds

UWA = {};


UWA.extend = function() {
    for (var property in arguments[1]) arguments[0][property] = arguments[1][property];
    return arguments[0];
}

UWA.merge = function() {
    for (var property in arguments[1]) {
      if(typeof arguments[0][property] == "undefined")
        arguments[0][property] = arguments[1][property];
    }
    return arguments[0];
}

UWA.log = function(string) {}






////////////////////////////////////////////
//  Elements
////////////////////////////////////////////

UWA.$element = function(el){
  if (el) {
    if (!el.isUwaExtended) {
      UWA.extend(el, UWA.Element);
      el.isUwaExtended = true;
    }
    return el;
  }
}


if (typeof UWA.Element == "undefined") UWA.Element = {};

UWA.extend(UWA.Element, {
  
  hasClassName: function(className) {
    return this.hasClass(className);
  },
  addClassName: function(className) {
    return this.addClass(className);
  },
  removeClassName: function(className) {
    return this.removeClass(className);
  },
  hide: function() {
   return this.setStyle('display', 'none');
  },
  show: function() {
    return this.setStyle('display', '');
  },
  toggle: function() {
    if(this.style.display == 'none') {
      this.style.display = '';
    } else {
      this.style.display = 'none';
    }
  },
  getDimensions: function() {
    return { 'width' : this.offseWidth , 'height' : this.offseHeight }
  },

  addContent: function(content) {
    if (typeof content == 'string') {
      var node = document.createElement("div");
      node.innerHTML = content;
      return this.appendChild(node);
    }
    return this.appendChild(content);
  },

  appendText: function(text) {
    var node = document.createTextNode(text);
    return this.appendChild(node);
  },

  setText: function(text) {
    this[(typeof this.innerText != 'undefined') ? 'innerText' : 'textContent'] = text;
    return this;
  },

  setHTML: function(html) {
    this.innerHTML = html;
    return this;
  },

  setContent: function(content) {
    if (typeof content == 'string') {
      this.setHTML(content);
    } else if (typeof content == 'object') {
      this.empty();
      this.appendChild(content);
    }
    return this;
  },

  empty: function() {
    this.innerHTML = '';
    return this;
  },
  
  getParent: function(){
		return this.parentNode;
	},

	getChildren: function(){
		return this.childNodes;
	},

    getElementsByClassName: function(className) {
        var children = (this || document.body).getElementsByTagName('*');
        var res = [];
        for(var i=0; i<children.length; i++) {
            if(children[i].className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) {
//            if(children[i].className.indexOf(className) != -1) {
                UWA.$element(children[i])
                res.push(children[i]);
            }
        }
//        return res.length == 0 ? null : res;
        return res;
    }

});


////////////////////////////////////////////
//  Requests
////////////////////////////////////////////

UWA.Data = {};
UWA.Data.getFeed = function(url, callback) {
    request.commonRequest(url, callback, "feed");
}

UWA.Data.getXml = function(url, callback) {
    request.commonRequest(url, callback, "xml");
}

UWA.Data.getJson = function(url, callback) {
    request.commonRequest(url, callback, "json");
}

UWA.Data.getText = function(url, callback) {
    request.commonRequest(url, callback, "text");
}

UWA.Data.request = function(url, params) {
    request.commonRequest(url, params.onComplete, params.type);
}

function _(str) {
	return str;
}



////////////////////////////////////////
// NV
////////////////////////////////////////
/*
NV_PATH = "/";
NV_HOST = BASE_URL;
NV_STATIC  = "http://" + BASE_URL;
NV_ECO  = BASE_URL;
NV_MODULES  = BASE_URL;
*/
var NV_HOST = 'www.netvibes.com';
var NV_PATH = 'http://www.netvibes.com/';
var NV_STATIC = '';
var NV_MODULES = 'nvmodules.netvibes.com';



UWA.Utils = {}
UWA.Utils.setTooltip = function(a,b,c) {}



////////////////////////////////////////
// CONTROLS - TAB VIEW
////////////////////////////////////////
UWA.Controls = {}
UWA.Controls.TabView = function() {
   

    this.dom = document.createElement("div");
    this.dom.className = "nv-tabSet";
    this.head = document.createElement("ul");
    this.head.className = "nv-tabList";
    this.dom.appendChild(this.head);


    this.tabs = {};
    this.tabsContent = {};

    this.activeTab = null;

    this.callBacks = {};

    // data: { text: "", customInfo: "" }
    this.addTab = function(name, data) {
        var self = this;
        var tab = document.createElement("li");
        tab.className = "";

        var lnk = document.createElement("a");
        lnk.innerHTML = data.text;
        lnk.href = "javascript:void(0);";
        lnk.onclick = function() {
            self.onTabClick(name);
            return false;
        }
        tab.appendChild(lnk);

        this.tabs[name] = tab;
        this.head.appendChild(tab);

        var tabContent = createElementEx("div");
        tabContent.className = "nv-tabContent";
        tabContent.style.display = "none";

        this.tabsContent[name] = tabContent;
        this.dom.appendChild(tabContent);

        if(this.activeTab == null) {
            this.selectTab(name);
        }
    }


    this.onTabClick = function(name) {
        this.selectTab(name);
        this.callBacks["activeTabChange"](name, null);
    }


    this.selectTab = function(name) {
        if(this.activeTab) {
            this.hideTab(this.activeTab);
        }
        this.activeTab = name;
        this.showTab(name);
    }

    this.showTab = function(name) {
        this.tabs[name].className = "selected";
        this.tabsContent[name].style.display = "";
    }

    this.hideTab = function(name) {
        this.tabs[name].className = "";
        this.tabsContent[name].style.display = "none";
    }


    this.appendTo = function(parentEl) {
        parentEl.appendChild(this.dom);
    }


    this.getTabContent = function(name) {
        return this.tabsContent[name];
    }

    this.setContent = function(name, content) {
        this.tabsContent[name].setContent(content);
    }

    this.observe = function(eventName, callBack) {
        this.callBacks[eventName] = callBack;
    }

}




////////////////////////////////////////
// CONTROLS - PAGER
////////////////////////////////////////

// data: { module: object, limit: items per page, offset: current offset, dataArray: items }
// items: [ { title, description, link }, ... ]
UWA.Controls.Pager = function(data) {

    this.module = data.module;

    var perPage = parseInt(data.limit || 5);
    var offset = parseInt(data.offset || 0);
    var total = data.dataArray.length;

    var self = this;

    var dom = document.createElement("div");
    dom.className = "nv-pager";
    var prev = document.createElement("a");
    prev.className = "prev";
    prev.innerHTML = loc.text("lbl_prev");
    prev.style.display = (offset > 0) ? "block" : "none";
    prev.href = "javascript:void(0);";
    prev.onclick = function() {
        self.updateOffset(-perPage);
        return false;
    }
    dom.appendChild(prev);

    var next = document.createElement("a");
    next.className = "next";
    next.innerHTML = loc.text("lbl_next");
    next.style.display = (offset < total - perPage) ? "block" : "none";
    next.href = "javascript:void(0);";
    next.onclick = function() {
        self.updateOffset(perPage);
        return false;
    }
    dom.appendChild(next);        


    this.updateOffset = function(d) {
        offset += d;
        prev.style.display = (offset > 0) ? "block" : "none";
        next.style.display = (offset < total - perPage) ? "block" : "none";
        this.onChange(offset);
    }


    this.getContent = function() {
        return dom;        
    }

    this.onChange = function(newOffset) {}

}

// JavaScript Document
if(jQuery) {
	//Converts XML DOM to JSON
	jQuery.extend ({
		xmlToJSON: function(xdoc) {
		try {
			if(!xdoc){ return null; }
			var tmpObj = {};
				tmpObj.typeOf = "JSXBObject";
			var xroot = (xdoc.nodeType == 9)?xdoc.documentElement:xdoc;
			
			if(xdoc.nodeType == 3 || xdoc.nodeType == 4) {
				return xdoc.nodeValue;
			}			
			//Set Object Nodes
			function setObjects(obj, node) {
				var elemName;	//Element name
				var cnode;	//Current Node
				var tObj;	//New subnode
				var cName = "";
				if(!node) { return null; }
				if(!node.hasChildNodes()) { return null; }
				var nodeCount = node.childNodes.length - 1;	
				//Set node attributes if any
				if(node.attributes.length > 0) {
					setAttributes(obj, node);
				}
				//Process child nodes
				obj._children = [];
				obj.Text = "";
				var n = 0;
				do { //Order is irrelevant (speed-up)
					cnode = node.childNodes[n];
					switch(cnode.nodeType) {
						case 1: //Node
						//SOAP XML FIX to remove namespaces (i.e. soapenv:)
						elemName = (cnode.localName)?cnode.localName:cnode.baseName;
						elemName = formatName(elemName);
						if(cName != elemName) { obj._children.push(elemName); }
							//Create sub elemns array
							if(!obj[elemName]) {
								obj[elemName] = []; //Create Collection
							}
							tObj = {};
							obj[elemName].push(tObj);
							if(cnode.attributes.length > 0) {
								setAttributes(tObj, cnode);
							}
							//Set Helper functions (contains, indexOf, sort, etc);
							if(!obj[elemName].contains) {
								setHelpers(obj[elemName]);
							}	
						cName = elemName;
						if(cnode.hasChildNodes()) {
							setObjects(tObj, cnode); //Recursive Call
						}
						break;
						case 3: //Text Value
						obj.Text += jQuery.trim(cnode.nodeValue);
						break;
						case 4: //CDATA
						obj.Text += (cnode.text)?jQuery.trim(cnode.text):jQuery.trim(cnode.nodeValue);
						break;
					}
				} while(n++ < nodeCount);
			}
			//Set collections
			function setHelpers(grpObj) {
				//Selects a node withing array where attribute = value
				grpObj.getNodeByAttribute = function(attr, obj) {
					if(this.length > 0) {
						var cNode;
						var maxLen = this.length -1;
						try {
							do {
								cNode = this[maxLen];
								if(cNode[attr] == obj) {
									return cNode;
								}
							} while(maxLen--);
						} catch(e) {return false;}
						return false;
					}
				}
				
				grpObj.contains = function(attr, obj) {
					if(this.length > 0) {
						var maxLen = this.length -1;
						try {
							do {
								if(this[maxLen][attr] == obj) {
									return true;
								}
							} while(maxLen--);
						} catch(e) {return false;}
						return false;
					}
				}
				
				grpObj.indexOf = function(attr, obj) {
					var pos = -1;
					if(this.length > 0) {
						var maxLen = this.length -1;
						try {
							do {
								if(this[maxLen][attr] == obj) {
									pos = maxLen;
								}
							} while(maxLen--);
						} catch(e) {return -1;}
						return pos;
					}
				}
				
				grpObj.SortByAttribute = function(col, dir) {
					if(this.length) {				
						function getValue(pair, idx) {
							var out = pair[idx];
							out = (isNumeric(out))?parseFloat(out):out;
							return out;
						}
						function sortFn(a, b) {
							var res = 0;
							var tA, tB;						
							tA = getValue(a, col);
							tB = getValue(b, col);
							if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
							if(dir) {
								res = (dir.toUpperCase() == "DESC")?(0 - res):res;
							}
							return res;
						}
						this.sort(sortFn);
					}
				}
				
				grpObj.SortByValue = function(dir) {
					if(this.length) {
						function getValue(pair) {
							var out = pair.Text;
							out = (isNumeric(out))?parseFloat(out):out;
							return out;
						}
						function sortFn(a, b) {
							var res = 0;
							var tA, tB;
							tA = getValue(a);
							tB = getValue(b);
							if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
							if(dir) {
								res = (dir.toUpperCase() == "DESC")?(0 - res):res;
							}
							return res;
						}
						this.sort(sortFn);
					}
				}
				grpObj.SortByNode = function(node, dir) {
					if(this.length) {
						function getValue(pair, node) {
							var out = pair[node][0].Text;
							out = (isNumeric(out))?parseFloat(out):out;
							return out;
						}
						function sortFn(a, b) {
							var res = 0;
							var tA, tB;
							tA = getValue(a, node);
							tB = getValue(b, node);
							if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
							if(dir) {
								res = (dir.toUpperCase() == "DESC")?(0 - res):res;
							}
							return res;
						}
						this.sort(sortFn);
					}
				}
			}
			//Set Attributes of an object
			function setAttributes(obj, node) {
				if(node.attributes.length > 0) {
					var a = node.attributes.length-1;
					var attName;
					obj._attributes = [];
					do { //Order is irrelevant (speed-up)
						attName = String(formatName(node.attributes[a].name));
						obj._attributes.push(attName);				
						obj[attName] = jQuery.trim(node.attributes[a].value);
					} while(a--);
				}
			}
			//Alters attribute and collection names to comply with JS
			function formatName(name) {
				var regEx = /-/g;
				var tName = String(name).replace(regEx,"_");
				return tName;
			}
			var isNumeric = function(s) {
				var testStr = "";
				if(s && typeof s == "string") { testStr = s; }
				var pattern = /^((-)?([0-9]*)((\.{0,1})([0-9]+))?jQuery)/;
				return pattern.test(testStr);
			}
			//RUN
			setObjects(tmpObj, xroot);
			//Clean-up memmory
			xdoc = null;
			xroot = null;
			return tmpObj;
			
			} catch(e) {
				return null;	
			}
		}		
	})
	
	//Converts Text to XML DOM
	jQuery.extend({
		textToXML: function(strXML) {
			try {
			var xmlDoc = (jQuery.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
				xmlDoc.async = false;
			} catch(e) {throw new Error("XML Parser could not be instantiated");}
			var out;
			try {
				if(jQuery.browser.msie) {
					out = (xmlDoc.loadXML(strXML))?xmlDoc:false;
				} else {		
					out = xmlDoc.parseFromString(strXML, "text/xml");
				}
			} catch(e) { throw new Error("Error parsing XML string"); }
			return out;
		}
	})	
} else {
	alert("jQuery library is not present");	
}

;(function($){$.effects=$.effects||{};$.extend($.effects,{save:function(el,set){for(var i=0;i<set.length;i++){if(set[i]!==null)$.data(el[0],"ec.storage."+set[i],el[0].style[set[i]]);}},restore:function(el,set){for(var i=0;i<set.length;i++){if(set[i]!==null)el.css(set[i],$.data(el[0],"ec.storage."+set[i]));}},setMode:function(el,mode){if(mode=='toggle')mode=el.is(':hidden')?'show':'hide';return mode;},getBaseline:function(origin,original){var y,x;switch(origin[0]){case'top':y=0;break;case'middle':y=0.5;break;case'bottom':y=1;break;default:y=origin[0]/original.height;};switch(origin[1]){case'left':x=0;break;case'center':x=0.5;break;case'right':x=1;break;default:x=origin[1]/original.width;};return{x:x,y:y};},createWrapper:function(el){if(el.parent().attr('id')=='fxWrapper')
return el;var props={width:el.outerWidth({margin:true}),height:el.outerHeight({margin:true}),'float':el.css('float')};el.wrap('<div id="fxWrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');var wrapper=el.parent();if(el.css('position')=='static'){wrapper.css({position:'relative'});el.css({position:'relative'});}else{var top=parseInt(el.css('top'),10);if(isNaN(top))top='auto';var left=parseInt(el.css('left'),10);if(isNaN(left))left='auto';wrapper.css({position:el.css('position'),top:top,left:left,zIndex:el.css('z-index')}).show();el.css({position:'relative',top:0,left:0});}
wrapper.css(props);return wrapper;},removeWrapper:function(el){if(el.parent().attr('id')=='fxWrapper')
return el.parent().replaceWith(el);return el;},setTransition:function(el,list,factor,val){val=val||{};$.each(list,function(i,x){unit=el.cssUnit(x);if(unit[0]>0)val[x]=unit[0]*factor+unit[1];});return val;},animateClass:function(value,duration,easing,callback){var cb=(typeof easing=="function"?easing:(callback?callback:null));var ea=(typeof easing=="object"?easing:null);return this.each(function(){var offset={};var that=$(this);var oldStyleAttr=that.attr("style")||'';if(typeof oldStyleAttr=='object')oldStyleAttr=oldStyleAttr["cssText"];if(value.toggle){that.hasClass(value.toggle)?value.remove=value.toggle:value.add=value.toggle;}
var oldStyle=$.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(value.add)that.addClass(value.add);if(value.remove)that.removeClass(value.remove);var newStyle=$.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(value.add)that.removeClass(value.add);if(value.remove)that.addClass(value.remove);for(var n in newStyle){if(typeof newStyle[n]!="function"&&newStyle[n]&&n.indexOf("Moz")==-1&&n.indexOf("length")==-1&&newStyle[n]!=oldStyle[n]&&(n.match(/color/i)||(!n.match(/color/i)&&!isNaN(parseInt(newStyle[n],10))))&&(oldStyle.position!="static"||(oldStyle.position=="static"&&!n.match(/left|top|bottom|right/))))offset[n]=newStyle[n];}
that.animate(offset,duration,ea,function(){if(typeof $(this).attr("style")=='object'){$(this).attr("style")["cssText"]="";$(this).attr("style")["cssText"]=oldStyleAttr;}else $(this).attr("style",oldStyleAttr);if(value.add)$(this).addClass(value.add);if(value.remove)$(this).removeClass(value.remove);if(cb)cb.apply(this,arguments);});});}});$.fn.extend({_show:$.fn.show,_hide:$.fn.hide,__toggle:$.fn.toggle,_addClass:$.fn.addClass,_removeClass:$.fn.removeClass,_toggleClass:$.fn.toggleClass,effect:function(fx,o,speed,callback){return $.effects[fx]?$.effects[fx].call(this,{method:fx,options:o||{},duration:speed,callback:callback}):null;},show:function(){if(!arguments[0]||(arguments[0].constructor==Number||/(slow|normal|fast)/.test(arguments[0])))
return this._show.apply(this,arguments);else{var o=arguments[1]||{};o['mode']='show';return this.effect.apply(this,[arguments[0],o,arguments[2]||o.duration,arguments[3]||o.callback]);}},hide:function(){if(!arguments[0]||(arguments[0].constructor==Number||/(slow|normal|fast)/.test(arguments[0])))
return this._hide.apply(this,arguments);else{var o=arguments[1]||{};o['mode']='hide';return this.effect.apply(this,[arguments[0],o,arguments[2]||o.duration,arguments[3]||o.callback]);}},toggle:function(){if(!arguments[0]||(arguments[0].constructor==Number||/(slow|normal|fast)/.test(arguments[0]))||(arguments[0].constructor==Function))
return this.__toggle.apply(this,arguments);else{var o=arguments[1]||{};o['mode']='toggle';return this.effect.apply(this,[arguments[0],o,arguments[2]||o.duration,arguments[3]||o.callback]);}},addClass:function(classNames,speed,easing,callback){return speed?$.effects.animateClass.apply(this,[{add:classNames},speed,easing,callback]):this._addClass(classNames);},removeClass:function(classNames,speed,easing,callback){return speed?$.effects.animateClass.apply(this,[{remove:classNames},speed,easing,callback]):this._removeClass(classNames);},toggleClass:function(classNames,speed,easing,callback){return speed?$.effects.animateClass.apply(this,[{toggle:classNames},speed,easing,callback]):this._toggleClass(classNames);},morph:function(remove,add,speed,easing,callback){return $.effects.animateClass.apply(this,[{add:add,remove:remove},speed,easing,callback]);},switchClass:function(){return this.morph.apply(this,arguments);},cssUnit:function(key){var style=this.css(key),val=[];$.each(['em','px','%','pt'],function(i,unit){if(style.indexOf(unit)>0)
val=[parseFloat(style),unit];});return val;}});jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);}
fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)
return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent']
return colors[jQuery.trim(color).toLowerCase()];}
function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))
break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};jQuery.easing['jswing']=jQuery.easing['swing'];jQuery.extend(jQuery.easing,{def:'easeOutQuad',swing:function(x,t,b,c,d){return jQuery.easing[jQuery.easing.def](x,t,b,c,d);},easeInQuad:function(x,t,b,c,d){return c*(t/=d)*t+b;},easeOutQuad:function(x,t,b,c,d){return-c*(t/=d)*(t-2)+b;},easeInOutQuad:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;},easeInCubic:function(x,t,b,c,d){return c*(t/=d)*t*t+b;},easeOutCubic:function(x,t,b,c,d){return c*((t=t/d-1)*t*t+1)+b;},easeInOutCubic:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t+b;return c/2*((t-=2)*t*t+2)+b;},easeInQuart:function(x,t,b,c,d){return c*(t/=d)*t*t*t+b;},easeOutQuart:function(x,t,b,c,d){return-c*((t=t/d-1)*t*t*t-1)+b;},easeInOutQuart:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t+b;return-c/2*((t-=2)*t*t*t-2)+b;},easeInQuint:function(x,t,b,c,d){return c*(t/=d)*t*t*t*t+b;},easeOutQuint:function(x,t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b;},easeInOutQuint:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t*t+b;return c/2*((t-=2)*t*t*t*t+2)+b;},easeInSine:function(x,t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b;},easeOutSine:function(x,t,b,c,d){return c*Math.sin(t/d*(Math.PI/2))+b;},easeInOutSine:function(x,t,b,c,d){return-c/2*(Math.cos(Math.PI*t/d)-1)+b;},easeInExpo:function(x,t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOutExpo:function(x,t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOutExpo:function(x,t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;},easeInCirc:function(x,t,b,c,d){return-c*(Math.sqrt(1-(t/=d)*t)-1)+b;},easeOutCirc:function(x,t,b,c,d){return c*Math.sqrt(1-(t=t/d-1)*t)+b;},easeInOutCirc:function(x,t,b,c,d){if((t/=d/2)<1)return-c/2*(Math.sqrt(1-t*t)-1)+b;return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b;},easeInElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);return-(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;},easeOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);return a*Math.pow(2,-10*t)*Math.sin((t*d-s)*(2*Math.PI)/p)+c+b;},easeInOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d/2)==2)return b+c;if(!p)p=d*(.3*1.5);if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);if(t<1)return-.5*(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;return a*Math.pow(2,-10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p)*.5+c+b;},easeInBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*(t/=d)*t*((s+1)*t-s)+b;},easeOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b;},easeInOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;if((t/=d/2)<1)return c/2*(t*t*(((s*=(1.525))+1)*t-s))+b;return c/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;},easeInBounce:function(x,t,b,c,d){return c-jQuery.easing.easeOutBounce(x,d-t,0,c,d)+b;},easeOutBounce:function(x,t,b,c,d){if((t/=d)<(1/2.75)){return c*(7.5625*t*t)+b;}else if(t<(2/2.75)){return c*(7.5625*(t-=(1.5/2.75))*t+.75)+b;}else if(t<(2.5/2.75)){return c*(7.5625*(t-=(2.25/2.75))*t+.9375)+b;}else{return c*(7.5625*(t-=(2.625/2.75))*t+.984375)+b;}},easeInOutBounce:function(x,t,b,c,d){if(t<d/2)return jQuery.easing.easeInBounce(x,t*2,0,c,d)*.5+b;return jQuery.easing.easeOutBounce(x,t*2-d,0,c,d)*.5+c*.5+b;}});})(jQuery);;(function($){$.effects.highlight=function(o){return this.queue(function(){var el=$(this),props=['backgroundImage','backgroundColor','opacity'];var mode=$.effects.setMode(el,o.options.mode||'show');var color=o.options.color||"#ffff99";var oldColor=el.css("backgroundColor");$.effects.save(el,props);el.show();el.css({backgroundImage:'none',backgroundColor:color});var animation={backgroundColor:oldColor};if(mode=="hide")animation['opacity']=0;el.animate(animation,{queue:false,duration:o.duration,easing:o.options.easing,complete:function(){if(mode=="hide")el.hide();$.effects.restore(el,props);if(mode=="show"&&jQuery.browser.msie)this.style.removeAttribute('filter');if(o.callback)o.callback.apply(this,arguments);el.dequeue();}});});};})(jQuery);

/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[@src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[@src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);


function Auth() {

	this.init();

	this.cfg = {
		hasIcon: true,
		hasSizeBtn: false,
		hasCloseBtn: true,
		hasRefreshBtn: false,
		hasSettingsBtn: false,
		hasDrag: false,
		hasOnCloseConfirm: false,
		isOpenHidden: false,
		isSystem: true,
		title: loc.text("auth_title"),
		module: "Auth",
		uniqueId: SYS_WIDGETS_ID + 2
	}

	this.user = { id: null,
	email: null,
	password: null}




	this.domContent = [
	{ tag: "div", className: "float_panel",
	id: "login_form",
	childs: [
	{ tag: "div", className: "float_left",
	style: { width: "45%", padding: "8px" },
	childs: [
	// login exist user
	{ tag: "h1", html: loc.text("auth_exist_user") },
	{ tag: "div", html: loc.text("inp_email") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "login_email", size: "30",
	type: "text" }
	]},
	{ tag: "div", html: loc.text("inp_pwd") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "login_pwd", size: "30",
	type: "password" }
	]},
	{ tag: "div", style: { textAlign: "center", marginTop: "12px"},
	childs: [
	{ tag: "input", id: "login_btn",
	events: { onclick: "tryLogin()"},
	type: "button", value: loc.text("auth_load_my_page") }
	]},
	{ tag: "div", id: "login_msg",
	style: { marginTop: "12px", textAlign: "justify"}},

	// pwd remind
	{ tag: "div",
	style: { marginTop: "12px"},
	childs: [
	{ tag: "div",
	id: "pwd_remind_link",
	childs: [
	{ tag: "a", href: "showRemindForm()",
	html: loc.text("auth_lnk_forget_pwd") }
	]},
	{ tag: "div",
	display: false,
	id: "pwd_remind_form",
	childs: [
	{ tag: "h1", html: loc.text("auth_remind_title")},

	{ tag: "div", html: loc.text("inp_email") },
	{ tag: "div",
	childs: [
	{ tag: "input", size: "30",
	id: "inp_reminder_email",
	type: "text" },
	{ tag: "input", type: "button",
	value: loc.text("btn_send"),
	events: { onclick: "remindPwd()"} }
	]}
	]},
	{ tag: "div", id: "pwd_remind_msg",
	html: loc.text("msg_sending"),
	display: false }
	]}
	]},

	// new user explanation
	{ tag: "div", className: "float_right",
	style: { width: "45%", padding: "8px" },
	childs: [
	{ tag: "h1", html: loc.text("auth_new_user") },
	{ tag: "div", style: { textAlign: "justify"},
	html: loc.text("auth_reg_msg") },
	{ tag: "div", style: { textAlign: "center", marginTop: "12px"},
	childs: [
	{ tag: "input", id: "goreg_btn",
	events: { onclick: "showRegform()"},
	type: "button", value: loc.text("auth_registration") }
	]}
	]}
	]},

	{ tag: "div", id: "reg_form", className: "float_panel",
	display: false,
	childs: [
	{ tag: "div", className: "float_left",
	style: { width: "45%", padding: "8px" },
	childs: [
	{ tag: "h1", html: loc.text("auth_new_user") },
	{ tag: "div", style: { textAlign: "justify"},
	html: loc.text("auth_reg_msg") }
	]},

	{ tag: "div", className: "float_right",
	style: { width: "45%", padding: "8px" },
	childs: [
	{ tag: "h1", html: "&nbsp;" },
	{ tag: "div", html: loc.text("inp_email") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "reg_email", size: "30",
	type: "text" }
	]},
	{ tag: "div", html: loc.text("inp_email2") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "reg_email2", size: "30",
	type: "text" }
	]},

	{ tag: "div", html: loc.text("inp_pwd") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "reg_pwd", size: "30",
	type: "password" }
	]},
	{ tag: "div", html: loc.text("inp_pwd2") },
	{ tag: "div",
	childs: [
	{ tag: "input", id: "reg_pwd2", size: "30",
	type: "password" }
	]},

	{ tag: "div", style: { textAlign: "center", marginTop: "12px"},
	childs: [
	{ tag: "input", id: "reg_btn",
	events: { onclick: "tryRegister()"},
	type: "button", value: loc.text("auth_process_reg_btn") }
	]},
	{ tag: "div", id: "reg_msg",
	style: { marginTop: "12px", textAlign: "justify"}}
	]}
	]},


	{ tag: "div", id: "reg_ok", className: "float_panel",
	display: false,
	childs: [
	{ tag: "div", className: "float_left",
	style: { width: "45%", padding: "8px" },
	childs: [
	{ tag: "h1", html: loc.text("auth_new_user") },
	{ tag: "div", style: { textAlign: "justify"},
	html: loc.text("auth_registration_ok") },
	{ tag: "div", style: { textAlign: "center", marginTop: "12px"},
	childs: [
	{ tag: "input", type: "button",
	events: { onclick: "regFinish()"},
	value: loc.text("btn_ok")}
	]}
	]}
	]}
	]
	
	
	this.domContent = [];



	this.onBuildInterface = function() {
		this.buildDomModel(this.elements.content, this.domContent);

//		this.buildDomModel(desktop.elements.authButton,
//		[{ tag: "span", id:"signinBtn",
//		childs: [createButtonDom(loc.text("auth_lnk_sign_in"), "signIn()", "widgets/auth/img/sign_in.gif")]  },
//		{ tag: "span", id:"signoutBtn",
//		childs: [createButtonDom(loc.text("auth_lnk_sign_out"), "logout()", "widgets/auth/img/sign_out.gif")]  }]);
//
//		if(this.isLogged()) {
//			hideEl(this.elements.signinBtn);
//		} else {
//			hideEl(this.elements.signoutBtn);
//		}
//		this.setTitle(loc.text("auth_title"));
	}



	this.showRemindForm = function() {
		this.showElement("pwd_remind_form");
		this.hideElement("pwd_remind_link");
		this.hideElement("pwd_remind_msg");
		this.elements["inp_reminder_email"].value = "";
		this.elements["inp_reminder_email"].focus();
	}


	this.regFinish = function() {
		this.close();
	}


	this.remindPwd = function() {
		var email = trim(this.elements["inp_reminder_email"].value);
		if(this.checkEmail(email)) {
			request.send( { act: "remind_pwd", email: email }, this);
			this.hideElement("pwd_remind_form");
			this.showElement("pwd_remind_msg");
		}
	}


	this.showRegform = function() {
		this.showElement("reg_form");
		this.hideElement("login_form");
	}


	this.hideRegform = function() {
		this.hideElement("reg_form");
		this.showElement("login_form");
	}




	this.tryLogin = function() {
		var e = trim(this.elements["login_email"].value);
		var pwd = trim(this.elements["login_pwd"].value);
		if(e != "" && pwd != "") {
			request.send({ act: "login_user",
			email: e,
			password: pwd }, this);
			this.hideElement("login_btn");
			this.hideElement("goreg_btn");
			this.elements["login_msg"].innerHTML = loc.text("msg_processing");
		}
	}



	this.tryRegister = function() {
		var e = trim(this.elements["reg_email"].value);
		var e2 = trim(this.elements["reg_email2"].value);
		var pwd = trim(this.elements["reg_pwd"].value);
		var pwd2 = trim(this.elements["reg_pwd2"].value);

		if(e != e2 || !this.checkEmail(e)) {
			this.elements["reg_msg"].innerHTML = loc.text("auth_email_error");
		} else if(pwd != pwd2 || !this.checkPassword(pwd)) {
			this.elements["reg_msg"].innerHTML = loc.text("auth_pwd_error");
		} else if(e != "" && pwd !="") {
			request.send({ act: "register_user",
			email: e,
			password: pwd }, this);
			this.hideElement("reg_btn");
			this.elements["reg_msg"].innerHTML = loc.text("msg_processing");
		}
	}




	this.close = function() {
		this.hideRegform();
		desktop.closeCurrentPage();
	}


	this.signIn = function() {
		desktop.showPage('auth');
	}



	this.isLogged = function() {
		return this.user.email != '';
	}


	this.logout = function() {
		request.send({act: "logout"}, this);
	}



	this.loadUser = function() {
		this.anonymusId = getCookie("anonymusid");
		this.user.id = getCookie("userid");
		this.user.email = getCookie("useremail");
		this.user.password = getCookie("userpassword");
	}


	this.saveUser = function() {
		setCookie("userid", this.user.id);
		setCookie("useremail", this.user.email);
		setCookie("userpassword", this.user.password);
	}








	
	this.start = function() {
		if(session_user) {
			this.user = session_user;
			//            this.saveUser();
			this.onLoad();
		} else {
			this.loadUser();		
			request.send({act: "start_user", user_id: "", email: "", password: ""}, this);

//			if(this.user.email && this.user.password) {
//				request.send({act: "start_user", user_id: this.user.id, email: this.user.email, password: this.user.password}, this);
//			} else {
//				request.send({act: "start_anonymus", user_id: this.user.id}, this);
//			}
		}
	}


	this.dispatchMsg = function(msg) {
		switch(msg.status) {
			case "":
			break;

			case "start_result":
			this.user = msg.user;
			this.name = msg.name;
			auth.firstTime = msg.ftime;
			this.saveUser();
			this.onLoad();
			break;


			case "register_ok":
			this.showElement("reg_ok");
			this.hideElement("reg_form");
			this.elements["signinBtn"].style.display = "none";
			this.elements["signoutBtn"].style.display = "inline";
			this.user = msg.user;
			this.saveUser();
			//dimk
			break;

			case "register_error":
			this.elements["reg_msg"].innerHTML = loc.text("auth_msg_reg_error");
			this.elements["reg_email"].value = "";
			this.elements["reg_email2"].value = "";
			this.showElement("reg_btn");
			break;

			case "login_ok":
			setCookie("anonymusid", this.user.id);
			this.user = msg.user;
			this.saveUser();
			location.reload();
			break;

			case "login_error":
			this.elements["login_msg"].innerHTML = loc.text("auth_login_error");
			this.showElement("login_btn");
			this.showElement("goreg_btn");
			break;


			case "logout_ok":
			var anonymusId = getCookie("anonymusid");
			if(anonymusId) {
				this.user = {id: anonymusId, email: "", password: ""};
				this.saveUser();
				delCookie("anonymusid");
			} else {
				delCookie("userid");
				delCookie("useremail");
				delCookie("userpassword");
			}
			location.reload();
			break;


			case 'user_ok':
			if(!this.user.email) {
				setCookie("anonymusid", this.user.id);
			}
			this.user = msg.user;
			this.saveUser();
			location.reload();
			break;


			case "pwd_sent":
			this.elements["inp_reminder_email"].value = "";
			this.hideElement("pwd_remind_form");
			this.showElement("pwd_remind_link");
			this.hideElement("pwd_remind_msg");
			break;

		}
	}



	this.onLoad = function() {}



	this.registerUser = function() {
		var errors = [];
		email = trim(this.elements.selectEmail.value);
		password = trim(this.elements.selectPassword.value);
		if(!this.checkEmail(email)) {
			errors[errors.length] = "<b>" + loc.text("auth_msg_email_invalid") + "</b>";
		}
		if(!this.checkPassword(password)) {
			errors[errors.length]= "<b>" + loc.text("auth_msg_pwd_invalid") + "</b>";
		}
		if(errors.length > 0) {
			this.elements.messages.innerHTML = errors.join("<BR>");
		} else {
			hideEl(this.elements.submitButton);
			this.elements.messages.innerHTML = loc.text("msg_processing");
			request.send({act: "register_user", email: email, password: password}, this);
		}
	}



	this.checkEmail = function(str) {
		return /^[a-zA-Z][a-z0-9\-\_]{1,20}@[a-z0-9\-\_\.]{5,30}$/.test(str);
	}

	this.checkPassword = function(str) {
		return (str.length > 5);
	}

}
Auth.prototype = new Widget();

function Profiler() {

    this.data = {};

    this.cfg = {
        module: "Profiler",
        hasProfile: false
    }



    this.registerWidget = function(widget) {
        var profile = clone(widget.defaultProfile);
        if(this.data[widget.id]) {
            for(var i in this.data[widget.id]) {
                if(profile[i] != undefined) {
                    profile[i] = this.data[widget.id][i];
                }
            }
        } 
    
        widget.profile = profile;
    }


    this.saveProfile = function(widget) {
    if(auth.isLogged()){
        var wkey = widget.id;//getSignature();
        if(widget.profile) {
            act = this.data[wkey] ? "update" : "create";
            request.send({w: widget.cfg.module, act: act, wkey: wkey, data: escape(toCode(widget.profile))}, this, widget.cfg.saveMethod);
        } else {
            request.send({act: "delete", wkey: wkey}, this);
        }
        this.data[wkey] = widget.profile;
        }
    }


 
    this.loadProfile = function() {    
        request.send({act: "load_data"}, this); 
    }

    this.onLoad = function() {}

    this.dispatchMsg = function(msg) {
        if(msg.status == "loaded") {
            profiler.data = {};
            for(var i in msg.data) {
                try {
                    profiler.data[i] = toValue(unescape(msg.data[i]));
                } catch(e) {
                    profiler.data[i] = {}
                }
            }
            profiler.onLoad();
        }
    }
}

CCIDS = 10000;

function Menu() {
	this.init();

	this.cfg = {
		hasSizeBtn: false,
		hasRefreshBtn: false,
		hasSettingsBtn: false,
		hasDrag: false,
		isOpenHidden: true,
		isSystem: true,
		title: loc.text("menu_title"),
		module: "Menu",
		uniqueId: SYS_WIDGETS_ID + 3
	}



	this.defaultProfile["catalog"] = [];
	this.defaultProfile["recentw"] = [];

	this.widget = null;

	this.eachPageCount = 16;



	this.cuurent_opened_cat = null;

	this.catalog = [];

	this.catalog[CCIDS] = {categories: [{id: CCIDS+1, name: loc.text("menu_cutom_channels")}], items: []};
	this.catalog[CCIDS+1] = {categories: [], items: []};


	this.folder_o = new Image();
	this.folder_o.src = "static/client/folder-o.gif";
	this.folder_s = new Image();
	this.folder_s.src = "static/client/folder-s.gif";
	this.custom_shadowvbox = null;


	this.domModelContent = [
	{ tag: "div", className: "menu_hr"},

	{ tag: "div", className: "menu_panel", id: "cat_content"+CCIDS, display: false },

	{ tag: "div", className: "menu_hr"},

	{ tag: "div", className: "menu_panel", id: "cat_content0", display: false },

	{ tag: "div", className: "menu_hr"},

	{ tag: "div", className: "menu_panel",
	childs: [
	createButtonDom(loc.text("menu_recentw_folder"),
	"switchRWFolder()",
	this.folder_s.src,
	false,
	"recentw_folder_icon"),
	{ tag: "div", id: "recentw_list", className: "menu_sub_panel", display: false }
	]} ,
	{ tag: "div", className: "menu_panel", id: "addFeedMenuItem",
	childs: [createButtonDom(loc.text("menu_add_feed"), "showAddFeedPanel()", "widgets/menu/img/plus.gif")] }
	]


	this.domModelAdditional = [
	{tag : "div" ,align : "center" , className : "addToPage" , id: "preview", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "340px"} ,
	childs : [
	{tag : "div" , aliign : "center" ,
	childs :[
	{tag : "a" , href : "void(0)" , events : { onclick : "closePreview()"}  ,
	childs : [
	{tag : "img" , className : "fl" , src:"static/images/close_tools.gif" , width: "11"  , height:"11"}
	]
	} ,
	{tag : "a" , href : "void(0)" , className :"wit" , events : { onclick : "addToDesktop()"}  ,
	childs : [
	{tag : "img"  , src:"static/images/addToMyPage.gif" ,alt:"أضف الى صفحتي" }
	]
	}

	]
	} ,
	{tag : "div"  , className : "mart10" ,
	childs : [
	{tag : "span" ,id : "preview_panel" , style : {width: "100%", height: "auto", padding: "0", margin: "0" }}
	]
	}
	]
	}
	,
	{ tag: "div", className: "panel", id: "addFeedPanel", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "340px"},
	childs: [
	{ tag: "div", className: "caption",
	childs: [ createTableDom([{content: "<img src='widgets/menu/img/item.gif' style='vertical-align: middle'> &nbsp;<b>" + loc.text("menu_add_feed") + "</b>", width: "99%"},
	{content: createButtonDom(false, "closeAddFeedPanel()", "static/client/close.gif"), width: "1%"}
	]),

	createTableDom([{content: { tag: "div", innerHTML: loc.text("menu_inp_url"), style: {paddingTop: "15px", paddingBottom: "15px"}}, width: "1%"},
	{content: { tag: "input", type: "text", size: "40"}, width: "100%"},
	{content: { tag: "input", type: "button", id: "addFeedButton", events: {onclick: "addFeed()"}, value: loc.text("btn_add")}, width: "1%"}
	]),
	{ tag: "div", display: false, className: "menu_panel", style: {paddingBottom: "15px"}, align: "center"}
	]
	}
	]
	},
	{ tag: "div", className: "panel", id: "item_menu", display: false, style: {padding: "6px", position: "absolute", left: "0px", top: "0px", verticalAlign: "middle"},
	childs: [
	{ tag: "span", id: "item_menu_actions",
	childs: [
	createButtonDom("<b>"+loc.text("menu_rename")+"</b>", "showRenameItemSection()", "static/client/edit.gif"),
	{ tag: "br"},
	createButtonDom("<b>"+loc.text("menu_delete")+"</b>", "showDeleteItemSection()", "static/client/delete_link.gif")
	]},
	{ tag: "span", id: "item_menu_rename",
	display: false,
	innerHTML: "<b>" +loc.text("menu_rename_to")+"</b> &nbsp;",
	childs: [
	{ tag: "input", type: "text", id: "new_item_title", style: {width: "190px"}},
	{ tag: "input", type: "button", value: loc.text("btn_ok"), events: {onclick: "renameItem()"}},
	{ tag: "input", type: "button", value: loc.text("btn_cancel"), events: {onclick: "hideItemMenu()"} }
	]},
	{ tag: "span", id: "item_menu_delete",
	display: false,
	innerHTML: "<b>"+loc.text("menu_delete_prompt")+"</b> &nbsp;",
	childs: [
	{ tag: "input", type: "button", value: loc.text("btn_yes"), events: {onclick: "deleteItem()"} },
	{ tag: "input", type: "button", value: loc.text("btn_no"), events: {onclick: "hideItemMenu()"} }
	]}
	]
	}
	]


	this.tools_containter = [
	{tag : "div" , className:"tools" , align : "left"  ,
	childs : [
	{tag : "div" , className : "bul" ,
	childs :[
	{tag : "ul"  ,
	childs :[
	{tag : "li" , id : "portal_link" ,  className:"b1" , childs : [ {tag :"a" , href:"void(0)" , innerHTML : loc.text("portal_widgets") , events : { onclick:"showPortalWidgetsPanel()"}}]} ,
	{tag : "li" ,  id : "essential_link" , className:"b2" , childs : [ {tag :"a" , href:"void(0)" , innerHTML : loc.text("essential_widgets") , events : { onclick:"showEssentialWidgetsPanel()"}}]} ,
	{tag : "li" ,  id : "news_link" , className:"b3" , childs : [ {tag :"a" , href:"void(0)" , innerHTML :	loc.text("news_widgets")  , events : { onclick:"showNewsWidgetsPanel()"}}]}
	]
	},
	{tag : "hr" } ,
	{tag : "table" , className : "rss" , cellspacing : 7  ,
	childs : [
	{tag : "tr" ,
	childs :[
	{tag : "td" ,
	childs :[
	{tag : "div" , className : "b4" , innerHTML : "&nbsp;"}
	]
	}
	,
	{tag : "td" , align : "right" ,
	childs :[
	{tag : "strong"  , innerHTML : loc.text("menu_add_feed")}
	]
	}
	,
	{tag : "td" , innerHTML : "&nbsp;"}
	]
	}

	,
	{tag : "tr" ,
	childs :[
	{tag : "td" , colspan :2 ,
	childs :[
	{tag : "input" , type : "text" , id : "selectFeedUrl"} ,
	{ tag: "div", display: false, id: "addFeedStatus"}
	]
	}
	,
	{tag : "td"	 ,
	childs :[
	{tag : "img" , id : "addFeedButton" , src : "static/client/rss_submit.gif"   , width : "16" , height : "17" , events : { onclick : "addFeed()" }}
	]}
	]
	}
	]
	}

	]
	}
	,
	{tag : "div" , className : "widgetsArea"  ,
	childs : [
	{tag : "table" , width:"100%"  ,
	childs : [ {tag : "tr" ,
	childs : [
	{tag : "td"  , width : "20" , innerHTML : "<img src='"+images_url+"/static/client/star.gif' alt=''/>"} ,
	{tag : "td"  , className : "ttl" ,
	childs :[
	{tag : "span" , innerHTML : loc.text("browse_elements" )} ,
	{tag : "span" , innerHTML : " &raquo;  "} ,
	{tag : "span" , id : "menu_type_title" }
	]
	},
	{tag : "td"  , className : "hand" , events : { onclick : "close()" } ,  innerHTML : "<img src='"+images_url+"static/client/close_tools.gif' alt='' class='fl' />"}
	]
	}
	]
	} ,
	{tag : "div" , id : "menu_widgets"  , style: {width:"740px" , height:"190px"  , overflow:"hidden"}} ,
	{tag : "div" , className :  "cls"} ,
	{tag : "div" , id : "menu_paging"  , className : "paging" ,
	childs :[
	{tag : "table" , width : "100%" ,
	childs :[
	{tag : "tr" ,
	childs : [
	{tag : "td"   , id : "prev_btn" ,events : { onclick : "prevPage()"} ,  className:"prev" , html : "السابق"} ,
	{tag : "td"  , id : "page_num" , className : "num" , html : ""} ,
	{tag : "td"   , id : "next_btn" ,events : { onclick : "nextPage()"} ,  className:"next", html: "التالي"}
	]
	}
	]
	}
	]
	}

	]
	}
	]
	}
	];



	this.menuSlider = [
	{tag : "div" , className : "bul" ,
	childs :[
	{tag : "ul"  ,
	childs :[
	{tag : "li" , id : "portal_link" ,  className:"b1" , childs : [ {tag :"a" , href:"void(0)" , innerHTML : loc.text("portal_widgets") , events : {onmouseover : "hover_widget(this)"  ,  onclick:"showPortalWidgetsPanel()"}}]} ,
	{tag : "li" ,  id : "essential_link" , className:"b2" , childs : [ {tag :"a" , href:"void(0)" , innerHTML : loc.text("essential_widgets") , events : { onmouseover : "hover_widget(this)"  , onclick:"showEssentialWidgetsPanel()"}}]} ,
	{tag : "li" ,  id : "news_link" , className:"b3" , childs : [ {tag :"a" , href:"void(0)" , innerHTML :	loc.text("news_widgets")  , events : {onmouseover : "hover_widget(this)"  ,  onclick:"showNewsWidgetsPanel()"}}]}
	]
	},
	{tag : "hr" } ,
	{tag : "table" , className : "rss" , cellspacing : 7  ,
	childs : [
	{tag : "tr" ,
	childs :[
	{tag : "td" ,
	childs :[
	{tag : "div" , className : "b4" , innerHTML : "&nbsp;"}
	]
	}
	,
	{tag : "td" , align : "right" ,
	childs :[
	{tag : "strong"  , innerHTML : loc.text("menu_add_feed")}
	]
	}
	,
	{tag : "td" , innerHTML : "&nbsp;"}
	]
	}
	,
	{tag : "tr" ,
	childs :[
	{tag : "td" , colspan :2 , height:2  , innerHTML : "&nbsp;"	}
	,
	{tag : "td" ,  innerHTML : "&nbsp;" }
	]
	}
	,
	{tag : "tr" ,
	childs :[
	{tag : "td" , colspan :2 ,
	childs :[
	{tag : "input" , type : "text" , id : "selectFeedUrl"} ,
	{ tag: "div", display: false, id: "addFeedStatus"}
	]
	}
	,
	{tag : "td"	 ,
	childs :[
	{tag : "img" , id : "addFeedButton" , src : "static/client/rss_submit.gif"   , width : "16" , height : "17" , events : { onclick : "addFeed()" }}
	]}
	]
	}
	]
	}

	]
	}
	];

	this.png_fix_image = "png";
	if(ie_nav){
		this.png_fix_image = "gif";
	}

	//Wizard
	this.wizard = [
	{tag : "div" , className : "wiz" ,display : false, style : { position : "absolute" , zIndex : "99999" , top : "0px" , left : "0px"}  , id : "wizard" ,
	childs :[
	{tag : "ul" ,
	childs : [
	{tag : "li" , className : "st0"} ,
	{tag : "li" , className : "wizActive"  ,id : "step1_tab"  ,
	childs : [
	{tag : "div" ,className : "st1" }
	]
	} ,
	{tag : "li" , className : "wizInActive"   ,id : "step2_tab"  ,
	childs : [
	{tag : "div"   , className : "st2" }
	]
	} ,
	{tag : "li" , className : "wizInActive" , id : "step3_tab" ,
	childs : [
	{tag : "div"  ,className : "st3" }
	]
	}
	]
	}
	,
	{tag : "div"  , id : "wizard_preview" , display : false}

	]
	}
	];
	//Intro Wizard
	this.wizard_0 = [
	{tag : "div" , id : "wizard_intro" , className : "pop" , style : { position : "absolute" , marginTop : "70px" } , display : false ,
	childs : [
	{tag : "div" , className : "arrow" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png" } ,
	]
	}

	,
	{tag : "div" , className : "popIn" ,
	childs : [
	{tag : "div"   , className : "fl" ,
	childs : [
	{tag : "img" , src : "static/images/close_tools.gif"   ,  events : { onclick : "closeWizard()"}   }
	]
	}
	,
	{tag : "div" ,
	childs : [
	{tag : "a" , href : "void(0)" , events : { onclick : "showWizardStep1()"} ,
	childs : [
	{tag : "img" , src : "static/images/st0.gif" , width : "252" , height : "187"}
	]
	}
	]
	}
	]

	}


	]
	}
	];



	//Portal Widgets Selection
	this.wizard_1 = [
	{tag : "div" , id : "wizard_step1" , className : "pop" , style : { position : "absolute" , marginTop : "70px" } , display : false ,
	childs : [
	{tag : "div" , className : "arrow" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png"   }
	]
	}
	,
	{tag : "div" , className : "popIn" ,
	childs : [
	{tag : "div" , className : "close",  style : { marginTop : "0px" , marginRight : ( ie_nav ? "80px" : "270px")} ,
	childs : [
	{tag : "img" , src : "static/images/close_tools.gif"   ,  events : { onclick : "closeWizard()"}   }
	]
	}
	,
	{tag : "div" , align : "right" ,
	childs :[
	{tag : "img" , src : "static/images/picM3com.gif"}
	]
	}
	,
	{tag : "div" , id : "portal_wizard_widgets"} ,
	{tag : "div" , className : "mart10" ,
	childs :[
	{tag : "div" , className : "fr mart10" ,
	childs : [
	{tag : "a" , href : "void(0)" , innerHTML : "&laquo; رجوع"  , events : { onclick : "showWizardIntro()"}  }
	]
	}
	,
	{tag : "div" , className : "fl" ,
	childs : [
	{tag : "a" , href : "void(0)" , events : { onclick : "showWizardStep2()" }  ,
	childs : [
	{tag : "img" , src : "static/images/btnNext.gif" , border : "0"}
	]
	}
	]
	}
	,
	{tag : "div" , className : "cls" }
	]
	}

	]
	}

	]
	}
	];

	//Esential Tools Widgets Selection
	this.wizard_2 = [
	{tag : "div" , id : "wizard_step2" , className : "pop" , style : { position : "absolute" , marginTop : "70px" } , display : false ,
	childs : [
	{tag : "div" , className : "arrow" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png"   }
	]
	}
	,
	{tag : "div" , className : "popIn" ,
	childs : [
	{tag : "div" , className : "close" ,  style : { marginTop : "0px" , marginRight : ( ie_nav ? "80px" : "270px")},
	childs : [
	{tag : "img" , src : "static/images/close_tools.gif"   ,  events : { onclick : "closeWizard()"}   }
	]
	}
	,
	{tag : "div" , align : "right" ,
	childs :[
	{tag : "img" , src : "static/images/picInternet.gif"}
	]
	}
	,
	{tag : "div" , id : "essential_wizard_widgets"} ,
	{tag : "div" , className : "mart10" ,
	childs :[
	{tag : "div" , className : "fr mart10" ,
	childs : [
	{tag : "a" , href : "void(0)" , innerHTML : "&laquo; رجوع" , events : { onclick : "showWizardStep1()"}   }
	]
	}
	,
	{tag : "div" , className : "fl" ,
	childs : [
	{tag : "a" , href : "void(0)" , events : { onclick : "showWizardStep3()" } ,
	childs : [
	{tag : "img" , src : "static/images/btnNext.gif" , border : "0"}
	]
	}
	]
	}
	,
	{tag : "div" , className : "cls" }

	]
	}

	]
	}

	]
	}
	]
	//Theme Selection
	this.wizard_3 = [
	{tag : "div" , id : "wizard_step3" , className : "pop" , style : { position : "absolute" , marginTop : "70px" } , display : false ,
	childs : [
	{tag : "div" , className : "arrow" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png"  , className :"pngImg" }
	]
	}
	,
	{tag : "div" , className : "popIn" ,
	childs : [
	{tag : "div" , className : "close",  style : { marginTop : "0px" , marginRight : ( ie_nav ? "80px" : "270px")} ,
	childs : [
	{tag : "img" , src : "static/images/close_tools.gif"   ,  events : { onclick : "closeWizard()"}   }
	]
	}
	,
	{tag : "div" , align : "right" ,
	childs :[
	{tag : "img" , src : "static/images/picColor.gif"}
	]
	}
	,
	{tag : "div" , id : "wizard_themes" ,className :"mart10 skins skinsMini"},
	{tag : "div" , id : "wizard_skins" ,className :"mart10 skins"},
	{tag : "div" , className : "mart10" ,
	childs :[
	{tag : "div" , className : "fr mart10" ,
	childs : [
	{tag : "a" , href : "void(0)" , innerHTML : "&laquo; رجوع" , events : { onclick : "showWizardStep2()"} }
	]
	}
	,
	{tag : "div" , className : "fl" ,
	childs : [
	{tag : "a" , href : "void(0)" , events : { onclick : "showWizardStep4()"}  ,
	childs : [
	{tag : "img" , src : "static/images/btnNext.gif" , border : "0"}
	]
	}
	]
	}
	,
	{tag : "div" , className : "cls" }

	]
	}

	]
	}

	]
	}
	]
	msg = "<strong>لقد قمت بإعداد صفحتك تستطيع الآن تسمية صفحتك بما تحب</strong><br /> <br />";

	msg+='<strong>أو انقر على <span class="yel">"إضافة محتويات"</span>';
	msg+=" لإختيار المزيد  من القنوات ...</strong><br />";
	msg+='<br />';
	msg+="<strong>أو تغيير لون واجهة صفحتك بالنقر على<br /> ";
	msg+='<span class="yel">"تغيير الواجهة"</span></strong><br />';
	msg+="<br />";
	msg+="<strong>انطلق وجرب بنفسك!          </strong>";
	//Congratulations
	this.wizard_4 = [
	{tag : "div" , id : "wizard_step4" ,  className : "pop" , style : { position : "absolute" , marginTop : "70px" } , display : false ,
	childs : [
	{tag : "div" , className : "arrow" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png"   }
	]
	}
	,
	{tag : "div" , className : "arrow2" ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrow.png"   }
	]
	}
	,
	{tag : "div" , className : "arrow3" , style : { marginTop : "20px" } ,
	childs : [
	{tag : "img" , src : "static/images/wizardArrowRight.png"   }
	]
	}
	,
	{tag : "div" , className : "close" ,
	childs : [
	{tag : "img" , src : "static/images/close_tools.gif"   ,  events : { onclick : "closeWizard()"}   }
	]
	}
	,
	{tag : "div" , className : "popIn" ,
	childs : [
	{tag : "div" ,
	childs :[
	{tag : "img" , src : "static/images/congratulations.gif" }
	]
	}
	,
	{tag : "div" , className : "mart10 wit" , innerHTML : msg 	}
	]
	}

	]
	}
	];




	this.essential_widgets_pages = {name : "essential" , css_className : "b1" , title : loc.text("essential_widgets") , count : 0 , current : null , pages :new  Array()};
	this.portal_widgets_pages = {name : "portal" , css_className : "b2" , title : loc.text("portal_widgets") , count : 0 , current : null , pages :new  Array()};
	this.news_widgets_pages = {name : "news" , css_className : "b3" , title : loc.text("news_widgets") , count : 0 , current : null , pages :new  Array()};
	this.current_widget_menu = null;
	this.current_page = 0;




	this.menuItemId = 0;

	this.getMenuItemId = function(id) {
		var res = "menu_item_";
		if(id) {
			res = res + id;
		} else {
			this.menuItemId ++;
			res = res + this.menuItemId;
		}
		return res;
	}
	this.updatePageNum= function(){
		this.elements['page_num'].innerHTML = (this.current_page)  + "/" + this.current_widget_menu.count;

	}
	this.nextPage = function(){
		if(menu.current_widget_menu.count >1){
			if(menu.current_page  == menu.current_widget_menu.count){
				var next_page  = 1;
			}else{
				var next_page  =menu.current_page  + 1;
			}

			for(i=1;i<menu.current_widget_menu.pages.length;i++){
				jQuery(menu.current_widget_menu.pages[i]).hide();

			}

			jQuery(menu.current_widget_menu.pages[next_page]).fadeIn("slow");

			menu.current_page  = next_page ;
			menu.updatePageNum();
		}

	}
	this.prevPage = function(){
		//	varp(menu.current_widget_menu);
		if(menu.current_widget_menu.count >1){
			if(menu.current_page  == 1){
				var prev_page  = menu.current_widget_menu.count;
			}else{
				var prev_page  =menu.current_page  - 1;
			}

			for(i=1;i<menu.current_widget_menu.pages.length;i++){
				jQuery(menu.current_widget_menu.pages[i]).hide();

			}

			jQuery(menu.current_widget_menu.pages[prev_page]).fadeIn("slow");

			menu.current_page  = prev_page ;
			menu.updatePageNum();
		}
	}
	this.initial_pager = function(type){
		this.current_page = 1;
		this.current_widget_menu  = type;
		this.elements['next_btn'].onclick = this.nextPage;
		this.elements['prev_btn'].onclick = this.prevPage;
		this.elements['menu_type_title'].innerHTML = type.title;
		this.updatePageNum();
		jQuery("div.bul li").removeClass("current");
		jQuery(this.elements[this.current_widget_menu.name+"_link"]).addClass("current");

	}


	this.check_category_length =  function(type , typeObj){

		if(typeObj.current == null || typeObj.current.childNodes.length > this.eachPageCount ){

			var page = {tag : "div" , id : type+"_widgets_"+typeObj.count };
			this.buildDomModel(this.elements[type+"_widgets"],page);
			typeObj.current = this.elements[type+"_widgets_"+typeObj.count];

			typeObj.count++
			typeObj.pages[typeObj.count] = typeObj.current;

		}

	}

	this.showWizard = function(){
		jQuery(document).pngFix();
		var pdim = getPageSize();

		this.elements.wizard.style.width ="100%";
		this.showCustomShadow();
		showEl(this.elements.wizard);
		//document.getElementsByTagName("body")[0].style.overflow = "hidden";
		this.showWizardIntro();
	}

	this.showWizardIntro = function(){
		jQuery('.pop').hide();
		jQuery('.wizActive').addClass('wizInActive');
		if(ie_nav){
			cwidth = 325;
			var pdim = getPageSize().pWidth -cwidth;


			swidth =  parseInt(this.elements.step1_tab.offsetWidth)/2;
			this.elements.wizard_intro.style.left = pdim + "px";
		}
		this.elements.wizard_intro.style.display = "block";
	}

	this.showWizardStep1 = function(){

		jQuery('.pop').hide();

		jQuery('.wizActive').addClass('wizInActive');
		this.elements.step1_tab.className = "wizActive" ;
		sleft = getLeft(this.elements.step1_tab );
		cwidth = this.elements.wizard_intro.offsetWidth;

		swidth =  parseInt(this.elements.step1_tab.offsetWidth)/2;
		this.elements.wizard_step1.style.left = sleft - 180 + "px";
		this.elements.wizard_step1.style.display = "block";
	}

	this.showWizardStep2 = function(){
		jQuery('.pop').hide();
		jQuery('.wizActive').addClass('wizInActive');
		this.elements.step2_tab.className = "wizActive" ;
		sleft = getLeft(this.elements.step2_tab );
		cwidth = this.elements.wizard_intro.offsetWidth;

		swidth =  parseInt(this.elements.step2_tab.offsetWidth)/2;
		this.elements.wizard_step2.style.left = sleft - 180 + "px";
		this.elements.wizard_step2.style.display = "block";
	}

	this.showWizardStep3 = function(){
		if(this.themes_table == null){
			this.buildThemes();
			this.buildSkins();
		}
		jQuery('.pop').hide();
		jQuery('.wizActive').addClass('wizInActive');
		this.elements.step3_tab.className = "wizActive" ;
		sleft = getLeft(this.elements.step3_tab );
		cwidth = this.elements.wizard_intro.offsetWidth;

		swidth =  parseInt(this.elements.step3_tab.offsetWidth)/2;
		this.elements.wizard_step3.style.left = sleft - 180 + "px";
		this.elements.wizard_step3.style.display = "block";
	}

	this.showWizardStep4 = function(){
		this.applyWizardUserSelection();
		jQuery('.pop').hide();
		jQuery('.wizActive').addClass('wizInActive');


		stop = getTop(desktop.elements._skin_btn)-2;
		sleft = getLeft(desktop.elements._skin_btn);

		swidth =  parseInt(this.elements.step3_tab.offsetWidth)/2;
		this.elements.wizard_step4.style.left = sleft - 70 + "px";
		this.elements.wizard_step4.style.marginTop = stop+30 + "px";
		this.elements.wizard_step4.style.display = "block";

		setTimeout("closeWizadIM()" , 6000);
	}




	applyTheme = function(co){
		settings.setTheme(co)
	};
	this.applyWizardUserSelection =  function(){
		var theme = jQuery("input.themse_radio_:checked");
		if(theme.length >0){
			setTimeout("applyTheme('"+theme[0].value+"')" , 500);
		}
		var selected_widgets = jQuery("input.wizard_widgets_checkbox:checked");
		for(i=0;i<selected_widgets.length;i++){
			wname = selected_widgets[i].value
			this.widget = kernel.runWidget(wname, this.elements["wizard_preview"], false, {}, { isPreview: true});
			this.addToDesktop(true);
		}

	}


	closeWizadIM = function(){
		menu.closeWizard();
	}

	this.closeWizard = function(){
		//	document.getElementsByTagName("body")[0].style.overflow = "auto";
		jQuery('.pop').fadeOut("slow");
		jQuery('.wizActive').addClass('wizInActive');
		hideEl(this.elements.wizard);

		this.hideCustomShadow();
	}



	this.showTab =  function(tab_id){
		this.hideWizardTabs();
		showEl(this.elements[tab_id]);
	}

	this.hideWizardTabs = function(){
		hideEl(this.elements.wizard_widgets_essential);
		hideEl(this.elements.wizard_widgets_portal);
	}

	this.hideWidgetsPanels = function (){
		this.elements['news_widgets'].style.display  = "none";
		this.elements['essential_widgets'].style.display  = "none";
		this.elements['portal_widgets'].style.display  = "none";
	}
	this.showEssentialWidgetsPanel =function (){
		this.hideWidgetsPanels();
		this.elements['essential_widgets'].style.display  = "block";
		this.initial_pager(this.essential_widgets_pages );
	}

	this.showPortalWidgetsPanel =function (){
		this.hideWidgetsPanels();
		this.elements['portal_widgets'].style.display  = "block";
		this.initial_pager(this.portal_widgets_pages );
	}

	this.showNewsWidgetsPanel =function (){
		this.hideWidgetsPanels();
		this.elements['news_widgets'].style.display  = "block";
		this.initial_pager(this.news_widgets_pages );
	}


	this.onBuildInterface = function() {
		this.elements.window.className = "t_a";
		this.elements.window_title.style.display = "none";
		this.elements.content.className = 'widget_con';

		this.buildDomModel(this.elements.content, this.tools_containter);
		//this.buildDomModel(this.elements.menu_slider  , this.menuSlider);

		this.buildDomModel(document.body, this.domModelAdditional);
		this.buildDomModel(this.elements.menu_widgets  , [{tag : "div"  , id : "essential_widgets"}]);
		this.buildDomModel(this.elements.menu_widgets  , [{tag : "div"  , id : "portal_widgets" , display:false}]);
		this.buildDomModel(this.elements.menu_widgets  , [{tag : "div"  , id : "news_widgets" , display:false}]);




		this.buildDomModel(desktop.elements.wizardBtn ,   createButtonDom("<b>" + loc.text("mypagesteps") + "</b>", "showWizard()"));



		this.buildDomModel(document.body,    this.wizard);
		this.buildDomModel(this.elements.wizard,    this.wizard_0);
		this.buildDomModel(this.elements.wizard,    this.wizard_1);
		this.buildDomModel(this.elements.wizard,    this.wizard_2);
		this.buildDomModel(this.elements.wizard,    this.wizard_3);
		this.buildDomModel(this.elements.wizard,    this.wizard_4);



		this.setTitle(this.cfg.title);
		for(var w=0; w<menuWidgets.length; w++) {
			if(menuWidgets[w] == "-") {
				//	this.buildDomModel(this.elements["content"], { tag: "div", className: "menu_hr"});
			} else {
				var mid = this.getMenuItemId();
				var wname = menuWidgets[w].className.toLowerCase();

				this.buildDomModel(document.body,
				{ tag: "div", className: "hint", id: "hint_"+wname, display: false,
				style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
				innerHTML: loc.text(wname + "_hint").replace(/\n/g, "<br>") } );

				var m = { tag: "div", id : mid, className : "widget" ,
				events:{
					onclick : "openWidget('" + menuWidgets[w].className + "', '"+mid+"')"  ,
					onmouseover: "showHint(event , '" + wname + "', '"+mid+"')",
					onmouseout: "hideHint(event  , '" + wname + "' , '"+mid+"')" ,
					onmousemove: "showHint(event , '" + wname + "', '"+mid+"')"
				} ,
				childs :[
				{ tag : "div"  ,   childs : [ { tag : "img"  , src : "widgets/" + wname + "/big_ico.gif" }] } ,
				{ tag : "div"  ,  html : loc.text(wname + "_title") }
				]
				};
				this.check_category_length("essential" , this.essential_widgets_pages);
				this.buildDomModel(this.essential_widgets_pages.current, m);
			}
		}


		var swidgest = new Array(
		{name : "M3comMail"  , selected : true} ,
		{name : "Clipat"  , selected : true},
		{name : "Album"  }  ,
		{name : "M3comask" }  ,
		{name : "Ashabm3com" , selected : true}  ,
		{name : "Sport" });
		var ewidgest = new Array(
		{name : "Flickr"  , selected : true} ,
		{name : "Facebook" , selected : true} ,
		{name : "Gmail" } ,
		{name : "YoutubeVideo"  , selected : true} ,
		{name : "ToDoList" } ,
		{name : "Weather"  , selected : true}  );

		request.send({ act: "get_html_widgets" }, this);



		for(var w=0; w<portalWidgets.length; w++) {

			var mid = this.getMenuItemId();
			var wname = portalWidgets[w].className.toLowerCase();
			this.buildDomModel(document.body,
			{ tag: "div", className: "hint", id: "hint_"+wname, display: false,
			style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
			innerHTML: loc.text(wname + "_hint").replace(/\n/g, "<br>") } );

			var m = { tag: "div", id : mid, className : "widget" ,
			events:{
				onclick : "openWidget('" + portalWidgets[w].className + "', '"+mid+"')"
				,
				onmouseover: "showHint(event , '" + wname + "', '"+mid+"')",
				onmouseout: "hideHint(event  , '" + wname + "' , '"+mid+"')" ,
				onmousemove: "showHint(event , '" + wname + "', '"+mid+"')"
			} ,
			childs :[
			{ tag : "div"  , childs : [ { tag : "img"  , src : "widgets/" + wname + "/big_ico.gif" }] } ,
			{ tag : "div"  , html :  loc.text(wname + "_title")  }
			]
			};

			this.check_category_length("portal" , this.portal_widgets_pages);
			this.buildDomModel(this.portal_widgets_pages.current, m);



		}



		for(var w=0; w<newsWidgets.length; w++) {
			if(newsWidgets[w] == "-") {

			} else {
				var mid = this.getMenuItemId();
				var wname = newsWidgets[w].className.toLowerCase();

				this.buildDomModel(document.body,
				{ tag: "div", className: "hint", id: "hint_"+wname, display: false,
				style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
				innerHTML: loc.text(wname + "_hint").replace(/\n/g, "<br>") } );

				var m = { tag: "div", id : mid, className : "widget" ,
				events:{
					onclick : "openWidget('" + newsWidgets[w].className + "', '"+mid+"')"
					,
					onmouseover: "showHint(event , '" + wname + "', '"+mid+"')",
					onmouseout: "hideHint(event  , '" + wname + "' , '"+mid+"')",
					onmousemove: "showHint(event , '" + wname + "', '"+mid+"')"
				},
				childs :[
				{ tag : "div"  , childs : [ { tag : "img"  , src : "widgets/" + wname + "/big_ico.gif" }] } ,
				{ tag : "div"  , html : loc.text(wname + "_title") }
				]
				};
				this.check_category_length("news" , this.news_widgets_pages);
				this.buildDomModel(this.news_widgets_pages.current, m);


			}
		}

		this.showPortalWidgetsPanel();

		var selected_widgets_table = [
		{tag : "table"  , id: "selected_widgets_table"  ,
		style :{ width : "100%" , direction : "rtl"}}
		]
		this.buildDomModel(this.elements.portal_wizard_widgets, selected_widgets_table);

		for(i=0;i<swidgest.length;i++){


			if(i%3 == 0){
				var rid =   "row_"+i ;
				row = [{tag : "tr" , id :rid  }];

				this.buildDomModel(this.elements.selected_widgets_table_tbody, row);
			}

			var wname = swidgest[i].name.toLowerCase();
			if(swidgest[i].selected){
				input_radio = {tag : "input" , type : "checkbox" , value : swidgest[i].name , className : "wizard_widgets_checkbox radioselected"};
			}else{
				input_radio = {tag : "input" , type : "checkbox" , value : swidgest[i].name , className : "wizard_widgets_checkbox"};

			}
			var m_wizard1 =
			[
			{tag : "td" , childs : [
			{tag : "div" , className : "picM3com" ,
			childs : [
			{tag : "div" ,
			childs : [
			{tag : "img" , src : "widgets/"+wname+"/big_ico.gif"}
			]
			}
			,
			{tag : "div"  , style : { whiteSpace : "nowrap" }  , innerHTML : ( wname == "sport" ?  loc.text(wname + "_small_title") : loc.text(wname + "_title") )}
			,
			{tag : "div" ,
			childs :[		input_radio			]
			}
			]
			}
			]
			}
			];
			this.buildDomModel(this.elements[rid], m_wizard1);
		}


		var eselected_widgets_table = [
		{tag : "table"  , id: "eselected_widgets_table"
		,
		style :{width : "100%" , direction : "rtl"}}
		]
		this.buildDomModel(this.elements.essential_wizard_widgets, eselected_widgets_table);


		for(i=0;i<ewidgest.length;i++){


			if(i%3 == 0){
				var rid =   "row_"+i ;
				row = [{tag : "tr" , id :rid  }];

				this.buildDomModel(this.elements.eselected_widgets_table_tbody, row);
			}
			if(ewidgest[i].selected){

				input_radio = {tag : "input" , type : "checkbox", value : ewidgest[i].name , className : "wizard_widgets_checkbox radioselected"};
			}else{
				input_radio = {tag : "input" , type : "checkbox", value : ewidgest[i].name , className : "wizard_widgets_checkbox"};

			}
			var wname = ewidgest[i].name.toLowerCase();
			var m_wizard1 =
			[
			{tag : "td" , childs : [
			{tag : "div" , className : "picM3com" ,
			childs : [
			{tag : "div" ,
			childs : [
			{tag : "img" , src : "widgets/"+wname+"/big_ico.gif"}
			]
			}
			,
			{tag : "div", style : { whiteSpace : "nowrap" }  , innerHTML :  loc.text(wname + "_title") }
			,
			{tag : "div",
			childs :[	input_radio			]
			}
			]
			}
			]
			}
			];
			this.buildDomModel(this.elements[rid], m_wizard1);

		}

		jQuery("input.radioselected").attr("checked" , true);
	}


	this.themes_table = null;
	this.buildThemes =function(){
		this.themes_table = [
		{tag : "form" , childs : [
		{tag : "table"  , id: "wizard_themes_table"
		,
		style :{ width : "100%" ,direction : "rtl"}}
		]
		}
		];
		this.buildDomModel(this.elements.wizard_themes, this.themes_table);
		themes_list = settings.getSkinsList();



		for(i=0;i<themes_list.length;i++){


			if(i%3 == 0){
				var rid =   "row_"+i ;
				row = [{tag : "tr" , id :rid  }];

				this.buildDomModel(this.elements.wizard_themes_table_tbody, row);
			}


			var m_wizard1 =
			[
			{tag : "td" , align : "center"  ,
			childs : [
			{tag :"div" , id :"theme_"+themes_list[i].name  ,style : { cursor : "pointer" }   ,  className : themes_list[i].name ,
			events : {onmouseover : "wizard_theme_mouseOvr('theme_"+themes_list[i].name+"')" ,onmouseout : "wizard_theme_mouseOt('theme_"+themes_list[i].name+"')" , onclick : "wizard_select_theme('"+themes_list[i].name+"')"}
			} ,
			{tag : "input" , name :"wizard_selected_theme", id :"wizard_theme_radio_"+themes_list[i].name   , type : "radio" , className : "themse_radio_" , value : themes_list[i].name}
			]
			}
			];
			this.buildDomModel(this.elements[rid], m_wizard1);

		}
	}

	this.buildSkins =function(){
		this.skins_table =
		[
		{tag : "form" ,
		childs :
		[
		{tag : "table", id: "wizard_skins_table", style :{ width : "100%" ,direction : "rtl"} }
		]
		}
		];

		this.buildDomModel(this.elements.wizard_skins, this.skins_table);
		var skins_list = new Array();
		skins_list[0] = 't2';
		skins_list[1] = 't3';
		skins_list[2] = 't9';
		skins_list[3] = 't10';

		for(i=0;i<skins_list.length;i++){
			if (i%2 == 0) {
				var rid = "row_"+i;
				row = [{tag : "tr", id :rid  }];
				this.buildDomModel(this.elements.wizard_skins_table_tbody, row);
			}

			var m_wizard1 =
			[{tag : "td", align : "center",
			childs :
			[
			{tag: "div", id : "theme_" + skins_list[i], style: { cursor: "pointer", border: "#fff solid 1px"}, className: skins_list[i],
			events: {onmouseover: "wizard_theme_mouseOvr('theme_" + skins_list[i] + "')", onmouseout: "wizard_theme_mouseOt('theme_" + skins_list[i] + "')", onclick: "wizard_select_theme('" + skins_list[i] + "')"}
			},
			{ tag: "input", name: "wizard_selected_theme", id: "wizard_theme_radio_" + skins_list[i], type: "radio", className: "themse_radio_", value: skins_list[i] }
			]
			}];
			this.buildDomModel(this.elements[rid], m_wizard1);
		}
	}


	this.wizardSetTheme = function(name){
		settings.setTheme(name);
	}

	this.wizard_theme_mouseOvr = function ( id ) {
		this.elements[id].style.borderColor = '#999';
	}

	this.wizard_theme_mouseOt = function ( id ) {
		this.elements[id].style.borderColor = '#fff';
	}
	this.wizard_select_theme = function (cname){
		var radio_elem = jQuery(".themse_radio_");
		for(i=0;i<radio_elem.length;i++){
			radio_elem[i].checked = false;
		}
		this.elements["wizard_theme_radio_"+cname].checked = true;
	}
	// open/close sub menus
	this.switchPanel = function(name) {
		with (this.elements[name].style) {
			display = (display == 'none' ? 'block' : 'none');
		}
	}

	this.hover_widget = function(obj , t){
		//		if(t == 0){
		//			jQuery(obj).animate(
		//			{opacity : 1.0 }
		//			,
		//			500
		//			);
		//		}else{
		//			jQuery(obj).animate(
		//			{opacity : 0.6 }
		//			,
		//			500
		//			);
		//
		//		}
	}
	this.show = function() {
		if(!desktop.isMenuShow) {
			showEl(this.elements.window);
			settings.hide();
			//            desktop.elements.pager.style.marginLeft = this.elements.window.offsetWidth + 2 + "px";
			//            desktop.elements.pager.style.width = "auto";
			desktop.isMenuShow = true;
		}
	}


	this.hide = function() {
		if(desktop.isMenuShow) {
			hideEl(this.elements.window);
			//            desktop.elements.pager.style.marginLeft = 0;
			desktop.isMenuShow = false;
		}
	}

	this.close = function() {
		//        hideEl(desktop.elements.menu);
		this.hideItemMenu();
		this.closePreview();
		this.closeAddFeedPanel();
		this.hide();
	}



	//---------------------------------------------
	// PREVIEW
	//---------------------------------------------
	//dimk
	this.openWidget = function(widgetClass, mid, params) {
		if(!this.addingToDekstopInProgress){
			this.hideItemMenu();
			this.hideHint();
			this.closePreview();
			showEl(this.elements.preview);

			var pos = {left: getLeft(this.elements.menu_widgets) + parseInt(this.elements.menu_widgets.style.width , 10 )/3,
			top:  getTop(this.elements.menu_widgets) + 30};
			setElPos(this.elements.preview, pos);
			this.widget = kernel.runWidget(widgetClass, this.elements["preview_panel"], false, params, { isPreview: true});
			this.oldDisableOnClosePrompt = this.widget.disableOnClosePrompt;
			this.widget.disableOnClosePrompt = true;

			pos.top = pos.top - Math.round(this.elements.preview.offsetHeight / 2);
			setElPos(this.elements.preview, pos);
		}
	}

	this.closePreview = function(mtype) {
		if(this.widget) {
			this.widget.close();
		}
		this.widget = null;

		hideEl(this.elements.preview);
		this.elements.preview_panel.innerHTML = '';

	}

	this.customClosePreview = function (widget ,wparent  , oldDisableOnClosePrompt ,  call_back){
		preview =this.elements.preview;
		preview_panel = this.elements.preview_panel;
		jQuery(preview).animate(
		{
			top : getTop(wparent) ,
			left : getLeft(wparent) ,
			opacity : 0.2
		},1000 , function() { call_back(widget , wparent , oldDisableOnClosePrompt ) ;preview.style.display = "none" ;jQuery(preview).css("opacity" , 1); preview_panel.innerHTML="";  }
		);


	}
	this.addingToDekstopInProgress = false;
	this.addToDesktop = function(without_animation) {
		this.addingToDekstopInProgress = true;
		var w = this.widget;
		if(w){
			if(without_animation){
				w.setParent(desktop.getTinyPanel());
				w.isPreview = false;
				w.initDtagAndDrop();
				w.disableOnClosePrompt = this.oldDisableOnClosePrompt;
				w.save();
				w.elements.settings.style.display = "none";
				this.widget = null;
				this.closePreview();
				desktop.savePanels();
				this.addingToDekstopInProgress = false;
			}else{
				oldDisableOnClosePrompt = this.oldDisableOnClosePrompt;
				this.widget = null;
				parent_panel = desktop.getTinyPanel();
				this.customClosePreview(w , parent_panel , oldDisableOnClosePrompt,  function (w , pp , oldDisableOnClosePrompt){
					w.setParent(pp);
					w.isPreview = false;
					w.initDtagAndDrop();
					w.disableOnClosePrompt = oldDisableOnClosePrompt;
					w.save();
					desktop.savePanels();
					w.elements.settings.style.display = "none";
					menu.addingToDekstopInProgress = false;
				});
			}
		}

	}





	//---------------------------------------------
	// HINTS
	//---------------------------------------------
	this.currentHint = null;
	var hint_timer = null;
	var current_hint_obj = null;
	this.showHint = function(e , wname, mid) {
		if(!this.widget) {

			var mpos = getMousePos(e);

			if(isPosInObj(mpos , this.elements[mid])){

				this.hideHint();
				var pos = {left: mpos.left - 100,
				top:  mpos.top+20};
				setElPos(this.elements["hint_"+wname], pos);
				jQuery(this.elements["hint_"+wname]).show();
				current_hint_obj =  this.elements[mid];
				this.currentHint = wname;
				this.hideItemMenu();
				//	hint_timer = setTimeout("tohideHints()" , 3000);
			}
		}
	}

	tohideHints = function(){

		menu.hideHint();
		clearTimeout(hint_timer);
	}


	this.hideHint = function(e , wname  , mid) {


		if(e && wname && mid){
			var mpos = getMousePos(e);

			if(!isPosInObj(mpos , this.elements[mid])){

				if(wname) {
					jQuery(this.elements["hint_"+wname]).hide();
				} else if (this.currentHint) {
					jQuery(this.elements["hint_"+this.currentHint]).hide();
				}
			}
		}else{
			jQuery(".hint").hide();

		}

	}


	//---------------------------------------------
	// ADD CHANNELS
	//---------------------------------------------
	this.setAddFeedStatus = function(html) {

		if(html) {

			showEl(this.elements.addFeedStatus);

			this.elements.addFeedStatus.innerHTML = html;
		} else {
			clearEl(this.elements.addFeedStatus);
			hideEl(this.elements.addFeedStatus);
		}
	}

	this.addFeedPanelVisible = false;

	this.showAddFeedPanel = function() {
		this.hideItemMenu();
		if(!this.addFeedPanelVisible) {
			this.setAddFeedStatus(null);
			showEl(this.elements.addFeedPanel);
			showEl(this.elements.addFeedButton);
			var pos = {left:getLeft(this.elements.menu_widgets)+parseInt(this.elements.menu_widgets.style.width , 10)/2 + parseInt(this.elements.addFeedPanel.style.width , 10)/2,
			top:  getTop(this.elements.addFeedMenuItem)};

			setElPos(this.elements.addFeedPanel, pos);
			this.elements.selectFeedUrl.focus();
			this.addFeedPanelVisible = true;
		}
	}


	this.closeAddFeedPanel = function() {
		if(this.addFeedPanelVisible) {
			hideEl(this.elements.addFeedPanel);
			this.addFeedPanelVisible = false;
		}
	}


	this.addFeed = function() {
		var url = trim(this.elements.selectFeedUrl.value);
		if(url!="") {
			hideEl(this.elements.addFeedButton);

			this.setAddFeedStatus("<b>"+loc.text("menu_msg_cc")+"</b>");
			if(url.indexOf("http://") == -1) {
				url = "http://"+url;
			}
			this.newFeedUrl = url;
			xmlRequest.send(url, this, "addFeedDispatch");


		}
	}


	this.registerFeed = function(title, url) {
		var cn = this.catalog[CCIDS+1].items.length;
		this.profile.catalog[cn] = {title: title, url: url};
		var newItem = {id: CCIDS+cn+2, title: title.substr(0,25), url: url, icon: ''};
		this.catalog[CCIDS+1].items[cn] = newItem;

		this.renderCategory(CCIDS+1, true);

		this.save();
	}

	this.addFeedDispatch = function(response) {
		if(response.responseXML.documentElement) {
			var channel = XMLParser.xml2hash(response.responseXML.documentElement);
			if (channel.siteUrl != undefined ) {
				if (channel) {
					this.setAddFeedStatus("<b>"+loc.text("menu_msg_added", channel.title)+"</b>");
					this.elements.selectFeedUrl.value = '';
					//        this.profile.catalog[cn] = {title: channel.title, url: this.newFeedUrl};
					//	this.registerFeed(channel.title, this.newFeedUrl);

					showEl(this.elements.addFeedButton);

					var w = kernel.runWidget("Rss", desktop.getTinyPanel(), false, {url: this.newFeedUrl});
					w.save();
					desktop.savePanels();
					//`this.closeAddFeedPanel();
					return;
				}
			}
		}
		this.setAddFeedStatus("<b>"+loc.text("menu_msg_no_responce")+ "</b>");
		showEl(this.elements.addFeedButton);
	}



	//---------------------------------------------
	// ITEM MENU
	//---------------------------------------------
	this.activeItemId = null;
	this.showItemControl = function(id) {
		this.hideItemControl();
		showEl(this.elements["item_control"+id]);
		this.activeItemId = id;
	}

	this.hideItemControl = function() {
		if(this.activeItemId != null) {
			hideEl(this.elements["item_control"+this.activeItemId]);
		}
	}

	this.showItemMenu = function(mid) {
		if(!this.widget && !this.addFeedPanelVisible) {
			hideEl(this.elements.item_menu_rename);
			hideEl(this.elements.item_menu_delete);
			showEl(this.elements.item_menu_actions);
			showEl(this.elements.item_menu);

			var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 2,
			top:  getTop(this.elements[mid]) - 10};
			setElPos(this.elements.item_menu, pos);
		}
	}

	this.hideItemMenu = function() {
		hideEl(this.elements.item_menu);
	}

	this.showRenameItemSection = function() {
		var n = this.getItemNum(this.activeItemId);
		this.elements.new_item_title.value = this.profile.catalog[n].title;

		hideEl(this.elements.item_menu_actions);
		showEl(this.elements.item_menu_rename);
	}

	this.showDeleteItemSection = function() {
		hideEl(this.elements.item_menu_actions);
		showEl(this.elements.item_menu_delete);
	}

	this.getItemNum = function(itemId) {
		for(var i=0; i<this.catalog[CCIDS+1].items.length; i++) {
			if(this.catalog[CCIDS+1].items[i] != -1 && this.catalog[CCIDS+1].items[i].id == itemId) {
				return i;
			}
		}
	}

	this.renameItem = function() {
		var title = trim(this.elements.new_item_title.value);
		if(title != "") {
			var n = this.getItemNum(this.activeItemId);
			this.profile.catalog[n].title = title;
			this.catalog[CCIDS+1].items[n].title = title;
			this.elements["cat_item_title"+this.activeItemId].innerHTML = title;
			this.save();
			this.hideItemMenu();
		}
	}

	this.deleteItem = function() {
		var n = this.getItemNum(this.activeItemId);
		this.profile.catalog[n] = -1;
		this.catalog[CCIDS+1].items[n] = -1;
		this.elements["cat_item"+this.activeItemId].parentNode.removeChild(this.elements["cat_item"+this.activeItemId]);
		this.elements["cat_item"+this.activeItemId] = null;
		this.save();
		this.hideItemMenu();
	}




	this.showCustomShadow = function(opacity){
		if(!opacity){
			opacity = 20;
		}
		this.custom_shadowbox  = new ShadowBox(" ", {boxWidth:"400px" , transHoldTime:500 , maxOpacity: opacity});
		this.custom_shadowbox.show();
	}
	this.hideCustomShadow = function(){
		this.custom_shadowbox.hide();
	}







	//---------------------------------------------
	// CATALOGS
	//---------------------------------------------
	this.switchCategory = function(catId) {

		this.hideItemMenu();
		var el = this.elements["cat_content"+catId];

		if(el.style.display == 'none') {
			if(this.catalog[catId]) {
				if(this.catalog[catId].rendered) {
					this.showCatItemsPanel();
					showEl(el);

				} else {
					this.renderCategory(catId);
				}
			} else {

				if(catId < CCIDS) {
					var txt = document.createTextNode(loc.text("msg_loading"))
					el.appendChild(txt);
					showEl(el);
					request.send({act: "get_category", cat_id: catId}, this);
				}
			}
			if(catId != "0") {
				this.elements["fico_" + catId].setAttribute("src", this.folder_o.src);
				this.cuurent_opened_cat = el;
			}

		} else {
			if(catId != "0") {
				this.elements["fico_" + catId].setAttribute("src", this.folder_s.src);
			}
			hideEl(el);
		}
	}


	this.tmpIcons = {};
	this.renderCategory = function(catId, silent) {

		el = this.elements["cat_content"+catId];
		el.innerHTML = '';



		with(this.catalog[catId]) {

			if(categories) {
				for(var i=0; i<categories.length; i++) {

					this.buildDomModel(el,
					{ tag: "li", className: "sel", id: "cat"+categories[i].id,
					childs: [
					createButtonDom(categories[i].name,
					"switchCategory("+categories[i].id+")",
					this.folder_s.src,
					false,
					"fico_" + categories[i].id
					),
					{ tag: "li", id: "cat_content"+categories[i].id, className: "menu_sub_panel", display: false }
					]
					});

				}
			}

			if(items) {
				this.showCatItemsPanel();
				var m = null;
				this.elements['feeds_widgets'].innerHTML= "";

				for(var i=0; i<items.length; i++) {

					if(items[i] == -1) {
						continue;
					}
					var ico_id = "item_icon_"+items[i].id;

					//					m = { tag: "div", id: "cat_item"+items[i].id,
					//					childs: []}


					m = [{ tag: "div", id: "cat_item"+items[i].id, className : "widget"  ,
					events:{onclick :"openWidget('Rss', 'cat_item"+items[i].id+"', {url: '"+items[i].url + "'" + (items[i].icon ? ", icon: '"+items[i].icon+"'" : "") + "})"},
					childs :[
					{ tag : "div"  , childs : [ { id: ico_id, tag : "img"  , src :	"widgets/menu/img/item.gif" }] } ,

					{ tag : "div" , html : items[i].title , id :"cat_item_title"+items[i].id}
					]
					}
					];




					var cells = [
					{content: createButtonDom(items[i].title,
					"openWidget('Rss', 'cat_item"+items[i].id+"', {url: '"+items[i].url + "'" + (items[i].icon ? ", icon: '"+items[i].icon+"'" : "") + "})",
					"widgets/menu/img/item.gif",
					"cat_item_title"+items[i].id,
					ico_id),
					width: "99%"}];


					//					if(items[i].id > CCIDS) {
					//						m.events = {onmouseover: "showItemControl('"+items[i].id+"')", onmouseout: "hideItemControl()"};
					//						cells.push({content:
					//						{ tag: "img", src: "static/client/right_arrow.gif",
					//						id: "item_control"+items[i].id,
					//						style: {verticalAlign: "middle", cursor: "pointer"},
					//						display: false,
					//						events: {onmouseover: "showItemMenu('cat_item"+items[i].id+"')"}
					//						},
					//						width: "99%"});
					//					}

					//	m.childs.push(createTableDom(cells));



					this.buildDomModel(this.elements['feeds_widgets'], m);


					//alert(Dump(items[i]));

					//alert(items[i].url);
					var icons = [
					items[i].icon,
					getDomain(items[i].url) + "/favicon.ico",
					getDir(items[i].url) + "/favicon.ico"
					];

					//
					//					with(this.elements[ico_id].style) {
					//						width = "16px";
					//						heigth = "16px";
					//					}
					//alert(Dump(ico_id));
					loadIcon(this.elements[ico_id], icons);

				}


			}



			if(!items  &&  !categories) {
				el.innerHTML = loc.text("msg_empty");
			}

			rendered = true;
		}

		if(!silent) {
			el.style.display = 'block';
		}
		this.catalog[catId].rendered = true;


	}


	//---------------------------------------------
	// Recent UWA widgets
	//---------------------------------------------

	this.rwFolderVisible = false;

	this.switchRWFolder = function() {
		this.hideItemMenu();
		this.rwFolderVisible = !this.rwFolderVisible;
		if(this.rwFolderVisible) {
			this.showElement("recentw_list");
			this.elements["recentw_folder_icon"].setAttribute("src", this.folder_o.src);
		} else {
			this.hideElement("recentw_list");
			this.elements["recentw_folder_icon"].setAttribute("src", this.folder_s.src);
		}
	}



	this.renderRecentWidgets = function() {
		var l = desktop.getRecentWidgetsList();
		if(l.length) {
			this.elements["recentw_list"].innerHTML = "";
			for(var i=0; i<l.length; i++) {
				var mid = "rw" + i;
				var m = { tag: "div", className: "menu_panel",
				id: "menu_item_" + mid,
				childs: [
				createButtonDom(l[i].title,
				"openWidget('UWAWidget', '" + mid + "', {url: '" + l[i].url + "'})",
				l[i].icon, mid)
				]
				}
				this.buildDomModel(this.elements["recentw_list"], m);
			}
		} else {
			this.elements["recentw_list"].innerHTML = loc.text("msg_empty");
		}
	}


	this.openRecentWidget = function(idx) {
		var l = desktop.getRecentWidgetsList();
		var w = kernel.runWidget("UWAWidget", desktop.getTinyPanel(), false, {url: l[idx].url});
		w.save();
		desktop.savePanels();
	}


	//---------------------------------------------
	// HTML WIDGETS
	//---------------------------------------------
	this.renderHTMLWidgetsList = function(data) {
		if(data) {
			//	this.elements["html_widgets"].innerHTML = "";

			for(var i=0; i<data.length; i++) {
				var mid = this.getMenuItemId();
				this.buildDomModel(document.body,
				{ tag: "div", className: "hint", id: "hint_htmlwidget_"+data[i].id, display: false,
				style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
				innerHTML: loc.text("html_widget_"+data[i].id+ "_hint").replace(/\n/g, "<br>") } );

				var m = { tag: "div", id : mid,className : "widget" ,
				events:{onclick :"openHTMLWidget('" + data[i].id + "', '"+mid+"')",

				onmouseover: "showHint(event , 'htmlwidget_"+data[i].id + "', '"+mid+"')",
				onmouseout: "hideHint(event  ,'htmlwidget_"+data[i].id + "', '"+mid+"')" ,
				onmousemove: "showHint(event , 'htmlwidget_"+data[i].id + "', '"+mid+"')"
				},
				childs :[
				{ tag : "div"  , childs : [ { tag : "img"  , src : "var/hwicons/" + data[i].icon }] } ,
				{ tag : "div"  , html :data[i].title}
				]
				};

				if(this.essential_widgets_pages.current == null || this.essential_widgets_pages.current.childNodes.length > this.eachPageCount ){
					var page = {tag : "div" , id : "essential_widgets_"+this.essential_widgets_pages.count };
					this.buildDomModel(this.elements["essential_widgets"],page);
					this.essential_widgets_pages.current = this.elements["essential_widgets_"+this.essential_widgets_pages.count];

					this.essential_widgets_pages.count++;

					this.essential_widgets_pages.pages[this.essential_widgets_pages.count] = this.essential_widgets_pages.current;

				}

				this.buildDomModel(this.essential_widgets_pages.current, m);
				//				this.initial_pager(this.essential_widgets_pages);
			}
		}
	}



	this.openHTMLWidget = function(hwId, mid) {
		//    this.openWidget = function(widgetClass, mid, params) {
		this.openWidget("HTMLWidget", mid, { id: hwId });
	}



	//---------------------------------------------
	// DISPATCHER
	//---------------------------------------------
	this.dispatchMsg = function(msg) {
		switch (msg.status) {

			case "category_data":
			this.catalog[msg.cat_id] = { categories: msg.categories, items: msg.items};
			this.renderCategory(msg.cat_id);
			break;


			case "html_widgets":
			this.renderHTMLWidgetsList(msg.data);
			break;
		}
	}

}
Menu.prototype = new Widget();

function Settings() {
	this.init();

	this.cfg = {
		hasSizeBtn: false,
		hasRefreshBtn: false,
		hasSettingsBtn: false,
		hasDrag: false,
		isOpenHidden: true,
		isSystem: true,
		title: loc.text("settings_title"),
		module: "Settings",
		uniqueId: SYS_WIDGETS_ID + 4
	}



	// Profile

	this.defaultProfile["background"] = "";

	// Menu

	this.getMenuItemModel = function(name, title) {
		var m =
		{ tag: "a", id: "mi_" + name,
		href: "showPage('" + name + "')",
		html: title }
		return m;
	}


	this.getPageModel = function(name, title) {
		var self = this;
		var m =
		{ tag: "div", id: "page_" + name,
		cn: "page",
		display: false,
		childs: [
		{ tag: "div", cn: "title",
		html: title },
		{ tag: "div", cn: "content",
		childs: self["pmodel_" + name] }
		]}
		return m;
	}


	this.activePage = false;
	this.showPage = function(name) {
		if(name == this.activePage) return;
		if(this.activePage) {
			this.hideElement("page_" + this.activePage);
			this.elements["mi_" + this.activePage].className = "";
		}
		this.showElement("page_" + name);
		this.elements["mi_" + name].className = "selected";
		this.activePage = name;
		var self = this;
		this.closeActiveColorsPoup();
		self["onShowPage_" + name]();
	}


	this.onShowPage_account = function() {
		if(auth.isLogged()) {
			this.showElement("account_controls");
			this.hideElement("account_msg");
		} else {
			this.hideElement("account_controls");
			this.showElement("account_msg");
		}
	}


	//Pager

	this.updatePageNum= function(){
		//	this.logtobrowser("Updat");
		this.elements['page_num'].innerHTML = (settings.current_page)  + "/" + settings.current_type_list.count;

	}

	this.eachPageCount = 12;
	this.current_type_list = null;
	this.current_page  = 0 ;
	this.nextPage = function(){
		if(settings.current_type_list.count >1){
			if(settings.current_page  == settings.current_type_list.count){
				var next_page  = 1;
			}else{
				var next_page  =menu.current_page  + 1;
			}

			settings.setPage(next_page);
		}

	}
	this.prevPage = function(){
		//	varp(menu.current_type_list);
		if(settings.current_type_list.count >1){
			if(settings.current_page  == 1){
				var prev_page  = settings.current_type_list.count;
			}else{
				var prev_page  =settings.current_page  - 1;
			}

			settings.setPage(prev_page);

		}
	}
	this.setPage = function(page){
		if(page >=0 && page <= settings.current_type_list.pages.length){
			for(i=1;i<settings.current_type_list.pages.length;i++){
				jQuery(settings.current_type_list.pages[i]).hide();
			}
			jQuery(settings.current_type_list.pages[page]).fadeIn("slow");
			settings.current_page  = page ;
			settings.updatePageNum();
		}
	}

	this.initial_pager = function(type){

		this.logtobrowser("Inial paging ....");
		this.current_page = 1;
		this.current_type_list  = type;
		this.elements['next_btn'].onclick = this.nextPage;
		this.elements['prev_btn'].onclick = this.prevPage;
		//this.elements['menu_type_title'].innerHTML = type.title;
		this.updatePageNum();
		settings.setPage(1);
		//	jQuery("div.bul li").removeClass("current");
		//	jQuery(this.elements[this.current_type_list.name+"_link"]).addClass("current");

	}


	this.check_category_length =  function(type , typeObj){

		this.logtobrowser("Number of allow pages :"+this.eachPageCount +"\n type:"+type+ "\n obj "+typeObj.current);

		if(typeObj.current == null || typeObj.current.childNodes.length >= this.eachPageCount ){
			this.logtobrowser("Count :"+typeObj.count);
			var page = {tag : "div" , id : type+"_list_"+typeObj.count , display:false };
			this.buildDomModel(this.elements[type+"_list"],page);
			typeObj.current = this.elements[type+"_list_"+typeObj.count];

			typeObj.count++
			typeObj.pages[typeObj.count] = typeObj.current;

		}
		//		if(typeObj.current != null ){
		//			this.logtobrowser("current legnth :"+	typeObj.current.childNodes.length);
		//		}

	}

	this.logtobrowser = function(msg){
//		if(console){
//			console.log(msg);
//		}
	}

	// Themes

	this.pmodel_themes = [
	{ tag: "div", id: "themes_list", cn: "tools" },
	{ tag: "div",  cn: "themes",
	childs:
	[
	{tag :"div" ,
	childs:
	[
	{ tag: "div",id : "skins_list" ,
	childs:
	[
	{ tag: "img", src: "static/client/picTheme.gif"}
	]
	}
	]

	}
,
	{tag : "div" , id : "menu_paging"  , className : "paging" ,
	childs :[
	{tag : "table" , width : "100%" ,
	childs :[
	{tag : "tr" ,
	childs : [
	{tag : "td"   , id : "prev_btn" ,events : { onclick : "prevPage()"} ,  className:"prev" , html : "السابق"} ,
	{tag : "td"  , id : "page_num" , className : "num" , html : ""} ,
	{tag : "td"   , id : "next_btn" ,events : { onclick : "nextPage()"} ,  className:"next", html: "التالي"}
	]
	}
	]
	}
	]
	}
	,
	{tag : "br" , className :  "cls"}

	]
	}
	];

	this.skins_pages = {name : "skin_pages"  , title : "الوجاهات"  , count : 0 , current : null , pages :new  Array()};


	this.isThemesLoaded = false;
	this.isSkinsLoaded = false;
	this.current_type_list = null;
	this.current_page = 0;
	this.onShowPage_themes = function() {
		if(!this.isThemesLoaded) {
			this.elements["themes_list"].innerHTML = loc.text("msg_loading");
			request.send({ act: "get_themes" }, this);
		}

		if(!this.isSkinsLoaded) {
			request.send({ act: "get_skins" }, this);
		}
	}

	this.mouseOvr = function ( id ) {
		this.elements[id].style.borderColor = '#999';
	}

	this.mouseOt = function ( id ) {
		this.elements[id].style.borderColor = '#fff';
	}

	this.skinsList = null;

	this.getSkinsList = function (){
		return this.skinsList ;
	}


	this.renderSkins = function(themes) {
		if (themes == null) {

		} else {


			for (i=0; i<themes.length; i++) {
				var cns = (themes[i].name == desktop.profile["theme"]) ? "skinBg current" : "skinBg";

				var skin =
				{tag: "div", id: "theme_boxs_" + themes[i].name, className: cns, events: {onclick: "setTheme('" + themes[i].name + "','t')"},
				childs:
				[
				{ tag: "div", id: "Theme_" + themes[i].name, className: themes[i].name },
				{ tag: "div", id: "title_" + themes[i].name, className: "title_" + themes[i].name, innerHTML: themes[i].description }
				]
				};
				this.check_category_length("skins" , this.skins_pages);
				this.buildDomModel(this.skins_pages.current, skin);

				//	this.buildDomModel(this.elements["skins_list"],skin);
			}
			this.buildDomModel(this.elements["skins_list"],{ tag: "div", className: "cls"});
			this.initial_pager(this.skins_pages );
		}
	}


	this.renderThemes = function(list) {
		if(list == null) {
			this.elements["themes_list"].innerHTML = "No themes found :(";
		} else {
			this.skinsList  = list;
			this.elements["themes_list"].innerHTML = "";

			var skinsHTML = [];
			var c = 0;
			for(var i=0; i< list.length; i++) {
				c++;
				var cn = (list[i].name == desktop.profile["theme"]) ? "current" : "";
				skinsHTML.push({tag: "li", id: "theme_box_" + list[i].name, events: {onclick: "setTheme('" + list[i].name + "','c')", onmouseover: "mouseOvr('theme_box_" + list[i].name + "');", onmouseout: "mouseOt('theme_box_" + list[i].name + "');"}, className: list[i].description + " " + cn, style: {cursor:"pointer"}});
				
			}
			var HTML = [{tag: "table",width: "100%", className: "skinsCon", border: "0", cellspacing: "0", cellpadding: "5",
			childs: [
			{tag: "tr",
			childs:[
			{tag: "td", innerHTML: '<img src="static/client/picColor.gif" />'},
			{tag : "td"  , className : "hand" , events : { onclick : "hide()" } ,  innerHTML : "<img src='/static/client/close_tools.gif' alt='' class='fl' />"}
			]
			},
			{tag: "tr",
			childs: [
			{tag: "td", colspan: "2",
			childs:[
			{tag: "div", className: "skins", style: {width: "900px", margin: "auto"},
			childs: [
			{tag: "ul",
			childs: skinsHTML
			},
			{tag: "div", className: "cls"}
			]
			}
			]
			}
			]
			}
			]
			}];
			this.buildDomModel(this.elements["themes_list"], HTML);

		}
	}


	this.setCurrentTheme = function(name) {
		if(this.elements["theme_box_" + name]) {
			this.elements["theme_box_" + name].className = "current";
		}
	}


	this.setTheme = function(name, type) {
		if(desktop.profile["theme"] != name) {
			if(this.elements["theme_box_" + desktop.profile["theme"]]) {
				this.elements["theme_box_" + desktop.profile["theme"]].className = desktop.profile["theme"];
			}
			if(this.elements["theme_boxs_" + desktop.profile["theme"]]) {
				this.elements["theme_boxs_" + desktop.profile["theme"]].className = 'skinBg';
			}
			if (type == 'c') {
				this.elements["theme_box_" + name].className = name + " current";
			} else if (type == 't') {

				this.elements["theme_boxs_" + name].className += " current";
			}
			desktop.profile["theme"] = name;
			desktop.applyTheme();
			desktop.save();
		}
	}



	this.activeWpTab = null;
	this.showWpTab = function(name) {
		if(name == this.activeWpTab) return;
		if(this.activeWpTab) {
			this.hideElement("tabpage_" + this.activeWpTab);
			this.elements["tab_" + this.activeWpTab].className = "tab";
		}
		this.showElement("tabpage_" + name);
		this.elements["tab_" + name].className = "tab_selected";
		this.activeWpTab = name;
	}


	this.onHeaderHeightChanging = function(h) {
		desktop.profile["header_size"] = h;
		desktop.applyHeaderSize();
	}

	this.onHeaderHeightChanged = function(h) {
		desktop.profile["header_size"] = h;
		desktop.applyHeaderSize();
		desktop.save();
	}



	this.onSelectColor = function(pos, c) {
		this.elements["inp_" + pos + "_color"].checked = true;
		this.elements["inp_" + pos + "_color_text"].value = c;
		this.elements["inp_" + pos + "_color_img"].style.background = c;
		this.setBackground(pos, c);
		this.closeActiveColorsPoup();
	}


	this.selectBackgroundColor = function(pos) {
		var c = this.elements["inp_" + pos + "_color_text"].value;
		if(trim(c) == "") {
			c = "#FFFFFF";
			this.elements["inp_" + pos + "_color_text"].value = c;
		}
		this.elements["inp_" + pos + "_color"].checked = true;
		this.elements["inp_" + pos + "_color_img"].style.background = c;
		this.setBackground(pos, c);
	}




	// images


	this.getImageUrlFromBg = function(str) {
		return str.substring(4, str.length-1);
	}


	this.activeImageSource = { top: false, bottom: false };
	//    this.isIntImagesLoaded = { top: false, bottom: false };


	this.showImagesSource = function(pos) {
		var s = this.elements["inp_image_source_" + pos].value;
		if(this.activeImageSource[pos] == s) return;
		if(this.activeImageSource[pos]) {
			this.hideElement("image_source_" + pos + this.activeImageSource[pos]);
		}
		this.showElement("image_source_" + pos + s);
		this.activeImageSource[pos] = s;
	}


	this.loadImageFromUrl = function(pos) {
		this.setWallpaper(pos, this.elements["inp_image_url_" + pos].value);
	}


	// System

	this.currentPopup = false;

	this.showColorsPopup = function(id) {
		if(this.currentPopup) {
			if(this.currentPopup == id) return;
			this.closePopup(this.currentPopup);
		}
		this.selectBackgroundColor(id);

		this.currentPopup = id;
		this.showElement(id + "_popup");

		var pe = this.elements[id + "_popup"];
		var be = this.elements["inp_" + id + "_color"];

		var pos = {
			left: getLeft(be) - 2,
			top:  getTop(be) - 4 - pe.offsetHeight
		}
		setElPos(pe, pos);
	}


	this.closeColorsPopup = function(id) {
		this.hideElement(id + "_popup");
		this.currentPopup = false;
	}

	this.closeActiveColorsPoup = function() {
		if(!this.currentPopup) return;
		this.closeColorsPopup(this.currentPopup)
	}




	this.onBuildInterface = function() {
		/*
		var m =
		{ tag: "div", cn: "msettings",

		childs: [
		{ tag: "div", cn: "menu",
		childs: [
		this.getMenuItemModel("account", "Account"),
		this.getMenuItemModel("themes", "Themes"),
		this.getMenuItemModel("wallpapers", "Wallpapers")
		]},

		{ tag: "div", cn: "pages",
		childs: [
		// this.getPageModel("account", "Account"),
		//this.getPageModel("themes", "Themes")
		//this.getPageModel("wallpapers", "Wallpapers")
		]}
		]}
		*/
		//Hide Title
		this.elements.window.className = "t_a";
		this.elements.window_title.style.display = "none";
		this.elements.content.className = 'widget_con';
		//this.buildDomModel(this.elements["content"], m);
		this.buildDomModel(this.elements["content"], this.pmodel_themes);
		/*
		this.buildDomModel(document.body, [
		this.getColorsPopupModel("top"),
		this.getColorsPopupModel("bottom")
		]);
		*/
	}



	this.onOpen = function() {
		//this.setTitle(this.cfg.title);
		//this.showPage("themes");
		//this.showImagesSource("top");
		//this.showImagesSource("bottom");
		this.onShowPage_themes();
	}


	this.close = function() {
		this.closeActiveColorsPoup();
		desktop.hideActivePopup();
	}


	this.dispatchMsg = function(msg) {
		switch (msg.status) {
			case "themes_list":
			this.isThemesLoaded = true;
			this.renderThemes(msg.data);
			break;
			case "skins_list":
			this.isSkinsLoaded = true;
			this.renderSkins(msg.data);
			break;
			case "pwd_changed":
			this.elements["change_pwd_msg"].innerHTML = loc.text("settings_pwd_changed");
			this.elements["btn_change_pwd"].disabled = false;
			this.elements["inp_old_pwd"].value = "";
			this.elements["inp_new_pwd"].value = "";
			this.elements["inp_new_pwd2"].value = "";
			auth.user.password = msg.npwd;
			auth.saveUser();
			break;

			case "wallpapers":
			this.isWallpapersLoaded = true;
			for(var d in msg.data) {
				for(var i=0; i<msg.data[d].length; i++) {
					var wp = msg.data[d][i];
					this.wallpapers[d].push(
					{ thumb: "var/wallpapers/thumbs/" + d + "_" + wp.t,
					file:  "var/wallpapers/" + d + "/" + wp.f });
				}
			}
			this.renderWallpapers("top", "int", this.wallpapers["top"]);
			this.renderWallpapers("bottom", "int", this.wallpapers["bottom"]);
			break;
		}
	}

	this.show = function() {
		if(!desktop.isSettingsShow) {
			menu.hide();
			showEl(this.elements.window);
			//            desktop.elements.pager.style.marginLeft = this.elements.window.offsetWidth + 2 + "px";
			//            desktop.elements.pager.style.width = "auto";
			desktop.isSettingsShow = true;
		}
	}


	this.hide = function() {
		if(desktop.isSettingsShow) {
			hideEl(this.elements.window);
			//            desktop.elements.pager.style.marginLeft = 0;
			desktop.isSettingsShow = false;
		}
	}
}
Settings.prototype = new Widget();

function Feedback() {
    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasProfile: false,
        title: loc.text('feedback_user_feedback'),
        module: "Feedback",
        uniqueId: SYS_WIDGETS_ID + 7
    }


    this.onBuildInterface = function() {
        this.setTitle(this.cfg.title);

        this.buildDomModel(this.elements.content, [
           { tag: "div", align: "center", id: "feedback_status",
             html: "<B>" + loc.text("feedback_status") + "</B>"},
           { tag: "hr"},
           { tag: "div", className: "menu_panel", 
             id: "feedback_sending", 
             display: false, 
             innerHTML: "<p><b>"+loc.text('feedback_sending')+"</b></p>" },
           { tag: "table", width: "95%",
             id: "feedback_input",
             childs: [
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right",
                     childs: [{ tag: "div", innerHTML: loc.text('sendtofriend_your_email')}]},
                   { tag: "td",
                     childs: [{ tag: "input", type: "text", id: "inp_email", size: "30"}]}
                 ]
               },
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right", valign: "top",
                     childs: [{ tag: "div", innerHTML: loc.text('feedback_feedback_text')}]},
                   { tag: "td",
                     childs: [{ tag: "textarea", id: "inp_message", rows: 16, cols: 50, style: {width: "90%"} }]}
                 ]},
               { tag: "tr",
                 childs: [
                   { tag: "td"},
                   { tag: "td",
                     childs: [
                       { tag: "input", type: "button", align: "center", 
                         value: loc.text('btn_send'), 
                         events: {onclick: "sendFeedback()"}}
                     ]}
                 ]}
             ]}      
        ]);
        this.elements["content"].style.height = "300px";
        this.elements["inp_email"].value = auth.user.email;
    }



    this.close = function() {
        desktop.hideActivePopup();
    }


    this.showText = function() {}
    this.applyText = function() {}


    //-------------------------------------
    // SEND
    //-------------------------------------
    this.sendFeedback = function() {
        var str = this.elements["inp_message"].value;
        if(str!="") {
            hideEl(this.elements.feedback_input);
            showEl(this.elements.feedback_sending);
            request.send({ act: "feedback", 
                           text: str, 
                           email: this.elements["inp_email"].value}, 
                         this, "POST");
        }
        else {
            alert(loc.text('feedback_text_empty'));
        }
    }


    this.dispatchMsg = function(msg) {
        switch (msg.status) {
            case "feedback_saved":
            	this.elements.feedback_status.innerHTML = "<b>"+loc.text('feedback_msg_saved')+"</b>";
            	this.elements["inp_message"].value = "";
            	showEl(this.elements.feedback_input);
            	hideEl(this.elements.feedback_sending);
                break;
            case "empty_text":
            	this.elements.feedback_status.innerHTML = loc.text('feedback_msg_empty');
            	showEl(this.elements.feedback_input);
            	hideEl(this.elements.feedback_sending);
                break;
        }
    }



}
Feedback.prototype = new Widget();


function Custompage() {

    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasProfile: false,
        title: loc.text("custompage_title"),
        module: "Custompage",
        uniqueId: SYS_WIDGETS_ID + 8
    }


    this.onBuildInterface = function() {
        this.setTitle(loc.text("custompage_title"));
        this.elements["content"].style.height = "300px";
        this.elements["content"].style.overflow = "auto";
    }


    this.close = function() {
        desktop.hideActivePopup();
    }


    this.setData = function(title, content) {
        this.setTitle(title);
        this.elements["content"].innerHTML = content.parseUrl();
    }


}
Custompage.prototype = new Widget();

function SendToFriend() {

    this.init();

    this.domSendToFriend = {
        tag: "div", className: "menu_panel",
        childs: [
           { tag: "div", align: "center", id: "send_status",
             style: { fontWeight: "bold" },
             html: loc.text("sendtofriend_status") },
           {tag: "hr"},
           {tag: "table", width: "95%",
             childs: [
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right",
                     childs: [{ tag: "div", innerHTML: loc.text('sendtofriend_your_name')}]
                   },
                   { tag: "td",
                     childs: [{ tag: "input", type: "text", id: "ed_name", size: "30"}]
                   }
                 ]
               },
               { tag: "tr", childs: [{ tag: "td"},{ tag: "td"}]},
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right",
                     childs: [{ tag: "div", innerHTML: loc.text('sendtofriend_your_email')}]
                   },
                   { tag: "td",
                     childs: [{ tag: "input", type: "text", id: "ed_email", size: "30" }]
                   }
                 ]
               },
               { tag: "tr", childs: [{ tag: "td"},{ tag: "td"}]},
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right",
                     childs: [{ tag: "div", innerHTML: loc.text('sendtofriend_friend_email')}]
                   },
                   { tag: "td",
                     childs: [{ tag: "input", type: "text", id: "ed_friend_email", size: "30" }]
                   }
                 ]
               },
               { tag: "tr", childs: [{ tag: "td"},{ tag: "td"}]},
               { tag: "tr",
                 childs: [
                   { tag: "td", width: "30%", align: "right", valign: "top",
                     childs: [{ tag: "div", innerHTML: loc.text('sendtofriend_message')}]
                   },
                   { tag: "td",
                     childs: [{ tag: "textarea", id: "ed_message", rows: "9", cols: "50", style: {width: "90%"} }]
                   }
                 ]
               },
               { tag: "tr", childs: [{ tag: "td", innerHTML: "&nbsp;"},{ tag: "td"}]},

             ]
           },
           { tag: "div", align: "center", id: "btn_send", 
             childs: [
               { tag: "input", 
                 type: "button", value: loc.text('sendtofriend_send'), 
                 events: {onclick: "doSend()"}}
             ]}
        ]}




    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasProfile: false,
        title: "",
        module: "SendToFriend",
        uniqueId: SYS_WIDGETS_ID + 9
    }


    this.onBuildInterface = function() {
        this.setTitle(loc.text('sendtofriend_title'));
        this.elements["content"].style.height = "300px";
        this.buildDomModel(this.elements.content, this.domSendToFriend);
        this.elements["ed_email"].value = auth.user.email;
        this.elements["ed_message"].value = "http://" + baseUrl;
    }


    this.close = function() {
        desktop.hideActivePopup();
    }

    this.dispatchMsg = function(msg) {
        //alert(msg.status);
        switch(msg.status) {
            case 'ok':
                this.showElement("btn_send");
                this.elements.send_status.innerHTML = '<font color=green>'+loc.text('sendtofriend_send_ok')+'</font>';
                break;
            case 'failed':
                this.elements.send_status.innerHTML = '<font color=red>'+loc.text('sendtofriend_send_failed')+'</font>';
                this.showElement("btn_send");
                break;
        }
    }

    this.doSend = function() {

        var name_val   = this.elements.ed_name.value;
        var email_val  = this.elements.ed_email.value;
        var femail_val = this.elements.ed_friend_email.value;
        var msg_val    = this.elements.ed_message.value;


        //todo: e-mail check
        if (email_val=="") {
           alert(loc.text('sendtofriend_email_empty'));
           this.elements.ed_email.focus();
           return;
        }
        if (checkEmailAddress(email_val)==false) {
           alert(loc.text('sendtofriend_email_invalid'));
           this.elements.ed_email.focus();
           return;
        }

        if (femail_val=="") {
           alert(loc.text('sendtofriend_femail_empty'));
           this.elements.ed_friend_email.focus();
           return;
        }
        if (checkEmailAddress(femail_val)==false) {
           alert(loc.text('sendtofriend_femail_invalid'));
           this.elements.ed_friend_email.focus();
           return;
        }

        this.elements["send_status"].innerHTML = loc.text("msg_processing");
        this.hideElement("btn_send");
        request.send({
                   act    : "send_to_friend",
                   name   : name_val,
                   email  : email_val,
                   femail : femail_val,
                   msg    : msg_val
                   },
                   this);
    }

}
SendToFriend.prototype = new Widget();



// E-MAIL
function checkEmailAddress(value)
{
   //trim(field);
   var goodEmail = value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);

   if (goodEmail)
      return true;
   else
      return false;
}


function Rss() {
    this.init();

    this.cfg = {
        title: loc.text("rss_title"),
        module: "Rss"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
   		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        this.elements["select_url"].value = this.profile["url"];
    }

    this.onOpen = function() {
        this.setTitle(loc.text("rss_title"));
        this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.setUrl = function() {
        if(this.isLoading) {
            this.elements["select_url"].value = this.profile["url"];
        } else {
            var url = trim(this.elements["select_url"].value);
            if(url != "") {
                if(url.indexOf("http://") == -1) {
                    url = "http://" + url;
                }
                if(this.profile["url"] != 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();
                }
            } else {
                this.elements["content"].innerHTML = loc.text("msg_empty");
            }
        }
        this.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        if(this.profile.url != "") {
            var date = new Date();
            this.lastRefresh = date.getSeconds();
            this.setTitle(loc.text("msg_loading"));

            var wid = this.id;
            var iconEl = this.elements.icon;
            xmlRequest.send(this.profile.url, this, "showChannel");
            this.isLoading == true;
        } else {
            this.elements["content"].innerHTML = loc.text("msg_empty");
        }
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            if(!this.isPreview) {
                this.isInReader = true;
                rssreader.channelLastRefresh = this.lastRefresh;
                rssreader.elements["icon"].src = this.elements["icon"].src;
                rssreader.openChannel(wid, feedId);
            }
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();

            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span", href: "void",
                  innerHTML: this.data.title.substr(0,25)
                  });

            /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements["title"].innerHTML = loc.text("rss_msg_error");
        this.elements["content"].innerHTML = "";
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(!this.isPreview && rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Rss.prototype = new Widget();

function RssReader() {
    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasProfile: false,
        hasCloseBtn: true,
        title: loc.text("rssreader_title"),
        module: "RssReader",
        uniqueId: SYS_WIDGETS_ID + 5
    }

    this.domContent = {
        tag: "table", 
        style: { width: "100%" },
        childs: [
          { tag: "tr",
            childs: [
              { tag: "td", width: "35%",
                childs: [
                  createButtonDom(loc.text("rssreader_read_all"), "readAll()", "widgets/rssreader/img/folder_open.gif"),
                  { tag: "span", html: " &nbsp; &nbsp; &nbsp; "},
                  createButtonDom(loc.text("rssreader_unread_all"), "unReadAll()", "widgets/rssreader/img/folder_close.gif")
                ]},
              { tag: "td", 
                childs: [{ tag: "div", id: "channelTitle"}]}
            ]},
          { tag: "tr",
            childs: [
              { tag: "td", width: "35%",
                childs: [
                  { tag: "div", id: "menu", className: "listBox", style: {width: "auto", height: "340px"}}
                ]},
              { tag: "td",
                childs: [
                  { tag: "div", id: "view", className: "listBox", style: {width: "auto", height: "340px"}}
                ]}
            ]}
        ]}


    this.channelLastRefresh = null;

    this.onBuildInterface = function() {
        this.elements["content"].style.height = "390px";
        this.buildDomModel(this.elements.content, this.domContent);
        this.setTitle(this.cfg.title);
    }


    this.buildChannel = function() {
//        this.elements.channelTitle.innerHTML = "<h1><a target=\"_blank\" href=\""+this.data.LINK+"\">"+this.data.title+"</a></h1>";
        this.elements.channelTitle.innerHTML = "<h1>"+this.data.title+"</h1>";
        this.elements.menu.innerHTML = "";
        this.elements.view.innerHTML = "";
        var count = kernel.getWidget(this.widgetId).getItemsCount();
        for(var i=0; i< count; i++) {
            this.buildDomModel(this.elements.menu, 
                               [{ tag: "div", className: "menu_panel",
                                  childs: [
                                    { tag: "a", 
                                      innerHTML: this.data.items[i].title.wordWrap(38),
                                      id: "menuItem"+i,
                                      href: "void", 
                                      events: {onclick: "readFeed("+i+")"}, 
                                      className: "listItem" + (this.data.items[i].isRead == 1 ? "Visited" : "") }
                                  ]
                                },
                                { tag: "hr", width: "100%"}
                               ]);
        }
    }


    
    this.readFeed = function(feedId) {
        this.elements.view.innerHTML = "";
        var content = this.data.items[feedId]["content"] ? this.data.items[feedId]["content"] : this.data.items[feedId]["description"];
        var url = this.data.items[feedId]["link"]["href"] ? this.data.items[feedId]["link"]["href"] : this.data.items[feedId]["link"];
        this.buildDomModel(this.elements.view, [
            { tag: "div", className: "float_panel",
              childs: [
                { tag: "div", className: "float_left",
                  display: (feedId > 0),
                  childs: [
                    createButtonDom(false, "readFeed("+(feedId-1)+")", "widgets/rssreader/img/previous.gif", "readPrev")
                  ]},
                { tag: "div", className: "float_right",
                  display: (feedId < kernel.getWidget(this.widgetId).getItemsCount() - 1),
                  childs: [
                    createButtonDom(false, "readFeed("+(feedId+1)+")", "widgets/rssreader/img/next.gif", "readNext")
                  ]}
              ]},

            { tag: "hr", width: "100%"},

            { tag: "div", className: "menu_panel",
              innerHTML: "<p><a href='" + url + "' class='rssreader_item_title' target=_blank>" + this.data.items[feedId].title + "</a>"+
                         "<p>"+(content ? content : "")
            }
          ]);


        if(kernel.getWidget(this.widgetId)) {
            kernel.getWidget(this.widgetId).processItemRead(feedId);
            kernel.getWidget(this.widgetId).save();
        }
        this.elements['menuItem'+feedId].className = "listItemVisited";

        this.updateTitle();
    }



    this.readAll = function() {
        var count = kernel.getWidget(this.widgetId).getItemsCount();

        for(var i=0; i<count; i++) {
            kernel.getWidget(this.widgetId).processItemRead(i);
        }
        this.buildChannel();

        var w = kernel.getWidget(this.widgetId);
        if(w) {
            w.save();
        }
        this.updateTitle();
    }


    this.unReadAll = function() {
        var count = kernel.getWidget(this.widgetId).getItemsCount();

        for(var i=0; i<count; i++) {
            kernel.getWidget(this.widgetId).processItemUnread(i);
        }
        this.buildChannel();

        var w = kernel.getWidget(this.widgetId);
        if(w) {
            w.save();
        }
        this.updateTitle();
    }



    this.updateTitle = function() {
        if(this.data) {
            var count = kernel.getWidget(this.widgetId).getItemsCount();
            var readed = kernel.getWidget(this.widgetId).getReadedItemsCount()

            this.elements.title.innerHTML = '';

            this.buildDomModel(this.elements.title, 
                { tag: "span", 
                  innerHTML: this.data.title.substr(0,25)
                  });
			/*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " &nbsp;(" + (count - readed) + ")" });
            }
            */
        }
    }



    this.openChannel = function(widgetId, feedId) {
        menu.hide();
        this.data = kernel.getWidget(widgetId).data;
        this.widgetId = widgetId;
        this.buildChannel();
        this.elements.icon.src = kernel.getWidget(widgetId).elements.icon.src;
        desktop.showPopup('rssreader', {top: "10%"});
        this.readFeed(feedId);
    }


    this.close = function() {
        if(this.widgetId && kernel.getWidget(this.widgetId)) {
            if(this.channelLastRefresh == kernel.getWidget(this.widgetId).lastRefresh) {
                kernel.getWidget(this.widgetId).isInReader = false;
//                kernel.getWidget(this.widgetId).data = this.data;
            }
        }
        desktop.hideActivePopup();
    }
 
}
RssReader.prototype = new Widget();

function FlashPlayer() {
    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        hasProfile: false,
        title: loc.text("flash_title"),
        module: "FlashPlayer",
        uniqueId: SYS_WIDGETS_ID + 6
    }


    this.onBuildInterface = function() {
        this.elements.content.style.height = "400px";
    }


    this.openFlash = function(widgetId) {
        this.widgetId = widgetId;
        var widget = kernel.getWidget(widgetId);
        this.setTitle(this.cfg.title + ": " + widget.profile.title);
        widget.elements.flash_container.parentNode.removeChild(widget.elements.flash_container);
        this.elements.content.appendChild(widget.elements.flash_container);
        desktop.showPopup('flashplayer');
    }


    this.close = function() {
        if(this.widgetId) {
            var widget = kernel.getWidget(this.widgetId);
            widget.elements.flash_container.parentNode.removeChild(widget.elements.flash_container);
            widget.elements.flash_content.appendChild(widget.elements.flash_container);
        }
        desktop.hideActivePopup();
    }
 
}
FlashPlayer.prototype = new Widget();

function Messenger() {
    this.init();


    this.cfg = {
        hasSettingsBtn: false,
        title: loc.text("messenger_title"),
        module: "Messenger"
    }


    this.domContent = [
        { tag: "div", className: "bevel_section", innerHTML: loc.text("messenger_clist"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_contact_list')"}
        },
        { tag: "div", className: "menu_panel", id: "section_contact_list", display: false,
          childs: [
            { tag: "div", className: "menu_panel", id: "contact_list"},
            { tag: "hr", width: "100%"},
            { tag: "div", className: "menu_panel", 
              childs: [
                { tag: "span", innerHTML: loc.text("messenger_cadd") },
                { tag: "input", type: "text", style: {width: "120px"}, id: "edit_user_id"},
                { tag: "input", type: "button", value: " Add ", events: {onclick: "addContact()"}}
              ]}
          ]
        },


        { tag: "div", className: "bevel_section", innerHTML: loc.text("messenger_compose"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_compose')"}
        },
        { tag: "div", className: "menu_panel", id: "section_compose", display: false,
          childs: [
            { tag: "div", className: "menu_panel", innerHTML: loc.text("messenger_recipient"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "edit_recipient"}
              ]
            },
            { tag: "div", className: "menu_panel", innerHTML: loc.text("messenger_text") + "<br>",
              childs: [
                { tag: "textarea", style: {width: "95%", height: "80"}, id: "edit_body"}
              ]
            },
            { tag: "input", type: "button", value: loc.text("btn_send"), id: "send_btn", events: {onclick: "sendMessage()"}},
            { tag: "div", id: "send_status"}
          ]
        },

        { tag: "div", className: "bevel_section", innerHTML: loc.text("messenger_inbox"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_new_messages')"}
        },
        { tag: "div", className: "menu_panel", id: "section_new_messages", display: false,
          childs: [
            { tag: "div", id: "new_messages", className:"listBox", style: {width: "auto", height: "300px"}, innerHTML: loc.text("msg_loading") },
            { tag: "div", id: "clear_new_messages", display: false, align: "right",
              childs: [
                createButtonDom(loc.text("messenger_clear"), "clearMessages()", "widgets/messenger/img/clear.gif")
              ]
            }
          ]
        },

        { tag: "div", id: "tmp", display: false}
    ]


    this.defaultProfile["contact_list"] = [];

    this.messages = [];
    this.isUpdating = false;

    this.switchSection = function(sid) {
        if(this.elements[sid].style.display == 'none') {
            showEl(this.elements[sid]);
        } else {
            hideEl(this.elements[sid]);
        }
    }




    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.content, this.domContent);
        this.renderContactList();
        this.setTitle(this.cfg.title);
    }


    this.onOpen = function() {
        kernel.processTimer(this.id, 30000);
    }


    this.timerHandler = function() {
        this.refresh();
    }



    this.addContact = function() {
        var id = trim(this.elements.edit_user_id.value);
        if(id != "") {
            this.profile.contact_list[arrayFirstFree(this.profile.contact_list)] = id;
            this.save();
            this.renderContactList();
            this.elements.edit_user_id.value = '';
        }
    }

    this.deleteContact = function(num) {
        if(confirm(  loc.text("messenger_delete_confirm", "\"" + this.profile.contact_list[num] + "\"")  )) {
            this.profile.contact_list[num] = undefined;
            this.renderContactList();
            this.save();
        }
    }


    this.renderContactList = function() {
        var fl = true;
        this.elements.contact_list.innerHTML = "";
        for(var i=0; i<this.profile.contact_list.length; i++) {
           if(this.profile.contact_list[i] != undefined) {
               var itemDom = { tag: "div", className: "menu_panel", id: "contact"+i,
                               childs: [
                                 createTableDom([ {content: createButtonDom(this.profile.contact_list[i], "startNewMessage("+i+")", "widgets/messenger/img/user.gif"), width: "90%"},
                                                  {content: createButtonDom(false, "deleteContact("+i+")", "static/client/delete_link.gif"), width: "1%"}
                                                ])
                               ]
                             }
               this.buildDomModel(this.elements.contact_list, itemDom);
               fl = false;
           }
        }

        if(fl) {
            this.elements.contact_list.innerHTML = loc.text("msg_empty");
        }
    }



    this.startNewMessage = function(contactNum) {
        hideEl(this.elements.section_contact_list);
        showEl(this.elements.section_compose);
        this.elements.edit_recipient.value = this.profile.contact_list[contactNum];
//        this.elements.edit_body.value = '';
        this.elements.edit_body.focus();
    }


    this.replyTo = function(email) {
        showEl(this.elements.section_compose);
        this.elements.edit_recipient.value = email;
        this.elements.edit_body.value = '';
        this.elements.edit_body.focus();
    }




    this.refresh = function() {
        if(!this.isUpdating) {
            request.send({act: "get_new_messages", user_id: auth.user.id}, this);
            this.isUpdating = true;
        }
    }



    this.sendMessage = function() {
        if((trim(this.elements.edit_recipient.value) == "") || 
           (trim(this.elements.edit_body.value) == "")) {
            this.elements.send_status.innerHTML = "<b>" + loc.text("messenger_send_error")+ "</b>";
            return;
        }
        hideEl(this.elements.send_btn);
        showEl(this.elements.send_status);
        this.elements.send_status.innerHTML = loc.text("msg_sending");

        request.send({act: "send", 
                      user_id: auth.user.id, 
                      to: trim(this.elements.edit_recipient.value), 
                      body: this.elements.edit_body.value}, this);
    }



    this.firstRenderMessages = true;

    this.renderMessages = function() {
        if(this.messages.length > 0) {
            var time = new Date();
            if(this.firstRenderMessages) {
                this.elements.new_messages.innerHTML = '';
            }
            this.firstRenderMessages = false;

            var isNewMessages = false;
            for(var i=0; i<this.messages.length; i++) {
                if(this.messages[i].rendered) {
                    continue;
                }
                this.messages[i].rendered = true;
                isNewMessages = true;

                var from = (this.messages[i].from_email == "") ? 
                    { tag: "div", innerHTML: "<b>"+loc.text("messenger_anonym")+"</b>" }
                    :
                    createButtonDom("<b>"+this.messages[i].from_email+"</b>", "replyTo('"+this.messages[i].from_email+"')", "widgets/messenger/img/user.gif");
                
                this.buildDomModel(this.elements.tmp, 
                    { tag: "div", className: "menu_panel", id: "last_msg",
                      childs: [
                        from ,
                        { tag: "div", class_name: "menu_panel", innerHTML: '[' + time.toLocaleString() + ']'},
                        { tag: "div", className: "note", innerHTML: text2html(unescape(this.messages[i].body)) }
                      ]
                    });

                if(this.elements.new_messages.firstChild) {
                    this.elements.new_messages.insertBefore(this.elements.last_msg, this.elements.new_messages.firstChild);
                } else {
                    this.elements.new_messages.appendChild(this.elements.last_msg);
                }
            }
            if(isNewMessages) {
                showEl(this.elements.section_new_messages);
            }
            showEl(this.elements.clear_new_messages);
        } else {
            this.elements.new_messages.innerHTML = loc.text("messenger_no_messages");
        }
    }


    this.clearMessages = function() {
        this.firstRenderMessages = true;
        this.messages = [];
        this.renderMessages();
        hideEl(this.elements.clear_new_messages);
    }



    this.dispatchMsg = function(msg) {
        this.isUpdating = false;
        if(msg.status) {
            switch(msg.status) {
                case "new_messages":
                    if(msg.list.length > 0) {
                        var ids = [];
                        for(var i=0; i<msg.list.length; i++) {
                            this.messages.push(msg.list[i]);
                            ids.push(msg.list[i].id);
                        }
                        request.send({act: "set_received", user_id: auth.user.id, ids: ids.join("_")}, this);
                    }
                    this.renderMessages();
                    break;

                case "send_ok":
                    this.elements.edit_body.value = '';
                    showEl(this.elements.send_btn);
                    this.elements.send_status.innerHTML = "Message sent.";
                    break;

                case "send_error":
                    this.elements.send_status.innerHTML = "<b>Error:</b> Recipient not found...";
                    showEl(this.elements.send_btn);
                    break;
            }
        }
    }

}
Messenger.prototype = new Widget();

function PopMail() {
    this.init();


    this.cfg = {
        hasSettingsBtn: true,
        title: loc.text("popmail_title"),
        module: "PopMail"
    }


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_mcount")},
            { tag: "select", id: "inp_count",events:{onchange:"setItemsCount()"}, 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:"20", text: "20"}
              ]
            }
            /*,
            { tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "setItemsCount()"}, className: "settings_control"}*/
          ]
        },

        { tag: "div", className: "settings_section", align: "center",
          innerHTML: "<b>"+ loc.text("popmail_asettings") + "</b>"},

        { tag: "div", className: "settings_section",
           childs: [ 
             { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_login")},
             { tag: "input", id: "select_login", type: "text", size: "15", className: "settings_control"} 
           ]},

        { tag: "div", className: "settings_section",
           childs: [ 
             { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_pwd")},
             { tag: "input", id: "select_password", type: "password", size: "15", className: "settings_control"} 
           ]},

        { tag: "div", className: "settings_section",
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_protocol")},
            { tag: "select", id: "select_protocol", className: "settings_control",
              events: {onchange: "updatePort()"},
              options: [
                { value: "pop3", text: "POP3" },
                { value: "imap", text: "IMAP4" }
              ]
            }
          ]
        },

        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_secure")},
            { tag: "input", type: "checkbox", id: "select_secure",  
              events: {onchange: "updatePort()"}, 
              className: "settings_control"} 
          ]},

        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_server")},
            { tag: "input", id: "select_server", type: "text", size: "15", className: "settings_control"} 
          ]},

        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_port")},
            { tag: "input", id: "select_port", type: "text", size: "5", value: "110"} 
          ]},

        { tag: "div", className: "settings_section", align: "center",
          childs: [ 
            { tag: "input", type: "button", value: loc.text("btn_save"), events: {onclick: "saveProfile()"}} 
          ]},
   		  { tag: "div", className: "cls"}
    ]

    this.domContent = [
        { tag: "div",
          style: { width: "100%", zoom: "1", overflow: "hidden" },
          childs: [
            { tag: "div", className: "menu_panel", id: "messages", display: false,
              childs: [
                { tag: "div", className: "menu_panel", 
                  style: { paddingLeft: "30px", background: "url(widgets/aolmail/ico.gif) no-repeat 0 0"},
                  childs: [
                    { tag: "b", html: loc.text("popmail_total") },
                    { tag: "span", id: "total_messages"}
                  ]},
                { tag: "div", id: "mail_list"}
              ]}
          ]},

        { tag: "div", className: "menu_panel", id: "loading_note", display: false, 
		style: { background: "url(static/client/loader.gif) no-repeat center center"}	
		},

        { tag: "div", className: "menu_panel", id: "config_note", display: false,
          style: { paddingLeft: "30px",textAlign : "center"},
          innerHTML: loc.text("popmail_msg_not_configured")},

        { tag: "div", className: "menu_panel", id: "no_messages_note", display: false,
          style: { paddingLeft: "30px",textAlign : "center"},
          innerHTML: loc.text("popmail_msg_no_mails")}
    ]

    this.defaultProfile["login"] = "";
    this.defaultProfile["password"] = "";
    this.defaultProfile["protocol"] = "pop3";
    this.defaultProfile["secure"] = "0";
    this.defaultProfile["server"] = "";
    this.defaultProfile["port"] = "110";

    this.defaultProfile["title"] = loc.text("popmail_title");
    this.defaultProfile["mcount"] = "8";


    this.isLoading = false;

    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.buildDomModel(this.elements.content, this.domContent);

        this.elements.select_login.value = this.profile.login;
        this.elements.select_password.value = this.profile.password;
        this.elements.select_protocol.value = this.profile.protocol;
        this.elements.select_secure.checked = this.profile.secure == 1;
        this.elements.select_server.value = this.profile.server;
        this.elements.select_port.value = this.profile.port;
        this.elements.inp_count.value = this.profile.mcount;

        this.setTitle(this.profile.title);
    }



    this.onOpen = function() {
        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.refresh();
        }
//        kernel.processTimer(this.id, 30000);
    }


    this.updatePort = function() {
        this.elements["select_port"].value = 
            (this.elements["select_protocol"].value == "pop3") 
            ?
            (this.elements["select_secure"].checked ? "995" : "110")
            :
            (this.elements["select_secure"].checked ? "993" : "143")
    }


    this.isProfileEmpty = function() {
        return this.profile.login == "" || this.profile.password == "" || this.profile.server == "";
    }


    this.setContent = function(section) {
        var sections = ["config_note", "loading_note", "messages", "no_messages_note"];
        for(var i = 0; i<sections.length; i++) {
            if(section == sections[i]) {
                this.showElement(sections[i]);
            } else {
                this.hideElement(sections[i]);
            }
        }
    }


    this.saveProfile = function() {
        this.profile.login = trim(this.elements.select_login.value);
        this.profile.password = trim(this.elements.select_password.value); 
        this.profile.protocol = this.elements.select_protocol.value;
        this.profile.secure = this.elements.select_secure.checked ? 1 : 0;
        this.profile.server = trim(this.elements.select_server.value);
        this.profile.port = trim(this.elements.select_port.value);

        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.save();
            this.refresh();
        }
    }


    this.setItemsCount = function() {
        var c = this.elements["inp_count"].value;
        if(this.profile.mcount != c) {
            this.profile.mcount = c;
            this.save();
            this.renderMessages();
        }
    }




    this.timerHandler = function() {
        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.refresh();
        }
    }


    this.req = null;
    this.timerId = null;

    this.refresh = function() {
            if(this.isReduced) {
                                this.show();
                        }
        if(!this.isProfileEmpty() && !this.isLoading) {
            this.isLoading = true;
            this.setContent("loading_note");
            var protocol = "/" + this.profile.protocol + 
                           ((this.profile.secure == 1) ? "/ssl" : "") +
                           "/novalidate-cert";

            this.req = request.send({ login: this.profile.login,
                                      password: this.profile.password,
                                      protocol: protocol,
                                      server: this.profile.server,
                                      port: this.profile.port }, this);
            var self = this;
            var f = function() {
                updateLoadingIcon(-1);
                self.req.onreadystatechange = function() {};
                self.isLoading = false;
                self.setContent("config_note");
            }
            this.timerId = setTimeout(f, 30000);
        }
    }



    this.renderMessages = function() {
        if(this.data) {
            this.setContent("messages");        
            this.elements.total_messages.innerHTML = "<B>" + this.totalMessages + "<B>";
            this.elements.mail_list.innerHTML = '';
            var cnt = Math.min(this.data.length, this.profile.mcount);
            for(var i=0; i<cnt; i++) {
                try {
                    this.buildDomModel(this.elements.mail_list,
                                       { tag: "div", className: "menu_panel", 
                                         innerHTML: "<B>" + this.data[i].from + "</B>",
                                         childs: [
                                           { tag: "div", className: "note", innerHTML: this.data[i].subj.wordWrap(20) }
                                         ]
                                       });
                } catch(e) {}
            }
        }
    }


    this.dispatchMsg = function(msg) {
        clearTimeout(this.timerId);
        this.isLoading = false;
        switch(msg.status) {
            case "empty":
                this.setContent("no_messages_note");
                break;
            case "data":
                this.data = msg.data;
                this.totalMessages = msg.total;
                this.renderMessages();
                break;
            case "error":
                this.setContent("config_note");
                break;
        }
    }

}
PopMail.prototype = new Widget();


function Gmail() {
    this.init();


    this.cfg = {
        hasSettingsBtn: true,
        hasTitle: false,
        title: "",
        module: "Gmail"
    }


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("gmail_inp_mcount"), className: "settings_label"},
            { tag: "select", id: "news_count", className: "settings_control", events: {onchange: "setNewsCount()"},
              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:"20", text: "20"}
              ]
            } 
            
          ]
        },
	  { tag: "div", className: "cls"}
    ]



    this.domContent = [
    	{ tag: "div", id: "loading"},
        { tag: "div", id: "messages_area", className:"messages_area",  
          display: false,
          childs: [
            { tag: "div", 
              style: { padding: "10px 10px 0 30px", height: "24px"},
              childs: [
                { tag: "span", id: "mail_total" },
                { tag: "div", className: "settings_section", style: { margin: "5px 0 10px 0" },
                childs:
                [   
                	 
                	{ tag: "input", type: "checkbox", style: { margin: "0 0 0 5px"}, 
                	events: {onclick: "switchMailsContent()"}, id: "switcher"},
                	{ tag: "label", innerHTML: loc.text("gmail_inp_details") }
                ]}
              ]},
            { tag: "div", id: "mail_list", style: { margin:"20px 10px 10px 10px"}}
          ]
        },
        { tag: "div", id: "config_note", className: "config_note", event: {onkeypress: "saveProfile()"},          
          innerHTML: loc.text("gmail_msg_not_configured"),
          childs:
          [
          	{ tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", innerHTML: loc.text("gmail_inp_account"), className: "settings_label"},
            { tag: "input", id: "select_email", type: "text", size: "15", className: "settings_control"} 
          ]},

        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", innerHTML: loc.text("gmail_inp_pwd"), className: "settings_label"},
            { tag: "input", id: "select_password", type: "password", size: "15", className: "settings_control"} 
          ]},{ tag: "div", className: "settings_section", align: "center",
          childs: [ 
            { tag: "input", type: "button", value: loc.text("btn_save"), events: {onclick: "saveProfile()"} } ]}
          ]},
        { tag: "div", className: "menu_panel", id: "msg_no_new_mails", innerHTML: loc.text("gmail_msg_no_mails"), display: false}
        

    ]

    this.defaultProfile["title"] = "";
    this.defaultProfile["email"] = "";
    this.defaultProfile["password"] = "";
    this.defaultProfile["newsCount"] = "8";



    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        //this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
        this.buildDomModel(this.elements.content, this.domContent);

        this.elements.news_count.value = this.profile.newsCount;
        this.elements.select_email.value = this.profile.email;
        this.elements.select_password.value = this.profile.password;

        if(this.profile["email"] != "" && this.profile["password"] != "") {
            this.hideElement("config_note");
        }
        jQuery("input").keypress(function (e) {        
    if (e.which == 13 ) {
    	 // saveProfile();
     }      
    });
    }

	
    
    this.onOpen = function() {
        if(trim(this.profile.title) == "") {
            this.profile.title = loc.text("gmail_title");
        }  
        this.elements.mail_list.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';      
        this.setTitle(this.profile.title);
        kernel.processTimer(this.id, 600*1000);
    }


    this.timerHandler = function() {
        this.refresh();
    }


    this.saveProfile = function() {
        this.profile.email = "" + trim(this.elements.select_email.value).split("@gmail.com")[0];
        this.profile.password = trim(this.elements.select_password.value);
        this.save();
        this.hideElement("messages_area");
        this.refresh();
    }


    this.setNewsCount = function() {
        this.profile.newsCount = this.elements.news_count.value;
        this.save();
        this.renderMessages();
    }


    var isLoading = false;

    this.refresh = function() {
        this.hideElement("msg_no_new_mails");
        this.elements.loading.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
        if(this.profile["email"] != "" && this.profile["password"] != "") {
            if(!isLoading) {            	
                isLoading = true;                               
                this.hideElement("config_note");
                xmlRequest.send("https://mail.google.com/mail/feed/atom/", this, "showMail", {login: this.profile.email, password: this.profile.password});
            }
            if(this.isReduced) {
            	this.elements.loading.innerHTML = '';
				this.show();
			}
        } else {
            this.showElement("config_note");
            this.elements.loading.innerHTML = '';
        }
            if(this.isReduced) {
            this.elements.loading.innerHTML = '';
				this.show();
			}        
    }

    this.showMail = function(response) {
        isLoading = false;
        if(response.responseXML && response.responseXML.documentElement) {
            var te = response.responseXML.documentElement.getElementsByTagName("TITLE");

            if(!(te[0] && te[0].firstChild.nodeValue == "Unauthorized")) {
                try {
                    this.data = XMLParser.xml2hash(response.responseXML.documentElement, "entry");
                    this.fullCount = response.responseXML.documentElement.getElementsByTagName("fullcount")[0].firstChild.nodeValue;
                    
                    if(this.data) {
                        this.renderMessages();
                        return true;
                    } 
                } catch(e) {}
            } 
            
        } 
        this.setConfigState();
    }


    this.setConfigState = function() {
    	this.elements.loading.innerHTML = '';
        this.setTitle(this.profile.title);
        this.showElement("config_note");
        this.hideElement("messages_area");
    }


    this.switchMailsContent = function() {
        if(this.data.items) {
            var count = Math.min(this.data.items.length, this.profile.newsCount);
            for(var i=0; i<count; i++) {
                if(this.elements.switcher.checked) {
                    this.showElement("mail_content" + i);
                } else {
                    this.hideElement("mail_content" + i);
                }
            }
        }
    }


    this.renderMessages = function() {
    	this.elements.loading.innerHTML = '';
        this.elements.title.innerHTML = '';
        this.buildDomModel(this.elements.title, 
                           createButtonDom(this.profile.title, "openInbox()"));
        if(this.data && this.data.items.length > 0) {
            this.hideElement("msg_no_new_mails");
            this.hideElement("config_note");
            this.showElement("messages_area");
            this.elements.mail_list.innerHTML = '';

            this.elements.mail_total.innerHTML = '<b>' + loc.text("gmail_msg_total", this.fullCount) + '</b>';
            this.elements.switcher.checked = false;


            var count = Math.min(this.data.items.length, this.profile.newsCount);

            for(var i=0; i<count; i++) {
                try {
                    if(this.data.items[i].author) {
                        var from = this.data.items[i].author["name"] ? this.data.items[i].author["name"] : this.data.items[i].author["email"];
                    } else {
                        var from = "[...]";
                    }
                    var subj = this.data.items[i].title ? this.data.items[i].title : "[...]";
                    var content = this.data.items[i].summary ? this.data.items[i].summary : "[...]";
                    this.buildDomModel(this.elements.mail_list, 
                        { tag: "div", className: "menu_panel",
                          childs: [
                            { tag: "a", sysHref: this.data.items[i].link.href, target: "_blank",
                              innerHTML: "<b>" + from + "</b> - " + subj },
                            { tag: "div", id: "mail_content"+i, className: "note", display: false,
                              innerHTML: content }
                          ]
                        });
                } catch(e) {}
            }
        } else {
            //this.showElement("msg_no_new_mails");
        }
    }


    this.openInbox = function() {
        window.open("http://mail.google.com/mail");
    }
    
    
    this.checkEnter = function(e){
		var characterCode
	 		if(e && e.which){
	 			e = e
	 			characterCode = e.which
	 		}
	 		else{
	 			e = event
	 			characterCode = e.keyCode
	 			}	 
	 		if(characterCode == 13){
 	 			this.saveProfile();
 	 			return false
	 		}
		return true	
}

}
Gmail.prototype = new Widget();

function YahooMail() {
    this.init();


    this.cfg = {
        hasSettingsBtn: true,
        title: "",
        module: "YahooMail"
    }


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_mcount")},
            { tag: "select", id: "inp_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:"20", text: "20"}
              ]
            },
            { tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "setItemsCount()"}, className: "settings_control"}
          ]
        },

        { tag: "div", className: "settings_section", align: "center",
          innerHTML: "<b>"+ loc.text("popmail_asettings") + "</b>"},

        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "a", sysHref: "http://help.yahoo.com/help/us/mail/pop/pop-40.html",
              target: "_blank",
              html: loc.text("yahoomail_info") }
          ]},

        { tag: "div", className: "settings_section",
           childs: [ 
             { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_login")},
             { tag: "input", id: "select_login", type: "text", size: "15", className: "settings_control"} 
           ]},

        { tag: "div", className: "settings_section",
           childs: [ 
             { tag: "span", className: "settings_label", innerHTML: loc.text("popmail_inp_pwd")},
             { tag: "input", id: "select_password", type: "password", size: "15", className: "settings_control"} 
           ]},

        { tag: "div", className: "settings_section", align: "center",
          childs: [ 
            { tag: "input", type: "button", value: loc.text("btn_save"), events: {onclick: "saveProfile()"}} 
          ]},
		    		  { tag: "div", className: "cls"}
    ]


    this.domContent = [
        { tag: "div", className: "menu_panel", id: "messages", display: false,
          childs: [
            { tag: "div", className: "menu_panel", 
              style: { paddingLeft: "30px", background: "url(widgets/aolmail/ico.gif) no-repeat 0 0"},
              childs: [
                { tag: "b", html: loc.text("popmail_total") },
                { tag: "span", id: "total_messages"}
              ]},
            { tag: "div", id: "mail_list"}
          ]},

        { tag: "div", className: "menu_panel", id: "loading_note", display: false,
          style: { paddingLeft: "30px", background: "url(widgets/yahoomail/ico.gif) no-repeat 0 0"},
          innerHTML: loc.text("msg_loading")},

        { tag: "div", className: "menu_panel", id: "config_note", display: false,
          style: { paddingLeft: "30px", background: "url(widgets/yahoomail/ico.gif) no-repeat 0 0"},
          innerHTML: loc.text("popmail_msg_not_configured")},

        { tag: "div", className: "menu_panel", id: "no_messages_note", display: false,
          style: { paddingLeft: "30px", background: "url(widgets/yahoomail/ico.gif) no-repeat 0 0"},
          innerHTML: loc.text("popmail_msg_no_mails")}
    ]

    this.defaultProfile["login"] = "";
    this.defaultProfile["password"] = "";

    this.defaultProfile["title"] = "";
    this.defaultProfile["mcount"] = "8";


    var isLoading = false;

    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.buildDomModel(this.elements.content, this.domContent);

        this.elements.select_login.value = this.profile.login;
        this.elements.select_password.value = this.profile.password;
        this.elements.inp_count.value = this.profile.mcount;

        var t = this.profile.title != "" ? this.profile.title : loc.text("yahoomail_title");
        this.setTitle(t);
    }



    this.onOpen = function() {
        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.refresh();
        }
    }



    this.isProfileEmpty = function() {
        return this.profile.login == "" || this.profile.password == "";
    }


    this.setContent = function(section) {
        var sections = ["config_note", "loading_note", "messages", "no_messages_note"];
        for(var i = 0; i<sections.length; i++) {
            if(section == sections[i]) {
                showEl(this.elements[sections[i]]);
            } else {
                hideEl(this.elements[sections[i]]);
            }
        }
    }


    this.saveProfile = function() {
        var l = trim(this.elements.select_login.value);
        if(l.indexOf("@") != -1) {
            l = l.substr(0, l.indexOf("@"));
            this.elements.select_login.value = l;
        }
        var p = trim(this.elements.select_password.value); 

        if(this.profile.login != l || this.profile.password != p) {
            this.profile.login = l;
            this.profile.password = p;
            this.save();
        }

        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.refresh();
        }
    }


    this.setItemsCount = function() {
        var c = this.elements["inp_count"].value;
        if(this.profile.mcount != c) {
            this.profile.mcount = c;
            this.save();
            this.renderMessages();
        }
    }




    this.timerHandler = function() {
        if(this.isProfileEmpty()) {
            this.setContent("config_note");
        } else {
            this.refresh();
        }
    }


    this.req = null;
    this.timerId = null;

    this.refresh = function() {
        if(!this.isProfileEmpty() && !isLoading) {
            isLoading = true;
            this.setContent("loading_note");
            var protocol = "/pop3/ssl/novalidate-cert";

            this.req = request.send({ login: this.profile.login,
                                      password: this.profile.password,
                                      protocol: protocol,
                                      server: "pop.mail.yahoo.com",
                                      port: 995 }, this);

            var self = this;
            var f = function() {
                updateLoadingIcon(-1);
                self.req.onreadystatechange = function() {};
                self.isLoading = false;
                self.setContent("config_note");
            }
            this.timerId = setTimeout(f, 30000);
        }
    }



    this.renderMessages = function() {
        if(this.data) {
            this.setContent("messages");        
            this.elements.total_messages.innerHTML = "<B>" + this.totalMessages + "<B>";
            this.elements.mail_list.innerHTML = '';
            var cnt = Math.min(this.data.length, this.profile.mcount);
            for(var i=0; i<cnt; i++) {
                try {
                    this.buildDomModel(this.elements.mail_list,
                                       { tag: "div", className: "menu_panel", 
                                         innerHTML: "<B>" + this.data[i].from + "</B>",
                                         childs: [
                                           { tag: "div", className: "note", innerHTML: this.data[i].subj }
                                         ]
                                       });
                } catch(e) {}
            }
        }
    }


    this.dispatchMsg = function(msg) {
        clearTimeout(this.timerId);
        isLoading = false;
        switch(msg.status) {
            case "empty":
                this.setContent("no_messages_note");
                break;
            case "data":
                this.data = msg.data;
                this.totalMessages = msg.total;
                this.renderMessages();
                break;
            case "error":
                this.setContent("config_note");
                break;
        }
    }

}
YahooMail.prototype = new Widget();

function Bookmarks() {
    this.init();


    this.cfg = {
        hasRefreshBtn: false,
        title: loc.text("bookmarks_title"),
        module: "Bookmarks",
        saveMethod: "POST"
    }



    this.domSettings = [

        { tag: "div", className: "bevel_section", innerHTML: loc.text("bookmarks_import"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_import')"}
        },

        { tag: "div", className: "menu_panel", id: "section_import", display: false, align: "center", 
          innerHTML: "<iframe name='uiframe"+this.id+"' style='width: 0px; height: 0px; border: 0px'></iframe>",
          childs: [
            { tag: "form", method: "post", enctype: "multipart/form-data", action:"bookmarks.php", 
              target: "uiframe"+this.id,
              id: "upload_form",
              style: {padding: "0px", margin: "0px"},
              childs: [
                { tag: "input", type: "hidden", name: "MAX_FILE_SIZE", value:"500000"},
                { tag: "input", type: "hidden", id: "form_wid", name: "wid"},
                { tag: "input", type: "hidden", id: "form_user_id", name: "user_id"},
                { tag: "input", type: "file", name:"user_file", id: "user_file"},
                { tag: "input", type: "button", value: loc.text("bookmarks_btn_import"), id: "upload_submit_btn", events: {onclick: "uploadFile()"}}
              ]},
            { tag: "div", id: "import_msg", style: {width: "100%", display: "block"}, display: false}
          ]
        },

        { tag: "div", className: "bevel_section", innerHTML: loc.text("bookmarks_sec_delete"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_delete')"}
        },
        { tag: "div", className: "menu_panel", id: "section_delete", display: false, align: "center",
          childs: [
            { tag: "input", type: "button", value: loc.text("bookmarks_btn_delete_all"), events: {onclick: "deleteBookmarks()"}}
          ]
        },


        { tag: "div", className: "bevel_section", innerHTML: loc.text("bookmarks_sec_add"), id: "add_bookmark",
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_add')"}
        },

        { tag: "div", className: "menu_panel", id: "section_add", display: false, 
          childs: [
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_title"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "select_title"}
              ]
            },
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_url"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "select_url"}
              ]
            },              
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_tags"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "select_tags"}
              ]
            },              
            { tag: "div", className: "menu_panel", align: "center",
              childs: [
                { tag: "input", type: "button", value: loc.text("btn_save"), events: {onclick: "processAdd()"}}
              ]
            }
          ]
        },
	  { tag: "div", className: "cls"}
    ];


    this.domContent = [
        { tag: "div", className: "bevel_section", innerHTML: loc.text("bookmarks_sec_edit"), id: "edit_bookmark", display: false, 
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_edit')"}
        },

        { tag: "div", className: "menu_panel", id: "section_edit", display: false, 
          childs: [
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_title"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "edit_title"}
              ]
            },
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_url"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "edit_url"}
              ]
            },              
            { tag: "div", className: "menu_panel", innerHTML: loc.text("bookmarks_inp_tags"),
              childs: [
                { tag: "input", type: "text", size: "30", id: "edit_tags"}
              ]
            },              
            { tag: "div", className: "menu_panel", align: "center",
              childs: [
                { tag: "input", type: "button", value: loc.text("btn_save"), events: {onclick: "processUpdate()"}}
              ]
            }
          ]
        },

        { tag: "div", className: "bevel_section", innerHTML: loc.text("bookmark_sec_tags"),
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_tags')"}},

        { tag: "div", className: "menu_panel", id: "section_tags", display: false, align: "left"},

        { tag: "hr", width: "100%"},

        { tag: "div", className: "menu_panel", id: "bookmarks", align: "left"}
    ]

    this.defaultProfile["title"] = loc.text("bookmarks_title");
    this.defaultProfile["tags"] = ['default']; 
    this.defaultProfile["bookmarks"] = []; 

    this.activeTag = 0;

    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);        
        this.buildDomModel(this.elements.content, this.domContent);        
        this.applyTag(0);
        this.elements["form_wid"].value = this.id;
        this.elements["form_user_id"].value = auth.user.id;
    }


    this.onShowSettings = function() {
        this.closeEdit();
    }


    this.settingsSetTitle = function() {
        this.profile.title = trim(this.elements.input_title.value);
        this.setTitle(this.profile.title + ": "+ this.profile.tags[this.activeTag]);
        this.save();
    }

    this.switchSection = function(sid) {
        if(this.elements[sid].style.display == 'none') {
            showEl(this.elements[sid]);
        } else {
            hideEl(this.elements[sid]);
        }
    }



    // importing
    this.uploadFile = function() {
        if(trim(this.elements.user_file.value)!="") {
            showEl(this.elements.import_msg);
            this.elements.import_msg.innerHTML = loc.text("bookmarks_msg_import");
            hideEl(this.elements.upload_submit_btn);
            this.elements.upload_form.submit();
        }
    }




    this.processImported = function(links) {
        showEl(this.elements.upload_submit_btn);
        if(links) {
            for(var i=0; i<links.length; i++) {
                this.addBookmark(links[i][0], links[i][1], "Imported bookmaks");
            }
            this.renderTags();
            showEl(this.elements.section_tags);
            this.applyTag(this.activeTag);
            this.save();
            hideEl(this.elements.import_msg);
            hideEl(this.elements.section_import);
            this.hideSettings();
            this.elements.import_msg.innerHTML = "";
        } else {
            this.elements.import_msg.innerHTML = loc.text("bookmarks_msg_import_error");
        }
    }




    this.editBookmarkId = null;
    this.closeEdit = function() {
        if(this.editBookmarkId != null) {
            hideEl(this.elements.section_edit);
            hideEl(this.elements.edit_bookmark);
            this.isEditOpen = null;
        }
    }

    this.openEdit = function(id) {
        this.editBookmarkId = id;

        var tags = [];
        for(var i = 0; i < this.profile.bookmarks[id].tags.length; i++) {
            tags.push(this.profile.tags[this.profile.bookmarks[id].tags[i]])
        }
        this.elements.edit_title.value = this.profile.bookmarks[id].title;
        this.elements.edit_url.value = this.profile.bookmarks[id].url;
        this.elements.edit_tags.value = tags.join(", ");

        showEl(this.elements.section_edit);
        showEl(this.elements.edit_bookmark);
        hideEl(this.elements.settings);
    }


    this.processUpdate = function() {
        if(this.editBookmarkId != null) {
            var title = trim(this.elements.edit_title.value);
            var url = trim(this.elements.edit_url.value);
            if(title != "" && url != "") {
                this.updateBookmark(this.editBookmarkId, title, url, trim(this.elements.edit_tags.value));

                this.applyTag(this.activeTag);
                this.save();
            }
        }
        this.closeEdit();
    }




    this.deleteBookmarks = function() {
        this.profile.bookmarks = this.defaultProfile["bookmarks"];
        this.profile.tags = this.defaultProfile["tags"];
        this.applyTag(0);
    }



    this.processAdd = function() { 
        var title = trim(this.elements.select_title.value);
        var url = trim(this.elements.select_url.value);
        if(title != "" && url != "") {
            this.closeEdit();
            this.addBookmark(title, url, trim(this.elements.select_tags.value));
            this.save();
            this.applyTag(this.activeTag);

            this.elements.select_title.value = '';
            this.elements.select_url.value = '';
            this.elements.select_tags.value = '';
        }
    }




    this.renderTags = function() {
        this.elements.section_tags.innerHTML = '';
        for(var t=0; t<this.profile.tags.length; t++) {
            if(this.profile.tags[t] != undefined) {
                if(this.activeTag != t) {
                    this.buildDomModel(this.elements.section_tags,
                        { tag: "a", 
                          href: "void", events: { onclick: "applyTag("+t+")"}, 
                          innerHTML: this.profile.tags[t],
                          style: { margin: "4px"}
                        });
                } else {
                    this.buildDomModel(this.elements.section_tags,
                        { tag: "span", innerHTML: this.profile.tags[t],
                          style: { margin: "4px"}
                        });
                }
            }
        }
    }





    this.applyTag = function(tagId) {
        this.closeEdit();
        this.activeTag = tagId;
        this.setTitle(this.profile.title + ": "+ this.profile.tags[tagId]);

        var list = this.getBookmarksByTagId(tagId);

        this.elements.bookmarks.innerHTML = '';
        for(var i = 0; i<list.length; i++) {
            var itemDom = { tag: "div", className: "menu_panel", id: "item"+list[i],
                            childs: [
                              createTableDom([ {content: {tag: "a", id: "item_title"+list[i], sysHref: this.profile.bookmarks[list[i]].url, target: "_blank", innerHTML: this.profile.bookmarks[list[i]].title}, width: "95%"},
                                               {content: createButtonDom(false, "openEdit("+list[i]+")", "static/client/edit.gif"), width: "1%"},
                                               {content: createButtonDom(false, "deleteItem("+list[i]+")", "static/client/delete_link.gif"), width: "1%"}
                                             ], "95%")
                            ]
                          }
            this.buildDomModel(this.elements.bookmarks, itemDom);
        }

        this.renderTags();
    }


    this.deleteItem = function(id) {
        if(confirm(loc.text("bookmarks_delete_prompt", this.profile.bookmarks[id].title))) {
            this.closeEdit();
            this.deleteBookmark(id);
            if(this.profile.tags[this.activeTag]) {
                this.applyTag(this.activeTag);
            } else {
                this.applyTag(0);
            }
            this.save();
        }
    }



    this.updateBookmark = function(id, title, url, tags) {
        this.deleteBookmark(id);
        this.addBookmark(title, url, tags);    
    }


    this.addBookmark = function(title, url, tagsData) {
        var newBookmark = { title: title, 
                            url: url, 
                            tags: [] };

        if(typeof(tagsData) == "string") {
            var tags = tagsData!= "" ? tagsData.split(",") : false;
        } else {
            var tags = tagsData;
        }

        if(tags) {
            for(var i = 0; i<tags.length; i++) {
                tags[i] = trim(tags[i]);
                var tn = arraySearch(tags[i], this.profile.tags)
                if(tn != undefined) {
                    newBookmark.tags.push(tn);
                } else {
                    var idx = arrayFirstFree(this.profile.tags);
                    this.profile.tags[idx] = tags[i];
                    newBookmark.tags.push(idx);
                }
            }
        } else {
            newBookmark.tags = [0];
        }

        this.activeTag = newBookmark.tags[0];
        this.profile.bookmarks[arrayFirstFree(this.profile.bookmarks)] = newBookmark;
    }



    this.deleteBookmark = function(id) {
        var tags = this.profile.bookmarks[id].tags;
        for(var i=0; i<tags.length; i++) {
            if(tags[i] != 0) {
                var count = 0;
                for(var j=0; j<this.profile.bookmarks.length; j++) {
                    if(this.profile.bookmarks[j] && arraySearch(tags[i], this.profile.bookmarks[j].tags) != undefined) {
                        count++;
                    }
                }
                if(count<2) {
                    this.profile.tags[tags[i]] = undefined;
                }
            }
        }
        this.profile.bookmarks[id] = undefined;
    }


    this.getBookmarksByTagId = function(tagId) {
        var res = [];

        for(var i=0; i<this.profile.bookmarks.length; i++) {
            if(this.profile.bookmarks[i] && 
               this.profile.bookmarks[i].tags != undefined &&
               arraySearch(tagId, this.profile.bookmarks[i].tags) != undefined) {
                res.push(i);
            }
        }
        return res;
    }

 
}
Bookmarks.prototype = new Widget();

function ToDoList() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        title_prefix: loc.text("todolist_title_prefix"),
        title: "",
        module: "ToDoList"
    }


    this.defaultProfile["items"] = [];
    this.defaultProfile["title"] = "";



    this.domSettings = [
           { tag: "div", className: "settings_section",
              childs: [
                  { tag: "span", innerHTML: loc.text("todolist_inp_todo"), className: "settings_label"},
                  {tag: "input", id: "todo_title", type: "text", size: "15", className: "settings_control"},
                  {tag: "input", type: "button", value: loc.text("btn_add"), events: {onclick: "addItem()"}, className: "settings_control button"}
              ]},
  		  { tag: "div", className: "cls"}
    ]

    this.domContent = { tag: "table", className: "sys_table", id: "items_table",
                        width: "100%",
                        childs: [] }


    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.renderItems();
    }


    this.onOpen = function() {
        this.setTitle(this.profile.title);
    }

    this.setTitle = function(html) {
    	var str = this.cfg.title_prefix + html.truncate(15) ;
        this.elements.title.innerHTML = str;        
    }


    this.renderItems = function() {
        this.elements.content.innerHTML = "";
        this.buildDomModel(this.elements.content, this.domContent);
        for(var i=0; i<this.profile.items.length; i++) {
            this.renderItem(i);
        }
    }

    this.renderItem = function(n) {
        this.buildDomModel(this.elements.items_table_tbody,
            { tag: "tr", id: "item"+n,
              childs: [
                { tag: "td", width: "1%",
                  childs: [
                    { tag: "input", id: "item_checkbox"+n, type: "checkbox", events: {onclick: "switchItem("+n+")"}, checked: this.profile.items[n].completed}
                  ]},
                { tag: "td", width: "95%",
                  childs: [
                    { tag: "div",
                      style: {textDecoration: this.profile.items[n].completed ? "line-through" : "", overflow: "hidden"},
                      id: "item_title"+n, innerHTML: this.profile.items[n].title.wordWrap(10) }
                  ]},

                { tag: "td", width: "1%",
                  childs: [ createButtonDom(false, "moveItemUp("+n+")", "static/client/move_up.gif") ]},

                { tag: "td", width: "1%",
                  childs: [ createButtonDom(false, "moveItemDown("+n+")", "static/client/move_down.gif") ]},

                { tag: "td", width: "1%",
                  childs: [ createButtonDom(false, "editItem("+n+")", "static/client/edit.gif") ]},

                { tag: "td", width: "1%",
                  childs: [ createButtonDom(false, "deleteItem("+n+")", "static/client/delete_link.gif") ]}
              ]
            });
    }


    this.addItem = function() {
        var title = trim(this.elements.todo_title.value);
        if(!title) {
            return;
        }

        var newId = this.profile.items.length;
        var newItem = {title: title, completed: false};
        this.profile.items[newId] = newItem;
        this.renderItem(newId);
        this.save();

        this.elements.todo_title.value = '';
    }


    this.switchItem = function(id) {
        this.profile.items[id].completed = !this.profile.items[id].completed;
        this.elements['item_title'+id].style.textDecoration = this.profile.items[id].completed ? "line-through" : "" ;
        this.save();
    }


    this.moveItemUp = function(id) {
          if(id > 0) {
            this.swapItems(id, id-1);
            this.renderItems();
            this.save();
        }
    }

    this.moveItemDown = function(id) {
        if(id < this.profile.items.length - 1) {
            this.swapItems(id, id+1);
            this.renderItems();
            this.save();
        }
    }


    this.editItem = function(id) {
        var res = trim(prompt(loc.text("todolist_todo_edit"), this.profile.items[id].title));
        if(res) {
            this.profile.items[id].title = res;
            this.elements['item_title'+id].innerHTML = res.wordWrap(10);
        }
        this.save();
    }



    this.deleteItem = function(id) {
        if(confirm(  loc.text("todolist_delete_confirm", this.profile.items[id].title)  )) {
            var tmp = [];
            for(var i=0; i<this.profile.items.length; i++) {
                if(i != id) {
                    tmp.push(this.profile.items[i]);
                }
            }
            this.profile.items = tmp;
            tmp = null;
            this.renderItems();
            this.save();
        }
    }



    this.swapItems = function(a,b) {
        var tmp = this.profile.items[a];
        this.profile.items[a] = this.profile.items[b];
        this.profile.items[b] = tmp;
    }    
}
ToDoList.prototype = new Widget();

function Webnote() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        title: loc.text("webnote_title"),
        module: "Webnote"
    }

    this.defaultProfile["title"] = this.cfg.title;
    this.defaultProfile["text"] = loc.text("webnote_text");


    this.contentDomWebnote = [
        { tag: "div", id: "text_show", 
          className: "webnote_text"},
        { tag: "textarea", id: "text_edit", 
          display: false,
          className: "webnote_textarea",
          events: {onclick: "applyText()", onblur: "showText()"}}
    ]


    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.content, this.contentDomWebnote);

        var text_show = this.elements.text_show;
        var text_edit = this.elements.text_edit;
        var widget = this;

        this.elements.text_show["onclick"] = function() { widget.editText(widget, text_show, text_edit); };

        var t = this.profile.text.jsUnescape();
        this.elements.text_show.innerHTML = text2html(t).parseUrl();
        this.elements.text_edit.value = t;
        this.setTitle(this.profile.title);
    }


    this.editText = function(widget, text_show, text_edit) {
        var h = text_show.offsetHeight;
        hideEl2(text_show);
        showEl2(text_edit);

        text_edit.style.height = (h+16)+"px";
        text_edit.focus();

        text_edit.onkeyup = function() {
 			text_show.innerHTML = text2html(this.value);
 			showEl2(text_show);
 			this.style.height = (text_show.offsetHeight+16) + "px";
 			hideEl2(text_show);
 		}

        text_edit.onblur = function() {
            text = this.value.replace(/\\/g, "");
            this.onblur = null;
            hideEl2(this);
            htmlText = text2html(text);
            text_show.innerHTML = htmlText.jsUnescape().parseUrl();
            text_show.style.display = "block";
            text_show.onclick =  function() { widget.editText(widget, text_show, text_edit); };
            widget.profile.text = text.jsEscape();
            widget.save();
		}
    }

    this.showText = function() {}
    this.applyText = function() {}

}
Webnote.prototype = new Widget();

function Flash() {
    this.init();


    this.cfg = {
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        itemsDir: 'var/flash/',
        title: loc.text("flash_title"),
        module: "Flash"
    }

    this.flash_catalog = [];    


    this.domContent = [
        { tag: "div", className: "menu_panel", id: "controls", display: false,
          childs: [
            createTableDom([{content: createButtonDom(loc.text("flash_open"), "openPlayer()", "widgets/flash/img/full_screen.gif"), width: "70%"},
                            {content: createButtonDom(loc.text("flash_stop"), "stopFlash()", "widgets/flash/img/stop.gif"), width: "30%"}]),
          ]
        },

        { tag: "div", style: {padding: "0px", margin: "0px"}, id: "flash_content", 
          childs: [
            { tag: "div", id: "flash_container", style: {width: "100%", height: "100%"} }
          ]
        },
        { tag: "div", className: "menu_panel", id: "flash_cat_content0", display: false }
    ];


    this.defaultProfile["file"] = "";
    this.defaultProfile["title"] = loc.text("flash_title");


    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.content, this.domContent);
        this.switchFlashCategory(0);
        this.setTitle(this.profile.title);
        if(this.profile.file != "") {
            this.loadFlash();
        }
    }


    this.openPlayer = function() {
        flashPlayer.openFlash(this.id);
    }


    this.stopFlash = function() {
        this.elements.flash_container.innerHTML = '';
        hideEl(this.elements.flash_content);
        hideEl(this.elements.controls);

        this.profile.title = this.cfg.title;
        this.profile.file = "";
        this.setTitle(this.profile.title);
        this.save();
    }



    this.switchFlashCategory = function(catId) {
        var el = this.elements["flash_cat_content"+catId];
        if(el.style.display == 'none') {
            if(this.flash_catalog[catId]) {
                if(this.flash_catalog[catId].rendered) {
                    el.style.display = 'block';
                } else {
                    this.renderFlashCategory(catId);
                }
            } else {
                el.innerHTML = loc.text("msg_loading");
                el.style.display = 'block';
                request.send({act: "get_flash_category", cat_id: catId}, this);
            }
            if(catId != "0") {
                this.elements["fico_" + catId].setAttribute("src", menu.folder_o.src);
            }
        } else {
            if(catId != "0") {
                this.elements["fico_" + catId].setAttribute("src", menu.folder_s.src);
            }
            el.style.display = 'none';
        }
    }


    this.renderFlashCategory = function(catId, silent) {
        el = this.elements["flash_cat_content"+catId];
        el.innerHTML = '';
        with(this.flash_catalog[catId]) {
            if(categories) {
                for(var i=0; i<categories.length; i++) {
                    this.buildDomModel(el, 
                      { tag: "div", className: "menu_panel", id: "flash_cat"+categories[i].id, 
                        childs: [
                          createButtonDom(categories[i].name, 
                                          "switchFlashCategory("+categories[i].id+")", 
                                          menu.folder_s.src,
                                          null,
                                          "fico_" + categories[i].id),
                          { tag: "div", id: "flash_cat_content"+categories[i].id, className: "menu_sub_panel", display: false }
                        ]
                      });
                }
            }

            if(items) {
                for(var i=0; i<items.length; i++) {
                    this.buildDomModel(el, 
                      { tag: "div", className: "menu_panel", id: "flash_cat_item"+items[i].id, 
                        childs: [
                          createButtonDom(items[i].title, 
                                          "openFlash('"+items[i].file+"', '"+items[i].title.addSlashes()+"')", 
                                          "widgets/flash/img/item.gif", 
                                          "flash_cat_item"+items[i].id)
                        ]
                      });
                }
            }  

            if(!items  &&  !categories) {
                el.innerHTML = loc.text("msg_empty");
            }

            rendered = true;
        }

        if(!silent) {
            el.style.display = 'block';
        }
        this.flash_catalog[catId].rendered = true;
    }



    this.openFlash = function(file, title) {
        this.profile.title = title;
        this.profile.file = file;
        this.loadFlash(file, title);
        this.save();
    }

    this.loadFlash = function() {
        if(this.profile.file) {
            showEl(this.elements.controls);
            this.setTitle(this.profile.title);

            showEl(this.elements.flash_content);

            this.elements.flash_content.style.height = "200px";

            this.elements.flash_container.style.height = "100%";
            this.elements.flash_container.align = "center";
            this.elements.flash_container.innerHTML = '';
            var h = (mozilla_nav ? "90%" : "100%");
            this.elements.flash_container.innerHTML = 
                 '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+
                 '        codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=5,0,0,0" '+
                 '        height='+h+' width=100%>'+
                 '<param name=movie '+
                 '       value="'+this.cfg.itemsDir+this.profile.file+'">'+
                 '<param name=quality value=high>'+
                 '<param name=bgcolor value=#ffffff>'+
                 '<embed src="'+this.cfg.itemsDir+this.profile.file+'" '+
                 '       quality=high bgcolor=#FFFFFF '+
                 '       height='+h+' width=100%'+
                 '       type="application/x-shockwave-flash" '+
                 '       pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>'+
                 '</object>';
        }
    }


    this.dispatchMsg = function(msg) {
        switch (msg.status) {

            case "flash_category_data":
                this.flash_catalog[msg.cat_id] = { categories: msg.categories, items: msg.items};
                this.renderFlashCategory(msg.cat_id);
                break;
        }
    }
 
}
Flash.prototype = new Widget();

function Flickr() {
	this.init();

	this.cfg = {
		title: loc.text("flickr_title"),
		module: "Flickr"
		// Caption settings button (show/hide widget settings panel).
		// Default value: true
	}



	this.defaultProfile["tags"] = "";
	this.defaultProfile["layout"] = "s"; // s|t
	this.defaultProfile["target"] = "s"; // s|f

	this.ctag  = 1;



	this.tagUrl = "http://www.flickr.com/services/feeds/photos_public.gne?format=rss_200";

	this.domSettings = [
	//	{ tag: "div", className: "settings_section",
	//	childs: [
	//	{ tag: "span", innerHTML: loc.text("flickr_inp_tags"), className: "settings_label"},
	//	{ tag: "input", type: "text", size: "15", id: "selectTags", className: "settings_control"},
	//	{ tag: "input", type: "button", events: {onclick: "setTags()"}, value: loc.text("btn_search"), className: "settings_control"},
	//	]},

	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: loc.text("flickr_inp_layout"), className: "settings_label"},
	{ tag: "select", id: "selectLayout", events: {onclick: "setLayout()"}, className: "settings_control",
	options: [
	{ value:"s", text: loc.text("flickr_slides")},
	{ value:"t", text: loc.text("flickr_thumbs")}
	]
	}
	]},


	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: loc.text("flickr_open_to"), className: "settings_label"},
	{ tag: "select", id: "selectTarget", events: {onclick: "setTarget()"}, className: "settings_control",
	options: [
	{ value:"s", text: loc.text("flickr_to_site")},
	{ value:"f", text: loc.text("flickr_to_full")}
	]
	}
	]},
	{ tag: "div", className: "cls"}
	]


	this.domContent = [ { tag: "div", className: "", id: "head", display: true,
	style: { textAlign: "center"},
	childs: [
	{tag : "img" , className : "hand" , id : "flickrNext" , src : "widgets/flickr/img/previous.gif"    , events : { onclick : "showNextPhoto()" }},
	{ tag: "span", innerHTML: "&nbsp;"},
	{tag : "img" , className : "hand" ,id : "flickrPrev" , src : "widgets/flickr/img/next.gif"    , events : { onclick : "showPrevPhoto()" }},

	]
	},
	{ tag: "div", className: "flickr", id: "view_big", style: {textAlign: "center"}, display: false,
	childs: [
	{ tag: "a", href: "void", events: {onclick: "openBigPhoto()"},
	childs: [
	{ tag: "img", id: "big_photo" }
	]}
	]},
	{ tag: "div", className: "flickr", id: "view_thumbs", style: {textAlign: "center"}, display: false }];


	this.onBuildInterface = function() {
		this.elements["settings"].innerHTML = "";
		this.buildDomModel(this.elements.settings, this.domSettings);
		this.buildDomModel(this.elements.content, this.domContent);
		//this.elements.selectTags.value = this.profile.tags;
		this.elements.selectLayout.value = this.profile.layout;
		this.elements.selectTarget.value = this.profile.target;
	}


	this.setLayout = function() {
		this.profile.layout = this.elements.selectLayout.value;
		this.save();
		this.renderPhotos();
	}

	this.setTarget = function() {
		this.profile.target = this.elements.selectTarget.value;
		this.save();
	}

	this.setTags = function() {
		//  var tags = trim(this.elements.selectTags.value);
		tags = "ksa,nature,car,mountain,islam,animals,camels";
		if(tags != "") {
			this.profile.tags = tags;
			this.save();
			this.refresh();
		}
	}


	this.onOpen = function() {
		this.refresh();
	}

	this.refresh = function() {
		try{

		tags = new Array("ksa","nature","car","mountain","islam","animals","camels");
	
		tag = tags[Math.ceil(Math.random()*(tags.length - 1) + 1)];
		if(tag){
			this.ctag = tag;
		}

		this.setTitle(loc.text("msg_loading"));
		xmlRequest.send(this.tagUrl + "&tags="+this.ctag.urlencode(), this, "showPhotos");

		}catch(e){
			
		}

	}


	this.renderPhotos = function() {
		try{
		if(this.data) {
			if(this.profile.layout == "s") {
				if(this.data.items.length > 1) {
					showEl2(this.elements.head);
				} else {
					hideEl2(this.elements.head);
				}
				this.curPhoto = 0;
				this.showBigPhoto(this.curPhoto);
			} else {
				this.showAllPhotos();
			}
		}
		}catch(e){
			
		}
	}


	/// photo rotate

	this.curPhoto = 0;

	this.showPrevPhoto = function() {
		this.curPhoto--;
		if(this.curPhoto<0) {
			this.curPhoto = this.data.items.length-1;
		}
		this.showBigPhoto(this.curPhoto);
	}

	this.showNextPhoto = function() {
		this.curPhoto++;
		if(this.curPhoto >= this.data.items.length) {
			this.curPhoto = 0;
		}
		this.showBigPhoto(this.curPhoto);
	}
  

	// show photos

	this.showBigPhoto = function(n) {
		hideEl2(this.elements.view_thumbs);
		showEl2(this.elements.view_big);
		if(this.data.items.length > 0) {
			var src = this.data.items[n]["media:thumbnail"]["url"];
			src = src.substr(0, src.length-5) + 'm.jpg';
			if(ie_nav) {
				preloadImg(this.elements.big_photo, src);
			} else {
				this.elements.big_photo.src = src;
			}
			showEl2(this.elements.head);
		} else {
			this.elements.view_thumbs.innerHTML = 'لا يوجد نتائج بحث';
			hideEl2(this.elements.head);
			showEl2(this.elements.view_thumbs);
		}

	}


	this.showAllPhotos = function() {
		showEl2(this.elements.view_thumbs);
		hideEl2(this.elements.view_big);
		hideEl2(this.elements.head);
		if(this.data.items.length > 0) {
			var photosDom = [];
			for(var i=0; i<this.data.items.length; i++) {
				photosDom[photosDom.length] = { tag: "a", href: "void", events: {onclick: "openPhoto("+i+")"},
				innerHTML: "<img width=75 src='"+this.data.items[i]["media:thumbnail"].url+"'> "};
			}
			this.elements.view_thumbs.innerHTML = '';
			this.buildDomModel(this.elements.view_thumbs, photosDom);
		} else {
			this.elements.view_thumbs.innerHTML = 'لا يوجد نتائج بحث';
			//this.buildDomModel(this.elements.view_thumbs, photosDom);
		}

	}


	this.openBigPhoto = function() {
		this.openPhoto(this.curPhoto);
	}

	this.openPhoto = function(n) {
		open((this.profile.target == "s") ? this.data.items[n].link : this.data.items[n]["media:content"].url);
	}



	this.showPhotos = function(response) {
		if(response.responseXML.documentElement) {
			this.data = XMLParser.xml2hash(response.responseXML.documentElement);
			if(this.data) {
				this.setTitle(loc.text("flickr_title"));
				this.renderPhotos();
			}else{
				this.refresh();
			}
		}
	}


}
Flickr.prototype = new Widget();

function FoxVideo() {
    this.init();

    this.cfg = {
        title: "",
        module: "FoxVideo"
    };


    this.channels = [
    	{text:"Top News", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=Top%20News&title=Fox%20Sports%20video%20-%20Top%20news&p=33"},
		{text:"Most Watched", value:"http://rss.video.msn.com/s/us/rss.aspx?t=hotVideo&c=topsports&title=%20MSN%20Video%20-%20sports&p=05"},		
		{text:"MLB", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=Baseball%20News&title=Fox%20Sports%20video%20-%20Baseball%20News&p=33"},
		{text:"NFL", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=NFL%20News&title=Fox%20Sports%20video%20-%20NFL%20news&p=33"},
		{text:"NCAA FB", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=College%20FB%20News&title=Fox%20Sports%20video%20-%20College%20FB%20News&p=33"},
		{text:"NBA", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=NBA%20News&title=Fox%20Sports%20video%20-%20NBA%20news&p=33"},
		{text:"NHL", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=Hockey%20News&title=Fox%20Sports%20video%20-%20Hockey%20news&p=33"},
		{text:"NCAA BK", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=College%20BK%20News&title=Fox%20Sports%20video%20-%20College%20BK%20News&p=33"},
		{text:"NASCAR", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=More%20Fox%20Sports&title=Fox%20Sports%20video%20-%20More%20Fox%20Sports%25&p=33"},
		{text:"GOLF", value:"http://rss.video.msn.com/s/us/rss.aspx?t=Fox%20Sports&c=More%20Fox%20Sports&title=Fox%20Sports%20video%20-%20More%20Fox%20Sports%25&p=33"}
    ];


    this.defaultProfile["title"] = "";
    this.defaultProfile["channel"] = "0";
    this.defaultProfile["count"] = "6";

    var isLoading = false;
    var req = null;
    var content = null;
    var itemsCount = 25;

    var sel_count_options = [];
    for(var i=1; i<=itemsCount; i++) {
        sel_count_options.push({value: i, text: " " + i + " "});
    }

    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("foxvideo_inp_channel"), className: "settings_label"},
            { tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
              options: this.channels }
          ]},

        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("foxvideo_inp_count"), className: "settings_label"},
            { tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
              options: sel_count_options }
          ]},
   		  { tag: "div", className: "cls"}
    ]



    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements["inp_channel"].selectedIndex = this.profile.channel;
        this.elements["inp_count"].value = this.profile.count;
    }


    this.setChannel = function() {
        if(isLoading) {
            this.elements["inp_channel"].selectedIndex = this.profile.channel;
        } else {
            var c = this.elements["inp_channel"].selectedIndex;
            if(c != this.profile.channel) {
                this.profile.channel = this.elements["inp_channel"].selectedIndex;
                this.save();
                req = null;
                isLoading = false;
                this.refresh();
            }
        }
    }


    this.setCount = function() {
        var c = this.elements["inp_count"].value;
        if(c != this.profile.count) {
            this.profile.count = c;
            this.save();
            this.renderContent();
        }
    }


    this.onOpen = function() {
        this.refresh();
    }




    this.refresh = function() {
        if(!isLoading) {        
            this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
            req = xmlRequest.send(this.channels[this.profile.channel].value, this, "parseContent");
            isLoading = true;
        }
            if(this.isReduced) {
				this.show();
			}             
    }


    this.parseContent = function(response) {
        isLoading = false;
        if(response.responseXML && response.responseXML.documentElement) {
            content = XMLParser.xml2hash(response.responseXML.documentElement);
        } else {
            content = null;
        }
        this.renderContent();
    }

    

    this.renderContent = function() {    
        if(content) {
        
            if(this.profile.title != "") {
                this.setTitle(this.profile.title);
            } else {
                this.setTitle(content.title);
            }
            var l = Math.min(content.items.length, this.profile.count);
            var c = "";
            var st = "";

            for(var i=0; i<l; i++) {
                st = i % 2 ? "background: #F0F0F0;" : "";
                var lnk = content.items[i]["link"];
                c += "<tr style='"+st+"'>"+
                     "<td valign=top style='padding: 4px;'><a href='"+lnk+"' target=_blank><img width='85' height='65' style='border: 0' src='"+ content.items[i].enclosure.url +"'/></a></td>"+
                     "<td style='padding: 4px;'><a href='"+lnk+"' target=_blank><b>"+content.items[i].title+"</b></a>"+
                     "<p>" +content.items[i].description.substring(0,100) + "</td>" +
                     "</tr>";
            }
            
            this.elements["content"].innerHTML = '';                         
            this.elements["content"].innerHTML = "<table class='plan_table'>" + c + "</table>";
        } else {
            this.setTitle(loc.text("msg_error"));
        }
    }
 
}
FoxVideo.prototype = new Widget();

function AolVideo() {
    this.init();

    this.cfg = {
        title: "",
        module: "AolVideo"
    };


    this.channel = "http://spinner.aol.com/musicsessions/sessions_archive.adp";

    this.defaultProfile["title"] = "";
    this.defaultProfile["count"] = "6";

    var loading = false;
    var req = null;
    var content = null;
    var itemsCount = 25;

    var sel_count_options = [];
    for(var i=1; i<=itemsCount; i++) {
        sel_count_options.push({value: i, text: " " + i + " "});
    }

    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("aolvideo_inp_count"), className: "settings_label"},
            { tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
              options: sel_count_options }
          ]},
   		  { tag: "div", className: "cls"}
		  
    ]



    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements["inp_count"].value = this.profile.count;
    }


    this.setCount = function() {
        var c = this.elements["inp_count"].value;
        if(c != this.profile.count) {
            this.profile.count = c;
            this.save();
            this.renderContent();
        }
    }


    this.onOpen = function() {
        this.refresh();
    }



    this.refresh = function() {
        if(!loading) {
            this.setTitle(loc.text("msg_loading"));
            req = xmlRequest.send(this.channel, this, "parseContent");
            loading = true;
        }
    }


    this.parseContent = function(response) {
        loading = false;
        if(response.responseXML && response.responseXML.documentElement) {
            try {
                var doc = response.responseXML.documentElement;
                var items = doc.getElementsByTagName("session");
                content = [];

                var last = items.length - Math.min(itemsCount, items.length);
                if(last <0) { 
                    last = 0;
                }

                for(var i=items.length-1; i>last; i--) {
                    if(!items[i].getElementsByTagName("artistThumb")[0].firstChild) {
                        if(last > 0) last--;
                    } else {
                        content.push({
                            id: items[i].getAttribute("id"),
                            name: items[i].getElementsByTagName("artistName")[0].firstChild.nodeValue,
                            thumb: items[i].getElementsByTagName("artistThumb")[0].firstChild.nodeValue
                        });
                    }
                }
            } catch(e) { 
                content = null; 
            }
        } else {
            content = null;
        }
        this.renderContent();
    }

    

    this.renderContent = function() {
        if(content) {
            if(this.profile.title != "") {
                this.setTitle(this.profile.title);
            } else {
                this.setTitle(loc.text("aolvideo_title"));
            }
            var l = Math.min(content.length, this.profile.count);
            var c = "";
            var st = "";

            for(var i=0; i<l; i++) {
                st = i % 2 ? "background: #F0F0F0;" : "";
                var lnk = "http://music.aol.com/videos/sessions/sessions_flash.adp?ncid=AOLMUS00050000000052&defaultShow=" + content[i].id;
                c += "<tr style='"+st+"'>"+
                     "<td valign=top style='padding: 4px;' width=10%><a href='"+lnk+"' target=_blank><img style='border: 0' src='"+ content[i].thumb +"'/></a></td>"+
                     "<td style='padding: 4px;' valign=top>" + content[i].name + "<br>" + loc.text("aolvideo_session") + content[i].id + "<br>" +
                     "<a href='"+lnk+"' target=_blank>"+
                     "<img src='widgets/aolvideo/cam.gif' style='margin-right: 4px; height: 8px; border: 0; vertical-align: middle;'>"+
                     "<b>"+loc.text("aolvideo_lnk_watch")+"</b></a>"+"</td>" +
                     "</tr>";
            }
            this.elements["content"].innerHTML = "<table class='plan_table' width=99%>" + c + "</table>";
        } else {
            this.setTitle(loc.text("msg_error"));
        }
    }
 
}
AolVideo.prototype = new Widget();

function GoogleVideo() {
	this.init();

	this.cfg = {
		title: "",
		module: "GoogleVideo"
	};


	this.channels = [
	{text:"Popular", value:"http://video.google.com/videofeed?type=top100new&num=10"},
	{text:"Featured", value:"http://video.google.com/videofeed?type=search&q=is:forsale&so=1&num=10"},
	{text:"Comedy", value:"http://video.google.com/videofeed?type=search&q=genre:comedy&so=1&num=10"},
	{text:"Music", value:"http://video.google.com/videofeed?type=search&q=type:music_video&so=1&num=10"},
	{text:"TV Shows", value:"http://video.google.com/videofeed?type=search&q=type:tvshow&so=1&num=10"},
	{text:"Sports", value:"http://video.google.com/videofeed?type=search&q=type:sports%20OR%20genre:sports&so=1&num=10"},
	{text:"Education", value:"http://video.google.com/videofeed?type=search&q=genre:educational&so=1&num=10"}
	];


	this.defaultProfile["title"] = "";
	this.defaultProfile["channel"] = "0";
	this.defaultProfile["count"] = "6";

	var isLoading = false;
	var req = null;
	var content = null;
	var itemsCount = 10;

	var sel_count_options = [];
	for(var i=1; i<=itemsCount; i++) {
		sel_count_options.push({value: i, text: " " + i + " "});
	}

	this.domSettings = [
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: loc.text("googlevideo_inp_channel"), className: "settings_label"},
	{ tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
	options: this.channels }
	]},

	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: loc.text("googlevideo_inp_count"), className: "settings_label"},
	{ tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
	options: sel_count_options }
	]},
	{ tag: "div", className: "cls"}
	]



	this.onBuildInterface = function() {
		this.buildDomModel(this.elements.settings, this.domSettings);
		if(isNaN(parseInt(this.profile.channel))){
			this.profile.channel = 0;
		}
		this.elements["inp_channel"].selectedIndex = this.profile.channel;
		this.elements["inp_count"].value = this.profile.count;
	}


	this.setChannel = function() {
		if(isLoading) {
			this.elements["inp_channel"].selectedIndex = this.profile.channel;
		} else {
			var c = this.elements["inp_channel"].selectedIndex;
			if(c != this.profile.channel) {
				this.profile.channel = this.elements["inp_channel"].selectedIndex;
				this.save();
				req = null;
				isLoading = false;
				this.refresh();
			}
		}
	}


	this.setCount = function() {
		var c = this.elements["inp_count"].value;
		if(c != this.profile.count) {
			this.profile.count = c;
			this.save();
			this.renderContent();
		}
	}


	this.onOpen = function() {
		this.refresh();
	}




	this.refresh = function() {
		if(this.isReduced) {
			this.show();
		}
		if(!isLoading) {
			//this.setTitle(loc.text("msg_loading"));
			this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
			req = xmlRequest.send(this.channels[this.profile.channel].value, this, "parseContent");
			isLoading = true;
		}
	}


	this.parseContent = function(response) {
		isLoading = false;
		if(response.responseXML && response.responseXML.documentElement) {
			content = XMLParser.xml2hash(response.responseXML.documentElement);
			//            varpw(content);
		} else {
			content = null;
		}
		this.renderContent();
	}



	this.renderContent = function() {
		if(content) {
			if(this.profile.title != "") {
				this.setTitle(this.profile.title);
			} else {
				this.setTitle(content.title);
			}
			var l = Math.min(content.items.length, this.profile.count);
			var c = "";
			var st = "";

			for(var i=0; i<l; i++) {
				st = i % 2 == "1" ? "background: #F0F0F0;" : "";
				var lnk = content.items[i]["link"];

				c += "<tr style='"+st+"'>"+
				"<td valign=top style='padding: 4px;'><a href='"+lnk+"' target=_blank><img border=0 width=80 src='"+ content.items[i]["media:group"]["media:thumbnail"].url +"'/></a></td>"+
				"<td valign=top style='padding: 4px;'><a href='"+lnk+"' target=_blank><b>"+content.items[i]["media:group"]["media:title"]+"</b></a>"+
				"<p>" +content.items[i]["media:group"]["media:description"].truncate(150) + "</td>" +
				"</tr>";
			}
			this.elements["content"].innerHTML = '';
			this.elements["content"].innerHTML = "<table class='plan_table'>" + c + "</table>";
		} else {
			this.setTitle(loc.text("msg_error"));
		}
	}

}
GoogleVideo.prototype = new Widget();

function YoutubeVideo() {
    this.init();

    this.cfg = {
        title: "tube",
        module: "YoutubeVideo",
        hasTitle: false
    };

    


  this.channels = [
    	{text:"- القائمة -", value: "", isBold: true},
    	{text:"مقاطع مرئية حديثة", value: "http://tube.m3com.com.sa/rss.xml/view/source/newVideosCat/start/0/limit/15/cid/297"},
    	{text:"الأكثر تقييماَ", value: "http://tube.m3com.com.sa/rss.xml/view/source/topRatedVideosCat/start/0/limit/15/cid/297"},
    	{text:"الأكثر تعليقاَ", value: "http://tube.m3com.com.sa/rss.xml/view/source/mostCommentedVideosCat/start/0/limit/15/cid/297"},
    	{text:"الأكثر تعليقاَ لهذا الأسبوع", value: "http://tube.m3com.com.sa/rss.xml/view/source/mostCommentsThisWeekCat/start/0/limit/15/cid/297"},
    	{text:"الأكثر مشاهدة", value: "http://tube.m3com.com.sa/rss.xml/view/source/mostViewVideosCat/start/0/limit/15/cid/297"} 	
    ];



    this.defaultProfile["title"] = "";
    this.defaultProfile["channel"] = "1";
    this.defaultProfile["count"] = "6";

    var isLoading = false;
    var req = null;
    var content = null;
    var itemsCount = 15;

    var sel_count_options = [];
    for(var i=1; i<=itemsCount; i++) {
        sel_count_options.push({value: i, text: " " + i + " "});
    }

    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("clipat_inp_channel"), className: "settings_label"},
            { tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
              options: this.channels }
          ]},

        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("clipat_inp_count"), className: "settings_label"},
            { tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
              options: sel_count_options }
          ]},
   		  { tag: "div", className: "cls"}
    ]



    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements["inp_channel"].selectedIndex = this.profile.channel;
        this.elements["inp_count"].value = this.profile.count;
    }


    this.setChannel = function() {
        if(isLoading) {
            this.elements["inp_channel"].selectedIndex = this.profile.channel;
        } else {
            var c = this.elements["inp_channel"].selectedIndex;
            if(c != this.profile.channel && this.channels[c].value != "") {
                this.profile.channel = c;
                this.save();
                req = null;
                isLoading = false;
                this.refresh();
            }
        }
    }


    this.setCount = function() {
        var c = this.elements["inp_count"].value;
        if(c != this.profile.count) {
            this.profile.count = c;
            this.save();
            this.renderContent();
        }
    }


    this.onOpen = function() {
        this.refresh();
    }




    this.refresh = function() {
       if(this.isReduced) {
			this.show();
		}         
        if(!isLoading) {
            this.setTitle(loc.text("msg_loading"));            
            this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>'; 
            req = xmlRequest.send(this.channels[this.profile.channel].value, this, "parseContent");
            isLoading = true;  
       }
      
    }


    this.parseContent = function(response) {
        isLoading = false;
        if(response.responseXML) {            
			content = jQuery.xmlToJSON(response.responseXML);
			content = content.channel[0];            
//            varpw(content);
        } else {
            content = null;
        }
        this.renderContent();
    }

    
    this.renderContent = function() {
        if(content) {
           this.setTitle(loc.text("youtubevideo_title"));
            var l = Math.min(content.item.length, this.profile.count);
            var c = "";
            var st = "";

            for(var i=0; i<l; i++) {
                st = i % 2 == "1" ? "dark" : "";
                var lnk = "http://www.youtube.com/watch?v="+content.item[i].youtube_id[0].Text;
//                var lnk2 = content.items[i]["enclosure"].url;
                var lnk2 = lnk;
                c += "<tr class='"+st+"'>"+
                     "<td valign=top style='padding: 4px;'>"+
                     "<a href='"+lnk+"' target=_blank><img border=0 width=85 height=65 src='"+ content.item[i].thumbnail[0].Text +"'/></a>"+
                     "</td><td valign=top style='padding: 4px;'>"+
                     "<a href='"+lnk+"' target=_blank><b>"+content.item[i].title[0].Text+"</b></a><br class=half />" +                     
                                                              
                     "<br><span class=txt11>" + loc.text("clipat_watchCount") + "&nbsp " + content.item[i].total_views[0].Text + "</span>" +
                     "<br ><span class=txt11>" + loc.text("clipat_playingTime") + "&nbsp " + content.item[i].playing_time[0].Text + "</span>" +
                     "</td>"+
                     "</tr>";
            }
            this.elements["content"].innerHTML = "<table  width=100% cellspacing=0>" + c + "</table>";
        } else {
            this.setTitle(loc.text("msg_error"));
        }
    }
//
//    this.channels = [
//    	{text:"- مقاطع مرئية -", value: "", isBold: true},
//    	{text:"أضيفت حديثا", value: "http://youtube.com/rss/global/recently_added.rss"},
//    	{text:"مختارة حديثاً", value: "http://youtube.com/rss/global/recently_featured.rss"},
//    	{text:" الأكثر تفضيلاً", value: "http://youtube.com/rss/global/top_favorites.rss"},
//    	{text:"الأكثر تقييماً", value: "http://youtube.com/rss/global/top_rated.rss"},
//    	{text:"- المقاطع الأكثر مشاهدةً -", value: "", isBold: true},
//    	{text:"اليوم", value: "http://youtube.com/rss/global/top_viewed_today.rss"},
//    	{text:"هذا الأسبوع", value: "http://youtube.com/rss/global/top_viewed_week.rss"},
//    	{text:"هذا الشهر", value: "http://youtube.com/rss/global/top_viewed_month.rss"},
//    	{text:"جميع الأوقات", value: "http://youtube.com/rss/global/top_viewed.rss"},
//    	{text:"- المقاطع الأكثر نقاشاَ -", value: "", isBold: true},
//    	{text:"اليوم", value: "http://youtube.com/rss/global/most_discussed_today.rss"},
//    	{text:"هذا الأسبوع", value: "http://youtube.com/rss/global/most_discussed_week.rss"},
//    	{text:"هذا الشهر", value: "http://youtube.com/rss/global/most_discussed_month.rss"}
//    ];
//
//
//    this.defaultProfile["title"] = "";
//    this.defaultProfile["channel"] = "1";
//    this.defaultProfile["count"] = "6";
//
//    var isLoading = false;
//    var req = null;
//    var content = null;
//    var itemsCount = 15;
//
//    var sel_count_options = [];
//    for(var i=1; i<=itemsCount; i++) {
//        sel_count_options.push({value: i, text: " " + i + " "});
//    }
//
//    this.domSettings = [
//        { tag: "div", className: "settings_section", 
//          childs: [
//            { tag: "span", innerHTML: loc.text("googlevideo_inp_channel"), className: "settings_label"},
//            { tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
//              options: this.channels }
//          ]},
//
//        { tag: "div", className: "settings_section", 
//          childs: [
//            { tag: "span", innerHTML: loc.text("googlevideo_inp_count"), className: "settings_label"},
//            { tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
//              options: sel_count_options }
//          ]},
//  		  { tag: "div", className: "cls"}	  
//    ]
//
//
//
//    this.onBuildInterface = function() {
//        this.buildDomModel(this.elements.settings, this.domSettings);
//        this.elements["inp_channel"].selectedIndex = this.profile.channel;
//        this.elements["inp_count"].value = this.profile.count;
//    }
//
//
//    this.setChannel = function() {
//        if(isLoading) {
//            this.elements["inp_channel"].selectedIndex = this.profile.channel;
//        } else {
//            var c = this.elements["inp_channel"].selectedIndex;
//            if(c != this.profile.channel && this.channels[c].value != "") {
//                this.profile.channel = c;
//                this.save();
//                req = null;
//                isLoading = false;
//                this.refresh();
//            }
//        }
//    }
//
//
//    this.setCount = function() {
//        var c = this.elements["inp_count"].value;
//        if(c != this.profile.count) {
//            this.profile.count = c;
//            this.save();
//            this.renderContent();
//        }
//    }
//
//
//    this.onOpen = function() {
//        this.refresh();
//    }
//
//
//
//
//    this.refresh = function() {
//       if(this.isReduced) {
//			this.show();
//		}          
//        if(!isLoading) {
//            this.setTitle(loc.text("msg_loading"));
//            this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
//            req = xmlRequest.send(this.channels[this.profile.channel].value, this, "parseContent");
//            isLoading = true;
//        }
//    }
//
//
//    this.parseContent = function(response) {
//        isLoading = false;
//        if(response.responseXML && response.responseXML.documentElement) {
//            content = XMLParser.xml2hash(response.responseXML.documentElement);
////            varpw(content);
//        } else {
//            content = null;
//        }
//        this.renderContent();
//    }
//
//    
//
//    this.renderContent = function() {
//        if(content) {
//        /*
//            if(this.profile.title != "") {
//                this.setTitle(this.profile.title);
//            } else {
//                this.setTitle(content.title);
//            }
//*/
//this.setTitle(loc.text("youtubevideo_title"));
//            var l = Math.min(content.items.length, this.profile.count);
//            var c = "";
//            var st = "";
//
//            for(var i=0; i<l; i++) {
//                st = i % 2 == "1" ? "background: #F0F0F0;" : "";
//                var lnk = content.items[i]["link"];
//                var lnk2 = content.items[i]["enclosure"].url;
//                c += "<tr style='"+st+"'>"+
//                     "<td valign=top style='padding: 4px;'>"+
//                     "<a href='"+lnk+"' target=_blank><img border=0 width=85 height=65  src='"+ content.items[i]["media:thumbnail"].url +"'/></a>"+
//                     "</td><td valign=top style='padding: 4px;'>"+
//                     "<a href='"+lnk+"' target=_blank><b>"+content.items[i].title+"</b></a>" +
//
//                     "<br><br><a class='txt11' href='"+lnk2+"' target=_blank>"+
//                     "<img src='widgets/youtubevideo/cam.gif' style='margin-right: 4px; height: 8px; border: 0; vertical-align: middle;'>&nbsp"+
//                     loc.text("youtubevideo_lnk_watch")+"</a>"
//                                         
//                     "</td>"+
//                     "</tr>";
//            }
//            this.elements["content"].innerHTML = "<table class='plan_table' width=100%>" + c + "</table>";
//        } else {
//            this.setTitle(loc.text("msg_error"));
//        }
//    }
 
}
YoutubeVideo.prototype = new Widget();

function Weather() {
    this.init();

    this.cfg = {
        title: loc.text("weather_title"),
        module: "Weather"
    };

    this.defaultProfile["city"] = "SAXX0017";
    this.defaultProfile["unit"] = "c";
	//KSA Cities
	var KSACitis = [];
	KSACitis.push({value: 'SAXX0017', text: 'الرياض'});
	KSACitis.push({value: 'SAXX0013', text: 'مكة المكرمة'});
	KSACitis.push({value: 'SAXX0014', text: 'المدينة المنورة'});
	KSACitis.push({value: 'SAXX0002', text: 'الدمام'});
	KSACitis.push({value: 'SAXX0012', text: 'جدة'});
	KSACitis.push({value: 'SAXX0033', text: 'الطائف'});
	KSACitis.push({value: 'SAXX0027', text: 'تبوك'});
	KSACitis.push({value: 'SAXX0034', text: 'وادي الدواسر'});
	KSACitis.push({value: 'SAXX0019', text: 'شقرا'});
	KSACitis.push({value: 'SAXX0032', text: 'ينبع البحر'});
	KSACitis.push({value: 'SAXX0028', text: 'حائل'});
	KSACitis.push({value: 'SAXX0023', text: 'عرعر'});	
	KSACitis.push({value: 'SAXX0005', text: 'الجوف'});
	KSACitis.push({value: 'SAXX0038', text: 'نجران'});
	KSACitis.push({value: 'SAXX0036', text: 'أبها'});
	KSACitis.push({value: 'SAXX0040', text: 'جيزان'});
	KSACitis.push({value: 'SAXX0039', text: 'شرورة'});			 	
	KSACitis.push({value: 'SAXX0031', text: 'الأحساء'});			 	
	KSACitis.push({value: 'SAXX0026', text: 'القصيم'});			 	
			
    this.domSettings = [
        
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("weather_inp_town"), className: "settings_label"},
            { tag: "select",id: "citySelect",events: {onchange: "setCity()"},options: KSACitis }            
          ]},        
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("weather_inp_unit"), className: "settings_label"},
            { tag: "select", id: "setUnit", events: {onchange: "setUnit()"}, className: "settings_control",
              options: [
                { value:"c", text: loc.text("weather_celsius")},
                { value:"f", text: loc.text("weather_fahrenheit")}
              ]}
          ]},                            
        { tag: "div", className: "settings_section",display: false, 
          childs: [
            { tag: "span", innerHTML: loc.text("weather_inp_town"), className: "settings_label"},
            { tag: "input", type: "text", size: 15, id: "setCity", className: "settings_control"},
            { tag: "input", type: "button", id: "btn_setCity", events: {onclick: "loadCities()"}, value: loc.text("btn_set"), className: "settings_control"},
          ]},
        { tag: "div", id :"citiesListDIV",className: "settings_section", display: false,
          childs: [
            { tag: "span",innerHTML: "City", className: "settings_label"},
        	{ tag: "div", id :"citiesList",className: "settings_section"}                         
          ]},
   		  { tag: "div", className: "cls"}
        
    ]


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.setUnit.value = this.profile.unit;
    }



    this.onOpen = function() {
        this.refresh();
    }

    var loading = false;
    var firstTime = true;
    this.refresh = function() { 
    	if(firstTime) {
    		this.profile.city = this.defaultProfile["city"];
    		firstTime = false;
    	}
        if(!loading) {
            loading = true;            
            this.setTitle(loc.text("msg_loading"));
            //this.elements["content"].innerHTML = '<div align="center">' + loc.text("msg_loading") + '</div>';
            this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
                          
            xmlRequest.send("http://xoap.weather.com/weather/local/"+this.profile.city+"?cc=*&unit=d&dayf=4&link=xoap&prod=xoap&par=1065917043&key=d309e29420f0141b", this, "showWeather");
			if(this.isReduced) {
				this.show();
			}            
        }
    }


	this.setKSACity = function() {	            
	var html = [{ tag: "select",id: "citySelect",events: {onchange: "setCity()"},options: KSACitis }];
	this.buildDomModel(this.elements.citiesList, html);	
	
	} 
    this.setUnit = function() {
        this.profile.unit = this.elements.setUnit.value;
        this.renderWeather();
        this.save();
			//Hide Setting
          	if(!this.isSettingsReduced) {
            	this.hideSettings();
            }
            //if widjet minimize show it
			if(this.isReduced) {
				this.show();
			}	                
    }


    this.loadCities = function() {
        this.elements.citiesList.innerHTML = loc.text("msg_loading");
        showEl(this.elements.citiesListDIV);
        this.elements["btn_setCity"].disabled = true;
        xmlRequest.send("http://xoap.weather.com/search/search?where="+this.elements.setCity.value, this, "showCities");
    }


    this.showCities = function(response) {
        this.elements["btn_setCity"].disabled = false;
        this.elements.citiesList.innerHTML = '';
        
        var doc = response.responseXML.documentElement;
        var r = doc.getElementsByTagName("loc");
        if(r.length == 1) {
            this.setCity(r[0].getAttribute("id"));
            hideEl(this.elements.citiesListDIV);
        } else if (r.length == 0) {
            this.elements.citiesList.innerHTML = "<b>" + loc.text("weather_no_cities") + "</b>";
        } else {
            var clistDom = [];
            for(var i=0; i<r.length; i++) {
				clistDom[i] = {value: r[i].getAttribute("id"), text: r[i].firstChild.nodeValue};                                   
            }
            var html = [{ tag: "select",id: "citySelect",events: {onchange: "setCity()"},options: clistDom }];
            this.buildDomModel(this.elements.citiesList, html);
        }                 
    }


    this.setCity = function(id) {    
    	cityID = (id == undefined)  ? this.elements.citySelect.value : id;    
    	this.profile.city =  cityID ;          
        hideEl(this.elements.citiesListDIV);
        this.save();
        this.refresh();
    }



    this.toCelcius = function(n) {
		var calc = Math.round((n-32)*5/9);
		return (isNaN(calc)) ? loc.text("weather_na") : calc + "&#176;";
	}
	
	this.getTemp = function(node) {
		var hi = node.getElementsByTagName("hi")[0].firstChild.nodeValue;
		var low = node.getElementsByTagName("low")[0].firstChild.nodeValue;

        if(this.profile.unit == "c") {
           	hi = this.toCelcius(hi);
            low = this.toCelcius(low);
        }
		
		return low+" / "+hi+"";
	}



    this.renderWeather = function() {
        if(!this.data) {
            return false;
        }
    	var days = this.data.getElementsByTagName("day");
        var mDays = [];
        var pic;

        for(var i=0; i<days.length; i++) {
        if(i == 0) {        	
        	pic = parseInt(this.data.getElementsByTagName("cc")[0].getElementsByTagName("icon")[0].firstChild.nodeValue);
        } else {
        	pic = parseInt(days[i].getElementsByTagName("icon")[0].firstChild.nodeValue);
        }
            
            pic = ((pic < 10) ? "0" : "") + pic + ".png";
            mDays.push({ tag: "td", style: {textAlign: "center"}, 
                         childs: [
                            //{ tag: "div", innerHTML: days[i].getAttribute("t")},
                            { tag: "div", innerHTML: this.arabicDays(days[i].getAttribute("t"))},
                            { tag: "img", src: 'static/weather/' + pic },
                            { tag: "div", innerHTML: this.getTemp(days[i]) }
                         ]});
        }



        var m ={tag: "div", className:"waether",
        childs: [
        { tag: "table", className: "sys_table", style: {width: "100%"},
                  childs: [
                    {tag: "tr", 
                    	childs: [
                    		{tag: "td", colspan: "2", id:"weatherCity", style:{padding:"10px 30px 20px 0"}},
                    		{tag: "td", colspan: "2", align:"left", innerHTML: '<a target = "_blank" href="http://www.weather.com/"><img src="widgets/weather/weatherLogo.png" /></a>'}
                    	]
                    	},
                    { tag: "tr",
                      childs: mDays }
                  ]}
        ]
        } 
        ;

        this.elements["content"].innerHTML = '';
        this.buildDomModel(this.elements["content"], m);
		//this.setTitle(loc.text("weather_title") + ' في ' + this.elements.citySelect[this.elements.citySelect.selectedIndex].text);
		this.setTitle(loc.text("weather_title"));
		this.buildDomModel(this.elements["weatherCity"], {tag : "a", href:"void(0);", style:{cursor: "pointer"},events: {onclick: "switchSettings();"}, innerHTML: '<strong>' + this.elements.citySelect[this.elements.citySelect.selectedIndex].text + '</strong>'});
		
			/*
        if(this.data.getElementsByTagName("dnam").length>0) {
            this.setTitle(this.data.getElementsByTagName("dnam")[0].firstChild.nodeValue);
        }
        */
    }


    this.showWeather = function(response) {
        this.data = response.responseXML.documentElement;
        this.renderWeather();
        loading = false;
        //Hide Setting Area        
			//Hide Setting
          	if(!this.isSettingsReduced) {
            	this.hideSettings();
            }
            //if widjet minimize show it
			if(this.isReduced) {
				this.show();
			}	        
    }

 	
 	this.arabicDays = function(day) { 	
 		var arabicDaysArray = new Array();
 		
 		arabicDaysArray['Saturday']="السبت"; 		
		arabicDaysArray['Sunday']="الأحد";
		arabicDaysArray['Friday']="الجمعة";
		arabicDaysArray['Thursday']="الخميس";
		arabicDaysArray['Wednesday']="الأربعاء";
		arabicDaysArray['Tuesday']="الثلاثاء";
		arabicDaysArray['Monday']="الإثنين"; 		
 		return arabicDaysArray[day];
 	}
 	
 
}
Weather.prototype = new Widget();

function Websearch() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        hasSettingsBtn: true,
        title: loc.text("websearch_title"),
        module: "Websearch"
    }

 
    this.defaultProfile["openHere"] = "0";
    this.defaultProfile["serverId"] = 0;


    this.domSettings = [
        { tag: "div", className: "settings_section",
          childs: [
            
            { tag: "input", id: "set_target", type: "checkbox", events: {onclick: "setTarget()"}, className: "settings_control"},
            { tag: "span", innerHTML: loc.text("websearch_results_target") }
          ]},
		    		  { tag: "div", className: "cls"}
    ]


    this.domContent = [
        { tag: "div", className: "divList", style: {marginTop: "4px", padding: "0px", direction: "rtl"}, id: "servers_tabs", 
        childs: 
        [
        	{ tag: "ul", id: "tabList" }
        ]},
        { tag: "div", className: "menu_dpanel", style: { padding: "6px", marginTop: "6px"},
          childs: [
            createTableDom([{content: { tag: "img", id: "server_logo", border: "0", display: false, style: {marginRight: "10px"} }, width: "1%"},
                            {content: { tag: "input", id: "search_text", type: "text", style: {width: "95%", align: "center"}}, width: "98%"},
                            {content: { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "goSearch()"}}, width: "1%"}], "90%")
          ]}
    ]

    this.onBuildInterface = function() {
       this.elements["settings"].innerHTML = "";
       this.buildDomModel(this.elements.settings, this.domSettings);

        this.buildDomModel(this.elements.content, this.domContent);
        for(var i=0; i<websearch_servers.length; i++) {
        	if (i == 0) {
        		on =  'on';
        	} else {
        		on = '';
        	}        	
            this.buildDomModel(this.elements.tabList,
                { tag: "li", className: on, style: {width: "65px", textAlign: "center"},              
                  id: "tab_"+i, 
                  childs:
                  [
                 	 { tag: "a", href: "void", innerHTML: websearch_servers[i].title, events: {onclick: "setServer('"+i+"')"}}
                  ]
                
            });
                  
        }

        if(this.profile.serverId > websearch_servers.length - 1) {
            this.profile.serverId = websearch_servers.length - 1;
        } else if (!websearch_servers[this.profile.serverId]) {
            this.profile.serverId = 0;
        }

        this.elements.set_target.checked = (this.profile.openHere == 1);

        this.showServerTab(this.profile.serverId);
//        this.setTitle(this.profile.title);


        var widget = this;
        this.elements["search_text"]["onkeyup"] = function(event) { if (!event) { event = window.event } if(event.keyCode == 13) { widget.goSearch() } };
    }


    this.setTarget = function() {
        this.profile.openHere = (this.elements.set_target.checked ? "1" : "0");
        this.save();
    }


    this.setServer = function(serverId) {
        this.profile.serverId = serverId;
        this.showServerTab(serverId);
        this.save();
    } 
	
    this.activeTab = 0;
    this.showServerTab = function(serverId) {   
    
        if(this.activeTab ||  this.activeTab == 0) {        	
        	this.elements["tab_"+this.activeTab].className = '';
        }
        this.elements["tab_"+serverId].className = "on";
        this.elements["tab_"+serverId].getElementsByTagName("a")[0].style.color = "#fff";
        this.activeTab = serverId;
        this.elements["search_text"].value = '';

        if(websearch_servers[serverId].logo != "") {
            showEl(this.elements.server_logo);
            this.elements.server_logo.src = 'var/img/'+websearch_servers[serverId].logo;
        } else {
            hideEl(this.elements.server_logo);
        }
        this.setTitle(websearch_servers[serverId].title);
    }


    this.goSearch = function() {
        var str = this.elements.search_text.value;
        if(str == "") {
            return;
        }

        var url = websearch_servers[this.profile.serverId].url+str;
        if(this.profile.openHere == 1) {
            document.location = url;
        } else {
            window.open(url);
        }
    }
}
Websearch.prototype = new Widget();

function HTMLBrowser() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        hasProfile: true,
        title: loc.text("browser_title"),
        module: "HTMLBrowser"
    };

    this.defaultProfile["home_page"] = "";


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("browser_inp_url"), className: "settings_label"},
            { tag: "input", type: "text", size: 15, id: "inp_home_page", className: "settings_control"},
            { tag: "input", type: "button", events: {onclick: "setHomePage()"}, value: loc.text("btn_go"), className: "settings_control"}
          ]} ,
		{ tag: "div", className: "cls"}
    ]



    this.domContent = [
        { tag: "iframe",
          id: "browser",
          vspace: "0",
          hspace: "0",
          marginwidth: "0",
          marginheight: "0",
          frameBorder: "0",
          style: { width: "100%", height: "340px", border: "0" }}
    ]


    this.onBuildInterface = function() {
        this.setTitle(loc.text("browser_title"));
        this.elements.settings.innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.buildDomModel(this.elements.content, this.domContent);
        this.elements["inp_home_page"].value = this.profile["home_page"];
    }


    this.onOpen = function() {
        this.navHome();
    }


    this.setHomePage = function() {
        this.profile["home_page"] = this.formatUrl(this.elements["inp_home_page"].value);
        this.elements["inp_home_page"].value = this.profile["home_page"];
        this.navHome();
        this.save();
        this.switchSettings();
    }


    this.navHome = function() {
        this.elements["browser"].src = this.profile["home_page"];
    }

  
    this.formatUrl = function(str) {
        var url = trim(str);
        if(url.indexOf("http://") == -1) {
            url = "http://"+url;
        }
        return url;
    } 
 
 
}
HTMLBrowser.prototype = new Widget();

function Calculator() {

    this.init();

    this.cfg = {
        hasProfile: false,
        title: "",
        hasSettingsBtn: false,
        hasRefreshBtn: false,
        module: "Calculator",
        hasTitle: false
    }


    this.numpadButtons = [
        [ {type: "sys1", numkey: "sys", action: "memoryClear()", text: "MC"},
          {type: "sys1", numkey: "sys", action: "memoryRestore()", text: "MR"},
          {type: "sys1", numkey: "sys", action: "memoryStore()", text: "MS"},
          {type: "sys1", numkey: "sys", action: "memoryAdd()", text: "M+"},
          {type: "sys2", numkey: "sys", action: "clear()", text: "C"},
          {type: "sys2", numkey: "sys", action: "clearE()", text: "CE"} ],

        [ {type: "std", numkey: "num", action: "addNumber(7)", text: "7"},
          {type: "std", numkey: "num", action: "addNumber(8)", text: "8"},
          {type: "std", numkey: "num", action: "addNumber(9)", text: "9"},
          {type: "std", numkey: "op", action: "setOperation('/')", text: "/"},
          {type: "std", numkey: "op", action: "evalSqrt()", text: "sqrt"} ],

        [ {type: "std", numkey: "num", action: "addNumber(4)", text: "4"},
          {type: "std", numkey: "num", action: "addNumber(5)", text: "5"},
          {type: "std", numkey: "num", action: "addNumber(6)", text: "6"},
          {type: "std", numkey: "op", action: "setOperation('*')", text: "*"},
          {type: "std", numkey: "op", action: "evalPercent()", text: "%"} ],

        [ {type: "std", numkey: "num", action: "addNumber(1)", text: "1"},
          {type: "std", numkey: "num", action: "addNumber(2)", text: "2"},
          {type: "std", numkey: "num", action: "addNumber(3)", text: "3"},
          {type: "std", numkey: "op", action: "setOperation('-')", text: "-"},
          {type: "std", numkey: "op", action: "eval1x()", text: "1/x"} ],

        [ {type: "std", numkey: "op", action: "changeSign()", text: "+/-"},
          {type: "std", numkey: "num", action: "addNumber(0)", text: "0"},
          {type: "std", numkey: "num", action: "addPoint()", text: ","},
          {type: "std", numkey: "op", action: "setOperation('+')", text: "+"},
          {type: "std", numkey: "op", action: "evalute()", text: "="} ]
    ]



    this.onBuildInterface = function() {
        var numpadModel = [];
        for(var r=0; r<this.numpadButtons.length; r++) {
            var rowModel = [];
            for(var b=0; b<this.numpadButtons[r].length; b++) {
                rowModel.push(
                    { tag: "div", className: "calc_btn_" + this.numpadButtons[r][b].type,
                      childs: [
                        { tag: "button", innerHTML: this.numpadButtons[r][b].text, className: "calc_padkey_"+ this.numpadButtons[r][b].numkey,
                          events: { onclick: this.numpadButtons[r][b].action }}
                      ]});
            }
            numpadModel.push(
                { tag: "div", className: "calc_numpad_row",
                  childs: rowModel });
        }


        this.buildDomModel(this.elements["content"], [
            { tag: "div", className: "calc_display", innerHTML: "0",
              id: "display"},
            { tag: "div", className: "calc_numpad",
              childs: numpadModel }
        ]);
    }



    this.onOpen = function() {
        this.setTitle(loc.text("calculator_title"));
    }




    


    this.addPointFlag = false;
    this.memory = null;
    this.operation = null;
    this.activeNumber = 0;
    this.needClear = false;
    this.isError = false;




    this.getValue = function() {
        var v = trim(this.elements["display"].innerHTML);
        if(v == "E") {
            this.setValue(0);
            v = "0";
        }
        return v;
    }


    this.setValue = function(v) {
        this.elements["display"].innerHTML = v;
    }





    this.addNumber = function(n) {
        if(this.isError) {
            this.setValue(0);
            this.isError = false;
        }

        if(this.needClear) {
            this.setValue(0);
            this.needClear = false;
        }

        if((this.getValue() == "0") && !this.addPointFlag) {
            this.setValue(n);
        } else {
            if(this.addPointFlag) {
                this.elements["display"].innerHTML += ".";
            }
            this.elements["display"].innerHTML += n;
        }
        this.addPointFlag = false;
    }


    this.addPoint = function() {
        if(this.needClear) {
            this.setValue(0);
            this.needClear = false;
        }

        if(this.getValue().indexOf(".") == -1) {
            this.addPointFlag = true;
        }
    }





    this.setOperation = function(op) {
        if(this.operation != null) {
            this.evalute();
        }
        this.addPointFlag = false;
        this.activeNumber = parseFloat(this.getValue());
        this.operation = op;
        this.needClear = true;
    }


    this.evalute = function() {
        if(this.operation != null) {
            var v = parseFloat(this.getValue());
            switch(this.operation) {
                case "*":
                    this.setValue(v * this.activeNumber);
                    break;

                case "+":
                    this.setValue(v + this.activeNumber);
                    break;

                case "-":
                    this.setValue(this.activeNumber - v);
                    break;

                case "/":
                    if(v != 0) {
                        this.setValue(this.activeNumber / v);
                    } else {
                        this.setValue("E");
                    }
                    break;
            }
            this.operation = false;
            this.addPointFlag = false;
            this.needClear = true;
        }
    }


    this.evalPercent = function() {
        if(this.activeNumber != null && this.operation != null) {
            this.addPointFlag = false;
            var v = parseFloat(this.getValue());
            this.setValue(v*this.activeNumber/100);
        }
    }


    this.evalSqrt = function() {
        this.addPointFlag = false;
        var v = parseFloat(this.getValue());
        this.setValue(Math.sqrt(v));
    }


    this.eval1x = function() {
        this.addPointFlag = false;        
        var v = parseFloat(this.getValue());
        if(v != 0) {
            this.setValue(1/v);
        } else {
            this.setValue("E");
        }
    }


    this.changeSign = function() {
        var v = parseFloat(this.getValue());
        if(v != 0) {
            this.setValue(-v);
        }
    }






    this.memoryClear = function() {
        this.memory = null;
    }

    this.memoryRestore = function() {
        if(this.memory != null) {
            this.setValue(this.memory);
            this.needClear = true;
        }
    }

    this.memoryStore = function() {
        this.memory = parseFloat(this.getValue());
    }

    this.memoryAdd = function() {
        if(this.memory == null) {
            this.memory = 0;
        }
        this.memory += parseFloat(this.getValue());
    }





    this.clear = function() {
        this.addPointFlag = false;
        this.operation = null;
        this.activeNumber = 0;
        this.setValue(0);
    }


    this.clearE = function() {
        this.addPointFlag = false;
        this.setValue(0);
    }

}
Calculator.prototype = new Widget();

function HTMLBox() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        //hasTitle: false,
        title: loc.text("htmlbox_title"),
        module: "HTMLBox"
    }

    this.defaultProfile["title"] = loc.text("htmlbox_title");
    this.defaultProfile["html"] = "";


    this.onBuildInterface = function() {
        this.buildDomModel(this.elements["settings"], [
          { tag: "div", className: "settings_section",
            childs: [
              { tag: "span", innerHTML: loc.text("htmlbox_inp_source"), className: "settings_label"},
              { tag: "br"},
              { tag: "textarea", id: "inp_source",
                style: { overflow: "auto", width: "98%", height: "120px" , direction : "ltr" , textAlign : "left"} }
            ]},

          { tag: "div", className: "settings_section",
            childs: [
              { tag: "input", type: "button", value: loc.text("btn_ok"), 
                events: { onclick: "onChangeSource()" }, className: "settings_control"}
            ]}
       ]);
    }



    this.onChangeSource = function() {
        var t = this.elements["inp_source"].value;
        this.renderHTML(t);
        this.profile["html"] = t.jsEscape();
        this.save();
        this.hideSettings();
    }


    this.onOpen = function() {
        this.setTitle(this.profile["title"]);
        this.elements["input_title"].value = this.profile["title"];
        this.elements["content"].style.textAlign = "center";

        var html = this.profile["html"].jsUnescape();
        this.elements["inp_source"].value = html;
        this.elements["inp_source"].onfocus = function() {
            this.select();
        }

        this.renderHTML(html);
    }



    this.setIcon = function(html) {
        var url = html.substring(html.indexOf('http://'));
    	var favIcon = url.substring(0, url.indexOf('/', 8));
        if(favIcon == "") {
            favIcon = "http://" + baseUrl + "widgets/htmlbox/ico.gif";
        } else {
            favIcon += "/favicon.ico";

        }
    	this.elements["icon"].setAttribute("src", favIcon);
    }



    this.renderHTML = function(html) {
        this.setIcon(html);
        if(!(html && html.length)) {
            this.elements["content"].innerHTML = "<div style='text-align: left'>" + loc.text("htmlbox_help") + "</div>";
        } else {
            if(html.indexOf('<script') != -1) {
                this.elements["content"].innerHTML = "";
                this.buildDomModel(this.elements["content"], 
                    { tag: "iframe", 
                      id: "iframe",
                      scrolling: "no",
                      border: "0",
                      frameBorder: "0" });

                this.elements["iframe"].src = "ewloader.php?wid=" + this.id + "&code=" + encodeURIComponent(html);
            } else {
                if (html.match(/^http:\/\/.*\.(jpg|png|gif|bmp)$/)) { 
                    html = '&nbsp;<img src="' + html + '" />';
                }
                this.elements["content"].innerHTML = html;
            }
        }
    }


    this.updateIframeSize = function(w, h) {
        this.elements["iframe"].style.width = w + "px";
        this.elements["iframe"].style.height = w + "px";
    }


}
HTMLBox.prototype = new Widget();

function HTMLWidget() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasTitle: false,
        title: "",
        module: "HTMLWidget"
    }

    this.defaultProfile["id"] = "";


    this.onOpen = function() {
        this.setTitle(loc.text("msg_loading"));
        request.send({ act: "get_data", id: this.profile["id"]}, this);
    }



    this.renderHTML = function(html) {
    	if(html.indexOf('<script') != -1) {
            this.elements["content"].innerHTML = "";
            this.buildDomModel(this.elements["content"], 
                { tag: "iframe", 
                  id: "iframe",
                  scrolling: "no",
                  border: "0",
                  frameBorder: "0" });

            this.elements["iframe"].src = "ewloader.php?wid=" + this.id + "&code=" + encodeURIComponent(html);
        } else {
            this.elements["content"].innerHTML = html;
        }
    }


    this.updateIframeSize = function(w, h) {
        this.elements["iframe"].style.width = w + "px";
        this.elements["iframe"].style.height = w + "px";
    }



    this.dispatchMsg = function(msg) {
        switch(msg.status) {
            case "data":
                this.elements["content"].style.textAlign = "center";
                this.setTitle(msg.data.title);
                this.renderHTML(msg.data.source);
                this.elements["icon"].setAttribute("src", "var/hwicons/" + msg.data.icon);
                break;

            case "error":
                this.elements["content"].innerHTML = loc.text("msg_error");
                this.setTitle(loc.text("msg_error"));
                break;
        }
    }

}
HTMLWidget.prototype = new Widget();

function UWAWidget() {
    this.init();

    this.cfg = {
        hasRefreshBtn: false,
        hasProfile: true,
        hasTitle: false,
        title: loc.text("uwawidget_title"),
        module: "UWAWidget"
    };

    this.defaultProfile["url"] = "";
    this.defaultProfile["prefs"] = "";


    this.domSettings = [
        { tag: "div", className: "settings_section", 
          id: "settings_widget",
          childs: [
            { tag: "span", innerHTML: "URL:", className: "settings_label"},
            { tag: "input", type: "text", size: 15, id: "inp_url", className: "settings_control"},
            { tag: "input", type: "button", events: {onclick: "setURL()"}, value: loc.text("btn_go"), className: "settings_control"}
          ]},
        { tag: "div",
          id: "settings_uwa",
          display: false,
          childs: [
            { tag: "hr" },
            { tag: "div", id: "settings_ex" },
            { tag: "div", 
              style: { textAlign: "center", width: "auto"},
              childs: [
                { tag: "input", type: "button",
                  value: loc.text("btn_ok"),
                  events: { onclick: "saveWidgetPrefs()" }}
              ]},
            { tag: "hr"},
            { tag: "div", id: "widget_info",
              style: { textAlign: "right", width: "auto"} }
          ]}
    ]


    this.onBuildInterface = function() {
        this.setTitle(loc.text("uwawidget_title"));
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements["wbody"] = createElementEx("div");
        this.elements["content"].appendChild(this.elements["wbody"]);
        var self = this;
        this.elements["inp_url"].onkeyup = function(e) {
            e = fix_event(e);
            if(e.keyCode == 13) {
                self.setURL();
            }
        }
        this.elements["inp_url"].value = this.profile["url"];
    }


    this.onOpen = function() {
//        this.elements["exTitle"] = createElementEx("div");
//        this.elements["title"].appendChild(this.elements["exTitle"]);
        this.loadWidget();
    }

//    this.setTitle = function(html) {
//        this.elements["exTitle"].setHTML(html);
//    }

    var isLoading = false;
    var flAddToRecentList = false;

    this.setURL = function() {
        if(isLoading) {
            return;
        }
        var url = this.formatUrl(this.elements["inp_url"].value);
        if(this.profile["url"] != url) {
            this.hideElement("settings_uwa");
            this.profile["prefs"] = "";
            this.profile["url"] = url;
            this.elements["inp_url"].value = url;
            this.save();
            this.switchSettings();
            this.loadWidget();

            flAddToRecentList = true;
        }
    }


    this.loadWidget = function() {
        if(this.profile["url"] != "") {
            this.elements["wbody"].innerHTML = loc.text("msg_loading");
            var self = this;
            request.getUWA(this.profile["url"], this, "parseWidget");
        } else {
            this.elements["wbody"].innerHTML = loc.text("uwawidget_help");
            this.setTitle(loc.text("uwawidget_title"));
            this.elements["settings_ex"].innerHTML = "";
        }
    }

  
    this.formatUrl = function(str) {
        var url = trim(str);
        if(url.indexOf("http://") == -1) {
            url = "http://"+url;
        }
        return url;
    } 


    this.buildSettingsSection = function(model) {
        this.buildDomModel(this.elements["settings_ex"],
            { tag: "div", className: "settings_section",
              childs: model });
    }


    // WIDGET INFO

    var winfo = {};


    this.updatePrefElement = function(name, value) {
        if(winfo.prefs[name]) {
            switch(winfo.prefs[name].type) {
                case "text":
                    this.elements["pref_" + name].value = trim(value);
                    break;

                case "list":
                case "range":
                    this.elements["pref_" + name].value = value;
                    break;

                case "boolean":
                    this.elements["pref_" + name].checked = (value == "true");
                    break;
            }
        }
    }

    this.getPrefElementValue = function(name) {
        var value;
        if(winfo.prefs[name]) {
            switch(winfo.prefs[name].type) {
                case "boolean":
                    value = this.elements["pref_" + name].checked ? "true" : "false";
                    break;
                case "text":
                    value = trim(this.elements["pref_" + name].value);
                    break;
                case "list":
                case "range":
                    value = this.elements["pref_" + name].value;
                    break;
                case "hidden":
                    value = this.profile["prefs"][name];
                    break;
            }
        } else {
            value = "";
        }
        return value;
    }



    this.showError = function() {
        this.setTitle(loc.text("msg_error"));
        this.elements["wbody"].innerHTML = "";
        isLoading = false;
    }


    this.parseWidget = function(xml) {
        var doc = xml.documentElement;

        if(!doc || !doc.tagName) {
//            Debug.log("UWA widget loading error!\nwid: "+ this.id + "\nmodule URL: " + this.profile["url"]);
            this.showError();
            return;
        } 

        if(doc.tagName == "parsererror") {
//            Debug.log("UWA parsing error!\nwid: "+ this.id + "\nmodule URL: " + this.profile["url"] + "\n----\n" + new XMLSerializer().serializeToString(doc));
            this.showError();
            return;
        }
        var __self = this;

        if(doc) {
            this.elements["wbody"].innerHTML = "";
        } else {
            this.elements["wbody"].innerHTML = loc.text("msg_error");
            isLoading = false;
            return;
        }

        if(doc.getElementsByTagName("title")[0]) {
            winfo.title = doc.getElementsByTagName("title")[0].firstChild.nodeValue;
        } else {
            winfo.title = loc.text("uwawidget_title");
        }
        this.setTitle(winfo.title);


        if(doc.getElementsByTagName("body")[0]) {
            winfo.body = doc.getElementsByTagName("body")[0].firstChild.nodeValue;
            if(winfo.body != null) {
                this.elements["wbody"].innerHTML = winfo.body;
            }
        }


        winfo.meta = {}
        var meta = doc.getElementsByTagName("meta");
        for(var i=0; i<meta.length; i++) {
            winfo.meta[meta[i].getAttribute("name")] = meta[i].getAttribute("content");
        }

        this.elements["widget_info"].innerHTML = loc.text("uwawidget_widgetby") + " <b>" + winfo.meta["author"] + "</b>";

        winfo.icon = "";
        var links = doc.getElementsByTagName("link");
        for(var i=0; i<links.length; i++) {
            if(links[i].getAttribute("rel") == "icon") {
                winfo.icon = links[i].getAttribute("href");
                this.elements["icon"].setAttribute("src", winfo.icon);
                break; // TODO: or continue? ;)
            }
        }
        if(winfo.icon == "") {
            winfo.icon = "widgets/uwawidget/ico.gif";
            this.elements["icon"].setAttribute("src", winfo.icon);
        }

        var styles = doc.getElementsByTagName("style");
        var cssText = "";
        for(var i=0; i<styles.length; i++) {
            cssText += styles[i].firstChild.nodeValue;
        }

        var styleEl = document.createElement('style');
        styleEl.type = "text/css";
        var headEl = document.getElementsByTagName('head')[0];
        headEl.appendChild(styleEl);

        if (styleEl.styleSheet) {
            styleEl.styleSheet.cssText = cssText;
        } else {
            var tn = document.createTextNode(cssText);
            styleEl.appendChild(tn);
        }


        // add to recent list
        if(window["menu"]) {
            desktop.addRecentWidget(winfo.title, this.profile["url"], this.elements["icon"].src);
        }

        // preferences
        winfo.prefs = {}
        this.elements["settings_ex"].innerHTML = "";
        var prefs = doc.getElementsByTagName("preference");

        var prof = {};
        var isProfileEmpty = this.profile["prefs"] == "";
        if(isProfileEmpty) {
            this.profile["prefs"] = {};
        }
        var settingsModel = [];

        winfo.preferences = []; // nv
        for(var i=0; i<prefs.length; i++) {
            var name = prefs[i].getAttribute("name");
            var defValue = prefs[i].getAttribute("defaultValue");
            if(defValue == null) {
                defValue = "";
            }
            var label = prefs[i].getAttribute("label");

            var fillValue = isProfileEmpty ? defValue : this.profile["prefs"][name];

            winfo.prefs[name] = { type: prefs[i].getAttribute("type") };
            winfo.preferences[i] = { name: name, defaultValue: defValue, label: label }; // nv
            switch(prefs[i].getAttribute("type")) {
                case "text":
                    var sm = [
                        { tag: "span", className: "settings_label",
                          html: label },
                        { tag: "input", type: "text", className: "settings_control", 
                          size: "15",
                          id: "pref_" + name }
                    ];
                    this.buildSettingsSection(sm);
                    this.updatePrefElement(name, fillValue);

                    this.elements["pref_" + name].onkeyup = function(e) {
                        e = fix_event(e);
                        if(e.keyCode == 13) {
                            __self.saveWidgetPrefs();
                        }
                    }
                    break;

                case "list":
                    var options = [];
                    for(var j=0; j<prefs[i].childNodes.length; j++) {
                        var o = prefs[i].childNodes[j];
                        if(o.nodeType == 1) {
                            options.push({ text: o.getAttribute("label"), value: o.getAttribute("value")});
                        }
                    }
                    var sm = [
                        { tag: "span", className: "settings_label",
                          html: label },
                        { tag: "select", className: "settings_control", 
                          options: options,
                          id: "pref_" + name }
                    ];
                    this.buildSettingsSection(sm);
                    this.updatePrefElement(name, fillValue);
                    break;

                case "range":
                    var pt = parseInt(prefs[i].getAttribute("min"));
                    var rmax = parseInt(prefs[i].getAttribute("max"));
                    var rstep = parseInt(prefs[i].getAttribute("step"));
                    winfo.preferences[i].min = pt; // nv
                    winfo.preferences[i].max = rmax; // nv
                    winfo.preferences[i].step = rstep; // nv
                    var options = [];
                    do {
                        options.push( { text: pt, value: pt } );
                        pt += rstep;
                    } while (pt <= rmax);

                    var sm = [
                        { tag: "span", className: "settings_label",
                          html: label },
                        { tag: "select", className: "settings_control", 
                          options: options,
                          id: "pref_" + name }
                    ];
                    this.buildSettingsSection(sm);
                    this.updatePrefElement(name, fillValue);
                    break;


                case "boolean":
                    var sm = [
                        { tag: "span", className: "settings_label",
                          html: label },
                        { tag: "input", type: "checkbox", 
                          className: "settings_control",
                          id: "pref_" + name }
                    ];
                    this.buildSettingsSection(sm);
                    this.updatePrefElement(name, fillValue);
//                    this.elements["pref_" + name].checked = fillValue == "1";
                    break;
            }

            if(isProfileEmpty) {
                this.profile["prefs"][name] = defValue;
            }
        }

        var scripts = doc.getElementsByTagName("script");
        var jsCode = "";
        for(var i=0; i<scripts.length; i++) {
            if(scripts[i].getAttribute("src") == null) {
                jsCode += scripts[i].firstChild.nodeValue;
            }
        }

        this.runJSCode(jsCode);

        isLoading = false;
    }
 

    // WIDGET EXECUTION

    this.saveWidgetPrefs = function() {
        var isChanged = false;
        var value = "";
        for(var i in winfo.prefs) {
            value = this.getPrefElementValue(i);
            if(!isChanged && this.profile["prefs"][i] != value) {
                isChanged = true;
            }        
            this.profile["prefs"][i] = value;
        }
        this.hideSettings();
        if(isChanged) {
            this.save();
            this.widget.onRefresh();
        }
    }




    this.runJSCode = function(code) {
        var widget = {};
        var __self = this;


        widget.body = this.elements["wbody"];
        widget.lang = loc.lang.toLowerCase() + "_" + loc.lang.toUpperCase();
        widget.locale = loc.lang.toLowerCase();

        widget.onLoad = function() {}
        widget.onRefresh = function() {}
        widget.onResize = function() {}
        widget.onSearch = function() {}
        widget.onResetSearch = function() {}
        widget.onKeyboardAction = function() {}
        widget.onUpdateTitle = function() {}
        widget.onUpdateBody = function() {}

        widget.elements = {}
        widget.elements.title = __self.elements["exTitle"];


        // undocumented
        widget.environment = {
            commUrl: ""
        }


        widget.periodicals = {};
        widget.clearPeriodical = function(name) {
            if(this.periodicals[name]) {
                clearInterval(this.periodicals[name])
            }
        }
        widget.setPeriodical = function(name, fn, delay, force) {
            this.clearPeriodical(name);
            fn = fn.bind(this);
            this.periodicals[name] = setInterval(fn, delay);
            if (force) {
                fn();
            }
        }





        widget.callback = function(fname) {
            widget[fname]();
        }
        widget.preferences = winfo.preferences;
        widget.data = this.profile["prefs"]; 
        var data = widget.data;



        widget.addBody = function(content) {
            if(typeof(content) == "string") {
                var div = createElementEx("div");
                div.setHTML(content);
                widget.body.appendChild(div);
            } else {
                __self.elements["wbody"].appendChild(content);
            }
            widget.onUpdateBody();
        }


        widget.createElement = function(tagName) {
            if (tagName == 'script' ) return false;
            var el = document.createElement(tagName);
            UWA.$element(el);
            if(typeof elName == 'string') {
                widget.elements[elName] = el;
            } 
            return el;
        }


        widget.getValue = function(name) {
//            return __self.profile["prefs"][name];
            var res;

            if(winfo.prefs[name]) {
                if(winfo.prefs[name].type == "hidden") {
                    res = __self.profile["prefs"][name];
                } else {
                    res = __self.getPrefElementValue(name);
                }
            } else {
                res = ""
            }
            return res;
        }


        widget.setValue = function(name, value) {
            if(__self.profile["prefs"][name] != value) {
                __self.profile["prefs"][name] = value;
                __self.updatePrefElement(name, value);
                __self.save();
            }
        }


        widget.log = function(string) {}


        widget.openURL = function(url) {
            window.open(url);
        }


        widget.setAutoRefresh = function(delay) {}


        widget.setBody = function(content) {
            widget.body.setContent(content);
            widget.onUpdateBody();
        }


        widget.setSearchResultCount = function(count) {}


        widget.setTitle = function(title) {
            __self.setTitle(title);
            widget.onUpdateTitle();
        }


        widget.getInt = function(name) {
            var value = this.getValue(name);
            if(value == 'true' || value == true) value = 1;
            value = parseInt(value, 10);
            return isNaN(value) ? 0 : value;
        }
  
        widget.getBool = function(name) {
            return widget.getInt(name) ? true : false;
        }

        widget.setUnreadCount = function(count) {}

/*
        var w= window.open();
        w.document.open();
        w.document.write("<pre>" + code + "</pre>");
        w.document.close();
*/
        try {
            eval(code);
        } catch(e) { 
            if(BASE_URL == "mevou") {
                alert("UWA error!\nwid: "+ this.id + "\nmodule URL: " + this.profile["url"] + "\n----\n" + e.name + "\n" + e.message); 
            }
        }
        
        widget.onLoad();
        __self.widget = widget;
        this.showElement("settings_uwa");

        //dimk
        if(flAddToRecentList) {
            desktop.addRecentWidget(this.getWidgetInfo());
            if(window["menu"]) {
                menu.renderRecentWidgets();
            }
            flAddToRecentList = false;
        }

        this.onWidgetLoad();
    }


    this.onWidgetLoad = function() {}


    this.getWidgetInfo = function() {
        var res = {
            title: winfo.title,
            url: this.profile["url"],
            icon: winfo.icon
        }
        return res;
    }
 
}
UWAWidget.prototype = new Widget();

function Album() {
	this.init();

	this.cfg = {
		title: loc.text("album_title"),
		module: "Album",
		hasTitle: false
	}

	this.channels = [
	{text:"- القائمة -", value: "", isBold: true},
	{text:"صور حديثة", value: "http://album.m3com.com.sa/rss.xml/newImages/start/0/limit/15"},
	{text:"الأكثر تقييماَ", value: "http://album.m3com.com.sa/rss.xml/imagesMostRated/start/0/limit/15"},
	{text:"الأكثر تعليقاَ", value: "http://album.m3com.com.sa/rss.xml/imagesMostComments/start/0/limit/15"},
	{text:"الأكثر مشاهدة", value: "http://album.m3com.com.sa/rss.xml/imagesMostView/start/0/limit/15"}
	];

	this.defaultProfile["tags"] = "";
	//this.defaultProfile["layout"] = "t"; // s|t
	this.defaultProfile["target"] = "s"; // s|f
	this.defaultProfile["channel"] = "1";



	this.tagUrl = "http://www.m3com.com.sa/feeds/view/T/zoom/N/HPfeeds";
	this.thumpURL = 'http://album.m3com.com.sa/showSquareImage/view/size/89/imageID/';
	this.bigURL = 'http://album.m3com.com.sa/showSquareImage/view/size/135/imageID/';
	var isLoading = false;

	this.domSettings = [
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: loc.text("tag"), className: "settings_label"},
	{ tag: "input", type: "text", size: "15", id: "selectTags", className: "settings_control"},
	{ tag: "input", type: "button", events: {onclick: "setTags()"}, value: loc.text("btn_search"), className: "settings_control"},
	]},
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", innerHTML: "قنوات", className: "settings_label"},
	{ tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
	options: this.channels }
	]},
	{ tag: "div", className: "cls"}
	/*
	,

	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span",style: { textAlign: "right"}, innerHTML: loc.text("album_inp_layout"), className: "settings_label"},
	{ tag: "select", id: "selectLayout", events: {onclick: "setLayout()"}, className: "settings_control",
	options: [
	{ value:"s", text: loc.text("album_slides")},
	{ value:"t", text: loc.text("album_thumbs")}
	]
	}
	]},
	*/


	]


	this.domContent = [ { tag: "div", className: "menu_panel", id: "head", display: false,
	style: { textAlign: "center"},
	childs: [
	createButtonDom(false, "showPrevPhoto()", "widgets/flickr/img/previous.gif"),
	{ tag: "span", innerHTML: "&nbsp;"},
	createButtonDom(false, "showNextPhoto()", "widgets/flickr/img/next.gif")
	]
	},
	{ tag: "div", className: "menu_panel", id: "view_big", style: {textAlign: "center"}, display: false,
	childs: [
	{ tag: "a", href: "void", events: {onclick: "openBigPhoto()"},
	childs: [
	{ tag: "img", id: "big_photo" }
	]}
	]},
	{ tag: "div", className:"album", style:{textAlign:"center"},id: "view_thumbs", display: false }];


	this.onBuildInterface = function() {
		this.elements["settings"].innerHTML = "";
		this.buildDomModel(this.elements.settings, this.domSettings);
		this.buildDomModel(this.elements.content, this.domContent);

		//		this.elements.selectTags.value = this.profile.tags;
		//		this.elements.selectLayout.value = this.profile.layout;
		this.elements["inp_channel"].selectedIndex = this.profile.channel;

	}

	this.setChannel = function() {
		isTags = false;
		if(isLoading) {
			this.elements["inp_channel"].selectedIndex = this.profile.channel;
		} else {
			var c = this.elements["inp_channel"].selectedIndex;
			if(c != this.profile.channel && this.channels[c].value != "") {
				this.profile.channel = c;
				this.save();
				isLoading = false;
				this.refresh();
			}
		}
	}

	this.setLayout = function() {
		this.profile.layout = this.elements.selectLayout.value;
		this.save();
		this.renderPhotos();
	}

	this.setTarget = function() {
		this.profile.target = this.elements.selectTarget.value;
		this.save();
	}
	var tags = '';
	var isTags = false;
	this.setTags = function() {
		tags = trim(this.elements.selectTags.value);
		if(tags != "") {
			//	this.profile.tags = tags;
			//	this.save();
			isLoading = false;
			isTags = true;
			this.refresh();
		}
	}


	this.onOpen = function() {
		this.refresh();
	}


	this.refresh = function() {
		if(!isLoading) {
			this.setTitle(loc.text("msg_loading"));
			this.elements.view_thumbs.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

			var feed = this.channels[this.profile.channel].value;
			if(isTags && tags != '') {
				feed = 'http://album.m3com.com.sa/rss.xml/imagesByTagName/tagName/' + tags.urlencode() + '/start/0/limit/12';
			}
			xmlRequest.send(feed, this, "showPhotos");
			isLoading = true;
			if(!this.isSettingsReduced) {
				this.hideSettings();
			}

			if(this.isReduced) {
				this.show();
			}
		}
	}

	this.showPhotos = function(response) {
		isLoading = false;
		if(response.responseXML) {
			this.data = jQuery.xmlToJSON(response.responseXML);
			this.data = this.data.channel[0];
			if(this.data) {
				this.setTitle(loc.text("album_title"));
				this.renderPhotos();
			}
		}
	}

	this.renderPhotos = function() {
		if(this.data.total[0].Text > 0) {
			this.showAllPhotos();
			/*
			if(this.profile.layout == "s") { //slides
			showEl(this.elements.head);
			this.curPhoto = 0;
			this.showBigPhoto(this.curPhoto);
			} else {
			this.showAllPhotos();
			}
			*/
		} else {
			showEl(this.elements.view_thumbs);
			hideEl(this.elements.view_big);
			hideEl(this.elements.head);
			this.elements.view_thumbs.innerHTML = 'للأسف لا يوجد نتائج';
		}
	}


	/// photo rotate

	this.curPhoto = 0;

	this.showPrevPhoto = function() {
		this.curPhoto--;
		if(this.curPhoto<0) {
			this.curPhoto = this.data.item.length-1;
		}
		this.showBigPhoto(this.curPhoto);
	}

	this.showNextPhoto = function() {
		this.curPhoto++;
		if(this.curPhoto >= this.data.item.length) {
			this.curPhoto = 0;
		}
		this.showBigPhoto(this.curPhoto);
	}


	// show photos

	this.showBigPhoto = function(n) {

		hideEl(this.elements.view_thumbs);
		showEl(this.elements.view_big);
		var src = this.bigURL + this.data.item[n].keywords[0].Text;

		if(ie_nav) {
			preloadImg(this.elements.big_photo, src);
		} else {
			this.elements.big_photo.src = src;
		}
		showEl(this.elements.head);
	}


	this.showAllPhotos = function() {
		showEl(this.elements.view_thumbs);
		hideEl(this.elements.view_big);
		hideEl(this.elements.head);
		var photosDom = [];
		for(var i=0; i<this.data.item.length; i++) {
			photosDom[photosDom.length] = 
			{ tag: "a", href: "void", events: {onclick: "openPhoto("+i+")"},
			innerHTML: "<img style='width:90px;height:75px;' src='" + this.thumpURL + this.data.item[i].keywords[0].Text + "'> "};
			
			
		}
		photosDom.push({tag: "div", className: "cls"});
		photosDom.push({tag: "div", className: "upload", innerHTML: "<a target='_blank' href='http://album.m3com.com.sa/upload/view'><img style='float:none;' border='0' src='static/images/uploadYourPhotos.gif' /></a>"});
		this.elements.view_thumbs.innerHTML = '';
		this.buildDomModel(this.elements.view_thumbs, photosDom);

	}


	this.openBigPhoto = function() {
		this.openPhoto(this.curPhoto);
	}

	this.openPhoto = function(n) {
		//		open((this.profile.target == "s") ? this.data.items[n].link : this.data.items[n]["media:content"].url);
		open(this.data.item[n].link[0].Text);
	}





}
Album.prototype = new Widget();

function PrayerTime() {
	this.init();

	this.cfg = {
		title: loc.text("prayertime_title"),
		hasSettingsBtn: false,
		hasRefreshBtn: false,
		module: "PrayerTime"
	}

	this.defaultProfile["cityNo"] = "0";
	this.feedUrl = "http://www.m3com.com.sa/feeds/view/T/islam/N/prayerTimes";
	this.data;
	var KSACitis = [];

	//KSA Cities
	KSACitis.push({value: '0', text: 'الرياض'});
	KSACitis.push({value: '1', text: 'مكة المكرمة'});
	KSACitis.push({value: '2', text: 'المدينة المنورة'});
	KSACitis.push({value: '3', text: 'الدمام'});
	KSACitis.push({value: '4', text: 'جدة'});
	KSACitis.push({value: '5', text: 'الطائف'});
	KSACitis.push({value: '6', text: 'تبوك'});
	KSACitis.push({value: '7', text: 'المجمعة'});
	KSACitis.push({value: '8', text: 'بريدة'});
	KSACitis.push({value: '9', text: 'وادي الدواسر'});
	KSACitis.push({value: '10', text: 'شقرا'});
	KSACitis.push({value: '11', text: 'ينبع البحر'});
	KSACitis.push({value: '12', text: 'الهفوف - الأحساء'});
	KSACitis.push({value: '13', text: 'حفر الباطن'});
	KSACitis.push({value: '14', text: 'الجبيل'});
	KSACitis.push({value: '15', text: 'الخفجي'});
	KSACitis.push({value: '16', text: 'حائل'});
	KSACitis.push({value: '17', text: 'عرعر'});
	KSACitis.push({value: '18', text: 'القريات'});
	KSACitis.push({value: '19', text: 'الجوف'});
	KSACitis.push({value: '20', text: 'نجران'});
	KSACitis.push({value: '21', text: 'أبها'});
	KSACitis.push({value: '22', text: 'جيزان'});
	KSACitis.push({value: '23', text: 'الباحه'});
	KSACitis.push({value: '24', text: 'شرورة'});


//	var HTML = [{ tag: "table", width: "95%",
//	id: "prayerTime",
//	childs: row}
//	];



	this.domContent = [
	{ tag: "div", className: "prayertime_bgPray",
	childs: [
		{ tag: "div",
		childs: [
			{tag: "table", border: "0", cellspacing: "0", cellpadding: "0",
				childs: [{tag: "tr",
					childs:[
						{tag: "td", className: "txt12", innerHTML: loc.text("prayertime_city")},
						{tag: "td",
							childs:[
								{ tag: "select", id: "selectCity", events: {onchange: "showPrayerTime()"},
									options: KSACitis }
							]
						}
					]
				},
				{tag: "tr",
					childs: [
					{tag: "td", innerHTML: "&nbsp;"},
					{tag: "td", innerHTML: "&nbsp;"}
					]
				}
				]
		}
		]},
		{ tag: "div", id: "prayerTimes", style: {textAlign: "right"}, display: true }
	]
	}
];

	this.onBuildInterface = function() {
		this.elements["settings"].innerHTML = "";
		//this.buildDomModel(this.elements.settings, this.domSettings);
		this.buildDomModel(this.elements.content, this.domContent);

		this.elements.selectCity.value = this.profile.cityNo;
	}

	this.onOpen = function() {
		this.refresh();
	}

	var isDataLoaded = false;
	this.refresh = function() {
		if(!isDataLoaded) {
			isDataLoaded = true;
			this.setTitle(loc.text("msg_loading"));
			xmlRequest.send(this.feedUrl, this, "handleResponse");
		}
	}

	this.handleResponse = function(response) {
		if(response.responseXML.documentElement) {
			this.data = jQuery.xmlToJSON(response.responseXML);
			if(this.data) {
				this.showPrayerTime();
			}
		}
	}

	this.showPrayerTime = function () {
		var cityNo = this.elements.selectCity.value;
		var row = [];
		for(var i = 0; i < this.data.City[cityNo].pTime.length; i++) {
			row.push({ tag: "tr",
			childs: [
			{ tag: "td", width: "50%", align: "right", innerHTML: this.data.City[cityNo].pTime[i].Text},
			{ tag: "td", width: "50%", align: "right", innerHTML: this.data.City[cityNo].pTime[i].name}
			]});
		}

		row.push({ tag: "tr",
			childs: [
			{ tag: "td", width: "50%", colspan: "2", innerHTML: '<a href="http://islam.m3com.com.sa/prayer-time/view/">&raquo; المزيد من اوقات الصلاة في مدن العالم</a>'}
			]});

		var HTML = [
						{ tag: "table", width: "60%", cellspacing: "5", cellpadding: "3", border: "0", id: "prayerTime",
							childs: row}
				];
		this.elements.prayerTimes.innerHTML = '';
		this.buildDomModel(this.elements.prayerTimes, HTML);
		this.profile.cityNo = this.elements.selectCity.value;
		this.setTitle(loc.text("prayertime_title") + ' في ' + this.elements.selectCity[this.elements.selectCity.selectedIndex].text);
		this.save();
	}
}




//sdfsdf
PrayerTime.prototype = new Widget();

function Cnn() {
    this.init();

    this.cfg = {
        title: loc.text("rss_title"),
        module: "Cnn"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://rss.cnn.com/rss/cnn_latest.rss";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { 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: loc.text("rss_all")}
              ]
            },
            { tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "setNewsCount()"}}
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control",
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}
              ]
            },
            { tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "setPeriod()"}}
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},
        { tag: "div", className: "settings_section",
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
  		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel");
        this.isLoading == true;
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "a", href: "void",
                  innerHTML: this.data.title.substr(0,26)
                   });

           /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Cnn.prototype = new Widget();

function Cnnarabic() {
    this.init();

    this.cfg = {
        title: loc.text("cnnarabic_title"),
        module: "Cnnarabic"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://arabic.cnn.com/rss/cnnarabic_topnews.rss";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
		{ tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
    	this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgCnn"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel");
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span", 
                  innerHTML: loc.text("cnnarabic_title")
                   });

            /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgCnn"});
            for(var i=0; i<count; i++) {
                  this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i,
                                     dir: "ltr",
                                     align: "right" });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Cnnarabic.prototype = new Widget();

function Asharqalawsatnews() {
    this.init();

    this.cfg = {
        title: loc.text("asharqalawsatnews_title"),
        module: "Asharqalawsatnews"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.asharqalawsat.com/rss/AAARSS4.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control", events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }           
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]}, { tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
   		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgAsharqalawsat"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "windows" });
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span",
                  innerHTML: loc.text("asharqalawsatnews_title")
                  });

            /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgAsharqalawsat"});
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Asharqalawsatnews.prototype = new Widget();

//
// Widget class definition. Class name must be unique for each widget.
//
function Ashabm3com() {



    //
    // Calling of init() function must be placed at begining of widget.
    //
    this.init();




    //
    // Widget config - definition of widget parametrs.
    // 
    // Note: you does't need to overload default values,
    // for example:      
    //
    //    this.cfg = {
    //        module: "Demo"
    //    }
    //  

    this.cfg = {
        // Caption icon image. 
        // Default value: true
        hasIcon: true, 
        hasTitle: false,

        // Caption size button (show/hide widget content). 
        // Default value: true
        hasSizeBtn: true,

        // Caption close button (close widget and remove it from page). 
        // Default value: true
        hasCloseBtn: true,

        // Caption refresh button (this.refresh() method will be called on click). 
        // Default value: true
        hasRefreshBtn: true,

        // Caption settings button (show/hide widget settings panel). 
        // Default value: true
        hasSettingsBtn: false,

        // Drag&drop (widget window will be dragable). 
        // Default value: true
        hasDrag: true,

        // Show confirmation prompt to user before closing widget. 
        // Default value: true
        hasOnCloseConfirm: true,

        // Widget will has profile or not. 
        // Default value: true
        hasProfile: true,

        // Widget name (name of widget class)
        // Important: always must be filled and be unique for each widget
        module: "Ashabm3com",

        // Method of sending widget profile to server. Must be "GET" or "POST"
        // Default value: "GET"
        saveMethod: "GET"
    };




    //
    // Widget profile default values. 
    // That values will stored to profile on first start(when user add widget to page)
    //
    this.defaultProfile["title"] = loc.text("ashabm3com_title");
    this.defaultProfile["text"] = "";




    //
    // Hash HTML model for Demo widget settings panel
    //
    // About multylanguage support:
    // loc.text(label) is system function that return text string for label corresponding current user language,
    // all text strings must be added to language .xml files in format:
    // <string id="label">string</string>
    //
    this.modelSettings = [
 
    ]

    //
    // Hash HTML model for Demo widget content area
    //
    this.modelContent = [
    	{ tag: "div", align: "center", id: "loading", display: true,
    		childs:
    		[
    			{ tag: "img", src: "static/client/loader.gif" }
    		]
    	},
        { tag: "div", id: "main", className: "main", display: false,
        	childs: 
        	[
        		{ tag: "div", className: "mart10 marr10", 
        			childs:
        			[
        				{ tag: "table", 
        					childs:
        					[	
	    						{ tag: "tr", 
	    							childs: 
	    							[
	    								{ tag: "td", width: "100", childs: [{ tag: "img", id: "avatar", className: "avatar", width:"80", height:"80"}]},
	    								{ tag: "td", 
	    								childs:
	    								[
	    								{ tag: "table", cellpadding: "5", childs: 
	    									[
	    										{ tag: "tr", childs: [ { tag: "td", id: "fullname", className: "fullname", colspan: "2"} ]},
	    										{ tag: "tr", childs: 
	    										[
	    											{ tag: "td", childs: [{ tag: "img", width:"16", height:"14", src: "static/client/iconProfile.gif"}] }, 
	    											{ tag: "td", childs: [ { tag: "a", id: "userProfileLink", calssName: "userProfileLink", target: "_blank" } ]}
	    										]},
	    										{ tag: "tr", childs: 
	    										[
	    											{ tag: "td", childs: [ { tag: "img", width:"16", height:"14", src: "static/client/iconEdit.gif"} ] }, 
	    											{ tag: "td", childs: [ { tag: "a", id: "editProfile", calssName: "editProfile", target: "_blank" } ]}
	    										]}
	    									]
	    									}
	    								]
	    								}
	    							]
	    						}    					
    	    				]
        				}
        			]
        		},
        		{ tag: "div", id: "users", className: "mart10"},
        		{ tag: "div", id: "friendson", className: "mart10"},
        		{ tag: "div", id: "friendsonline", className: "mart10" },
        		{ tag: "div", className: "cls" },
        	]
        }
      
    ]

/*

{ tag: "table", className: "sys_table", style: {width: "100%"},
	       childs: [
	         { tag: "tr",
	           childs: [
	           		{ tag: "td", style: {textAlign: "center"}, 
	              childs: [                            
	                 { tag: "img", id: "userImage", src: "" },
	                 { tag: "a", id: "userProfileLink", href: "" },
	                 { tag: "br"},                            
	                 { tag: "a", id: "editProfile", href: ""},
	                 { tag: "br"},
	                 { tag: "div", id: "userFullName"}
	              ]}
	           ] 
	          }
	       ]}
*/

    //
    // Build all static interface elements for widget here
    //
    this.onBuildInterface = function() {      
        this.req = request.send({},this);
        this.buildDomModel(this.elements["settings"], this.modelSettings);
        this.buildDomModel(this.elements["content"], this.modelContent);
        // call function this.setTitle() to set title in widget caption
        this.setTitle(this.profile["title"]);
    }
    
	this.url;
	var isDataLoaded = false;
	this.dispatchMsg = function(msg) {		
		this.url = "http://friends.m3com.com.sa/as7abAfaqi/view/uname/" + msg.uname.urlencode();		
		if(!isDataLoaded) {
			isDataLoaded = true;			
			xmlRequest.send(this.url, this, "handleResponse");
		}				 
    }
    
    //handle XML respone 
	this.handleResponse = function(response) {				
		if(response.responseXML.documentElement) {
		this.data = jQuery.xmlToJSON(response.responseXML);
			if(this.data) {
				if ( this.data.userexist[0].Text == 1 ) {
					this.showElement('main');
					this.hideElement('loading');
					this.elements["fullname"].innerHTML = this.data.userInformation[0].userFullName[0].Text;
					this.elements["avatar"].src = this.data.userInformation[0].userImage[0].Text;
					this.elements["userProfileLink"].href = this.data.userInformation[0].userProfileLink[0].Text;
	       			this.elements["userProfileLink"].innerHTML = loc.text("myaccount");
	       			this.elements["editProfile"].href =this.data.userInformation[0].editProfile[0].Text;
	       			this.elements["editProfile"].innerHTML = loc.text("editmyaccount");
	       			this.buildDomModel(this.elements["users"],
	       				{ tag: "div", className: "subTitleGray", innerHTML: loc.text("ashabm3com_friendsnews") }
	       			);
	       			try {
	       				this.elements["users"].innerHTML = '';     					
						for(var i=0; i< this.data.userAction[0].userActionItem.length; i++) {
							this.buildDomModel(this.elements["users"],
							{ 
								tag: "div", id: "userAction", className: "userAction",
								innerHTML:  this.data.userAction[0].userActionItem[i].action[0].Text
							}); 
							
						}
					} catch ( err ) {
						this.buildDomModel(this.elements.content,
							{ 
								tag: "div", id: "userAction", className: "liveError",
								innerHTML: loc.text("onactions")
							});
					}
					//this.buildDomModel(this.elements["friendson"],
	       			//	{ tag: "div", className: "subTitleGray", innerHTML: loc.text("ashabm3com_friendson") }
	       			//);
					try {		
						this.elements["friendson"].innerHTML = '';
						this.elements["friendsonline"].innerHTML = '';
						var onlineFriends = this.data.onlineFriends[0].onlineFriendsItem.length;						
						this.buildDomModel(this.elements["friendson"],
						{ 
							tag: "div", id: "onlineFriendsNum", className: "subTitleGray",
							innerHTML:  loc.text("onlinefriendsnum") + onlineFriends + loc.text("onlinefnum")
						});				
		
						for ( var i=0; i< onlineFriends; i++ ) {
							this.buildDomModel(this.elements["friendsonline"],
							{ 
								tag: "div", id: "onlineFriends", className: "onlineFriends",
								innerHTML:  this.data.onlineFriends[0].onlineFriendsItem[i].friend[0].Text
							});					
						}
					} catch ( err ) { }
				} else {
					this.hideElement('loading');					
					this.showElement('main');
					this.elements['main'].innerHTML = loc.text("ashabm3com_on_user");
					this.elements['main'].className = "liveError";
				}
			}
		}
	}
	
    //
    // this.onOpen() function will called when widget added to page.
    //
    this.onOpen = function() {
   
        // Any code
    }


    
    //
    // Caption refresh button call back
    //
    this.refresh = function() {
    	this.hideElement('main');
		this.showElement('loading');
    	xmlRequest.send(this.url, this, "handleResponse");   
    	if(this.isReduced) {
			this.show();
		} 
    }

 
}

//
// Definition of class prototype. Prototype always must be Widget object.
//
Ashabm3com.prototype = new Widget();

//
// Widget class definition. Class name must be unique for each widget.
//
function Sport() {
    //
    // Calling of init() function must be placed at begining of widget.
    //
    this.init();    this.cfg = {
        // Caption icon image. 
        // Default value: true
        hasIcon: true, 
        hasTitle: false,

        // Caption size button (show/hide widget content). 
        // Default value: true
        hasSizeBtn: true,

        // Caption close button (close widget and remove it from page). 
        // Default value: true
        hasCloseBtn: true,

        // Caption refresh button (this.refresh() method will be called on click). 
        // Default value: true
        hasRefreshBtn: true,

        // Caption settings button (show/hide widget settings panel). 
        // Default value: true
        hasSettingsBtn: false,

        // Drag&drop (widget window will be dragable). Sport
        // Default value: true
        hasDrag: true,

        // Show confirmation prompt to user before closing widget. 
        // Default value: true
        hasOnCloseConfirm: true,

        // Widget will has profile or not. 
        // Default value: true
        hasProfile: true,

        // Widget name (name of widget class)
        // Important: always must be filled and be unique for each widget
        module: "Sport",

        // Method of sending widget profile to server. Must be "GET" or "POST"
        // Default value: "GET"
        saveMethod: "GET"
    };
    
    //
    // Widget profile default values. 
    // That values will stored to profile on first start(when user add widget to page)
    //
    this.defaultProfile["title"] = loc.text("m3comsfl_title");

    //
    // Hash HTML model for Demo widget settings panel
    //
    this.modelSettings = [ 
    ]


    //
    // Hash HTML model for Demo widget content area
    //
    this.modelContent = [    	
    	{ tag: "div", id: "saudiFootbal", className: "saudiFootbal", 
    	childs: [
    		{ tag: "div", id: "saudiHeader", className: "bgSFL"},
    		{ tag: "div", id: "tabSet", className: "tabSet", 
    			childs: [
    			{tag: "div", className: "divList", childs: [
    				{ tag: "ul", id: "tabList", className: "tabList", 
	    			childs: [
	    				{ tag: "li", id: "tabNews", className: "tabNews", name: "news", 
	    				childs: [
    						{ tag: "a", href: "void", innerHTML: loc.text("m3comsfl_news"), events: { onclick: "openUrl('news')" }},
    					]},	    			
    					{ tag: "li", id: "tabMatches", className: "tabMatches", name: "matches", 
	    				childs: [
    						{ tag: "a", href: "void", innerHTML: loc.text("m3comsfl_matches"), events: { onclick: "openUrl('matches')" }},
    					]},
    					{ tag: "li", id: "tabRanking", className: "tabRanking", name: "ranking", 
	    				childs: [
    						{ tag: "a", href: "void", innerHTML: loc.text("m3comsfl_ranking"), events: { onclick: "openUrl('ranking')" }	},
    					]},
    					{ tag: "li", id: "tabLive", className: "tabLive on", name: "live", 
	    				childs: [
    						{ tag: "a", href: "void", innerHTML: loc.text("m3comsfl_live"), events: { onclick: "openUrl('live')" }
    						},
    					]},    					
	    			]},
    			]},	    			
	    		{ tag: "div", id: "live", display: false, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },
	    		{ tag: "div", id: "matches", className: "matches", display: false, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },
	        	{ tag: "div", id: "ranking", calssName: "ranking", display: true, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },	        	
	        	{ tag: "div", id: "news", className: "news", display: false, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },	
    			]},
    	]}
    ]



    //
    // Build all static interface elements for widget here
    //
    this.onBuildInterface = function() {
    	 
    	//this.openUrl('news');        
        this.buildDomModel(this.elements["settings"], this.modelSettings);
        this.buildDomModel(this.elements["content"], this.modelContent);        
        this.setTitle(this.profile["title"]);
    }
    
    
    
	this.feedType1 = '';
	this.url = "http://sports.m3com.com.sa/ASPX_Pages/FeedsToSTC.aspx?sec_id=330&type=";
	
    //handle XML respone 
	this.handleResponse = function(response) {
		if (response.responseXML.documentElement) {		
		this.data = jQuery.xmlToJSON(response.responseXML);
		this.elements[feedType1].innerHTML = "";
			
			if (this.data) {
			 switch ( feedType1 ) {
	           case "matches":
	                /*** Matches ***/
	                
	                if (this.data.Section_Status[0].Text != 'False') {
		       			try { 
		       				this.matchesElements = "<table id='mainmatches' class='mainRanking' width='100%' cellpadding='3' cellspeacing='0'><tr><td class='nowrapwithalign' >"
		       					+ loc.text("m3comsfl_team1") + "</td><td colspan='2' class='nowrapwithalign'>"
		       					+ loc.text("m3comsfl_score") + "</td><td class='nowrapwithalign'>" 
		       					+ loc.text("m3comsfl_team2") + "</td><td class='nowrapwithalign'>"  
								+ loc.text("m3comsfl_gtime") + "</td><tr>";
		       			    
							for(var i=0; i< this.data.Matches[0].Match.length; i++) {
								this.matchesElements += 
								"<tr><td class='aligncenter'>" 
									+ this.data.Matches[0].Match[i].item[0].Team1_Name[0].Text + "</td><td><div class='goal'>"
									+ this.data.Matches[0].Match[i].item[0].Team1_score[0].Text + "</div></td><td><div class='goal'>"
									+ this.data.Matches[0].Match[i].item[0].Team2_score[0].Text + "</div></td><td class='aligncenter'>"
									+ this.data.Matches[0].Match[i].item[0].Team2_Name[0].Text + "</td><td>"
									+ this.data.Matches[0].Match[i].item[0].date[0].Text + "</td></tr>";
							}
							this.matchesElements += "</tr></table>";
							this.elements['matches'].innerHTML = this.matchesElements;
							jQuery("table.mainmatches tr:even").addClass("dark");
						} catch ( err ) {
							this.buildDomModel(this.elements['matches'],
								{ 
									tag: "div", id: "matdches", 
									innerHTML: loc.text("onactions")
								});					
						} 
					} else {						
						this.buildDomModel(this.elements['matches'],
						{ 
							tag: "div", id: "matdches", className: "liveError",
							innerHTML: loc.text("sport_noleague")
						});	
					}
	                break;
	            case "ranking":
	                       
	          		/*** Rankings ***/				
					try { 
						this.tableElements = "<table id='mainRanking' class='mainRanking' width='100%' cellpadding='4' cellspeacing='0'><tr><td>" 
													+ loc.text("m3comsfl_team") + "</td><td>" 
													+ loc.text("m3comsfl_pld") + "</td><td>" 
													+ loc.text("m3comsfl_won") + "</td><td>" 
													+ loc.text("m3comsfl_draw") + "</td><td>" 
													+ loc.text("m3comsfl_lost") + "</td><td>" 
													+ loc.text("m3comsfl_gf") + "</td><td>" 
													+ loc.text("m3comsfl_gc") + "</td><td>" 
													+ loc.text("m3comsfl_pts");
						for(var i=0; i< this.data.item.length; i++) {
							this.tableElements += 
							"<tr><td>" 
								+ this.data.item[i].Team_Name[0].Text + "</td><td>"
								+ this.data.item[i].Played[0].Text + "</td><td>"
								+ this.data.item[i].Win[0].Text + "</td><td>"
								+ this.data.item[i].Draw[0].Text + "</td><td>"
								+ this.data.item[i].Lose[0].Text + "</td><td>"
								+ this.data.item[i].Scored[0].Text + "</td><td>"
								+ this.data.item[i].conceded[0].Text + "</td><td>"
								+ this.data.item[i].Points[0].Text + "</td></tr>";							
						}
						this.tableElements += "</tr></table>";
						this.elements['ranking'].innerHTML = this.tableElements;
						jQuery("table.mainRanking tr:even").addClass("dark");
					} catch ( err ) {
					
						/*this.buildDomModel(this.elements['mainRanking'],
							{ 
								tag: "div", id: "matdches", 
								innerHTML: loc.text("onactions")
							});
						*/
					}
					
	                break;
	            case "news":
	            	this.newsData = this.data;
	                /*** News ***/			
					try {
	       				this.callNews(0);
					} catch ( err ) {
					/*
						this.buildDomModel(this.elements['news'],
							{ 
								tag: "div", id: "matdches", 
								innerHTML: loc.text("onactions")
							});
					*/
					}
	                break;
	                    	case "live":	           	           	
	                /*** Live ***/	            
	       			try { 
	       				for(var i=0; i< this.data.LiveMatch.length; i++) {
		       			    this.buildDomModel(this.elements['live'],
		       			    	{ tag: "div", 
		       			    	childs: [
		       			    		{ tag: "div", innerHTML: this.data.LiveMatch[i].StartDt[0].Text.replace(/AM/,loc.text("m3comsfl_am")).replace(/PM/,loc.text("m3comsfl_pm")), className: "txt11"},	       			    
				       			    { tag: "table", id: "livematches", className: "livematches", width: "100%", cellpadding: "5", cellspacing: "0", 
				       			    childs: 
				       			    [
				       			    	{ tag: "tr", 
										childs:
										[								
											{ tag: "td", childs: [ { tag: "img", src: this.data.LiveMatch[i].HomeTeamImage[0].Text} ] },
											{ tag: "td", innerHTML:  this.data.LiveMatch[i].HomeTeam[0].Text },
											{ tag: "td", innerHTML:  this.data.LiveMatch[i].HomeScore[0].Text + " - " + this.data.LiveMatch[i].AwayScore[0].Text},
											{ tag: "td", innerHTML:  this.data.LiveMatch[i].AwayTeam[0].Text },
											{ tag: "td", childs: [ { tag: "img", src: this.data.LiveMatch[i].AwayTeamImage[0].Text} ] },
										]}
				       			    ]}
				       			]}
		       			    );
	       			    }						
					} catch ( err ) {					
						this.buildDomModel(this.elements['live'],
						{
							tag: "div", id: "liveError", className: "liveError",
							innerHTML: loc.text("m3comsfl_nolive")
						});					
					}                
	                break;
	        	}
			}
		}
	}
	
	this.setNewsCount = function(count) {
        this.callNews(count);
    }
	
	this.callNews = function ( from ) {	
		count = parseInt(from , 10) + 3;
		prevCount = parseInt(from , 10) - 3;
		
		if (count > this.newsData.item.length) {
			count = this.newsData.item.length;
		}
		
		this.elements["news"].innerHTML = "";
		for ( var i= from; i< count; i++) {
			var img = this.newsData.item[i].image[0].Text.replace(/temp/, 'thumb');
			var image = img.replace(/sports.m3com.com.sa\/SportsImages/,"sportimages.m3com.com.sa");
			this.buildDomModel(this.elements['news'],
			{ tag: "div", className: "matchesNews",
				childs:[								
					{ tag: "a", className: "Team_Name", events:{ onclick:"openURL2('" + this.newsData.item[i].link[0].Text + "')"},
					childs: [
						{ tag: "img", src: image, className: "fr",style: { width: "65px", height: "50px" }}
					] },
					{ tag: "h3", 
					childs: [
						{ tag: "a", className: "Team_Name", innerHTML:  this.newsData.item[i].title[0].Text, events:{ onclick:"openURL2('" + this.newsData.item[i].link[0].Text + "')"} }
					] },
					{ tag: "p", className: "Team1_Name", innerHTML: this.newsData.item[i].intro[0].Text.truncate(100) },
				]
			}			
			);			
		}
			
		if (prevCount >= 0) { 
			this.buildDomModel(this.elements['news'],
				{ tag: "img", src: "static/client/prev1.gif", title: loc.text("prev"), className: "fr",
					 events: { onclick: "setNewsCount(" + prevCount + ")"}, style: { cursor: "pointer" }
				}				
			);
			
		}
			
		if ( count < this.newsData.item.length) { 
			this.buildDomModel(this.elements['news'],
				{ tag: "img", src: "static/client/next1.gif", title: loc.text("next"), className: "fl", 
					events: { onclick: "setNewsCount(" + count + ")"}, style: { cursor: "pointer" }
				}
			);
		}
		this.buildDomModel(this.elements['news'],
				{ tag: "div", className: "cls"}				
		);
	}
	
    //
    // this.onOpen() function will called when widget added to page.
    //
    this.onOpen = function() {
    	this.openUrl('news');
    }
    
    this.openURL2 = function (url){	
		window.open(url);
	}
    
	var isMatchesLoaded = false;
	var isNewsLoaded = false;
	var isRankingsLoaded = false;
	var isLiveLoaded = false;
	this.openUrl = function(type) {		
		urlRequest = this.url + type;		
		feedType1 = type;
		switch (type){
			case "news":			
				if (!isNewsLoaded) {
					this.feedType1 = "news";				
					isNewsLoaded = true;	
					xmlRequest.send(this.url+"news", this, "handleResponse");
				}
				this.elements['tabNews'].className = 'on';
				this.elements['tabRanking'].className = '';
				this.elements['tabMatches'].className = '';
				this.elements['tabLive'].className = '';	
				break;
			case "matches":
				if (!isMatchesLoaded) {
					isMatchesLoaded = true;	
					xmlRequest.send(urlRequest, this, "handleResponse");
				}
				this.elements['tabNews'].className = '';
				this.elements['tabRanking'].className = '';
				this.elements['tabMatches'].className = 'on';
				this.elements['tabLive'].className = '';	
				break;
			case "ranking":
				if (!isRankingsLoaded) {
					isRankingsLoaded = true;	
					xmlRequest.send(urlRequest, this, "handleResponse");
				}
				this.elements['tabNews'].className = '';
				this.elements['tabRanking'].className = 'on';
				this.elements['tabMatches'].className = '';
				this.elements['tabLive'].className = '';				
				break;			
			case "live":
				if (!isLiveLoaded) {
					isLiveLoaded = true;	
					xmlRequest.send("http://sports.m3com.com.sa/aspx_pages/LiveMatchesFeeds.aspx", this, "handleResponse");
				}
				this.elements['tabNews'].className = '';
				this.elements['tabRanking'].className = '';
				this.elements['tabMatches'].className = '';
				this.elements['tabLive'].className = 'on';
				break;
		}
		
		var sections = ["news", "matches", "ranking", "live"];
		for(var i = 0; i<sections.length; i++) {
			if(type == sections[i]) {				
				this.showElement(sections[i]);
			} else {
				this.hideElement(sections[i]);
			}
		}
	}
    
    //
    // Caption refresh button call back
    //
    this.refresh = function() {
    	
    	switch (feedType1){
			case "news":
				
				this.elements["news"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send(urlRequest, this, "handleResponse");				
				break;
			case "matches":
				//this.elements["matches"].innerHTML = "";
				//this.elements["matches"].innerHTML = loc.text("msg_loading");
				this.elements["matches"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send(urlRequest, this, "handleResponse");
				break;
			case "ranking":
				//this.elements["ranking"].innerHTML = "";
				//this.elements["ranking"].innerHTML = loc.text("msg_loading");
				this.elements["ranking"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send(urlRequest, this, "handleResponse");
				break;			
			case "live":
				//this.elements["live"].innerHTML = "";
				//this.elements["live"].innerHTML = loc.text("msg_loading");
				this.elements["live"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send("http://sports.m3com.com.sa/aspx_pages/LiveMatchesFeeds.aspx", this, "handleResponse");				
				break;
		}
		if(this.isReduced) {
			this.show();
		}
    } 
}

//
// Definition of class prototype. Prototype always must be Widget object.
//
Sport.prototype = new Widget();


function M3comask() {



    //
    // Calling of init() function must be placed at begining of widget.
    //
    this.init();

    this.cfg = {
        // Caption icon image. 
        // Default value: true
        hasIcon: true, 
		hasTitle: false,
        // Caption size button (show/hide widget content). 
        // Default value: true
        hasSizeBtn: true,

        // Caption close button (close widget and remove it from page). 
        // Default value: true
        hasCloseBtn: true,

        // Caption refresh button (this.refresh() method will be called on click). 
        // Default value: true
        hasRefreshBtn: true,

        // Caption settings button (show/hide widget settings panel). 
        // Default value: true
        hasSettingsBtn: false,

        // Drag&drop (widget window will be dragable). Sport
        // Default value: true
        hasDrag: true,

        // Show confirmation prompt to user before closing widget. 
        // Default value: true
        hasOnCloseConfirm: true,

        // Widget will has profile or not. 
        // Default value: true
        hasProfile: true,

        // Widget name (name of widget class)
        // Important: always must be filled and be unique for each widget
        module: "M3comask",

        // Method of sending widget profile to server. Must be "GET" or "POST"
        // Default value: "GET"
        saveMethod: "GET"
    };




    //
    // Widget profile default values. 
    // That values will stored to profile on first start(when user add widget to page)
    //
    this.defaultProfile["title"] = loc.text("m3comask_title");    

    //
    // Hash HTML model for Ask widget settings panel
    this.modelSettings = [
       
    ]

    //
    // Hash HTML model for Demo widget content area
    //
    this.modelContent = [
    	{ tag: "div", id: "ask", className: "ask", 
    	childs: [
    		{ tag: "div", id: "askHeader", className: "askHeader"},
    		{ tag: "div", id: "tabSet", className: "tabSet", 
    			childs: [
    				{ tag: "div", className: "divList", 
	    				childs:	[
		    			{ tag: "ul", id: "tabList", className: "tabList", 
		    			childs: [
		    				{ tag: "li", id: "latestfeeds", className: "latestfeeds on", name: "latestfeeds", 
		    				childs: [
	    						{ tag: "a", href: "void", innerHTML: loc.text("m3comask_latest"), events: { onclick: "openUrl('latestContainer')" }},
	    					]},
		    				{ tag: "li", id: "tabLive", className: "tabLive", name: "live", 
		    				childs: [
	    						{ tag: "a", href: "void", innerHTML: loc.text("m3comask_groups"), events: { onclick: "openUrl('cats')" }},
	    					]},
	    					
	    					
	    					
		    			]},
	    			]},
	    			{ tag: "div", id: "catContainer", className: "catContainer", display: false,
	    				childs: [
							{ tag: "div", id: "cats", calssName: "cats", display: true, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>'},
	    					{ tag: "div", id: "subcatsa", className: "subcatsa", display: false, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },
	    					{ tag: "div", id: "getSubCatFeeds", className: "latestContainer", display: false, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },
	    				]	    			
	    			},
	    			{ tag: "div", id: "latestContainer", className: "latestContainer", display: true, innerHTML: '<div align="center"><img src="static/client/loader.gif" /></div>' },
    			]},
    	]}
    ]



    //
    // Build all static interface elements for widget here
    //
    this.onBuildInterface = function() { 		
        //this.req = request.send({},this);
        //this.openUrl('cats');
        this.buildDomModel(this.elements["settings"], this.modelSettings);
        this.buildDomModel(this.elements["content"], this.modelContent);
        // call function this.setTitle() to set title in widget caption
        this.setTitle(this.profile["title"]);        
    }
    
    //get the sub categories
    //this.subOptions = [];
	this.getSubCats = function() {
  		try {
	  		if( catId != -1) { 
	  			this.subOptions = []; 			
	  			this.elements['subcatsa'].innerHTML = "";
	  			this.showElement('subcatsa');
	  			catId = this.data1.category[this.elements["maincats"].value].id[0].Text;	    		
		    	this.subOptions.push({value: "-1", text: loc.text("m3comask_selsub")});   		    	
			        for(var i=0; i< this.data1.category[this.elements["maincats"].value].subCats[0].cat.length; i++) {
			        	this.subOptions.push({value: this.data1.category[this.elements["maincats"].value].subCats[0].cat[i].id[0].Text, text: this.data1.category[this.elements["maincats"].value].subCats[0].cat[i].name[0].Text});        		        	            			
			        }		         
		       		this.buildDomModel(this.elements['subcatsa'],{tag: "select", id: "subcats", className: "subcats mart5", events: { onchange: "getFeedIds()" }, options: this.subOptions});
	       	}	
		} catch ( err ) {}
    }
	
	var catId = "";
	var subCatId = "";
	
	this.getFeedIds = function() {
		subCatId = this.elements["subcats"].value;		
		if ( subCatId != -1 ) {
			this.elements["getSubCatFeeds"].innerHTML = "";
			this.elements["getSubCatFeeds"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
			this.showElement('getSubCatFeeds');			
			url = "http://ask.m3com.com.sa/widget/view/type/latestCat/l1/" + catId + "/l2/" + subCatId;
			this.openUrl('getSubCatFeeds');
		} 
					
    }
    
    
    //handle XML response
    this.catsOptions = []; 
	this.handleResponse = function(response) {
		 			
		if (response.responseXML.documentElement) {
		switch ( feedType ) {
	    	case "cats":	    		           		
				this.data1 = jQuery.xmlToJSON(response.responseXML);		
				this.elements[feedType].innerHTML = "";	
				if (this.data1) {	
	                /*** Categories ***/          
	       			try {
	       				
	       				this.catsOptions.push({value: "-1", text: loc.text("m3comask_selcat")});	       				
	       				for(var i=0; i< this.data1.category.length; i++) {
	       					this.catsOptions.push({value: i, text: this.data1.category[i].name[0].Text});        					
    					}	       				
		       			//var categories = "<option value='-1'>" + loc.text("m3comask_selcat") + "</option>";
		                //for(var i=0; i< this.data1.category.length; i++) {
		                //			alert(this.data1.category[i].name[0].Text);
		                //	categories += "<option value='" + i + "'>" + this.data1.category[i].name[0].Text + "</option>";
		                //} 
	       			    this.buildDomModel(this.elements['cats'],{tag: "select", id: "maincats", className: "maincats mart10", events: { onchange: "getSubCats()" },options: this.catsOptions});	
					} catch ( err ) {}
				}                
	            break;			
			case "getSubCatFeeds":
	        	    this.data = jQuery.xmlToJSON(response.responseXML);		
					this.elements[feedType].innerHTML = "";	
					if (this.data) {	
	                	/*** Sub Category Feeds ***/			
						try {
	       					this.callNews(0);
						} catch ( err ) {}
					}
	                break;
			case "latestContainer":
	        	    this.dataCats = jQuery.xmlToJSON(response.responseXML);		
					this.elements[feedType].innerHTML = "";	
					if (this.dataCats) {	
	                	/*** Sub Category Feeds ***/			
						try {
	       					this.callLatestFeeds(0);
						} catch ( err ) {}
					}
	                break;
	        	}//switch
			}//if
	}//handle
	
	this.setNewsCount = function(count) {
		if ( feedType == 'latestContainer') {		
        	this.callLatestFeeds(count);
        } else {
        	this.callNews(count);
        }
    }
    
    this.callNews = function ( from ) {    	
		if (this.data.item) {
			count = parseInt(from , 10) + 3;
			prevCount = parseInt(from , 10) - 3;		
		if (count > this.data.item.length) {
			count = this.data.item.length;
		}		
		this.elements["getSubCatFeeds"].innerHTML = "";
		
		
		for ( var i= from; i< count; i++) {
			this.buildDomModel(this.elements['getSubCatFeeds'],
			{ tag: "div", 
				childs:[
					{ tag: "h3", 
					childs: [
						{ tag: "a", className: "Team_Name", innerHTML:  this.data.item[i].question[0].Text, href : "void(0)", style: { cursor: "pointer" },
							 events:{
							 	onclick:"openURL2('"+this.data.item[i].link[0].Text+"')"
							 	}
						}
					] },					
					{ tag: "p", className: "Team1_Name", innerHTML:  this.data.item[i].answer[0].Text.truncate(100) },
				]
			}			
			);						
		}
			
		if (prevCount >= 0) { 
			this.buildDomModel(this.elements['getSubCatFeeds'],
			{ tag: "img", src: "static/client/prev1.gif", title: loc.text("prev"), className: "fr", events: { onclick: "setNewsCount(" + prevCount + ")"}, style: { cursor: "pointer" } },
			{ tag: "div", className: "cls"}
			);
		}
			
		if ( count < this.data.item.length) { 
			this.buildDomModel(this.elements['getSubCatFeeds'],
			{ tag: "img", src: "static/client/next1.gif", title: loc.text("next"), className: "fl", events: { onclick: "setNewsCount(" + count + ")"}, style: { cursor: "pointer" }	},
			{ tag: "div", className: "cls"} 
			);
		}
		this.buildDomModel(this.elements['getSubCatFeeds'],
				{ tag: "div", className: "cls"}				
		);
		} else {
			this.elements["getSubCatFeeds"].innerHTML = loc.text("m3comask_no_content");
		}		
	}
	
	this.openURL2 = function (url){	
		window.open(url);
	}
	
	this.callLatestFeeds = function ( from ) {
	if (this.dataCats.item) {
			count = parseInt(from , 10) + 3;
			prevCount = parseInt(from , 10) - 3;		
		if (count > this.dataCats.item.length) {
			count = this.dataCats.item.length;
		}		
		this.elements["latestContainer"].innerHTML = "";
		
		
		for ( var i= from; i< count; i++) {
			this.buildDomModel(this.elements['latestContainer'],
			{ tag: "div", 
				childs:[
					{ tag: "h3", className: "mart10",
					childs: [
						{ tag: "a", className: "Team_Name", innerHTML:  this.dataCats.item[i].question[0].Text, style: { cursor: "pointer" },
							events:{ onclick:"openURL2('" + this.dataCats.item[i].link[0].link[0].Text + "')"}
						}
					] },					
					{ tag: "p", className: "Team1_Name", innerHTML:  this.dataCats.item[i].answer[0].Text.truncate(100) + "..." },
				]
			}			
			);						
		}
			
		if (prevCount >= 0) { 
			this.buildDomModel(this.elements['latestContainer'],
			{ tag: "img", src: "static/client/prev1.gif", title: loc.text("prev"), className: "fr", events: { onclick: "setNewsCount(" + prevCount + ")"}, style: { cursor: "pointer" } },
			{ tag: "div", className: "cls"}
			);
		}
			
		if ( count < this.dataCats.item.length) { 
			this.buildDomModel(this.elements['latestContainer'],
			{ tag: "img", src: "static/client/next1.gif", title: loc.text("next"), className: "fl", events: { onclick: "setNewsCount(" + count + ")"}, style: { cursor: "pointer" }	},
			{ tag: "div", className: "cls"} 
			);
		}
		
		this.buildDomModel(this.elements['latestContainer'],
				{ tag: "div", className: "cls"}				
		);
		} else {
			this.elements["latestContainer"].innerHTML = loc.text("m3comask_no_content");
		}		
	}
	
    //
    // this.onOpen() function will called when widget added to page.
    //
    this.onOpen = function() {
    	this.openUrl('latestContainer'); 
    }
    
	var isSubCatsLoaded = false;
	var isCatsLoaded = false;
	var isLatestContainer = false;
		
	this.feedType = '';
	//this.url = "http://sports.m3akm.com.sa/ASPX_Pages/FeedsToSTC.aspx?sec_id=219&type=news";
	
	this.openUrl = function(type) {		
		urlRequest = this.url + type;
		feedType = type;
		switch (type){
			
			case "cats":			
				//urlRequest = this.url + "getCats";
				this.hideElement('latestContainer');								
				this.showElement('catContainer');
				this.elements['latestfeeds'].className = '';
				this.elements['tabLive'].className = 'on';	
				if (!isCatsLoaded) {				
					isCatsLoaded = true;	
					xmlRequest.send("http://ask.m3com.com.sa/widget/view/type/getCats", this, "handleResponse");
				}
				break;
			case "getSubCatFeeds":
					xmlRequest.send(url, this, "handleResponse");				
				break;
			case "latestContainer":				
				this.hideElement('catContainer');				
				this.showElement('latestContainer');
				this.elements['tabLive'].className = '';	
				this.elements['latestfeeds'].className = 'on';								
				if (!isLatestContainer) {		
					isLatestContainer = true;	
					xmlRequest.send('http://ask.m3com.com.sa/widget/view/type/latestQwithAnswers', this, "handleResponse");
				}
				break;
			case "catContainer":				
				this.hideElement('latestContainer');								
				this.showElement('catContainer');
				this.elements['latestfeeds'].className = '';
				this.elements['tabLive'].className = 'on';						
				
				break;
		}	
	}
    
    //
    // Caption refresh button call back
    //
    this.refresh = function() {
    	switch (feedType){
			case "latestContainer":		
				//this.elements["latestContainer"].innerHTML = "";
				this.elements["latestContainer"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send("http://ask.m3com.com.sa/widget/view/type/latestQwithAnswers", this, "handleResponse");				
				break;
			case "getSubCatFeeds":
			
				//this.elements["catContainer"].innerHTML = "";
				this.elements["catContainer"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
				xmlRequest.send(url, this, "handleResponse");
				this.getFeedIds();
				break;
		}
		if(this.isReduced) {
			this.show();
		}	
    }

 
}

//
// Definition of class prototype. Prototype always must be Widget object.
//
M3comask.prototype = new Widget();

function M3comMail() {
	this.init();


	this.cfg = {
		hasSettingsBtn: true,
		title: loc.text("m3commail_title"),
		module: "M3comMail",
		hasTitle: false
	};

	//
	this.isLoading = false;
	this.u = "";//username
	this.p = "";//password
	this.mh = "";//mailhost	
	this.feedURL = "http://mail3.m3com.com.sa/mail/getMessages.php";	
	
	this.defaultProfile["inp_count"] = "10";
	
	this.domSettings = [
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", className: "settings_label", innerHTML: loc.text("m3commail_mcount")},
	{ tag: "select", id: "inp_count", events: {onchange:"setItemsCount()"}, 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:"20", text: "20"}
		]
	}
	]
	},
	{ tag: "div", className: "cls"},
	]

//Start Build Content
	this.domContent = [
	{ tag: "div", className: "menu_panel", id: "loading_note", display: false, 
		style: { background: "url(static/client/loader.gif) no-repeat center center"}	
	},
	{ tag: "div", className: "martb5 mart10",
		childs :[
			{ tag: "table", id:"infoTable", width: "100%", border: "0", cellspacing : "5", cellpadding: "0",
				childs: [{ tag: "tr", 
					childs:[
						{ tag: "td", width: "20", innerHTML: "<img src='widgets/m3commail/img/icon_newMail.gif' width='16' height='17' alt='' />"},
						{ tag: "td", 
							childs: [
								{tag: "strong", innerHTML: 'عدد الرسائل في بريدك الوارد:',
									childs: [
										{ tag: "span", className: "txtOrng", id: "total_messages"}
									]
								}
								]
						}
						]
					},
					{tag: "tr", 
						childs: [
							{tag: "td", colspan: "2", innerHTML: "<a target='_blank' href='http://webmail2.m3com.com.sa/mail/mailbox.php?rnd=" + rnd + "'><strong>البريد الوارد</strong></a>"}
						]
					}				
				]							
			}
		]
	},
	
	{ tag: "div",
	style: { width: "100%", zoom: "1"},
	childs: [
	{ tag: "div", className: "marB10 txt12"},

	{ tag: "div", id: "messages", className: "m3commail_bgMail"}
	]},

	{ tag: "div", className: "menu_panel", id: "config_note", display: false,
	style: { background: "url(widgets/M3comMail/ico.gif) no-repeat 0 0"},
	innerHTML: loc.text("m3commail_msg_not_configured")},

	{ tag: "div", className: "menu_panel", id: "no_messages_note", display: false,
	style: { background: "url(widgets/M3comMail/ico.gif) no-repeat 0 0"},
	innerHTML: loc.text("m3commail_msg_no_mails")}
	]


	this.defaultProfile["mcount"] = "20";


	

	this.onBuildInterface = function() {
		try{	
					
			this.buildDomModel(this.elements.settings, this.domSettings);
			this.buildDomModel(this.elements.content, this.domContent);

			this.elements.inp_count.value = this.profile.mcount;

			this.setTitle(loc.text("m3commail_title"));
		} catch(err)
		{
			txt="There was an error on this page.\n\n";
			txt+="Error description: " + err.description + "\n\n";
			txt+="Click OK to continue.\n\n";
			//alert(txt);
		}
	}



	this.onOpen = function() {
		if(!auth.isLogged()) {
			
			this.setContent("messages");
			this.hideElement("infoTable");
				
			msgContent = loc.text("desktop_not_login", ' <a href="javascript:checkLogin()">الدخول</a> ');
			this.elements.messages.innerHTML = '';							
			this.buildDomModel(this.elements.messages, {tag: "div",innerHTML: msgContent});			
		} else {
			request.send({},this);
			this.refresh();			
		}

	}


	this.refresh = function() {
		if(!auth.isLogged()) {
			
			this.setContent("messages");
			this.hideElement("infoTable");
				
			msgContent = loc.text("desktop_not_login", ' <a href="javascript:checkLogin()">الدخول</a> ');
			this.elements.messages.innerHTML = '';							
			this.buildDomModel(this.elements.messages, {tag: "div",innerHTML: msgContent});
			return;			
		}	
		if(!this.isProfileEmpty()) {						
			this.setContent("loading_note");
			this.loadMessages();
			//Hide Setting
          	if(!this.isSettingsReduced) {
            	this.hideSettings();
            }
            //if widjet minimize show it
			if(this.isReduced) {
				this.show();
			}						
		}
	}
	
	this.loadMessages = function ( ) {
		xmlRequest.send( this.feedURL + '?msgCount=20&mh=' + this.mh, this, "handleResponse", {login: this.u, password: this.p});
	}
	this.dispatchMsg = function(res) {
			if(res && !this.isLoading) {
				this.u = res.u;
				this.p = res.p;
				this.mh = res.mh;
				
				this.isLoading = true;			
				this.setContent("loading_note");
				this.loadMessages();				
			}
												
    }
    
	this.handleResponse = function(response) {	
		if(response.responseXML.documentElement) {
			this.data = jQuery.xmlToJSON(response.responseXML);	                
			if(this.data) {
				this.renderMessages();
			}
		}
	}
	this.isProfileEmpty = function() {
		return this.p == "" || this.u == "" || this.mh == "";
	}


	this.setContent = function(section) {
		var sections = ["config_note", "loading_note", "messages", "no_messages_note"];
		for(var i = 0; i<sections.length; i++) {
			if(section == sections[i]) {
				this.showElement(sections[i]);
			} else {
				this.hideElement(sections[i]);
			}
		}		
          if(!this.isSettingsReduced) {
            	this.hideSettings();
            }
            
			if(this.isReduced) {
				this.show();
			}		
	}


	this.saveProfile = function() {

		if(this.isProfileEmpty()) {
			this.setContent("config_note");
		} else {
			this.save();
			this.refresh();
		}
	}


	this.setItemsCount = function() {
		var c = this.elements["inp_count"].value;
		if(this.profile.mcount != c) {
			this.profile.mcount = c;
			this.save();
			this.renderMessages();
		}
	}

	this.timerHandler = function() {
		if(this.isProfileEmpty()) {
			this.setContent("config_note");
		} else {
			this.refresh();
		}
	}
		

	this.renderMessages = function() {
	try {
	
	
		if(this.data) {		
			if(this.data.info[0].error[0].Text == '0'){	
			this.setContent("messages");
			this.elements.total_messages.innerHTML = "<b> " + this.data.info[0].unseen[0].Text + " </b>";			
			this.elements.messages.innerHTML = '';			
						
			if(this.data.message.length <=  this.profile.mcount) {
				var cnt = this.data.message.length; 					
			} else {
				var cnt = Math.min(this.data.message.length, this.profile.mcount);								
			}
			var mailLIST = [];
			var msgContent = '';			
			for(var i=0; i<cnt; i++) {				
					msgContent = '';
					if(this.data.message[i].read[0].Text == '0') {
						msgContent = loc.text("m3commail_unread", this.data.message[i].subject[0].Text.substring(0,25));
					} else {
						msgContent = this.data.message[i].subject[0].Text.substring(0,25);
					}
										
					mailLIST.push({ tag: "tr",
					childs: [
						{ tag: "td", title: this.data.message[i].subject[0].Text, innerHTML: "<a target='_blank' href='http://webmail2.m3com.com.sa/mail/message.php?rnd=" + rnd + "&uid=" + this.data.message[i].uid[0].Text + "'>" + msgContent + "</a>"},
						{ tag: "td", title: this.data.message[i].from[0].Text, innerHTML: this.data.message[i].from[0].Text}						
					]});
			}
			this.buildDomModel(this.elements.messages, {tag: "table", id: "mail_list", width: "100%", border: "0", cellspacing : "5", cellpadding: "2", childs:mailLIST});
			} else {
				this.setContent("messages");
				this.hideElement("infoTable");
				this.elements.messages.innerHTML = '';
				this.buildDomModel(this.elements.messages, {tag: "div",innerHTML: "حدثت مشكلة في بريدك على معكم , الرجاء المحاولة في وقت لاحق"});				
			}
		} else {
			//alert('this.data is Empty');
		}
		
		
		} catch (e) {
		//	alert(this.data.length + '|' + this.profile.mcount);
			//alert(e.description);		
		}
	}


this.showMail = function(response) {
//alert(response);
//alert(Dump(response));
}    
    /*
	this.dispatchMsg = function(msg) {
		alert(msg);
		clearTimeout(this.timerId);
		this.isLoading = false;
		switch(msg.status) {
			case "empty":
			this.setContent("no_messages_note");
			break;
			case "data":
			this.data = msg.data;
			this.totalMessages = msg.total;
			this.renderMessages();
			break;
			case "error":
			this.setContent("config_note");
			break;
		}
	}
	*/

}
M3comMail.prototype = new Widget();

function Bbcarabic() {
    this.init();

    this.cfg = {
        title: loc.text("bbcarabic_title"),
        module: "Bbcarabic"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://newsrss.bbc.co.uk/rss/arabic/news/rss.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgBbc"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "windows" });
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span",
                  innerHTML: loc.text("bbcarabic_title")
                  });

            /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgBbc"});           
            for(var i=0; i<count; i++) {
            	if(i == 0) {            
               		this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item_main" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),                                     
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i , 
                                     	childs:
                                     	[
                                     		{ tag: "div", name: "img", className: "fr",  
                                     			childs: [
                                     					{ tag: "img", id: "news_thumbnail", src: this.data.items[0]['media:thumbnail'].url, 
                                     						style: { width: "80px", height: "70px"} 
                                     					}		
                                     				]
                                     		},
                                     		{ tag: "p", id: "para", innerHTML: this.data.items[i].title }
                                     		
                                     	]
                                     });
           		} else {
            	  this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i });
            	}                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Bbcarabic.prototype = new Widget();

function Alarabiya() {
    this.init();

    this.cfg = {
        title: loc.text("alarabiya_title"),
        module: "Alarabiya"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.alarabiya.net/rss/rss_top08.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
    	this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlarabiya"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel");
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span",
                  innerHTML: loc.text("alarabiya_title")
                 });

            /*if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }*/
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;
    
 	 //this.buildDomModel(this.elements.content, { tag: "div", className: "dsds", id: "ds"});
 	
    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlarabiya"});         
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i,
                                     dir: "ltr",
                                     align: "right" });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Alarabiya.prototype = new Widget();

function Aljazeera() {
    this.init();

    this.cfg = {
        title: loc.text("aljazeera_title"),
        module: "Aljazeera"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.aljazeera.net/AljazeeraRSS/RSS/Rss.aspx?URL=RSS-Portal.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
  		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {    	
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgAljazeera"});
    	this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {    	
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel");
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span",
                  innerHTML: loc.text("aljazeera_title")
                  });
			/*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }*/
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                 /*   var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }*/
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgAljazeera"});
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i,
                                     dir: "ltr",
                                     align: "right" });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Aljazeera.prototype = new Widget();

function Clipat() {
    this.init();

    this.cfg = {        
        module: "Clipat",
        hasTitle: false
    };


    this.channels = [
    	{text:"- القائمة -", value: "", isBold: true},
    	{text:"مقاطع مرئية حديثة", value: "http://tube.m3com.com.sa/rss.xml/view/source/newVideo/start/0/limit/15"},
    	{text:"الأكثر تقييماَ", value: "http://tube.m3com.com.sa/rss.xml/view/source/videoMostRated/start/0/limit/15"},
    	{text:"الأكثر تعليقاَ", value: "http://tube.m3com.com.sa/rss.xml/view/source/videoMostComments/start/0/limit/15"},
    	{text:"الأكثر تعليقاَ لهذا الأسبوع", value: "http://tube.m3com.com.sa/rss.xml/view/source/videoMostCommentsThisWeek/start/0/limit/15"},
    	{text:"الأكثر مشاهدة", value: "http://tube.m3com.com.sa/rss.xml/view/source/videoMostView/start/0/limit/15"} 	
    ];

    this.defaultProfile["title"] = "";
    this.defaultProfile["channel"] = "1";
    this.defaultProfile["count"] = "6";

    var isLoading = false;
    var req = null;
    var content = null;
    var itemsCount = 15;

    var sel_count_options = [];
    for(var i=1; i<=itemsCount; i++) {
        sel_count_options.push({value: i, text: " " + i + " "});
    }

    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("clipat_inp_channel"), className: "settings_label"},
            { tag: "select", id: "inp_channel", events: {onchange: "setChannel()"}, className: "settings_control",
              options: this.channels }
          ]},

        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", innerHTML: loc.text("clipat_inp_count"), className: "settings_label"},
            { tag: "select", id: "inp_count", events: {onchange: "setCount()"}, className: "settings_control",
              options: sel_count_options }
          ]},
   		  { tag: "div", className: "cls"}
    ]



    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements["inp_channel"].selectedIndex = this.profile.channel;
        this.elements["inp_count"].value = this.profile.count;
    }


    this.setChannel = function() {
        if(isLoading) {
            this.elements["inp_channel"].selectedIndex = this.profile.channel;
        } else {
            var c = this.elements["inp_channel"].selectedIndex;
            if(c != this.profile.channel && this.channels[c].value != "") {
                this.profile.channel = c;
                this.save();
                req = null;
                isLoading = false;
                this.refresh();
            }
        }
    }


    this.setCount = function() {
        var c = this.elements["inp_count"].value;
        if(c != this.profile.count) {
            this.profile.count = c;
            this.save();
            this.renderContent();
        }
    }


    this.onOpen = function() {
        this.refresh();
    }




    this.refresh = function() {
       if(this.isReduced) {
			this.show();
		}         
        if(!isLoading) {
            this.setTitle(loc.text("msg_loading"));            
            this.elements["content"].innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>'; 
            req = xmlRequest.send(this.channels[this.profile.channel].value, this, "parseContent");
            isLoading = true;  
       }
      
    }


    this.parseContent = function(response) {
        isLoading = false;
        if(response.responseXML) {            
			content = jQuery.xmlToJSON(response.responseXML);
			content = content.channel[0];            
//            varpw(content);
        } else {
            content = null;
        }
        this.renderContent();
    }

    
    this.renderContent = function() {
        if(content) {
            this.setTitle(loc.text("clipat_title"));
            var l = Math.min(content.item.length, this.profile.count);
            var c = "";
            var st = "";

            for(var i=0; i<l; i++) {
                st = i % 2 == "1" ? "dark" : "";
                var lnk = content.item[i].link[0].Text;
//                var lnk2 = content.items[i]["enclosure"].url;
                var lnk2 = lnk;
                c += "<tr class='"+st+"'>"+
                     "<td valign=top style='padding: 4px;'>"+
                     "<a href='"+lnk+"' target=_blank><img border=0 width=85 height=65 src='"+ content.item[i].thumbnail[0].Text +"'/></a>"+
                     "</td><td valign=top style='padding: 4px;'>"+
                     "<a href='"+lnk+"' target=_blank><b>"+content.item[i].title[0].Text+"</b></a><br class=half />" +                     
                                                              
                     "<br><span class=txt11>" + loc.text("clipat_watchCount") + "&nbsp " + content.item[i].total_views[0].Text + "</span>" +
                     "<br ><span class=txt11>" + loc.text("clipat_playingTime") + "&nbsp " + content.item[i].playing_time[0].Text + "</span>" +
                     "</td>"+
                     "</tr>";
            }
            this.elements["content"].innerHTML = "<table  width=100% cellspacing=0>" + c + "</table><div class='upload'><a target='_blank' href='http://tube.m3com.com.sa/videoUpload/view'><img border='0' src='"+images_url+"static/images/uploadVideo.gif' /></a></div>";
        } else {
            this.setTitle(loc.text("msg_error"));
        }
    }
 
}
Clipat.prototype = new Widget();

function Alwatannews() {
    this.init();

    this.cfg = {
        title: loc.text("alwatannews_title"),
        module: "Alwatannews"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.alwatan.com.sa/news/RSS/RssHome.asp";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlwatan"});
        kernel.processTimer(this.id, this.profile.period * 1000);

    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;        
        xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "windows" });        
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span",
                  innerHTML: loc.text("alwatannews_title")
                   });

            /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlwatan"});
            for(var i=0; i<count; i++) {
               this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i,
                                     dir: "ltr",
                                     align: "right" });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Alwatannews.prototype = new Widget();

function Alriyadhnews() {
	this.init();

	this.cfg = {
		title: loc.text("alriyadhnews_title"),
		module: "Alriyadhnews"
	}

	this.defaultProfile["cnt"] = 10;
	this.defaultProfile["opend"] = 0;
	this.defaultProfile["url"] = "http://www.alriyadh.com/section.main.xml";
	this.defaultProfile["icon"] = "";
	this.defaultProfile["period"] = 600;
	this.defaultProfile["md5"] = [];



	this.domSettings = [
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
	{ tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
	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: loc.text("rss_all")}
	]
	}
	]
	},
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
	{ tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
	options: [
	{ value:"120", text: loc.text("rss_p120")},
	{ value:"300", text: loc.text("rss_p300")},
	{ value:"600", text: loc.text("rss_p600")},
	{ value:"1200", text: loc.text("rss_p1200")},
	{ value:"1800", text: loc.text("rss_p1800")},
	{ value:"3600", text: loc.text("rss_p3600")},
	{ value:"10800", text: loc.text("rss_p10800")}
	]
	}
	]},
	{ tag: "div", className: "settings_section",
	childs: [
	{ tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
	{ tag: "input", type: "checkbox", id: "opend",
	events: { onclick: "setOpenDirectly()"}
	}
	]},{ tag: "div", className: "settings_section", display: false,
	childs: [
	{ tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
	{ tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
	{ tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
	]} ,
	{ tag: "div", className: "cls"}
	]


	this.lastRefresh = null
	this.isLoading = false;
	this.isInReader = false;


	this.onBuildInterface = function() {
		this.elements["settings"].innerHTML = "";
		this.buildDomModel(this.elements.settings, this.domSettings);
		this.elements.period.value = this.profile.period;
		this.elements.news_count.value = this.profile.cnt;
		this.elements.opend.checked = this.profile.opend == 1;
		this.elements.content.style.padding = "6px";
		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;
			}
			if(this.profile["url"] != 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.hideSettings();
	}

	this.setOpenDirectly = function() {
		this.profile.opend = this.elements.opend.checked ? 1 : 0;
		this.save();
	}


	this.setNewsCount = function() {
		this.profile.cnt = this.elements.news_count.value;
		this.save();
		this.showChannelTitle();
		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() {
		this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
		this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlriyadh"});
		kernel.processTimer(this.id, this.profile.period * 1000);
	}


	this.timerHandler = function() {
		if(!this.isInReader) {
			this.refresh();
		}
	}

	this.refresh = function() {
		var date = new Date();
		this.lastRefresh = date.getSeconds();
		this.setTitle(loc.text("msg_loading"));
		this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

		var wid = this.id;
		var iconEl = this.elements.icon;
		xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "utf8" });
		this.isLoading == true;
		if(this.isReduced) {
			this.show();
		}
	}


	this.openChannel = function(wid, feedId) {
		if(this.profile.opend == 1) {
			window.open(this.data.items[feedId]["link"]);
		} else {
			this.isInReader = true;
			rssreader.channelLastRefresh = this.lastRefresh;
			rssreader.elements["icon"].src = this.elements["icon"].src;
			rssreader.openChannel(wid, feedId);
		}
	}


	this.getItemsCount = function() {
		return Math.min(this.data.items.length, this.profile.cnt);
	}


	this.processItemRead = function(itemIdx) {
		this.data.items[itemIdx].isRead = 1;
		this.profile["readed"][itemIdx] = 1;
		this.showChannelTitle();
		this.elements["item_" + itemIdx].className = "rss_box_item_visited";
	}

	this.processItemUnread = function(itemIdx) {
		this.data.items[itemIdx].isRead = 0;
		this.profile["readed"][itemIdx] = 0;
		this.showChannelTitle();
		this.elements["item_" + itemIdx].className = "rss_box_item";
	}


	this.getReadedItemsCount = function() {
		var count = this.getItemsCount();
		var res = 0;
		for(var i=0; i<count; i++) {
			if(this.data.items[i].isRead == 1) {
				res ++;
			}
		}
		return res;
	}


	this.showChannelTitle = function() {
		if(this.data) {
			var count = this.getItemsCount();
			var readed = this.getReadedItemsCount();

			this.elements.title.innerHTML = '';
			this.buildDomModel(this.elements.title,
			{ tag: "span",
			innerHTML: loc.text("alriyadhnews_title")
			});

			/*
			if(count > readed) {
			this.buildDomModel(this.elements.title,
			{ tag: "span",
			innerHTML: " " + (count - readed)});
			}
			*/
		}
	}


	this.lastFeed = {
		url: null,
		time: null
	}


	this.getItemMd5 = function(idx) {
		var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
		var str = this.data.items[idx].title + content;
		return crc32(str);
	}


	this.showChannel = function(response) {
		this.isLoading == false;
		if(response.responseXML && response.responseXML.documentElement) {
			this.data = XMLParser.xml2hash(response.responseXML.documentElement);
			var newMd5 = [];
			if(this.data) {
				var count = this.data.items.length;
				var l = this.profile["md5"].length;

				for(var i=0; i<count; i++) {
					var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
					var j = this.isReaded(md5);

					if(j != null) {
						this.data.items[i].isRead = 1;
						newMd5.push(md5);
						l--;
					}
				}

				this.profile["md5"] = newMd5;
				if(l != 0) {
					this.save();
				}
			}

			this.renderChannel();
			this.showChannelTitle();
		} else {
			this.showError();
		}
	}




	this.iconLoaded = false;

	this.renderChannel = function() {
		if(this.data) {
			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);
				this.iconLoaded = true;
			}

			var count = this.getItemsCount();
			this.elements.content.innerHTML = '';
			this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlriyadh"});
			str = this.data.items[0]['content'];
			/*	if(typeof(str) == null){
			str = this.data.items[0]['description'];
			}*/
			var s = str.match(/<img src="(.*)" a/);
			link = s[1];
			for(var i=0; i<count; i++) {
				if(i == 0) {
					this.buildDomModel(this.elements.content,
					{ tag: "div", className: "rss_box_item_main" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
					events: { onclick: "openChannel("+this.id+","+i+")" },
					id: "item_" + i ,
					childs:
					[
					{ tag: "div", name: "img", className: "fr",
					childs: [
					{ tag: "img", id: "news_thumbnail", src: link, width: "80", height: "70" }
					]
					},
					{ tag: "p", id: "para", innerHTML: this.data.items[i].title }
					]
					});
				} else {
					this.buildDomModel(this.elements.content,
					{ tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
					innerHTML: this.data.items[i].title,
					events: { onclick: "openChannel("+this.id+","+i+")" },
					id: "item_" + i });
				}

			}
		} else if (!this.isLoading) {
			this.showError();
		}
	}


	this.showError = function() {
		this.elements.title.innerHTML = loc.text("rss_msg_error");
	}


	this.openSite = function() {
		if(this.data) {
			window.open(this.data.siteUrl);
		}
	}


	this.onClose = function() {
		if(rssreader.widgetId && rssreader.widgetId == this.id) {
			rssreader.close();
		}
	}


	// Read/unread hash
	this.isReaded = function(md5) {
		for(var i=0; i<this.profile["md5"].length; i++) {
			if(this.profile["md5"][i] == md5) {
				return i;
			}
		}
		return null;
	}


	this.setReaded = function(idx) {
		var md5 = this.data.items[idx].md5;
		var i = this.isReaded(md5);
		if(i == null) {
			this.profile["md5"].push(md5);
		}
	}


	this.unsetReaded = function(idx) {
		var md5 = this.data.items[idx].md5;
		var i = this.isReaded(md5);
		if(i != null) {
			delete(this.profile["md5"][i]);
		}
	}



	this.processItemRead = function(itemIdx) {
		this.data.items[itemIdx].isRead = 1;
		this.setReaded(itemIdx);
		this.showChannelTitle();
		this.elements["item_" + itemIdx].className = "rss_box_item_visited";
	}

	this.processItemUnread = function(itemIdx) {
		this.data.items[itemIdx].isRead = 0;
		this.unsetReaded(itemIdx);
		this.showChannelTitle();
		this.elements["item_" + itemIdx].className = "rss_box_item";
	}


	this.getReadedItemsCount = function() {
		var count = this.getItemsCount();
		var res = 0;
		for(var i=0; i<count; i++) {
			if(this.data.items[i].isRead == 1) {
				res ++;
			}
		}

		return res;
	}

}
Alriyadhnews.prototype = new Widget();

function Alyaumnews() {
    this.init();

    this.cfg = {
        title: loc.text("alyaumnews_title"),
        module: "Alyaumnews"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.alyaum.com/issue/index.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



     this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
   		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlyaum"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "windows" });
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span", 
                  innerHTML: loc.text("alyaumnews_title")
                   });

           /*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgAlyaum"});
            for(var i=0; i<count; i++) {
                 this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i,
                                     dir: "ltr",
                                     align: "right" });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Alyaumnews.prototype = new Widget();

function Aljazirahnews() {
    this.init();

    this.cfg = {
        title: loc.text("aljazirahnews_title"),
        module: "Aljazirahnews"
    }

    this.defaultProfile["cnt"] = 10;
    this.defaultProfile["opend"] = 0;
    this.defaultProfile["url"] = "http://www.al-jazirah.com.sa/rss/fr.xml";
    this.defaultProfile["icon"] = "";
    this.defaultProfile["period"] = 600;
    this.defaultProfile["md5"] = [];



    this.domSettings = [
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_ncount")},
            { tag: "select", id: "news_count", className: "settings_control",  events: {onchange: "setNewsCount()"},
              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: loc.text("rss_all")}
              ]
            }
          ]
        },
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_refresh")},
            { tag: "select", id: "period", className: "settings_control", events: {onchange: "setPeriod()"},
              options: [
                { value:"120", text: loc.text("rss_p120")},
                { value:"300", text: loc.text("rss_p300")},
                { value:"600", text: loc.text("rss_p600")},
                { value:"1200", text: loc.text("rss_p1200")},
                { value:"1800", text: loc.text("rss_p1800")},
                { value:"3600", text: loc.text("rss_p3600")},
                { value:"10800", text: loc.text("rss_p10800")}  
              ]
            }            
          ]},
        { tag: "div", className: "settings_section", 
          childs: [
            { tag: "span", className: "settings_label", innerHTML: loc.text("rss_inp_open_to")},
            { tag: "input", type: "checkbox", id: "opend",
              events: { onclick: "setOpenDirectly()"}
            }
          ]},{ tag: "div", className: "settings_section", display: false,
          childs: [ 
            { tag: "span", innerHTML: loc.text("rss_inp_url"), className: "settings_label"},
            { tag: "input", id: "select_url", type: "text", size: "15", className: "settings_control", disabled: "true"},
            { tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
          ]},
  		  { tag: "div", className: "cls"}
    ]


    this.lastRefresh = null
    this.isLoading = false;
    this.isInReader = false;


    this.onBuildInterface = function() {
        this.elements["settings"].innerHTML = "";
        this.buildDomModel(this.elements.settings, this.domSettings);
        this.elements.period.value = this.profile.period;
        this.elements.news_count.value = this.profile.cnt;
        this.elements.opend.checked = this.profile.opend == 1;
        this.elements.content.style.padding = "6px";
        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;
            }
            if(this.profile["url"] != 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.hideSettings();
    }

    this.setOpenDirectly = function() {
        this.profile.opend = this.elements.opend.checked ? 1 : 0;
        this.save();
    }


    this.setNewsCount = function() {
        this.profile.cnt = this.elements.news_count.value;
        this.save();
        this.showChannelTitle();
        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() {
    	this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';
    	this.buildDomModel(this.elements.content, { tag: "div", className: "bgJazirah"});
        kernel.processTimer(this.id, this.profile.period * 1000);
    }


    this.timerHandler = function() {
        if(!this.isInReader) {
            this.refresh();
        }
    }

    this.refresh = function() {
        var date = new Date();
        this.lastRefresh = date.getSeconds();
        this.setTitle(loc.text("msg_loading"));
        this.elements.content.innerHTML = '<div align="center"><img src="static/client/loader.gif" /></div>';

        var wid = this.id;
        var iconEl = this.elements.icon;
        xmlRequest.send(this.profile.url, this, "showChannel",{ charset: "windows" });
        this.isLoading == true;
        if(this.isReduced) {
			this.show();
		}
    }


    this.openChannel = function(wid, feedId) {
        if(this.profile.opend == 1) {
            window.open(this.data.items[feedId]["link"]);
        } else {
            this.isInReader = true;
            rssreader.channelLastRefresh = this.lastRefresh;
            rssreader.elements["icon"].src = this.elements["icon"].src;
            rssreader.openChannel(wid, feedId);
        }
    }


    this.getItemsCount = function() {
        return Math.min(this.data.items.length, this.profile.cnt);
    }


    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.profile["readed"][itemIdx] = 1;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.profile["readed"][itemIdx] = 0;
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        return res;
    }


    this.showChannelTitle = function() {
        if(this.data) {
            var count = this.getItemsCount();
            var readed = this.getReadedItemsCount();
			
            this.elements.title.innerHTML = '';
            this.buildDomModel(this.elements.title, 
                { tag: "span", 
                  innerHTML: loc.text("aljazirahnews_title")
                  });
			/*
            if(count > readed) {
                this.buildDomModel(this.elements.title, 
                    { tag: "span", 
                      innerHTML: " " + (count - readed)});
            }
            */
        }
    }


    this.lastFeed = {
        url: null,
        time: null
    }


    this.getItemMd5 = function(idx) {
        var content = this.data.items[idx]["content"] ? this.data.items[idx]["content"] : this.data.items[idx]["description"];
        var str = this.data.items[idx].title + content;
        return crc32(str);
    }


    this.showChannel = function(response) {
        this.isLoading == false;
        if(response.responseXML && response.responseXML.documentElement) {
            this.data = XMLParser.xml2hash(response.responseXML.documentElement);
            var newMd5 = [];
            if(this.data) {
                var count = this.data.items.length;
                var l = this.profile["md5"].length;

                for(var i=0; i<count; i++) {
                    var md5 = this.data.items[i]["md5"] = this.getItemMd5(i);
                    var j = this.isReaded(md5);

                    if(j != null) {
                        this.data.items[i].isRead = 1;
                        newMd5.push(md5);
                        l--;
                    }
                }

                this.profile["md5"] = newMd5;
                if(l != 0) {
                this.save();
            }
            }

            this.renderChannel();
            this.showChannelTitle();
        } else {
            this.showError();
        }
    }




    this.iconLoaded = false;

    this.renderChannel = function() {
        if(this.data) {
            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);
                this.iconLoaded = true;
            }

            var count = this.getItemsCount();
            this.elements.content.innerHTML = '';
            this.buildDomModel(this.elements.content, { tag: "div", className: "bgJazirah"});
            for(var i=0; i<count; i++) {
                this.buildDomModel(this.elements.content, 
                                   { tag: "div", className: "rss_box_item" + ( (this.data.items[i].isRead == 1) ? "_visited" : ""),
                                     innerHTML: this.data.items[i].title.wordWrap(38),
                                     events: { onclick: "openChannel("+this.id+","+i+")" },
                                     id: "item_" + i });
                                                   
            }
        } else if (!this.isLoading) {
            this.showError();
        }
    }


    this.showError = function() {
        this.elements.title.innerHTML = loc.text("rss_msg_error");
    }

    
    this.openSite = function() {
        if(this.data) {
            window.open(this.data.siteUrl);
        }
    }


    this.onClose = function() {
        if(rssreader.widgetId && rssreader.widgetId == this.id) {
            rssreader.close();
        }
    }


    // Read/unread hash
    this.isReaded = function(md5) {
        for(var i=0; i<this.profile["md5"].length; i++) {
            if(this.profile["md5"][i] == md5) {
                return i;
            }
        }
        return null;
    }


    this.setReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i == null) {
            this.profile["md5"].push(md5);
        }
    }


    this.unsetReaded = function(idx) {
        var md5 = this.data.items[idx].md5;
        var i = this.isReaded(md5);
        if(i != null) {
            delete(this.profile["md5"][i]);
        }
    }



    this.processItemRead = function(itemIdx) {
        this.data.items[itemIdx].isRead = 1;
        this.setReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item_visited";
    }

    this.processItemUnread = function(itemIdx) {
        this.data.items[itemIdx].isRead = 0;
        this.unsetReaded(itemIdx);
        this.showChannelTitle();
        this.elements["item_" + itemIdx].className = "rss_box_item";
    }


    this.getReadedItemsCount = function() {
        var count = this.getItemsCount();
        var res = 0;
        for(var i=0; i<count; i++) {
            if(this.data.items[i].isRead == 1) {
                res ++;
            }
        }
        
        return res;
    }
 
}
Aljazirahnews.prototype = new Widget();

//
// Widget class definition. Class name must be unique for each widget.
//
function Facebook() {



    //
    // Calling of init() function must be placed at begining of widget.
    //
    this.init();




    //
    // Widget config - definition of widget parametrs.
    // 
    // Note: you does't need to overload default values,
    // for example:      
    //
    //    this.cfg = {
    //        module: "Demo"
    //    }
    //  

    this.cfg = {
        // Caption settings button (show/hide widget settings panel). 
        // Default value: true
        hasSettingsBtn: false,
         hasRefreshBtn: false,
        // Widget name (name of widget class)
        // Important: always must be filled and be unique for each widget
        module: "Facebook",
        
        hasTitle : false
    };




    //
    // Widget profile default values. 
    // That values will stored to profile on first start(when user add widget to page)
    //
    this.defaultProfile["title"] = "Facebook";
    this.defaultProfile["text"] = "abc";




    //
    // Hash HTML model for Demo widget settings panel
    //
    // About multylanguage support:
    // loc.text(label) is system function that return text string for label corresponding current user language,
    // all text strings must be added to language .xml files in format:
    // <string id="label">string</string>
    //
    this.modelSettings = [
		{ tag: "div", className: "settings_section"},
		{ tag: "div", className: "cls"}
    ];



  




    //
    // Hash HTML model for Demo widget content area
    //
    this.modelContent = [
        { tag: "div", id: "text" }
    ]



    //
    // Build all static interface elements for widget here
    //
    this.onBuildInterface = function() {
        //
        // Building HTML from models,
        // to get more information have a look to document.createElement() function specification for browsers 
        // and DOM specifications.
        //
        // properties that extended:
        //
        // id - will add pointer to elements in this.elements hash
        // events - hash with events and callbacks that will be attached to element
        // html - alias to innerHTML
        // 
        // Default elements in this.elements hash:
        // "settings" - settings panel
        // "content" - content element inside widget window
        // "title" - title element in widget window caption
        //
        
        var facebook_embed = '<embed pluginspage="http://www.adobe.com/go/getflashplayer" src="http://www.yourminis.com/Dir/GetContainer.api?uri=yourminis/jeremy/mini:facebook" width="290" height="440" wmode="transparent" FlashVars="height=440&hostname=www.yourminis.com&color=16777215&tips=1&width=290&uri=yourminis/jeremy/mini%3Afacebook&swfhost=ct.yourminis.com&statshostname=stats.yourminis.com&ds=0&fsort=status&" type="application/x-shockwave-flash" allowScriptAccess="always" ></embed><br />';

        var fcontent = [
        {tag : "div" , innerHTML : facebook_embed}        ];
        
//        this.buildDomModel(this.elements["settings"]);
        this.buildDomModel(this.elements["content"], fcontent);

        // call function this.setTitle() to set title in widget caption
        this.setTitle("Facebook");

        // title control present in settings panle by default.
        // use this.elements["settings"].innerHTML = "" to delete it
     
      //  this.elements["text"].innerHTML = this.profile["text"];
    }



    //
    // this.onOpen() function will called when widget added to page.
    //
    this.onOpen = function() {
        // Any code
    }


 
}

//
// Definition of class prototype. Prototype always must be Widget object.
//
Facebook.prototype = new Widget();
