var Famark = Famark || {};

Famark.pageLoad = function () {

    Famark._divUploadHtml = 'Upload';
    Famark._divUploadingHtml = 'Uploading...';
    Famark._deletedMessage = 'deleted!';
    Famark._isWorkingPrefex = 'Uploading "';
    Famark._isWorkingSuffix = '" please wait...';
    Famark._largeFileErrorMessage = 'Too large file(s)!';

    var frmMain = document.getElementById('frmMain');
    if (frmMain == null)
        return;

    var divData = document.getElementById('divData');
    var btnDel = document.getElementById('btnDel');
    var btnSort = document.getElementById('btnSort');
    var btnRef = document.getElementById('btnRef');

    var inFile = document.getElementById('inFile');
    var fileWrapperContent = document.getElementById('fileWrapperContent');
    fileWrapperContent.innerHTML = Famark._divUploadHtml;

    Famark.formatIsoDates();

    var workFrame = document.getElementById('workFrame');
    Famark.addHandler(workFrame, 'load', function () {
        var frameDoc = workFrame.contentDocument || workFrame.contentWindow.document;
        var result = {};
        try {
            result = Famark.parseJSON(frameDoc.body.innerHTML);
        } catch (e) {
            result.ErrorMessage = (frameDoc.body.innerHTML.indexOf('404') > 0) ? Famark._largeFileErrorMessage
                : (e.message.toLowerCase().indexOf('unexpected token <') > -1 ? Famark.htmlToText(frameDoc.body.innerHTML) : e.message);
        }
        if (result.ErrorMessage == null || result.ErrorMessage == '') {
            window.location.replace('List.ashx?entity=' + divData.getAttribute('data-entity') +
                '&rid=' + divData.getAttribute('data-rid') + '&filesOrderBy=' + divData.getAttribute('data-filesOrderBy'));
        } else {
            alert(result.ErrorMessage);
            fileWrapperContent.innerHTML = Famark._divUploadHtml;
        }
        Famark._preventUnloadMessage = null;
        if (window.parent.Famark != null && window.parent.Famark.setWorking != null)
            window.parent.Famark.setWorking(false, Famark._preventUnloadMessage);
    });

    inFile.onchange = function () {
        if (inFile.value == '')
            return;

        inFile.style.visibility = 'hidden';
        fileWrapperContent.innerHTML = Famark._divUploadingHtml;
        Famark._preventUnloadMessage = Famark._isWorkingPrefex + inFile.value.substring(inFile.value.lastIndexOf('\\') + 1) + Famark._isWorkingSuffix;
        if (window.parent.Famark != null && window.parent.Famark.setWorking != null)
            window.parent.Famark.setWorking(true, Famark._preventUnloadMessage);

        Famark.removeHiddenFields(frmMain);

        Famark.appendHiddenFields(frmMain, 'entity', divData.getAttribute('data-entity'));
        Famark.appendHiddenFields(frmMain, 'work', 'UploadAttachment');
        Famark.appendHiddenFields(frmMain, 'rid', divData.getAttribute('data-rid'));
        frmMain.action = 'Work.ashx';
        frmMain.target = 'workFrame';
        frmMain.submit();
    };

    inFile.onfocus = function () {
        fileWrapperContent.className = 'fileWrapperFocus';
    };

    inFile.onblur = function () {
        fileWrapperContent.className = '';
    };

    divData.onclick = function (e) {
        e = e || window.event;
        var el = e.target || e.srcElement;

        while (el.nodeName != 'DIV' && el.nodeName != 'BODY')
            el = el.parentNode;

        if (el.nodeName != 'DIV')
            return;

        var file = el.getAttribute('data-file');

        if (file == null || file == '')
            return;

        var selId = divData.getAttribute('data-selected');

        if (e.ctrlKey == 1 && selId != null && selId != '') {
            var selPos = selId.indexOf(file);
            if (selPos > -1) {
                var nextPos = selId.indexOf('|', selPos + 1);
                if (nextPos < 0)
                    selId = selId.substring(0, selPos - 1);
                else
                    selId = selId.substring(0, selPos) + selId.substring(nextPos + 1);

                el.className = el.lastClassName;
                divData.setAttribute('data-selected', selId);
                return;
            }

            selId = selId + '|' + file;
        } else if (e.shiftKey == 1 && selId != null && selId != '') {
            var sib = document.body.previousElementSibling ? 'previousElementSibling' : 'previousSibling';
            var rI;
            function getRowIndex(row) {
                rI = 0;
                while ((row = row[sib]) != null)
                    rI++;
                return rI;
            }

            var rows = el.parentNode.childNodes;
            var lastPos = selId.lastIndexOf('|');
            var lastFileName = selId.substring(lastPos + 1);
            var lastFileItem;
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].getAttribute('data-file') == lastFileName) {
                    lastFileItem = rows[i];
                    break;
                }
            }

            var items = Famark.getElementsByClassName('selected', 'div', divData);
            for (var i = 0; i < items.length; i++)
                items[i].className = items[i].lastClassName;

            if (lastFileItem) {
                selId = '';
                var lastRowIndex = getRowIndex(lastFileItem);
                var newRowIndex = getRowIndex(el);
                if (newRowIndex > lastRowIndex) {
                    for (rI = lastRowIndex; rI < newRowIndex; rI++) {
                        rows[rI].lastClassName = rows[rI].className;
                        rows[rI].className = 'selected';
                        selId += rows[rI].getAttribute('data-file') + '|';
                    }
                }
                else if (lastRowIndex > newRowIndex) {
                    for (rI = lastRowIndex; rI > newRowIndex; rI--) {
                        rows[rI].lastClassName = rows[rI].className;
                        rows[rI].className = 'selected';
                        selId += rows[rI].getAttribute('data-file') + '|';
                    }
                }
                selId += el.getAttribute('data-file');
            } else {
                selId = file;
            }
            Famark.clearSelection();
        } else {
            if (selId != null && selId != '') {
                var items = Famark.getElementsByClassName('selected', 'div', divData);
                for (var i = 0; i < items.length; i++)
                    items[i].className = items[i].lastClassName;
            }
            selId = file;
        }

        el.lastClassName = el.className;
        el.className = 'selected';
        divData.setAttribute('data-selected', selId);
    };

    divData.ondblclick = function (e) {
        e = e || window.event;
        var el = e.target || e.srcElement;

        while (el.nodeName != 'DIV' && el.nodeName != 'BODY')
            el = el.parentNode;

        if (el.nodeName != 'DIV')
            return;

        var file = el.getAttribute('data-file');

        if (file == null || file == '')
            return;

        //prevent selection on dblclick
        Famark.clearSelection();

        var downFrame = document.getElementById('downFrame');

        downFrame.src = 'Attachment/' + divData.getAttribute('data-entity') +
            '/' + divData.getAttribute('data-rid') + '/' + window.encodeURIComponent(file) +
            '?type=' + window.encodeURIComponent('application/octet-stream');
    };
    
    if (btnDel != null) {
        btnDel.onclick = function () {
            var selId = divData.getAttribute('data-selected');
            if (selId == null || selId == '')
                return;

            var data = 'entity=' + divData.getAttribute('data-entity') +
                '&rid=' + divData.getAttribute('data-rid') +
                '&work=DeleteAttachment&files=' + window.encodeURIComponent(selId);

            var http = new XMLHttpRequest();
            http.open('POST', 'Work.ashx', false);
            http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            http.send(data);
            var result = Famark.parseJSON(http.responseText);
            if (result.ErrorMessage == null || result.ErrorMessage == '') {
                divData.setAttribute('data-selected', '');
                var items = Famark.getElementsByClassName('selected', 'div', divData);
                for (var i = 0; i < items.length; i++) {
                    items[i].className = 'deleted';
                    items[i].setAttribute('data-file', '');
                }
            } else
                alert(result.ErrorMessage);
        };
    }
    
    if (btnSort != null) {
        var selSort = document.getElementById('selSort');

        function sortFiles(sortDesc) {
            if (Famark._preventUnloadMessage) {
                alert(Famark._preventUnloadMessage);
                return;
            }
            var filesOrderBy = selSort.value;
            if (sortDesc)
                filesOrderBy += ' Desc';

            divData.setAttribute('data-filesOrderBy', filesOrderBy);

            var key = divData.getAttribute('data-entity') + '.filesOrderBy.';
            Famark.setCookie(key, filesOrderBy, 60);

            window.location.replace('List.ashx?entity=' + divData.getAttribute('data-entity') +
                '&rid=' + divData.getAttribute('data-rid') + '&filesOrderBy=' + window.encodeURIComponent(filesOrderBy));
        }

        btnSort.onclick = function () {
            //toggle sort direction
            if (btnSort.getAttribute('data-sortDirection') == 'down') {
                btnSort.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#sort-arrow-up'></use></svg>";
                btnSort.setAttribute('data-sortDirection', 'up');
                sortFiles(true);
            } else {
                btnSort.innerHTML = "<svg class='icon'><use href='Attachment/all-icons.svg#sort-arrow-down'></use></svg>";
                btnSort.setAttribute('data-sortDirection', 'down');
                sortFiles(false);
            }
        };

        selSort.onchange = function () {
            //use current sort direction
            sortFiles(btnSort.getAttribute('data-sortDirection') == 'up');
        };
    }

    if (btnRef != null) {
        btnRef.onclick = function () {
            window.location.replace('List.ashx?entity=' + divData.getAttribute('data-entity') +
                '&rid=' + divData.getAttribute('data-rid') + '&filesOrderBy=' + divData.getAttribute('data-filesOrderBy'));
        };
    }

    var screenLoad = function () {
        window.setTimeout(function () {
            var newHeight = document.body.clientHeight - divData.offsetTop;
            if (newHeight < 0)
                newHeight = 0;
            divData.style.height = newHeight + 'px';
        }, 40);
    };

    Famark.addHandler(window, 'resize', screenLoad);

    screenLoad();
};
Famark.htmlToText = function (html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    return div.textContent;
};
Famark.removeHiddenFields = function (frm) {
    var fields = frm.getElementsByTagName('input');
    var hdFields = [];

    for (var i = 0; i < fields.length; i++) {
        if (fields[i].type == 'hidden')
            hdFields.push(fields[i]);
    }

    for (var j = 0; j < hdFields.length; j++)
        frm.removeChild(hdFields[j]);
};
Famark.appendHiddenFields = function (frm, name, value) {
    var el = document.createElement('input');
    el.type = 'hidden';
    el.name = name;
    el.value = value;
    frm.appendChild(el);
};

