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;
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) {
el.style.display = 'block';
}
function hideEl(el) {
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 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.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>");
}
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) {
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 {
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) {
//                        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} : null;
},
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, mostrar, clase) {
if (mostrar == false || mostrar === false){
mostrar = false;
}else{
mostrar =true;
}
//if((mostrar!=false) && (mostrar != null) && (mostrar != undefined)) {
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: title, className: clase}
]
,display:mostrar
}
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}
]
,display:mostrar
};
if(id) button.id = id;
}
} else {
var button = { tag: "a", href: "void", events: {onclick: action}, innerHTML: title, className: clase
,display:mostrar
};
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(sinBorde) {
if (sinBorde=="sinBorde"){
mostrar = false;
estilo="";
}else{
mostrar = true;
estilo="window_content";
}
this.defaultProfile = {
title: ""
}
this.domModel =
{ tag: "div", className: "window", id: "window",
childs: [
{ tag: "div",
childs: [
{ tag: "table", className: "plan_table", style: { width: "100%"},
childs: [
{ tag: "tr", display: mostrar,
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: estilo,
id: "content" },
{ tag: "div", className: "window_footer", id: "footer",
childs: [
{ tag: "table", className: "plan_table", style: {width: "100%"},
childs: [
{ tag: "tr", display: mostrar,
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);
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: "widgets/"+this.cfg.module.toLowerCase()+"/ico.gif",
style: { width: "16px", height: "16px"}}
]}
);
}
m.push(
{ tag: "div", id: "title", className: "caption_title" }
);
if(this.cfg.hasCloseBtn) {
m.push(
{ tag: "a", href: "void",
title: loc.text("wbtn_close"),
className: "btn_close",
display: !this.cfg.hasDrag,
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: !this.cfg.hasDrag,
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: !this.cfg.hasDrag,
events: {onclick: "refresh()"},
id: "btn_refresh" }
);
}
this.buildDomModel(this.elements["caption"], m);
}
this.initDtagAndDrop = function() {
if(this.cfg.hasDrag) {
this.elements.caption.style.cursor = 'move';
this.elements.window.drag = new Drag(this.elements.window, this.elements.caption);
}
}
this.buildInterface = function() {
if(!this.isPreview) {
this.initDtagAndDrop();
}
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: "15", className: "settings_control"},
{tag: "input", type: "button", value: loc.text("btn_set"), events: {onclick: "settingsSetTitle()"}, className: "settings_control"}
]}
);
this.onBuildInterface();
}
this.disableOnClosePrompt = false;
this.isForceClose = false;
this.forceClose = function() {
this.isForceClose = true;
this.disableOnClosePrompt = true;
this.close();
}
this.close = function() {
var flag = (this.cfg.hasOnCloseConfirm && !this.disableOnClosePrompt) ?
confirm(loc.text("desktop_confirm_widget_remove"))
:
true;
if(flag) {
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.setTitle = function(html) {
this.elements.title.innerHTML = html;
}
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 = "http://"+baseUrl+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;
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]) {
this.elements[id].style.display = 'none';
}
}
this.showElement = function(id, display) {
if(this.elements[id]) {
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"));
menu = kernel.runWidget("Menu", document.body);
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"));
desktop.wakeUp();
}
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,
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];
//alert(c + " - " + cfgWidget[c]);
}
}
//alert(className);
//if (className=="Calculator") w.cfg["hasCloseBtn"] = false;
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 = lenguaPredeterminada;
}
request.getXML("lang/" + this.lang.toLowerCase() + ".xml", this, "parseLangXML");
}
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: true,
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
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",
childs: [
createButtonDom(loc.text("menu_title"), "switchMenu()", "widgets/menu/ico.gif","menuPrincipal","iconoPrincipal",true,"arriba")
]},
{ tag: "div", cn: "float_right", display: eval(verCabecera),
childs: [
// ::Avanzo:: Ocultamos las funciones superiores de cabecera.
createButtonDom(loc.text("desktop_show_all"), "showAll()","","mostrarTodo","",eval(verMostrarTodo)),
{ tag: "span", innerHTML: "&nbsp;&nbsp;|&nbsp;&nbsp;", display: eval(verSep1)},
createButtonDom(loc.text("desktop_hide_all"), "hideAll()","","ocultarTodo","",eval(verOcultarTodo)),
{ tag: "span", innerHTML: "&nbsp;&nbsp;|&nbsp;&nbsp;", display: eval(verSep2)},
createButtonDom(loc.text("desktop_lnk_settings"), "showPopup(\"settings\")", "static/client/settings.gif","ajustes","",eval(verAjustes)),
{ tag: "span", innerHTML: "&nbsp;&nbsp;|&nbsp;&nbsp;", display: eval(verSep3)},
{ tag: "span", id: "authButton", display: eval(verAuthButton)}
]}
]},
// title
{ tag: "div", cn: "title_section",
id: "title_section",
childs: [
{ tag: "div", className: "title",
childs:[
// ::Avanzo:: Logo de avanzo e intereconomia
{ tag: "span", id: "title_box", className: "desktop_title_box", display: eval(verCajaTitle)},
{ tag: "img",  src: "static/images/cabecera.gif", display : eval(verLogoCabecera) },
{ 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"}
]}
]},
// tabs
{ tag: "div", className: "tabs_panel",
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" }
]}
]},
{ tag: "div", className: "header_hr" }
]},
// widgets
{ tag: "div", cn: "desktop_columns",
id: "desktop_columns" },
// footer
// ::Avanzo:: Ocultamos el pie con idiomas.
{ tag: "div", cn: "desktop_footer", display: eval(verFooter),
childs: [
{ tag: "span", className: "sp_footer", align: "center", innerHTML: desktopLangsHTML, display: eval(verIdiomas) },
{ tag: "br"},{ tag: "br"},
{ tag: "span", id: "bottom_links_0", align: "center",  display: eval(verOpcionesFooter),
childs: [
{ tag: "a", sysHref: "/doc/", html: "Universal Widget API" , display: eval(verUWAPI) },
{ tag: "span", html: "&nbsp;&nbsp;|&nbsp;&nbsp;", display: eval(verSep4) },
{ tag: "a", href: "showPopup('feedback')", html: loc.text('desktop_lnk_user_feedback'), display: eval(verOpinion) },
{ tag: "span", html: "&nbsp;&nbsp;|&nbsp;&nbsp;" , display: eval(verSep5)},
{ tag: "a", href: "showPopup('sendtofriend')", html: loc.text('desktop_lnk_sendtofriend') , display: eval(verAmigo)},
{ tag: "span", html: "&nbsp;&nbsp;|&nbsp;&nbsp;", display: ((mozilla_nav || ie_nav) && eval(verSep6)) },
{ tag: "a", href: "addToFavorites('feedback')", display: ((mozilla_nav || ie_nav) && eval(verFavoritos)) , html: loc.text('desktop_lnk_favorites') }
]},
{ tag: "span", id: "custom_pages_links", align: "center", display:eval(verDemolink) },
{ tag: "span", innerHTML: "&nbsp;<br>"}
]},
{ 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.isMenuShow = false;
this.switchMenu = function() {
if(this.isMenuShow) {
menu.hide();
} else {
menu.show();
}
}
// Popups
this.popupsHistory = [];
this.showPopup = function(name) {
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";
var top = document.documentElement.scrollTop || document.body.scrollTop;
this.elements["popups"].style.top = 50 + top + "px";
this.updatePopupPosition();
}
this.hideActivePopup = function() {
if(!this.popupsHistory.length) return;
var name = this.popupsHistory.pop();
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.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;
}
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);
}
// ::Avanzo:: Quitamos el estilo a la pestaña Avanzo.
//El elemento tab 0 - 1 es la pestaña de Avanzo y no queremos que coja
//el estilo tab_box_selected para que no tenga configuración ni borrar.
if (idx < pestanasFijas){
this.elements["tab_" + idx].className = "tab_box";
}
}
// 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: { paddingBottom: "50px", 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%",
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"));
// ::Avanzo:: Ocultamos el pie "Powered by Avanzo"
if (verTplPie){
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 = [
"Avanzo",
"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) {}
}
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.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","","",true,"arriba")]  },
{ tag: "span", id:"signoutBtn",
childs: [createButtonDom(loc.text("auth_lnk_sign_out"), "logout()", "widgets/auth/img/sign_out.gif","","",true,"arriba")]  }]);
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.hideActivePopup();
}
this.signIn = function() {
desktop.showPopup('auth');
}
this.isLogged = function() {
return this.user.email != '';
}
this.logout = function() {
if(privado){
document.location.href="login.php";
}else{
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();
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.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) {
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.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.domModelContent = [
{ tag: "div", className: "menu_panel", id: "addFeedMenuItem",
childs: [createButtonDom(loc.text("menu_add_feed"), "showAddFeedPanel()", "widgets/menu/img/plus.gif")] },
{ 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 }
]}
]
this.domModelAdditional = [
{ tag: "div", className: "panel", id: "preview", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "300px"},
childs: [
{ tag: "div", className: "panel_section",
childs: [createTableDom([{content: createButtonDom("<b>" + loc.text("menu_add2desktop") + "</b>", "addToDesktop()", "widgets/menu/img/plus.gif"), width: "99%"},
{content: {tag: "a", href: "void", events: {onclick: "closePreview()"}, innerHTML: "<img src='static/client/close.gif'>"}, width: "1%"}
]),
{ tag: "div", 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", id: "selectFeedUrl"}, width: "100%"},
{content: { tag: "input", type: "button", id: "addFeedButton", events: {onclick: "addFeed()"}, value: loc.text("btn_add")}, width: "1%"}
]),
{ tag: "div", display: false, id: "addFeedStatus", 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.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.onBuildInterface = function() {
this.elements.window.style.position = "absolute";
this.elements.window.style.margin = "2px";
this.elements.window.style.top = "0px";
this.elements.window.style.left = "0px";
this.elements.window.style.width = "235px";
this.buildDomModel(this.elements.content, this.domModelContent);
this.buildDomModel(document.body, this.domModelAdditional);
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", className: "menu_panel",
events: {
onmouseover: "showHint('" + wname + "', '"+mid+"')",
onmouseout: "hideHint('" + wname + "')"},
childs: [
createButtonDom(loc.text(wname + "_title"), "openWidget('" + menuWidgets[w].className + "', '"+mid+"')", "widgets/" + wname + "/ico.gif", mid)
]
}
this.buildDomModel(this.elements["content"], m);
}
}
// HTML Widgets
this.buildDomModel(this.elements["content"], [
{ tag: "div", className: "menu_hr"},
{ tag: "div", id: "html_widgets",
html: loc.text("msg_loading") }
]);
request.send({ act: "get_html_widgets" }, this);
// Load feeds catalog
this.switchCategory(0);
// Custom feeds
var tmp = [];
for(var i=0; i<this.profile.catalog.length; i++) {
if(this.profile.catalog[i]["title"]) {
tmp.push(this.profile.catalog[i]);
}
}
this.profile.catalog = null;
this.profile.catalog = tmp;
for(var i=0; i<this.profile.catalog.length; i++) {
this.catalog[CCIDS+1].items[i] = clone(this.profile.catalog[i]);
this.catalog[CCIDS+1].items[i].id = CCIDS + 2 + parseInt(i);
}
this.renderCategory(CCIDS);
this.renderRecentWidgets();
}
// open/close sub menus
this.switchPanel = function(name) {
with (this.elements[name].style) {
display = (display == 'none' ? 'block' : 'none');
}
}
this.show = function() {
if(!desktop.isMenuShow) {
showEl(this.elements.window);
//            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) {
this.hideItemMenu();
this.hideHint();
this.closePreview();
showEl(this.elements.preview);
var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 12,
top:  getTop(this.elements[mid])};
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() {
if(this.widget) {
this.widget.close();
}
this.widget = null;
hideEl(this.elements.preview);
this.elements.preview_panel.innerHTML = '';
}
this.addToDesktop = function() {
var w = this.widget;
if(w) {
w.setParent(desktop.getTinyPanel());
w.isPreview = false;
w.initDtagAndDrop();
w.disableOnClosePrompt = this.oldDisableOnClosePrompt;
w.save();
this.widget = null;
this.closePreview();
desktop.savePanels();
}
}
//---------------------------------------------
// HINTS
//---------------------------------------------
this.currentHint = null;
this.showHint = function(wname, mid) {
if(!this.widget) {
var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 12,
top:  getTop(this.elements[mid])};
setElPos(this.elements["hint_"+wname], pos);
showEl(this.elements["hint_"+wname]);
this.currentHint = wname;
this.hideItemMenu();
}
}
this.hideHint = function(wname) {
if(wname) {
hideEl(this.elements["hint_"+wname]);
} else if (this.currentHint) {
hideEl(this.elements["hint_"+this.currentHint]);
}
}
//---------------------------------------------
// 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.window) + this.elements.window.offsetWidth + 12,
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) {
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();
}
//---------------------------------------------
// 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) {
showEl(el);
} else {
this.renderCategory(catId);
}
} else {
if(catId < CCIDS) {
el.innerHTML = loc.text("msg_loading");
showEl(el);
request.send({act: "get_category", cat_id: catId}, this);
}
}
if(catId != "0") {
this.elements["fico_" + catId].setAttribute("src", this.folder_o.src);
}
} 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: "div", className: "menu_panel", id: "cat"+categories[i].id,
childs: [
createButtonDom(categories[i].name,
"switchCategory("+categories[i].id+")",
this.folder_s.src,
false,
"fico_" + categories[i].id
),
{ tag: "div", id: "cat_content"+categories[i].id, className: "menu_sub_panel", display: false }
]
});
}
}
if(items) {
var m = null;
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,
style: {width: "100%", padding: "0px"},
childs: []}
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(el, m);
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";
}
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();
var m = { tag: "div", className: "menu_panel",
childs: [
createButtonDom(data[i].title,
"openHTMLWidget('" + data[i].id + "', '"+mid+"')", "var/hwicons/" + data[i].icon, mid)
]}
this.buildDomModel(this.elements["html_widgets"], m);
}
} else {
this.elements["html_widgets"].innerHTML = "";
}
}
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,
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]();
}
// Account
this.pmodel_account = [
{ tag: "div", id: "account_controls",
display: false,
childs: [
{ tag: "div", className: "float_panel",
childs: [
{ tag: "div", className: "float_left",
style: { width: "45%", padding: "2px" },
childs: [
{ tag: "div", html: loc.text("settings_inp_old_pwd")},
{ tag: "div",
childs: [
{ tag: "input", id: "inp_old_pwd", size: "30",
type: "password" }
]},
{ tag: "div", id: "change_pwd_msg",
style: { marginTop: "12px"}}
]},
{ tag: "div", className: "float_right",
style: { width: "45%", padding: "2px" },
childs: [
{ tag: "div", html: loc.text("settings_inp_new_pwd")},
{ tag: "div",
childs: [
{ tag: "input", id: "inp_new_pwd", size: "30",
type: "password" }
]},
{ tag: "div", html: loc.text("settings_inp_new_pwd2")},
{ tag: "div",
childs: [
{ tag: "input", id: "inp_new_pwd2", size: "30",
type: "password" }
]}
]}
]},
{ tag: "div", style: { textAlign: "center", marginTop: "6px", height: "25px"},
childs: [
{ tag: "input", id: "btn_change_pwd",
events: { onclick: "changePwd()"},
type: "button", value: loc.text("settings_btn_change_pwd") }
]}
]},
{ tag: "div", id: "account_msg",
display: false,
html: "<b>" + loc.text("auth_reg_first") + "</b><br><br>" + loc.text("auth_reg_msg") }
];
this.onShowPage_account = function() {
if(auth.isLogged()) {
this.showElement("account_controls");
this.hideElement("account_msg");
} else {
this.hideElement("account_controls");
this.showElement("account_msg");
}
}
this.changePwd = function() {
if(auth.isLogged()) {
var p1 = trim(this.elements["inp_new_pwd"].value);
var p2 = trim(this.elements["inp_new_pwd2"].value);
var opwd = trim(this.elements["inp_old_pwd"].value);
if(opwd == auth.user.password) {
if((p1 == p2) && (p1 != "")) {
var opwd = trim(this.elements["inp_old_pwd"].value);
request.send({ act: "change_pwd", npwd: p1}, this);
this.elements["change_pwd_msg"].innerHTML = loc.text("msg_processing");
this.elements["btn_change_pwd"].disabled = true;
} else {
this.elements["change_pwd_msg"].innerHTML = loc.text("settings_new_pwd_wrong");
}
} else {
this.elements["change_pwd_msg"].innerHTML = loc.text("settings_old_pwd_wrong");
}
} else {
alert(loc.text("settings_msg_sign_in"));
}
}
// Themes
this.pmodel_themes = [
{ tag: "div", id: "themes_list", cn: "themes_list" }
];
this.isThemesLoaded = false;
this.onShowPage_themes = function() {
if(!this.isThemesLoaded) {
this.elements["themes_list"].innerHTML = loc.text("msg_loading");
request.send({ act: "get_themes" }, this);
}
}
this.renderThemes = function(list) {
if(list == null) {
this.elements["themes_list"].innerHTML = "No themes found :(";
} else {
this.elements["themes_list"].innerHTML = "";
for(var i=0; i< list.length; i++) {
var cn = (list[i].name == desktop.profile["theme"]) ? "theme_box_selected" : "theme_box";
this.buildDomModel(this.elements["themes_list"],
{ tag: "div", className: cn,
id: "theme_box_" + list[i].name,
events: { onclick: "setTheme('" + list[i].name + "')" },
childs: [
{ tag: "div", className: "theme_thumbnail_box",
childs: [
{ tag: "img", className: "theme_thumbnail",
src: "themes/" + list[i].name + "/thumbnail.jpg" }
]},
{ tag: "div", className: "theme_description_box",
innerHTML: list[i].description }
]}
);
}
}
}
this.setCurrentTheme = function(name) {
if(this.elements["theme_box_" + name]) {
this.elements["theme_box_" + name].className = "theme_box_selected";
}
}
this.setTheme = function(name) {
if(desktop.profile["theme"] != name) {
if(this.elements["theme_box_" + desktop.profile["theme"]]) {
this.elements["theme_box_" + desktop.profile["theme"]].className = "theme_box";
}
this.elements["theme_box_" + name].className = "theme_box_selected";
desktop.profile["theme"] = name;
desktop.applyTheme();
desktop.save();
}
}
// Wallpapers
this.getImageMenu = function(pos) {
var m =
{ tag: "div",
childs: [
{ tag: "div",
childs: [
{ tag: "span", html: "Select an image from: " },
{ tag: "select",
id: "inp_image_source_" + pos,
events: { onchange: "showImagesSource('" + pos + "')"},
options: [
{ value: "int", text: "default images" },
{ value: "url", text: "link(url)" },
{ value: "flickr", text: "flickr" }
]}
]},
{ tag: "div", id: "image_source_" + pos + "int",
display: false,
childs: [
{ tag: "div", cn: "wlist",
style: { height: "183px" },
id: "wplist_int_" + pos }
]},
{ tag: "div", id: "image_source_" + pos + "url",
cn: "wlist",
style: { padding: "10px", height: "163px"},
display: false,
childs: [
{ tag: "span", html: "Address (URL): "},
{ tag: "input", type: "text",
style: { width: "300px"},
id: "inp_image_url_" + pos },
{ tag: "input", type: "button",
value: "Apply",
events: { onclick: "loadImageFromUrl('" + pos + "')"}}
]},
{ tag: "div", id: "image_source_" + pos + "flickr",
display: false,
childs: [
{ tag: "div",
style: { margin: "5px 0px 5px 0px"},
childs: [
{ tag: "img",
style: { width: "16px", height: "16px" },
src: "static/flickr.png" },
{ tag: "input", type: "text", size: 50,
value: (pos == "top" ? "background" : "wallpaper"),
id: "inp_flickr_search_" + pos },
{ tag: "input", type: "button",
value: "Search",
events: { onclick: "searchImagesFromFlickr('" + pos + "')"}}
]},
{ tag: "div", cn: "wlist",
style: { height: "152px" },
id: "wplist_flickr_" + pos }
]}
]}
return m;
}
this.pmodel_wallpapers = [
{ tag: "div", cn: "tabs_box",
childs: [
{ tag: "a", id: "tab_wp_top",
href: "showWpTab('wp_top')",
cn: "tab",
html: "Top wallpaper" },
{ tag: "a", id: "tab_wp_bottom",
href: "showWpTab('wp_bottom')",
cn: "tab",
html: "Bottom wallpaper" }
]},
{ tag: "div", cn: "tabs_pages_box",
childs: [
// page top bg
{ tag: "div", id: "tabpage_wp_top",
display: false,
childs: [
this.getImageMenu("top"),
{ tag: "div", cn: "section",
childs: [
{ tag: "span", html: "Display mode: " },
{ tag: "select", id: "inp_bgtop_mode",
options: [
{ text: "tile", value: "repeat" },
{ text: "center", value: "no-repeat" }
]},
{ tag: "span", html: " &nbsp; &nbsp; Alignment: " },
{ tag: "select", id: "inp_bgtop_align",
options: [
{ text: "top", value: "top center" },
{ text: "middle", value: "center" },
{ text: "bottom", value: "bottom center" }
]},
{ tag: "input", type: "button",
value: loc.text("btn_set"),
events: { onclick: "setBackgroundExtra('top')"}}
]},
{ tag: "div", cn: "section",
childs: [
{ tag: "span", html: "Or background color: "},
// color
{ tag: "input", type: "radio",
id: "inp_top_color",
events: { onclick: "selectBackgroundColor('top')"},
name: "wpt" },
{ tag: "img", width: 30, height: 17, cn: "inp_color_box",
src: "static/s.gif",
events: { onclick: "showColorsPopup('top')" },
id: "inp_top_color_img" },
{ tag: "input", type: "text",
id: "inp_top_color_text",
size: 10 },
// default
{ tag: "input", type: "radio",
id: "inp_bgtop_default",
events: { onclick: "setBackground('top',false)"},
name: "wpt" },
{ tag: "span", html: "Default" },
// transparent
{ tag: "input", type: "radio",
id: "inp_bgtop_transparent",
events: { onclick: "setBackground('top','transparent')"},
name: "wpt" },
{ tag: "span", html: "Transparent" }
]},
{ tag: "div", cn: "section",
html: "Header height:"},
{ tag: "div", cn: "section",
childs: [
{ tag: "div", cn: "track_box",
childs: [
{ tag: "div", cn: "gripper",
id: "hh_gripper" }
]}
]}
]},
// page bottom bg
{ tag: "div", id: "tabpage_wp_bottom",
display: false,
childs: [
this.getImageMenu("bottom"),
{ tag: "div", cn: "section",
childs: [
{ tag: "span", html: "Display mode: " },
{ tag: "select", id: "inp_bgbottom_mode",
options: [
{ text: "tile", value: "repeat center" },
{ text: "center", value: "no-repeat center" }
]},
{ tag: "span", html: " &nbsp; &nbsp;" },
{ tag: "input", type: "button",
value: loc.text("btn_set"),
events: { onclick: "setBackgroundExtra('bottom')"}},
{ tag: "span", html: " &nbsp; &nbsp;" },
{ tag: "input", type: "checkbox",
id: "inp_bgbottom_fixed",
events: { onclick: "setBackgroundExtra('bottom')"}},
{ tag: "span", html: " Fixed &nbsp; &nbsp; " },
]},
{ tag: "div", cn: "section",
childs: [
{ tag: "span", html: "Or background color: "},
// color
{ tag: "input", type: "radio",
id: "inp_bottom_color",
events: { onclick: "selectBackgroundColor('bottom')"},
name: "wpb" },
{ tag: "img", width: 30, height: 17, cn: "inp_color_box",
src: "static/s.gif",
events: { onclick: "showColorsPopup('bottom')" },
id: "inp_bottom_color_img" },
{ tag: "input", type: "text",
id: "inp_bottom_color_text",
size: 10 },
// default
{ tag: "input", type: "radio",
id: "inp_bgbottom_default",
events: { onclick: "setBackground('bottom',false)"},
name: "wpb" },
{ tag: "span", html: "Default" }
]}
]}
]}
];
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.isWallpapersLoaded = false;
this.isWalppapersFilled = false;
this.onShowPage_wallpapers = function() {
if(!this.isWalppapersFilled) {
this.searchImagesFromFlickr("top");
this.searchImagesFromFlickr("bottom");
var self = this;
this.elements["hh_gripper"].tracker =
new Tracker(this.elements["hh_gripper"],
{ start: 0, end: 75,
value: desktop.profile["header_size"],
width: 482,
onchange: self.onHeaderHeightChanging,
onstop: self.onHeaderHeightChanged });
var pt = desktop.profile["background"]['top'];
if(pt["mode"]) {
this.elements["inp_bgtop_mode"].value = pt.mode;
this.elements["inp_bgtop_align"].value = pt.align;
this.elements["inp_image_url_top"].value = this.getImageUrlFromBg(pt.value);
} else if(pt == "transparent") {
this.elements["inp_bgtop_transparent"].checked = true;
} else if(pt && pt.indexOf("#") != -1) {
this.elements["inp_top_color"].checked = true;
this.elements["inp_top_color_text"].value = pt;
this.elements["inp_top_color_img"].style.background = pt;
} else {
this.elements["inp_bgtop_default"].checked = true;
}
var pb = desktop.profile["background"]['bottom'];
if(pb["mode"]) {
this.elements["inp_bgbottom_mode"].value = pb.mode;
this.elements["inp_bgbottom_fixed"].checked = pb.fix;
this.elements["inp_image_url_bottom"].value = this.getImageUrlFromBg(pb.value);
} else if(pb && pb.indexOf("#") != -1) {
this.elements["inp_bottom_color"].checked = true;
this.elements["inp_bottom_color_text"].value = pb;
this.elements["inp_bottom_color_img"].style.background = pb;
} else if(pb == "default") {
this.elements["inp_bgbottom_default"].checked = true;
}
this.showWpTab("wp_top");
this.isWalppapersFilled = true;
}
if(!this.isWallpapersLoaded) {
this.elements["wplist_int_top"].innerHTML = loc.text("msg_loading");
this.elements["wplist_int_bottom"].innerHTML = loc.text("msg_loading");
request.send( {act: "get_wallpapers"}, this);
}
}
this.wallpapers = { top: [], bottom: [] }
this.renderWallpaperThumb = function(el, pos, thumb, file) {
this.buildDomModel(this.elements[el],
{ tag: "a", cn: "thumb",
events: { onclick: "setWallpaper('" + pos + "','" + file + "')"},
childs: [
{ tag: "img",
src: thumb }
]}
);
}
this.renderWallpapers = function(pos, src, list) {
var el = "wplist_"+ src+ "_" + pos ;
this.elements[el].innerHTML = "";
for(var i=0; i<list.length; i++) {
this.renderWallpaperThumb(el, pos, list[i].thumb, list[i].file);
}
}
this.setWallpaper = function(pos, image) {
this.elements["inp_image_url_" + pos].value = image;
if(pos == "top") {
this.elements["inp_bgtop_transparent"].checked = false;
this.elements["inp_bgtop_default"].checked = false;
this.elements["inp_top_color"].checked = false;
this.setBackground(pos,
{ value: "url(" + image + ")",
mode: this.elements["inp_bgtop_mode"].value,
align: this.elements["inp_bgtop_align"].value });
} else {
this.elements["inp_bottom_color"].checked = false;
this.elements["inp_bgbottom_fixed"].checked = false;
this.setBackground(pos,
{ value: "url(" + image + ")",
mode: this.elements["inp_bgbottom_mode"].value,
fix: this.elements["inp_bgbottom_fixed"].checked });
}
}
this.setBackgroundExtra = function(pos) {
if(desktop.profile["background"][pos]["mode"]) {
if(pos == "top") {
desktop.profile["background"][pos].mode = this.elements["inp_bgtop_mode"].value;
desktop.profile["background"][pos].align = this.elements["inp_bgtop_align"].value;
} else {
desktop.profile["background"][pos].mode = this.elements["inp_bgbottom_mode"].value;
desktop.profile["background"][pos].fix = this.elements["inp_bgbottom_fixed"].checked;
}
desktop.save();
desktop.applyBackgrounds();
}
}
this.setBackground = function(pos, value) {
desktop.profile["background"][pos] = value;
desktop.save();
desktop.applyBackgrounds();
}
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);
}
// Colors poup
this.getColorsPopupModel = function(id) {
var colorsTable = { tag: "table", cellSpacing: "0", cellPadding: "0",
style: {borderLeft: "1px solid gray", borderTop: "1px solid gray"},
childs: [] }
for(var i=0; i<colorsChart.length; i++) {
var tds = [];
for(var j=0; j<colorsChart[i].length; j++) {
tds.push({ tag: "td",
childs: [
{ tag: "div",
style: {borderRight: "1px solid gray", borderBottom: "1px solid gray", background: colorsChart[i][j], width: "16px", height: "16px", cursor: "pointer"},
events: {onclick: "onSelectColor(\"" + id + "\", \"" + colorsChart[i][j] + "\")"}
}
]
});
}
colorsTable.childs.push({tag: "tr", childs: tds});
}
var m =
{ tag: "div", className: "panel", id: id+"_popup", display: false,
style: {position: "absolute", zIndex: "20000", width: "306px", height: "174px", overflow: "hidden"},
childs: [
{ tag: "div", className: "caption",
childs: [
createTableDom([{content: "<b>Select color</b>", width: "100%"},
{content: createButtonDom(false, "closeColorsPopup(\""+id+"\")", "static/client/close.gif"), width: "1%"}
])
]},
{ tag: "div", className: "content",
childs: [ colorsTable ]}
]}
return m;
}
// 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);
}
this.flickRequest = { top: false, bottom: false };
this.searchImagesFromFlickr = function(pos) {
if(this.flickRequest[pos]) return;
var str = trim(this.elements["inp_flickr_search_" + pos].value);
if(str == "") return;
var url = "http://www.flickr.com/services/feeds/photos_public.gne?format=rss_200&tags=" + str;
var self = this;
request.getFeed(url, this, "processFlicrImages_" + pos);
this.flickRequest[pos] = str;
this.elements["wplist_flickr_" + pos].innerHTML = loc.text("msg_loading");
}
this.renderFlickrImages = function(pos, list) {
if(list) {
var res = [];
for(var i=0; i<list.length; i++) {
var t = list[i]["MEDIA:THUMBNAIL"]["URL"];
var f = t.substr(0, t.length-6) + '.jpg'
res.push({ thumb: t, file: f});
}
this.renderWallpapers(pos, "flickr", res);
} else {
this.elements["wplist_flickr_" + pos].innerHTML = loc.text("msg_error");
}
}
this.processFlicrImages_top = function(data) {
this.elements["inp_flickr_search_top"].value = this.flickRequest["top"];
this.flickRequest["top"] = false;
this.renderFlickrImages("top", data[1]);
}
this.processFlicrImages_bottom = function(data) {
this.elements["inp_flickr_search_bottom"].value = this.flickRequest["bottom"];
this.flickRequest["bottom"] = false;
this.renderFlickrImages("bottom", data[1]);
}
// 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")
]}
]}
this.buildDomModel(this.elements["content"], m);
this.buildDomModel(document.body, [
this.getColorsPopupModel("top"),
this.getColorsPopupModel("bottom")
]);
}
this.onOpen = function() {
this.setTitle(this.cfg.title);
this.showImagesSource("top");
this.showImagesSource("bottom");
}
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 "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;
}
}
}
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",
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",
events: { onenter: "setUrl()" },
type: "text", size: "15", className: "settings_control"},
{ tag: "input", type: "button", value: loc.text("btn_go"), events: {onclick: "setUrl()"}}
]}
]
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 = loc.text("msg_loading");
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: "a", href: "void",
innerHTML: this.data.title.substr(0,25),
events: { onclick: "openSite()" } });
if(count > readed) {
this.buildDomModel(this.elements.title,
{ tag: "span",
innerHTML: " &nbsp;(" + (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,
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: "a", href: "void",
innerHTML: this.data.title.substr(0,25),
events: { onclick: "openSite()" } });
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');
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", 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()"}}
]}
]
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: { paddingLeft: "30px", background: "url(widgets/popmail/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/popmail/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/popmail/ico.gif) no-repeat 0 0"},
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.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,
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",
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: "setNewsCount()"}, className: "settings_control"}
]
},
{ 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()"}} ]}
]
this.domContent = [
{ tag: "div", id: "messages_area",
display: false,
childs: [
{ tag: "div",
style: { padding: "0 0 0 30px", height: "24px", background: "url(widgets/gmail/ico.gif) no-repeat 0 0"},
childs: [
{ tag: "span", id: "mail_total" },
{ tag: "input", type: "checkbox",
style: { margin: "0 0 0 16px"},
events: {onclick: "switchMailsContent()"}, id: "switcher"}
]},
{ tag: "div", id: "mail_list"}
]
},
{ tag: "div", id: "config_note",
style: { paddingLeft: "30px", background: "url(widgets/gmail/ico.gif) no-repeat 0 0"},
innerHTML: loc.text("gmail_msg_not_configured")},
{ 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.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");
}
}
this.onOpen = function() {
if(trim(this.profile.title) == "") {
this.profile.title = loc.text("gmail_title");
}
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");
if(this.profile["email"] != "" && this.profile["password"] != "") {
if(!isLoading) {
isLoading = true;
this.setTitle(loc.text("msg_loading"));
this.hideElement("config_note");
xmlRequest.send("https://mail.google.com/mail/feed/atom/", this, "showMail", {login: this.profile.email, password: this.profile.password});
}
} else {
this.showElement("config_note");
}
}
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.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.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");
}
}
Gmail.prototype = new Widget();
function AolMail() {
this.init();
this.cfg = {
hasSettingsBtn: true,
title: "",
module: "AolMail"
}
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: "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()"}}
]}
]
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/aolmail/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/aolmail/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/aolmail/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("aolmail_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 = "/imap/ssl/novalidate-cert";
this.req = request.send({ login: this.profile.login,
password: this.profile.password,
protocol: protocol,
server: "imap.aol.com",
port: 993 }, 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;
}
}
}
AolMail.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()"}}
]}
]
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()"}}
]
}
]
}
];
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: " Add ", events: {onclick: "addItem()"}, className: "settings_control"}
]}
]
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) {
this.elements.title.innerHTML = this.cfg.title_prefix + html;
}
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;
hideEl(text_show);
showEl(text_edit);
text_edit.style.height = (h+16)+"px";
text_edit.focus();
text_edit.onkeyup = function() {
text_show.innerHTML = text2html(this.value);
showEl(text_show);
this.style.height = (text_show.offsetHeight+16) + "px";
hideEl(text_show);
}
text_edit.onblur = function() {
text = this.value.replace(/\\/g, "");
this.onblur = null;
hideEl(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_postfix"),
module: "Flickr"
}
this.defaultProfile["tags"] = "";
this.defaultProfile["layout"] = "s"; // s|t
this.defaultProfile["target"] = "s"; // s|f
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: " Set ", 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")}
]
}
]}
]
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: "menu_panel", 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);
if(tags != "") {
this.profile.tags = tags;
this.save();
this.refresh();
}
}
this.onOpen = function() {
this.refresh();
}
this.refresh = function() {
this.setTitle(loc.text("msg_loading"));
xmlRequest.send(this.tagUrl + (this.profile.tags=="" ? "" :  "&tags="+escape(this.profile.tags)), this, "showPhotos");
}
this.renderPhotos = function() {
if(this.data) {
if(this.profile.layout == "s") {
if(this.data.items.length > 1) {
showEl(this.elements.head);
} else {
hideEl(this.elements.head);
}
this.curPhoto = 0;
this.showBigPhoto(this.curPhoto);
} else {
this.showAllPhotos();
}
}
}
/// 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) {
hideEl(this.elements.view_thumbs);
showEl(this.elements.view_big);
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;
}
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.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);
}
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(this.data.title);
this.renderPhotos();
}
}
}
}
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 }
]}
]
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.setTitle(loc.text("msg_loading"));
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);
} 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 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 + "</td>" +
"</tr>";
}
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 }
]}
]
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 }
]}
]
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.setTitle(loc.text("msg_loading"));
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"] + "</td>" +
"</tr>";
}
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: "",
module: "YoutubeVideo"
};
this.channels = [
{text:"- Video -", value: "", isBold: true},
{text:"Recently Added", value: "http://youtube.com/rss/global/recently_added.rss"},
{text:"Recently Featured", value: "http://youtube.com/rss/global/recently_featured.rss"},
{text:"Top Favorites", value: "http://youtube.com/rss/global/top_favorites.rss"},
{text:"Top Rated", value: "http://youtube.com/rss/global/top_rated.rss"},
{text:"- Most Viewed Videos -", value: "", isBold: true},
{text:"Today", value: "http://youtube.com/rss/global/top_viewed_today.rss"},
{text:"This Week", value: "http://youtube.com/rss/global/top_viewed_week.rss"},
{text:"This Month", value: "http://youtube.com/rss/global/top_viewed_month.rss"},
{text:"All Time", value: "http://youtube.com/rss/global/top_viewed.rss"},
{text:"- Most Discussed Videos -", value: "", isBold: true},
{text:"Today", value: "http://youtube.com/rss/global/most_discussed_today.rss"},
{text:"This Week", value: "http://youtube.com/rss/global/most_discussed_week.rss"},
{text:"This Month", 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 }
]}
]
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(!isLoading) {
this.setTitle(loc.text("msg_loading"));
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"];
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=120 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 href='"+lnk2+"' target=_blank>"+
"<img src='widgets/youtubevideo/cam.gif' style='margin-right: 4px; height: 8px; border: 0; vertical-align: middle;'>"+
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"] = "RSXX0199";
this.defaultProfile["unit"] = "c";
this.domSettings = [
{ 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",
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", className: "settings_section", id: "citiesList", display: false}
]
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;
this.refresh = function() {
if(!loading) {
loading = true;
this.setTitle(loc.text("msg_loading"));
xmlRequest.send("http://xoap.weather.com/weather/local/"+this.profile.city+"?cc=*&unit=d&dayf=4", this, "showWeather");
}
}
this.setUnit = function() {
this.profile.unit = this.elements.setUnit.value;
this.renderWeather();
this.save();
}
this.loadCities = function() {
this.elements.citiesList.innerHTML = loc.text("msg_loading");
showEl(this.elements.citiesList);
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 = '';
showEl(this.elements.citiesList);
var doc = response.responseXML.documentElement;
var r = doc.getElementsByTagName("loc");
if(r.length == 1) {
this.setCity(r[0].getAttribute("id"))
} 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] = { tag: "li",
childs: [
{ tag: "a", href: "void", events: {onclick: "setCity('"+r[i].getAttribute("id")+"')"},
innerHTML: r[i].firstChild.nodeValue}
]
}
}
this.buildDomModel(this.elements.citiesList, { tag: "ul", childs: clistDom });
}
}
this.setCity = function(id) {
this.profile.city = id;
hideEl(this.elements.citiesList);
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++) {
pic = parseInt(days[i].getElementsByTagName("icon")[0].firstChild.nodeValue);
pic = ((pic < 10) ? "0" : "") + pic + ".gif";
mDays.push({ tag: "td", style: {textAlign: "center"},
childs: [
{ tag: "div", innerHTML: days[i].getAttribute("t") },
{ tag: "img", src: 'static/weather/' + pic },
{ tag: "div", innerHTML: this.getTemp(days[i]) }
]});
}
var m = { tag: "table", className: "sys_table", style: {width: "100%"},
childs: [
{ tag: "tr",
childs: mDays }
]};
this.elements["content"].innerHTML = '';
this.buildDomModel(this.elements["content"], m);
if(this.data.getElementsByTagName("dnam").length>0) {
this.setTitle(this.cfg.title + " : " + this.data.getElementsByTagName("dnam")[0].firstChild.nodeValue);
}
}
this.showWeather = function(response) {
this.data = response.responseXML.documentElement;
this.renderWeather();
loading = false;
}
}
Weather.prototype = new Widget();
function Websearch() {
this.init();
this.cfg = {
hasRefreshBtn: false,
title: loc.text("websearch_title"),
module: "Websearch"
}
this.defaultProfile["openHere"] = "0";
this.defaultProfile["serverId"] = 1;
this.domSettings = [
{ tag: "div", className: "settings_section",
childs: [
{ tag: "span", innerHTML: loc.text("websearch_results_target"), className: "settings_label"},
{ tag: "input", id: "set_target", type: "checkbox", events: {onclick: "setTarget()"}, className: "settings_control"}
]}
]
this.domContent = [
{ tag: "div", className: "menu_panel", style: {marginTop: "4px", padding: "0px"}, id: "servers_tabs", innerHTML: " "},
{ tag: "div", className: "menu_panel", style: {background: "#EAEAFF", 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++) {
this.buildDomModel(this.elements.servers_tabs,
{ tag: "span", className: "bevel_section",
style: {cursor: "pointer", fontWeight: "normal"},
id: "tab_"+i, align: "center",
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 = null;
this.showServerTab = function(serverId) {
if(this.activeTab) {
this.elements["tab_"+this.activeTab].style.backgroundColor = "#EAEAFF";
this.elements["tab_"+this.activeTab].style.fontWeight = "normal";
}
this.elements["tab_"+serverId].style.backgroundColor = "#FFFFFF";
this.elements["tab_"+serverId].style.fontWeight = "bold";
this.activeTab = serverId;
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+escape(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"}
]}
]
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 avanzobrowser() {
// ::Avanzo:: objeto navegador de Avanzo.
this.init();
this.cfg = {
hasIcon: false,
hasRefreshBtn: false,
hasSettingsBtn: true,
hasProfile: true,
hasSizeBtn: false,
hasCloseBtn: true,
hasDrag: false,
title: loc.text("browser_title"),
module: "avanzobrowser"
};
this.defaultProfile["home_page"] = "escuela/cursos.php";
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"}
]}
]
this.domContent = [
{ tag: "iframe",
id: "browser",
vspace: "0",
hspace: "0",
marginwidth: "0",
marginheight: "0",
frameBorder: "0",
style: { width: "100%", height: "680px", border: "0" }}
]
this.onBuildInterface = function() {
this.setTitle("Avanzo");
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.elements["inp_home_page"].value = "escuela/cursos.php";
}
this.onOpen = function() {
this.navHome();
}
this.setHomePage = function() {
//this.profile["home_page"] = this.formatUrl(this.elements["inp_home_page"].value);
this.profile["home_page"] = "escuela/cursos.php";
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;
}
}
avanzobrowser.prototype = new Widget("sinBorde");
function HTMLBrowserAvanzo() {
// ::Avanzo:: objeto navegador sin opciones para mostrar las URL que queramos.
this.init();
this.cfg = {
hasRefreshBtn: false,
hasSettingsBtn: false,
hasCloseBtn: false,
hasProfile: true,
title: loc.text("browser_title"),
module: "HTMLBrowserAvanzo"
};
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"}
]}
]
this.domContent = [
{ tag: "iframe",
id: "browser",
vspace: "0",
hspace: "0",
marginwidth: "0",
marginheight: "0",
frameBorder: "0",
style: { width: "100%", height: "400px", border: "0" }}
]
this.onBuildInterface = function() {
this.setTitle("Avanzo - Solicitud de cursos");
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;
}
}
HTMLBrowserAvanzo.prototype = new Widget();
function HTMLBrowserBolsa() {
// ::Avanzo:: objeto navegador sin opciones para mostrar las URL que queramos.
this.init();
this.cfg = {
hasRefreshBtn: false,
hasSettingsBtn: false,
hasCloseBtn: false,
hasProfile: true,
title: loc.text("browser_title"),
module: "HTMLBrowserBolsa"
};
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"}
]}
]
this.domContent = [
{ tag: "iframe",
id: "browser",
vspace: "0",
hspace: "0",
marginwidth: "0",
marginheight: "0",
frameBorder: "0",
style: { width: "100%", height: "400px", border: "0" }}
]
this.onBuildInterface = function() {
this.setTitle("Valores de bolsa");
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;
}
}
HTMLBrowserBolsa.prototype = new Widget();
function Calculator() {
this.init();
this.cfg = {
hasProfile: false,
title: "",
hasSettingsBtn: false,
hasRefreshBtn: false,
module: "Calculator"
}
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,
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"} }
]},
{ 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,
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,
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();
