/** 
 * function the is called when any page is loaded.
 * main use is to make the flash error fade out after 10 seconds
 * DEPENDANT: jquery
 */
 
if (typeof MGI == "undefined") {
     var MGI = {};
 }

MGI.flashfade=500; /* time(ms) to fade the flashbox, 0 means don't fade */

/**************************************************************************
 * add a master load function for all things loading
 */
 
function masterLoadFunction()
{
    /* for all objects with the class flash, fade them in */
    if(MGI.flashfade != 0){
        flashElement = $('.flashmsg').fadeIn(MGI.flashfade);        
    }
    
    $("a.delete").click(function(e){
        var answer = confirm($(this).attr('warning'));
        if(!answer){
            e.preventDefault();
            return false;
        }
        return true;
    });
}

$(window).ready(masterLoadFunction);

/**************************************************************************
 * Execution unit namespace with generic functions we'd really like to use
 * all over the place */
EUNIT = {
    createCookie: function(name,value,days) {
    	if (days) {
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();
    	}
    	else{
    	    var expires = "";
	    }
    	document.cookie = name+"="+value+expires+"; path=/";
    },

    readCookie: function(name) {
    	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;
    },

    eraseCookie: function(name) {
    	createCookie(name,"",-1);
    },

    daysInMonth: function (year, month) {
         return 32 - new Date(year, month, 32).getDate();
    },
    
    toggleVisible: function(elem) {
        $(elem).toggleClass("invisible");
    },

    makeVisible: function(elem) {
        $(elem).removeClass("invisible");
    },
 
    makeInvisible: function(elem) {
        $(elem).addClass("invisible");
    },

    isVisible: function(elem) {
        // you may also want to check for
        // getElement(elem).style.display == "none"
        return !($('elem').hasClass(elem, "invisible"));
    },
    
    replaceChildNodes: function(elem, newchildren){
        $(elem).empty().append(newchildren);
    },
    
    getElement: function(name){
        return $('#'+name)[0];
    },
    
    getFirstElementByTagAndClassName: function(tag, classname, parent){
        if(parent){
            return $(parent).find('.'+classname).filter(tag+":first")[0];
        }else{
            return $('.'+classname).filter(tag+":first")[0];
        }
    },
    
    flash : function(msg){
        $('#pagecontent').prepend("<div class='flash'><div class='flashmsg'>"+msg+"</div></div>");
        $('.flashmsg').fadeIn(MGI.flashfade);        
    },
    
    removeFlash : function(){
        $(".flash").remove();
    },
    
    log : function(stuff){
        if(typeof console != "undefined"){
            console.log(stuff);
        }
    }
};

// DOM element creator for jQuery and Prototype by Michael Geary
// http://mg.to/topics/programming/javascript/jquery
// Inspired by MochiKit.DOM by Bob Ippolito
// Free beer and free speech. Enjoy!

$.defineTag = function( tag ) {
    $[tag.toUpperCase()] = function() {
        return $._createNode( tag, arguments );
    };
};

(function() {
    var tags = [
        'a', 'br', 'button', 'canvas', 'div', 'fieldset', 'form',
        'h1', 'h2', 'h3', 'hr', 'img', 'input', 'label', 'legend',
        'li', 'ol', 'optgroup', 'option', 'p', 'pre', 'select',
        'span', 'strong', 'table', 'tbody', 'td', 'textarea',
        'tfoot', 'th', 'thead', 'tr', 'tt', 'ul' ];
    for( var i = tags.length - 1;  i >= 0;  i-- ) {
        $.defineTag( tags[i] );
    }
})();

$.NBSP = '\u00a0';

$._createNode = function( tag, args ) {
    var fix = { 'class':'className', 'Class':'className' };
    var e;
    try {
        var attrs = args[0] || {};
        e = document.createElement( tag );
        $(e).attr(attrs);
        if (attrs.style) $(e).css(attrs.style);
        //   for( var attr in attrs ) {
        //     var a = fix[attr] || attr;
        //     e[a] = attrs[attr];
        // }
        for( var i = 1;  i < args.length;  i++ ) {
            var arg = args[i];
            if( arg == null ) continue;
            if( arg.constructor != Array ) append( arg );
            else for( var j = 0;  j < arg.length;  j++ )
                append( arg[j] );
        }
    }
    catch( ex ) {
        console.log( 'Cannot create <' + tag + '> element:\n' +
            args.toSource() + '\n' + args + '\n' + ex);
        e = null;
    }

    function append( arg ) {
        if( arg == null ) return;
        var c = arg.constructor;
        switch( typeof arg ) {
            case 'number': arg = '' + arg;  // fall through
            case 'string': arg = document.createTextNode( arg );
        }
        e.appendChild( arg );
    }

    return e;
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};