$(function() {
		$(".datepicker").datepicker({yearRange: '1992:2012',dayNamesMin: ['Svē', 'Pir', 'Otr', 'Tre', 'Cet', 'Pie', 'Ses'] ,monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jūn', 'Jūl', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'],firstDay: 1, monthNames: ['Janvāris','Februāris','Marts','Aprīlis','Maijs','Jūnijs','Jūlijs','Augusts','Septembris','Oktobris','Novembris','Decembris'], dateFormat: 'yy/mm/dd', changeYear: true, changeMonth: true });
        $( "#form2_birth_date" ).datepicker( "option", "yearRange", '2004:2012' );
        $( "#form2_document_rdate" ).datepicker( "option", "yearRange", '2004:2012' );
        $( "#form1_passport_vdate" ).datepicker( "option", "yearRange", '2010:2022' );
});
$(document).ready(function(){
	
	//External links
	$('a[rel="external"]').attr('target', '_blank');

	var adr_nr=1;
	
	$('.help').tipsy({gravity: 's',fade: true});	
	//$('#form3').show();
    //$('#form2').hide();  
    //$('#form1').hide();  
    //$('#form0').hide(); 
    $('#to_lip').click(function(){window.location.href = 'http://www.lip.lv';}); 
    $('#to_rows').click(function(){window.location.href = 'http://registrs.lip.lv';}); 
	
    /* Input fileds limitation */
    //Numbers only    
    $("#form1_phone").keypress(function (e){        
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=44 && e.which!=59 && e.which!=32)            
            return false;        
    });
    $("#postal_code").keypress(function (e){        
        if( $(this).val().length==7 && e.which!=8)            
            return false; 
        //if( $(this).val().length<4 && e.which==8)            
          //  return false; 
        //if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=44 && e.which!=59 && e.which!=32)            
          //  return false;
    });
    
    //Person id function
    function person_id(field,e){
        //Do nothing if person code max length reached
        if(field.val().length>=12 && e!=8)
            return false;        
        
        //If 6th symbol try push "-"
        if(field.val().length==6 && e==45)
            return true;
         
        //If try to push non-numeric button
        if( e!=8 && e!=0 && (e<48 || e>57))
            return false;
        
        //Automatic add "-" if it need
        else if(e!=8){       
            if(field.val().length==6)              
               field.val(field.val()+'-');                      
        }   
    }
    $("#form1_person_id").keypress(function (e){ return person_id($(this),e.which);});
    $("#form2_person_id").keypress(function (e){ return person_id($(this),e.which);});
    
    //Dialog messages
    $("#error_message").dialog({
    	modal: true,
        autoOpen: false,
    	buttons: {
    		'Labi': function() {
    			$(this).dialog('close');
    		}
    	}
    }); 
    $('#check_data').dialog({    				   				
    	modal: true,
        autoOpen: false,
    	buttons: {					
    		'Labi': function() {
    			$(this).dialog('close');
    		}
    	}    			
    });    
    
	//bernudarzu nonemsanai
	$("#schools").change(function() 
    { 
		if($("#schools").val()==3){
			$("#school1").show();
			$("#school2").show();
			$("#school3").show();            
		}
		else if($("#schools").val()==2){
			$("#school1").show();
			$("#school2").show();
			$("#school3").hide();      
            $('.combo_school .bd_id'+$('#form2_school3').val()).show();
            $('#form2_school3').val(0);           
		}
		else{
			$("#school1").show();
			$("#school2").hide();
			$("#school3").hide();
            $('.combo_school .bd_id'+$('#form2_school3').val()).show();
            $('.combo_school .bd_id'+$('#form2_school2').val()).show();
            $('#form2_school3').val(0);
            $('#form2_school2').val(0);
		}        
    }); 
	
	//buttonam hoveris
	$('.button').hover(
	function(){ 
		$(this).addClass("ui-state-hover"); 
	},
	function(){ 
		$(this).removeClass("ui-state-hover"); 
	})
	
	//nospiesta 0. talak poga
	$('#forward0').click(function() {			
			$('h1').text("Informācija par vecāku (aizbildni), kura reģistrē bērnu Liepājas pirmsskolas izglītības iestāžu rindās");
			$('#div_buttons').show();
			$('#form1').show();
			$('#form0').hide();		
	});

	//nospiesta 1. poga.
	$('#forward1').click(function() {            
            //Form validation
            $('#form1 :input').removeClass('ui-state-error');
            var error=false;
            $.each(  ["form1_name","form1_surname","form1_person_id","adressadd1","adressadd2","form1_passport_nr","form1_passport_institution","form1_passport_rdate","form1_passport_vdate","form1_phone","form1_email"] , function(i,form_id){
                if($('#'+form_id).val()==''){
                    error=true;
                    $('#'+form_id).addClass('ui-state-error');	
                }  
            });
			if ( !( (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i).test( $('#form1_email').val() ) ) ){
				error=true;
				$('#form1_email').addClass('ui-state-error');
			}
            if(error==false){            
                //Disables datapicker icon                               
                $( ".datepicker" ).datepicker( "disable" );  				
    			$("#progress p").text("2 no 4");
    			$(".add_adress").hide();
    			$(".adress").css({width: '392px'});
    			$("#progress").progressbar('value' , 50 );
    			$('#buttons2').show();
    			$('#buttons1').hide();
    			$('#form1 :input').attr('disabled', true);    			
    			$('#check_data').dialog('open');
            }
            else
                $("#error_message").dialog('open');
			
	});
		
	//nospiesta 2 atpakal poga
	$('#back2').click(function() {
            //Enables datepicker icon
            $( ".datepicker" ).datepicker( "enable" );			
			$("#progress p").text("1 no 4");
			$(".add_adress:hidden").removeAttr('style').hide().fadeIn();		
			$(".adress").css({width: '323px'});
			$("#progress").progressbar('value' , 25 );
			$('#buttons2').hide();
			$('#buttons1').show();
			$('#form1 :input').attr('disabled', false);			
	});
	
	//nospiesta 2. talak poga
	$('#forward2').click(function() {
            //Enables datepicker icon
            $( ".datepicker" ).datepicker( "enable" );			
			$("#progress p").text("3 no 4");
			$(".add_adress:hidden").removeAttr('style').hide().fadeIn();		
			$(".adress").css({width: '323px'});
			$('#progress').progressbar('value' , 75 );
			$('h1').text("Informācija par bērnu, kuru vēlaties piereģistrēt Liepājas pirmsskolas izglītības iestāžu rindās");
			$('#buttons2').hide();
			$('#buttons3').show();
			$('#form1').hide();
			$('#form2').show();					
	});
	
	//nospiesta 3. atpakal poga
	$('#back3').click(function() {
            //Disables datapicker icon       
            $( ".datepicker" ).datepicker( "disable" );			
			$("#progress p").text("2 no 4");
			$(".add_adress").hide();
			$(".adress").css({width: '392px'});
			$("#progress").progressbar('value' , 50 );
			$('h1').text("Informācija par vecāku (aizbildni), kura reģistrē bērnu Liepājas pirmsskolas izglītības iestāžu rindās");
			$('#buttons3').hide();
			$('#buttons2').show();
			$('#form1').show();
			$('#form2').hide();					
	});
	
	//nospiesta 3. talak poga
	$('#forward3').click(function() {
            //Form validation
            $('#form2 :input').removeClass('ui-state-error');
            var error=false;
            $.each(  ["form2_name","form2_surname","form2_person_id","form2_birth_date","form2_gender","form2_nationality","form2_status","form2_language","form2_document_nr","form2_document_institution","form2_document_rdate","adressadd3","adressadd4","form2_school1","form2_lang1"] , function(i,form_id){
                if($('#'+form_id).val()=='' || $('#'+form_id).val()=='0'){
                    error=true;
                    $('#'+form_id).addClass('ui-state-error');	
                }
				if($('#form2_priority_1').val()==1){
					if($('#brother_name_1').val()==''){
						error=true;
						$('#brother_name_1').addClass('ui-state-error');
					}
				}
            });
            if($("#schools").val()>=2){
                $.each(  ["form2_school2","form2_lang2"] , function(i,form_id){
                    if($('#'+form_id).val()=='' || $('#'+form_id).val()=='0'){
                        error=true;
                        $('#'+form_id).addClass('ui-state-error');	
                    }  
                }); 
				if($('#form2_priority_2').val()==1){
					if($('#brother_name_2').val()==''){
						error=true;
						$('#brother_name_2').addClass('ui-state-error');
					}
				}
            }
            if($("#schools").val()==3){
                $.each(  ["form2_school3","form2_lang3"] , function(i,form_id){
                    if($('#'+form_id).val()=='' || $('#'+form_id).val()=='0'){
                        error=true;
                        $('#'+form_id).addClass('ui-state-error');	
                    }  
                }); 
				if($('#form2_priority_3').val()==1){
					if($('#brother_name_3').val()==''){
						error=true;
						$('#brother_name_3').addClass('ui-state-error');
					}
				}
            }            
            if(error==false){
                //Disables datapicker icon       
                $( ".datepicker" ).datepicker( "disable" );
    			$("#progress p").text("4 no 4");
    			$(".add_adress").hide();
    			$(".adress").css({width: '412px'});
    			$("#progress").progressbar('value' , 100 );
    			$('#buttons4').show();
    			$('#buttons3').hide();
    			$('#validation').text('Pārbaudiet vai visi dati pareizi!');
    			$('#form2 :input').attr('disabled', true);    			
    			$('#check_data').dialog('open');
            }
            else
                $("#error_message").dialog('open');
	});
	
	//nospiesta 4. atpakal poga
	$('#back4').click(function() {
            //Enables datepicker icon
            $( ".datepicker" ).datepicker( "enable" );
			$("#progress p").text("3 no 4");
			$(".add_adress:hidden").removeAttr('style').hide().fadeIn();		
			$(".adress").css({width: '343px'});
			$('#form2 :input').attr('disabled', false);	
			$("#progress").progressbar('value' , 75 );
			$('#buttons4').hide();
			$('#buttons3').show();						
	});
	
	//nospiesta pabeigt
	$('#forward4').click(function() {
            
            var post_data='add_entry=add_entry&parent_name='+$('#form1_name').val()+
            '&parent_surname='+$('#form1_surname').val()+'&parent_person_id='+$('#form1_person_id').val()+
            '&parent_declared_adress='+$('#adressadd1').val()+'&parent_real_adress='+$('#adressadd2').val()+
            '&parent_passport_nr='+$('#form1_passport_nr').val()+'&parent_passport_institution='+$('#form1_passport_institution').val()+
            '&parent_passport_rdate='+$('#form1_passport_rdate').val()+'&parent_passport_vdate='+$('#form1_passport_vdate').val()+
            '&parent_phone='+$('#form1_phone').val()+'&parent_email='+$('#form1_email').val()+
            '&child_name='+$('#form2_name').val()+'&child_surname='+$('#form2_surname').val()+
            '&child_person_id='+$('#form2_person_id').val()+'&child_birth_date='+$('#form2_birth_date').val()+
            '&child_gender='+$('#form2_gender').val()+'&child_nationality='+$('#form2_nationality').val()+
            '&child_status='+$('#form2_status').val()+'&child_language='+$('#form2_language').val()+
            '&child_document_nr='+$('#form2_document_nr').val()+'&child_document_institution='+$('#form2_document_institution').val()+
            '&child_document_rdate='+$('#form2_document_rdate').val()+'&child_declared_adress='+$('#adressadd3').val()+
            '&child_real_adress='+$('#adressadd4').val()+'&child_school_1='+$('#form2_school1').val()+'&child_schools='+$('#schools').val()+
            '&child_school_lang_1='+$('#form2_lang1').val()+'&child_school_priority_1='+$('#form2_priority_1').val()+'&brother_name_1='+$('#brother_name_1').val()+
            '&child_school_2='+$('#form2_school2').val()+'&child_school_lang_2='+$('#form2_lang2').val()+'&child_school_priority_2='+$('#form2_priority_2').val()+'&brother_name_2='+$('#brother_name_2').val()+
            '&child_school_3='+$('#form2_school3').val()+'&child_school_lang_3='+$('#form2_lang3').val()+'&child_school_priority_3='+$('#form2_priority_3').val()+'&brother_name_3='+$('#brother_name_3').val();
                        
            $.ajax({
                type: "POST",
                url: 'index.php',
                dataType: "json",                                                    
                data: post_data,                        
                success: function(data) {                         
                    if(data.error==false){
                        $('h1').text("");
                        $('#finish_email').text($('#form1_email').val());
            			$("#progress").hide();
            			$('#buttons4').hide();
						$('#time').html('Jūsu dati iesniegti '+data.text+'.');
            			$('#form3').show();
            			$('#form2').hide();                                       
                    }     
                    else
                        alert(data.text);                         
                }
            }); 								
	});

    $('#apply_rules').click(function () {
        $(this).attr('checked')? $('#forward0').attr('disabled', false) : $('#forward0').attr('disabled', true);
    });
    //$("#current_adress").hide();
    $('.check_adress').click(function(){
        if($('#'+this.id).attr('checked') == '')
            $('#adressad'+this.id).val('');     
        else       
            $('#adressad'+this.id).val($('#adressadd'+(this.id.charAt(1)-1)).val());
    });

    //Disallow choose the same school
    $('.combo_school').change(function(){        
        $('.bd_li').show();        
        
        $('.combo_school .bd_id'+$('#form2_school1').val()).hide();
        $('.combo_school .bd_id'+$('#form2_school2').val()).hide();
        $('.combo_school .bd_id'+$('#form2_school3').val()).hide();        
        
        $('#form2_school1 .bd_id'+$('#form2_school1').val()).show();
        $('#form2_school2 .bd_id'+$('#form2_school2').val()).show();
        $('#form2_school3 .bd_id'+$('#form2_school3').val()).show();   
		
		//Update Learning languages list menu
		var school_id=$(this).attr("name").replace("child_school_", "");
		$('#form2_lang'+school_id+' option').remove();
		if(schools[$('#form2_school'+school_id).val()]==0)
			$('#form2_lang'+school_id).append('<option value="0"></option><option value="lv">Latviešu</option>');		
		else if(schools[$('#form2_school'+school_id).val()]==1)
			$('#form2_lang'+school_id).append('<option value="0"></option><option value="ru">Mazākumtautību</option>');		
		else			
			$('#form2_lang'+school_id).append('<option value="0"></option><option value="lv">Latviešu</option><option value="ru">Mazākumtautību</option>');			
    });
	
	//Hide or dysplay brother/sister name field	
	$('.combo_priority').change(function(){
		var id=$(this).attr("name").replace("child_school_priority_", "");
		if($(this).val()==1)
			$('#brother_'+id).show();
		else
			$('#brother_'+id).hide();	
	});
    
});

	$(function() {
		$("#progress").progressbar({value: 25});
	});   

	$(function() {
		
		var street = $("#street"),
			flat = $("#flat"),			
			state = $("#state"),			
			city = $("#city"),			
			province = $("#province"),			
			willage = $("#willage"),			
			pre_city = $("#pre_city"),			
			house = $("#house"),			
			postal_code = $("#postal_code"),			
			allFields = $([]).add(street).add(flat).add(state).add(city).add(province).add(willage).add(pre_city).add(house).add(postal_code),
			reqFields = $([]).add(house).add(city).add(postal_code),
			tips = $("#validateTips");
            
		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}
		
		function checkFields(){
			var status=true;
            
            $.each(reqFields, function() { 
                if($(this).val()==''){
                    $(this).addClass('ui-state-error');                    
                    status=false;
                }
            });
            
            if(postal_code.val()=='LV-' || postal_code.val().length!=7){
                postal_code.addClass('ui-state-error');                    
                status=false;
            }
            
            //if(status==false) updateTips("Jāaizpilda visi lauki!");           
            return status;
		}
		
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 470,
			modal: true,
			buttons: {
				'Ievietot': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');									
					bValid = checkFields();		
                
					if (bValid) {
                        $('#adress'+adr_nr).val('');                        
                        
                        //CITY
                        if($("#city").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+$("#city").val()+', ');                  
                        
                        //WILLAGE
                        if($("#willage").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+$("#willage").val()+', ');                        
                        
                        //STREET
                        if($("#street").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+$("#street").val()+' iela, ');                                                  
                        
                        //HOUSE
                        if($("#house").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+$("#house").val()+' ');                                                  
                        
                        //FLAT
                        if($("#flat").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+'dz. '+$("#flat").val()+' ');                                                  
                        
                        //POSTAL CODE
                        if($("#postal_code").val()!='')                            
                                $('#adress'+adr_nr).val($('#adress'+adr_nr).val()+$("#postal_code").val());                                                  
                        
                       $(this).dialog('close');						
					}
				},
				'Aizvērt': function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.removeClass('ui-state-error');
			}
		});		
		
		$('.add_adress').click(function() {adr_nr=this.id;$('#dialog').dialog('open');})	
	});

