// Open Error-Message-Box
function showError(headline, content, errorClass) {
	
	// reset classes
    $("#errorMessage").attr("class", "hidden");

	// set style of error class
    if (typeof errorClass == 'undefined') errorClass = 'notice';    

	// insert headline of error message
    var errorContent = '<h2>' + headline + '</h2>';

	// concatenate content or add class for displaying only the headline without margin-bottom
	if (content) 	{ errorContent += '<p>' + content + '</p>'; }
	else 			{ $("#errorMessage").addClass("messageHeadlineOnly"); }

	// add classes to errorMessage-div and show it
    $("#errorMessage").addClass(errorClass).html(errorContent).slideDown();
	// scroll to top, so user can read the error message
	$(window).scrollTop(0);
    
}

// show notice (wrapper)
function showNotice(headline, content) {
	
	showError(headline, content, 'notice');
	
}

// 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;
}

// start indicator to wait (increasing number of dots)
function startWaitingIndicator(element) {

    var span = $("#" + element);

    waitingIndicator = window.setInterval(function(){
		var text = span.text();
		if (text.length < 5){
			span.text(text + '.');
		} else {
			span.text('');
		}
	}, 400);
    
}

// stop indicator to wait
function stopWaitingIndicator(element) {
    
    window.clearInterval(waitingIndicator);
    $("#" + element).text('');

}

/**
 * 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");
        
    }
    
}

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

// jQuery Ready-Handler
$(function() {

    // Hide all elements which should be initially hidden
    $(".hidden").hide();

	// open and close content of boxes
	$("a.slide_more").click(function(event) {
		event.preventDefault();
		$($(this).attr("href")).slideToggle("slow");
		$(($(this).attr("href"))+'_less').toggle();
		$(($(this).attr("href"))+'_more').toggle();
	});
	
	// 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.default_value").css("color", inactive_color);
	var default_values = new Array();
	$("input.default_value").focus(function() {
	  if (!default_values[this.id]) {
	    default_values[this.id] = this.value;
	  }
	  if (this.value == default_values[this.id]) {
	    this.value = '';
	    this.style.color = active_color;
	  }
	  $(this).blur(function() {
	    if (this.value == '') {
	      this.style.color = inactive_color;
	      this.value = default_values[this.id];
	    }
	  });
	});

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

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

	// generic class for closing the window
    $('a.closeWindow').click(function(event){
		event.preventDefault();
		window.close();
	});

	// generic class for choosing / unchoosing all checkboxes in one form
    $(".toogleAllCheckboxes").click(function(event){
		event.preventDefault();
		var checkboxes = $(event.target).parents("form").find(":checkboxes");
		if ($(checkboxes + ":checked").size() > 0) 	var checked = true;
		else 										var checked = false;
		$(checkboxes).attr("checked", !checked);
    });

    // dropdown for direct access to offerTypes
    $('#directSearchOfferTypeForm #offerType').change(function(event){
       
       var url = $('#directSearchOfferTypeForm option:selected').attr('value');
       
       if (url.length > 0) {
           
           window.location = url;
           
       }
        
    });

});

