/*
 * SimpleModal Kommentar Formular
 *
 */

var numOfWrongCaptchaTries = 0;

$(document).ready(function () {

	$('#commentlink').click(function (e) {
		$('#commentform').show();
		$('#commentshow').hide();
	});

	$('#commentcancel').click(function (e) {
		$('#commentform').fadeOut(200);
		$('#commentshow').show();

	});

	$('#commentsave').click(function (e) {
			e.preventDefault();
			// validate form
			var checkval = comment.validate();

		});

});







var comment = {
	message: null,
	open: function (dialog) {
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.content.fadeIn(200, function () {
					$('#commentform #name').focus();
				});
				// resize the textarea for safari
				if ($.browser.safari) {
					$('#commentform textarea').attr({
						cols: '37',
						rows: '8'
					});
				}
			});
		});
	},
	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 () {

		comment.message = '';
		if (!$('#commentform #name').val()) {
			comment.message += 'Bitte geben Sie ihren Namen an. ';
		}

		var email = $('#commentform #email').val();
		if (!email) {
			comment.message += 'Bitte geben Sie ihre Email-Adresse an. ';
		}
		else {
			// 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)) {
				comment.message += 'Die Email-Adresse ist ungültig. ';
			}
		}


		if (!$('#commentform #message').val()) {
			comment.message += 'Bitte geben Sie einen Kommenar ein.';
		}

        if ($('#commentform #code').val() == "") {
            comment.message += 'Bitte geben Sie die Sicherheitszahl ein. ';
            comment.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;
                        comment.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++;
                        comment.message += 'Bitte &uuml;berpr&uuml;fen Sie die Sicherheitszahl. ';
                    }

                    //console.log("comment.message.length: "+comment.message.length);

			        if (comment.message.length > 0) {
			            comment.showError();
			            saveComment(false);
			        }
			        else {
			            saveComment(true);
			        }

		        },
		        error: function (res) {
		            saveComment(false);
		        }
		    });

        }


	},
	showError: function () {
		$('#commentform .message').html($('<div class="error"></div>').append(comment.message)).fadeIn(200);
	}
};


function showMoreComments(start, step) {
    // Kommentare blättern
    //$('#morecomment').click(function (e) {
            var countcomments = parseInt($('#countcomments').val());
            $.ajax({
                type: "POST",
                url: 'action/getcomment.php',
                data: 'media_id='+$('#media_id').val()+'&start='+start+'&step='+step,
                dataType: 'json',
                complete: function (xhr) {

                    var res = xhr.responseText;
                    var res = eval('(' + res + ')');    // JSON-Objekt auswerten
                    resultCode = res.result_code;

                    var htmlneu = '';

                    for (i = 0; i < res.length; i++){
                        htmlneu += '<h5>'+ res[i].name+'</h5>'+res[i].kommentar_text+'<br />';
                        htmlneu += '<div class="line"></div>';
                    }
                    $('#comment').html(htmlneu);

                    var stop2 = start+step;

                    // Link zurück blättern
                    if (start >= step) {
                        var htmllink = '<a href="javascript:;" onclick="showMoreComments('+(start-step)+','+step+');">zur&uuml;ck</a>';
                        $('#lesscomment').html(htmllink);
                        $('#lesscomment').show();
                    } else {
                        $('#lesscomment').hide();
                    }

                    // Link weiter blättern
                    if (stop2 < countcomments) {
                      var htmllink = '<a href="javascript:;" onclick="showMoreComments('+stop2+','+step+');">weiter</a>';
                      $('#morecomment').html(htmllink);
                      $('#morecomment').show();
                    } else {
                      $('#morecomment').hide();
                    }

                },
                error: comment.error
            });
   // });





}


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 saveComment = function (commentValidate) {
            if (commentValidate) {
                $('#commentform .message').fadeOut(function () {
                    $('#commentform .message').removeClass('error').empty();
                });
                $('#commentform .title').html('Wird gespeichert ...');
                $('#commentform form').fadeOut(200, function () {
                    $('#commentform .loading').fadeIn(200, function () {
                        // data: "name=John&location=Boston",
                        $.ajax({
                            type: "POST",
                            url: 'action/do_addcomment.php',
                            //data: $('#commentform form').serialize() + '&action=send'+'&media_id='+$('#media_id').val(),
							              data: '&message='+ $('#message').val() + '&name='+ $('#name').val() + '&email='+ $('#email').val() + '&code='+ $('#code').val() + '&action=send'+'&media_id='+$('#media_id').val(),
                            dataType: 'html',
                            complete: function (xhr) {
                                $('#commentform .loading').fadeOut(200, function () {
                                    var res = xhr.responseText;
                                    if (res == 0) {

                                        // fehler
                                        var htmlneu = '<div class="div_text_allgemein">Es ist ein Fehler aufgetreten. </div>';
                                        $('#commentform').show();
                                        $('#commentshow').show();
                                        $('#commentform .title').hide();
                                        $('#commentform .message').html(htmlneu).fadeIn(200);
                                    }
                                    else if (res == 1){

                                        //res==1 ->ok
                                        var htmlneu = '<h5>' + $('#commentform #name').val() + '</h5>';
                                        htmlneu += $('#commentform #message').val()+'<br><br>';
                                        htmlneu += '<div class="line"></div>';

                                        $('#commentform .title').html(htmlneu);

                                    }


                                });
                            },
                            error: comment.error
                        });
                    });
                });
            }
            else {
                if ($('#commentform .message:visible').length > 0) {
                    $('#commentform .message div').fadeOut(200, function () {
                        $('#commentform .message div').empty();
                        comment.showError();
                        $('#commentform .message div').fadeIn(200);
                    });
                }
                else {
                    $('#commentform .message').animate({
                        height: '50px'
                    }, comment.showError);
                }

            }
}
