// detect screen size.
if (screen) setCookie('screen', screen.width + 'x' + screen.height);

//////////////////////////////////////////////////
// category: DOM functions
//////////////////////////////////////////////////

function getElement(id)
{
    var e;
    if (document.getElementById) {
        e = document.getElementById(id);
    }
    else if (document.all) {
        e = document.all[id];
    }
    else if (document.layers) {
        e = document.layers[id]; // WARNING: no support for nested layers in NS4
    }
    else {
        e = eval("document."+id);
    }

    if (!e) { // not found. Try document.forms
        if (document.forms) {
            e = document.forms[id];
        }
    }
    return e;
}

function getFormElement(name) {
    var i,j,obj;
    if (!document.forms) return null;
    if (!document.forms.length) return null;
    for (i=0; i<document.forms.length; i++) {
        if (document.forms[i].elements) {
            for (j=0; j<document.forms[i].elements.length; j++) {
                if (document.forms[i].elements[j]) {
                    obj = document.forms[i].elements[j];
                    if (obj.name == name) {
                        return obj;
                    }
                }
            }
        }
    }
}

function focusElement(p) {
    if (typeof(p) == "string") {
        p = getElement(p);
    }
    if (p && p.focus) {
        p.focus();
    }
}

function focusFormElement(name) {
    var x = getFormElement(name);
    if (x && x.focus) {
        x.focus();
    }
}

/**
 *
 * @param string id The id of the element to remove
 * return Node the deleted element
 */
function removeElement(id) {
    e = getElement(id);
    return e.parentNode.removeChild(e);
}

/**
 *
 *
 */
function isChildOf(childId, parentId) {
    var e = getElement(childId);
    while(e=e.parentNode) {
        if (e.id==parentId) {
            return true;
        }
    }
    return false;
}

/**
 *
 *
 */
function isParentTo(parentId, childId) {
    return isChildOf(childId, parentId);
}

function getKeyCode(e)
{
    if (document.layers)
        return e.which;
    else if (document.all)
        return event.keyCode;
    else if (document.getElementById)
        return e.keyCode;
    return 0;
}

function submitForm(id)
{
    var f;
    if (document.forms) f = document.forms[id];
    else f = getElement(id);

    if (f && f.submit) f.submit();
}

function getPosition(who){
    var L= 0,T= 0;
    while(who){
        L+= who.offsetLeft;
        T+= who.offsetTop;
        who= who.offsetParent;
    }
    var pos = {x: L, y: T};
    return pos
}

//////////////////////////////////////////////////
// Timer functions
//////////////////////////////////////////////////

function Timer(cmd, ms)
{
    this.cmd = cmd;
    this.ms = ms;
    this.tp = 0;
}

Timer.prototype.start = function()
{
    if (this.tp > 0)
        this.reset();
    this.tp = window.setTimeout(this.cmd, this.ms);
}

Timer.prototype.reset = function()
{
    if (this.tp > 0)
        window.clearTimeout(this.tp);
    this.tp = 0;
}



//////////////////////////////////////////////////
//  category: Form functions
//////////////////////////////////////////////////

function setFormField(form, field, value)
{
    document.forms[form].elements[field].value = value;
}

function checkUncheckAll(toggle, group)
{
    var frm = toggle.form;

    for ( var i = 0; i < frm.elements[group].length; i++ )
    {
        frm.elements[group][i].checked = toggle.checked;
    }
}

function checkUncheckAllByValue(toggle, value)
{
    var frm = toggle.form;

    for ( var i = 0; i < frm.elements.length; i++ )
    {
      if (frm.elements[i].value == value){
	frm.elements[i].checked = toggle.checked;
      }
    }
}

