var pageCount = 1;
var currentPage = 1;
var via_object = oDestination;
var currency_symbols_object = ({ "AUD":"A$",      "GBP":"£",      "CAD":"C$",     "CNY":"元",
                                "EUR":"€",      "HKD":"HK$",    "INR":"Rs",     "IDR":"Rp",
                                "ILS":"₪",      "JPY":"¥",      "KRW":"₩",      "MYR":"RM",
                                "NZD":"NZ$",    "PKR":"Rs",     "PHP":"Php",    "RUB":"руб",
                                "SAR":"﷼",      "SGD":"S$",     "ZAR":"R",      "SEK":"kr",
                                "CHF":"SFr",    "TWD":"元",      "THB":"฿",      "USD":"$",
                                "AED":" د.إ ",  "VND":"₫",      "ORG":"" });


$().ready(function()
{
  
  $('#via_columns .column').hide(); // intialize columns
  
  columnInit();
  columnPage();
  
  $('#via_columns .column:first').find('.btn_close').remove();

  $('#content .paging .paging_next').prev().click().addClass('selected').end();

  $('#via_columns .column:first').find('.col_sel').clone().attr('id','add_sel').attr('disabled','').css('width','260px').appendTo('.search_textbox');
  
  $('#add_sel').find('option').eq(0).html('Choose an Asia Pacific destination here');

  $('#btn_add').css('margin-left', '115px').css('margin-top', '-2px');  
  
  $('#content .paging a.paging_next').click(function(){
    if(currentPage < pageCount)
    {
     var clickPage = parseInt($('#content .paging a.selected').html(),10);
     $('#content .paging a.selected').next().click();
     $('#content .paging a').eq(clickPage).next().addClass('selected');
    }
  });

  $('#content .paging a.paging_prev').click(function(){
    if(currentPage > 1)
    {
      var clickPage = parseInt($('#content .paging a.selected').html(),10);
      $('#content .paging a.selected').prev().click();
      $('#content .paging a').eq(clickPage).prev().addClass('selected');
    }
  });   
});

// get currency
function getCurrency(s)
{
  return currency_symbols_object[wego_currency2]; 
}

function getConversion(n)
{
  return Math.round(wego_conversion2/exchangeRates['SGD']*n);
}

function convertToCash(n)
{
    return n;
}

