/*
      BETA MOOSE SAYS:
    ___            ___
   /   \          /   \
   \_   \        /  __/
    _\   \      /  /__
    \___  \____/   __/
        \_       _/
          | @ @  \_     meeeeh meh meh it's beta!
          |
        _/     /\
       /o)  (o/\ \_
       \_____/ /
         \| |_/
          \_|
*/

// menu stuff ------------------------------
current_product = null;

function setupAccordionMenu(){
  var menu = $('config-menu-accordion');
  artwork_image_url = $('main-work-image').src;
  $('link-about-product').hide();
  // products
  menu.select('.product-type').each(function(product_type){
    product_type.down('form').hide();
    // attach click event to product names
    product_type.down('span.product-type-label').observe('click', function(e){
      switchProduct(product_type);
      e.stop();
    });
  });
  
  // product option values
  menu.select('.option-values').each(function(option_value_list){
    // hide all but active option values
    if (!option_value_list.match('.active')){
      option_value_list.hide();
    }
    // attach click event to option value
    option_value_list.select('li').each(function(option_value){
      option_value.observe('click', function(e){
        updateProductOption(option_value);
        e.stop();
      });
    });
    // attach click event to parent option
    option_value_list.previous().observe('click', function (e) {
      showOptionValues(option_value_list);
      e.stop();
    });
  });

  // add to cart forms
  menu.select('form').each(function (form) {

    /*
    form.observe('submit', function (e) {
    
    the form's submit event isn't firing, so instead we'll observe the
    submit button's click event. Submitting the form without using the
    button (ie. using keyboard) will call the button's click event anyway.
    */

    all_values_selected = function(form) {
      return form.select('.option-field').all(function (e) {
        return e.getValue() != '';
      });
    }
    form.down('.submit a').observe('click', function (e) {
      if (all_values_selected(form)) {
        var submit = form.down('.submit');
        opt = {
          asynchronous: true,
          method: 'post',
          requestHeaders: {Accept: 'application/json'},
          postBody: Form.serialize(form),
          onSuccess: function(t) {
            submit.update("Thanks! <a href='" + t.responseJSON.checkout_url + "'>Checkout now</a>")
            submit.down('a').observe('click', function(e){document.location = submit.down('a').href;}); // sorry god
            items = t.responseJSON.total_items 
            label = items == 1 ? 'Item' : 'Items'
            $('cart-total').update(' (' + t.responseJSON.total_items + ' ' + label + ')');
            $('header-view-cart').show();
            $('header-check-out').show();
          },
          onFailure: function(t) {
            submit.update("Could not add item to cart :(");
          },
          evalJSON: true
        };
      
        request = new Ajax.Request(form.action, opt);
        submit.update("Going...");
      } else {
        $$('.options-error').each(function (a) { a.show() });
      }
    
      e.stop();
    });

    // buy now button
    form.down('.submit-checkout a').observe('click', function (e) {
      if (all_values_selected(form)) {
        var submit = form.down('.submit-checkout');
        opt = {
          asynchronous: true,
          method: 'post',
          requestHeaders: {Accept: 'application/json'},
          postBody: Form.serialize(form),
          onSuccess: function(t) {
            document.location = t.responseJSON.checkout_url;
          },
          onFailure: function(t) {
            submit.update("Could not add item to cart :(");
          },
          evalJSON: true
        };
      
        request = new Ajax.Request(form.action, opt);
        submit.update("Going...");
      } else {
        $$('.options-error').each(function (a) { a.show() });
      }
    
      e.stop();
    });
    

  });

  $('main-work-image').onload = $('main-progress-indicator').fade({duration: 0.2});

  // show the menu
  menu.removeClassName('loading');
  validateTshirtOptions();
}

function showOptionValues(clicked_menu){
  clicked_menu.up('.product-type').select('.option').each(function(option){
    option.removeClassName('selected');
  });
  clicked_menu.previous('.option').addClassName('selected');
  var active_menu = clicked_menu.up('.product-type').select('.active')[0];
  if(!(active_menu == clicked_menu)){
    new Effect.BlindUp(active_menu, {duration: 0.2});
    active_menu.removeClassName('active');
    new Effect.BlindDown(clicked_menu, {duration: 0.2});
    clicked_menu.addClassName('active');
  }
}

function switchProduct(product){
  if(current_product == product && product.match('.active')){
    $('main-work-image').src = artwork_image_url;
    product.removeClassName('active');
    $('link-about-product').hide();
    product.down('form').fade();
    $('price-range-for-work').appear();
    setTimeout(function(){new Effect.Move('config-menu-accordion', { x: 20, y: 80, mode: 'absolute' });}, 1000);
  }
  else {
    $('main-progress-indicator').appear({duration: 0.2});    

    // change the 'about mounted prints' link to match the currently selected product.
    // this is not too sexy, please see beta moose at line 1.
    $('link-about-product').show().update('about ' + (product.down('span').innerHTML).toLowerCase() + 's');

    current_product = product;

    // any product selected yet?
    if ($$('#config-menu-accordion .product-type.active').length > 0) {
      menu_delay_in_ms = 0;
    }
    else {
      menu_delay_in_ms = 1000;
      new Effect.Move('config-menu-accordion', { x: -115, y: 80, mode: 'absolute' });
    }

    $$('#config-menu-accordion .product-type').each(function(product_type){
      product_type.removeClassName('active');
      product_type.down('form').hide();
    });


    setTimeout(function(){product.down('form').appear()}, menu_delay_in_ms);
    $('price-range-for-work').fade();
    product.addClassName('active');
    getPriceForConfiguredProduct(product);
  }
}

