// Open Error-Message-Box
function showError(headline, content, errorClass)
{
    
    if (typeof errorClass == 'undefined') errorClass = 'notice';    
    var errorContent = '<h1>' + headline + '</h1><p>' + content + '</p>';
    $("#errorMessage").addClass(errorClass).html(errorContent).slideDown();
	// scroll to top, so user can read the error message
	$(window).scrollTop(0);
    
}

// converts things like 10.000,00, 10,000.00, 10000 (i.e. normal numbers but german/english) to usable integer
function parseNumber(string) {

	// return, if nothing was consigned
	if(typeof string == 'undefined') return;

	// stip all non-digit characters from string
	string = string.replace(/([^0-9\.,]+)/g, "");

    var length = string.length
    var presumedDeviderPos      = length - 2;
    var presumedDevider         = string.slice(presumedDeviderPos - 1, presumedDeviderPos);

    // is there a devider?
    if (presumedDevider != "," && presumedDevider != ".") {
        string      = string.replace(/\./g, "").replace(/,/g, "");          // remove everything
        return parseFloat(string);
    } else if (presumedDevider == ",") {
        var preComma    = string.slice(0, presumedDeviderPos-1);
        var fromComma   = string.slice(presumedDeviderPos-1, length);
        preComma    = preComma.replace(/\./g, "");                          // remove all periods in preComma
        fromComma   = fromComma.replace(/,/g, ".");                         // replace last comma with period
        return parseFloat(preComma + fromComma);
    } else {
        string = string.replace(/,/g, "");                                  // remove all commas
        return (parseFloat(string));
    }

}

// formats number to this: 10.000,00 EUR
function showCurrency(nStr)
{
    nStr = nStr.toFixed(2);
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2 + " EUR";
}