//set top top deals
function setTopDealsAndDescription(keyword, i)
{
  $.ajax({
          type: 'GET',
          url: '/feed/lccdests.xml',
          dataType: 'xml',
          success: function(xml)
            {
              $('destination', xml).each(function()
                     {
                        if(keyword == $.trim($(this).find("city").text().split('\(',1)[0]))
                        { 
                          var marker = $('#via_columns .column').eq(i).find('.column_row');
                          
                          marker.hide();
                          // set description
                          long_description = $(this).find('long_description').text();
                          
                          $('.long_description').eq(i).text(long_description);

                            if(i>0)
                            {
                              var x = 0;

                              populate_cheapest_airfares($(this).find('airportcode').text(), $('#via_columns .column').eq(i).find('.topflightdeals_item'));

                              // top hotels deals
                              for(var y=5, x=2; y>0; y--)
                              {

                                if(
                                  ($(this).find('cheapest'+ (y).toString() +'star').attr('currency') == undefined) || 
                                  ($(this).find('cheapest'+ (y).toString() +'star').attr('amount') == undefined) || 
                                  ($(this).find('cheapest'+ (y).toString() +'star').attr('url') == undefined) || 
                                  ($(this).find('cheapest'+ (y).toString() +'star').attr('hotelname') == undefined)
                                  )
                                {

                                  marker.eq(x).hide();

                                } else {
                                  marker.eq(x).find('a.col_left2').text( concatTo($(this).find('cheapest'+ (y).toString() +'star').attr('hotelname'), 27 ) );
                                  marker.eq(x).find('a.col_left2').attr('href',$(this).find('cheapest'+ (y).toString() +'star').attr('url'));                              
                                  marker.eq(x).find('div.col_right2 span.bold').text( getCurrency( $(this).find('cheapest'+ $.trim((y)+' ') +'star').attr('currency') ) + ' ' + convertToCash( getConversion( parseInt($(this).find('cheapest'+ $.trim((y)+' ') +'star').attr('amount'),10)) ) );

                                  marker.eq(x).show();
                                  x++;
                                  if (x > 4) break;
                                }                                   
                              }
                              

                          } else {

                             var iata = $('#home_country').find('option:selected').attr('value').toLowerCase().split('|',1)[0];
                            //if( (iata == 'sg') || (iata == '') ) {
                            $('.column').eq(0).find('.txt_topflightdeals').hide();
                            $('.column').eq(0).find('.more_flight_deals').hide();
                            $('.column').eq(0).find('.col_tax').hide();
                            $('.column').eq(0).find('.left_hr').eq(0).addClass('hr_hide');
                            $('.column').eq(0).find('.column_row').hide();

                            var singaporeColumn = false;

                            // top hotels deals
                            for(var y=5, j=0; y>0; y--)
                            {

                              singaporeColumn = $('.column').eq(0).find('.tophoteldeals_wrap .column_row').eq(j);

                              if(
                                ($(this).find('cheapest'+ (y).toString() +'star').attr('currency') == undefined) || 
                                ($(this).find('cheapest'+ (y).toString() +'star').attr('amount') == undefined) || 
                                ($(this).find('cheapest'+ (y).toString() +'star').attr('url') == undefined) || 
                                ($(this).find('cheapest'+ (y).toString() +'star').attr('hotelname') == undefined)
                                )
                              {

                                singaporeColumn.hide();

                              } else {
                                singaporeColumn.find('a.col_left2').text( concatTo($(this).find('cheapest'+ (y).toString() +'star').attr('hotelname'), 27 ) );
                                singaporeColumn.find('a.col_left2').attr('href',$(this).find('cheapest'+ (y).toString() +'star').attr('url'));                              
                                singaporeColumn.find('div.col_right2 span.bold').text( getCurrency( $(this).find('cheapest'+ $.trim((y)+' ') +'star').attr('currency') ) + ' ' + convertToCash( getConversion( parseInt($(this).find('cheapest'+ $.trim((y)+' ') +'star').attr('amount'),10)) ) );

                                singaporeColumn.show();
                                j++;
                                if (j > 2) break;
                              }                                   
                            }
                          }
                        }
                     }
              );


            }
      }
  );
}

//alt cheap airfares method
function populate_cheapest_airfares(citycode, jq_obj){  
  var url = '/flights/airfares/SIN/'+ citycode+'?limit=5&format=js&include_only_full_prices=true';

  $.ajax({
    type: 'GET',
    url: url,
    dataType: 'json',
    timeout: 12000,
    beforeSend: function(){
      jq_obj.parent().addClass('loading');
    },
    success: function(data){
      var airline_arr = [];
      
      $(data).each(function(i){
        var airline = $(this)[0];
        var index = airline_arr.length;
        
        if(airline_arr.length <2 && !(airline.airline_name in oc(airline_arr))) {
          airline_arr.push(airline.airline_name);
          
          jq_obj.eq(index).find('.col_left').css('background','url(http://media.wego.com/images/flights/airlines/80x27/' + airline.airline_code + '.gif) no-repeat left center');
          jq_obj.eq(index).find('.col_left').attr('href', 'http://' + airline.provider_id).attr('title', 'Go to the ' + airline.airline_name + ' website');
          
          jq_obj.eq(index).find('.col_right em').text( getCurrency(airline.currency_code) + " " );
          jq_obj.eq(index).find('.col_right .currency').text( getConversion( airline.amount));
          jq_obj.eq(index).find('.col_right a').attr('href', airline.url);
        
          jq_obj.eq(index).show();
          
          
        }
        jq_obj.parent().removeClass('loading');
      });
    }
               
  });
  
}

