var GsProduct = {
  el_qty: null,
  el_price: null,
  el_active_radio: null,
  el_main_image: null,
  el_main_image_overlay: null,
  el_main_image_overlay_image: null,
  show_timeout: null,
  inventory: null,
  selected_inventory: null,


  init: function() {

    //initialize any nutrition divs
    $('.nutrition_hover').each(function() {
      $(this).html('<img src="/assets/templates/gaspare/img/nutrition-button.png"/>');
      var item_url = $(this).attr('data');
      $(this).qtip({
        content: '<img src="' + item_url + '"/>',
        style: {
          padding: 4,
          border: {
            width: 1,
            radius: 1,
            color: '#228312'
          }
        },
        position: {
          corner: {
            target: 'leftBottom',
            tooltip: 'rightBottom'
          }
        }
      });
    });


    var social_url = 'http://www.chocoville.com/' + GaspareStore.fbLink;

    $('.fb_product_btn').append(
      $('<iframe src="http://www.facebook.com/widgets/like.php?href=' + social_url + 
        '&layout=button_count" scrolling="no" frameborder="0" style="border:none; width:78px; height:28px; margin-bottom: -10px;"></iframe>'));

    $('#copy_link input[type="text"]').val(social_url);
    $('#copy_link input[type="text"]').click(function() {
      $(this).select();
    });

    this.el_qty = $('#product .pricing_box .qty_select');
    this.el_price = $('#product .pricing_box .price');
    this.el_main_image = $('#product .main_image img.main');
    this.el_main_image_overlay = $('#product .main_image .overlay');
    this.el_main_image_overlay_image = $('#product .main_image .overlay img:first');
    this._bindEvents();

    // fade out image overlay  
    this.el_main_image_overlay.hide();

    this._populateTwitterLink();

    this._resizePriceBox();

    // setup radio price
    $('#product .pricing_box .radio:first').click();
  },

  _populateTwitterLink: function() {
    var link = $('#tweet_free_chocolate');
    var bitly = link.attr('data');
    var tweet = encodeURIComponent("@gpa Would love to receive a coupon for " + bitly + " #chocolate");
    link.attr('href', link.attr('href') + tweet);
  },

  updateTotal: function(qty, price) {
    var total = this.el_qty.val() * price;
    var formatted_price = total.toString();
    var pieces = formatted_price.split('.');

    if(pieces.length > 1 && pieces[1].length > 2) {

      if(parseInt(pieces[1].substr(2,1),10) > 5 ){
        pieces[1] = (parseInt(pieces[1].substr(0,2), 10) + 1) + '';
      } else {
        pieces[1] = pieces[1].substr(0,2);
      }
    }

    formatted_price = "";

    // add commas for every 3rd character
    var chars = pieces[0].length -1;
    var total_chars = 0;
    while(chars >= 0) {

      var digit = pieces[0].charAt(chars);

      formatted_price = digit + formatted_price;

      if((formatted_price.length % 3) === 0 && (chars-1 !== -1)) {
        formatted_price = ',' + formatted_price;
      }

      chars --;
      total_chars ++;
    }

    if(pieces.length > 1) {
      formatted_price = formatted_price + '.' + pieces[1];
    }

    if (pieces.length == 1) {
      formatted_price = formatted_price + '.00';
    } else if(pieces[1].length == 1) {
      formatted_price  = formatted_price + '0';
    }
    this.el_price.html('$' + formatted_price);
  },

  fadeGalleryImage: function(src, direction) {

  },

  _resizePriceBox: function() {
    var radios_height = 0;
    $('div.radio_text').each(function() {
      radios_height += $(this).outerHeight(); 
    });

    var difference = 260 - radios_height;

    if (difference > 0) {
      var new_height = (260 - difference) + 5;
      $('#radio_container').css('height', new_height + 'px');

      var new_pricebox_height = $('.pricing_box').height() - difference;
      $('.pricing_box').css('height', new_pricebox_height + 'px');
    }

  },

  _bindTabs: function() {
    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

      $("ul.tabs li").removeClass("active"); //Remove any "active" class
      $(this).addClass("active"); //Add "active" class to selected tab
      $(".tab_content").hide(); //Hide all tab content

      var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
      $(activeTab).fadeIn(); //Fade in the active ID content
      return false;
    });
  },

  _bindEvents: function() {
    this._bindTabs();
    var obj = this;

    $('#add_product').ajaxForm({
      iframe: 'form_reception',
      beforeSend: function(xhr) {

        // check for cart divs and remove them before we submit
        var cart = $('.popup_container.cart');
        if(cart.length == 1) {
          GaspareStore._removePopup(cart);	
        }


        xhr.setRequestHeader("Content-type", "text/html;charset=iso-8859-1");
        if(xhr.overrideMimeType) {
          xhr.overrideMimeType('text/html; charset=iso-8859-1');
        }
      },
      beforeSubmit: function(arr, form, options) {
        if(obj.selected_inventory == 0) {
          alert("We're sorry, this item is currently out of stock");
          return false;
        }

        if(obj.selected_inventory < $('.qty_select').val()) {
          alert("We're sorry, you've requested " + $('.qty_select').val() + "; but we only have " + obj.selected_inventory + " in stock.");
	  return false;
        }

        return true;
      },
      success: function(responseText) {
        GaspareStore.showAddedToCart(
          $('#tab_details img').attr('src'), 
          $('.main_description .title').html());
        GaspareStore._removePopup($('.popup_container.product'),
        function() {
          GaspareStore._loadPopup(Cart, '/view_cart.asp', function() {
            GaspareStore.hideAddedToCart();
          });
        });
      }
    });

    $('#product .pricing_box .radio').click(function() {
      obj.el_active_radio = $(this);
      var radio_price = obj.el_active_radio.attr('data').replace(/[^0-9\.]/g, '');
      var inventory_id = obj.el_active_radio.attr('name').replace(/[^0-9\.]/g, '');
      obj.inventory = window['inventoryarray' + inventory_id];

      var inventory_row = $(obj.el_active_radio).parent().index();

      var inventory_numbers = obj.inventory[inventory_row].split('-');
      var inventory = inventory_numbers[1];

      obj.selected_inventory = inventory;

      if(inventory > 0) {
        $('#product_availability').html('In Stock');
      } else {
        $('#product_availability').html('<span style="color:#920922;">Out of Stock</span>');
      }

      var qty = obj.el_qty.val();
      obj.updateTotal(qty, radio_price);

      // update id
      var opt_id = obj.el_active_radio.attr('id');
      var option_value = $('input:[name=OptID_' + opt_id + ']').val();
      $('#listing_option').html(option_value);
    });

    this.el_qty.change(function() {
      var radio_price = obj.el_active_radio.attr('data').replace(/[^0-9\.]/g, '');
      var qty = obj.el_qty.val();
      obj.updateTotal(qty, radio_price);
    });

    $('#product .hover_images').children().each(function() {

    var data = $(this).attr('data');
    var first_char = data.substring(0,0);

	// non-image placeholders start with [ and end with ]
        if (first_char == '[') { return; } 

        if ($(this).attr('data').substring(0,1) == '[') {
          $(this).remove();
          return;
        }

        $(this).hover(
          function() {
            //hover in
            var hover_img = "http://s3.amazonaws.com/chocolat/" + $(this).attr('data');
            var thumb_src = hover_img;

            obj.show_timeout = setTimeout(function() {
              obj.el_main_image_overlay_image.attr('src', thumb_src);
              obj.el_main_image_overlay.fadeIn(300, function() {
                obj.el_main_image.attr('src', thumb_src); 
                obj.el_main_image_overlay.hide();
              });

            }, 300);
          }, 
          function() { 
            clearTimeout(obj.show_timeout);
          });
      }
    );
  }
};

