/*!
 * jQuery Blinds
 * http://www.littlewebthings.com/projects/blinds
 *
 * Copyright 2010, Vassilis Dourdounis
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
 
// Ryan's change notes:
// allowing linking of images via data-url attribute
// automatic generation of navigation buttons
// rotation between images
(function($){

   $.fn.blinds = function (options) {

      $(this).find('li').hide();
      $(this).addClass('blinds_slideshow');

      settings = {};
      settings.tile_orchestration = this.tile_orchestration;

      settings.links = false;
      settings.links_numbered = false;
      
      settings.rotate = false;
      settings.rotate_interval = 5000;
      
      settings.h_res = 12;
      settings.v_res = 1;

      settings.width = $(this).find('li:first').width();
      settings.height = $(this).find('li:first').height();

      jQuery.extend(settings, options);

      tiles_width = settings.width / settings.h_res;
      tiles_height = settings.height / settings.v_res;

      // Create blinds_container
      $(this).append('<div class="blinds_container"></div>');

      blinds_container = $(this).find('.blinds_container');
      
      // Get image and url list
      blinds_images = [];
      blinds_urls = [];
      inner_nav = settings.links ? [] : null;
      $(this).find('img').each(function (i, e) {
         blinds_images[blinds_images.length] = {'title': e.alt, 'src': e.src};
         blinds_urls[blinds_urls.length] = { 'href': $(e).data('url') || '#' };
         if(inner_nav)
            inner_nav[inner_nav.length] = '<a href="#"' + (i == 0 ? ' class="active"' : '') + '>' + (settings.links_numbered ? (i + 1) : '&nbsp;') + '</a>';
      });
      
      var cssimg = blinds_images.length > 1 ? blinds_images[1] : blinds_images[0];
      blinds_container.css({
         'position'   : 'relative', 
         'display'   : 'block', 
         'width'      : settings.width, 
         'height'   : settings.height, 
//         'border'   : '1px solid red', // debuging
         'background': 'transparent url("' + cssimg['src'] + '") 0px 0px no-repeat'
      } );
      // Setup anchor tag
      blinds_container.append('<a class="slideshow_url" href="' + blinds_urls[0].href + '"></a>');
      var url_container = $(this).find('.blinds_container a.slideshow_url');
      
      // Setup tiles
      for (i = 0; i < settings.h_res; i++)
      {
         for (j = 0; j < settings.v_res; j++)
         {
            if (tile = $(this).find('.tile_' + i + '_' + j))
            {
               h = '<div class="outer_tile_' + i + '_' + j + '"><div class="tile_' + i + '_' + j + '"></div></div>';
               url_container.append(h);
               outer_tile = $(this).find('.outer_tile_' + i + '_' + j);
               outer_tile.css({
                  'position'   : 'absolute',
                  'width'      : tiles_width,
                  'height'   : tiles_height,
                  'left'      : i * tiles_width,
                  'top'      : j * tiles_height
               })

               tile = $(this).find('.tile_' + i + '_' + j);
               tile.css({
                  'position'   : 'absolute',
                  'width'      : tiles_width,
                  'height'   : tiles_height,
                  'left'      : 0,
                  'top'      : 0,
//                  'border'   : '1px solid red', // debuging
                  'background': 'transparent url("' + blinds_images[0]['src'] + '") -' + (i * tiles_width) + 'px -' + (j * tiles_height) + 'px no-repeat' 
               })
               
               jQuery.data($(tile)[0], 'blinds_position', {'i': i, 'j': j});
            }
         }
      }
      // attaching nav
      if(inner_nav && blinds_images.length > 1){
         blinds_container.append('<div class="nav">' + inner_nav.join('') + '</div>');
         // click handlers for links
         $(this).find('.blinds_container div.nav a').each(function (i, e){
            $(e).click({'idx': i}, function(event){
               $('.slideshow').blinds_change(event.data.idx);
               return false;
            });
         });
      }
      
      var _this = this;
      jQuery.data(this[0], 'blinds_config', {
         'h_res': settings.h_res,
         'v_res': settings.v_res,
         'tiles_width': tiles_width,
         'tiles_height': tiles_height,
         'images': blinds_images,
         'links': blinds_urls,
         'img_index': 0,
         'change_buffer': 0,
         'interval': settings.rotate_interval,
         'interval_idx': settings.rotate ? setTimeout(function(){ $(_this).blinds_rotate(); }, settings.rotate_interval) : null,
         'tile_orchestration': settings.tile_orchestration
      });
   }
   $.fn.blinds_rotate = function () {
      config = jQuery.data($(this)[0], 'blinds_config');
      if(config.images.length == 1)
         return;
      newidx = config.img_index + 1 == config.images.length ? 0 : config.img_index + 1;
      $(this).blinds_change(newidx);
   }
   $.fn.blinds_change = function (img_index) {
      config = jQuery.data($(this)[0], 'blinds_config');
      
      // reset the timer
      if(config.interval_idx){
         clearTimeout(config.interval_idx);
         var _this = this;
         config.interval_idx = setTimeout(function(){ $(_this).blinds_rotate(); }, config.interval);
      }
      
      // if there are links, set class names
      if(config.links.length > 0){
         $(this).find('div.nav a.active').removeClass('active');
         $($(this).find('div.nav a')[img_index]).addClass('active');
      }
      
      // reset all sprites
      for (i = 0; i < config.h_res; i++)
      {
         for (j = 0; j < config.v_res; j++) {
            $(this).find('.tile_' + i + '_' + j).show().css('background', 'transparent ' + 'url("' + config.images[config.img_index]['src'] + '") -' + (i * config.tiles_width) + 'px -' + (j * config.tiles_height) + 'px no-repeat');
         }
      }

      $(this).children('.blinds_container').css('background', 'transparent url("' + blinds_images[img_index]['src'] + '") 0px 0px no-repeat' );
      config.img_index = img_index;
      // changing the href
      var url_container = $(this).find('.blinds_container a.slideshow_url');
      if(url_container.length > 0)
         url_container[0].href = config.links[img_index].href;
      
      jQuery.data($(this)[0], 'blinds_config', config);

      for (i = 0; i < config.h_res; i++)
      {
         for (j = 0; j < config.v_res; j++) {
            t = config.tile_orchestration(i, j, config.h_res, config.v_res);
            
            config = jQuery.data($(this)[0], 'blinds_config');
            config.change_buffer = config.change_buffer + 1;
            jQuery.data(this[0], 'blinds_config', config);

            $(this).find('.tile_' + i + '_' + j).fadeOut(t, function() {
               blinds_pos = jQuery.data($(this)[0], 'blinds_position');
               config = jQuery.data($(this).parents('.blinds_slideshow')[0], 'blinds_config');

               $(this).css('background', 'transparent ' + 'url("' + config.images[config.img_index]['src'] + '") -' + (blinds_pos.i * config.tiles_width) + 'px -' + (blinds_pos.j * config.tiles_height) + 'px no-repeat');

               config.change_buffer = config.change_buffer - 1;
               jQuery.data($(this).parents('.blinds_slideshow')[0], 'blinds_config', config);

               if (config.change_buffer == 0) {
//                  $(this).parent().parent().children().children().css('width', config.tiles_width);
                  $(this).parent().parent().children().children().show();
               }

            });
         }
      }
   }

   $.fn.tile_orchestration = function (i, j, total_x, total_y) {
      return (Math.abs(i-total_x/2)+Math.abs(j-total_y/2))*100;
   }

})(jQuery);