function selectOptionValue(option_value){
  // deactivate other option_values
  if (!option_value)
    return false;
  option_value.up('ul').select('li').each(function(option_value){
    option_value.removeClassName('selected');
  });
  // change the menu label to the selected value
  option_value.addClassName('selected');

  menu_title_for_this_option_value = option_value.up('div').previous('div').down('span')
  form_field_for_this_option_value = option_value.up('div').down('input');

  option_value_name = option_value.down('span.display-name').innerHTML;

  if(menu_title_for_this_option_value.innerHTML != option_value_name){
    $('main-progress-indicator').appear({duration: 0.2});
  }

  menu_title_for_this_option_value.update(option_value_name);
  form_field_for_this_option_value.value = extractId(option_value.id);
}

function updateProductOption(option_value){
  product = option_value.up('div.product-type');
  selectOptionValue(option_value);
  validateTshirtOptions();
  getPriceForConfiguredProduct(product);
}  

//  utility stuff --------------------------

// Adapted from http://www.ivanuzunov.net/top-10-javascript-stringprototype-extensions/
String.prototype.startsWith = function(t, i) {
  if (i==false) { 
    return (t == this.substring(0, t.length)); 
  } else { 
    return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); 
  }
}

function extractId(value) {
  tokens = value.split('-');
  return tokens[tokens.length-1];
}

function getProductParams(product) {
  params = "";
  product.select('input').each(function(input){
    if (input.name.startsWith('options') || input.name.startsWith('product_id'))
      params += input.name + '=' + input.value + '&'; // options[62]=35
			       });
  return params;
}

function getPriceForConfiguredProduct(product){
  url_for_price = "/works/" + getWorkID() + "/price";
  params = getProductParams(product);

  price_container = product.down('h4');
  opt = {
    asynchronous: true,
    method: 'get',
    parameters: params,
    onSuccess: function(t) {
      price_container.update(t.responseText);
      $('main-work-image').writeAttribute({
        src:    t.headerJSON.product_image_url,
        height: null, 
        width:  null
      });
    }
  };
  $('main-work-image').observe('load', function(){$('main-progress-indicator').fade({duration: 0.2});});

  request = new Ajax.Request(url_for_price, opt);
}

function getWorkID(){
  return extractId($$('#main .work')[0].id);
}

function disableTextSelectionForElement(element){
  element.onselectstart = function() {
      return false;
  };
  element.unselectable = "on";
  element.style.MozUserSelect = "none";
  element.style.cursor = "pointer";
}

window.onload = function () {
  setupAccordionMenu();
}

function availableTees() {
  // rake rb_dev:generate_available_tee_json
  // [size: {style: [color1, color2]}]
  return {115: {126: [117, 77, 102, 114, 98, 118, 149, 116], 88: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 98, 119, 103, 116, 101, 152, 121, 151], 87: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 73: {126: [117, 77, 102, 114, 98, 118, 149, 116], 88: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97], 138: [117, 77, 99, 114, 98, 118, 119, 116], 87: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 74: {126: [117, 77, 102, 114, 98, 118, 149, 116], 88: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97], 138: [117, 77, 99, 114, 98, 118, 119, 116], 87: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 86: {126: [117, 77, 102, 114, 98, 118, 149, 116], 88: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97], 138: [117, 77, 99, 114, 98, 118, 119, 116], 87: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 75: {126: [117, 77, 102, 114, 98, 118, 149, 116], 88: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97], 138: [117, 77, 99, 114, 98, 118, 119, 116], 87: [120, 117, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 125: {87: [120, 99, 77, 150, 147, 104, 146, 102, 114, 100, 118, 98, 119, 103, 116, 101, 152, 121, 151, 97]}, 153: {138: [117, 77, 99, 114, 98, 118, 119, 116]}}
}

function keys(hash) {
  if (hash instanceof Array)
    return hash;

  var a = [];
  for (i in hash) {
    a.push(i * 1);
  }
  return a;
}

function validOptionValues(parent_codes) {
  var values = availableTees();
  parent_codes.each(function (code) {
    values = values[code] || {}
  });
  return keys(values);
}

function validateTshirtValues(parents, element, code) {
  values = validOptionValues(parents);
  $('option-' + code).next('div').select('li').each(function (ov) {
    if (values.indexOf(extractId(ov.id) * 1) < 0) {
      ov.hide();
      ov.removeClassName("visible")
    } else {
      ov.show();
      ov.addClassName("visible")
    }
  });

  selected = $F(element) * 1;
  if (values.indexOf(selected) < 0) {
    $(element).setValue('');
    menu_title_for_this_option_value = $(element).up('div').previous('div').down('span')
    menu_title_for_this_option_value.innerHTML = 'Please select&hellip;';
    selected = null;
  }
  parents.push(selected);
  return parents;
}

function validateTshirtOptions() {
  if ($('product-type-tshirt')) {
    // Reduce displayed options to those supported
    // Select none if option not available
    selected = [$F('options[22]') * 1];
    selected = validateTshirtValues(selected, 'options[23]', 'Style');
    selected = validateTshirtValues(selected, 'options[24]', 'BodyColor');
  }
}
