(function($){

  $.fn.variety = function(options){

    var defaults = {
      'items':[],
      'category_id':0,
      'upc':''
    };
    var opts = $.extend(defaults, options);

    // text, url, photo

    return this.each(function(options){
      
      var element = $(this);
      var items = opts.items;
      var page_index = 0;
      var div = $('<div>').addClass('items');
      var view = $('<div>').addClass('items-view');
      var title = $('<div>').addClass('title');
      var item_index = 0;
      var item_width = 115;
      var item_count = 4;
      var animated = false;
      var category_id = opts.category_id;
      var upc = opts.upc;
      var ajax_enabled = false;
      
//trace('upc:' + upc);
//trace('items.length:' + items.length);
      
      element.data('copy_html', $('.main .copy-container').html());
      element.addClass('category'+category_id.toString()[0]);

           
      if(items.length == 1) {
        var item = items[0];
        $('.category .main').append('<div class="variety"></div>');
        if(category_id == 6001007){
          $('.category .level3-prop .main-callout').hide();
          $('.level3-prop .copy-container').css({'left':'22px','top':'92px'}).append( $('<a>').attr('href', '#').addClass('link-6001007') );
        }else{
           add_nutrition();
          $('.level3-prop .copy-container').css({'left':'0px','top':'0px'}).empty();
        }
        
        show(item, element);
        // open up
        $('.category .level3-prop .variety').css('height', '493px');
        $('.category .level3-prop .main').css('height', '493px');
        $('.category .level3-prop .related').hide();
        $('.category .level3-prop .related-callout').hide();
        $('.category .level3-prop .main > .ex').hide();
        $('.category .main .nutrition').css({'top':'335px', 'height':'0'});
        $('.category .main .ingredients').css({'top':'335px', 'height':'0'});
        return;
      }
        

//trace('variety.items.length:'+items.length);
      for(var i=0;i<item_count;i++){
        if(items.length > i){
          item_index = i;
          var item = items[item_index];
          var a = $('<div>').addClass('img').data('item', item).append($('<img>').attr('alt', item.name).attr('src', 'images/variety-view/' + item.upc + '_t.png'));
          a.bind('mouseenter', function(event){
            $(this).addClass('hover');
          }).bind('mouseleave', function(event){
            $(this).removeClass('hover');
          }).bind('click', function(event){
            $(this).parent().parent().parent().find('.img').removeClass('selected');
            $(this).addClass('selected');
            var item = $(this).data('item');
            if(ajax_enabled){
              show(item, element);
              $('.category .right-ad .cross-view').cross({'category_id':item.category_id, 'upc':item.upc});
            }else{
              document.location.href = furl('category.aspx?upc=' + item.upc);
            }
          });
          var b = $('<div>').addClass('name').html(item.name);
          div.append($('<div>').addClass('item').attr('item_index', item_index).css('left', i*item_width).append(a).append(b)); 
        }
      }

        var left_arrow = $('<div>').addClass('left-arrow').html(' ').bind('click', function(event){
         item_index = parseInt(element.find('.items .item:first').attr('item_index'));
         var item_count_valid = 0;
         for(var i=0;i<item_count;i++){
          item_index = item_index - 1;
          var item;
//trace(item_index);
          
          if(item_index < 0){
           item = {'upc':'blank', 'name':''};
           $(this).hide();
           break;
          }else if(item_index == 0){
            item= items[item_index];
            item_count_valid++;
           $(this).hide();
          }else{
            item = items[item_index];
            item_count_valid++;
          }

          var a = $('<div>').addClass('img').data('item', item).append($('<img>').attr('alt', item.name).attr('src', 'images/variety-view/' + item.upc + '_t.png'));
          a.bind('mouseenter', function(event){
            var item = $(this).data('item');
            if(item.upc != 'blank')  $(this).addClass('hover');
          }).bind('mouseleave', function(event){
            var item = $(this).data('item');
            if(item.upc != 'blank') $(this).removeClass('hover');
          }).bind('click', function(event){
            var item = $(this).data('item');
            if(item.upc != 'blank'){
              $(this).parent().parent().parent().find('.img').removeClass('selected');
              $(this).addClass('selected');
              if(ajax_enabled){
                show(item, element);
              $('.category .right-ad .cross-view').cross({'category_id':item.category_id, 'upc':item.upc});
              }else{
                document.location.href = furl('category.aspx?upc=' + item.upc);
              }
            }
          });
          var b = $('<div>').addClass('name').html(item.name);
          element.find('.items').prepend($('<div>').addClass('item').attr('item_index', item_index).css('left', -((i+1)*item_width)).append(a).append(b)); 
         }
        $(this).parent().find('.item').each(function(i, o){
          $(this).animate({'left':'+='+(item_width*item_count_valid)}, 'slow', function(){
            if(i >= item_count) $(this).remove(); 
          });
        });
        
        $(this).parent().find('.right-arrow').show();
        
      });

      var right_arrow = $('<div>').addClass('right-arrow').html(' ').bind('click', function(event){
          item_index = parseInt(element.find('.items .item:last').attr('item_index'));
           var item_count_valid = 0;
           for(var i=0;i<item_count;i++){
            item_index = item_index + 1;
            var item;
            
            if(item_index > items.length - 1){
             item = {'upc':'blank', 'name':''};
             $(this).hide();
              break;
            }else{
              item = items[item_index];
              item_count_valid++;
            }
            var a = $('<div>').addClass('img').data('item', item).append($('<img>').attr('alt', item.name).attr('src', 'images/variety-view/' + item.upc + '_t.png'));
            a.bind('mouseenter', function(event){
              var item = $(this).data('item');
              if(item.upc != 'blank')  $(this).addClass('hover');
            }).bind('mouseleave', function(event){
              var item = $(this).data('item');
              if(item.upc != 'blank') $(this).removeClass('hover');
            }).bind('click', function(event){
              var item = $(this).data('item');
              if(item.upc != 'blank'){
                $(this).parent().parent().parent().find('.img').removeClass('selected');
                $(this).addClass('selected');
                if(ajax_enabled){
                  show(item, element);
                $('.category .right-ad .cross-view').cross({'category_id':item.category_id, 'upc':item.upc});
                }else{
                  document.location.href = furl('category.aspx?upc=' + item.upc);
                }
              }
            });
            var b = $('<div>').addClass('name').html(item.name);
            element.find('.items').append($('<div>').addClass('item').attr('item_index', item_index).css('left', (i*item_width)+(item_width * item_count)).append(a).append(b)); 
           }
           
          $(this).parent().find('.item').each(function(i, o){
            $(this).animate({'left':'-='+(item_width*item_count_valid)}, 'slow', function(){
              if(i < item_count_valid) $(this).remove(); 
            });
          });

        $(this).parent().find('.left-arrow').show();

      });

      element.empty();
      element.append(title).append(view.append(div));
      if(items.length > item_count){
        element.append(left_arrow);
        element.append(right_arrow);
        //left_arrow.trigger('click');
      }      
     
      $('.category .main').append('<div class="variety"></div>');
     
//trace('variety.category_id:' + category_id);
      switch(category_id){
        case '4003002':
        case '4003001':
        case '3003001':
        break;
        default:
          add_nutrition();
        break;
      }
    
    
      if(upc.length > 0){
        // this method was not working on items off the carousel
        // the challenge is finding elements that are not a part of the carousel, adding them, sliding the carousel over to view them and showing them selected
        for(var i=0;i<items.length;i++){
          var item = items[i];
          if(item.upc == upc){
             $(element).find('.items .img').each(function(i, o){
              var aitem = $(this).data('item');
              if(aitem.upc == upc){
                $(this).parent().parent().parent().find('.img').removeClass('selected');
                $(this).addClass('selected');
              }
            }); 
            
            // now you have to find the anchor
            show(item, element);
          }
        }
      }
      
      if(items.length == 0) $(element).hide();


      $(window).bind('hashchange', function(){
//trace('variety_hash');

        var hash = location.hash;
        if(hash.length == 0) $('.category .main > .ex').trigger('click');
            
        var upc = hash.replace('#', '');
        for(var i=0;i<items.length;i++){
          var item = items[i];
          if(item.upc == upc){
            show(item, element);
          }
        }
      });
          

    });
    function show(item, element){
      window.location.hash = '#' + item.upc;
      
      var url = 'images/variety-view/' + item.upc + '.png';
      var thumb = url.replace('.png', '_t.png');
      
      var w = $('.category .main').width();
      var h = $('.category .main').height();
      $('.category .main').css('background-position', '-1000px -1000px');
      
      $('.category .main .variety').css('background-image', 'url(' + url + ')').css('width', w).css('height', h).show();

      $('.category .main .copy-container').html(item.html);

      // just add divs for the name and the thumb
      $('.category .main .variety').append( $('<img>').addClass('reactions-thumb').attr('src', thumb) );
      $('.category .main .variety').append( $('<div>').addClass('reactions-name').html(item.name) );
      $('.category .main .variety').append( $('<div>').addClass('reactions-description').html(item.description) );
      $('.category .main .variety').append( $('<div>').addClass('reactions-share-message').html(item.share_message) );

      $('.category .main .nutrition').data('nh', (item.category_id == 3002014 || item.category_id == 4001002) ? 312 : 260);
      
      
      if($('#upc_hidden').length == 0){
        var input = $('<input>').attr({'type':'hidden','name':'upc_hidden','id':'upc_hidden','value':item.upc});
        $('form').append(input);
      }
      
            
      if(item.category_id == 6001007) $('.level3-prop .copy-container').append( $('<a>').attr('href', 'https://www.vanillavisa.com/home.html?product=giftcard').attr('target', '_blank').addClass('link-6001007') );
      
      if(item.upc == '3002002-004'){
        $('.category .main .copy-container .copy').css('top', '65px');
      } else if (item.upc == '3002014-004' || item.upc == '3002014-002' || item.upc == '3002001-002' || item.upc.indexOf('3002002-') != -1 || item.upc.indexOf('3002003-') != -1 || item.upc.indexOf('3002007-') != -1 || item.upc == '3003001-001' || item.upc == '3003001-002' || item.upc == '3002011-001' || item.upc == '3002015-001'  || item.upc == '3003001-004' || item.upc == '3002013-001') { 
        $('.category .main .copy-container .copy').css('top', '110px');
     	}else if( item.upc == '3002012-002' || item.upc == '3002014-001'){
     		$('.category .main .copy-container .copy').css('top', '113px');
     } else if (item.upc == "4003001-008" || item.upc == "4003001-007" || item.upc.indexOf('4001002-') != -1) {
        $('.category .main .copy-container .copy').css('top', '97px');
      }else if(item.upc == '3003001-007'){
        $('.category .main .copy-container .copy').css('top', '160px');
      }else if(item.upc == '3002014-003'){
        $('.category .main .copy-container .copy').css({'top':'160px','width':'200px'});
      } else{
         $('.category .main .copy-container .copy').css('top', '65px');
      }
      
      if($('.category .main > .ex').length == 0){
        $('.category .main').append($('<div>').addClass('ex').bind('click', function(){

          $('.category .main').css('background-position', '0 0');
          $('.category .main .variety').hide();
          $('.category .main .nutrition').hide();
          $('.category .main .ingredients').hide();
          $(element).find('div.img').removeClass('selected');

          $('.category .right-ad .cross-view').cross({'category_id':item.category_id});

          // position the divs at start
          $('.category .main .nutrition').css({'top':'100%', 'height':'0'});
          $('.category .main .ingredients').css({'top':'100%', 'height':'0'});

          $('.category .main .copy-container').css('top', '0px');
          $('.category .main .copy-container').html(element.data('copy_html'));
                    
          // hide the tabs
          $('.category .main .tab').hide();
          
          //hide the ex
          $('.category .main .nutrition .ex').hide();
          $('.category .main .ingredients .ex').hide();
          
          $('#like').show();

          $(this).hide();
        }));
      }

      $('.category .main > .ex').show();
      
      var url = 'images/variety-view/' + item.upc + '_n.png';
//trace('url_n:' + url);
      $('.category .main .nutrition').css({'top':'100%', 'height':'0'});
      $('.category .main .nutrition').css('background-image', 'url(' + url + ')');
      $('.category .main .nutrition').show();

      var url = 'images/variety-view/' + item.upc + '_i.png';
//trace('url_i:' + url);
      $('.category .main .ingredients').css({'top':'100%', 'height':'0'});
      $('.category .main .ingredients').css('background-image', 'url(' + url + ')');
      $('.category .main .ingredients').show();

      //hide the ex
      $('.category .main .nutrition .ex').hide();
      $('.category .main .ingredients .ex').hide();
      
      $('#like').hide();

      //$(element).find('div.img').removeClass('selected');
      //$(this).addClass('selected');
      $('.category .main .tab').show();
    }
    function add_nutrition(){
//trace('add_nutrition');

      $('.category .main').append('<div class="nutrition"><div class="tab"></div><div class="ex"></div><div class="img"></div></div><div class="ingredients"><div class="tab"></div><div class="ex"></div><div class="img"></div></div>');

      $('.category .main .nutrition .tab').click(function(){
        var element = $(this);
        var div = element.parent();
        var nh = div.data('nh');
        if(div.height() == 0){
          $('.category .main  .tab').hide();
          div.css({'top': div.position().top + 'px'}).show();
          div.find('.ex').show();
          div.animate({'top':'-='+nh+'px', 'height':nh+'px'}, function(){  });
        }else{
          
          div.animate({'top':'+='+nh+'px', 'height':'0px'}, function(){ element.show(); div.find('.img').hide(); });
        }
      });
      
    
      $('.category .main .nutrition .ex').click(function(){
        var element = $(this);
        element.hide();
        var div = element.parent();
        var nh = div.data('nh');
        $(this).parent().animate({'top':'+='+nh+'px', 'height':'-='+nh+'px'}, function(){ div.find('.img').hide();  $('.category .main  .tab').show(); });
      });
    
      $('.category .main .ingredients .tab').click(function(){
        var element = $(this);
        var div = element.parent();
        
        if(div.height() == 0){
          $('.category .main  .tab').hide();
          div.css({'top': div.position().top + 'px'}).show();
          div.find('.ex').show();
          div.animate({'top':'-=340px', 'height':'340px'}, function(){  });
        }else{
          div.animate({'top':'+=340px', 'height':'0px'}, function(){ element.show(); });
        }
      });
    
      $('.category .main .ingredients .ex').click(function(){
        var element = $(this);
        element.hide();
        var div = element.parent();
        
        $(this).parent().animate({'top':'+=340px', 'height':'-=340px'}, function(){  $('.category .main  .tab').show();  });
      });
    }
    function xalert(o){
     var s = '';
      for(var p in o){
       s += p + ':' + o[p] + '\n';
      }
      alert(s);
    }
//trace(s){
//      if(window.console) window.console.log(s);
//    }
    
    
  };


})(jQuery);



 
