//IE detect
if ($.browser.msie && $.browser.version.substr(0,1)<8) {
  var IE7 = 1;
} else var IE7 = 0;
if ($.browser.msie && $.browser.version.substr(0,1)<9 && $.browser.version.substr(0,1)>7) {
  var IE8 = 1;
} else var IE8 = 0;
if ($.browser.msie ) {
  var IE = 1;
} else var IE = 0;

var timeoutID;
var nMonth  = 3;
var calendar_img = '/img/calendar.gif';
var flyoleob = new Object();

function filtr_go(formId){
	clearTimeout(timeoutID);
	timeoutID = setTimeout(function(){applyFilters(formId);},1500);
}

function applyFilters(formId){
zborwindow();
	$("form#"+formId).submit();
	return false;
}

function zborwindow(){
 var __dialog = $('<div></div>').html('').dialog({autoOpen: false});
 __dialog.dialog({width: 400 ,height:300, position: ['center','center'], modal: true,closeOnEscape: false,draggable: false,resizable: false,
                open: function(event, ui) {$(".ui-dialog-titlebar").hide()}
                  });
 __dialog.html('<div class="ajax-splash-load"> '+  $('#preloader-fly').html() +' </div>');
 __dialog.dialog('open');
}

function zborwindow_show_error(id){
 $( "#"+id ).dialog({width: 460 ,height:300,position: ['center','center'], modal: true,closeOnEscape: false,draggable: false,resizable: false});
}