//http://snook.ca/archives/javascript/testing_for_a_v
function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

//set search links for each column
function setSearchLinks(index)
{

  var key = $('#via_columns .column').eq(index).find('.title span').html().split(',',1)[0];

  $('#via_columns .column')
    .eq(index)
    .find('.search-blogs')        
    .attr('href','/research/search.php?code=forums_blogs&q=' + key)
    .parent()   
    .find('.search-articles')       
    .attr('href','/research/search.php?code=newspaper_articles&q=' + key)
    .parent()
    .find('.search-books')
    .attr('href', '/research/search.php?code=guide_books&q=' + key)
    .end();
    
}

//set select items and populate data for column
function setSelect()
{
      $('#via_columns .column').find('.col_sel').change(function()
      {   
        var index = $('#via_columns .column').find('.col_sel').index(this); 
    
        if($(this).find('option:selected').text() != "Choose another destination")
        {
          $(this).parent()
            .find('.title')
            .html( setTitle( $(this).find('option:selected').attr('value') ) )
            .parent()
            .find('.img')
            .css('background', setBackground( $(this).find('option:selected').attr('value'), true ))
            .end();       
                        
            //alert(setBackground( $(this).find('option:selected').attr('value'),true ));         
          if($(this).find('option:selected').text() == 'Siem Reap')
          {
            $('#via_columns .column')
              .eq(index)
              .find('.title')
              .html( setTitle('rep') )
              .parent()
              .find('.img')
              .css('background', "url(/images/dashboard/destinations/rep.jpg)")
              .end();       
          }
          
          if(index == 0) {
            $(this).parent().find('.more_flight_deals').attr('href', '/flights/airfares/to/SIN');
          } else { 
            $(this).parent().find('.more_flight_deals').attr('href', '/flights/airfares/SIN/'+ getDestination('location',$(this).find('option:selected').text(),'iata_code') +'/');
          }
        
          $(this).parent().find('.more_hotel_deals').attr('href', '/hotels/'+ getDestination('location',$(this).find('option:selected').text(),'iata_code') +'/');         

          setTopDealsAndDescription( $(this).parent().find('.title span').text().split(' \(',1)[0].split(',')[0], index );

          // setSearchLinks(index);
        
        }
            
      });

}

function getDestination(option, value, keyword) {
  var result = null;  
  var valDestination = via_object['destination'];
  for(var x=0; x<valDestination.length; x++ ) {
    if (valDestination[x][option] == value) {
      result = valDestination[x][keyword];
      break;
    }
  }
  return result;
}

function setTitle(keyword, bool) {
    keyword = keyword.toLowerCase();
  var title;
  var key;
  
  if(bool == undefined) bool = false;

  for(x = 0; x < via_object.destination.length ; x++ )
  {
    if(bool)
    {
      key = (via_object.destination[x].location);
    }
    else
    {
      key = (via_object.destination[x].iata_code).toLowerCase();
    }

    if (keyword == key)
    {
      
      if (via_object.destination[x].location.toLowerCase() == via_object.destination[x].country.toLowerCase())
      {
        title = "<span class=\"bold\">" + via_object.destination[x].location + "</span>";
        title = title + "<em></em>";
      }
      else
      {
        title = "<span class=\"bold\">" + via_object.destination[x].location + ",</span>";
        title = title + "<em> " + via_object.destination[x].country + "</em>";        
      }
      break;
    }
    
  }
  
  return title;
}

function setBackground(keyword, bool) {
    keyword = keyword.toLowerCase();
  var bkg;
  var key;
  
  if (bool == undefined) bool = false;
  
  for(x = 0; x < via_object.destination.length ; x++ )
  {
    if(bool)
    {   
      key = (via_object.destination[x].iata_code).toLowerCase();
    }
    else
    {
      key = (via_object.destination[x].location).toLowerCase();   
    }

    if (keyword.toLowerCase() == key)
    {
      bkg = "url(/images/dashboard/destinations/" + (via_object.destination[x].iata_code).toLowerCase() + ".jpg)";
      break;        
    }
  }

  return bkg; 
}

