/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var selectURL = './rservice2';
var bgSiteFlag = false;
var bColor;



jQuery(function(){



jQuery("#dateTo").datepicker({
         dateFormat: 'dd.mm.yy',
         minDate:  0,
         maxDate: +100,
         constrainInput: true,
         /*beforeShow: function(){
             secondDp = true;
             var df = jQuery('#dateFrom').val();
             if(df.length>0){
                 //jQuery( "#dateTo" ).datepicker( "option", "minDate", minFDate );
             
         },}*/
         onSelect: function(dateText, inst) {
            //jQuery('#dateTo').datepicker('setDate', dateText);
            //jQuery('#toDate').val('');
            jQuery('#loadedTables').hide();
            }
});
jQuery('#dateTo').datepicker( "setDate" , new Date() );
//jQuery('#dateTo').datepicker( "option" ,'minDate', new Date() );

jQuery.ajaxSetup({
    url: selectURL,
    type: "GET",
    timeout: 30000
});
bColor = '#009DDD';

if(jQuery('div.menu').size()>0){
    bColor   = jQuery('div.menu').css("background-color");
    bgSiteFlag = true;
    setFormColors(bColor);
}

jQuery('#searchButton').click(getTable);
jQuery('#calImg').click(function(){jQuery("#dateTo").datepicker('show');});


jQuery('#outCity').change(getCountries);
jQuery.preloadImages("img/ajax-loaderS.gif");

});

function updateOutCities(){
  jQuery('#outCity').loadSelect(outCityArray);
}
function updateCountries(){
  jQuery('#country').loadSelect(countryArray);
}
function getCountries(){
blockForm();
var params = 'task=GetFlights&chParam=getCountryes&noutCity='+jQuery('#outCity').val();
jQuery.ajax({
      data: params, //
      dataType: "script",
      success: function(response){
          if(response.indexOf("Exception")!=-1){
              jQuery('#loadedTables').hide();
              jQuery('#errorDiv').html("Ошибка получения данных!");
          }
          unblockForm();
      },//убрать здесь анимацию
      error: function(xhr,stat,e){
          jQuery('#loadedTables').hide();
          jQuery('#errorDiv').html("Повторите попытку позже!");
          unblockForm();
          // delete wait animation
      }
    });
}
function blockForm(){
  jQuery('#loadedTables').hide();
  jQuery('#errorDiv').empty();
  jQuery('#content').block({
message: '<div>Загрузка данных<br/><br/><img src="img/ajax-loaderS.gif"/></div>',
fadeIn:50,
fadeOut:50,
css: {border: '4px solid '+bColor,
       height: '70px',
       width:  '180px',
       backgroundColor: '#fff',
       fontSize: '12px',
       color: "#000",
       padding: "10px"},
overlayCSS:  {
    backgroundColor: '#fff',
    opacity:         0.6
    }

  });
}



function unblockForm(){
    jQuery("#content").unblock();
}

function getTable(){
    if(checkForm()){
        blockForm();
        var params = 'task=GetFlGVD&'+'outCity='+jQuery('#outCity').val()+'&country='+jQuery('#country').val()+'&dateTo='+jQuery('#dateTo').val();
        //alert(params);
        jQuery.ajax({
            data:params,
            dataType:'script',
            success:function(response){
                unblockForm();
                if(response.indexOf('Exception')!=-1){
                    jQuery('#errorDiv').html("<span style='color:#599FF0'>Ничего не найдено........</span>");
                }
                //jQuery('#dfFrom').html(response);
                //jQuery('#loadedTables').html(response);
            },
            error:function(){
                unblockForm();
                jQuery('#errorDiv').html("Повторите попытку позже!");
                return false;}
        });
    }
}


