//skrypt obsługuje formularze rejestracji

//spolszczenie komunikatów validatora
jQuery.extend(jQuery.validator.messages, {
	required: "To pole jest wymagane.",
	remote: "Proszę o wypełnienie tego pola.",
	email: "Niepoprawny adres email.",
	url: "Proszę o podanie prawidłowego URL.",
	date: "Proszę o podanie prawidłowej daty.",
	dateISO: "Proszę o podanie prawidłowej daty (ISO).",
	number: "Proszę o podanie prawidłowej liczby.",
	digits: "Proszę o podanie samych cyfr.",
	creditcard: "Proszę o podanie prawidłowej karty kredytowej.",
	equalTo: "Proszę o podanie tej samej wartości ponownie.",
	accept: "Proszę o podanie wartości z prawidłowym rozszerzeniem.",
	maxlength: jQuery.format("Proszę o podanie nie więcej niż {0} znaków."),
	minlength: jQuery.format("Proszę o podanie przynajmniej {0} znaków."),
	rangelength: jQuery.format("Proszę o podanie wartości o długości od {0} do {1} znaków."),
	rangeValue: jQuery.format("Proszę o podanie wartości z przedziału od {0} do {1}."),
	range: jQuery.format("Proszę o podanie wartości z przedziału od {0} do {1}."),
	maxValue: jQuery.format("Proszę o podanie wartości mniejszej bądź równej {0}."),
	max: jQuery.format("Proszę o podanie wartości mniejszej bądź równej {0}."),
	minValue: jQuery.format("Proszę o podanie wartości większej bądź równej {0}."),
	min: jQuery.format("Proszę o podanie wartości większej bądź równej {0}.")
});