Famark.addHandler = function (el, ev, fn) {
    if (el.addEventListener)
        el.addEventListener(ev, fn, false);
    else if (el.attachEvent)
        el.attachEvent('on' + ev, fn);
    else
        el[ev] = fn;
};

Famark.parseJSON = function (data) {
    if (data == null || typeof data !== 'string')
        return null;

    data = (data.trim) ? data.trim() : data.replace(/^\s+|\s+$/g, '');

    if (window.JSON && window.JSON.parse)
        return window.JSON.parse(data);

    var valData = data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
    valData = valData.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    valData = valData.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

    var valExp = /^[\],:{}\s]*$/;

    if (valExp.test(valData))
        return (new Function('return ' + data))();

    alert('Invalid JSON: ' + data);
    return null;
};

Famark.getElementsByClassName = function (cName, tName, node) {
    var els = [];
    var tmp, i;

    tName = tName || '*';
    node = node || document;

    if (node.getElementsByClassName) {
        tmp = node.getElementsByClassName(cName);
        for (i = 0; i < tmp.length; i++)
            els.push(tmp[i]);
    }
    else {
        var pattern = new RegExp('\\b' + cName + '\\b');
        tmp = node.getElementsByTagName(tName);
        for (i = 0; i < tmp.length; i++) {
            if (pattern.test(tmp[i].className))
                els.push(tmp[i]);
        }
    }

    return els;
};

