var Form = function() {
	this.validateEmail = function(elementValue){
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		return emailPattern.test(elementValue);
	}
	
	this.validateDate = function(dateStr, past) {
		var pattern = /^[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}$/;
		if(dateStr.match(pattern)) {
			var date_array = dateStr.split('-');
			var day = date_array[0];

			var month = date_array[1] - 1;
			var year = date_array[2];

			var source_date = new Date(year,month,day);

			if(year != source_date.getFullYear()) {
				return false;
			}
			if(month != source_date.getMonth())	{
				return false;
			}
			if(day != source_date.getDate()) {
				return false;
			}
			if(past) {
				var today = new Date();
				if(year >= today.getFullYear() && month >= today.getMonth() && day >= today.getDate()) {
					return false;
				}
			}
		} else {
			return false;
		}
		return true;
	}
	
	this.validateControlPesel = function(elementValue){
		var emailPattern = /^[0-9]{11}$/;
		if(emailPattern.test(elementValue)) {
			var arr = elementValue.split('');
			var ratio = parseInt(arr[0])*1 + parseInt(arr[1])*3 + parseInt(arr[2])*7 + parseInt(arr[3])*9 + parseInt(arr[4])*1 + parseInt(arr[5])*3 + parseInt(arr[6])*7 + parseInt(arr[7])*9 + parseInt(arr[8])*1 + parseInt(arr[9])*3;
			var controlInt = ratio%10;
			if(controlInt != 0) {
				controlInt = 10 - controlInt;
			}
			var controlSum = parseInt(elementValue.substr(10,1));
			if(controlInt == controlSum) {
				return true;
			} 
		}
		return false;
	}
	
	this.validatePhone = function(elementValue){
		var emailPattern = /^[0-9+-]{4,20}$/;
		return emailPattern.test(elementValue);
	}
	
	this.firstStepFrame = function() {
		if($('#first-time').attr('checked')) {
			$('div.alert p').hide();
			$('#alert1').show();
			$('#ofe_account').hide();
		} else if($('#second-time').attr('checked')) {
			$('div.alert p').hide();
			$('#alert2').show();
			$('#ofe_account').show();
		} else {
			$('div.alert p').hide();
			$('#alert0').show();
			$('#ofe_account').hide();
		}
	}
	
	this.validateField = function(element) {
		$('#' + element).blur(function() {
			var pattern = /^[_-]*$/;
			var pattern2 = /^[0-]*$/;
			if(pattern.test($(this).val())) {
				$(this).val($(this).attr('placeholder'));
			}
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder') || pattern2.test($(this).val())) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').addClass('err');
				$(this).attr('style', 'border: 1px solid #ff9966;');
			} else {
				$('#' + $(this).attr('id') + '-valid').removeClass('err');
				$('#' + $(this).attr('id') + '-valid').addClass('ok');
				$(this).attr('style', 'border: 1px solid #53c515;');
			}
		});
	}
	
	this.validateFieldBdate = function(element) {
		$('#' + element).blur(function() {
			var pattern = /^[_-]*$/;
			if(pattern.test($(this).val())) {
				$(this).val($(this).attr('placeholder'));
			}
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').addClass('err');
				$(this).attr('style', 'border: 1px solid #ff9966;');
			} else {
				var today = new Date();
				var tm = today.getMonth()+1;
				var ty = today.getFullYear();
				var date = $(this).val().split('-');
				var diff = ty - date[2];
				if((date[1] > tm)) diff--;
				if(isNaN(diff) || diff < 0 || diff > 110 || !form.validateDate($(this).val(), true)) {
					$('#' + $(this).attr('id') + '-valid').removeClass('ok');
					$('#' + $(this).attr('id') + '-valid').addClass('err');
					$(this).attr('style', 'border: 1px solid #ff9966;');
				} else {
					$('#' + $(this).attr('id') + '-valid').removeClass('err');
					$('#' + $(this).attr('id') + '-valid').addClass('ok');
					$(this).attr('style', 'border: 1px solid #53c515;');
				}
			}
		});
	}
	
	this.limitText = function(element, limit) {
		$('#' + element).keyup(function() {
			if ($(this).val().length > limit) {
				$(this).val($(this).val().substring(0, limit));
			} 
		});
	}
	
	this.validateInt = function(element) {
		$('#' + element).keydown(function(event) {
			// Allow only backspace and delete
			if ( event.keyCode == 46 || event.keyCode == 8 ) {
				// let it happen, don't do anything
			}
			else {
				// Ensure that it is a number and stop the keypress
				if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
					event.preventDefault(); 
				}   
				if(parseInt($(this).val()) >= 100) {
					event.preventDefault(); 
					$(this).val(100);
				}
			}
		});
		$('#' + element).blur(function() {
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').addClass('err');
				$(this).attr('style', 'border: 1px solid #ff9966;');
			} else {
				$('#' + $(this).attr('id') + '-valid').removeClass('err');
				$('#' + $(this).attr('id') + '-valid').addClass('ok');
				$(this).attr('style', 'border: 1px solid #53c515;');
			}
		});
	}
	
	this.validateField2 = function(element) {
		$('#' + element).change(function() {
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').addClass('err');
				$(this).attr('style', 'border: 1px solid #ff9966;');
			} else {
				$('#' + $(this).attr('id') + '-valid').removeClass('err');
				$('#' + $(this).attr('id') + '-valid').addClass('ok');
				$(this).attr('style', 'border: 1px solid #53c515;');
			}
		});
	}
	
	this.addressDataClear = function() {
		$('#saddress_correspondence_street').val('');
		$('#saddress_correspondence_homenumber').val('');
		$('#saddress_correspondence_flatnumber').val('');
		$('#saddress_correspondence_zipcode').val('');
		$('#saddress_correspondence_city').val('');
		$('#saddress_correspondence_country').val('');
		$('#div_saddress_correspondence_post').hide();
		$("#saddress_correspondence_zipcode").mask("99-999");
	}
	
	this.addressDataCopy = function() {
		$('#saddress_correspondence_street').val($('#saddress_street').val());
		$('#saddress_correspondence_homenumber').val($('#saddress_homenumber').val());
		$('#saddress_correspondence_flatnumber').val($('#saddress_flatnumber').val());
		$('#saddress_correspondence_zipcode').val($('#saddress_zipcode').val());
		$('#saddress_correspondence_city').val($('#saddress_city').val());
		$('#saddress_correspondence_country').val($('#saddress_country').val());
		$('#saddress_correspondence_post').val($('#saddress_post').val());
		if($('#saddress_country').val() != 'PL') {
			$('#div_saddress_correspondence_post').show();
			$("#saddress_correspondence_zipcode").unmask();
		} else {
			$('#div_saddress_correspondence_post').hide();
			$("#saddress_correspondence_zipcode").mask("99-999");
		}
	}
	
	this.showError = function(element, option) {
		$('#' + element + '-valid').addClass('err');
		if(option == 'radio') {
			$('[name="' + element + '"]').each(function() {
				$('label[for="' + $(this).attr('id') + '"]').attr('style', 'color: #ff3300');
			});
		} else {
			$('#' + element).attr('style', 'border: 1px solid #ff9966;');
		}
	}
	
	this.valid = function(element, validationType) {
		if(validationType == 'required') {
			if($('#'+element).val() == '' || $('#'+element).val() == $('#'+element).attr('placeholder')) {
				form.showError(element);
				return 1;
			}
		} else if(validationType == 'radio') {
			if($('[name="'+element+'"]:checked').val() == '' || $('[name="'+element+'"]:checked').val() == undefined ) {
				form.showError(element, 'radio');
				return 1;
			}
		} else if(validationType == 'pesel') {
			if($('#'+element).val() != '' && $('#'+element).val() != $('#'+element).attr('placeholder')) {
				if(!form.validateControlPesel($('#'+element).val())){
					form.showError(element);
					return 1;
				}
			} 
		} else if(validationType == 'phone') {
			if($('#'+element).val() != '' && $('#'+element).val() != $('#'+element).attr('placeholder')) {
				if(!form.validatePhone($('#'+element).val())){
					form.showError(element);
					return 1;
				}
			} 
		} else if(validationType == 'email') {
			if($('#'+element).val() != '' && $('#'+element).val() != $('#'+element).attr('placeholder')) {
				if(!form.validateEmail($('#'+element).val())){
					form.showError(element);
					return 1;
				}
			} 
		}
		return null;
		
	}
	
	this.validateFirstStep = function() {
		$('.validator').each(function() {
			$(this).removeClass('ok').removeClass('err');
			var element = $(this).attr('id').replace('-valid','');
			if($('#' + element)) {
				$('#' + element).removeAttr('style');
			} 
			$('[name="' + element + '"]').each(function() {
				if($('[name="' + element + '"]').attr('type') == 'radio') {
					$('label[for="' + $(this).attr('id') + '"]').removeAttr('style');
				}
			});
		});
		
		var err = 0;
//		err += form.valid('ntype', 'radio');
//		err += form.valid('sforname', 'required');
//		err += form.valid('sname', 'required');
//		err += form.valid('tbirthdate', 'required');
//		err += form.valid('sidentity_pesel', 'pesel');
//		err += form.valid('bsex', 'radio');
//		err += form.valid('saddress_city', 'required');
//		err += form.valid('saddress_zipcode', 'required');
//		
//		if($('#second-time').attr('checked')) {
//			err += form.valid('sname_ofe', 'required');
//			err += form.valid('saccount_number_ofe', 'required');
//		}
//		if($('#sidentity_pesel').val() == '' || $('#sidentity_pesel').val() == $('#sidentity_pesel').attr('placeholder')) {
//			err += form.valid('bidentity_type', 'radio');
//			err += form.valid('sidentity_name', 'required');
//		}
//		err += form.valid('sphone_number', 'phone');
//		err += form.valid('semail', 'email')
		//err += form.valid('bdata_process', 'radio');
		
		if(err == 0) {
			$('[placeholder]').each(function() {
				if($(this).val() == $(this).attr('placeholder')) {
					$(this).val(''); 
				}
			});
			$('#wniosek').submit();
//		} else {
//			$('html, body').animate({scrollTop: 0}, 0);
//			$('#dialog-message').html('<p>Prosze uzupełnić zaznaczone dane.</p>');
//			$( "#dialog-message" ).dialog({
//				modal: true,
//				width: 460,
//				buttons: {
//					OK: function() {
//						$(this).dialog( "close" );
//					}
//				}
//			});
		}
	}
	
	this.validateSecondStep = function() {
		$('[placeholder]').each(function() {
			if($(this).val() == $(this).attr('placeholder')) {
				$(this).val(''); 
			}
		});
		$('#wniosek').submit();
	}
	
	this.validateThirdStep = function() {
		$('.validator').each(function() {
			$(this).removeClass('ok').removeClass('err');
			var element = $(this).attr('id').replace('-valid','');
			if($('#' + element)) {
				$('#' + element).removeAttr('style');
			} 
			$('[name="' + element + '"]').each(function() {
				if($('[name="' + element + '"]').attr('type') == 'radio') {
					$('label[for="' + $(this).attr('id') + '"]').removeAttr('style');
				}
			});
		});
		
		var err = 0;
//		err += form.valid('bofe_exist', 'radio');
//		if($('#bofe_exist_T').is(':checked')) {
//			err += form.valid('bcommunity_asset', 'radio');
//		}
		
		if(err == 0) {
			$('#wniosek').submit();
//		} else {
//			$('html, body').animate({scrollTop: 0}, 0);
//			$('#dialog-message').html('<p>Prosze uzupełnić zaznaczone dane.</p>');
//			$( "#dialog-message" ).dialog({
//				modal: true,
//				width: 460,
//				buttons: {
//					OK: function() {
//						$(this).dialog( "close" );
//					}
//				}
//			});
		}
	}
	
	this.validateOfeBirthdate = function() {
		$('[name="tbirthdate"]').blur(function() {
			var pattern = /^[_-]*$/;
			if(pattern.test($(this).val())) {
				$(this).val($(this).attr('placeholder'));
			}
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').addClass('err');
				$(this).attr('style', 'border: 1px solid #ff9966;');
			} else {
				var today = new Date();
				var tm = today.getMonth()+1;
				var ty = today.getFullYear();
				var date = $(this).val().split('-');
				var diff = ty - date[2];
				if((date[1] > tm)) diff--;
				if(diff < 18 && diff >= 13) {
					$('#' + $(this).attr('id') + '-valid').removeClass('err');
					$('#' + $(this).attr('id') + '-valid').addClass('ok');
					$(this).attr('style', 'border: 1px solid #53c515;');
					$('#dialog-message').html('<p>W przypadku osób małoletnich wraz z formularzem umowy zostanie przesłany formularz "Zgoda przedstawiciela ustawowego na zawarcie umowy o członkostwo w Pekao OFE".</p>');
					$( "#dialog-message" ).dialog({
						modal: true,
						width: 460,
						buttons: {
							OK: function() {
								$(this).dialog( "close" );
							}
						}
					});
				} else if(isNaN(diff) || diff < 13 || date[2] < 1949 || !form.validateDate($(this).val(), true)) {
					$('#' + $(this).attr('id') + '-valid').removeClass('ok');
					$('#' + $(this).attr('id') + '-valid').addClass('err');
					$(this).attr('style', 'border: 1px solid #ff9966;');
				} else {
					$('#' + $(this).attr('id') + '-valid').removeClass('err');
					$('#' + $(this).attr('id') + '-valid').addClass('ok');
					$(this).attr('style', 'border: 1px solid #53c515;');
				}
			}
		});
	}
	
	this.validateDesignatedPesel = function(id) {
		$('#' + id).blur(function() {
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + $(this).attr('id') + '-valid').removeClass('ok');
				$('#' + $(this).attr('id') + '-valid').removeClass('err');
				$(this).removeAttr('style');
			} else {
				if(form.validateControlPesel($(this).val())){
					if(form.validateDate($('#tdesignated_tbirthdate_' + $(this).attr('id').substr(18)).val(), true)) {
						if(form.comparePeselAndDate($(this).val(), $('#tdesignated_tbirthdate_' + $(this).attr('id').substr(18)).val())) {
							$('#' + $(this).attr('id') + '-valid').removeClass('err');
							$('#' + $(this).attr('id') + '-valid').addClass('ok');
							$(this).attr('style', 'border: 1px solid #53c515;');
						} else {
							$('#' + $(this).attr('id') + '-valid').removeClass('ok');
							$('#' + $(this).attr('id') + '-valid').addClass('err');
							$(this).attr('style', 'border: 1px solid #ff9966;');
						}
					} else {
						$('#' + $(this).attr('id') + '-valid').removeClass('err');
						$('#' + $(this).attr('id') + '-valid').addClass('ok');
						$(this).attr('style', 'border: 1px solid #53c515;');
					}
				} else {
					$('#' + $(this).attr('id') + '-valid').removeClass('ok');
					$('#' + $(this).attr('id') + '-valid').addClass('err');
					$(this).attr('style', 'border: 1px solid #ff9966;');
				}
			}
		});
	}
	
	this.validatePesel = function(elem) {
		$('#' + elem).blur(function() {
			var pattern = /^[_]*$/;
			if(pattern.test($(this).val())) {
				$(this).val($(this).attr('placeholder'));
			}
			if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
				$('#' + elem + '-valid').removeClass('ok');
				$('#' + elem + '-valid').removeClass('err');
				$('#' + elem).removeAttr('style');
			} else {
				var p = $('#' + elem).val();
				if(form.validateControlPesel(p)) {
					if(form.validateDate($('#tbirthdate').val(), true)) {
						if(form.comparePeselAndDate(p, $('#tbirthdate').val())) {
							$('#' + elem + '-valid').removeClass('err');
							$('#' + elem + '-valid').addClass('ok');
							$('#' + elem).attr('style', 'border: 1px solid #53c515;');
						} else {
							$('#' + elem + '-valid').removeClass('ok');
							$('#' + elem + '-valid').addClass('err');
							$('#' + elem).attr('style', 'border: 1px solid #ff9966;');
						}
					} else {
						$('#' + elem + '-valid').removeClass('err');
						$('#' + elem + '-valid').addClass('ok');
						$('#' + elem).attr('style', 'border: 1px solid #53c515;');
					}
				} else {
					$('#' + elem + '-valid').removeClass('ok');
					$('#' + elem + '-valid').addClass('err');
					$('#' + elem).attr('style', 'border: 1px solid #ff9966;');
				}
			}
		});
	}
	
	this.comparePeselAndDate = function(pesel, date) {
		var year=parseInt(pesel.substr(0,2),10);
		var month=parseInt(pesel.substr(2,2),10);
		var day=parseInt(pesel.substr(4,2),10);
		var century;

		if(!isNaN(month)) {
			if(month>=1 && month<=12) {
				century=1900;	    
			} else if(month>=21 && month<=32) {
				century=2000;
				month-=20;	    
			} else if(month>=81 && month<=92) {
				century=1800;
				month-=80;
			} else if(month>=41 && month<=52) {
				century=2100;
				month-=40;	    
			} else if(month>=61 && month<=72) {
				century=2200;
				month-=60;	    
			}
			year+=century;
			if(day<10) {
				day = '0' + day;
			}
			if(month<10) {
				month = '0' + month;
			}
		}
		if((day + '-' + month + '-' + year) == date) {
			return true;
		} 
		return false;
	}
	
	this.addPerson = function() {
		var persons = $('#person-count').val();
		var fieldset = $('#fieldset-0').clone();
			
		$('#additional-persons').append('<fieldset class="form-fields" id="fieldset-' + persons + '"><div class="close_person" id="close_fieldset-' + persons + '"></div>' + fieldset.html() + '</fieldset>');
		
		$('#fieldset-' + persons).find('.clear_person').remove();
		$('#fieldset-' + persons).find('input').each(function() {
			$(this).attr('id', $(this).attr('id').replace('0', persons));
			$(this).removeClass('hasDatepicker');
			$(this).attr('style', '');
			$(this).val('');
		});
		$('#fieldset-' + persons).find('select').each(function() {
			$(this).attr('id', $(this).attr('id').replace('0', persons));
		});
		$('#fieldset-' + persons).find('span.validator').each(function() {
			$(this).attr('id', $(this).attr('id').replace('0-valid', persons + '-valid'));
			$(this).removeClass('err');
			$(this).removeClass('ok');
		});
		$('#fieldset-' + persons + ' #div_saddress_post_0').attr('id', 'div_saddress_post_' + persons);
		$('#sdesignated_country_' + persons).val('PL');
		$('#div_saddress_post_' + persons).hide();
		
		// maski
		$("#tdesignated_tbirthdate_" + persons).mask("99-99-9999");
		$("#sdesignated_pesel_" + persons).mask("99999999999");
		$("#sdesignated_zipcode_" + persons).mask("99-999");
		
//		var now = new Date();
//		
//		$("#tdesignated_tbirthdate_" + persons).datepicker({
//			changeMonth: true,
//			changeYear: true,
//			minDate: '01-01-1940',
//			maxDate: now.getDate() + '-' + (now.getMonth()+1) + '-' + now.getFullYear(),
//			yearRange: "1940:" + now.getFullYear(),
//			dateFormat: "dd-mm-yy"
//		});
		
		form.placeholderPerson('#fieldset-'+persons);
		
		// walidacja
		form.validateField('sdesignated_forname_' + persons);
		form.validateField('sdesignated_name_' + persons);
		form.validateDesignatedPesel('sdesignated_pesel_' + persons);
		form.validateFieldBdate('tdesignated_tbirthdate_' + persons);
		form.validateField('sdesignated_city_' + persons);
//		form.validateField('sdesignated_street_' + persons);
//		form.validateField('sdesignated_homenumber_' + persons);
		form.validateField('sdesignated_zipcode_' + persons);
		form.validateInt('fdesignated_percent_' + persons);
		
		$('#sdesignated_country_' + persons).change(function() {
			if($(this).val() != 'PL') {
				$(this).attr('id').substring(20);
				$('#div_saddress_post_' + $(this).attr('id').substring(20)).show();
				$("#sdesignated_zipcode_" + $(this).attr('id').substring(20)).unmask();
			} else {
				$('#div_saddress_post_' + $(this).attr('id').substring(20)).hide();
				$("#sdesignated_zipcode_" + $(this).attr('id').substring(20)).mask("99-999");
			}
		});
		
		$('#close_fieldset-' + persons).click(function() {
			$('#' + $(this).attr('id').substr(6)).remove();
			$('#person-count').val(parseInt($('#person-count').val())-1);
		});
			
		$('#person-count').val(parseInt(persons) + 1);
	}
	
	// all browser fix for html5 placeholder
	this.placeholderFix = function () {
		$('[placeholder]').focus(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
				input.removeClass('placeholder');
			}
		}).blur(function() {
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('placeholder')) {
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			}
		}).blur();
	}
	
	// all browser fix for html5 placeholder
	this.placeholderPerson = function (container) {
		$(container + ' [placeholder]').focus(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
				input.removeClass('placeholder');
			}
		}).blur(function() {
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('placeholder')) {
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			}
		}).blur();
	}
}

// create instance
var form = new Form();