$(function(){ 
    
if($( '.find-flights').length) nMonth = 1;

if($(".dateflights, input.dateflights").length ){ 
    $(".dateflights, input.dateflights").datepicker({
        dateFormat: 'yy-mm-dd',numberOfMonths: nMonth,
        maxDate: '+12M +10D',firstDay: 1,showOn: 'both',buttonImage: calendar_img,
	buttonImageOnly: true,minDate: 0,
        onSelect: function(input, inst){
            if( $(this).is('input[name=date_from]') ){
                 var itemVal = $(this).val();
                 var dateTable = itemVal.split("-");
                 $( "input[name=date_to]" ).datepicker( "option", "minDate", new Date(dateTable[0],dateTable[1] -1 , dateTable[2]) );
			if($( "input[name=date_to]" ).val() < itemVal){
				$( "input[name=date_to]" ).val(itemVal);
			}
            }
            if( $(this).is( "input[name=date_to]" ) ){
               if($( "input[name=date_from]" ).val()>$( this ).val()){
                 $( "input[name=date_to]" ).val($("input[name=date_from]").val());
               }
            }
        }
    });
}


if($('.btn_second, .fly-details-close').length){
    $('.btn_second, .fly-details-close').click(function(e){e.preventDefault();

       var $form = '#' + $(this).parents('form').attr('id');
       if($( $form  +' > div > div > div.fly-details-wrap').is(':hidden'))
        $( $form  +' > div > div > div.fly-details-wrap').slideDown("slow")
       else
        $( $form  +' > div > div > div.fly-details-wrap').slideUp("slow")
    });
}

if($('.page-number').length){
    $('.page-number').click(function(){//e.preventDefault();
       var p = $(this).attr('id').split('_')
       $('.pagination_page_number').val(p[1]);
      // zborwindow();
       $(this).parents('form').submit();
       return false;
    });
}
if($('#pre-from').length){
    $('#pre-from').click(function(){
         $('#date_from_button').val($('#date_from_p').val())
          zborwindow();
        //alert($(this).parents('form').serialize())
        $(this).parents('form').submit();
    });
    $('#nex-from').click(function(){
        $('#date_from_button').val($('#date_from_n').val())
           zborwindow();
        $(this).parents('form').submit();
    });
    $('#pre-to').click(function(){
        $('#date_to_button').val($('#date_to_p').val())
           zborwindow();
        $(this).parents('form').submit();
    });
    $('#nex-to').click(function(){
        $('#date_to_button').val($('#date_to_n').val())
           zborwindow();
        $(this).parents('form').submit();
    });
}

if($('.form-submit').length){

    $('.form-submit').click(function(e){ 
      var valid = 0;
      var fid = $(this).parents('form').attr('id');

       if(fid == ''){
         valid = 1;
       }else if( $("#"+fid).length ){ //alert('1')
          valid = $("#"+fid).validationEngine('validate');
       }

       if(valid){//zborwindow();
         $(this).parents('form').submit();
       }
       e.preventDefault();
    });
}

if($('.f.form-submitt').length){

    $('.f.form-submitt').click(function(e){
      var valid = 0;
      var fid = $(this).parents('form').attr('id');

       if(fid == ''){
         valid = 1;
       }else if( $("#"+fid).length ){ //alert('1')
          valid = $("#"+fid).validationEngine('validate');
       }

       if(valid){//zborwindow();
         $(this).parents('form').submit();
       }
       e.preventDefault();
    });
}

if($('.submit-form').length){
    $('.submit-form').click(function(e){
       $(this).parents('form').submit();

     // if($($(this).parents('form').attr('id')).validationEngine('validate'))
     //     zborwindow();

       e.preventDefault();
    });
}

if($('#get-invoice').length){
    $('#get-invoice').change(function(){
        var n = $("#get-invoice:checked").length;
         $( '#'+ $(this).parents('form').attr('id') ).validationEngine('hideAll');
             if(n) {
                     $('#get-invoice-form').show();
                     $('#valid_invoice').children().each(function(){
                              var $id = $(this).attr('id').split("__")[1];
                              $('#'+$id).addClass($(this).html());
                     });
                     $("#get-invoice").val('Y');
                    // $("#get-invoice-hidden").val('Y');
                     $("#get-invoice-form").validationEngine();
             }else  {
                     $('#get-invoice-form').hide();
                     $('#valid_invoice').children().each(function(){
                         var $id = $(this).attr('id').split("__")[1];
                         $('#'+$id).removeClass($(this).html());
                     });
                    // closeCCErrorMsg();
               $("#get-invoice").val('N');
             //  $("#get-invoice-hidden").val('N');
              }
    } );
}

if($('.fly_details_item').length){
    $('.fly_details_item').change(function() {
        var prefix = 'detailed';
        var r_id = $(this).attr('id');
        var r_name = $(this).attr('name');
        var myForm = $(this).parents('form');
        var table_r_id = r_id.split('_');
        var form_id = $(myForm).attr('id');
        var table_r_name = r_name.split('_');
        var form_id_avl=form_id.split('_');
        var id_name = false;
        var name = false;
            if(table_r_name.length == 2){
                    name = prefix + '_' + table_r_id[0] + '_' + table_r_id[2];
            }
            if(table_r_name.length == 3){
                    name = table_r_name[1] + '_' + table_r_name[2];
            }
            if(table_r_id.length == 4){
                    id_name = table_r_id[1] + '_' + table_r_id[2] + '_' + table_r_id[3];
            }

            if(table_r_id.length == 3){
                    id_name = prefix + '_' + table_r_id[0] + '_' + table_r_id[1] + '_' + table_r_id[2];
            }

            if(name != false && id_name != false){

                    $('#' + form_id+ ' input[name='+name+']').each(function(){
                            $(this).attr("checked",false);
                    });
            $('input#' + id_name).attr("checked",true);
            }
    });
}

if($('#first_pass_name1 > input').length){
    $("#first_pass_name1 > input").blur(function(){
        $('#name').val( $(this).val() );
    });
}
if($('#first_pass_surname1 > input').length){
    $("#first_pass_surname1 > input").blur(function(){
        $('#surname').val( $(this).val() );
    });
}

if($('#pay-type').length){
    $('#pay-type').change(function() {
       $('.payment').hide();
       $('#OF').hide();

       if( $('#pay-type option:selected').attr('id')=='_CCO' )
           $('#CCO').show();
       else
       $('#'+ $(this).val()).show();

       $('#delivery-type').show();

        $( '#'+ $(this).parents('form').attr('id')).validationEngine('hideAll');
         $('#valid_cc').children().each(function() {
          var $id = $(this).attr('id').split("__")[1];
          $('#'+$id).removeClass($(this).html());
         });

       $("#delivery-type [value='EM']").attr("selected", "selected");

       if( $('#pay-type').val() =='CC'){
         $('#valid_cc').children().each(function(){
          var $id = $(this).attr('id').split("__")[1];
          $('#'+$id).addClass($(this).html());
         });

        $("#CC").validationEngine();
       }else if( $('#pay-type').val() =='CA'){
         $("#delivery-type [value='OF']").attr("selected", "selected");
         $('#OF').show()
         $('#delivery-type').hide();
       }
    });
}


if($('#form123').length){
    $("#form123").validationEngine();
}
if($('#GOL_searchForm').length ){
   $("#GOL_searchForm").validationEngine();
}

if($('a.ajax').length ){
    $('a.ajax').click(function(e) {e.preventDefault();

       var __predialog = $('<div></div>').html('').dialog({autoOpen: false});
 __predialog.dialog({width: 400 ,height:300, position: ['center','center'], modal: true,closeOnEscape: false,draggable: false,resizable: false,
                open: function(event, ui) {$(".ui-dialog-titlebar").hide()}
                  });
 __predialog.html('<div class="ajax-splash-load"> '+  $('#preloader-fly').html() +' </div>');
 __predialog.dialog('open');

       // __dialog.dialog({position: ['center','center'], modal: true,closeOnEscape: false,draggable: false,resizable: false,
       //              open: function(event, ui) {$(".ui-dialog-titlebar-close").hide()}})
       //  var htm = $('#preloader-fly').html();
      //  __dialog.html('<div class="ajax-splash-load">'+ htm +'</div>');
      //  __dialog.dialog('open');

       var url = this.href;
       var title = $(this).attr("title");
       var dialog = $('#ajax-load-zbor');
       var txt = $('#im_placerclose').text();
       var buttonsOpts = {};
       buttonsOpts[txt] = function () {dialog.dialog('close');};
          dialog.load( url,{},function (responseText, textStatus, XMLHttpRequest) {
                __predialog.dialog('close');
                dialog.dialog({title: title, bgiframe: true,height: 550,width: 750,modal: true,draggable: false,resizable: false,
                                close: function() {/*$("#ajax-load-zbor").remove();$(this).dialog('destroy')*/},
                                buttons: buttonsOpts, stack: true});
                               }
          );
    });
}

//filters
if($('div.actionFilter').length ){
    $('div.actionFilter').each(function(){
            var filterId = $(this).attr('id');
            var tableFilterId = filterId.split('-');
            var numId = tableFilterId[2];
            var currency_display=$('#currency_filtr').attr('value');
            $(this).slider({
                    range: true,
                    min: parseInt($("#filterValueMin-"+numId).text()),
                    max: parseInt($("#filterValueMax-"+numId).text()),
                    values: [parseInt($("#filterCurrentValueMin-"+numId).text()), parseInt($("#filterCurrentValueMax-"+numId).text())],
                    start: function(event, ui) {
                            clearTimeout(timeoutID);
                            },
                    stop: function(event, ui) {
                            filtr_go('filtersForm');
                            },
                    slide: function(event, ui) {
                            if(numId == 1){
                                    $("#amount-" + numId).text( " " + ui.values[0] + ' - '+ ui.values[1]+" "+ currency_display);
                                    $("#amount-" + numId + "-min").val(ui.values[0]);
                                    $("#amount-" + numId + "-max").val(ui.values[1]);
                            }else{
                                    $("#amount-" + numId).text(ui.values[0] + ':00 - ' + ui.values[1]+':00');
                                    $("#amount-" + numId + "-min").val(ui.values[0]+'00');
                                    $("#amount-" + numId + "-max").val(ui.values[1]+'00');
                            }
                    }
            });

            if(numId == 1){
                    currency_display=$('#currency_filtr').attr('value');
                    $("#amount-" + numId).text( " " + $("#slider-range-" + numId).slider("values", 0) + ' - '+ $("#slider-range-" + numId).slider("values", 1)+" "+currency_display);
                    $("#amount-" + numId + "-min").val($("#slider-range-" + numId).slider("values", 0));
                    $("#amount-" + numId + "-max").val($("#slider-range-" + numId).slider("values", 1));
                    // Set filter prices label
                    var spanWidth = $("#amount-" + numId).css('width');
                    spanWidth = spanWidth.substr(0, spanWidth.length-2);
                    var h3Width = $("#amount-" + numId).parents('h3').css('width');
                    //h3Width = h3Width.substr(0, h3Width.length-2); //TODO check error on iframe version h3Width undefind value
                    h3Width = 200;
                    if ((spanWidth > (h3Width/2)) || (IE && $(window).width()<1280))
                        $("#amount-" + numId).prev().html($('.prices-short').html());
            }else{
                    $("#amount-" + numId).text($("#slider-range-" + numId).slider("values", 0) + ':00 - ' + $("#slider-range-" + numId).slider("values", 1)+':00');
                    $("#amount-" + numId + "-min").val($("#slider-range-" + numId).slider("values", 0)+'00');
                    $("#amount-" + numId + "-max").val($("#slider-range-" + numId).slider("values", 1)+'00');
            }


    });
}

if($('input.actionFilter').length ){
    $('input.actionFilter').change(function(){
            clearTimeout(timeoutID);
            filtr_go('filtersForm');


    });
}


 

if($("#AO3_StepOne2_originButton_0, #AO3_StepOne2_destinationButton_0").length ){
    $('#AO3_StepOne2_originButton_0, #AO3_StepOne2_destinationButton_0').click(function(){
       var __dialog = $('<div></div>').html('').dialog({autoOpen: false});

       var _pos =$(this).offset();var _wt = $(window).scrollTop();var _wl = $(window).scrollLeft();
      var _h = $(this).height()+4;var _w = $(__dialog).dialog("option", "width")-$(this).width();
       __dialog.dialog({position:[_pos.left - _wl - _w ,_pos.top - _wt + _h],
       close: function(){__dialog.remove();$(this).dialog('destroy');}});
       flyoleob.__objid = this.id.replace('Button',"");
       var form = document.createElement('form');
       form.id = "__form";
       var div = document.createElement('div')
       form.appendChild(div);
       var hid = document.createElement('select');
           hid.name = "continent";
           hid.id= "___continent";
           hid.onchange = function(){__change(this);};
       div.appendChild(hid)
       __dialog.html(form);

       $.ajax({type: "POST",url: baseUrl + curr_lang +'/searching/autocomplete' ,dataType: "json",data:{step:6},
       success: function(data){
         $('#___continent').append( $('<option></option>').val('').html(data.continents_template) );
         $.map(data.continents,function (item) {$('#___continent').append( $('<option></option>').val(item.code).html(item.name) );});
       }});

       __dialog.dialog('open');
    });
}

if($("input[name='one_way']").length ){
    $("input[name='one_way']").click(function(){
       if($(this).val() == 'Y') $('#AO3_StepOne2_flightSegment_1Div').hide();
       if($(this).val() == 'N') $('#AO3_StepOne2_flightSegment_1Div').show();
    });
}

if($("#AO3_StepOne2_origin_0:input, #AO3_StepOne2_destination_0:input").length ){
    $("#AO3_StepOne2_origin_0:input, #AO3_StepOne2_destination_0:input").autocomplete({
     source: function( request, response ) {
                  $.ajax({url: baseUrl + curr_lang +'/searching/autocomplete',
                          dataType: "json",type: 'POST',
                          data: {q: request.term,timestamp:new Date().getTime(),step:1},
                          success: function(data ){
                              response( $.map( data.cities, function( item ) {
                              return {label: item.airportCode + ' ' +item.cityName + ' ' + ( item.airportName==''? '' : '(' +item.airportName+ ')'  ),
                                      value: item.cityName + ( item.airportName==''? '' : ' ' + '(' +item.airportName+ ')'  ),
                                      key : item.airportCode
                                     }
                               }));
                           }
                          });
     },
     minLength : 3,
     select:function( event, ui ){
         var var_name = $(this).attr('name').replace('name','code');
        $('input[name="'+var_name+'"]').val(ui.item.key);
     }
    }
    );
}


});


