// if is exist jquery

var flyoleob = new Object();

flyoleob.init = function setaddress(www){flyoleob.url = www;}

//flyoleob.__language = 'EN';
flyoleob.__dot = '.'
flyoleob.__minus = '-'
flyoleob.__space = ' ';
flyoleob.__oa = '(';
flyoleob.__ca = ')';
flyoleob.__empty = '';
flyoleob.__objid = '';
flyoleob.urll = 'zbor.md';
//flyoleob.form = '';

function initFly() {

   var nMonth  = 3;
   if($( '.find-flights').length) nMonth = 1

    var calendar_img = '/img/calendar.gif';
    $(".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());
               }
            }
        }
    });

 //flyoleob.url = 'zbor.md';

//$('#AO3_StepOne2_departure_1TimeSettDiv').;

if($("input[name='one_way']:checked").val()=='N')
 $('#AO3_StepOne2_flightSegment_1Div').show();
else if($("input[name='one_way']:checked").val()=='Y')
 $('#AO3_StepOne2_flightSegment_1Div').hide();




__dialog = $('<div></div>').html('').dialog({autoOpen: false});
 
// init
$.ajax({type: "GET",url: flyoleob.url ,dataType: "json",
             success: function(data){
                var loc =  data.search_form_details;
                 $( "input[name=name_from]").val(loc.name_from);
                 $( "input[name=name_to]").val(loc.name_to);
                 $( "input[name='date_from']").val( loc.date_from_y  + flyoleob.__minus + loc.date_from_m + flyoleob.__minus + loc.date_from_d);
                 $( "input[name='date_to']").val( loc.date_to_y + flyoleob.__minus + loc.date_to_m+ flyoleob.__minus + loc.date_to_d);
                 $( 'input[name="code_from"]').val(loc.code_from);
                 $( 'input[name="code_to"]').val(loc.code_to);


                 if($( 'select[name="pref_carrier1"]').length){
                    $('select[name="pref_carrier1"]').append( $('<option></option>').val(''));
                    $.map(loc.extra_information.carriers,function (item) {$('select[name="pref_carrier1"]').append( $('<option></option>').val(item.code).html(item.fullName) );});
                 }
                 setautocomplete();
             }
});

//$('#AO3_StepOne2_destination_0, #AO3_StepOne2_origin_0').click( function(){$(this).val('');});

// operation
/*$('#AO3_StepOne2_origin_0').change(function() {
  if($(this).val()==''){
    var hid = document.createElement('input');
    hid.type = 'text';
    hid.id = $(this).attr("id");
    hid.value = '';
    hid.name = $(this).attr("name");
    $('#AO3_StepOne2_origin_0').after(hid);
    $(this).remove();
    setautocomplete();
  }
});*/

$('#AO3_StepOne2_originButton_0, #AO3_StepOne2_destinationButton_0').click(function(){
   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]});
   flyoleob.__objid = this.id.replace('Button',flyoleob.__empty);
   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: flyoleob.url ,dataType: "json",data:{step:6},
   success: function(data){
     $('#___continent').append( $('<option></option>').val(flyoleob.__empty).html(data.continents_template) );
     $.map(data.continents,function (item) {$('#___continent').append( $('<option></option>').val(item.code).html(item.name) );});
   }});
    
   __dialog.dialog('open');
});


$("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($(this).val() == 'multi') window.location = 'http://'+ flyoleob.urll ;
});

$("a[name='flygo']").click(function(e){

 __dialog.dialog({position: ['center','center'], modal: true,closeOnEscape: false,draggable: false,resizable: false,
                 open: function(event, ui) {$(".ui-dialog-titlebar-close").hide()}
                  }
)

 /*   var htm = '<object width="100%" height="100%" type="application/x-shockwave-flash" data="/swf/loader-explore.swf" id="flash" style="visibility: visible;">'+
'<param name="allowScriptAccess" value="sameDomain">'+
'<PARAM NAME="bgcolor" VALUE="#fff">'+
'<param name="flashvars" value="withReturn=true&amp;cityName0='+$("input[name='name_from']").val()+'&amp;cityName1=&amp;cityName2=&amp;cityName3=&amp;cityName4='+$("input[name='name_to']").val()+'">'+
'</object>'*/
 __dialog.html('<div class="ajax-splash-load"><h3>Searching <br> please wait</h3><img src="/img/ajax-loader.gif"/></div>');


var $array = ['name_from','name_to','date_from','date_to']; var toexit = 0;
$.map($(this).parents("form").serializeArray(),function(item){
   if( $.inArray(item.name, $array) > -1 ){
       var thisobj = '';
      if($("input[name='"+item.name+"']").length )
       thisobj = $("input[name='"+item.name+"']");
      else if($("select[name='"+item.name+"']").length )
       thisobj = $("select[name='"+item.name+"']");

      if(thisobj.val() == ''){
          toexit = 1;
          thisobj.css({ 'border-color': 'red' });
      }
      else {
          thisobj.css({'border-color':'' });
        if(nMonth == 3) thisobj.css({'border-color':'#848484 #C1C1C1 #E1E1E1 #C0C0C0' });
      }

   }

});

 if(!toexit ){
  //$('#flyloadapi').html(htm).css({'width': '100%', 'height': '100%'}).show();
  __dialog.dialog('open');
  $(this).parents("form").submit();
 }
 e.preventDefault();
 return false;
});



};

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('Choose'));
         function __chose(){
             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]);
             __dialog.dialog('close');
             return false;
         }
	 butt.onclick = __chose;
      $('#'+jvar.id).after(butt);
   }
   
   $.ajax({type: "GET",url: flyoleob.url ,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(flyoleob.__empty).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(flyoleob.__empty).html(data.cities_label) )
            $.map(data.cities,function (item) {
          $('#'+jvar.id).append( $('<option></option>').val(item.code+','+item.city_name+ flyoleob.__oa + item.name + flyoleob.__ca).html(item.city_name+ flyoleob.__oa + item.name + flyoleob.__ca ) )
                });
        }

   }}); 
   

}



function setautocomplete(){
$("#AO3_StepOne2_origin_0:input, #AO3_StepOne2_destination_0:input").autocomplete({
 source: function( request, response ) {
              $.ajax({url: flyoleob.url,
                      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 + flyoleob.__space +item.cityName + flyoleob.__space + ( item.airportName==flyoleob.__empty? flyoleob.__empty : flyoleob.__oa +item.airportName+ flyoleob.__ca  ),
	                          value: item.cityName + ( item.airportName==flyoleob.__empty? flyoleob.__empty : flyoleob.__space + flyoleob.__oa +item.airportName+ flyoleob.__ca  ),
                                  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);
 }
}
);


}