// formats number to this: 10.000,00
function showNumber(nStr)
{
    nStr = nStr.toFixed(2);
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

// performance test (Usage: var start = performanceTest("start"); ... code to test ... performanceTest("stop", start);
function performanceTest(start, startTime) {

    var date            = new Date();
    var milliseconds    = date.getTime();        
    
    if (start == "start") {

        return milliseconds;

    } else {
        
        console.log(milliseconds - startTime, "Laufzeit in Millisekunden");
        
    }
    
}

// simple console for debugging in IE
function simpleConsole(text) {

    if ($('#simpleConsole').length == 0) {
    
        $('body').prepend('<div id="simpleConsole" style="position: absolute; top: 50px; left: 600px; z-index: 9999; line-height: 1.1em;"></div>');
    
    }

    var time = new Date();
    var ms = time.getMilliseconds();

    $('#simpleConsole').prepend('<p style="color: red; font-size: 10px; margin: 0; padding: 0;">' + ms + ': ' + text + '</p>');
    
    if ($('#simpleConsole p').length > 10) {
        $('#simpleConsole p:last').remove();
    }
    
    
}

// colors for default value
var active_color 	= '#707173'; 	// Colour of user provided text
var inactive_color 	= '#bec3c0'; 	// Colour of default text

// preload images
// usage: $.preLoadImages('public/images/dummies/4.png', 'image1.jpg');
(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery);

// workaround for IE-Bug (doesn't recognise .css('backgroundPosition))
(function($) {
    jQuery.fn.backgroundPosition = function() {
        var p = $(this).css('background-position');
        if(typeof(p) === 'undefined') return $(this).css('background-position-x') + ' ' + $(this).css('background-position-y');
        else return p;
    };
})(jQuery);

// leading zeros
function leadingZeros(num, totalChars, padWith) {
	num = num + "";
	padWith = (padWith) ? padWith : "0";
	if (num.length < totalChars) {
		while (num.length < totalChars) {
			num = padWith + num;
		}
	} else {}

	if (num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
		num = num.substring((num.length - totalChars), totalChars);
	} else {}

	return num;
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function ucfirst (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'

    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

// select something, that is NOT a child of some other element | usage: $("a.ajax").filter(":parents(.ajaxTargets)") | explanation: http://jsbin.com/adece
jQuery.expr[':'].parents = function(a,i,m){
    return jQuery(a).parents(m[3]).length < 1;
};

/*
 *  Simple Confirm-Dialog
 *  usage: 
 *      $('#testConfirm').click(function(){
 *          Confirm.default('#confirmTarget', 'Sind Sie sicher?', function(){
 *              console.log('callback');
 *          });
 *          return false;
 *      });
 **/
var Confirm = {
    targetSelector: '',
    createDialogContent: function(question) {
        return question + ' <a href="#" class="positive">Ja</a> / <a href="#" class="negative">Nein</a>';
    },
    clearDialog: function() {
        if ($(this.targetSelector).is(':visible')) {
            $(this.targetSelector).slideUp(function(){
                $(this).html('');
            });
        } else {
            $(this.targetSelector).html('');
        }
    },
    inline: function(targetSelector, question, f) {
        this.targetSelector = targetSelector;
        $(this.targetSelector)
        .html(Confirm.createDialogContent(question))
        .find('a.positive').click(function(){
            if (typeof f == "function") {
                f();
            }
            Confirm.clearDialog();
            return false;
        })
        .parent().find('a.negative').click(function(){
            Confirm.clearDialog();
            return false;
        });
        if ($(this.targetSelector).is(':hidden')) {
            $(this.targetSelector).slideDown();
        }
    }
}

// jQuery Ready-Handler
jQuery(document).ready(function($){
    
    // Hide all elements which should be initially hidden
    $(".hidden").hide();

	// open and close hidden element (variable)
	$("a.slideTarget").click(function(event) {
		event.preventDefault();
		$($(this).attr("href")).slideToggle("slow");
	});
	
    // replace button link with span of same optic to prevent double clicking
    $(".preventDoubleClick.button").click(function(){
        var disabledLink = '<span id="' + $(this).attr("id") + '" class="' + $(this).attr("class") + '">' + $(this).text() + '</span>';
        $(this).replaceWith(disabledLink);
    });

	// disable submit button to prevent double submission
	// ATTENTION: using this stops transmission of submit-button value, so check if form-data was sent has to be changed
	$(".preventDoubleClick.submit").click(function(event){
    
	       // only disable field, if form is valid (jQuery Validator); and I put it inside a try-and-catch to prevent errors
	    try {
	   	    if ($(this).parent("form").valid()) {
	               $(this).attr("disabled","disabled");
	   	    }
	       } catch(err) {
	           $(this).attr("disabled","disabled");
	       }

	});

	// add zebra-stripes to odd cells in .zebra tables (via .each so each table starts new)
	$("table.zebra").each(function(){
		$(this).find("tbody tr:odd td").css("background-color", "#eee");
	});

	// defaultValue of input form (lighter color and get replaced)
	// Written by Rob Schmitt, The Web Developer's Blog (http://webdeveloper.beforeseven.com/)
	$("input.defaultValue").css("color", inactive_color);
	var defaultValues = new Array();
	$("input.defaultValue").focus(function() {
	  if (!defaultValues[this.id]) {
	    defaultValues[this.id] = this.value;
	  }
	  if (this.value == defaultValues[this.id]) {
	    this.value = '';
	    this.style.color = active_color;
	  }
	  $(this).blur(function() {
	    if (this.value == '') {
	      this.style.color = inactive_color;
	      this.value = defaultValues[this.id];
	    }
	  });
	});

	// standard dialog for displaying a confirmation-message
	$('a.confirm').click(function(){
	  return confirm(langAreYouSure);
	});

	// generic class for go back to previous page
    $('a.goBack').click(function(event){
		event.preventDefault();
		history.back();
	});

    // extends $.support with check for position: fixed; returns TRUE if supported and FALSE if unsupported (IE6)
    $.support.positionFixed = (function(){
        var isSupported = null;
        if (document.createElement) {
            var el = document.createElement('div');
            if (el && el.style) {
                el.style.position = 'fixed';
                el.style.top = '10px';
                var root = document.body;
                if (root && root.appendChild && root.removeChild) {
                    root.appendChild(el);
                    isSupported = (el.offsetTop === 10);
                    root.removeChild(el);
                }
            }
        }
        return isSupported;
    })();

});
