/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/*
 * form validation for PWB
 */

$(document).ready(function() {

	function isValidEmail(email) {
		return (email.length > 4 && email.indexOf('@') > 1 && email.indexOf('.') > 1 && (email.indexOf('@') < email.lastIndexOf('.')) && (email.lastIndexOf('.') != email.length-1));
	}


	// login form
	// check if the login is correct
	if ($('#loginform').length) {
		// prefill the form
		var prefilledLoginData = $.cookie('shbpermalogin');
		if (prefilledLoginData) {
			$('#loginusername').val(prefilledLoginData.substr(0, (prefilledLoginData.indexOf('|')-1)));
			$('#password').val(prefilledLoginData.substr((prefilledLoginData.indexOf('|')+2)));
			$('#permalogin').attr('checked', 'checked');	
		}
	
		var origError = $('#pwerror').html();
	
		$('#loginform').submit(function() {
			submitForm = true;

			$.ajax({
				url: '/index.php',
				async: false,
				dataType: 'html',
				data: {
					'type': 13,
					'validationType': 'logincheck',
					'validationUser': $('#loginusername').val(),
					'validationValue': $('#password').val()
				}, 
				success: function(data) {
					if (data == '2') {
						$('#pwerror').html('Ihr Konto ist gesperrt. Bitte kontaktieren Sie unser Team.').show();
						submitForm = false;
					} else if (data != '1') {
						$('#pwerror').html(origError).show();
						$('#password').addClass('error');	
						submitForm = false;
					}
				}
			});

			// store data in a cookie
			if (submitForm && $('#permalogin').attr('checked')) {
				$.cookie('shbpermalogin', $('#loginusername').val() + ' | ' + $('#password').val(), { expires: 365, path: '/'});
			} else {
				$.cookie('shbpermalogin', null, { path: '/'});
			}
			
			return submitForm;
		});
		
		// check if registration code exists
		$('#regcodeform').submit(function() {
			submitForm = true;

				// first check if we can submit the login form
			if ($('#loginusername').val() != '' && $('#password').val() != '') {
				$('#loginform').submit();
			}

			if ($('#regCode').val().length) {
				$.ajax({
					url: '/index.php',
					async: false,
					dataType: 'html',
					data: {
						'type': 13,
						'validationType': 'registercode',
						'validationValue': $('#regCode').val()
					}, 
					success: function(data) {
						if (data != '1') {
							$('#regerror').show();
							$('#regCode').addClass('error');	
							submitForm = false;
						}
					}
				});
			}
			return submitForm;
		});
		
	}


	// registration form
	if ($('form#registration').length) {
		$('#registration').submit(function() {
			submitForm = true;

			$('input', $(this)).removeClass('error');
			$('.registererror', $(this)).remove();
			$(this).find('.required').each(function() {
				if ($(this).val() == '') {
					$(this).addClass('error');
					$(this).parent().after('<div class="registererror" style="position: static; display: block;">Dieses Feld ist ein Pflichtfeld. Bitte überprüfen Sie Ihre Eingabe.</div>');
					submitForm = false;
				}
			});
			
			// check if the username exists
			username = $('#uid3').val();
			if (username.length && username.length < 6) {
				$('#uid3').parent().next('.registererror').remove();
				$('#uid3').parent().after('<div class="registererror" style="position: static; display: block;">Der Benutzername muss aus mindestens 6 Zeichen bestehen.</div>');
				submitForm = false;
			} else if (username.length) {
				$.ajax({
					url: '/index.php',
					async: false,
					dataType: 'html',
					data: {
						'type': 13,
						'validationType': 'registerusername',
						'validationValue': username
					}, 
					success: function(data) {
						if (data == '1') {
							$('#uid3').parent().next('.registererror').remove();
							$('#uid3').parent().after('<div class="registererror" style="position: static; display: block;">Benutzername bereits vergeben.</div>');			
							submitForm = false;
						}
					}
				});
			}

			// check if the password has the right format
			var pass = $('#uid4').val();
			if (pass.length && (pass.length < 6 || !(/\d/.test(pass)))) {
				$('#uid4').parent().next('.registererror').remove();
				$('#uid4').parent().after('<div class="registererror" style="position: static; display: block;">Bitte mindestens 6 Zeichen inkl. mindestens einer Zahl</div>');
				submitForm = false;
			}
			
			// check if the password matches
			if ($('#uid4').val() != $('#uid5').val()) {
				$('#uid5').parent().next('.registererror').remove();
				$('#uid5').parent().after('<div class="registererror" style="position: static; display: block;">Die beiden Passwörter stimmen nicht überein.</div>');
				submitForm = false;
			}
			
			// check if there is a valid email address
			if ($('#uid12').val().length && !isValidEmail($('#uid12').val())) {
				$('#uid12').parent().next('.registererror').remove();
				$('#uid12').parent().after('<div class="registererror" style="position: static; display: block;">Dies ist keine gültige Email-Adresse.</div>');
				submitForm = false;
			} else if ($('#uid12').val() != '') {
				$.ajax({
					url: '/index.php',
					async: false,
					dataType: 'html',
					data: {
						'type': 13,
						'validationType': 'registeremail',
						'validationValue': $('#uid12').val()
					}, 
					success: function(data) {
						if (data == '1') {
							$('#uid12').parent().next('.registererror').remove();
							$('#uid12').parent().after('<div class="registererror" style="position: static; display: block;">Email-Adresse bereits vergeben.</div>');			
							submitForm = false;
						}
					}
				});
			}

			// check if the privacy checkbox was set
			if (!$('#check_uid2_0').attr('checked')) {
				$('#check_uid2_0').parent().next('.registererror').remove();
				$('#check_uid2_0').parent().after('<div class="registererror" style="position: static; display: block;">Bitte bestätigen Sie die Datenschutzbedingungen.</div>');
				submitForm = false;
			}
			
			return submitForm;
		});
	
	}
	

	// edit profile form
	if ($('form#editprofile').length) {
		$('#editprofile').submit(function() {
			submitForm = true;

			$('input', $(this)).removeClass('error');
			$('.registererror', $(this)).remove();
			$(this).find('.required').each(function() {
				if ($(this).val() == '') {
					$(this).addClass('error');
					$(this).parent().after('<div class="registererror" style="position: static; display: block;">Dieses Feld ist ein Pflichtfeld. Bitte überprüfen Sie Ihre Eingabe.</div>');
					submitForm = false;
				}
			});
			

			// check if the password has the right format
			var pass = $('#uid23').val();
			if (pass.length && (pass.length < 6 || !(/\d/.test(pass)))) {
				$('#uid23').parent().next('.registererror').remove();
				$('#uid23').parent().after('<div class="registererror" style="position: static; display: block;">Bitte mindestens 6 Zeichen inkl. mindestens einer Zahl</div>');
				submitForm = false;
			}
			
			// check if the password matches
			if ($('#uid23').val() != $('#uid24').val()) {
				$('#uid24').parent().next('.registererror').remove();
				$('#uid24').parent().after('<div class="registererror" style="position: static; display: block;">Die beiden Passwörter stimmen nicht überein.</div>');
				submitForm = false;
			}
			
			// check if there is a valid email address
			email = $('#uid30').val();
			if (email.length && !isValidEmail(email)) {
				$('#uid30').parent().next('.registererror').remove();
				$('#uid30').parent().after('<div class="registererror" style="position: static; display: block;">Dies ist keine gültige Email-Adresse.</div>');
				submitForm = false;
			} else {
				$.ajax({
					url: '/index.php',
					async: false,
					dataType: 'html',
					data: {
						'type': 13,
						'validationType': 'registeremail',
						'validationValue': email
					}, 
					success: function(data) {
						if (data == '1') {
							$('#uid30').parent().next('.registererror').remove();
							$('#uid30').parent().after('<div class="registererror" style="position: static; display: block;">Email-Adresse bereits vergeben.</div>');
							submitForm = false;
						}
					}
				});
			}
			return submitForm;
		});
	
	}


	// check the forgot password form
	if ($('#sendresetpasswordform').length) {
		$('#sendresetpasswordform').submit(function() {
			submitForm = true;

			// check if the password has the right format
			usernameField = $('.forgotemail', $(this));
			if (usernameField.val() != '') {
				$.ajax({
					url: '/index.php',
					async: false,
					dataType: 'html',
					data: {
						'type': 13,
						'validationType': 'isuserlocked',
						'validationValue': $(usernameField).val()
					}, 
					success: function(data) {
						if (data == '1') {
							$(usernameField).parent().next('.registererror').remove();
							$(usernameField).parent().after('<div class="registererror" style="position: static; display: block;">Ihr Konto ist gesperrt. Bitte kontaktieren Sie unser Team.</div>');			
							submitForm = false;
						}
					}
				});
			}
			
			return submitForm;
		});
	}




	// check the forgot password form
	if ($('#resetpasswordform').length) {
		$('#resetpasswordform').submit(function() {
			submitForm = true;

			// check if the password has the right format
			pass1field = $('.pw1', $(this));
			pass2field = $('.pw2', $(this));
			var pass = pass1field.val();
			if (pass.length && (pass.length < 6 || !(/\d/.test(pass)))) {
				$(pass1field).parent().next('.registererror').remove();
				$(pass1field).parent().after('<div class="registererror" style="position: static; display: block;">Bitte mindestens 6 Zeichen inkl. mindestens einer Zahl</div>');
				submitForm = false;
			}
			
			// check if the password matches
			if ($(pass1field).val() != $(pass2field).val()) {
				$(pass2field).parent().next('.registererror').remove();
				$(pass2field).parent().after('<div class="registererror" style="position: static; display: block;">Die beiden Passwörter stimmen nicht überein.</div>');
				submitForm = false;
			}
			
			return submitForm;
		});
	}



	// check the infomaterial order form
	if ($('#submitInfomaterial').length) {
	
		//$('#submitInfomaterial').parents('.rightcontent').wrapInner('<form action="" method="post" id="infoMaterialForm"></form>');
	
		$('#submitInfomaterial').click(function() {
			var success = true;
			if ($('#infoname').val() == '') {
				$('#infoname').addClass('error');
				$('#infonameerror').show();
				success = false;
			} else {
				$('#infoname').removeClass('error');
				$('#infonameerror').hide();
			}
	
			if ($('#infostr').val() == '') {
				$('#infostr').addClass('error');
				$('#infostrerror').show();
				success = false;
			} else {
				$('#infostr').removeClass('error');
				$('#infostrerror').hide();
			}
	
			if ($('#infoplz').val() == '') {
				$('#infoplz').addClass('error');
				$('#infoplzerror').show();
				success = false;
			} else {
				$('#infoplz').removeClass('error');
				$('#infoplzerror').hide();
			}

			if (success) {
				var url = window.location.href;
				var data = $('.rightcontent :input').serializeArray();
				$.get(url, data);
				$(this).next().show();
			}
		
		});
	}




	// realty, make sure that the form is submitted (and thus, the 
	// 
	$('a.savefavorites').click(function(evt) {
		var frm = $(document.forms['tx_realty_pi1_list_view']);
		var data = frm.serialize();
		$.post(frm.attr('action'), data, function(res) {});
		$(this).removeClass('merkzettel').addClass('merkzettel_saved').html('Auf der Merkliste gespeichert');
		evt.preventDefault();
	});

	if ($('form#realtyfavorites').length) {
		var frm = $('form#realtyfavorites');
		$('input:checkbox').each(function() {
			$(this).attr('checked', true);
		});
		
		frm.submit(function() {
			$('input:checkbox').each(function() {
				if ($(this).attr('checked')) {
					$(this).attr('checked', false);
				} else {
					$(this).attr('checked', true);
				}
			});
		});
	}
	
	
	// go back one (or two) pages to the last search page when on the favorites list
	$('a.go').click(function() {
	
		if (document.referrer.indexOf('suche') > 0) {
			history.go(-1);
		} else {
			history.go(-2);	
		}
		return false;
	});

	// fix the glossary default
	if ($('#searchform_select_tx_sgglossary_pi1').length) {
		var list = $('ul', $('#searchform_select_tx_sgglossary_pi1')).first();
		if (list.find('.ac').length == 0) {
			list.find('li.other').first().addClass('ac');
		}
	}

});
