/**
 * For the homepage route search - this function accepts a location
 * string, eg weymouth, Dorset, United Kingdom, and redirects to the 
 * appropriate page on My VR
 * @param string loc    the location
 */
function vrSearchUrl(loc) {
  return $('.routebox form').attr('action') + '#!location=' + loc;
}



$(function() {

    // Language popup - delay then slidedown
    $('.langpop').hide();
    
    if($.cookie('langpop_closed') != 1) {
    	window.setTimeout(function() { $('.langpop').slideDown(); }, 500);
    }
    
    // Close language popup
    $('.langpop .close').click(function() {
    	$.cookie('langpop_closed', 1);
      $('.langpop').slideUp();
      return false;
    });

    // Homepage fancybox
    $('a[rel=fancybox]').fancybox({titleShow : false, overlayOpacity: 0.7, overlayColor : '#000'});

    // Homepage route tabs
    $('.routetabs ul.tabs').simpletabs();

    // Homepage slides
    $('.homeslides').cycle({ pager : '.pager', pause : true, timeout : 10000});

    // Homepage search for routes form
    // Clear input field if placeholder text
    $('input[name=location]').focus(function() {
      if($(this).val().match('region')) {
        $(this).val('');
      }
    });
    

    // Prevent homepage location form from submitting
    $('input[name=location]').parent('form').submit(function() {
      return false;
    });
    
    // Remove homepage submit button from location form
    $('.routebox input.submit').remove();
    
    // Use ViewRanger API to suggest locations
    var timeout = 1000;
    $('input[name=location]').keyup(function(e) {

      var inp    = this;
      var q      = $(inp).val();
      
      // Get keycode
      var code = (e.keyCode ? e.keyCode : e.which);

      switch(code) {

        // Enter
        case 13:
          // Selected value is the selected LI elements child anchor text
          var val = $('ul.myvrsearchres li.selected a').text();
          if(val == '') {
            alert('Please select a location from the list of options');
          }
          else {
            location.href = vrSearchUrl(val);
          }
          return false;
          break;

        // Up arrow
        case 38:
          if(!$('ul.myvrsearchres').children('li.selected').is(':first-child')) {
            $('ul.myvrsearchres').children('li.selected').removeClass('selected').prev().addClass('selected');
          }
          return;

        // Down arrow
        case 40:
          if(!$('ul.myvrsearchres').children('li.selected').is(':last-child')) {
            $('ul.myvrsearchres').children('li.selected').removeClass('selected').next().addClass('selected');
          }
          return;
      }

      // Only do query periodically after pause in typing to prevent lots of queries
      window.setTimeout(function() {
        if(q == $(inp).val() && (q != '')) {
    
          // Set 'loading' class on input
          $(inp).addClass('loading');

          // API endpoint URL
          var url = $('base').attr('href') + 'index.php/ajax/vrapi';

          $.get(url, {query : q}, function(data) {
            $(inp).removeClass('loading');
            var ul = $('ul.myvrsearchres');
            $(ul).html('');
            $(data.data).each(function(i, item) {

              // Create clickable links in LIs
              var a = $('<a href="' + vrSearchUrl(item[1]) + '">' + item[1] + '</a>');
              var li= $('<li></li>');
              $(li).append(a);
              $(ul).append(li);

            });
            
            // Preselect the first item in the list
            $(ul).children('li:first').addClass('selected');

          });

        }
      }, timeout);

    });
    
    $('body').click(function() {
      $('ul.myvrsearchres').html('');
    });



    // Stop iframes from scrolling
    $('iframe').attr('scrolling',   'no');
    $('iframe').attr('frameBorder', 0);


    // Expanding blog archive months
    $('.blogarchive').hideMaxListItems({ 'max': 12,  'moreHTML': '<p class="maxlist-more"><a href="#">More...</a></p>'});
    $('.maxlist-more a').live('click', function() {
      $(this).parent().remove();
      return false;
    });




    // Make external links open in new window
    // What is current host?
    $('a').each(function() {
      var href = $(this).attr('href');
      if(href && (href.match('http://') !== null) && (href.match(window.location.host) === null)) {
        $(this).attr('target', '_blank');
      };
    });

  
    // Date pickers
    $('input.date').calendricalDate();
    $('input.time').calendricalTime(); 

    // Phone compatibility form
    var fm = $('form#phonesearch');
    
    // Manufacturer field auto-submits form
    $('select[name=manufacturer]').change(function() {
      $(this).parents('form').trigger('submit');
    });
    $('select[name=OperatingSystem]').change(function() {
      $(this).parents('form').trigger('submit');
    });
    // Allow click on large phone icons
    $('ul.phone_os a').click(function() {
      var os = $(this).attr('id').split('_')[1];
      // Clear manufacturer
      $('select[name=manufacturer]').val('');
      // Set OS
      $('select[name=OperatingSystem]').val(os).trigger('change');
      return false;
    });

    // Clear form and re-submit to show all phones
    $('#viewallphones').click(function() {
      $(this).parents('form').find('select,input').val('').attr('checked', false);
      $(this).parents('form').trigger('submit');
      return false;
    });
    
    // Highlight odd table rows
    $('table tbody tr:odd').addClass('odd');
    
    // Add class to LI elements
    $('li:last-child').addClass('last-child');

    // Homepage gallery
    $('#gallery').cycle({
        fx:     'fade',
        speed:  2000,
        timeout: 2000,
        pager:  '#nav_1',
        pagerAnchorBuilder: function(idx, slide) {
            // return sel string for existing anchor
            //return '#nav_1 li:eq(' + (idx) + ') a';
            return '<li><a class="" href="#">&nbsp;</a></li>';
        }
    });
});

