jQuery(document).ready(function(){

	// this is the handler if the "abbonieren" button has been clicked
	jQuery("#nl_check_mail").click( function( event ) {
		checkMail( event );
	});

	// this is the handler for closing the overlay
	jQuery(".lightbox_close").click( function( event ) {
		closeOverlay();
	});
	// this is the handler for closing the overlay by a link
	jQuery(".lightbox_close_lnk").click( function( event ) {
		closeOverlay();
	});

	// this is the handler for the submit handling of the newsletter form
	jQuery("#acceptance").click( function( event ) {
		handleSubmitState("#acceptance", "#nl_req_submit");
	});




	// this is the handler for opening the "Angebot anfordern" form
	jQuery("#qc_submit").click( function( event ) {

		event.preventDefault();
		jQuery('#lightbox').load("/contact?op=load&content=quick_contact_request_form", function () {
			// register handlers for the 'new' elements being loaded

                jQuery('#phone').val( jQuery('#qc_phone').val() );
                jQuery('#qc_phone').val("");

            jQuery('#contact_acceptance').bind('click', function(){
				handleSubmitState("#contact_acceptance", "#offer_submit");
            });

			// register handlers for closing the overlay
			jQuery('.lightbox_close').click(function(){
				closeLightbox();
			});

            // handle the submission of the offer request from
	        jQuery("#offer_submit").click( function( event ) {
				handleOfferSubmit(event);
            });
        });
		
		// show the light box
        jQuery('#lightbox').show();      
	});

	// this is the handler for opening the "Angebot anfordern" form
	jQuery("#requestOfferBtn").click( function( event ) {
		event.preventDefault();
		jQuery('#lightbox').load("/contact?op=load&content=offer_request_form", function () {
			// register handlers for the 'new' elements being loaded
            jQuery('#contact_acceptance').bind('click', function(){
				handleSubmitState("#contact_acceptance", "#offer_submit");
            });

			// register handlers for closing the overlay
			jQuery('.lightbox_close').click(function(){
				closeLightbox();
			});

            // handle the submission of the offer request from
	        jQuery("#offer_submit").click( function( event ) {
				handleOfferSubmit(event);
            });
        });
		
		// show the light box
        jQuery('#lightbox').show();        
	});

	// handle the submission of the newsletter request form
	jQuery("#nl_req_submit").click( function( event ) {
		// prevent the form from being submitted
		event.preventDefault();

		// determine the data to be used for requesting the newsletter
		var mail = jQuery("#mail").val();
		var title = jQuery("#title").val();
		var name = jQuery("#name").val();

		if ( jQuery("#acceptance").is(':checked') ) {
			jQuery.ajax({
				type: "GET",
				url: "/nlservice",
				data: "op=request&mail=" + mail + "&title=" + title + "&name=" + name,
				success: function(){
					showSuccess();
				},
				error: function(){
					showError();
				},
			});
		}
	});


});

/**
 * Check the given mail address against the DB and verify
 * that it is not already registered
 */
function checkMail( event ) {
  event.preventDefault();
  var mail = jQuery("#mail_req").val();

  if ( mail != "" ) {
    jQuery.ajax({
		type: "GET",
		url: "/nlservice",
		data: "op=checkMail&mail=" + mail ,
		success: function( mailExisting ){
			handleCheckMailResult( mailExisting );
		}
    });
  }
  else {
	// display error message
	jQuery( "#nl_msg" ).empty();
	jQuery( "#nl_msg" ).append( '<strong>Fehler</strong>: Bitte geben Sie eine g&#252;ltige EMail-Adresse ein.' );
  }
}

/**
 *	Depending on whether or not the given mail is already
 *  existing, an error message has to be set or even removed.
 *	If the given mail address is not existing, the overlay with the
 *  request form has to be displayed.
 */