//initialize columns
function columnInit() {

  columnCreateInit();
  columnDestroyInit();

  $('#via_columns .column').each(
    function( index ) {
      
      var country = $(this).find('.title span').text().split(',',1)[0];
      for(x=0; x<via_object.destination.length; x++) {
        addSelectOption(index,via_object.destination[x].location,via_object.destination[x].iata_code);        
      }
      

      if(index == 0) {
        $(this).find('.more_flight_deals').attr('href', '/flights/airfares/to/SIN');
      } else { 
        $(this).find('.more_flight_deals').attr('href', '/flights/airfares/SIN/'+ getDestination('location',$(this).find('.title span.bold').text().split(',',1)[0],'iata_code') +'/');
      }

      $(this).find('.more_hotel_deals').attr('href', '/hotels/'+ getDestination('location',$(this).find('.title span.bold').text().split(',',1)[0],'iata_code') +'/');     
      
      setTopDealsAndDescription( country, index );
                
      $(this).find('.img').css( 'background', setBackground(country) );
      
      setSearchLinks(index);
      
    }
  );

}

function addSelectOption(index, dest, iata)
{
  $('#via_columns .column')
    .eq(index)
    .find('.col_sel')
    .append("<option value=" + iata + ">" + dest + "</option>")
    .end();
}

//initialize cloning the last destination column
function columnCreateInit()
{

  $('#content #btn_add')
    .click(function()
    { 
  
      if( $('#add_sel').find('option:selected').attr('value') == 'Choose an Asia Pacific destination here' )
      {
        alert('Please select a destination.');
      }
      else
      {
        var index = 1;
        $('#content .column:last')
          .clone()
          .addClass('column-child')         
          .insertAfter("#content .column:first")
          .find('.col_sel').attr('disabled','').end()         
          .fadeIn("slow")
          .end();

        if($('#content .column:first').next().find('.btn_close').attr('href') == undefined) $('<a href="#" title="" class="btn_close"></a>').insertBefore($('#content .column:first').next().find('.title'));
        
        columnDestroyInit();
        columnPage();
              
        
        var selectBox = $('#add_sel');
        var setIndex = selectBox[0].selectedIndex;
        
        selectBox = $('#content .column:first').next().find('.col_sel');

        selectBox.find('option')[setIndex].selected = true;
        
        if(selectBox.find('option:selected').text() != "Choose another destination")
        {
          $('#via_columns .column')
            .eq(index)
            .find('.title')
            .html( setTitle( selectBox.find('option:selected').attr('value') ) )
            .parent()
            .find('.img')
            .css('background', setBackground( selectBox.find('option:selected').attr('value'), true ))
            .end();       
          
          if(selectBox.find('option:selected').text() == 'Siem Reap')
          {
            $('#via_columns .column')
              .eq(index)
              .find('.title')
              .html( setTitle('Siem Reap', true) )
              .parent()
              .find('.img')
              .css('background', "url(/images/dashboard/destinations/rep.jpg)")
              .end();       
          }
          
          if(selectBox.find('option:selected').text() == 'Kuala Terengganu')
          {
            $('#via_columns .column')
              .eq(index)
              .find('.title')
              .html( setTitle('Kuala Terengganu', true) )
              .parent()
              .find('.img')
              .css('background', "url(/images/dashboard/destinations/tgg.jpg)")
              .end();       
          }
        
          setTopDealsAndDescription( $('#via_columns .column').eq(index).find('.title span').text().split(',',1)[0].split(' \(')[0], index );
                      
          
          if(index > 0) $('#via_columns').find('.column').find('.sel_col').removeAttr('disabled');
          
          // setSearchLinks(index);
        }

                                $('#content .column:first').next().find('.more_flight_deals').attr('href', '/flights/airfares/SIN/'+ getDestination('location',$('#content .column:first').next().find('.title span.bold').text().split(',',1)[0],'iata_code') +'/');
$('#content .column:first').next().find('.more_hotel_deals').attr('href', '/hotels/'+ getDestination('location',$('#content .column:first').next().find('.title span.bold').text().split(',',1)[0],'iata_code') +'/');

      }
      return false;
    });
    
}