function checkForm(){
    if(jQuery('#dateFrom').val()==''){
        alert('Выберите дату вылета!');
        jQuery('#dateTo').datepicker('show');
        return false;
    }
    return true;
}
//заполняет таблицу, левую или правую (isFlyTo)
function createTable(){// второй параметр флаг для парса таблицы, третий , селектор, куда надо добавить таблицу
    if(rowsArr.length==0){
        jQuery('#loadedTables').html("<h1 class='attention' style='text-align:center;'>Ничего не найдено...</h1>").show('slow');
        return;
    }
    var rowClass = bgSiteFlag?'dat':'lBlue';
    var table = '<table cellspacing="0" cellpadding="0" border="0" width="100%" id="detailsTable">';
    table+='<tr class="headrow" style="background-color:'+bColor+'"><th>Дата и время<br>вылета</th><th>Дата и время<br>прилета</th><th>Рейс</th><th>Аэропорт<br>вылета</th><th>Начало<br>выдачи</th><th>Доп.<br>информация</th></tr>';
    for(var i=0; i<rowsArr.length; i++){
        var hrText = (rowsArr[i].addInfo).substr(0, 8)+'...';
        table+='<tr'+((i%2==1)?(' class="'+rowClass+'"'):'')+'>';
        table+='    <td>'+rowsArr[i].flyDate+'</td>';
        table+='    <td>'+rowsArr[i].arrDate+'</td>';
        table+='    <td>'+rowsArr[i].numReys+'</td>';

        //для аэропорта делаем еще ссылку
        var ap = createAirportLnk(rowsArr[i].airport);

        table+='    <td>'+ap+'</td>';
        table+='    <td>'+rowsArr[i].issueDate+'</td>';
        table+='    <td><a style="color:'+bColor+'" class="title" href="#" title="Рейс '+rowsArr[i].numReys+', дата вылета '+rowsArr[i].flyDate+'|'+rowsArr[i].addInfo+'|">'+hrText+'</a></td>';
        table+='</tr>';

    }
    table+='</table>';
    jQuery('#loadedTables').html(table);
    jQuery('a.title').cluetip({splitTitle: '|',cluetipClass: 'jtip'});
    /*jQuery('a.title').cluetip({
  splitTitle: '|',
  cluetipClass: 'jtip',
  arrows: true,
  dropShadow: false,
  hoverIntent: false,
  sticky: true,
  mouseOutClose: true,
  closePosition: 'title'//,
  //closeText: 'Закрыть'//'<img src="cross.png" alt="close" />'
});*/
    jQuery('#loadedTables').show('slow');

}





function setFormColors(bColor){
    jQuery('#content fieldset').css('border-color', bColor);
    jQuery('#content legend').css("border-color", bColor);
    jQuery('#content legend').css('background-color', bColor);
    jQuery('#outCity, #country, #dateTo').css("border-color", bColor);
    jQuery('#searchButton').css('background-color', bColor);
    jQuery('h1.attention').css('color', bColor);
    
}

function createAirportLnk(apName){
    apName = jQuery.trim(apName);
    switch(apName){
        case 'Domodedovo':
            return '<a href="com_img/Domodedovo.jpg" title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Domodedovo</a>';
            break;
        case 'Sheremetievo D':
            return '<a href="com_img/Sheremetievo D.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Sheremetievo D</a>';
            break;
        case 'Vnukovo':
            return '<a href="com_img/Vnukovo.html"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Vnukovo</a>';
            break;
        case 'Kazan':
            return '<a href="com_img/Kazan.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Kazan</a>';
            break;
        case 'Koltsovo':
            return '<a href="com_img/koltsovo.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Koltsovo</a>';
            break;
        case 'KURUMOCH':
            return '<a href="com_img/KURUMOCH.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">KURUMOCH</a>';
            braek;
        case 'Pulkovo-2':
            return '<a href="com_img/Pulkovo-2.html"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Pulkovo-2</a>';
            break;
        case 'UFA':
            return '<a href="com_img/UFA.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">UFA</a>';
            break;
		case 'Sheremetevo F':
			return '<a href="com_img/Sheremetevo F.jpg"  title="Схема аэропорта" target="_blank" class="airpLink" style="color:'+bColor+';">Sheremetevo F</a>';
			break;
        default:
            return apName;

    }
}



