﻿// Copyright (c) 2009 Xarka Software
// http://www.xarka.gr/   

function isDefined(variable) {
    return eval("(typeof(" + variable + ")!='undefined');");
}

function pageWidth(w) {
    w = w == undefined ? window : w;
    return w.innerWidth != null ? w.innerWidth
    : w.document.documentElement && w.document.documentElement.clientWidth
    ? w.document.documentElement.clientWidth : w.document.body != null ? w.document.body.clientWidth : null;
}
function pageHeight(w) {
    w = w == undefined ? window : w;
    return w.innerHeight != null ? w.innerHeight
    : w.document.documentElement && w.document.documentElement.clientHeight
    ? w.document.documentElement.clientHeight : w.document.body != null ? w.document.body.clientHeight : null;
}

function GetTopLeft(element) {
    elm = document.getElementById(element);
    var x, y = 0;
    x = elm.offsetLeft;
    y = elm.offsetTop;
    elm = elm.offsetParent;
    while (elm != null) {
        x = parseInt(x) + parseInt(elm.offsetLeft);
        y = parseInt(y) + parseInt(elm.offsetTop);
        elm = elm.offsetParent;
    }
    return { Top: y, Left: x };
}

function getFocusedGridId(grid) {
    i = grid.GetFocusedRowIndex();
    v = (i < 0) ? -1 : grid.keys[i - grid.visibleStartIndex];
    return v;
}

function gridFocusedCP(grid, cpletter) {
    var id = getFocusedGridId(grid);
    return (id != -1) ? eval('grid.cp' + cpletter + id) : null;
}

var debugCount = 0;
function debugBox(str) {
    str += "<br>" + ++debugCount;
    document.getElementById("ctl00_DebugBox").style.visibility = "visible";
    document.getElementById("ctl00_DebugBox").innerHTML = str;
}

