[^]*?<\/ITEMS>/gm)) {
debug(5,"fix item order", { "_xml" : _xml });
if (typeof oarg.xhttpobj.responseXML == 'undefined') {
_xml = hs.functions.fix_xml(oarg.xhttpobj.responseText);
}
// fix item order
_xml = _xml.replace(/<(TXT|BOX|ICO|GRAF|CAM)\s\w+=[^]*?\/>/g, function(match, capture) {
return match.replace(capture,'ITEM type="' + capture + '"');
});
try {
oarg.xhttpobj.responseXML = $.parseXML(_xml)
} catch (e) {
debug(0,"INVALID XML",e);
return null;
}
}
try {
var _json = $.xml2json(oarg.xhttpobj.responseXML);
return _json;
} catch (e) {
oarg.error = e.toString();
}
}
}
}
debug(0,"Error: " + oarg.error, oarg);
switch (oarg.error) {
case "auth_error" : hs.functions.login_dialog( oarg ); break;
case "pass_error" : hs.functions.login_dialog( oarg ); break;
case "timeout !!" : hs.functions.login_init( oarg ); break;
case "connreset" : hs.functions.reconnect( oarg ); break;
case "handle error !!" : hs.functions.login_init( oarg ); break;
case "user kidnapped !!": hs.functions.login_init( oarg ); break;
case "99" : debug(0,"Visuseite nicht gefunden",oarg); break;
default : alert("Error " + oarg.error); break
}
return (oarg.error == "");
}
hs.functions.reconnect = function( oarg ) {
hs.functions.popup_overlay(true,true);
hs.connection.failure += 1;
debug(3,"reconnect " + hs.connection.failure,oarg);
var _waittime = Math.min(2000 * (hs.connection.failure -1) ,60000); // max 60sec
$.each(hs.session,function(index,session) {
session.connection_status = "reconnect";
session.ajax_queue.clearQueue();
session.ajax_xhr.abort('reconnect');
debug(3,"clear_session",session);
// remove all session except main VISU session
if(session.target != "VISU") {
delete hs.session[session.target];
}
});
if (navigator.onLine) {
setTimeout(function() {
if(hs.session.VISU.connection_status != "connected") {
hs.functions.login_init({
"session" : hs.session.VISU
});
}
},_waittime + 1);
}
}
hs.functions.swap_object = function( obj ) {
var _ret = {};
for (var key in obj) {
_ret[obj[key]] = key;
}
return _ret;
}
hs.functions.entity = new (function() {
var map = {
"&" : "&",
"<" : "<",
">" : ">",
'"' : """,
"'" : "'"
};
var rmap = hs.functions.swap_object( map );
this.encode_regex = new RegExp("[" + Object.keys(map).join("") + "]","g");
this.decode_regex = new RegExp("[" + Object.keys(rmap).join("") + "]","g");
this.encode = function ( text ) {
return text.replace(this.encode_regex, function (entity) {
return map[entity];
});
}
this.decode = function ( text ) {
return text.replace(this.decode_regex, function (entity) {
return rmap[entity];
});
}
return this;
})();
hs.functions.fix_xml = function ( xml ) {
debug(4,"fix_xml: broken xml ",{ "xml": xml });
var _result = null;
var _regex = new RegExp(/=\"(.*?)\"/gm);
while( _result = _regex.exec(xml)) {
var _match = _result[1];
if (_match.match(hs.functions.entity.encode_regex) == null) {
continue;
}
var _match_len = _match.length;
_match = hs.functions.entity.encode(_match);
var _xml_len = xml.length;
var _index = _result.index +2;
xml = xml.substr(0,_index ) + _match + xml.substr(_index + _match_len ,_xml_len - _index + _match_len);
}
return xml;
}
hs.functions.login_init = function( oarg ) {
debug(5,"[start] login_init:",oarg);
oarg.session.connection_status = "init";
oarg.session.ajax_queue.clearQueue();
var _cmd = "init";
var _url = "/hsgui?cmd=" + _cmd;
_url += "&user=" + hs.auth.username;
_url += "&cid=" + hs.auth.gui_design;
_url += "&ref=" + hs.auth.gui_refresh;
hs.functions.make_request( {
"session" : oarg.session,
"cmd" : _cmd,
"url" : _url
});
};
hs.functions.async.login = function( oarg ) {
debug(5,"[start] async.login:",oarg);
oarg.session.connection_status = "authenticate";
oarg.session.auth.handle = oarg.json.HS.HND;
oarg.session.auth.tan = oarg.json.HS.TAN;
oarg.session.auth.tan_counter = 0;
oarg.session.auth.pos = parseInt(oarg.json.HS.POS)+1;
oarg.session.auth.glob_key1 = hs.functions.make_globkey(0x5c);
oarg.session.auth.glob_key2 = hs.functions.make_globkey(0x36);
hs.functions.make_request( {
"session" : oarg.session,
"cmd" : "login"
});
};
hs.functions.async.logged_in = function( oarg ) {
debug(5,"[start] async.logged_in (" + oarg.session.target + "):",oarg.json);
// check main
hs.connection.failure = 0;
oarg.session.connection_status = "connected";
if (hs.user == null) {
hs.user = {};
hs.user.load_background = parseInt(oarg.json.HS.VIS._bgi); // unwichtig ?
hs.user.fullscreen_visu = oarg.json.HS.VIS._fv == 1;
hs.user.start_page = parseInt(oarg.json.HS.USR._vis);
hs.user.start_query = parseInt(oarg.json.HS.USR._qry);
hs.user.start_list = parseInt(oarg.json.HS.USR._lst);
hs.user.start_go = parseInt(oarg.json.HS.USR._go); // ????
hs.user.streaming = oarg.json.HS.USR._stream == 1;
hs.user.refresh_visu = oarg.json.HS.USR._refvis*1;
hs.user.refresh_visucam = oarg.json.HS.USR._refvcam*1;
hs.user.refresh_visugraf = oarg.json.HS.USR._refvgraf*1;
hs.user.refresh_visugrafcam = oarg.json.HS.USR._refvgrafcam*1;
hs.user.refresh_list = oarg.json.HS.USR._reflst*1;
hs.user.refresh_query = oarg.json.HS.USR._refqry*1;
hs.user.refresh_mask = oarg.json.HS.USR._refmask*1;
hs.user.refresh_graf = oarg.json.HS.USR._refgraf*1;
hs.user.refresh_cam = oarg.json.HS.USR._refcam*1;
hs.functions.update_timer();
}
// überprüfen ob die Schriften sich geändert haben
if (hs.gui.hashes._font != oarg.json.HS.HASH._font) {
hs.functions.make_request( {
"session" : oarg.session,
"cmd" : "getfont"
});
}
// überprüfen ob die Parameter geändert wurden
if (hs.gui.hashes._para != oarg.json.HS.HASH._para) {
hs.functions.make_request( {
"session" : oarg.session,
"cmd" : "getattr"
});
}
hs.gui.hashes = oarg.json.HS.HASH;
hs.functions.storage("set","hashes",hs.gui.hashes);
// remove old pages after reconnect
debug(4,"Remove old pages",hs.gui.pages);
$.each(hs.gui.pages,function(index,page) {
if(page.session.target == oarg.session.target) {
page.object.remove()
delete hs.gui.pages[page.id];
}
});
// Visuseite laden
oarg.session.start_page = oarg.session.start_page || hs.user.start_page;
oarg.page_id = oarg.session.active_page ? oarg.session.active_page.page_id : null || oarg.session.start_page;
hs.functions.load_page( oarg );
setTimeout(hs.functions.popup_overlay,500);
};
hs.functions.update_timer = function() {
if ( hs.gui.update_timer != null) {
clearTimeout(hs.gui.update_timer)
}
if(hs.auth.password) {
hs.functions.update()
}
hs.gui.update_timer = setTimeout(hs.functions.update_timer, (hs.user.refresh_visu *50));
}
hs.functions.update = function() {
var _now = $.now();
$.each(hs.session, function(index, session) {
var _delay = (hs.gui.hidden || (session.target_obj.is(":visible") == false) ) ? hs.connection.hiddentime * 1000: 0;
if(session.connection_status != "connected" || !session.active_page) {
return;
}
if (session.active_page.next_update && session.active_page.next_update + _delay <= _now) {
debug(5,"Update " + session.active_page.id,session);
session.active_page.next_update = hs.functions.get_next_update(session.active_page) ;
hs.functions.make_request( {
"session" : session,
"cmd" : "gvu&id=" + session.active_page.page_id + "&det=1",
"page_id" : session.active_page.page_id
});
}
$.each(session.active_page.items, function(index,item) {
if($.inArray(item.type,["CAM","GRAF","ICO"]) > -1) {
if(item.next_update && item.next_update + _delay <= _now) {
item.next_update = null;
debug(5,"Update " + item.uid,item);
hs.functions.load_image({
"item" : item
});
}
}
if(item.type == "TXT" && item.next_update && item.next_update + _delay <= _now) {
if(typeof item.update_code == 'function') {
debug(5,"Update " + item.uid,session);
item.update_code( {
"session" : session,
"item" : item,
"page_id" : session.active_page.page_id
});
}
}
});
});
}
hs.functions.do_command = function( oarg ) {
debug(4,"do_command:",oarg);
if (oarg.item.has_command) {
hs.functions.make_request( {
"session" : oarg.item.session,
"cmd" : "vcu&id=" + oarg.item.id,
"page_id" : oarg.page_id
});
}
}
hs.functions.do_list_command = function( oarg, pos ) {
debug(4,"do_list_command:",oarg);
if (oarg.item.has_command) {
hs.functions.make_request( {
"session" : oarg.item.session,
"cmd" : "lstcmd&id=" + oarg.item.id + "&pos=" + pos,
"page_id" : oarg.page_id
});
}
}
hs.functions.math_round = function(value, digits) {
var _exp = parseInt("1" + Array(1 + (digits || 0) ).join("0"));
return Math.round(value * _exp) / _exp;
}
hs.functions.do_valset = function ( oarg ) {
debug(4,"do_valset: " + oarg.item.value,oarg);
if(typeof oarg.item.value == 'undefined' || oarg.item.action_id != 9) {
return;
}
if(oarg.item.session.active_page != oarg.item.page) {
debug(1,"Error Valset page not the active page",oarg);
return;
}
if(oarg.item.info) {
oarg.item.value = hs.functions.math_round(oarg.item.value,oarg.item.info._prec);
}
hs.functions.make_request( {
"session" : oarg.item.session,
"cmd" : "valset&id=" + oarg.item.id + "&val=" + oarg.item.value,
"page_id" : oarg.item.page.page_id
});
}
hs.functions.load_page = function( oarg ) {
debug(4,"load_page (" + oarg.session.target + "): " + oarg.page_id, oarg);
var _extra_request = "";
if (typeof oarg.item != 'undefined' && oarg.item.has_command) {
_extra_request = "&cmdid=" + oarg.item.id + "&cmdpos=0";
}
oarg.page_id = parseInt(oarg.page_id) || oarg.session.start_page;
if (hs.gui.pages.hasOwnProperty(oarg.page_id)) {
var _page = hs.gui.pages[oarg.page_id];
if (!_page.hidepage) {
//FIXME
if ($.inArray(oarg.page_id, hs.gui.active_pages) > -1 ) {
debug(5,"load_page:FadeIn Cached Page "+oarg.page_id);
_page.object.css("z-index","50");
_page.object.fadeIn(20);
hs.functions.add_history( oarg );
document.title = "xxAPI² - " + _page.text1;
}
oarg.cmd = "gv&id=" + oarg.page_id + "&det=1" + _extra_request;
hs.functions.make_request( oarg );
return
}
}
hs.functions.make_request( {
"session" : oarg.session,
"cmd" : "gv&id=" + oarg.page_id + "&det=1" + _extra_request,
"page_id" : oarg.page_id
});
};
hs.functions.async.gv = function( oarg ) {
debug(5,"async.gv (" + oarg.session.target + "): ",oarg);
if (oarg.session.target == "VISU" && oarg.json.HS.VISU && (oarg.json.HS.VISU._pop*1) > 0) {
debug(3,"visu_alarm",oarg);
setTimeout(function() {
oarg.page_id = oarg.json.HS.VISU._pop*1;
hs.functions.load_page(oarg) ;
},1);
return;
}
if (oarg.json.HS.ITEMS) {
new hs.functions.hs_page( oarg );
}
};
hs.functions.mouse_event = function( oarg ) {
debug(5,"mouse_event: " + oarg.item.event.type,oarg);
if (typeof oarg.item.eventcode[oarg.item.event.type] == 'function') {
oarg.item.eventcode[oarg.item.event.type]( oarg );
}
if (oarg.item.click) {
switch(oarg.item.event.type) {
case "mousedown" :
case "touchstart" : oarg.item.object.addClass("activevisuelement"); break;
case "mouseup" :
case "mouseleave" :
case "blur" :
case "touchend" : window.setTimeout(function() {oarg.item.object.removeClass("activevisuelement");},hs.options.visualclickdelay); break;
}
}
}
hs.functions.check_click = function( oarg ) {
debug(3,"check_click",oarg);
oarg.action = "click";
//var _session_position = oarg.item.session.target_obj.position();
xxAPI.events.lastclick.event = oarg.item.event = oarg.item.event || {};
xxAPI.events.lastclick.top = oarg.item.event.pageY // - _session_position.top;
xxAPI.events.lastclick.left = oarg.item.event.pageX // - _session_position.left;
/*
Element .action_id
0 = Nur Befehl
1 = Seitenaufruf (optional Befehl)
2 =
3 =
4 =
5 =
6 =
7 = Kamera (CAM)
8 = Wochenschaltuhr /hsgui?cmd=getpag&id=31&hnd=4&code=C52747C9D8 (TIM)
9 = Werteingabe /hsgui?cmd=getpag&id=23&hnd=3&code=CB87CC79BA (VAL)
10 = Urlaubskalender (VAC)
11 = Feiertagskalender (HOL)
12 = Datum/Uhrzeit setzen /hsgui?cmd=getpag&id=17&hnd=3&code=CB87CC79BA (DATE)
13 =
14 = Meldungsarchiv /hsgui?cmd=getmsg&id=29&dir=0&cnt=5&hnd=4&code=2EB8E86D8F (MSG)
15 = Buddy /hsgui?cmd=getbud&id=25&dir=0&cnt=5&hnd=3&code=CC16E8CD49 (BUD)
16 = Diagramm /hsgui?cmd=getpag&id=32&hnd=4&code=C65F9B4058 (GRAF)
17 = Kamera-Archiv /hsgui?cmd=getcama&id=30&dir=0&cnt=6&hnd=4&code=FF8BF7D074 (CAMA)
18 = Universal Zeitschaltuhr /hsgui?cmd=getuhr&id=18&dir=0&cnt=5&hnd=4&code=18831A2D12 (UHR)
19 =
20 = Seite aktualisieren
21 = Navigation: Startseite
22 = Navigation: Zurück
23 = Menü /hsgui?cmd=gl&id=153&frm=1&cnt=5&hnd=2&code=935C315C9D /hsgui?cmd=glu&hnd=1&code=33B5E3DF74 // /hsgui?cmd=gl&id=291&frm=1&cnt=5&hnd=1&code=A5840BEDB8
24 = Query /hsgui?cmd=gq&id=6&frm=1&cnt=5&chk=0&hnd=4&code=3BC1D69459
25 = Navigation: Beenden /hsgui?cmd=logout&hnd=3&code=AE7A1C1473
*/
switch (oarg.item.action_id) {
case -1:
break;
case 0:
// 0 = Nur Befehl
hs.functions.do_command( oarg );
break;
case 1:
// 1 = Seitenaufruf (optional Befehl)
oarg.page_id = oarg.item.open_page;
oarg.session = hs.session[oarg.session.default_target] || oarg.session;
hs.functions.load_page( oarg );
break;
case 7:
hs.functions.popup_image( oarg );
break;
case 8:
case 18:
// Wochenschaltuhr / UZSU
/*
/hsgui?cmd=timset&id=31&days=000000000&frm=1200&to=2100&act=0&hnd=4&code=A2669029CE
*/
hs.functions.popup_timer ( oarg );
break;
case 9:
// Werteingabe
hs.functions.popup_werteingabe( oarg );
break;
case 12:
// Datum/Zeit setzen
/*
/hsgui?cmd=getpag&id=17&hnd=3&code=CB87CC79BA
/hsgui?cmd=dateset&id=17&date=20141209&time=092100&hnd=4&code=C49E6423F3
*/
alert("Datum/Zeit setzen noch nicht implementiert");
break;
case 14:
case 15:
hs.functions.popup_lister( oarg );
break;
case 16:
// Diagramm
/*
/hsgui?cmd=getpag&id=32&hnd=4&code=C65F9B4058
*/
hs.functions.popup_image( oarg );
break;
case 17:
hs.functions.popup_lister( oarg );
break;
case 21:
// 21 = Navigation: Startseite
if ( oarg.session.start_page != oarg.item.page.id) {
oarg.page_id = oarg.session.start_page;
hs.functions.load_page( oarg );
}
break;
case 22:
// 22 = Navigation: Zurück
debug(5,"history_back",oarg);
if (oarg.session.history.length > 1) {
oarg.session.history.pop();
var _lastpage = oarg.session.history.pop();
if(oarg.item.page.is_popup) {
oarg.item.page.object.detach()
}
if (_lastpage !== undefined) {
oarg.page_id = _lastpage.page_id;
hs.functions.load_page( oarg );
}
}
break;
case 23:
// 23 = Menü
//hs.functions.make_request({ session:session,cmd:"gl&id=" + hs.user.start_list + "&frm=1&cnt=5"} );
alert("Menü noch nicht implementiert");
break;
case 25:
// 25 = Logout
hs.functions.logout();
break;
default:
alert("Funktionstyp " + oarg.item.action_id + " noch nicht implementiert");
}
}
hs.functions.logout = function() {
hs.auth.password = "";
hs.auth.glob_key1 = "";
hs.auth.glob_key2 = "";
// hs.functions.make_request({
// "session" : _item.session,
// "cmd" : "logout"
// });
window.location.href = (window.location.href.replace(window.location.hash,"") + "?logout=1");
}
hs.functions.async.getfont = function( oarg ) {
hs.gui.fonts = {
0 : {}
};
$.each(oarg.json.HS.FONTS.FONT,
function(i,item) {
hs.gui.fonts[item._id] = {
'font-family' : item._name,
'font-size' : item._size + "pt",
'font-weight' : item._bold == 1 ? "bold":"normal"
};
}
);
hs.gui.systemfonts = {}
$.each(oarg.json.HS.SYSFONTS.FONT,
function(i,item) {
hs.gui.systemfonts[item._key] = {
'font-family' : item._name,
'font-size' : item._size + "pt",
'font-weight' : item._bold == 1 ? "bold":"normal",
'color' : hs.functions.get_hexcolor(item._color)
};
}
);
hs.functions.storage("set","fonts",hs.gui.fonts);
hs.functions.storage("set","systemfonts",hs.gui.systemfonts);
};
hs.functions.async.getattr = function( oarg ) {
$.each(oarg.json.HS.PARAS.P,
function(i,item) {
// parse Integer if possible
hs.gui.attr[item._key.toLowerCase()] = isNaN(item._val*1) ? item._val:item._val*1;
}
);
hs.gui.attr.initial_visu_height = (
hs.gui.attr.ltitleh +
(hs.gui.attr.llinec * hs.gui.attr.llineh) +
hs.gui.attr.lnavh +
(hs.gui.attr.hasborder == 0 ? 0:
hs.gui.attr.lsep1h + hs.gui.attr.lsep2h + hs.gui.attr.lsep3h + hs.gui.attr.lsep4h
)
);
hs.gui.attr.initial_visu_width = (
(6 * hs.gui.attr.lnavw) +
(hs.gui.attr.hasborder < 2 ? 0:
hs.gui.attr.lbleftw + hs.gui.attr.lbrightw
)
);
hs.functions.storage("set","attributes",hs.gui.attr);
};
hs.functions.login_dialog = function( oarg ) {
if( oarg ) {
oarg.session.connection_status = "login";
var errortype = oarg.error == "auth_error" ? "Benutzer falsch" : "Passwort falsch";
}
if (hs.gui.designs_html != null) {
return hs.functions.login_form(errortype)
}
$.ajax({
"url" : "/hs",
"contentType" : "application/x-www-form-urlencoded;charset=ISO-8859-1",
"dataType" : "html",
"complete" : function(xhttpobj) {
hs.functions.async.parse_designs(xhttpobj,errortype);
}
});
}
hs.functions.async.parse_designs = function(xhttpobj,errortype) {
try {
var _result = new RegExp(/.*(.*?name="cl".*?)<\/td>/).exec(xhttpobj.responseText);
hs.gui.designs_html = _result[1];
} catch (e) {
debug(0,"Error parsing Designs from /hs",xhttpobj);
hs.gui.designs_html = " ";
}
hs.functions.login_form(errortype)
}
hs.functions.login_form = function(errortype) {
var _form_html = "";
_form_html += "";
var _form_div = $('
').html(_form_html);
_form_div.modal({
"modal" : true,
"escClose" : false,
"autoPosition" : true,
"onShow" : function (dialog) {
hs.gui.modal_popup = this;
$('#login_form > select[name="cl"]').attr('tabindex', 3);
$('#login_form > select[name="cl"]').css("width", "100%");
if (hs.auth.gui_design.length > 0 && hs.gui.designs_html.match(hs.auth.gui_design)) {
$('#login_form > select[name="cl"]').val(hs.auth.gui_design);
} else {
$('#login_form > select[name="cl"]').val(
$('#login_form > select[name="cl"] > option:first').val()
);
}
//if (hs.auth.username.length > 0) {
//$('#login_form > input[name="password"]').attr("type","text");
//}
$('#login_form > button',dialog.data[0]).click(function (e) {
e.preventDefault();
hs.auth.username = $('#login_form > input[name="username"]').val();
hs.auth.password = $('#login_form > input[name="password"]').val();
hs.auth.gui_design = $('#login_form > [name="cl"]').val();
debug(5,"CHECKED: ",$('#login_form input[name="remember"]').prop("checked"));
if ($('#login_form input[name="remember"]').prop("checked")) {
hs.functions.storage("set","rememberpass",true);
hs.functions.storage("set","username",hs.auth.username);
hs.functions.storage("set","password",hs.auth.password);
hs.functions.storage("set","gui_design",hs.auth.gui_design);
} else {
hs.functions.storage("set","rememberpass",false);
//hs.functions.storage("remove","username");
hs.functions.storage("remove","password");
}
new hs.functions.hs_session("VISU");
//$('#login_form',elements));
hs.gui.modal_popup.close();
});
}
});
}
hs.functions.has_functions = function(obj) {
for (var i in obj) {
if (typeof obj[i] == 'function') {
return true;
}
}
return false;
}
hs.functions.number2align = function(align) {
switch (parseInt(align)) {
case 1:
return "left"
case 2:
return "center"
case 3:
return "right"
};
return ""
}
hs.functions.get_hexcolor = function(numcolor) {
var _hex = "";
if (typeof numcolor == 'undefined') {
return;
}
if (numcolor*1 >= 0) {
_hex = "#" + ("000000" + parseInt(numcolor).toString(16).toUpperCase()).substr(-6);
//debug(5,"get_hexcolor: " + numcolor + " = " + _hex);
} else {
_hex = "transparent";
}
return _hex;
}
hs.functions.get_rgba_color = function(hex,alpha) {
alpha = alpha || 1;
var _res = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return _res ? "rgba(" + parseInt(_res[1],16) + "," + parseInt(_res[2],16) + "," + parseInt(_res[3],16) + "," + alpha + ")" : "rgba(0,0,0,0)";
}
hs.functions.string_padding = function(str, len, pad, prefix) {
str || (str = "")
typeof str == "string" || (str = str.toString());
len || (len = 0);
pad || (pad = " ");
len += 1;
if (len >= str.length) {
if(prefix) {
return Array(len - str.length).join(pad) + str;
} else {
return str + Array(len - str.length).join(pad);
}
}
return str;
};
hs.functions.string_cut_after = function(str,pattern) {
var _idx = str.indexOf(pattern);
var _str = str
if (_idx != -1) {
_str = str.substring(0,_idx);
}
return _str;
}
hs.functions.get_query_parameter = function(item) {
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue ? svalue[1] : svalue;
}
hs.functions.get_hash_parameter = function(item) {
var svalue = location.hash.match(new RegExp("[#\&]" + item + "=([^\&]*)(\&?|$)","i"));
return svalue ? svalue[1] : svalue;
}
hs.functions.get_style = function(css_selector) {
var _regex = new RegExp(css_selector);
var _ret;
var _rules = [].map.call(document.styleSheets, function(item) {
return [].slice.call(item.cssRules);
}).reduce(function(a, b) {
return b.concat(a);
})
$.each(_rules,function(index,value) {
if(_regex.exec(value.selectorText || "")) {
_ret = value
return false;
}
});
return _ret ? _ret.style : {};
}
jQuery.fn.reverse = [].reverse;
jQuery.fn.center = function (parent, dir) {
parent || (parent = this.parent());
parent = parent instanceof jQuery ? parent : $(parent);
var _elem = this instanceof jQuery ? this : $(this);
debug(5,"center " + parent.width()+"/" +parent.height()+ "/" + this.width() + "/" +this.height());
if(parent.width() == null || parent.height() == null) {
_elem.in_dom(function() {
_elem.center();
},{once:true});
}
this.css("position",this.css("position") == "relative" ? "relative" : "absolute");
if(dir != "left") {
this.css("top",parent.height() < this.height() ? 0 : parent.height()/2 - this.height()/2);
}
if(dir != "top") {
this.css("left",parent.width() < this.width() ? 0 : parent.width()/2 - this.width()/2);
}
}
jQuery.fn.fitsize = function () {
var _elem = $(this);
if(!_elem.is(":visible")) {
return;
}
var _clone = _elem.data('fitsize-clone');
if(!_clone) {
_clone = $(" ", {
css : {
"visbility" : "hidden",
"font-size" : _elem.css('font-size'),
"font-family" : _elem.css('font-family'),
"font-style" : _elem.css('font-style'),
"font-weight" : _elem.css('font-weight'),
"font-variant" : _elem.css('font-variant')
}
});
_elem.data('fitsize-clone', _clone);
}
_clone.appendTo("body");
var _txt = _elem.prop("tagName") == "INPUT" ? _elem.val() : _elem.text();
_clone.html(_txt.replace(/\s/g," "));
var _width = _elem.innerWidth() * 0.9;
var _ratio = _width / (_clone.width() || 1);
var _fontsize = parseInt(_clone.css("font-size"),10);
if(_ratio < 1) {
_fontsize = Math.floor(_fontsize * _ratio);
debug(5,"font_change: " + _fontsize + "/" + _ratio + " " + _clone.width() + "/" + _width,_elem);
}
_clone.detach();
_elem.css("font-size",_fontsize);
}
jQuery.fn.in_dom = function(callback, options) {
var _elements = this;
var _options = $.extend({
"root" : document.body,
"once" : true
},options);
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var _observer = new MutationObserver(function(mutations) {
$.each(mutations,function(index,mutation) {
if(!mutation.addedNodes) {
return;
}
$.each(mutation.addedNodes,function(index,node) {
$.each(_elements,function(index,element) {
if(element === node || $.contains(node,element)) {
callback.apply(element);
if(_options.once) {
_elements.splice($.inArray(element,_elements),1);
}
}
});
});
});
if(!_elements.length > 0) {
_observer.disconnect();
}
});
_observer.observe(_options.root,{
childList: true,
subtree :true
});
};
hs.functions.set_viewport = function() {
return;
debug(5,"Set Viewport",hs.gui.attr);
$("#VISUCONTAINER").css({
"display" : "block",
"position" : "absolute",
"width" : hs.gui.attr.visu_width,
"height" : hs.gui.attr.visu_height
}).center(window);
//return true;
var _orientation = hs.functions.get_orientation();
var _visual_height = _orientation == "landscape" ? screen.width : screen.height;
var _visual_width = _orientation == "landscape" ? screen.height : screen.width;
var _scaleto_width = Math.floor ( _visual_width / hs.gui.attr.visu_width * 100) / 100;
var _scaleto_height = Math.floor ( _visual_height / hs.gui.attr.visu_height * 100) / 100;
var _scale_min = Math.min( _scaleto_width, _scaleto_height);
var _scale_max = Math.max( _scaleto_width, _scaleto_height, 1.0);
var _viewport_meta =
"viewport-fit=cover," +
"width=" + hs.gui.attr.visu_width +
(_scale_min > 1 ? "" : ",initial-scale=" + _scale_min) +
",minimum-scale=" + _scale_min +
",maximum-scale=" + _scale_max +
",user-scalable=" + (_scale_min != _scale_max ? "yes":"no");
$("#meta_viewport").attr("content", _viewport_meta );
debug(5,"Viewport: " + _viewport_meta + " orientation: " + _orientation + " vheight: " + _visual_height + " vwidth: " + _visual_width);
hs.gui.device.scale = Math.max(hs.gui.attr.visu_width,hs.gui.attr.visu_height) / Math.max(hs.gui.device.width,hs.gui.device.height);
if(hs.options.autoscale) {
var _container_scale_width = $(window).width()/hs.gui.attr.visu_width;
var _container_scale_height = $(window).height()/hs.gui.attr.visu_height;
hs.gui.container_scale = Math.min(_container_scale_width,_container_scale_height)
if(!hs.options.scaledown) {
hs.gui.container_scale = Math.max(hs.gui.container_scale,1.0);
}
if(hs.gui.container_scale < 1) {
$("#VISUCONTAINER").css({
"width" : "",
"height" : ""
});
}
$("#VISUCONTAINER").css("transform","scale(" + hs.gui.container_scale + "," + hs.gui.container_scale + ")");
} else {
hs.gui.container_scale = 1;
$("#VISUCONTAINER").css("transform","");
}
}
hs.functions.get_orientation = function () {
if (typeof orientation != "undefined") {
return ( orientation % 180 ? "landscape":"portrait");
} else {
return window.innerWidth > window.innerHeight ? "landscape" : "portrait";
}
}
hs.functions.stringify = function (obj) {
return JSON.stringify(obj, function (key, value) {
if (value instanceof Function || typeof value == 'function') {
// use strict wird im chrome nicht übernommen daher sind die Funktionen unterschiedlich
return value.toString().replace("\n\"use strict\";\n","");
}
return value;
});
}
hs.functions.date_from_hs = function (dstr) {
var _match = dstr.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/);
if (_match == null) {
return $.now();
}
if (hs.options.timezone === null) {
// Homeserver und Client gleiche Zeitzone
return new Date(
_match[1], // Year
_match[2] -1, // Month
_match[3], // Day
_match[4], // Hour
_match[5], // Minute
_match[6] // Seconds
);
} else {
return new Date(Date.UTC(
_match[1], // Year
_match[2] -1, // Month
_match[3], // Day
_match[4], // Hour
_match[5], // Minute
_match[6] // Seconds
)).diffhour((hs.options.timezone*-1));
}
}
Date.prototype.diffhour = function (hours) {
this.setHours(this.getHours() + hours);
return this;
}
Date.prototype.getWeekNumber = function() {
var d = new Date(+this);
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
}
Date.prototype.getDayNumber = function() {
var d = new Date(+this);
d.setHours(0,0,0);
return Math.floor((d - new Date(d.getFullYear(),0,1))/8.64e7)+1;
}
hs.functions.get_date_object = function ( date ) {
date || (date = (new Date()));
if(typeof date == 'string') {
date = new Date(date);
}
if(date == "Invalid Date") {
return;
}
var _date = {
"YYYY" : date.getFullYear(),
"M" : date.getMonth() + 1,
"d" : date.getDate(),
"H" : date.getHours(),
"m" : date.getMinutes(),
"i" : (function(hour) { return hour % 12 == 0 ? 12 : hour % 12 })(date.getHours()),
"s" : date.getSeconds(),
"f" : date.getMilliseconds(),
"w" : date.getDay(),
"U" : date.getWeekNumber(),
"j" : date.getDayNumber()
};
$.extend(_date,{
"YY" : _date.YYYY.toString().substring(2),
"MM" : hs.functions.string_padding(_date.M,2,"0",true),
"MMM" : hs.language.monthnames[_date.M].substring(0,3),
"MMMM" : hs.language.monthnames[_date.M],
"dd" : hs.functions.string_padding(_date.d,2,"0",true),
"ddd" : hs.language.weekdaynames[_date.w ].substring(0,2),
"dddd" : hs.language.weekdaynames[_date.w ],
"HH" : hs.functions.string_padding(_date.H,2,"0",true),
"ii" : hs.functions.string_padding(_date.i,2,"0",true),
"p" : _date.H > 12 ? "P" : "A",
"pp" : _date.H > 12 ? "PM" : "AM",
"mm" : hs.functions.string_padding(_date.m,2,"0",true),
"mz" : hs.functions.string_padding((_date.m - (_date.m % 10)),2,"0",true),
"ss" : hs.functions.string_padding(_date.s,2,"0",true),
"sz" : hs.functions.string_padding((_date.s - (_date.s % 10)),2,"0",true),
"ff" : hs.functions.string_padding(_date.f,2,"0",true).substring(0,2),
"fff" : hs.functions.string_padding(_date.f,3,"0",true).substring(0,3),
"f" : _date.f.toString().substring(0,1),
});
return _date;
}
hs.functions.format_date = function ( format, date ) {
var _date = hs.functions.get_date_object(date);
return format.replace(/%(\w+)\%/g,function(match,capture) {
return _date[capture] || match;
});
}
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
hs.functions.temp2rgb = function (low, high, temp) {
var _tempdiff = high-low;
var _rate = {
"cold" : _tempdiff *0.25,
"mid" : _tempdiff *0.5,
"warm" : _tempdiff *0.75
};
if (temp <= _rate.cold) {
var _cold = hs.options.temp_colors.one;
var _warm = hs.options.temp_colors.two;
high = _rate.cold;
} else if (temp >= _rate.cold && temp <= _rate.mid) {
var _cold = hs.options.temp_colors.two;
var _warm = hs.options.temp_colors.three;
low = _rate.cold;
high = _rate.mid;
} else if (temp >= _rate.mid && temp <= _rate.warm) {
var _cold = hs.options.temp_colors.three;
var _warm = hs.options.temp_colors.four;
low = _rate.mid;
high = _rate.warm;
} else if (temp >= _rate.warm) {
var _cold = hs.options.temp_colors.four;
var _warm = hs.options.temp_colors.five;
low = _rate.warm;
}
if(temp < low) {
temp = low;
}
if(temp > high) {
temp = high;
}
var _start = temp - low;
_tempdiff = high-low;
var _red = ((((_warm[0]-_cold[0])/_tempdiff)*_start)+_cold[0]).toFixed();
var _green = ((((_warm[1]-_cold[1])/_tempdiff)*_start)+_cold[1]).toFixed();
var _blue = ((((_warm[2]-_cold[2])/_tempdiff)*_start)+_cold[2]).toFixed();
return "rgb(" + _red + "," + _green + "," + _blue + ")";
}
hs.functions.post_loading = function () {
}
hs.functions.ajaxload_css = function (id, url, callback) {
debug(3,"[start] ajaxload css " + id);
var _content = hs.functions.storage("get","CACHE_FILE_" + id) || "";
var _element = $("", {
"id" : id,
"type" : "text/css"
}).text(_content);
$("head:first").append(_element);
$.ajax({
url: url,
cache: false, // url already tagged with date
async: true,
dataType: 'text',
context: _element
}).success(function(data,status,xhr) {
debug(3,"[start] loaded as [style] "+ id);
if (data != this.text()) {
this.text(data)
hs.functions.storage("set","CACHE_FILE_" + id,data);
}
callback(id,false);
}).error(function(xhr,status) {
debug(1,"[start] failed loading as [style] " + id + " / " + status);
callback(id,true);
});
}
hs.functions.element_loader = function ( urls, cache, callback ) {
var _failure = false;
var _finish = function(id, failure) {
var _index = _queue.indexOf(id);
if(_index < 0) {
return;
}
if(failure) {
_failure = true;
}
_queue.splice(_index,1);
if(_queue.length == 0) {
debug(3,"element_loader callback is called");
clearTimeout(_timer);
if(typeof callback == "function") {
callback(_failure);
}
}
debug(5,"[start] element_loader finished loading " + id + " from (" + _queue.length + ")");
};
var _timer = setTimeout(function() {
debug(1,"[start] Error element_loader: failed loading " + _queue.join(", "));
},3000);
var _getid = function(filename) {
return filename.replace(/http[s]?:\/\/.*?\//,"").replace(/\./g,"_").replace(/\//g,"_");
}
urls = typeof urls == 'string' ? [urls] : urls.concat();
var _base = $("base").attr("href") || "";
var _cache = typeof cache == "undefined" ? true : cache;
var _queue = [];
var _i,_filename, _id, _type, _element, _old_elem;
for (_i=0; _i < urls.length; _i++) {
_filename = _base + urls[_i];
_id = _getid(_filename);
_queue.push(_id);
}
for (_i=0; _i < urls.length; _i++) {
_filename = _base + urls[_i];
debug(3,"[start] element_loader loading " + _filename);
_id = _getid(_filename);
_type = _filename.toLowerCase().split(".");
_type = _type[_type.length -1];
switch(_type) {
case "js":
$.ajax({
url: _filename,
cache: _cache,
async: true,
dataType: 'script',
context: _id
})
.success(function(data,status,xhr) {
debug(5,"[start] loaded [getscript] " + this);
_finish(this,false);
})
.error(function(xhr,status) {
debug(1,"[start] failed loading [getscript] " + this + " / " + status);
_finish(this,true);
}
);
break;
case "css":
_old_elem = $("#" + _id).remove();
if (!_cache) {
_filename += "?_" + $.now();
}
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
hs.functions.ajaxload_css(_id,_filename,_finish);
continue;
}
debug(3,"[start] add [link] " + _filename);
var _element = $(" ", {
"id" : _id,
"rel" : "stylesheet",
"type" : "text/css",
"href" : _filename
}).on("load",function(event) {
var _id = event.target.id;
var _filename = event.target.href;
try { // Firefox issues Security Error
if(event.target.sheet && event.target.sheet.cssRules && event.target.sheet.cssRules.length == 0) {
debug(1,"[start] invalid length [link] " + _id);
hs.functions.ajaxload_css(_id,_filename,_finish);
$(event.target).remove();
return;
}
} catch (e) {};
debug(3,"[start] loaded [link] "+ _id,event.target);
_finish(_id,false);
}).on("error",function(event) {
var _id = event.target.id;
var _filename = event.target.href;
debug(2,"[start] failed loading [link] " + _id + " / trying with ajax",event);
$(event.target).remove();
hs.functions.ajaxload_css(_id,_filename,_finish);
});
if(!$.contains(document, _element[0])) {
$("head:first").append(_element);
}
}
}
}
hs.functions.storage = function ( command, name, value ) {
if(window.localStorage === undefined) {
// no support
debug(1,"localStorage not supported");
return;
}
switch(command) {
case "get":
var _json = window.localStorage.getItem(name);
try {
_json = JSON.parse(_json);
} catch(e) {
// convert localstorage to json
hs.functions.storage("set",name,_json);
}
return _json;
case "set":
if(value == undefined || value.toString().length == 0) {
window.localStorage.removeItem(name);
} else {
window.localStorage.setItem(name,JSON.stringify(value));
}
return;
case "remove":
window.localStorage.removeItem(name);
return;
case "clear":
window.localStorage.clear();
return;
};
}
hs.functions.fix_base = function() {
var _base = document.getElementById('htmlbase');
if (!_base) {
return
}
var _base_url = _base.href;
if (_base_url != location.href) {
var _elements = document.getElementsByTagName("link");
for ( var i = 0; i < _elements.length; i ++ ) {
// FIX href
_elements[i].setAttribute('href', _elements[i].href);
}
_elements = document.getElementsByName("msapplication-TileImage");
_elements[0].setAttribute('content', _base_url + _elements[0].content);
}
}
$(window).on('orientationchange', function(event) {
hs.functions.set_viewport();
//hs.functions.get_orientation();
});
$(window).resize(function() {
hs.functions.set_viewport();
});
$(document).on("keydown", function(e) {
if (e.ctrlKey && String.fromCharCode(e.which) === 'X') {
xxAPI.functions.XXAPICONFIG( null );
return false;
}
});
hs.functions.checkonline = function(e) {
debug(3,"xxAPI is " + e.type + "/" + (navigator.onLine ? "online" : "offline"));
var _online = e.type == "online";
hs.gui.hidden = !_online;
if (_online) {
hs.functions.popup_overlay(false,false);
hs.functions.reconnect("Online");
} else {
hs.functions.popup_overlay(true,true);
}
};
window.addEventListener("online",hs.functions.checkonline,true);
window.addEventListener("offline",hs.functions.checkonline,true);
$(document).on("visibilitychange", function() {
if(document.hidden) {
debug(3,"xxAPI is hidden, delayed refresh");
} else {
debug(3,"xxAPI is visible, normal refresh");
}
hs.gui.hidden = document.hidden;
});
$(document).on("touchmove", function(e) {
var _visual_width = hs.functions.get_orientation() == "landscape" ? screen.height : screen.width;
if( _visual_width >= document.documentElement.clientWidth) {
e.preventDefault();
}
});
// Fix iOS alert when using FastClick
var broken_alert = window.alert;
window.alert = function(msg) {
setTimeout(function() { broken_alert(msg); },0);
}
hs.functions.start_client = function() {
var _x2js = new X2JS();
$.xml2json = _x2js.xml2json;
FastClick.attach(document.body);
if(hs.functions.get_query_parameter("logout")) {
hs.functions.storage("remove","password");
window.location.replace(location.protocol + '//' + location.host + location.pathname);
}
hs.auth.username = hs.functions.storage("get","username") || hs.functions.get_hash_parameter("user");
hs.auth.password = hs.functions.storage("get","password") || hs.functions.get_hash_parameter("pass");
hs.auth.gui_design = hs.functions.storage("get","gui_design") || hs.functions.get_hash_parameter("design") || "";
hs.auth.gui_refresh = hs.functions.get_hash_parameter('refresh') || hs.auth.gui_refresh ;
xxAPI.start_page = hs.functions.get_hash_parameter("startpage");
hs.gui.hashes = hs.functions.storage("get","hashes") || hs.gui.hashes;
hs.gui.fonts = hs.functions.storage("get","fonts") || hs.gui.fonts;
hs.gui.systemfonts = hs.functions.storage("get","systemfonts") || hs.gui.systemfonts;
hs.gui.attr = hs.functions.storage("get","attributes") || hs.gui.attr;
if (hs.auth.username == null || hs.auth.password == null || hs.auth.gui_design == null) {
hs.functions.login_dialog()
} else {
debug(3,"[start] Main Session")
new hs.functions.hs_session("VISU");
if (hs.showstartuplog > 0 && hs.debug_cache.length > 0) {
setTimeout(function(){
alert(hs.debug_cache.join("\n"));
}
,hs.showstartuplog * 1000);
}
}
}
hs.debuglevel = hs.functions.get_hash_parameter("debug") || hs.functions.storage("get","debuglevel") || 0;
hs.showstartuplog = hs.functions.get_hash_parameter("showdebug") || 0;
$("html").on("touchmove",function(jQevent) {
var event = jQevent.originalEvent;
if (event && event.touches && event.touches.length != 2) {
event.preventDefault();
}
});
hs.functions.load_libraries = function() {
debug(3,"[start] load libraries");
if(hs.libraries_loaded) {
return;
}
hs.functions.element_loader([
"libs/fastclick.js", // https://github.com/ftlabs/fastclick
"libs/xml2json.min.js", // https://github.com/abdmob/x2js
"libs/jquery.md5.js", // https://github.com/placemarker/jQuery-MD5
"libs/jquery.simplemodal.js", // http://www.ericmmartin.com/projects/simplemodal
"libs/position-calculator.min.js", // https://github.com/tlindig/position-calculator
"libs/iscroll.js", // https://github.com/cubiq/iscroll
"libs/jquery.lazyload.min.js", // https://github.com/tuupola/jquery_lazyload
"libs/jquery.nouislider.min.css",
"libs/jquery.nouislider.pips.min.css",
"libs/jquery.nouislider.all.min.js", // https://github.com/leongersen/noUiSlider
"libs/jquery.knob.min.js", // https://github.com/aterrien/jQuery-Knob
"libs/xxapi.css",
"libs/theme.css"
],true,
function(fail) {
if(fail) {
if(confirm("failed to load all required javascript libraries\n\nReload?")) {
window.location.reload();
}
}
debug(3,"[start] fix base")
hs.libraries_loaded = true;
hs.functions.fix_base()
debug(3,"[start] fix base done")
$("base").attr("href","");
hs.functions.element_loader([
"custom.css",
"custom.js"
],hs.has_appcache,
function(fail) {
debug(3,"[start] hsclient")
hs.functions.start_client();
}
);
}
);
}
hs.functions.progressbar = function(element,percent) {
debug(1,"progressbar " + percent);
var _width = percent * element.width() / 100;
element.find('div').animate({ width: _width }, 0).html(percent + "% ");
}
debug(2,"[start] xxAPI² load");
if(window.applicationCache !== undefined) {
window.applicationCache.addEventListener('progress', function (e) {
if (Number(hs.cached_files_count)) {
$("#PROGRESSINFO").html(hs.cached_files[hs.cached_load_count - 1]);
var _percent = parseInt(hs.cached_load_count / hs.cached_files_count * 100);
hs.functions.progressbar($("#PROGRESSBAR"), _percent);
debug(5,"APPCACHE: download " + hs.cached_files[hs.cached_load_count - 1] + " - "+ hs.cached_load_count + "/" + hs.cached_files_count + " :: " + _percent);
}
hs.cached_load_count++;
});
}
$(document).ready(function() {
hs.has_appcache = $("html[manifest$=appcache]").length > 0;
if (hs.has_appcache && window.applicationCache !== undefined ) {
debug(3,"[start] HTML5 Manifest active");
$("html").css({
"width" : "100vh",
"height" : "100vh",
"background-color" : "#000000",
"color" : "#FFFFFF"
});
window.applicationCache.addEventListener('updateready', function (e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
window.location.reload();
}
});
window.applicationCache.addEventListener('noupdate', function (e) {
$("#POPUP").html("");
hs.functions.load_libraries();
});
window.applicationCache.addEventListener('cached', function (e) {
$("#POPUP").html("");
hs.functions.load_libraries();
});
window.applicationCache.addEventListener('checking', function (e) {
if(navigator.onLine) {
$("#POPUP").html("Check");
} else {
hs.functions.load_libraries();
}
});
window.applicationCache.addEventListener('obsolete', function (e) {
debug(1,"Appcache: Removed");
$("#POPUP").html("");
hs.functions.load_libraries();
});
window.applicationCache.addEventListener('error', function (e) {
debug(1,"Appcache: Error",e);
$("#POPUP").html("");
if(!navigator.onLine) {
hs.functions.load_libraries();
return false;
}
if(confirm("Appcache error: start anyway? " + window.applicationCache.status.toString())) {
hs.functions.load_libraries();
}
});
window.applicationCache.addEventListener('downloading', function (e) {
$.ajax({
url : $("html").attr("manifest"),
dataType : "text",
cache : false,
success : function( content ) {
hs.cached_files = content.match(/^(?:[/]|http[s]?:\/\/)?\w+[/.?]+.*/gm);
hs.cached_files_count = hs.cached_files.length;
}
});
$("#POPUP").html("
");
});
} else {
hs.functions.load_libraries();
}
});