/**
 * Curalia Cuwing client-side JavaScript.
 * $Id: default.js,v 1.28 2011-08-22 16:31:29 martin Exp $
 */
var opera = (document.all && navigator.userAgent && navigator.userAgent.indexOf("Opera")>=0);
var ie = (document.all && !opera);
var moz = !document.all;

if (!(document.getElementById && document.images)) {
 location.href=ROOT + "/oldbrowser.html";
}

function openBrowserWindow(url,name,opt) {
 var w=window.open(url,name,opt); if (w) { w.focus(); }; return w;
}

function clientPopup(url,name) {
 return openBrowserWindow(url,name,CLIENT_POPUP_PARAMS);
}

function validateString(f, msg, min, max) {
 if (!min) { min=1; }
 if (!max) { max=65535; }
 var v=true;
 if (!f.value || f.value.length<min || f.value.max>max) {
  alert(msg);
  try {
   f.focus();
   if (f["select"]) { f.select(); }
  } catch (e) {}
  v=false;
 }
 return v;
}

function validateRegexp(f, msg, re, opt) {
 var v=true;
 if ((!f.value && !opt) || (f.value && !re.test(f.value))) {
  alert(msg);
  try {
   f.focus();
   if (f["select"]) { f.select(); }
  } catch (e) {}
  v=false;
 }
 return v;
}

function changeBackground(divId,imgPath) {
 var obj = document.getElementById(divId);
 if (obj) {
  if (ie) {
   var s = ROOT + "/img/" + imgPath + "'";
   obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + s + ", sizingMethod='scale')";
  } else {
   var i = "url('" + ROOT + "/img/" + imgPath + "')";
   obj.style.backgroundImage = i;
  }
 }
}

function toggle() {
  cuwing.toggle(arguments);
}

// Toggle element display to explicit state by CSS visibility.
// Arguments: id string[element id], visibilityFlag string["1"|"0"]
function toggleVisibility(id, visibilityFlag) {
    var e = false;
    if (id) e = document.getElementById(id);
    if (!e || !e.style.visibility) return;
    e.style.visibility = visibilityFlag == "1" ? "visible" : "hidden";
}

function addClassName(element, className) {
 if (!element) return;
 removeClassName(element, className);
 element.className += ' ' + className;
}

function removeClassName(element, className) {
 if (!element) return;
 var newClassName = '';
 var a = element.className ? element.className.split(' ') : '';
 for (var i = 0; i < a.length; i++) {
  if (a[i] != className) {
   if (i > 0) newClassName += ' ';
   newClassName += a[i];
  }
 }
 element.className = newClassName;
}

/* TODO: Encapsulate all functions in Cuwing class */
function Cuwing() {
    this.setFormEnc("ISO-8859-1");
    this.opera = (document.all && navigator.userAgent && navigator.userAgent.indexOf("Opera")>=0);
    this.ie = (document.all && !opera);
    this.moz = !document.all;
}

/* toggle: element CSS display on/off-toggle [varargs string[element id]] */
Cuwing.prototype.toggle = function() {
    for (var i = 0; i < arguments.length; i++) {
        var elementId = arguments[i];
        var element = elementId ? document.getElementById(elementId) : null;
        if (element) {
            var d = 'none';
            if (element.style && '' + element.style.display == 'none') d = '';
            element.style.display = d;
        }
    }
};

/* setFormEnc: set FORM encoding */
Cuwing.prototype.setFormEnc = function(enc) {
    this._formEnc = enc;
    this._formEncUnicode = enc == "UTF-8" || enc == "utf-8";
};

/* encode: unicode safe URL encode (application/x-www-form-urlencoded) */
Cuwing.prototype.encode = function(str) {
    if (typeof(str) == "undefined" || str == null) return null;
    var e;
    if (this._formEncUnicode && typeof(encodeURIComponent) != "undefied") {
        e = encodeURIComponent(str);
    } else {
        e = escape(str);
    }
    return e.replace(/\u0020/g, '+');
};

/* decode: unicode safe URL decode (application/x-www-form-urlencoded) */
Cuwing.prototype.decode = function(str) {
    if (typeof(str) == "undefined" || str == null) return null;
    var d;
    if (this._formEncUnicode && typeof(decodeURIComponent) != "undefied") {
        d = decodeURIComponent(str);
    } else {
        d = unescape(str);
    }
    return d.replace(/\+/g, '\u0020');
};

/* addEventListener: cross-browser function for adding listeners in event chain */
Cuwing.prototype.addEventListener = function(element, eventType, eventListener, useCapture) {
    if (element) {
        if (element.addEventListener) {
            if (!useCapture) {
                useCapture = false;
            }
            element.addEventListener(eventType, eventListener, useCapture);
        } else if (element.attachEvent) {
            element.attachEvent("on" + eventType, eventListener);
        }
    }
};

/**
 * log: non-intrusive alert using (in priority order):
 *  FireBug console,
 *  Gecko error console,
 *  Gecko application console (requires browser.dom.window.dump.enabled=true)
 *  Window status (normally blocked in Gecko).
 */
Cuwing.prototype.log = function(message) {
    if (typeof(window.console) != "undefined") {
        window.console.info("Cuwing: " + message);
    } else if (typeof(dump) != "undefined") {
        dump(message + "\r\n");
    } else {
        window.status = message;
    }
};

/* getCookie: returns value (or null) of cookie with specified name */
Cuwing.prototype.getCookie = function(name) {
    if (!document.cookie) return null;
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

/* setCookie: return boolean status after setting specified cookie name/value */
Cuwing.prototype.setCookie = function(name, value, path, expireDays, domain) {
    try {
        var c = name + "=" + escape(value);
        if (expireDays) {
            var e = expireDays * 1000 * 60 * 60 * 24;
            var eD = new Date();
            eD.setTime(eD.getTime() + e);
            c = c + ";expires=" + eD.toGMTString();
        }
        if (path) { c = c + ";path=" + path; }
        if (domain) { c = c + ";domain=" + domain; }
        document.cookie = c;
        return true;
    } catch (e) {
        this.log(e);
        return false;
    }
};

/* getParam: returns parameter value (or null) of URL (GET) parameter with specified name */
Cuwing.prototype.getParam = function(name) {
    var v = null;
    try {
        var re = new RegExp("[\\?&]"+name+"=([^&#]*)");
        var res = re.exec(window.location.href);
        if (res != null) v = this.decode(res[1]);
    } catch (e) {
        v = null;
    }
    return v;
};

/* isAdmin: returns whether editing or published mode */
Cuwing.prototype.isAdmin = function() {
    return typeof(root) != "undefined" && "" + root != ""
        && typeof(document.location) != "undefined"
        && document.location.pathname && document.location.pathname != ""
        && document.location.pathname.substr(0, root.length + 7) == root + "/admin/";
};

/** getHost: returs client hostname or empty string if n/a */
Cuwing.prototype.getHost = function() {
    var h = "";
    try {
        h = window.location.hostname;
    } catch (e) {}
    return h;
};

var cuwing = window.cuwing || new Cuwing();