$().ready(function(){
	//validacja init
	$('#registration-form').validate({
		rules: {
			'service[name]': 'required',
			'service[street]': 'required',
			'service[postal]': 'required',
			'service[specialization]': 'required',
			'service[reception_phone]': 'required',
			'service[conact_phone]': 'required',
			'service[email]': {
				required: true,
				email: true
			}
		}
	});
	
	$('#contact-form').validate({
		rules: {
			'contact[od_imie_i_nazwisko]': 'required',
			'contact[od_email]': {
				required: true,
				email: true
			},
			'contact[od_telefon]': 'required',
			'contact[tresc]': 'required'
		}
	});

	//specjalizacje - pokazanie div'a z checkbox'ami
	var layerDiv = $('#specialisation_holder');
	$('#service_specialisation').click(function(evt, args){
		$(this).blur();
		if(layerDiv.is(':visible')) layerDiv.fadeOut(300);
		else {
			layerDiv.fadeIn(300);
			$.scrollTo('#specialisation_holder', 1000, {offset: -110});
		}
	}).keypress(function(){return false;});

	$('#specialisation_holder ul').each(function(){
		var letter = $(this).prev('strong').text();
		$(this).prev('strong').remove();
		$(this).wrap('<div class="list-wrapper"></div>');
		var parent = $(this).parent('.list-wrapper');
		parent.prepend('<strong>'+letter+'</strong>');
	});

	layerDiv.append('<div class="column-1" style="float: left;"></div><div class="column-2" style="float: left;"></div><div class="column-3"  style="float: left;"></div>');
	$('#specialisation_holder .list-wrapper').slice(0,8).appendTo('#specialisation_holder .column-1');
	$('#specialisation_holder .list-wrapper').slice(0,5).appendTo('#specialisation_holder .column-2');
	$('#specialisation_holder .list-wrapper').slice(0,5).appendTo('#specialisation_holder .column-3');

	//specjalizacje - zamknięcie div'a
	$('#specialisation_holder .close-layer').click(function(){
		layerDiv.fadeOut(300);
	});

	var checkAll = true;
	//specjalizacje - zaznaczenie/odznaczenie
	$('#specialisation_holder .select-all').click(function(){
		var input = $('#service_specialisation');
		var checkboxes = $(this).parent('div').parent('div').find('input');
		var labels = $(this).parent('div').parent('div').find('label');
		var labelsText = [];
		if(checkAll){
			checkboxes.attr('checked', true);
			for(var i=0; i<labels.length; i++){
				labelsText.push(labels.eq(i).text());
			}
			labelsText.pop();
			input.val(labelsText.join(', '));
			checkAll = false;
		}else{
			checkboxes.attr('checked', false);
			checkAll = true;
			input.val('');
		}
	});

	//specjalizaje - przerzucenie danych z checkboxów do inputa i na odwrót
	$('.checkbox_list input').click(function(){
		var input = $('#service_specialisation');
		var label = $(this).next('label').text();
		var valuesArr;
		if($(this).attr('checked')){
			valuesArr = input.val().split(', ');
			if(valuesArr[0]=='') valuesArr = [];
			if(valuesArr.indexOf(label)==-1) valuesArr.push( label );
			input.val(valuesArr.join(', '));
		}
		else {
			var startInd = input.val().indexOf(label);
			var endInd = input.val().indexOf(', ', startInd) + 2;
			var newVal;
			if(startInd!=-1){
				//usuwamy ostatni z wybranych, czyli taki który nie ma po sobie przecinka
				if(endInd==1) {
					newVal = input.val().split(', ');
					newVal.pop();
					newVal = newVal.join(', ');
				}
				else newVal = input.val().replace(input.val().substring(startInd, endInd), '');
				input.val(newVal);
			}
		}
	});

	// dopełnienie inputa z miastem
	var cityInput = $('#service_city');//#registration_klient_miejscowosc, #service_city
	cityInput.after('<div class="sugestBox"></div>');
	var sugestBox = cityInput.nextAll('.sugestBox');
	//console.log(sugestBox);
	var sugestBoxIndex;
	var sugestElems;
	var sugestBoxNo;
	
	cityInput.keyup(function(evt){
		if($(this).val().length>2 && evt.keyCode != 40 && evt.keyCode !=38){
			$.get('http://infomedic.loc/panel/services/AutocompleteCities/city/'+$(this).val(), {}, afterResponse);
			sugestBoxIndex = 0;
			console.log('http://infomedic.loc/services/AutocompleteCities/city/'+$(this).val());
			
		}
	});
	cityInput.keydown(function(evt){
		//console.log(evt.keyCode, sugestBox.is(':visible'));
		if((evt.keyCode != 40 && evt.keyCode !=38)|| !sugestBox.is(':visible')) return;
		else if(evt.keyCode==40 && sugestBoxIndex<sugestBoxNo-1){
			sugestElems.eq(sugestBoxIndex).removeClass('selected');
			sugestBoxIndex++;
			sugestElems.eq(sugestBoxIndex).addClass('selected');
			//console.log('dół', sugestBoxIndex, sugestBoxNo);
		}
		else if(evt.keyCode==38 && sugestBoxIndex>0){
			sugestElems.eq(sugestBoxIndex).removeClass('selected');
			sugestBoxIndex--;
			sugestElems.eq(sugestBoxIndex).addClass('selected');
			//console.log('góra');
		}
	});
	cityInput.blur(function(){
		sugestBox.hide();
		sugestBox.empty()
	});
	
	var afterResponse = function(data,success){
		if(success=='success') {
			sugestBox.empty();
			for(var i=0; i<5; i++){//data.length; i++){
				sugestBox.append('<div>dane ala z serwera'+data[i].nazwa_miasta+'</div>');
			}
			sugestElems = sugestBox.children('div');
			sugestElems.eq(0).addClass('selected');
			sugestElems.hover(function(){
				$(this).addClass('selected');
			}, function(){
				$(this).removeClass('selected');
			});
			sugestBoxNo = 5;//data.length;
			sugestBox.show();
		}
		
		//sugestBox.append('<div>jejejee</div>');
	};

    //walidacja formularza kontaktowego klienta
    $('#client-contact-form').validate({
		rules: {
			'question[client_name]': 'required',
			'question[client_email]': {
				required: true,
				email: true
			},
			'question[client_phone]': 'required',
			'question[question]': 'required',
            'question[captcha]': 'required'
		}
	});

});