/*
 * SimpleModal Protagonist Formular
 *
 * kopiert und angepasst: Lars Bassen
 */

var numOfWrongCaptchaTries = 0;

$(document).ready(function () {

	$('#protagonistsave').click(function (e) {
			e.preventDefault();
			// validate form
			var checkval = protagonist.validate();

		});

});




var protagonist = {
	message: null,
	open: function (dialog) {
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.content.fadeIn(200, function () {
					$('#protagonist #voting_result').focus();
				});
			});
		});
	},
	show: function (dialog) {

	},
	close: function (dialog) {
		dialog.content.fadeOut(200, function () {
			dialog.container.fadeOut(200, function () {
				dialog.overlay.fadeOut(200, function () {
					$.modal.remove(dialog);
				});
			});
		});
	},

	error: function (xhr) {
		//alert(xhr.statusText);
	},
	validate: function () {

		protagonist.message = '';

		var email = $('#protagonist #protagonist_email').val();
        if (email) {
			// Regex from: http://regexlib.com/REDetails.aspx?regexp_id=599
			var filter = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/;
			if (!filter.test(email)) {
				protagonist.message += 'Die Email-Adresse ist ung&uuml;ltig. ';
			}// if
        }// if

        var bild = $('#protagonist #protagonist_bild').val();
        if (bild) {
            var ext = bild.split('.').pop().toLowerCase();
            var allow = new Array('.jff','.jfif','.jif','.jpe','jpeg','jpg');
            if(jQuery.inArray(ext, allow) == -1) {
                protagonist.message += 'Die hochgeladene Datei ist keine JPEG-Datei! ';
            }// if
        }// if

        if ($('#protagonist #code').val() == "") {
            protagonist.message += 'Bitte geben Sie die Sicherheitszahl ein. ';
            protagonist.showError();
            return false;
        } else {
           /*
            * Überprüft, ob in dem Image CAPTCHA Feld das gleiche eingegeben wurde, wie in der Grafik
            * dargestellt
            */
			// async: false
		    $.ajax({
		        type: "GET",
		        url: 'action/check_captcha.php',
		        data: 'code='+$('#code').val(),
		        complete: function (res) {


		            var response = res.responseText;
                    //console.log("response: "+response);
                    if (response == '1')
                    {
                        //console.log("Code korrekt!");
                        numOfWrongCaptchaTries = 0;
                    }
                    else if (response == '2')
                    {
                        // Drei Fehlversuche, jetzt sollte ein neues Image-Captcha angezeigt werden
                        //console.log("3x falsch");
                        numOfWrongCaptchaTries = 0;
                        protagonist.message += 'Bitte &uuml;berpr&uuml;fen Sie die Sicherheitszahl.';
                        getNewCaptcha();
                    }
                    else
                    {
                        //console.log("DEBUG :" + response + ", action/check_captcha.php?code="+document.getElementById('code').value);
                        numOfWrongCaptchaTries++;
                        protagonist.message += 'Bitte &uuml;berpr&uuml;fen Sie die Sicherheitszahl.';
                    }

                    //console.log("protagonist.message.length: "+protagonist.message.length);

			        if (protagonist.message.length > 0) {
			            protagonist.showError();
			            saveprotagonist(false);
			        }
			        else {
			            saveprotagonist(true);
			        }

		        },
		        error: function (res) {
		            saveprotagonist(false);
		        }
		    });

        }


	},
	showError: function () {
		$('#protagonist .message').html($('<div class="error"></div>').append(protagonist.message)).fadeIn(200);
	}
};


var getNewCaptcha = function () {


    $.ajax({
        type: "GET",
        url: 'action/get_new_captcha.php',

        complete: function (res) {
            document.getElementById('iframe_imgcaptcha').src = res.responseText;
            numOfWrongCaptchaTries = 0;
            currentCaptcha = '';
            captchaIsOkay = false;
            document.getElementById('code').value = '';
        },
        error: function (res) {
            document.getElementById('code').value =  res.responseText;
        }
    });

    return false;
}


var saveprotagonist = function (protagonistValidate) {
            if (protagonistValidate) {
                $('#protagonist .message').fadeOut(function () {
                    $('#protagonist .message').removeClass('error').empty();
                });
                $('#protagonist .title').html('Wird gespeichert ...');
                $('body').animate({scrollTop: 0}, 1000);
                $('#protagonist form').fadeOut(200, function () {
                    $('#protagonist .loading').fadeIn(200, function () {

                        // wegen des Dateiuploads erfolgt die Verarbeitung des Formulars in einem iFrame
                        var frameName = 'do_protagonist';
                        var uploadFrame = $('<iframe name="' + frameName + '"></iframe>');
                        uploadFrame.css("display", "none");
                        $('#protagonist:first').append(uploadFrame);
                        $('#protagonist form').attr('method', 'post');
                        $('#protagonist form').attr('target', frameName);
                        $('#protagonist form').attr('action', 'action/do_sendprotagonist.php');
                        $('#protagonist form').submit();

                    });
                });
            }
            else {
                if ($('#protagonist .message:visible').length > 0) {
                    $('#protagonist .message div').fadeOut(200, function () {
                        $('#protagonist .message div').empty();
                        protagonist.showError();
                        $('#protagonist .message div').fadeIn(200);
                    });
                }
                else {
                    $('#protagonist .message').animate({
                        height: '50px'
                    }, protagonist.showError);
                }

            }
}