function __change(el,id){

   var slist = {'continent':{'id':'___country','name':'country','jvar':'countries','onchange':true,'button':false,'clearlist':['___country','___city']}
               ,'country'  :{'id':'___city',   'name':'city',   'jvar':'cities','onchange':false,'button':true,'clearlist':['___city']}};
   var __name = el.name;var jvar = {};

    $.each(slist, function(k, v) {if(__name == k )jvar = v;});

   if( $('#'+ jvar.id).length ){
     $('#'+jvar.id ).remove();
   }
   var hid = document.createElement('select');
    hid.id = jvar.id;
    hid.name = jvar.name;
   if(jvar.onchange) hid.onchange = function(){__change(this);};
    $(el).after(hid);
   if(jvar.button && !($('#__button').length) ){
     var butt = document.createElement('span');
         butt.id='__button';
         butt.setAttribute("class","ui-state-default ui-corner-all ui-state-hover");
         butt.appendChild(document.createTextNode( $('#btnchosetxt').val() ));
         function __chose(e){ //e.preventDefault();
             var citu = $('#___city').val().split(',')
              var var_name = $('#'+flyoleob.__objid).attr('name').replace('name','code');
             $('#'+flyoleob.__objid).val( citu[1] )
              $('input[name="'+var_name+'"]').val(citu[0]);
              $(this).parents('.ui-dialog').find('.ui-dialog-titlebar-close').click();
             return false;
         }
	 butt.onclick = __chose;
      $('#'+jvar.id).after(butt);
   }

   $.ajax({type: "GET",url: baseUrl + curr_lang +'/searching/autocomplete' ,dataType: "json",
   data: 'step=6'+'&'+$('#__form').serialize() ,
   success: function(data){
      $.each(jvar.clearlist, function(k, v) {$('#'+v).find('option').remove();
      });

        if(typeof data.countries!== "undefined"){
           $('#'+jvar.id).append( $('<option></option>').val('').html(data.countries_label) )
            $.map(data.countries,function (item) {$('#'+jvar.id).append( $('<option></option>').val(item.code).html(item.name) )});}
        else if(typeof data.cities!== "undefined"){
            $('#'+jvar.id).append( $('<option></option>').val('').html(data.cities_label) )
            $.map(data.cities,function (item) {
          $('#'+jvar.id).append( $('<option></option>').val(item.code+','+item.city_name+ '(' + item.name + ')').html(item.city_name+ '(' + item.name + ')' ) )
                });
        }

   }});


}