var xPool = 0;
var xInCallback = false;
function DoCallback(controlname, text, timeout) {
    text = text.replace(/([\"\\])/g, '\\$1');
    var cmd = 'if (isDefined("' + controlname + '") && !' + controlname + '.InCallback()) { ' +
      controlname + '.PerformCallback' + '("' + text + '"); } xInCallback=false; ';
    var t = timeout ? timeout : xPool;
    xPool += 50; if (xPool > 200) xPool = 0;
    xInCallback = true;
    window.setTimeout(cmd, t);
}

function DynPlay(file) {
    if (file != "") {
        document.getElementById("dhtmlspan").innerHTML =
            "<embed src='/voice/" + file + "' hidden='true' autostart='true' loop='false'>";
        setTimeout('document.getElementById("dhtmlspan").innerHTML=""', 30000);
    }
}

function SmartParentFrame(frameId, minHeight) {
    if (minHeight == undefined) minHeight = 300;
    window.parent.document.getElementById(frameId).height = Math.max(pageHeight(), minHeight);
    setInterval('if (isDefined("' + frameId + '")) window.parent.document.getElementById("' + frameId + '").height=Math.max(pageHeight(),300)', 1000);
}

function ResizableFrame(frameId, padding) {
    setInterval('document.getElementById("' + frameId + '").height=pageHeight()-' + padding, 500);
    document.getElementsByTagName("html")[0].style.overflow = "hidden";
}

function scrollToEnd(element) {
    d = document.getElementById(element);
    if (d != null)
        d.scrollTop = d.scrollHeight;
}

function eventSrc(event) {
    return event.srcElement ? event.srcElement : event.target;
}
function eventSrcChecked(event) {
    return eventSrc(event).checked ? 1 : 0;
}

function DateString(addYear, addDay) {
    var myDays = ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"]
    var cTime = new Date();

    var cTimeStr = cTime.getDate() + "/" + (cTime.getMonth() + 1);
    if (addYear)
        cTimeStr += "/" + (cTime.getFullYear() - 2000);
    if (addDay)
        cTimeStr = myDays[cTime.getDay()] + " " + cTimeStr;
    return cTimeStr;
}

function TimeString(addSeconds) {
    var cTime = new Date();
    var cHours = cTime.getHours();
    var cMinutes = cTime.getMinutes();
    var cSeconds = cTime.getSeconds();
    cMinutes = (cMinutes < 10 ? "0" : "") + cMinutes;
    cSeconds = (cSeconds < 10 ? "0" : "") + cSeconds;

    var cTimeStr = cHours + ":" + cMinutes;
    if (addSeconds)
        cTimeStr = ":" + cSeconds;
    return cTimeStr;
}

function DefaultClock() {
    return DateString(false, true) + " " + TimeString(false);
}

function EncodeHtml(html) {
    encodedHtml = escape(html);
    encodedHtml = encodedHtml.replace(/\//g, "%2F");
    encodedHtml = encodedHtml.replace(/\?/g, "%3F");
    encodedHtml = encodedHtml.replace(/=/g, "%3D");
    encodedHtml = encodedHtml.replace(/&/g, "%26");
    encodedHtml = encodedHtml.replace(/@/g, "%40");
    encodedHtml = encodedHtml.replace(/\+/g, "%2B");
    return encodedHtml;
}

function smartGridLink(grid, id, cpletter, basename, text) {
    var h = document.getElementById('h' + basename);
    if (h == null) return;
    var u = document.getElementById('u' + basename);
    if (id < 0 || u == null)
        h.style.display = 'none';
    else {
        var link = eval(grid + '.cp' + cpletter + id);
        h.style.display = (link != "") ? "block" : "none";
        u.href = link;
        u.innerHTML = text;
    }
}

function TopWindow() {
    var w = window;
    while (w != w.parent) { w = w.parent; }
    return w;
}

function WindowLevel() {
    var w = window;
    var level = 0;
    while (w != w.parent) {
        w = w.parent;
        level++;
    }
    return level;
}

function EvalBack(data) {
    var url = window.document.URL;
    url += (url.indexOf('?') < 0) ? "?" : "&";
    jx.load(url + data, function(data) {
        if (data != null && data.length > 3)
            try { eval(data); } catch (ex) { }
    }, 'text');
}

function GetIntParam(name) {
    var re = new RegExp('(&|\\?)' + name + '=(\\d+)');
    var str = window.location.href;
    if (re.test(str))
        return RegExp.$2;
    else
        return undefined;
}

// Popup /////////////////

var PopupCloseUp = new Array();
var LastWindow;

function XPopup() {
    var p = null;
    if (window.parent != null && window.parent.parent != null)
        p = window.parent.parent.ControlPopup;
    if (p == null && window.parent != null)
        p = window.parent.ControlPopup;
    if (p == null)
        p = IFramePopupContol;
    return p;
}

function XPopupWin(WinId) {
    return XPopup().GetWindow(WinId)
}

function PopupSet(WinId, Header, OnClose, Width, Height, ElementId) {
    var win = XPopupWin(WinId);
    win.SetHeaderText(Header);
    TopWindow().PopupCloseUp[WinId] = OnClose;

    if (Width == undefined)
        Width = pageWidth(TopWindow()) - 30 - WindowLevel() * 15;
    if (Height == undefined)
        Height = pageHeight(TopWindow()) - 20 - WindowLevel() * 10;

    var left, top;
    if (ElementId == undefined) {
        left = parseInt((pageWidth(TopWindow()) - Width) / 2);
        top = parseInt((pageHeight(TopWindow()) - Height) / 2);
    } else {
        var pp = GetTopLeft(ElementId);
        left = pp.Left + 80;
        top = pp.Top - parseInt(Height / 2);
    }
    XPopup().ShowWindowAtPos(win, left, top);
    XPopup().SetWindowSize(win, Width, Height);
    return { W: Width, H: Height };
}

function PopupIFrame(WinId, Header, URL, OnClose, Width, Height, ElementId, IgnoreRandom) {
    TopWindow().LastWindow = window;
    var size = PopupSet(WinId, Header, OnClose, Width, Height, ElementId);
    if (IgnoreRandom != 1) {
        URL += URL.indexOf("?") < 0 ? "?" : "&";
        URL += 'r=' + Math.random() + '&winid=' + WinId + '&winheight=' + size.H + '&winwidth=' + size.W;
    }
    XPopup().SetWindowContentUrl(XPopupWin(WinId), URL);
}

function PopupCallback(WinId, Header, URL, OnClose, Width, Height, ElementId) {
    PopupSet(WinId, Header, OnClose, Width, Height, ElementId);
    jx.load(URL, function(data) {
        if (data != null && data.length > 3)
            try { XPopup().SetWindowContentHtml(XPopupWin(WinId), data); } catch (ex) { }
    }, 'text');
}

function PopupClose(id) {
    if (id == undefined) {
        XPopup().HideWindow(XPopupWin(0));
        XPopup().HideWindow(XPopupWin(1));
        XPopup().HideWindow(XPopupWin(2));
        XPopup().HideWindow(XPopupWin(3));
        XPopup().HideWindow(XPopupWin(4));
    } else {
        XPopup().HideWindow(XPopupWin(id));
    }
}

function PopupCloseSelf() {
    var re = new RegExp('&winid=(\\d+)');
    var str = window.location.href;
    if (re.test(str)) {
        var winid = RegExp.$1;
        PopupClose(winid);
    }
    else
        PopupClose();
}

function PopupCloseSelfEvent(s, e) {
    PopupCloseSelf();
}

function PopupClientCloseUp(s, e) {
    var win = e.window;
    var onclose = TopWindow().PopupCloseUp[win.index];
    if (onclose != null && onclose != '')
        onclose(s, e);
}

// Hints /////////////////

function getposOffset(what, offsettype) {
    var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
    var parentEl = what.offsetParent;
    while (parentEl != null) {
        totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
        parentEl = parentEl.offsetParent;
    }
    return totaloffset;
}

function iecompattest() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge) {
    var ie = document.all
    var vertical_offset = "0" //horizontal offset of hint box from anchor link
    var horizontal_offset = "9px" //horizontal offset of hint box from anchor link
    var edgeoffset = (whichedge == "rightedge") ? parseInt(horizontal_offset) * -1 : parseInt(vertical_offset) * -1
    if (whichedge == "rightedge") {
        var windowedge = ie && !window.opera ? iecompattest().scrollLeft + iecompattest().clientWidth - 30 : window.pageXOffset + window.innerWidth - 40
        dropmenuobj.contentmeasure = dropmenuobj.offsetWidth
        if (windowedge - dropmenuobj.x < dropmenuobj.contentmeasure)
            edgeoffset = dropmenuobj.contentmeasure + obj.offsetWidth + parseInt(horizontal_offset)
    }
    else {
        var windowedge = ie && !window.opera ? iecompattest().scrollTop + iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18
        dropmenuobj.contentmeasure = dropmenuobj.offsetHeight
        if (windowedge - dropmenuobj.y < dropmenuobj.contentmeasure)
            edgeoffset = dropmenuobj.contentmeasure - obj.offsetHeight
    }
    return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth) {
    var ie = document.all
    var ns6 = document.getElementById && !document.all
    if ((ie || ns6) && document.getElementById("hintbox")) {
        dropmenuobj = document.getElementById("hintbox")
        dropmenuobj.innerHTML = menucontents
        dropmenuobj.style.left = dropmenuobj.style.top = -500
        if (tipwidth != undefined) {
            dropmenuobj.widthobj = dropmenuobj.style
            dropmenuobj.widthobj.width = tipwidth
        }
        dropmenuobj.x = getposOffset(obj, "left")
        dropmenuobj.y = getposOffset(obj, "top")
        dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + obj.offsetWidth + "px"
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + "px"
        dropmenuobj.style.visibility = "visible"
        obj.onmouseout = hidetip
    }
}

function hidetip(e) {
    dropmenuobj.style.visibility = "hidden"
    dropmenuobj.style.left = "-500px"
}

function createhintbox() {
    var divblock = document.createElement("div")
    divblock.setAttribute("id", "hintbox")
    document.body.appendChild(divblock)
}

if (window.addEventListener)
    window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
    window.attachEvent("onload", createhintbox)
else if (document.getElementById)
    window.onload = createhintbox


// Internal /////////////////

function ChatKeyHandler(s, e) {
    if (!isDefined('ChatGrid') || ChatGrid.InCallback()) return;

    if (e.htmlEvent.keyCode == 13) {
        var m = ChatTextBox.GetText('');
        DoCallback('ChatGrid', 'ADD/' + m);
        ChatTextBox.SetText('');
        e.htmlEvent.returnValue = false;
        try {
            e.htmlEvent.preventDefault();
            e.htmlEvent.stopPropagation();
        } catch (ex) { }
    }
}

