

var containerIds = new Array();
var containerIdsReloading = new Array();

var ajax_loading = false;
var delay_millisecs = 150;
var idCurrentlyLoading = '';
var errorCount = 0;

var addressFormChanged = false;

var loadTimer = null;
var startLoaderMillisecsAfterLoadingStarts = 1000;
var keepLoaderForMillisecsAfterCompletion = 1000;
var forceLoader = 0;


$(function() {
    initContainers();
});


function displayInfo (pageName, show) {
    if (show) {

	window.scrollTo(0,0);

	$.ajax({
	    type:	"GET",
	    dataType:	"html",
	    url:	"data/"+pageName+".php",
	    success:	function(responseData) {
		$("#infoPopup").html(responseData);
		var x = parseInt(($(window).width() /2) - ($("#infoPopup").width() /2));
		var y = parseInt(($(window).height() /2) - ($("#infoPopup").height() /2));

		if ($("body").height() > $(window).height()) {
		    $(".infoBg").height($("body").height());
		}
		else {
		    $(".infoBg").height($(window).height());
		}

		$("#infoPopup").css('left', x+'px');
		$("#infoPopup").css('top', y+'px');
				
		$(".infoBg").show();
		$("#infoPopup").fadeIn('fast');
	    }
	});
    }
    else {
	$("#infoPopup").fadeOut('fast', function(){
	    $(".infoBg").hide();
	});

    }
}


function startLoadTimer () {
    // console.log("load-timer starten?");
    if (!ajax_loading) {
	// console.log("JA, load-timer starten!");
	ajax_loading = 1;
	window.clearTimeout('loadTimer');
	loadTimer = setTimeout("showLoader(1)", startLoaderMillisecsAfterLoadingStarts);
    }
    else {
// console.log("NEIN, load-timer nicht starten!");
}
}

function stopLoadTimer () {
    // console.log("load-timer BEENDEN!");
    window.clearTimeout('loadTimer');
    loadTimer = setTimeout("showLoader(0)", keepLoaderForMillisecsAfterCompletion);
    ajax_loading = 0;
}


function showLoader(show) {
    if (show && ajax_loading) {
	$("#loader").show();
    }
    else {
	$("#loader").hide();
	ajax_loading = 0;
	forceLoader = 0;
    }
}


function info (msg, replace) {

    return $("#info").hide();

    if (replace) {
	$("#info").html(msg);
    }
    else {
	$("#info").append("<br>" + msg);
    }
    $("#info").show();
}


function initContainers() {

    $.ajax({
	type:		"GET",
	dataType:	"html",
	url:			"ajx/containers.php",
	success:		function(responseData) {
	    $("#rechteSpalte").append(responseData);
	    $(".section").each(function(){
		if (!$(this).hasClass('orderContainer')) {
		    containerIds[containerIds.length] = $(this).attr("id");
		}
		if ($(this).attr("id") == 'navi') {
		    $("#linkeSpalte").append(this);
		    $(this).show();
		}
	    });
	    loadFollowingSections ($(".firstContainer").attr("id"));
	}
    });
}


function initAdressUpdateButton() {

    addressFormChanged = false;

    $("#btUpdateAddress").click(function(){

	if(addressFormChanged) {
	    var adrUpdateString = '';

	    // console.log("Adresse pruefen...");

	    adrUpdateString += 'anr='  + $("#anrede").val();
	    adrUpdateString += '&vn='  + $("#vorname").val();
	    adrUpdateString += '&nn='  + $("#nachname").val();
	    var wkValue = ($("#wk").attr("checked")) ? '1' : '0';
	    adrUpdateString += '&wk='  + wkValue;

	    adrUpdateString += '&str='  + $("#strasse").val();
	    adrUpdateString += '&hnr='  + $("#hausnummer").val();
	    adrUpdateString += '&plz='  + $("#plz").val();
	    adrUpdateString += '&ort='  + $("#ort").val();
	    adrUpdateString += '&lkz='  + $("#lkz").val();

	    adrUpdateString = encodeURI(adrUpdateString);

	    addressFormChanged = false;
	    update('setPersdata', adrUpdateString, 'input');
	}
	else {
	    // console.log("WEITER ... ");
	    orderSummary();
	}
    });

    $(".adjust").click(function(){

	addressFormChanged = true;

	var strasse = $(this).attr('s');
	var ort = $(this).attr("o");

	if (strasse) {
	    $("#strasse").val(strasse);
	    $("#strasse").removeClass('err');
	    $(this).parent().fadeOut('slow');
	}

	if (ort) {
	    $("#ort").val(ort);
	    $("#ort").removeClass('err');
	    $(this).parent().fadeOut();
	}
	// check address after modification
	$("#btUpdateAddress").click();
    });

    $(".adjust").fadeIn();
}



function initAddressFormInputs() {

    $("#persdata input").change(function () {
	addressFormChanged = true;
    });
    $("#persdata select").change(function () {
	addressFormChanged = true;
    });
}



/**
	 * adds klickHandler for Container-Links
	 */