Famark.clearSelection = function () {
    if (document.selection && document.selection.empty) {
        try {
            document.selection.empty();
        } catch (e) { }
    } else if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
};

Famark.formatIsoDates = function () {

    var isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
    var isoDates = document.querySelectorAll('[data-format="datetime"]');

    for (var i = 0; i < isoDates.length; i++) {
        if (isoDateRegex.test(isoDates[i].textContent)) {
            var dt = Famark.getDateFromIso(isoDates[i].textContent);
            if (isFinite(dt)) {
                isoDates[i].textContent = Famark.getDisplayDateTime(dt);
            }
        }
    }
};

Famark.getDateFromIso = function (s) {
    var day = new Date('1980-12-21T15:25:00+05:30');
    if (isFinite(day) && day.getTime() === 346240500000)
        return new Date(s);
    var tz,
        rx = /^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
        p = rx.exec(s) || [];
    if (!p[1])
        return NaN;
    day = p[1].split(/\D/);
    for (var i = 0; i < day.length; i++)
        day[i] = parseInt(day[i], 10) || 0;
    day[1] -= 1;
    day = new Date(Date.UTC.apply(Date, day));
    if (!day.getDate())
        return NaN;
    if (p[5]) {
        tz = (parseInt(p[5], 10) * 60);
        if (p[6]) tz += parseInt(p[6], 10);
        if (p[4] == '+') tz *= -1;
        if (tz) day.setUTCMinutes(day.getUTCMinutes() + tz);
    }
    return day;
};

Famark.getDisplayDateTime = function (dt) {
    var year = dt.getFullYear();
    var month = dt.getMonth() + 1;
    var date = dt.getDate();
    var hours = dt.getHours();
    var mins = dt.getMinutes();
    return year + '-' + (month < 10 ? '0' : '') + month + '-' + (date < 10 ? '0' : '') + date + ' ' + Famark.getDisplayTime(hours, mins);
};

Famark.getDisplayTime = function (hh, mm) {
    var tt = hh > 11 ? 'PM' : 'AM';
    hh = ((hh + 11) % 12) + 1;
    return (hh < 10 ? '0' : '') + hh + ':' + (mm < 10 ? '0' : '') + mm + ' ' + tt;
};

Famark.setCookie = function (key, value, minutes) {
    value = window.escape(value);
    if (minutes != null) {
        var now = new Date();
        now.setMinutes(now.getMinutes() + minutes);
        value += '; expires=' + now.toUTCString();
    }
    document.cookie = key + "=" + value;
};