function init_option_selector(items, target) {
  var self = {};
  /*
  /  items => the jquery obj pointing to the dom listing of products
  /  target => contains the order form and the selects
  */
  function get_products() {//loop through the dom items and compose a list of products
    var products = Array();
    items.each(function() {
      var obj = {};
      $(this).children().each(function() {
        var val = $(this).text();
        $.each($(this).attr('class').split(' '), function() {
          obj[this] = val
        });
      });
      products.push(obj);
    });
    return products;
  }
  
  function get_possible_products(index) {
    var selections = {};
    var possible_products = Array();
    for(var i=0; i < index; i++){//compose a list of the currently selected options
      if (!self.selectors[i].val()) continue;
      selections['option'+(i+1)] = self.selectors[i].val();
    };
    $.each(self.products, function() {//filter products that match the selected options
      for(var key in selections) {
        if (this[key] != selections[key]) return;
      }
      possible_products.push(this);
    });
    return possible_products;
  }
  
  function select_option(index) {
    var possible_products = get_possible_products(index);
    for(var i=index; i < self.selectors.length; i++) {
      var selector = self.selectors[i];
      var pval = selector.val();
      selector.children('[value!=""]').remove();
      var added_options = {};
      $.each(possible_products, function() {//loop through possible products and add possible options
        var val = this['option'+(i+1)];
        if (added_options[val]) return;
        added_options[val] = true;
        var option = new Option();
        $(option).attr('value', val).text(val);
        selector.append(option);
      });
      selector.val(pval);
    }
    possible_products = get_possible_products(self.selectors.length); //given the current selection, is there one product match?
    if (possible_products.length == 1) { //person selected the last option
      select_product(possible_products[0]);//we have our product, update the form and send the signal
    } else {
      target.find('input[name="sku"]').val('');
      target.trigger('product-selected', [null, false, false]); //no product selected
    }
  }
  
  function bool(val) {
    return val == 'True' || val == '1';
  }
  
  function select_product(product) {
    for(key in product) {
      target.find('input[name="'+key+'"]').val(product[key]);
    }
    target.trigger('product-selected', [product, bool(product.can_order), bool(product.in_stock)]);
  }
  
  function init_selectors() {
    var index = 0;
    var selectors = Array();
    while(true) {
      index += 1;
      var selector = target.find('.product_option'+index);
      if (!selector.length) break;
      selectors.push(selector);
      selector.data('index', index); //need to duplicate index
      selector.change( function () {
        self.select_option($(this).data('index'));
      });
    }
    return selectors
  }

  self.products = get_products(items);
  self.select_option = select_option;
  self.select_product = select_product;
  self.selectors = init_selectors();
  if (!self.selectors.length && self.products.length == 1) {
    select_product(self.products[0]);
  } else {
    select_option(0);
  }
  return self;
}

