/*

# --------------------------------------
# PublishExec/interface/common.js
# created 2005-07-15 modified 2005-07-21
# (c) clientexec.com & gosu.pl all rights reserved
# Author: Cezary Tomczak
# --------------------------------------

*/

function element(id) { return document.getElementById(id); }

function $() {
    if (arguments.length == 1) return document.getElementById(arguments[0]);
    var ret = [];
    for (var i = 0; i < arguments.length; i++) {
        var el = arguments[i];
        if (typeof el == 'string') el = document.getElementById(el);
        ret.push(el);
    }
    return ret;
}

function addEvent(el, event, func) {
    if (el.addEventListener) { el.addEventListener(event, func, false); }
    else if (el.attachEvent) { el.attachEvent("on"+event, func); }
}
function removeEvent(el, event, func) {
    if (el.removeEventListener) { el.removeEventListener(event, func, true); }
    else if (el.detachEvent) { el.detachEvent("on"+event, func); }
}

function toggle(id) { element(id).style.display = (element(id).style.display != "none") ? "none" : "block"; }
function toggleOn(id) { if (!element(id)) throw 'toggleOn("'+id+'") failed'; element(id).style.visibility = "visible"; element(id).style.display = "block"; }
function toggleOff(id) { if (!element(id)) throw 'toggleOn("'+id+'") failed'; element(id).style.visibility = "hidden"; element(id).style.display = "none"; }

// IE creates calls functions for events in wrong order, this may cause conflicts, we fix this
var onLoadQueue = [];
function onLoad(func) {
    if (!onLoadQueue.length) {
        addEvent(window, "load", onLoadExecute);
    }
    onLoadQueue.push(func);
}
function onLoadExecute() {
    for (var i = 0; i < onLoadQueue.length; i++) {
        onLoadQueue[i]();
    }
}

function onUnload(func) { addEvent(window, "unload", func); }

function openWindow(url, width, height, more) {
    var x = (screen.width/2-width/2);
    var y = (screen.height/2-height/2);
    window.open(url, "", "scrollbars=yes,width="+width+",height="+height+",screenX="+(x)+",screenY="+y+",left="+x+",top="+y+(more ? ","+more : ""));
}

/* Check whether array contains given string */
Array.prototype.contains = function(s) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === s) { return true; }
    }
    return false;
};

/* Finds the index of the first occurence of item in the array, or -1 if not found */
Array.prototype.indexOf = function(item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === item) { return i; }
    }
    return -1;
};

/* Get the last element from the array */
Array.prototype.getLast = function() {
    return this[this.length-1];
};

/* Remove element with given index (mutates) */
Array.prototype.removeByIndex = function(index) {
    this.splice(index, 1);
};

/* Remove elements with such value (mutates) */
Array.prototype.removeByValue = function(value) {
    var i, indexes = [];
    for (i = 0; i < this.length; i++) {
        if (this[i] === value) { indexes.push(i); }
    }
    for (i = indexes.length - 1; i >= 0; i--) {
        this.splice(indexes[i], 1);
    }
};

/* Push an element at specified index */
Array.prototype.pushAtIndex = function(el, index) {
    this.splice(index, 0, el);
};

/* Strip whitespace from the beginning and end of a string  */
String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
};

/* Count the number of substring occurrences */
String.prototype.substrCount = function(s) {
    return this.split(s).length - 1;
};

/* Remove elements judged 'false' by the passed function (mutates) */
Array.prototype.filter = function(func) {
    var i, indexes = [];
    for (i = 0; i < this.length; ++i) {
        if (!func(this[i])) { indexes.push(i); }
    }
    for (i = indexes.length - 1; i >= 0; --i) {
        this.splice(indexes[i], 1);
    }
};

/* Replace ? tokens with variables passed as arguments in a string */
String.prototype.format = function() {
    if (!arguments.length) { throw "String.format() failed, no arguments passed, this = "+this; }
    var tokens = this.split("?");
    if (arguments.length != (tokens.length - 1)) { throw "String.format() failed, tokens != arguments, this = "+this; }
    var s = tokens[0];
    for (var i = 0; i < arguments.length; ++i) {
        s += (arguments[i] + tokens[i + 1]);
    }
    return s;
};

String.prototype.repeat = function(n)
{
    var ret = "";
    for (var i = 0; i < n; ++i) { ret += this; }
    return ret;
};

function padZeros(s, len)
{
    s = String(s);
    return "0".repeat(len-s.length)+s;
}

function getDateIso(d)
{
    if (!d) d = new Date();
    var ret = "";
    ret += d.getFullYear()+"-";
    ret += padZeros(d.getMonth()+1, 2)+"-";
    ret += padZeros(d.getDate(), 2)+" ";
    ret += padZeros(d.getHours(), 2)+":";
    ret += padZeros(d.getMinutes(), 2)+":";
    ret += padZeros(d.getSeconds(), 2);
    return ret;
}

String.prototype.htmlSafe = function() {
    var ret = this;
    ret = ret.replace(/</g, "&lt;");
    ret = ret.replace(/>/g, "&gt;");
    return ret;
};

String.prototype.isNumeric = function() {
    return /^[\d]+$/.test(this);
};

// TASKS
// create a queue of user tasks, to avoid any conflicts/errors by using async http calls ?
// before a new user task is created you need to be sure no previous user tasks will be performed
// private system functions do not need creating tasks, and shouldn't, because user tasks may call them, and so errors may appear

var globalTaskID = 0;
var globalTaskIDPerName = [];

function createTask(name)
{
    if (!name) return ++globalTaskID;
    if (!globalTaskIDPerName[name]) globalTaskIDPerName[name] = 0;
    return ++globalTaskIDPerName[name];
}
function isTaskActive(taskID, name)
{
    if (!name) return taskID == globalTaskID;
    return globalTaskIDPerName[name];
}

// LOADING ON
function loadingOn(id, message) {
    toggleOn(id);
    $(id).innerHTML = '<div class="loading">'+message+'</div>';
}

// -------
// COOKIES
// -------

var COOKIE_MONTH = 3600*24*30;
var COOKIE_YEAR = 3600*24*30*12;

function getCookie(name)
{
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; ++i) {
        var a = cookies[i].split("=");
        if (a.length == 2) {
            a[0] = a[0].trim();
            a[1] = a[1].trim();
            if (a[0] == name) {
                return unescape(a[1]);
            }
        }
    }
    return "";
}

function setCookie(name, value, seconds, path)
{
    if (typeof seconds == 'undefined') {
        seconds = COOKIE_YEAR;
    } else {
        alert('setCookie() can accept only 2 arguments');
        return false;
    }
    if (typeof path == 'undefined') {
        if (typeof APPLICATION_PATH == 'undefined') {
            alert('APPLICATION_PATH not defined');
            return false;
        }
        path = APPLICATION_PATH;
    } else {
        alert('setCookie() can accept only 2 arguments');
        return false;
    }
    var cookie = (name + "=" + escape(value));
    if (seconds) {
        var date = new Date(new Date().getTime()+seconds*1000);
        cookie += ("; expires="+date.toGMTString());
    }
    cookie += (path    ? "; path="+path : "");
    document.cookie = cookie;
}

function delCookie(name, path)
{
    if (typeof path == 'undefined') {
        if (typeof APPLICATION_PATH == 'undefined') {
            alert('APPLICATION_PATH not defined');
            return false;
        }
        path = APPLICATION_PATH;
    } else {
        alert('delCookie() can accept only 2 arguments');
        return false;
    }
    var cookie = (name + "=");
    cookie += (path    ? "; path="+path : "");
    cookie += "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    document.cookie = cookie;
}