// Function to fill up a selectBox from an array
// @param selectBoxId The id of the select-element
// @param options A list of options: Array(value1, html1, value2, html2, ...) or Array(value1, html1, optgroupId, ...)
// The optgroupId is an index into the groups array.
// @param groups A list of labels for option groups.
// @param firstOp Any element to append as first child to the select-box
// @param disable Disable the entire selectbox, or not
function replaceOptions(selectBoxId, options, groups, firstOp, disable) {
  var selectBox = getElement(selectBoxId);
  if (!selectBox) {
    return;
  }
  while(selectBox.hasChildNodes()) {
    selectBox.removeChild(selectBox.firstChild);
  }
  if (firstOp) {
    selectBox.appendChild(firstOp);
  }
  if (disable) {
    selectBox.disabled="1";
  }
  else {
    selectBox.removeAttribute("disabled");
  }
  if (!options) {
    return;
  }
  if(groups) {
    var optGroups = Array();
    for (var i=0;i<options.length;i+=3) {
      var group = options[i+2];
      if (!optGroups[group]) {
        optGroups[group] = document.createElement('optgroup');
        optGroups[group].label = groups[group];
      }
      optGroups[group].appendChild(createOption(options[i], options[i+1]));
    }
    for (theGroup in optGroups) {
      selectBox.appendChild(optGroups[theGroup]);
    }
  }
  else {
    for (var i=0;i<options.length;i += 2) {
       selectBox.appendChild(createOption(options[i], options[i+1]));
    }
  }
}

function createOption(value, text, cls) {
    var objOption=document.createElement("option");
    objOption.innerHTML = text;
    objOption.value     = value;
    if (cls>0) {
        objOption.setAttribute('class', cls);
    }
    return objOption;
}

function createLinkFromSelect(box, baseUrl) {
  var id = box.options[box.selectedIndex].value;
  if (!id) return;
  var name = box.options[box.selectedIndex].text;
  var href = baseUrl+id;
  var link = '<a href="'+href+'">'+name+'</a>';
  return link;
}

function getSelectedOption(box) {
    var option = box.options[box.selectedIndex];
    return option;
}

// Returns the selected-displayed text from a select-box
function getSelectedText(box) {
    var option = getSelectedOption(box);
    return option.text;
}

// returns the value of the selected option in a select-box
function getSelectedValue(box) {
    var option = getSelectedOption(box);
    return option.value;
}

function findOption(boxId, value) {
    var selectBox = document.getElementById(boxId);
    for (var i=0;i<selectBox.options.length;i++) {
        var theOption = selectBox.options[i];
        if (theOption.value == value) {
            return theOption;
        }
    }
    return null;
}

function findOptionByText(boxId, text) {
    var selectBox = document.getElementById(boxId);
    for (var i=0;i<selectBox.options.length;i++) {
        var theOption = selectBox.options[i];
        if (theOption.text == text) {
            return theOption;
        }
    }
    return null;
}

/**
 * Get selected radio from the name
 * Having two <input type="radio" name="choice"/> elements will return value from the selected one
 */
function getSelectedRadio(elementName) {
    var i,j,obj,name;
    var name = '';
    if (!document.forms) return null;
    if (!document.forms.length) return null;
    for (i=0; i<document.forms.length; i++) {
        if (document.forms[i].elements) {
            for (j=0; j<document.forms[i].elements.length; j++) {
                if (document.forms[i].elements[j]) {
                    obj = document.forms[i].elements[j];
                    if (obj.type && obj.type == "radio") {
                        if (!name && (obj.name == elementName || obj.id == elementName)) {
                            name = obj.name == elementName ? obj.name : obj.id;
                        }
                        if (obj && name && (obj.name == elementName || obj.id == elementName)) {
                            if (obj.checked) {
                                return obj.value;
                            }
                        }
                    }
                }
            }
        }
    }

    /*
    try {

        var elegetFormElement(elementName);

        if (typeof(form) == "string") {
            form = document.forms[form];
        }
        if (form.elements) {
            var value;
            for (var i=0; i<form.elements.length; i++) {
                var element = form.elements[i];
                if (element.type && element.type == "radio") {
                    if (element.checked) {
                        return element.value;
                    }
                }
            }
        }
    }
    catch (e) {
    }
    */
}

function inputClear(field, defaultText) {
    if (field.value == defaultText) {
        field.value = "";
    }
}

function inputRestore(field, defaultText) {
    if (field.value == "") {
       field.value = defaultText;
    }
}

//////////////////////////////////////////////////
//  category: Event functions - GUI
/////////////////////////////////////////////////

function EventDispatcher()
{
    this.observers = new Array();
}

EventDispatcher.prototype.registerObserver = function(eventName, callbackFnc)
{
    this.observers[this.observers.length] = eventName;
    this.observers[this.observers.length] = callbackFnc;
}