$(document).ready(function() {
  var num_images = $('#product_images li').length;
  if (!num_images) {
    //no images
    $('#product_image').hide();
    return;
  }
  if (num_images <= 1) {
    $('#product_images').hide();
  }
  if (num_images <= 5) {
    $('#product_images .left, #product_images .right').hide();
  }
  var options = {
    zoomWidth: 300,
    zoomHeight: 250,
    xOffset: 10,
    yOffset: 0,
    position: "right" //and MORE OPTIONS
  };
  function load_video(target, auto_play) {
        $("#main_image img").fadeOut(200);
        $('#main_image .display').html('<div id="video_piece">&nbsp;</div>');
        var flashvars = { 
            accentcolor:'0b6dd2',
            videoPath:target,
            baseurl: location.protocol + '//' + location.host,
            emailurl: "mailto:?body=I recommend visiting this page: "+location.href
        };
        
        var params = {
            bgcolor: '#000000',
            allowFullScreen:'true',
            scale:'noscale',
            wmode:'transparent',
            quality:'high',
            menu:'false',
            allowScriptAccess:'sameDomain'
        };
        var attributes = {id: 'video_piece'};
        swfobject.embedSWF("/static/videos/flash/Web_Cube_VideoPlayer.swf","video_piece","435","348","9.0.0", '', flashvars, params, attributes);
    }
    
   var media_list = WebCubePager($('#product_images'), 5);

   // clicking a thumbnail updates display and zoom
   media_list.find('li.image a.thumbnail').click(function() {
      var $this = $(this);
      var $link = $this.siblings('.display').find('.fullsize');
      media_list.find('li').removeClass('selected');
      $this.parent('li:first').addClass('selected');
      $('#main_image .display').html($this.siblings('.display').html());
      $('#main_image .display').data('link', $link);
      $('#main_image .display').click(function () {
         $('#product_image .zoomer a').click();
      });
      $('#main_image .display a').jqzoom(options);

      // center display image in its container
      $("#main_image .display").hide();
      $('#main_image img').load(function(){
          if(!$.browser.msie){
              var display_offset = [($('#main_image .display').width() - $('#main_image .display a img').width())/2,
                                    ($('#main_image .display').height() - $('#main_image .display a img').height())/2]
              $('#main_image .display a').css('left', display_offset[0]).css('top',display_offset[1]);
          }
          $("#main_image .display").fadeIn(500);
      });
      $('#main_image img').load();
      return false;
   });
   media_list.find('li.video a.thumbnail').click(function() {
        load_video($(this).attr('href'), true);
        return false;
   });
   $('#main_image .jqZoomPup').live('click', function () {
      $('#product_image .zoomer a').click();
      return false;
   });

   media_list.find('a.fullsize').fancybox();
   $('#main_image .zoomer a').click(function() {
      $('#main_image .display').data('link').click();
      return false;
   });

   // center thumbnails in case they are not proportionate
   //$('#product_images .thumb').each(function(){
   //     CtrThumbnailImage($(this));
   //});

    media_list.find('li a.thumbnail:first').click()
});

function CtrThumbnailImage(thumb) {
      //alert(thumb.children('a.thumbnail').height());
      thumb.children('a.thumbnail img').fadeOut(10);
      if(thumb.children('a.thumbnail').height()>0) {
          var thumb_offset = [(thumb.width() - thumb.children('a.thumbnail').width())/2,
                            (thumb.height() - thumb.children('a.thumbnail').height())/2];
          //alert(thumb_offset);
          thumb.children('a.thumbnail').css('left', thumb_offset[0]).css('top',thumb_offset[1]);
          thumb.children('a.thumbnail img').fadeIn(200);
      }
      else {
        setTimeout(function() {CtrThumbnailImage(thumb)}, 200);
      }
}

$(document).ready(function () {
    function load_recaptcha() {
        $('#review_post form').ajaxForm({
          target: '#review_post_cont',
          success: load_recaptcha
        }); 
        Recaptcha.create(RECAPTCHA_PUB_KEY,
                         "recaptcha_div", {
                          theme: 'white'
                        });
    }
    $('#write_review_btn a').click(function() {
        $('#write_review_btn').hide();
        $('#review_post').show();
        load_recaptcha();
        return false;
    });
    $('div.rating').each(function (){
        rating_value = parseFloat($(this).children('div.value').html());
        ratio = rating_value/5; // out of 5 stars
        full_width = $(this).width();
        $(this).children('div.value').html('&nbsp;');
        $(this).children('div.value').width(Math.round(ratio*full_width));
    });
});

$(document).ready(function() {
  $('form[name="request_instock_notification"]').submit(function() {
    $('body').append('<a id="_temp_rin_anchor" href="'+$(this).attr('action') + '?' + $(this).serialize() + '&iframe"></a>');
    $('#_temp_rin_anchor').fancybox().click().remove();
    return false;
  });

});

$(document).ready(function() {
   $('a#sendtofriend').fancybox({
       'frameWidth': 500,
       'frameHeight': 400
   }); 
});