function initContainerLinks(containerId) {

    $("#"+containerId+" .updateLink").click(function(){

	if (!ajax_loading) {

	    startLoadTimer();

	    info ("verarbeite klick im Container " + containerId, 1);

	    var action = $(this).attr("action");
	    var params = $(this).attr("params");
	    $(this).attr("href", 'javascript:void(0)');

	    if (action == "load") {
		reloadSection ( containerId, params );
	    }
	    else {
		update(	action, params, containerId	);
	    }
	}
	else {
    // console.log ("Keine aktion! Warte noch... ");
    }
    });

    if(containerId == 'orderInfo') {
	initAdressUpdateButton();
    }

    if(containerId == 'input') {
	if ($("#persdata").text()) {
	    initAddressFormInputs();
	}
    }

}


function editItems() {
    reloadSection('input', 'editSection=angebote');
}

function editAddress() {
    reloadSection('input', 'editSection=persdata');
}

function orderSummary() {
    reloadSection('input', 'editSection=orderSummary');
}

function sendOrder() {
    reloadSection('input', 'editSection=send');
}


function update(action, getVars, containerId) {

    // info ("update! " + containerId + " / " + action + " / " + getVars, 0);
    // alert (getVars);

    $.ajax({
	type:		"GET",
	dataType:	"html",
	url:		"ajx/updateBestellung.php",
	data:		"action=" + action + "&" + getVars,
	success:		function(responseData) {

	    if (containerId == 'input' && action == 'setPersdata') {
		forceLoader = 1;
		reloadSection(containerId, 'editSection=persdata');
	    }
	    else if (containerId == 'navi') {
		loadFollowingSections (containerId);
	    }
	    else {
		forceLoader = 1;
		reloadSection('input', 'editSection=angebote');
	    }
	}
    });
}


function reloadSection(sectionId, params) {

    $.ajax({
	type:		"GET",
	dataType:	"html",
	url:		'ajx/' + $("#"+sectionId).attr("f") + '.php',
	data:		params,
	success:	function(responseData) {
	    $("#" + sectionId).html(responseData);
	    if ((params && params.indexOf('angebote') != -1) 	 ||
		(params && params.indexOf('persdata') != -1) 	 ||
		(params && params.indexOf('orderSummary') != -1) ||
		($("#"+sectionId).attr("f") == 'userInputDispatch')) {
		initContainerLinks('input');
		reloadSection('orderInfo');
	    }
	    else {
		initContainerLinks(sectionId);
	    }

	    if (forceLoader) {
		stopLoadTimer();
		forceLoader = 0;
	    }

	    if(sectionId == 'orderInfo') {
		stopLoadTimer();
	    }
	}
    });
}


function checkForLoadError() {

    if (idCurrentlyLoading && $("#"+idCurrentlyLoading).attr("loading") == "Y") {
	errorCount++;
	info (idCurrentlyLoading + " Laedt noch (fehler "+errorCount+")", 0);
    }

    if (errorCount < 3) {
	setTimeout("checkForLoadError()", delay_millisecs);
    }
    else {
	ajax_loading = false;
	idCurrentlyLoading = '';
	errorCount = 0;
	info("Laden von " + idCurrentlyLoading + " abgebrochen!", 0);
	stopLoadTimer();
	forceLoader = 0;
    }
}


/**
	 * reloads container named in reload-array
	 */
function reloadSectionsFromReloadArray () {

    startLoadTimer ();

    if (containerIdsReloading.length == 0) {
	ajax_loading = false;
	idCurrentlyLoading = '';
	reloadSection('orderInfo');
	stopLoadTimer ();
	return;
    }

    var currentId = containerIdsReloading.shift();
    var filename = $("#"+currentId).attr("f");
    $("#"+currentId).attr("loading", "Y");

    if (idCurrentlyLoading != currentId) {
	idCurrentlyLoading = currentId;
	setTimeout("checkForLoadError()", delay_millisecs *2);
    }

    $.ajax({
	type:		"GET",
	dataType:	"HTML",
	url:		'ajx/' + $("#"+currentId).attr("f") + '.php',
	success:	function(responseData) {
	    $("#"+currentId).html(responseData);
	    $("#"+currentId).attr("loading", "N");
	    errorCount = 0;
	    initContainerLinks(currentId);
	    setTimeout("reloadSectionsFromReloadArray()", delay_millisecs);
	// reloadSectionsFromReloadArray();
	},
	error:	function(responseData) {
	    $("#"+currentId).html(currentId + ': Fehler beim Serverzugriff!');
	    setTimeout("reloadSectionsFromReloadArray()", delay_millisecs);
	}
    });
}



function loadFollowingSections (idOfCurrentSection) {

    var tempReloadArray = new Array();

    var idOfNextSection = '';
    var lookingForCurrent = true;

    for(var i=0; i < containerIds.length; i++) {

	if (lookingForCurrent && containerIds[i] == idOfCurrentSection) {
	    // found current sections entry:
	    lookingForCurrent = false;
	}

	if (!lookingForCurrent) {
	    tempReloadArray[tempReloadArray.length] = containerIds[i];
	}
    }
    containerIdsReloading = tempReloadArray;
    if (containerIdsReloading.length) {
	ajax_loading = true;
	setTimeout("reloadSectionsFromReloadArray()", delay_millisecs);
    }
}

