/*global jQuery, $, console, window, updatePhotos */
jQuery(function(){
  
  jQuery.ajaxSettings.traditional = true;
  // jQuery 1.4 appends [] to array item names
  // and it serializes objects recursively to post them for ajax
  // (jquery-1.4.2 line 5404, 5378 -- buildParams, param)
  // it recurses infinitely because we're passing it <OPTION>s



  /*
  **
  **    QUERY BAR -- 
  **     Interface to the URL query string.
  **     Queries have a couple variants, this parses either.
  */
  
  
  var QUERY = (function(){


    /* 
       If the page has been requested with a query string (via a product page), 
       it indicates to preset the gallery filter.
       This object parses query strings and returns an object like:
        { a: 'macro', o:'single', g:'wedding'}
     */
         
    function parseCommaDelimitedQuery(q){
      // query string is like "double,lbcak,wedding"; correlate it with menu item options
      var r = {};
      var sel = $.map(q.split(','), function(e,i) { return "[value='"+e+"']"; });
      if(!sel.length) {
        return {};
      }
      // associate them with the menus categories
      $('option').filter(sel.join(',')).each(function(i,e) {
        var k = $(e).parent().attr('name');
        r[k] = $(this).val();
      });
      return r;       
    }

    function parseNormalQuery(q){
      var r = {};
      jQuery.each(q.split('&'), function(){
        var key = this.split('=')[0];
        var val = this.split('=')[1];
        // convert floats, drop empty values
        if(/^[0-9.]+$/.test(val)) {
          val = parseFloat(val);
        }
        if(val) {
          r[key] = val;
        }
      });
      return r;
    }

    function parse(q) {
      q = q.replace(/^\?/,''); // remove the leading ?
      q = q.replace(/\&$/,''); // remove the trailing &

      // no query
      if (q.length === 0) {
        return {};
      }

      if (q.indexOf('=') !== -1) { 
        return parseNormalQuery(q); 
      }

      if(q == 'help') {              
        return({help:true});
      }

      return parseCommaDelimitedQuery(q);
    }

    var publicMethods = { parse: parse };
    
    return publicMethods;
  })();


  /*
  **
  **    FILTER MENU
  **
  */
  
  var MENUS = (function() {
    
    function findVisibleAccessoryMenu() {
      return $("select[name=a]:visible");
    }
    
    function updateFilters(data) {
      $('#gallery-filters option').each(function(i,e) {
        this.disabled = !((this.value == '') || 
        data.optic[this.value] ||
        data.accessory[this.value] ||
        data.genre[this.value]);
      });
    }

    function toggleTiltTransformer(show){           
      if(show) {
        $('#a').hide();
        $('#a_tt').show();
      } else {
        $('#a').show();
        $('#a_tt').hide();
      }
    }
    
    function getValue(){
      return({ 
        o: $('#o').val(), 
        a: findVisibleAccessoryMenu().val(),
        g: $('#g').val(),
        per_page: $('#per_page').val()
       });
    }
    
    var publicMethods = {
      findVisibleAccessoryMenu : findVisibleAccessoryMenu,
      updateFilters            : updateFilters,
      toggleTiltTransformer    : toggleTiltTransformer,
      getValue                 : getValue
    };
    
    return publicMethods;
  })();

  


/*
**
**    PHOTO LOADER
**
*/

var LOADER = (function(){

  // "start" parameter present when called from prev/next link in gallery-update-photos.php:
  function updatePhotos(start, sdata) {

    //center and show the loading notice

    $('#x-loading').center();
    $('#x-loading').fadeIn('fast');

    //collect variables to pass to php script

    sdata.s = sdata.s || start || 0; // s is for start; pagination 


    //load output into gallery div
    //$('#title').css({fontSize:12}).html('<pre>' + $.param(sdata) + '</pre>');

    // We use $.get instead of $.load so we can see the query strings in the server logs:
    $.get('gallery-update-photos.php',sdata,function(data, xhr){
      $('.gallery').html(data);

      //add listeners to new elements that have been loaded

      //lightbox for picture thumbnails

      $('.lightbox').lightbox({
        fileLoadingImage: '/images/loading.gif',
        fileBottomNavCloseImage: '/images/closelabel.gif'
      });


      //hide the loading notice

      $('#x-loading').fadeOut('fast');

    });

  }
  
  var publicMethods = {
    updatePhotos : updatePhotos
  };
  
  return publicMethods;
})();

  // attach to window so hardcoded prev/next click handlers can find it



  /*
  **
  **    CONTROLLER 
  **
  */


  function displayHelp(){
    var $help = $('<div>').css({textAlign:'left',background:'white'});
     $('select').each(function(i, select) {
       $help.append('<h4>'+select.name+'</h4>');
       $('option', this).each(function(i, option) {
         var select = $(option).parents('select').attr('name');
         if(!this.value) {
           return;
        }
         
         $help.append(
           "<div class='helpline'>"
            + $(this).text() +
         '<span class="helpexample">http://lensbaby.com/gallery-photo.php?' + select + '=' + option.value + '</span>'
         + "</div>");
       });
     });
     $help.append(
     "<p style ='margin:1em'>" + 
     " To combine options, separate them with <span style='color:red'>&amp;</span>, as in:<br>" +
       " gallery-photo.php?o=tt<span style='color:red'>&amp;</span>a=tt_macro<span style='color:red'>&amp;</span>per_page=20"+
       " + <br> (The above example shows a gallery of Tilt Transformer photos shot with a Macro Lens, with 20 images per page. )" +
       "</p>");
     $('body').prepend($help);
  }


  //
  // setup:
  //

  //preloads:
  var minusImg = $('<img/>').attr('src', '/images/img-minus.png');
  var loadingImg  = $('<img/>').attr('src', '/images/img-loading.gif');

  window.updatePhotosStartingAt = function(n){ 
    // have to get the menus' value twice, because it changes after we toggle the tilt transformer off.
    var q = MENUS.getValue();
    MENUS.toggleTiltTransformer(q.o == 'tt');
    LOADER.updatePhotos(n, MENUS.getValue()); 
  };

  // callback for gallery-update-photos.php's prev/next links.
  window.updatePhotosStartingAt0 = function() { updatePhotosStartingAt(0); }
  
  // callback by which gallery-update-photos.php provides the 
  // number of hits available for each possible refinement of the current
  // query, which is then used to disable options which would return 0 hits:
  window.updateFilters = MENUS.updateFilters;

  
  // handlers:
  $('.trigger').live('change', function() {
    updatePhotosStartingAt0();
  });
  
  $('#more-photos').live('click', updatePhotosStartingAt0);
  
  $('#reset').live('click', function(){
    $('#o,#a,#g').attr('selectedIndex',0);
    MENUS.toggleTiltTransformer(false);
    updatePhotosStartingAt0();
  });
  

  //hover src change and click actions for plus criteria images

  $('.plus').live('mouseover mouseout', function(evt){
    if(evt.type == 'mouseover') {
      this.src = '/images/img-minus.png';
    } else {
      this.src = '/images/img-plus.png';
    }
  });
  $('.plus.accessory').live('click', function(){
    MENUS.findVisibleAccessoryMenu().attr('selectedIndex',0);
    updatePhotosStartingAt0();
  });
  $('.plus.genre').live('click', function(){
    $('#g').attr('selectedIndex',0);
    updatePhotosStartingAt0();
  });


  //
  // set up the menus to correspond to the query string, if any:
  //
  var q = QUERY.parse(window.location.search);  

  if(q.g) {
    $('#g').val(q.g);
  }  

  if(q.o) {
    $('#o').val(q.o);
  }

  if(q.a) {
    MENUS.findVisibleAccessoryMenu().val(q.a);
  }

  if(q.help) {
    displayHelp();
  }

  //
  //  load the initial batch of photos:
  //
  updatePhotosStartingAt0();
  
});