function handleCheckMailResult( mailExisting ) {
	if ( "0" == mailExisting ) {
		// display the actual form
		jQuery( "#nl_msg" ).empty();
		
		// display the overlay and preset the requested mail address
		jQuery("#lightbox").show();
		jQuery("#nl_req_form").show();
		jQuery("#mail").val( jQuery("#mail_req").val() );
	} 
	else {
		// display error message
		jQuery( "#nl_msg" ).empty();
		jQuery( "#nl_msg" ).append( '<strong>Fehler</strong>: F&#252;r die eingegebene E-Mail-Adresse existiert bereits ein Abbonnement.' );
	}
}

/**
 * Show the success part of the newsletter request.
 */
function showSuccess() {
  jQuery("#nl_req_form").hide();
  jQuery("#nl_req_error").hide();
  jQuery("#nl_req_confirm").show();
}

/**
 * Show the error part of the newsletter request.
 */
function showError() {
  jQuery("#nl_req_form").hide();
  jQuery("#nl_req_error").show();
  jQuery("#nl_req_confirm").chide();
}

/**
 * Close the newsletter overlay
 */
function closeOverlay() {
  jQuery("#lightbox").hide();
  jQuery("#nl_req_form").hide();
  jQuery("#nl_req_error").hide();
  jQuery("#nl_req_confirm").hide();
  jQuery("#mail_req").val("");
}

/**
 * Closing the light box which is the overlay actually.
 */
function closeLightbox() {
	jQuery('#lightbox').hide();
	jQuery('#lightbox').empty();
}

/**
 * Generic handler for controlling the state of a given 
 * submit button.
 */ 
function handleSubmitState( checkbox_id, submit_id) {
  if(jQuery(checkbox_id).is(':checked')) {
    jQuery(submit_id).removeClass('inactivebutton');
    jQuery(submit_id).addClass('activebutton');
  }
  else {
    jQuery(submit_id).removeClass('activebutton');
    jQuery(submit_id).addClass('inactivebutton');
  }
}

/**
 * After submitting the request offer form, either a confirmation
 * or an error message will be displayed. The HTML code for this
 * messages is loaded dynamically so that the handlers for the 
 * elements ini the loaded code have to be registered as well.
 */
function handleOfferSubmit(event) {
	// prevent the form from being submitted
	event.preventDefault();
	
	// determine the data to be used for requesting the offer
	var phone = jQuery("#phone").val();
	var name = jQuery("#name").val();

        if ( phone == "" || name == "" ) {
            jQuery('#offer_msg').append("<strong>Bitte füllen Sie beide Felder aus!</strong>");
            return;
        }
        else {
             jQuery('#offer_msg').empty();
        }

        if (!phone.match(/^[0-9\s]*$/)) {
            jQuery('#offer_msg').append("<strong>Tippfehler?</strong> Bitte nur Ziffern und Leerzeichen f&#252; die Telefonnumer verwenden");
            return;
        }
        else {
             jQuery('#offer_msg').empty();
        }

	if ( jQuery("#contact_acceptance").is(':checked') ) {
		jQuery.ajax({
			type: "GET",
			url: "/contact",
			data: "op=contact&phone=" + phone + "&name=" + name,
			success: function(){
                jQuery('#lightbox').empty();
                jQuery('#lightbox').load("/contact?op=load&content=contact_confirm", function () {
					// register handlers for the 'new' elements being loaded

					// register handlers for closing the overlay
					jQuery('.lightbox_close').click(function(){
						closeLightbox();
					});
					
					// this is the handler for closing the overlay by a link
					jQuery(".lightbox_close_lnk").click( function( event ) {
						closeLightbox();
					});
				});
                jQuery('#lightbox').show();
			},
			error: function(){
				jQuery('#lightbox').empty();
                jQuery('#lightbox').load("/contact?op=load&content=contact_error", function () {
					// register handlers for the 'new' elements being loaded

					// register handlers for closing the overlay
					jQuery('.lightbox_close').click(function(){
						closeLightbox();
					});
					
					// this is the handler for closing the overlay by a link
					jQuery(".lightbox_close_lnk").click( function( event ) {
						closeLightbox();
					});
				});
                jQuery('#lightbox').show();
			}
		});
	}
}