//initialize removing a column
function columnDestroyInit()
{
  
  $('#content .column .btn_close')
    .click(function()
    { 
        
      $(this)
        .parent()
        .remove()
        .end();

      var columns = $('.column-child').size();
      var pages = Math.ceil(columns/3);
        
      if(currentPage > pages) {
        $('#content .paging a').eq(pages).click();
      }

      columnPage();
      
      return false;         
    });
}

//initialize pagination
function columnPage()
{
  $('.column').eq(0).show();
  var columns = $('.column-child').size();
  var pages = Math.ceil(columns/3);

  if (Math.ceil(columns/3) <= 0)
  {
    pageCount = 1;
  }
  else if (pageCount < Math.ceil(columns/3))
  {
    $('#content .paging a:last')    
        .prev()
        .clone()
        .removeClass('selected')
        .css('margin-right','4px')
        .html( parseInt( $('#content .paging .paging_next').prev().html() ,10)+1 )
        .insertBefore('#content .paging_next')
        .end();
        
    pageCount++;
  }
  else if(pageCount > Math.ceil(columns/3))
  {
    $('#content .paging .paging_next')      
        .prev()
        .remove()
        .end();

    pageCount--;
  }
  
  pageInit();
  
  
  if (currentPage == pageCount) {
    $('#content .paging .paging_next').addClass('disabled');
    if(currentPage > 1) $('#content .paging .paging_next').removeClass('disabled');           
  } else if (currentPage < pageCount) {
    $('#content .paging .paging_next').removeClass('disabled');     
    if(currentPage > 1) $('#content .paging .paging_next').removeClass('disabled');       
  } else if (currentPage == 1) {
    $('#content .paging .paging_prev').addClass('disabled');
  }

  if(pages<=1) {    
    $('#content .paging .paging_prev').addClass('disabled');
  } 
  
}

//initialize pagination
function pageInit()
{
    
  var $panePage = $('#content .paging a')
      .not('.paging_prev')
      .not('.paging_next')
      .click(function()
      {
        
        var columns = $('.column-child').size();
        var pages = Math.ceil(columns/3);       
          
        var clickPage = parseInt($(this).html(),10);
        
          $('#via_columns .column-child').hide();
          
          for (var x=((clickPage*3)-3); x<columns; x++)
          {
            $('#via_columns .column-child').eq(x).show();
          }
      
          $('#content .paging a').removeClass('selected');
        
          $(this).addClass('selected');

          currentPage = clickPage;

          if (currentPage == pageCount) {
            $('#content .paging .paging_next').addClass('disabled');
            if(currentPage > 1) $('#content .paging .paging_prev').removeClass('disabled');           
          } else if (currentPage < pageCount) {
            $('#content .paging .paging_next').removeClass('disabled');
            if(currentPage == 1) $('#content .paging .paging_prev').addClass('disabled');       
            if(currentPage > 1)
            {
              $('#content .paging .paging_next').removeClass('disabled');
              $('#content .paging .paging_prev').removeClass('disabled');
            }     
          }

          if(pages<=1) {    
            $('#content .paging .paging_prev').addClass('disabled');
          }

      })
      .end();
        
  setSelect();
  
}

function concatTo(string,count) {

  if (string == undefined) return 'none';
  if (isNaN(string)) string = string.toString();
  
  if(string.length > count) 
  {
    string = string.substring(0,count) + '...';
  }
  return $.trim(string);
}

function toCelcius(f) {
  var c=(f-32)/9*5;
  return Math.round(c);
}

