(function($){

  $.fn.related = function(options){

    var defaults = {
      'upc':'5200033877',
      'category_id':0
    };
    var opts = $.extend(defaults, options);

    // text, url, photo

    return this.each(function(options){
      
      var element = $(this);
      var items = [];
      var page_index = 0;
      var category_id = opts.category_id;
      var div = $('<div>').addClass('items');
      var view = $('<div>').addClass('items-view');
      var title = $('<div>').addClass('title');
      $(title).addClass('category'+category_id.toString()[0]);
      
      var item_index = 0;
      var item_width = 150;
      var item_count = 4;
      var ajax_enabled = true;
     
      
      var data = {};
      data.cmd = 'GetRelated';
      data.cmd_arg = opts.upc;
      data.dtm = new Date();

      var service_url = 'default.ashx';

	    var url = service_url + '?cmd=' + data.cmd + '&cmd_arg=' + data.cmd_arg;
	    //trace(url);
	    //window.location.href = url;
      //alert(url);

      $.getJSON(service_url, data, function(data){
        items = data.items;
        
       //trace('items.length:'+items.length);
      for(var i=0;i<item_count;i++){
        if(items.length > i){
          item_index = i;
          var item = items[item_index];
          item.photo = item.upc + '.png';
          var a = $('<a>').data('item', item).attr('href', 'javascript:void(0)').data('title', item.caption).append($('<img>').attr('src', 'images/product-view/'+item.photo));
          a.bind('mouseenter', function(event){
            //var div = $('<div>').addClass('hover').html($(this).data('title'));
            //$(this).append(div);
          }).bind('mouseleave', function(event){
            //$(this).find('.hover').remove();
          }).bind('click', function(event){
            var item = $(this).data('item');
            if(ajax_enabled){
              $('.product-view').each(function(i, o){
                show_page_item(item, $(o));
              });
            }else{
              document.location.href = '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++;
          }
          item.photo = item.upc + '.png';
          var a = $('<a>').data('item', item).attr('href', 'javascript:void(0)').data('title', item.caption).append($('<img>').attr('src', 'images/product-view/'+item.photo));
          a.bind('mouseenter', function(event){
            //var div = $('<div>').addClass('hover').html($(this).data('title'));
            //$(this).append(div);
          }).bind('mouseleave', function(event){
            //$(this).find('.hover').remove();
          }).bind('click', function(event){
            var item = $(this).data('item');
            if(ajax_enabled){
              $('.product-view').each(function(i, o){
                show_page_item(item, $(o));
              });
            }else{
              document.location.href = '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'));
          //trace('item_index:'+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++;
            }

            item.photo = item.upc + '.png';
            var a = $('<a>').data('item', item).attr('href', 'javascript:void(0)').data('title', item.caption).append($('<img>').attr('src', 'images/product-view/'+item.photo));
            a.bind('mouseenter', function(event){
              //var div = $('<div>').addClass('hover').html($(this).data('title'));
              //$(this).append(div);
            }).bind('mouseleave', function(event){
              //$(this).find('.hover').remove();
            }).bind('click', function(event){
              var item = $(this).data('item');
              if(ajax_enabled){
                $('.product-view').each(function(i, o){
                  show_page_item(item, $(o));
                });
              }else{
                document.location.href = '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);
      }      
      //div.scrollLeft(10);
        if(items.length == 0){
         $(element).hide();
         $('.product-related-callout').hide();
       }
        
      });


      $(window).bind('hashchange', function(){
        trace('related_hash');
        var hash = location.hash;
        if(hash.length == 0) {
          $('.product-view').each(function(i, o){
            show_page($(o));
          });
        }
            
        var upc = hash.replace('#', '');
        for(var i=0;i<items.length;i++){
          var item = items[i];
          if(item.upc == upc){
            $('.product-view').each(function(i, o){
              show_page_item(item, $(o));
            });
          }
        }
      });


    });
    function xalert(o){
     var s = '';
      for(var p in o){
       s += p + ':' + o[p] + '\n';
      }
      alert(s);
    }
    function trace(s){
      if(window.console) window.console.log(s);
    }
    
    
  };


})(jQuery);
