	/**
	  * @category
	  * @package	Ticket Buy Fly
	  * @author		Oktay Başkuş
	  * @copyright	2005 - 2011 ICON Perception Management Co.
	  * @license
	  * @version
	  * @filesource
	  * @link		http://www.iconpm.com
	  * @see
	  * @since
	  **/

(function($){
    
    
     var ajxcache=[];
    $.fn.airports=function(settings){
        var $obj=$(this)
        var offset=$obj.offset();
        //var source='http://www.amadeus.net/aria/2.1/resources/AIR/GB/#.txt'
        var source='/interfaces/ticketbuyfly/ajax/filter.php?f=#&m=20';
        
        var $divbox=$('#divbox');
        if($divbox.length==0){
            $divbox=$('<div />')
                .addClass('icon-autocomplate-box')
                .attr('id','divbox');
            $divbox.appendTo(document.body);    
        } 
        
        function createListitem(Item,filter,addClass){
            
            function getText(st){
                return $(st,Item).first().text();
            }
            
            var $li = $("<li />");
            var code = getText('ItemCode')
            var name = getText('ItemName')
            var cntr = getText('CountryCode')
            var city = getText('CityCode')
            var stat = getText('StateCode')
            
            var re= new RegExp("("+filter+")","gi")
            var strongedtext = name.replace(re,"<strong>$1</strong>")
            
            var rightinfo = cntr;
            
            if(stat){
                rightinfo = cntr+'/'+stat;
            }
            
            var items = $('Items Item',Item)
            var $a=$('<a href="#" title="' + name + '">' + strongedtext +'<span> '+rightinfo+'</span></a>')
                $a.attr('data_name',name)
                $a.attr('data_code',code)
                $a.attr('data_cntr',cntr)
                $a.click(function(){
                    $obj.val($(this).attr('data_name'))
                    $divbox.hide(200)
                    return false
                })
                if(addClass){
                    $a.addClass(addClass);
                }
            $li.append($a);
            
            if(items.length){
                var $ul = $("<ul />");
                items.each(function(){
                    var $sli = createListitem(this,filter,"sub-item");
                    $ul.append($sli);
                })
                $ul.appendTo($li);
            }
            return $li;
        }
        
        
        
        function autocompleteshow(data,filter){
            
            $divbox.empty();
            var itemsy = 0;
            var $ul=$('<ul />');
            
            data.each(function(){
                var Item = $(this);
                itemsy++;
                var $li = createListitem(Item,filter);
                $ul.append($li);
            })

            $ul.appendTo($divbox);
            $divbox.css({left:offset.left,top:offset.top+20})
            if(!$divbox.is(':visible')){
                $divbox.show(200)    
            }
            if(itemsy==0) {
                if($divbox.is(':visible')){
                    $divbox.hide(200)    
                }
            }    
        }
        
        var outtmo=null
        $obj.blur(function(){
            
            if(outtmo)clearTimeout(outtmo)
            outtmo=setTimeout(function(){if($('#divbox').length)$('#divbox').hide(200)},200)
            
        })
    var keyuptmo = null;
    $obj.keyup(
        function(){
            if(keyuptmo)clearTimeout(keyuptmo);
            
            keyuptmo = setTimeout(function(){
                var valx=$obj.val();
                if(valx.length<3){
                    if($('#divbox').length)$('#divbox').hide(200)
                    return true
                }
                var harf=valx.toUpperCase();
                if(harf){
                    var url=source.replace('#',harf);
                    if(!ajxcache[url]){
                        $.ajax({
                          url: url,
                          data: false,
                          success: function(data,t){
                              ajxcache[url]=$('Items[name=root]>Item',data);
                              autocompleteshow(ajxcache[url],valx)
                            },
                          dataType: 'xml'
                        });
                   }
                   else {
                    autocompleteshow(ajxcache[url],valx)
                   }
                }
            },300);
        });
    }


    $.fn.loadPrices=function(where){
         var $objx=$(this);
         $objx.empty()
         $.ajax({
                      url: '/interfaces/ticketbuyfly/ajax/prices.php',
                      data: false,
                      success: function(data,t){load(data,where)},
                      dataType: 'text'
                    });

        function load(data,where){
            var fulldata=$(data)
            var indata=$(where,fulldata)
            $('a',indata).each(function(){
                var aobj=$(this)
                var olink=aobj.attr('href')
                    olink=olink.split('?');
                    if(olink.length>1){
                         olink=olink[1];   
                        aobj.attr('href','http://'+document.location.host+'/promosyon?'+olink)    
                    }
            })
            indata.appendTo($objx)
        }
    }
    
    var countrydata = null;
    $.fn.cityOrAirport=function(){
        var $objs=$(this);
        var $citylist=$('#citylist');

        if(!countrydata){
            $.ajax({
//              url: '/interfaces/ticketbuyfly/ajax/city.php?l='+$('html').attr('lang'),
              url: '/interfaces/ticketbuyfly/ajax/Countries.xml',
              data: false,
              success: function(data,t){
                  countrydata=$(data).find('Country');
                  countrydata.sort(function(a, b){
                     var texta=$(a).find('CountryName').text();
                     var textb=$(b).find('CountryName').text();
                     return ( texta> textb)?1:-1;
                  });
              },
              dataType: 'xml'
            });
        }

        var citiesdata = null
        function filterlist(filter,obj,title){
            var $citylist=$('#citylist');
                $citylist.html('<div class="loading">Bekleyin...</div>')
                
                var onlyairports=obj.hasClass('only-airport');
                var onlycity=obj.hasClass('only-city');
                    var source='/interfaces/ticketbuyfly/ajax/Cities.php?l=#';
                if(onlyairports)
                    source='/interfaces/ticketbuyfly/ajax/Airports.php?l=#';
            var url=source.replace('#',filter)
            if (!ajxcache[url]){
                 $.ajax({
                  url: url,
                  data: false,
                  success: function(data,t){
                        var DomName="City";
                        if(onlyairports)
                            DomName="Airport";
                        citiesdata=$(data).find(DomName);
                        citiesdata.sort(function(a, b){
                             var texta=$(a).find(DomName+'Name').text();
                             var textb=$(b).find(DomName+'Name').text();
                             return ( texta> textb)?1:-1;
                          });
                        ajxcache[url] = citiesdata;
                        showAirlines(citiesdata,filter,obj,title);
                    
                    },
                  dataType: 'xml'
                });
            }else {
                showAirlines(ajxcache[url],filter,obj,title);
            }
        }

        function showAirlines(data,filter,obj,title){

            $citylist.empty();
            $('.links #alphabet').html('<a href="#all">Ülke Seçin</a>')
            $('.links #alphabet a[href=#all]').click(function(){obj.trigger('click');return false;})
            var onlyairports=obj.hasClass('only-airport');
            var onlycity=obj.hasClass('only-city');
            var $ul=$('<ul />').addClass('airport-list');
            var listelimiti=2000;
            //var ulkeler=data.split('[')
            var itemsy=0;
            var itemsyw=0;
            var listingcodes=''
            var eyalet_adi=''
            var eyalet_code=''
            
            var linksdata=new Array();
            
            
            data.each(function(){
                var item = $(this);
                
                var ulke_code = item.find('CountryCode').text();
                var ulke_adi = filter;

                var item_code = item.find('CityCode').text();
                var item_name = item.find('CityName').text();
                if(onlyairports){
                    item_code = item.find('AirportCode').text();
                    item_name = item.find('AirportName').text();
                }
                
                var city_code = item.find('CityCode').text();

                var item_symb = "";
                var eyalet_code = item.find('StateCode').text();
                var eyaletyok =  eyalet_code ? false : true;
                var eyalet_adi = "";
                var eyalet_adi_str ="";
                var item_name_str=item_name.length<20?item_name:item_name.substr(0,20)+'...';

                var paddili=''
                var parcode=''
                var paddto=0;

                var finx = 1;
                if(finx!=-1){
                    item_name_str=item_name.length<20?item_name:item_name.substr(0,20)+'...';
                    if(!eyaletyok)
                    eyalet_adi_str=eyalet_adi.length<10?eyalet_adi:eyalet_adi.substr(0,10)+'...';

                    var newstr=item_name_str;
                    var $a=$('<a href="#" title="'+item_name+' - ' + (eyaletyok?'':eyalet_adi+' / ') + ulke_adi + '">'+newstr+'<span> '+(eyaletyok?'':eyalet_adi_str)+' '+(title?ulke_adi:'')+'</span></a>')
                        $a.attr('data_name',item_name)
                        $a.attr('data_code',item_code)
                        $a.attr('data_cntr',ulke_adi)
                        $a.attr('data_ccod',ulke_code)
                        listingcodes+='|'+item_code;
                        if(paddto){
                            if(listingcodes.indexOf('|'+parcode)!=-1){
                                $a.addClass('sub-item')
                                if(itemsy>=ucdebir-1)itemsy--;
                            }
                        }
                    $a.click(function(){
                        var $objx=$('input',obj.parents('li'))
                            .val($(this).attr('data_name'))
                        $.colorbox.close();
                        return false
                    })
                    var $li=$('<li />').append($a)
                    linksdata[linksdata.length]=$li;
                }
                if(paddto)paddto--;
                if (item_symb.indexOf('{')!=-1){
                    paddto=parseInt(item_symb.substr(1,item_symb.length));
                    paddili=item_name;
                    parcode=item_code;
                }
            });
            
          
            var ucdebir=Math.floor(linksdata.length/3);
            
            linksdata.sort(function(a,b){
                var tx1=$('a',a).attr('data_name')
                var tx2=$('a',b).attr('data_name')
                  if ( tx1 < tx2 )
                    return -1;
                  if ( tx1 > tx2 )
                    return 1;
                  return 0; 
            });
            itemsy=0;
            lasthrf=''
            var harfdegisti = false
             for(var p=0; p< linksdata.length; p++) {
                itemsy++;
                $li=linksdata[p];

                
               
                
                var n_lasthrf=$('a',$li).attr('data_name').split('')[0].toUpperCase();
                harfdegisti=(lasthrf=='' || lasthrf!=n_lasthrf)?true:false
                
                if(harfdegisti){
                    $ul.appendTo($citylist);
                    $citylist.append('<div id="harf_'+n_lasthrf+'" class="group list-harf">'+n_lasthrf+'</div>')
                    $ul=$('<ul />').addClass('airport-list');
                    
                    var $harf_a=$('<a href="#harf_'+n_lasthrf+'">'+n_lasthrf+'</a>')
                    $($harf_a).click(function(){
                        var opos=$($(this).attr('href')).offset().top+$citylist.scrollTop()
                        var cpos=$citylist.offset().top
                        $citylist.animate({scrollTop: opos-cpos},400)
                        return false;
                    })
                    $('.links #alphabet').append($harf_a);
                    itemsy=0;
                }
                $ul.append($li);
                lasthrf=n_lasthrf;
  
                
                
            }
            
            
            if($('li',$ul).length>0){
                $ul.appendTo($citylist);
            }


            
            if(title) $('#cityorairports h3').html(title)
            else      {
                $('#cityorairports h3').html(ulke_adi)   
                $('.links #alphabet .current').removeClass("current")
            }
        }
        
        
        /*
        $('.links #alphabet a').each(function(){
            $(this).click(function(){
                var hrf=$(this).attr('href')
                if(hrf=="#all")    
                    lastobj.trigger('click')
                else{
                    var flt=hrf.substr(1,hrf.length)
                    filterlist(flt,lastobj,"'"+flt+"' Harfi İle Başlayanlar");
                }
            })
        })
        */
        
        
        var lasthrf = ""
        var lastobj = null;
        
        return $objs.each(function(){
            var $obja=$(this);
            lastobj=$obja;
            $obja.click(function(){

                $('#cityorairports h3').html($('#cityorairports h3').attr('title'))
                $citylist.empty()
                $('.links #alphabet').empty()
                var $ul=$('<ul />').addClass('city-list-ul');
                
                
                countrydata.each(function(){
                    var ulke = $(this);
                    
                    var ulke_adi = ulke.find('CountryName').text();
                    var ulke_code = ulke.find('CountryCode').text();
                    
                    
                    var n_lasthrf = ulke_adi.substr(0,1).toUpperCase();
                    
                    if(lasthrf == '' || lasthrf != n_lasthrf){ // harf değişti
                        var $harf_div=$('<div id="harf_' + n_lasthrf + '" class="group list-harf">' + n_lasthrf + '</div>')
                        $ul.append($harf_div)
                        
                        var $harf_a=$('<a href="#harf_' + n_lasthrf + '">' + n_lasthrf + '</a>')
                        $($harf_a).click(function(){
                            var opos=$($(this).attr('href')).offset().top + $citylist.scrollTop()
                            var cpos=$citylist.offset().top
                            $citylist.animate({scrollTop: opos-cpos},400)
                            return false;
                        })
                        $('.links #alphabet').append($harf_a);
                        lasthrf = n_lasthrf;
                    }
                    
                    
                    var $a=$('<a />')
                    
                    $a.attr('data_cntr', ulke_adi)
                    $a.attr('data_ccod', ulke_code)
                    
                    $a.click(function(){
                        filterlist($(this).attr('data_ccod'),$obja,$(this).attr('data_cntr'));
                        return false;
                    })
                    $a.html(ulke_adi);
                    var $li=$('<li />').append($a).appendTo($ul);
                })
                $citylist.html($ul)
                $citylist.animate({scrollTop: '5px'},100)
            })
        })
    }
    var sayac=0;
    $.fn.addFlight=function(){
        return $(this).each(function(){
            var $put_div=$('#extra_ucuslar');
            var $nrm_div=$('#normal_ucus').clone();
            $(this).click(function(){
                $kapsaspn=$('<span class="clone" />');
                $kapsaspn.append($nrm_div.clone())
                
               if (sayac>5) {
                    alert('Daha Fazla Uçuş Ekleyemezsiniz!')
                    return false
               } 
               $put_div.append($kapsaspn)
               sayac=$('.clone',$put_div).length+1
               
                $('input:nth(0)',$kapsaspn).attr('name','EF_From'+sayac)
                $('input:nth(1)',$kapsaspn).attr('name','EF_To'+sayac)
                $('input:nth(2)',$kapsaspn).attr('name','EF_DepartureDate'+sayac)
                
                $('input:nth(0)',$kapsaspn).attr('id','EF_From'+sayac)
                $('input:nth(1)',$kapsaspn).attr('id','EF_To'+sayac)
                $('input:nth(2)',$kapsaspn).attr('id','EF_DepartureDate'+sayac)
                
                $('span:nth(0)',$kapsaspn).html($('span:nth(0)',$kapsaspn).html().split(' ')[0]+' '+sayac)
                $removelink=$('<a href="#" class="remove-flight-link">İptal</a>');
                $removelink.click(function(){
                    $(this).parents('span').remove();
                    sayac=$('.clone',$put_div).length-1
                    return false
                })
                $('span:nth(0)',$kapsaspn).append($removelink)
               
               $('input:nth(0)',$kapsaspn).airports();
               $('input:nth(1)',$kapsaspn).airports();
               $('.city-or-airport',$kapsaspn).cityOrAirport()
               $("a.city-or-airport",$kapsaspn).colorbox({width:"800px", height:"600", inline:true, onLoad: function() {$('#cboxClose').css({position:'absolute',top:0})}});
               $('.EF_dates',$kapsaspn).show()
               
				$('input.date',$kapsaspn).datepicker({
					showOn: 'both', 
					minDate: 0,
                    showAnim: 'show',
					buttonImage: '/interfaces/ticketbuyfly/images/calendar.png', 
					buttonImageOnly: true,
					dateFormat:'dd/mm/yy'
				});
               return false;
            })
            
            
            
            
            
        })
        
        
        
        
        
    }
    
    
    
     $.fn.countrylistAlphabet=function(){
        var bolded = false;
        $(this).each(function(){if($(this).hasClass('current')){$(this).css('font-weight','bold').addClass('current');bolded=true}})
        $(this).each(function(){
            var $obj = $(this)
            $obj.click(function(){
                $obj.parent().parent().find('.current').removeClass('current').css('font-weight','');
                $(this).css('font-weight','bold').addClass('current');
            })
        })
        return $(this).each(function(){
            var $obj = $(this)
            if(!bolded){
                $obj.css('font-weight','bold').addClass('current')
                return false; 
                }
            return true
        })
     }
    
    $.fn.flightRadioCheck=function(obj,obj2){
        var $obj=$(obj);
        var $obj2=$(obj2,$('#search-flight'));

        return $(this).each(function(){
            $(this).change(function(){
                var valx=$(this).val();
                if(valx=="OneWay"){
                    
                    $obj.fadeTo(200,0)
                    if($obj2.length==0)$obj.hide(200)
                    $('input',$obj).val('');
                    $obj2.css('position','relative').animate({top:10},500)
                    $('input',$obj).attr('disabled','disabled')
                    $("#datesinputs").show(200)
                    $(".EF_dates").hide(200)
                    
                    $('#normal_ucus input:nth(0)').attr('name','External_FlightFareSearch_From')
                    $('#normal_ucus input:nth(1)').attr('name','External_FlightFareSearch_To')
                    $('#normal_ucus input:nth(2)').attr('name','External_FlightFareSearch_DepartureDate')
                    $('#normal_ucus input:nth(0)').attr('id','External_FlightFareSearch_From')
                    $('#normal_ucus input:nth(1)').attr('id','External_FlightFareSearch_To')
                    $('#normal_ucus input:nth(2)').attr('id','External_FlightFareSearch_DepartureDate')
                    
                }
                else if(valx=="RoundTrip") {
                    $obj2.css('position','relative').animate({top:0},500)
                    $obj.show(200).fadeTo(200,1)
                    $('input',$obj).removeAttr('disabled')
                    $("#datesinputs").show(200)
                    $(".EF_dates").hide(200)
                    
                    $('#normal_ucus input:nth(0)').attr('name','External_FlightFareSearch_From')
                    $('#normal_ucus input:nth(1)').attr('name','External_FlightFareSearch_To')
                    $('#normal_ucus input:nth(2)').attr('name','External_FlightFareSearch_DepartureDate')
                    $('#normal_ucus input:nth(0)').attr('id','External_FlightFareSearch_From')
                    $('#normal_ucus input:nth(1)').attr('id','External_FlightFareSearch_To')
                    $('#normal_ucus input:nth(2)').attr('id','External_FlightFareSearch_DepartureDate')
                    
                } else { //MultiLeg
                    $('#normal_ucus input:nth(0)').attr('name','EF_From1')
                    $('#normal_ucus input:nth(1)').attr('name','EF_To1')
                    $('#normal_ucus input:nth(2)').attr('name','EF_DepartureDate1')
                    
                    $('#normal_ucus input:nth(0)').attr('id','EF_From1')
                    $('#normal_ucus input:nth(1)').attr('id','EF_To1')
                    $('#normal_ucus input:nth(2)').attr('id','EF_DepartureDate1')
                    
                    $("#datesinputs").hide(200)
                    $(".EF_dates").show(300)
                }
                           
            })
        })
    }
    
    
    
     isPage = function(){
        result = false;
        if($("body").attr('id') == 'page'){
            result = true;
        }
        
        return result;
    }
    
    is404 = function(){
        result = false;
        if($("body").attr('id') == 'error-404'){
            result = true;
        }
        
        return result;
    };
    
    /* ajax sayfa icerik sabit url farklı */
    /*
 var a=$('a')
    a.click(function() {
      
      try{history.pushState(null, null, this.href)}catch(e){
          window.location.hash = this.href.split(window.location.host)[1];
      }
      return false
    })

 $(window).bind("popstate", function (b) {
        
    })
  */
})(jQuery);

