/****************************************************
 * JavaScript function library for Norne.           *
 *                                                  *
 *                                                  *
 ****************************************************/

/**
 * Global variables for NorneScript
 */
var NSNewWin;

/**
 * NorneScript constructor.
 */
function NorneScript () {
}

/**
 * Open new window
 *
 * @param string Url to open.
 * @param string Session key
 * @param int width
 * @param int height
 * @return bool
 */
NorneScript.prototype.open = function(url, sesskey, width, height) {

    var width  = (width != null && width != 'undefined')   ? width : 580;
    var height = (height != null && height != 'undefined') ? height: 480;
    var x = parseInt((screen.availWidth / 2) - (width / 2));
    var y = parseInt((screen.availHeight / 2) - (height / 2));

    var winOpt  = 'width='+ width;
        winOpt += ',height= '+ height;
        winOpt += ',left=' + x;
        winOpt += ',top=' + y;
        winOpt += ',scrollbars=yes';

    var url = url + '?sesskey=' + sesskey;
    if ( !NSNewWin || NSNewWin.closed ) {
        NSNewWin = window.open(url, 'dummy', winOpt);
        NSNewWin.focus();
    } else {
        NSNewWin.focus();
    }
    return true;
}

NorneScript.prototype.comment = function(url, width, height) {

    var width  = (width != null && width != 'undefined')   ? width : 580;
    var height = (height != null && height != 'undefined') ? height: 480;
    var x = parseInt((screen.availWidth / 2) - (width / 2));
    var y = parseInt((screen.availHeight / 2) - (height / 2));

    var winOpt  = 'width='+ width;
        winOpt += ',height= '+ height;
        winOpt += ',left=' + x;
        winOpt += ',top=' + y;
        winOpt += ',scrollbars=yes';

    var url = url;
    if ( !NSNewWin || NSNewWin.closed ) {
        NSNewWin = window.open(url, 'comments', winOpt);
        NSNewWin.focus();
    } else {
        NSNewWin.focus();
    }
    return true;
}

NorneScript.prototype.updCommentCount = function () {
    if ( document.getElementById && window.opener ) {
        var elem = opener.document.getElementById('comments');
        var txt = elem.innerHTML;

        txt = txt.replace(/\((\d+)\s?/, function (m) {
            m = m.replace(/[^0-9]+/, '');
            m = parseInt(m);
            return '(' + parseInt(m + 1) + ' ';
        });
        elem.innerHTML = txt;
    }
};

var Norne = new NorneScript;
