var Famark = Famark || {};

Famark.pageLoad = function () {

    Famark._successMessage = 'Performed!';

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

    var links = nav.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function (e) {
            e = e || window.event;
            var target = e.target || e.srcElement;
            if (target.href[target.href.length - 1] != '#') {
                var url = target.href + '?data-entity=' + nav.getAttribute('data-entity');
                var rid = nav.getAttribute('data-rid');
                if (rid != null && rid != '')
                    url += '&data-rid=' + rid;
                var filter = nav.getAttribute('data-filter');
                if (filter != null && filter != '')
                    url += '&data-filter=' + window.encodeURIComponent(filter);
                window.top.Famark.showWindow(url, 'Form', 60, 1);
                window.top.Famark.closeWindow(window);
            }
            else {
                var data = 'entity=' + nav.getAttribute('data-entity') +
                '&work=' + target.getAttribute('data-work') + '&rid=' + nav.getAttribute('data-rid');
                var linkText = target.innerHTML;
                target.innerHTML = '<img src="Attachment/loading.gif" alt="wait" style="width:32px;height:8px;" />';
                var http = new XMLHttpRequest();
                http.onreadystatechange = function () {
                    if (http.readyState === 4) {
                        var result = Famark.parseJSON(http.responseText);
                        target.innerHTML = linkText;
                        if (result.ErrorMessage != null && result.ErrorMessage != '')
                            alert(result.ErrorMessage);
                        else if (result.Output != null && result.Output != '')
                            alert(result.Output);
                        else
                            alert(Famark._successMessage);
                    }
                };
                http.open('POST', 'Work.ashx', true);
                http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                http.send(data);
            }
            return false;
        };
    }
};

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;
};