// Accepts arbitrary number of arguments.
// The entire received arguments-object will be passed to the observer
// The observer can access these as arguments[0], arguments[1], ...
// , where arguments[0] will equal the event name, and index 1...n will be the following arguments
// See @link {http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments}
EventDispatcher.prototype.notify = function(eventName)
{
    for (var i=0;i<this.observers.length;i+=2) {
        if (this.observers[i]==eventName) {
            this.observers[i+1](arguments);
        }
    }
}

// Global instance
eventDisp = new EventDispatcher();


function openWindow(content, title, width, height, doctype, base, css) {
    var win = window.open("", "edPreview", "menubar=no,toolbar=no,scrollbars=yes,resizable=yes,left=20,top=20,width=" + width + ",height="  + height);
    var html = "";
    var c = content;
    var pos = c.indexOf('<body'), pos2;

    if (pos != -1) {
        pos = c.indexOf('>', pos);
        pos2 = c.lastIndexOf('</body>');
        c = c.substring(pos + 1, pos2);
    }

    html += doctype
    html += '<html xmlns="http://www.w3.org/1999/xhtml">';
    html += '<head>';
    html += '<title>' + title + '</title>';
    html += '<base href="' + base + '" />';
    html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    html += '<link href="' + css + '" rel="stylesheet" type="text/css" />';
    html += '</head>';
    html += '<body>';
    html += c;
    html += '</body>';
    html += '</html>';

    win.document.write(html);
    win.document.close();
}


//////////////////////////////////////////////////
//  category: String functions
/////////////////////////////////////////////////

function strpad(padding, thisstring, length)
{
    var padded = new String(thisstring);
    while ( padded.length < length )
        padded = padding + padded;

    return padded;
}

function humanDate(thisdate, iso)
{
    if ( !iso )
    {
        return strpad("0",thisdate.getDate(), 2) + "-" + strpad("0", (thisdate.getMonth()+1), 2) + "-" + thisdate.getFullYear();
    }
    else
    {
        return thisdate.getFullYear() + "-" + strpad("0", (thisdate.getMonth()+1), 2) + "-" + strpad("0",thisdate.getDate(), 2);
    }
}

function isNull(i)
{
    return typeof i == 'object' && !i;
}

//
// Style functions
//

function showBlock(elementId)
{
    var e = getElement(elementId);
    if (e && e.style) e.style.display = 'block';
}

function showElement(elementId)
{
    var e = getElement(elementId);
    if (e && e.style) e.style.display = 'inline';
}

function hideElement(elementId)
{
    var e = getElement(elementId);
    if (e && e.style) {e.style.display = 'none'};
}

function isHidden(elementId)
{
    var e = getElement(elementId);
    if (e && e.style) return e.style.display == 'none';
    return false;
}

function setHidden(elementId, hide)
{
    setHiddenWithType(elementId, hide, false)
}

function setHiddenWithType(elementId, hide, isBlock)
{
    if (hide) {
        hideElement(elementId);
    }
    else {
        if (isBlock) {
            showBlock(elementId);
        }
        else {
            showElement(elementId);
        }
    }
}

function toggleHidden(elementId)
{
    hide = !isHidden(elementId);
    setHidden(elementId, hide);
}

function toggleHiddenBlock(elementId)
{
    hide = !isHidden(elementId);
    setHiddenWithType(elementId, hide, true);
}

///////////////////////
// Cookies
// From: http://www.netspade.com/articles/javascript/cookies.xml
///////////////////////

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function json_decode(s) {
    /*
    try {
        return eval('(' + s + ')');
    }
    catch (e) {
        return null;
    }
    */
    try {
        if (/^[\],:{}\s]*$/.test(s.replace(/\\./g, '@').
        replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, ']').
        replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
            return eval('(' + s + ')');
        }
        else {
            return null;
        }
    }
    catch (e) {
        return null;
    }
}


/**
 * Introduced by GMTA in order to make new landing page CSS without changing
 * every single HTML file 
 *
 */
function include_js(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

function include_css(style_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var css = document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', style_filename);
    html_doc.appendChild(css);
    return false;
}

include_css('/?page=css_landingpage&ajax=1');