var util = {

    date: function ( format, timestamp ) {
 
    var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];
 
    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                t = f.l(); return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },
 
        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
 
                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{
 
                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },
 
        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },
 
        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            //o not supported yet
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },
 
        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            //u not supported yet
 
        // Timezone
            //e not supported yet
            //I not supported yet
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            //Z not supported yet
 
        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            //r not supported yet
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };
 
    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }
 
        return ret;
    });
    }, // end date
    
    datecheck: function( month, day, year ) {
    var myDate = new Date();
    myDate.setFullYear( year, (month - 1), day );
 
    return ( (myDate.getMonth()+1) == month );
    }, // end datecheck
    
    print: function( array, return_val ) {

        var output = "", pad_char = " ", pad_val = 4;
     
        var formatArray = function (obj, cur_depth, pad_val, pad_char) {
            if (cur_depth > 0) {
                cur_depth++;
            }
     
            var base_pad = repeat_char(pad_val*cur_depth, pad_char);
            var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
            var str = "";
     
            if (obj instanceof Array || obj instanceof Object) {
                str += "Array\n" + base_pad + "(\n";
                for (var key in obj) {
                    if (obj[key] instanceof Array) {
                        str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                    } else {
                        str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                    }
                }
                str += base_pad + ")\n";
            } else if(obj == null || obj == undefined) {
                str = '';
            } else {
                str = obj.toString();
            }
     
            return str;
        };
     
        var repeat_char = function (len, pad_char) {
            var str = "";
            for(var i=0; i < len; i++) { 
                str += pad_char; 
            };
            return str;
        };
        output = formatArray(array, 0, pad_val, pad_char);
     
        if (return_val !== true) {
            document.write("<pre>" + output + "</pre>");
            return true;
        } else {
            alert(output);
        }
    }, // end print
    
    countrylist: function(strId, strContinent, intUserId)   {
        var arrCountryList = document.getElementById(strId).options;
        var intCountryListCount = arrCountryList.length;
        
        for(var intCount = intCountryListCount; intCount > -1; intCount--)  {
            arrCountryList[intCount] = null;
        }
        
        var strData = "";
        var intCount = 0;
        
        
        var strUrl = core.config('root') + "includes/ajax/util.countrylist.php?strContinent=" + strContinent + "&intUserId=" + intUserId;
        var objRequest = YAHOO.util.Connect.asyncRequest('GET', strUrl, {
            success: function(objData)  {
                var objJson = YAHOO.lang.JSON.parse(objData.responseText);
                for(var intCount = 0; intCount < objJson.length; intCount++)    {
                    strOption = new Option(objJson[intCount], objJson[intCount], false, true);
                    document.getElementById(strId).options[intCount] = strOption;
                }
                document.getElementById(strId).selectedIndex = 0;
            }
        });
        
    }, // countrylist
    
    toggle: function(mxdInput)  {
        if(typeof mxdInput == 'object') {
            
        }
        else if(typeof mxdInput == 'string')    {
            mxdInput = document.getElementById(mxdInput);
        }
        
        mxdInput.style.display = mxdInput.style.display == 'none' ? 'block' : 'none';
    }, // end toggle
    

    
    draggable: function(strSelector, objOptionList) {
        jQuery(strSelector).draggable( objOptionList );
    }, // end draggable
    
    droppable: function(strSelector, objOptionList) {
        //alert('droppabel');
        jQuery(strSelector).droppable( objOptionList );
    }, // end droppable
    
    urlable: function(arr, current_index) {
        var query = ""
        if(typeof current_index=='undefined') current_index = '';
    
        if(typeof(arr) == 'object') {
            var params = new Array();
            for(key in arr) {
                var data = arr[key];
                var key_value = key;
                if(current_index) {
                    key_value = current_index+"["+key+"]"
                }
    
                if(typeof(data) == 'object') {
                    if(data.length) { //List
                        for(var i=0;i<data.length; i++) {
                            params.push(key_value+"[]="+ued_encode(data[i],key_value)); //:RECURSION:
                        }
                    } else { //Associative array
                        params.push(ued_encode(data,key_value)); //:RECURSION:
                    }
                } else { //String or Number
                    params.push(key_value+"="+encodeURIComponent(data));
                }
            }
            query = params.join("&");
        } else {
            query = encodeURIComponent(arr);
        }
    
        return query;
    }, // end urlable
    removeLeadingZeros: function(mxdInput)  {
        
        var objReturn = new Array();
        
        if(typeof mxdInput == "string") {
            return parseInt(strInput.replace(/^(0+)/g, ''));
        }
        else if(typeof mxdInput == "object")    {
            
            for(var intCount = 0; intCount < mxdInput.length; intCount++)   {
                objReturn[intCount] = parseInt(mxdInput[intCount].replace(/^(0+)/g, ''));
            }
            return objReturn;
        } 
         
    }, // end removeLeadingZeros
    trim: function trim( str, charlist ) {
    	return jQuery.trim(str);
    },
    
    /**
     * Submits the form with the inputted email to a script,
     * which checks the email and mails a mail with the password to the
     * submitted email-address.
     * 
     * After sending a message will be displayed wheter the sending of the
     * password was successful or not.
     * 
     * // function is called from url http://[http-root]/user/password
     * // form located in templates/base/user/password.php
     */
    request_password: function() {
        jQuery.post(doc_root + "includes/ajax/user.request-password.php", {
                password_mail: jQuery('#password_mail').val()
        }, function (data, status) {
                if (data) {
                    jQuery('input#password_mail').removeClass('form-error').val('');
                    alert(gt.gettext('Das Passwort wurde an die von Ihnen angegebene E-Mail versand.'));
                    window.location.href = doc_root;
                }
                else {
                    jQuery('input#password_mail').addClass('form-error');
                    jQuery('input#password_mail').focus();
                    alert(gt.gettext('Ein Benutzer mit dieser E-Mail Adresse ist in unserem System nicht vorhanden. Überprüfen Sie bitte die Schreibweise Ihrer angegebenen E-Mail Adresse.'));
                }
        }, "json");     
    },
    
    /**
     * As the right column is position absolute, footer does not recognize it and 
     * does not flow after the right column, but is beeing placed behind it.
     * 
     * This function checks if the footer is behind the right column an places the 
     * footer below it.
     */
    check_footer_location : function() {
        if (jQuery('#mainCol').height() < jQuery('#subCol2').height()) {
            jQuery('#footer').css('marginTop', jQuery('#subCol2').height() - jQuery('#mainCol').height());
        }
        
        if (jQuery('#mainCol').height() < jQuery('#subCol1').height()) {
            jQuery('#footer').css('marginTop', jQuery('#subCol1').height() - jQuery('#mainCol').height());
        }
    },
    
    /**
     * Initialize the view and function of the tabs. 
     */
    initTabs : function() {
		// init tabs
		var tabContainers = jQuery("div.tabs > div");
		jQuery("ul.tabNavigation a").click(function() {

			
			tabContainers.hide();
			jQuery(this.hash).show();
			
			jQuery("ul.tabNavigation li").removeClass("selected");
			jQuery(this.parentNode).addClass('selected');
			
			$.address.value($(this).attr('id'));
			
			
			util.check_footer_location();
			
			return false;
		}).filter(":first").click();
		
		// save onclick function temporarely before the click event is being executed
//		var tmpfnc = tabs.filter(":first").attr('onclick');
		
//		tabs.filter(":first")
//			.attr('onclick', '') // delete onclick event (so the function will not be executed at initalisation of tabs)
//			.click() // execute click event (whithout the onclick-function)
//			.click(tmpfnc); // bind the onclick-function again for user clicks
		
		// end init tabs    	
    },
    
    close : function(dom_id) {
    	jQuery('#mainNavWrapper').css('z-index', 5); // default z-index for navi
    	if (jQuery('#' + dom_id).length > 0) {
    		// remove onscrollEvent from WINDOW
    		jQuery(window).unbind('scroll');//, util.position);
    		jQuery('#' + dom_id).removeShadow();
    		jQuery('#' + dom_id).fadeOut('normal');
    		jQuery('#content-hide-element').fadeOut('normal', function() {
    			jQuery('#content-hide-element').remove();    		
    		});
    		
    	}
    },
    

    /**
     * 
     */
    position: function()	{
		var dom_id = center_div != '' ? center_div : false;
    	jQuery('#' + dom_id)
//    		.css({
//				'-moz-box-shadow': '5px 5px 10px #999',
//				'-webkit-box-shadow' : '5px 5px 10px #999', 
//				'box-shadow' : '5px 5px 10px #999'
//	    		})
    		.center();
//		
//		if (!dom_id) return; // return to avoid errors if center_div has not been set before assigning this function as a handler 
//	
//		var objBox = document.getElementById(dom_id);
//		
//		//alert(jQuery(window).width() + ' ' + jQuery(window).height() + ' || ' + jQuery('#' + dom_id).width() + ' ' + jQuery('#' + dom_id).height());
//	
//	
//		
//		var intScreenWidth = jQuery(window).width();
//		var intScreenHeight = jQuery(window).width();
//		
//		var offset_px = intScreenHeight * 0.09;
//		
//		var scrollPos = jQuery(window).scrollTop() - offset_px;
//		
//		var intLeft = (intScreenWidth - jQuery('#' + dom_id).width()) / 2;
//		var intTop = (intScreenHeight/2 - jQuery('#' + dom_id).height()) + scrollPos;
//		
//		
//		//alert('calulatted top:left: ' + intTop + ' ' + intLeft);
//		
////		jQuery('#' + dom_id).css({
////				'top': intTop + 'px'
////		});
////		jQuery('#' + dom_id + '_dropShadow').css({
////			'top' : intTop + 'px'
////		});
//		jQuery('#' + dom_id).css({
//				'left': intLeft + 'px',
//				'top': intTop + 'px'
//		});
//		
//		jQuery('#' + dom_id + '_dropShadow').css({
//			'left' : intLeft + 'px',
//			'top' : intTop + 'px'
//		});
		
	
	}, // end position
	
	debug_tool : function(tool) {
        jQuery.post(doc_root + "includes/ajax/debugging-tools.php", {
           'tool' : tool
        }, function (data, status) {
			
        });			
	},
	
	highlite : function(obj, on, hover_color) {
		hover_color = typeof hover_color != 'undefined' ? hover_color : 'dcdde3'; 
		
		
		var color = '';
		if (on) {
			color = '#' + hover_color;
		}
		jQuery(obj).css('background-color', color);	
	},
	hide_workingspace : function() {
		jQuery('body').prepend('<div id="content-hide-element"></div>').fadeIn('fast');
		jQuery('#content-hide-element').css({
					'z-index': 999,
					'position' : 'absolute',
					'height': '10000px', 
					//'height' : jQuery('body').height(),
					'left' : '0px',
					'margin-top' : '-1000px'
		});

	},
	box_slide_toggle : function(link_obj, box_id) {
		if (box_id <= 0) return false;
		
		// Box minimieren-/expandieren-Link
		jQuery("#content_" + box_id).slideToggle("normal");
		jQuery(link_obj).toggleClass("active");

		jQuery("#content_" + box_id).css('zoom', 1);
		return false;
	
	}
};
