$(document).ready(function(){

	var selects_visibility = false;
	var valid_market = false;	
	// var valid_market_message = 'Select market';
	// var extra_destination_message = 'Select e-mail destination';
	// var globalcharmess = 'Por favor insira os nomes do bloco #_bloco_, num máximo de _limite_ caracteres.';

    $('.dialog-messages').hide();
	
    $('a.redressmessage').live('click', function(){ 
	    $('#redressmessage').dialog({
	    	modal: true,
	    	buttons: {
	    		Ok: function() {
	    			$(this).dialog( "close" );
	    		}
			}
		});	  
    });
    
	$.validator.addMethod(
	        "regex",
	        function(value, element, regexp) {
	            var check = false;
	            var re = new RegExp(regexp);
	            return this.optional(element) || re.test(value);
	        }
	);   

    $( "#login-form" ).dialog({
        modal: true,
        closeOnEscape: false,
        buttons: {
            "Login": function() {
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "form_common.php",
                    data: {
                        action: 'checkLogin', 
                        username: $('#username').val(),
                        password: $('#password').val()
                    }, 
                    success: function(msg) {
                        if (msg.success == true) {
                            $("#login-form").dialog('close');

                        } else {
                            $('#dialog-ko').dialog({
                                modal:true,
                                buttons: {
                                    ok: function() {
                                        $(this).dialog('close');
                                    }
                                }
                            });

                        }
                        
                    }
                });
            },
            Cancel: function() {
            	$('#username').val('');
            	$('#password').val('');            	
                return false;
            }            
         }
    });

    $('select#market').change(function() {
        var market = $(this).val();

        $("#emailExtra").remove();

        if (market == 'ES' || market == 'es') {
            $('#spn').hide();
            $('#spn > input').removeAttr('name');

        } else if (market == 'BR' || market == 'br') {
            $('.lblBr').html('Sobrenome <span class="requer">*</span>'); 


        } else {
            $('#spn').show();
            $('#spn > input').attr('name','fldPin');
            $('.lblBr').html('Apelido <span class="requer">*</span>'); 

        }

        $.ajax({
            type: "POST",
            url: "form_common.php",
            data: {action: 'getMarketLanguages', market: market}, 
            success: function(data) {
                $('#language').html("<option value=''>Seleccione a lingua</option>");
                $('#language').append(data);
            }
        });
    });

    if ( $('select#market').val() != '') {
        $('select#market').trigger('change');
    }

    $('#countries').change(function() {
        var market = $(this).val();
        valid_market = true;
        $.ajax({
            type: "POST",
            url: "form_common.php",
            data: {action: 'getExtraDestinations', market: market}, 
            success: function(data) {
                if (data) {
                	// if(market != 'ES' && market != 'es'){
	                    var formExtra = '<fieldset id="emailExtra">';
	                    formExtra += '<label class="paraOnde">Para onde deseja enviar o seu pedido?</label>';
	                    formExtra += '<select name="emailextra" id="emailextra">';
	                    formExtra += '<option disabled="disabled">--</option>';
	                    formExtra += data;
	                    formExtra += '</select>';
	                    formExtra += '<br /></fieldset>';
	                    if($('#emailExtra')) { $('#emailExtra').remove(); }
	                    $('#resetForm').before(formExtra);
	                    doOnde();
                	// } else { if($('#emailExtra')) { $('#emailExtra').remove(); } }
                }
            }
        });
        
        /*
        if (market == 'BR' || market == 'br') {
            $('.lblBr').html('Sobrenome <span class="requer">*</span>');
        } else {
            $('.lblBr').html('Apelido <span class="requer">*</span>');
        }        
        */
        
        // if(market == 'es') { $('#spn').hide();}
        
    });
    
    $('#resetForm').click(function(){ $('label.error').hide(); });

    $('[id^="hsao_"]').live('click', function(){
			var id = $(this).attr('id').split('_')[1];    	
			if(selects_visibility){
				$('.inputOD').removeClass('hide').addClass('show').show();
				$('select.selectsOD').removeClass('show').addClass('hide');
				selects_visibility = false;
			} else {
				$('.inputOD').removeClass('show').addClass('hide').hide();
				$('select.selectsOD').removeClass('hide').addClass('show');
				selects_visibility = true;				
			}
    });

    $('[id^="fldOrigA_"]').live('focus', function(event) {
        var id = $(this).attr('id').split('_')[1];

        $(this).autocomplete({
            source: 'form_common.php?action=getOriginsJson' + '&language=' + lang,
            minLength: 3,
            select: function(event, ui) {
                $('#fldOrig_' + id).val(ui.item.id);
                $('#fldOrigL_' + id).find('[value=' + ui.item.id + ']').attr('selected','selected');
                $('#fldDestA_' + id).removeAttr('disabled');
            }
        });        
    });

    $('[id^="fldDestA_"]').live('focus', function(event) {
        var id = $(this).attr('id').split('_')[1];
        var originId = $('#fldOrig_' + id).val(); 

        $(this).autocomplete({
            source: 'form_common.php?action=getDestinationsJson&origin=' + originId + '&language=' + lang,
            select: function(event, ui) {
                $('#fldDestL_' + id).find('[value=' + ui.item.id + ']').attr('selected','selected');            	
                $('#fldDest_' + id).val(ui.item.id);
            }
        });        
    });

    $('[id^="fldOrigL_"]').live('change', function() {
        var origin = $(this).val();
        var id = $(this).attr('id').split('_')[1];
        $('#fldOrig_' + id).val(origin);
        $('#fldOrigA_' + id).val($(':selected', $('#fldOrigL_' + id)).text());
    
        $.ajax({
            type: "POST",
            url: "form_common.php",
            data: {action: 'getDestinations', origin: origin, language: lang}, 
            success: function(data) {
                $('#fldDestL_' + id).html('<option disabled="disabled">' +  select_destination + '</option>');
                $('#fldDestL_' + id).append(data);
            }
        });
    });
    
    $('[id^="fldDestL_"]').live('change', function() {
        var dest = $(this).val();
        var id = $(this).attr('id').split('_')[1];
        $('#fldDest_' + id).val(dest);
        $('#fldDestA_' + id).val($(':selected', $('#fldDestL_' + id)).text());        
    });    
    
    // -- returns char limite message
    
	function getCharMessage(bloco,limite) { return globalcharmess.replace(/_bloco_/i,bloco).replace(/_limite_/i,limite); }
	
	// ---

    // Buttons
    //$("input:button, input:submit").button();

    $("#groupForm, #namesForm").submit(function(){

		if(!valid_market) {
			alert(valid_market_message);
			return false;
		}

		//-- validate name fields
		
		if($(this).attr('id') == 'namesForm') {

			var adult_cl = 53, child_cl = 45, cl_divided_by = 2;	
			var clmessage = '', hasalert = false;
			var cldestination = $("input[name='fldItn']:checked").val();
				
			$('div.passenger').each(function(){
				
				var namepos = $(this).attr('id').split('_')[1];
				var infantop = $('#fldHasInf_' + namepos);
				var chd_year = $('#fldBirthDateYear_' + namepos).val();
				var templimit = adult_cl;
				var adult_fld = infant_fld = '';				
								
				adult_fld = $('#fldName_' + namepos).val() + $('#fldSurname_' + namepos).val();
				infant_fld = $('input[name=fldInfName_' + namepos + ']').val() + $('input[name=fldInfLastName_' + namepos + ']').val();
				if(cldestination == 'US') { 
					adult_fld += $('#fldSecondname_' + namepos).val();
					infant_fld += $('input[name=fldInfSecondName_' + namepos + ']').val();
				}
				
				if(chd_year == '--') { 
					if($(':selected', infantop).val() == 'yes') {  templimit = 39; } 
					else { templimit = adult_cl; }
				} else { templimit = child_cl; }
				
				var adult_infant = adult_fld + infant_fld;
				
				// alert(adult_infant);
				// alert(adult_infant.length);
				
				if(adult_infant.length > templimit) { hasalert = true; clmessage += getCharMessage(namepos,templimit) + "\n"; }

			});
			
			if(hasalert) { alert(clmessage); return false; }
		}
		
		// --
		
		if($('#emailExtra') && ($(':selected', $('#emailextra')).val() == "--")) {
			alert(extra_destination_message);
			return false;			
		}

        if ( $(this).valid()) {

            // $(":submit", $(this)).attr('disabled', 'disabled');
            var formData = $(this).serialize();

            $.ajax({
                type: "POST",
                dataType: 'json',
                url: "form_common.php",
                data: {
                    action: 'submitForm', 
                    market: $(':selected', $('#countries')).val(),
                    language: $(':selected', $('#languages')).val(),
                    formType: $('#formType').val(),
                    formData: $(this).serialize()
                }, 

                success: function(msg) {
                    if (msg.success == true) {
                        $( "#dialog-form-ok" ).dialog({
                            modal: true,
                            buttons: {
                                Ok: function() {
                                    $( this ).dialog( "close" );
                                }
                            }
                        });
                    
                    } else {
                        $( "#dialog-form-ko" ).dialog({
                            modal: true,
                            buttons: {
                                Ok: function() {
                                    $( this ).dialog( "close" );
                                }
                            }
                        });
                    }
                }
            });

            return false;

        } else {

        }

        return false;
    });

    $(".dateISO").datepicker({ 
    	dateFormat: 'yy/mm/dd', 
    	minDate: new Date(),
    	maxDate: "+361d"
    });
    
    $(".dateISO").live('focus', function(){
        $(this).val("");
    });

    // ------------------------
    // form_grupos
    //

    $("#groupForm").validate({

        rules: {
            fldAgyname: {
                maxlength: 20,
                regex: "^[a-zA-Z]{1,20}$"
            },
            
            fldGroupname: {
                maxlength: 40,
                regex: "^[a-zA-Z]{1,40}$"
            },            

            fldPhone: {
                maxlength: 14,
                digits: true
            },
            
            fldIata: {
                maxlength: 8,
                digits: true
            },

            fldNrpassengers: {
                max: 98,
                digits: true                  
            },

            fldFlightni_1: {
                maxlength: 2
            },

            fldFlightn_1: {
                maxlength: 4,
                digits: true
            },
            
            fldFlightn_1: {
                minlength: 3,
                digits: true
            }
            
        }
    });


    // Add Flight
    $("#addFlight, .addFlight").live('click', function() {

        var flight = $(".flight:first").clone(); 
        var lastId = parseInt($(".flight:last").attr("id").split("_")[1]);
        var newId = lastId + 1;
		
        flight.attr("id", "flight_" + newId);
        $('label.error', flight).each(function(){
            $(this).remove(); 
        });

        $("legend", flight).html(flight_label_text + newId);
        $(".dateISO", flight).removeClass('hasDatepicker');

        $('.destination', flight).attr('disabled', 'disabled');
    
        $(":input", flight).each(function(){
            reCalculateIds($(this), newId, true);
        });
        
        $("a.hsao", flight).each(function(){
            reCalculateIds($(this), newId, true);
        });        

        $("fieldset.flight:last").after(flight);

        $('#fldFlightni_' + newId, flight).rules('add', {
            maxlength: 2
        });

        $('#fldFlightn_' + newId, flight).rules('add', {
            maxlength: 4,
            digits: true
        });

        $(".dateISO").each(function(){
            $(this).datepicker({dateFormat: 'yy/mm/dd',minDate: new Date(),maxDate: "+361d" });
        });

        //$("input:button, input:submit").button();
        return false;

    }); 

    $(".copyFlight").live('click', function(){
        
        var flight = $(this).parent().clone();
        var lastId = parseInt($(".flight:last").attr("id").split("_")[1]);
        var newId = lastId + 1;

        flight.attr("id", "flight_" + newId);
        $('label.error', flight).each(function(){
            $(this).remove(); 
        });

        $(".copyFlight", flight).removeClass('ui-state-hover');


        $("legend", flight).html("Voo #" + newId);
        $(".dateISO", flight).removeClass('hasDatepicker');
    
        $(":input", flight).each(function(){
            reCalculateIds($(this), newId, false);
        });

        $("fieldset.flight:last").after(flight);

        $('#fldFlightni_' + newId, flight).rules('add', {
            maxlength: 2
        });

        $('#fldFlightn_' + newId, flight).rules('add', {
            maxlength: 4,
            digits: true
        });

        $(".dateISO").each(function(){
            $(this).datepicker({ dateFormat: 'yy/mm/dd'});
        });

        //$("input:button, input:submit").button();

        return false;

    })

    // Remove Flight
    $(".removeFlight").live("click", function(){
        if ($(".flight").length >= 2) {
            $(this).parent().remove();

            var i = 1;
            $('.flight').each(function() {
                $('legend', $(this)).html(flight_label_text + '' + i);
                i++;
            });

            var newId = 1;
            $(".flight").each(function(){
                reCalculateIds($(this), newId);
                newId = newId + 1;
            });
        }
    });


    // ------------------------
    // form_nomes 
    //

    // Validation
    $("#namesForm").validate({
    });

    
    // Radio com os destinos
    $("input[name='fldItn']:radio").live('change', function(){
        var selected = $(this).val(); 
        
        if (selected != 'XX') {
            $('.notOthers').show()

            $(".others").each(function(){
                $(this).removeAttr('name');
                $(this).hide();
            });

            if( $('.passenger > .passengerExtra').length == 0) { 

                //$('.passenger > fieldset').after(extraInfo);
                $('.passenger').each(function() {
                    var extraInfo = $('#passengerExtra_1').clone();

                    if(selected != 'US') {
                        $('.usa', extraInfo).hide();
						$('.usa', '.name').hide();
                    } else {
						$('.usa', '.name').show();
                    }

                    extraInfo.removeAttr('id');
                    extraInfo.show();
                    
                    $(':input', extraInfo).each(function() {

                        if ( !$(this).hasClass('usa') ) {
                            var id = $(this).attr('id');
                            $(this).attr('name', id);
                        }
                    });

                    var newId = $(this).attr('id').split('_')[1];
                    $('fieldset:first', $(this)).after(extraInfo); 

                    $(':input', $(this)).each(function() {
                        reCalculateIds($(this), newId);
                    });

                });

            } else {

                if (selected == 'US') {

                    $('.usa', '.passenger > .passengerExtra').show();
					$('.usa', '.passenger > .baby').show();
					$('.usa', '.name').show();
                    $('.passenger input.usa').each(function() {
                        var id = $(this).attr('id');
                        $(this).attr('name', id);
                    });

                } else {
					
                    $('.usa', '.passenger > .passengerExtra').hide();
					$('.usa', '.passenger > .baby').hide();
					$('.usa', '.name').hide();					
                    $('input.usa').each(function() {
                        $(this).removeAttr('name');
                    });
                }
            }

        } else {
           $('.passenger > .passengerExtra').remove(); 
           $('.notOthers').hide();
            
			$('.usa', '.name').hide();
            
            $(".others").each(function(){
                var id = $(this).attr('id');
                $(this).attr('name', id);
                $(this).show();
            });
            
        }

    });


    // Passageiro com bebé
    $("select.passengerWithBaby").live('change', function() {
        var passenger = $(this).parent().parent().parent();
        newId = $('fieldset', passenger).attr('id').split('_')[1];

        var destination = $("input[name='fldItn']:checked").val();

        if ($(this).val() == 'yes') {

            var newBaby = $('#baby_1').clone(); 
            newBaby.removeAttr('id');
            newBaby.toggle();


            $(':input', newBaby).each(function(){
                reCalculateIds( $(this), newId, true);

                /*
                if ( !$(this).hasClass('usa') ) {
                    var id = $(this).attr('id');
                    $(this).attr('name', id);
                }
                */
            });

            if (destination != 'US') {
                $('.usa', newBaby).hide();
                $('.usa', newBaby).removeAttr('name');
            }
            
            if (destination == 'XX') {
                $('.notOthers', newBaby).hide();
                $('.notOthers', newBaby).removeAttr('name');
            }

            // TODO: Validações
            /*
            $('#fldInfName_' + newId, newBaby).rules('add', {
                maxlength: 2 
            });
            */

            newBaby.attr('id', 'baby_' + newId);
            $('fieldset:last', passenger).after(newBaby);

        } else {
            $('.baby', passenger).remove();
        }
    });


    // Add Nomes
    $("#addNames").click(function(){
        var amount = $(this).prev().val();
        var i = 0;
        
	    var today = new Date();        

        while (i < amount) {
        	
            var name = $(".name:first").parent().clone(); 
            var lastId = parseInt($(".passenger:last").attr("id").split("_")[1]);
            var newId = lastId + 1;
            
            if (lastId > 19) { return false; }

            // $(".date_infant", name).removeClass('hasDatepicker');
            $('label.error', name).each(function(){
                $(this).remove(); 
            });
            
            $('.baby', name).remove();

            $('fieldset', name).attr("id", "name_" + newId);
        
            $(":input", name).each(function(){
                reCalculateIds($(this), newId);
            });

            name.attr('id', 'passenger_' + newId);
            $("div.passenger:last").after(name);

            $('#fldFfni_' + newId, name).rules('add', {
                maxlength: 2
            });

            $('#fldFfn_' + newId, name).rules('add', {
                maxlength: 4,
                digits: true
            });
            
            /*
			$(".date_infant").each(function(){
				$(this).datepicker({
					dateFormat: 'yy/mm/dd', 			
					minDate: new Date(today.getFullYear() - 18, today.getMonth(), today.getDate()),
					maxDate: new Date(),
					changeMonth: true,
					changeYear: true			
				});
			});
			*/
            
            $('#fldTitle_' + newId, name).val('');            

            i++;
        }
        
	    $('.titleExtra').each(function(){
	    	$(this).bind('change', function(){
	   			$(this).next('input').val($(':selected', $(this)).val());
	    	});	
	    });        

    });
    
    // Remove Name 
    $(".removeName").live("click", function(){
        if ($(".name").length >= 2) {
            $(this).parent().parent().remove();

            var newId = 1;

            $(".passenger").each(function(){
            	/*
                reCalculateIds($(':input', $(this)), newId);
                $('fieldset', $(this)).attr('id', 'name_' + newId);
                */
                reCalculateIds($(this), newId);           
                newId = newId + 1;
            });
        }
    });
    
    /*
    $('.titleExtra').each(function(){
    	$(this).bind('change', function(){
   			$(this).next('input').val($(':selected', $(this)).val());
    	});	
    });
    */

    function getId(item) {
        
        while( $('[id^="name_"', item) ) {
            item = item.parent();
        }

        var id = item.attr('id')

        return id;
    
    }


    function reCalculateIds(item, newId, empty) {
        var id = item.attr("id");

        if (id != undefined) {
            var nId = id.split("_")[0] + "_" + newId;
            item.attr("id", nId);
            
            if(id.split("_")[0] == 'fldInfGenderMale' || id.split("_")[0] == 'fldInfGenderFemale') { 
                item.attr("name", 'fldInfGender_' + newId); 
                // if(id.split("_")[0] == 'fldInfGenderMale') { item.val("Male"); } else { item.val("Female"); }
            } else if(id.split("_")[0] == 'fldExtraGenderMale' || id.split("_")[0] == 'fldExtraGenderFemale') { 
                item.attr("name", 'fldExtraGender_' + newId); 
                // if(id.split("_")[0] == 'fldExtraGenderMale') { item.val("Male"); } else { item.val("Female"); }
            } else { item.attr("name", nId); }
        } 

        if (empty) {
            if ( item.attr("type") != "button" && item.attr("type") != "radio") {
                if (item.hasClass('date_infant')) {
                    item.attr("value", "DD/MM/AAAA");
                
                } else if (item.hasClass('tp')) {
                    item.attr("value", "TP");
                
                } else {
                    item.attr("value", "")
                }
            }
        }    
    }
    
    
    
    function reCalculateIds_(item, newId, empty) {
        var id = item.attr("id");
        
        if (id != undefined) {
        	
	        var realid = id.split("_")[0];
            
            var nId = realid + "_" + newId;
            item.attr("id", nId);
        
            if(realid == 'fldInfGenderMale' || realid == 'fldInfGenderFemale') { item.attr("name", 'fldInfGender_' + newId); }
            else if(realid == 'fldExtraGenderMale' || realid == 'fldExtraGenderFemale') { item.attr("name", 'fldExtraGender_' + newId); }
            else { item.attr("name", realid); }
            
        } 

        if (empty) {
            if ( item.attr("type") != "button") {
                if (item.hasClass('date_infant')) {
                    item.attr("value", "DD/MM/AAAA");
                
                } else if (item.hasClass('tp')) {
                    item.attr("value", "TP");
                
                } else {
                    item.attr("value", "")
                }
            }
        }    
    }    
    
    
});

