TGK = function(){
  return {}
}();

TGK.Homepage = function() {
  var selectedClassName = 'marquee_selected';

  var carouselDeselectAll = function() {
    $$("#marquee_navigation a."+selectedClassName).each(function(el) {
      el.removeClassName(selectedClassName);
    });
  }

  var carouselSelect = function(id) {
    $$("#marquee_navigation a[rel="+id+"]").each(function(el) {
      el.addClassName(selectedClassName);
    });
  }

  return {
    init: function() {
      if ($('marquee_wrapper')) {
        new Carousel('marquee_wrapper',
          $$('#marquee_carousel .marquee'),
          $$('#marquee_navigation a.marquee_jumper'),
          {
            duration: 0.2,
            auto: true,
            frequency: 6,
            visibleSlides: 1,
            circular: true,
            wheel: false,
            effect: 'fade',
            jumperClassName: 'marquee_jumper',
            selectedClassName: selectedClassName,
            beforeMove: function(carousel) {
              carouselDeselectAll();
            },
            afterMove: function(carousel) {
              id = carousel.current.getAttribute("id");
              if (!id.blank()) {
                carouselSelect(id);
              }
            }
          }
        );

        // Find middle of marquee_wrapper
        marquee_width = $('marquee_wrapper').getWidth();
        nav_width = $('marquee_navigation').getWidth();
        left_offset = (marquee_width - nav_width)/2;
        $('marquee_navigation').setStyle({left: left_offset + "px"});
        
        TGK.Utility.markLast($('tgk_about'), 'p');
      }
    },
    
    copyFeedburnerBlogLink: function() {
      a = $$('.feedburnerFeedBlock .headline a').first();
      if (a) {
        href = a.getAttribute('href')
        
        read_more_a = $('blog_item_read_more').down('a');
        if (read_more_a){
          read_more_a.setAttribute('href', href);
        }
      }
    }
  }
}();

TGK.Fonts = function(){
  return {}
}();

TGK.Fonts.Index = function(){
  return {
    reveal_fonts: function(kind) {
      id = kind + "_fonts";
      new Effect.BlindDown(id);
      $(kind + "_show_link").hide();
      $(kind + "_hide_link").show();
    },
    
    hide_fonts: function(kind) {
      id = kind + "_fonts";
      new Effect.BlindUp(id);
      $(kind + "_show_link").show();
      $(kind + "_hide_link").hide();
    }
    
  }
}();


TGK.Products = function(){
  return {}
}();

TGK.Products.Index = function() {
  var listing_grid;
  var filter;

  // Changes the appearance of #tgk_products_listing to indicate that new info is being loaded or has
  // completed loading.  Pass 'start' for +state+ to enable the effect, anything else to disable it.
  var reloadingChrome = function(state) {
    if(state == "start") {
      new Effect.Opacity(listing_grid, {duration: 0, to: 0.5 });
      new Effect.ScrollTo(listing_grid.readAttribute('id'));
    }
    else {
      new Effect.Opacity(listing_grid, {duration: 0, to: 1.0 });
      $$('.loading_indicator').each(function(el){ el.hide(); });
    }
    return true;
  }

  // Submits the filter form using AJAX
  var submitFilterForm = function() {
    form = $('tgk_productnav').down('form');

    reloadingChrome('start');
    new Ajax.Updater(
      listing_grid,
      form.action,
      {
        asynchronous:true,
        evalScripts:true,
        method:'get',
        onComplete:function(request){
          reloadingChrome('stop');
          //updateAddressBar(form);
        },
        parameters:form.serialize()
      }
    );
  }

  // TODO
  var updateAddressBar = function(form) {
    ids = [];

    $$('.classification_filter input').each(function(el) {
      if (el.checked == true) {
        val = el.readAttribute('id').gsub(/^filter_classification_id_/, '');
        ids.push(val);
      }
    });

    protocol = document.location.protocol;
    host     = document.location.host;
    serial = form.serialize({hash:true});
    // alert("ACTION: " + form.action);
    // alert("SER: " + serial['filter_classification_ids[]']);
    // alert("IDS: " + ids.sort().reverse().inspect());
  }

  return {
    // Initializes the product filters
    init: function() {
      filter = $('tgk_productnav');
      listing_grid = $('tgk_products_listing');

      if (filter && listing_grid) {
        // Hide the submit button
        filter.down("input[type='submit']").hide();

        // Show the loading indicator on click
        $$('.classification_filter input', '.classification_filter a').each(function(el) {
          el.observe('click', function(event) {
            el = event.element();
            el.next('.loading_indicator').show();

            // When a link is clicked enable this check box and disable all others
            if (el.tagName == 'A') {
              // Uncheck all
              $$('.classification_filter input').each(function(input) {
                input.checked = false;
              });

              // Check this one
              el.previous('input').checked = true;

              // Stop the default event
              event.stop();
            }

            // AJAX submit
            submitFilterForm();
          });
        });
      }
      
      splash = $('splash_wrapper');
      if ($('splash_wrapper')) {
        new Carousel('splash_wrapper',
          $$('#splash_carousel .collection_splash'),
          $$('#splash_navigation a.collection_jumper'),
          {
            duration: 0.2,
            auto: true,
            frequency: 6,
            visibleSlides: 1,
            circular: true,
            wheel: false,
            effect: 'fade',
            jumperClassName: 'collection_jumper',
            selectedClassName: 'selected',
            beforeMove: function(carousel) {
              $$("#splash_navigation a.selected").each(function(el) {
                el.removeClassName('selected');
              });
            },
            afterMove: function(carousel) {
              id = carousel.current.getAttribute("id");
              if (!id.blank()) {
                $$("#splash_navigation a[rel="+id+"]").each(function(el) {
                  el.addClassName('selected');
                });
              }
            }
          }
        );
      }
    }
  }
}();

TGK.Products.Show = function() {
  var product_thumbs_carousel;
  var all_product_photos;
  var tab_carousel;

  return {
    // Initializes the product filters
    init: function() {
      product_thumbs_carousel = $('product_thumbs_carousel');
      all_product_photos = $('all_product_photos');
      tab_carousel = $('tab_carousel');

      if (product_thumbs_carousel) {
        new Carousel('product_thumbs_carousel',
          $$('#product_thumbs_carousel_content .thumb'),
          $$('#product_thumbs a.product_thumbs_nav'),
          {
            duration: 0.2,
            auto: false,
            visibleSlides: 4,
            circular: false,
            wheel: false,
            effect: 'scroll',
            controlClassName: 'product_thumbs_nav'
          }
        );
      }
      
      if (all_product_photos) {
        new Carousel('main_photo',
          $$('#all_product_photos .product_photo'),
          $$('#product_thumbs_carousel a.main_photo_jumper'),
          {
            duration: 0.2,
            auto: false,
            visibleSlides: 1,
            circular: false,
            wheel: false,
            effect: 'fade',
            jumperClassName: 'main_photo_jumper',
            selectedClassName: 'photo_selected'
          }
        )
      }
      
      if (tab_carousel) {
        new Carousel('tab_carousel',
          $$('#tab_carousel .tab_content'),
          $$('#product_details_tabs a.tab_jumper'),
          {
            duration: 0,
            auto: false,
            visibleSlides: 1,
            circular: false,
            wheel: false,
            effect: 'fade',
            jumperClassName: 'tab_jumper',
            selectedClassName: 'selected'
          }
        )
      }
    }
  }
}();

TGK.Builders = function(){
  var tab_carousel;
  var builder_form;
  var selectedClassName = 'selected';
  
  var tabDeselectAll = function() {
    $$("#overlay_tabnav a."+selectedClassName).each(function(el) {
      el.removeClassName(selectedClassName);
    });
  }

  var tabSelect = function(id) {
    $$("#overlay_tabnav a[rel="+id+"]").each(function(el) {
      el.addClassName(selectedClassName);
    });
  }
  
  var recordAndRefresh = function(el) {
    form = el.up('form');
    name = el.getAttribute('name');
    changed_input_tracker = $('changed_input_tracker');
    if (changed_input_tracker) {
      changed_input_tracker.value = name;
    }
    
    if (builder_form) {
      $('updating_bar').show();
      new Ajax.Request('/builders/refresh', {
        asynchronous: true,
        evalScripts: true,
        parameters: builder_form.serialize(),
        onComplete: function(request) {
          $('updating_bar').hide();
        }
      });
    }
  }
  
  var matchVisibleHeightToTab = function(current, morph) {
    var visibleHeightPx = current.getHeight().toString() + "px";
    if (morph) {
      new Effect.Morph(tab_carousel, {
        style: "height: "+visibleHeightPx,
        duration: 0.5
      });
    }
    else {
      tab_carousel.setStyle({height: visibleHeightPx});
    }
  }
  
  return {
    init: function() {
      tab_carousel = $('build_and_buy_tab_carousel');
      builder_form = $('builder_form');

      if (tab_carousel) {
        // Set visible height
        matchVisibleHeightToTab($('tab_design_styles'));
        
        new Carousel('build_and_buy_tab_carousel',
          $$('#build_and_buy_tab_carousel .tab_content'),
          $$('#overlay_tabnav a.tab_jumper', '#tgk_ol_nav a.tab_nextprev'),
          {
            duration: 0.1,
            auto: false,
            visibleSlides: 1,
            circular: false,
            wheel: false,
            effect: 'fade',
            jumperClassName: 'tab_jumper',
            controlClassName: 'tab_nextprev',
            selectedClassName: selectedClassName,
            beforeMove: function(carousel) {
              tabDeselectAll();
            },
            afterMove: function(carousel) {
              var current = $(carousel.current);

              // Select the tab
              id = current.getAttribute("id");
              if (!id.blank()) {
                tabSelect(id);
              }
              
              // Morph the visible size
              matchVisibleHeightToTab(current, true);
              
              // Hide/show the next/prev links
              firstTab = $('tab_design_styles');
              lastTab = $('tab_design_extras');
              prev = $$('#tgk_ol_nav li.back a').first();
              next = $$('#tgk_ol_nav li.next a').first();
              if (firstTab == current) {
                prev.hide();
              }
              else {
                prev.show();
              }
              if (lastTab == current) {
                next.hide();
              }
              else {
                next.show();
              }
            }
          }
        )
      }
      
      if (builder_form) {
        save_for_later_button = $('builder_save_for_later_button');
        if (save_for_later_button) {
          save_for_later_button.observe('click', function(event) {
            $('builder_task').value = 'save_for_later';
          });
        }

        add_to_cart_button = $('builder_add_to_cart_button');
        if (add_to_cart_button) {
          add_to_cart_button.observe('click', function(event) {
            $('builder_task').value = 'add_to_cart';
          });
        }

        save_back_to_cart_button = $('builder_save_back_to_cart_button');
        if (save_back_to_cart_button) {
          save_back_to_cart_button.observe('click', function(event) {
            $('builder_task').value = 'save_back_to_cart';
          });
        }

        builder_form.observe('submit', function(event){
          event.stop();
          task = $('builder_task').value;
          if (task != 'refresh') {
            builder_form.submit();
          }
        });
        this.handleFormChangesForInputs(builder_form.getElements());
      }
      
      TGK.Utility.SelectBox.attach();
      TGK.Utility.Tooltip.attach();
    },
    
    handleFormChangesForInputs: function(elements) {
      elements.each(function(el){
        el.observe('change', function(event) {
          input = event.findElement('input');
          recordAndRefresh(input);
        });
        el.observe('faux_select_box:change', function(event) {
          input = event.findElement('input');
          recordAndRefresh(input)
        });
      });
    }
  }
}();

TGK.Utility = function() {
  return {
    // Mark the 'last' elements matching the given expression in the given container with the
    // '.last' class.
    markLast: function(container, expression) {
      container = $(container);
      if (container) {
        last_exp = expression + ":last"
        container.select(last_exp).each(function(el){
          el.addClassName('last');
        });
      }
    }
  };
}();

TGK.Utility.SelectBox = Class.create({
  initialize: function(container, options) {
    container = $(container);
    this.container = container;

    this.containerId = this.assignId();
    this.optionList = container.down('.faux_select_box_options');
    this.optionLinks = container.select('.option a');
    this.trigger = container.down('.trigger');
    this.hiddenField = container.down('input[type=hidden]');
    
    this.options = Object.extend({
      boundingBox: $$('body').first()
    },options || {});
    
    TGK.Utility.SelectBox.instances.push(this);
    
    // Move options list to the staging area just before the body tag
    this.stageOptions();
    
    // Select the default value
    this.selectDefault();
    
    // Show select box options when trigger clicked
    this.trigger.observe('click', function(event) {
      event.stop();
      this.showOptions();
    }.bindAsEventListener(this));
    
    this.optionLinks.each(function(link){
      link.observe('click', function(event) {
        event.stop();
        link = event.findElement('a');
        this.selectOption(link);
      }.bindAsEventListener(this));
    }.bind(this));
    
    // Any click not within this select box should revert to the default
    document.observe('click', function(event) {
      element = event.findElement("#"+this.containerId);
      if (!element) {
        this.selectDefault();
        this.hideOptions();
      }
    }.bindAsEventListener(this));
  },
  assignId: function() {
    elementId = this.container.readAttribute('id');
    if (elementId == null || elementId.blank()) {
      elementId = "faux_select_box_"+TGK.Utility.SelectBox.instances.length
      this.container.writeAttribute('id', elementId);
    }
    return elementId;
  },
  stageOptions: function() {
    this.optionList = this.optionList.remove();
    $$('body').first().insert({
      bottom: this.optionList
    });
    
    this.optionList.setStyle({
      position: 'absolute',
      display: 'none',
      top: this.calculatedVisiblePosition().top.toString() + "px",
      left: this.calculatedVisiblePosition().left.toString() + "px",
      zIndex: '9999'
    })
    
  },
  showOptions: function() {
    // Hide others
    TGK.Utility.SelectBox.instances.each(function(select_box){
      select_box.hideOptions();
    });
    
    this.optionList.addClassName('visible');
    this.optionList.show();
    optionsHeight = this.optionList.getHeight();
    optionsMaxHeight = 400;
    if (optionsMaxHeight && optionsHeight > optionsMaxHeight) {
      this.optionList.setStyle({
        height: optionsMaxHeight+'px'
      })
    }
    this.handleOverflow();
  },
  hideOptions: function() {
    this.optionList.removeClassName('visible');
    this.optionList.hide();
  },
  calculatedVisiblePosition: function() {
    selectBoxOffset = this.container.cumulativeOffset();
    return {
      top: selectBoxOffset.top - 1,
      left: selectBoxOffset.left - 26
    }
  },
  selectOption: function(link) {
    if (link) {
      value = link.readAttribute('rel');
      this.optionList.select('a').each(function(a){
        a.removeClassName('selected');
      });
      link.addClassName('selected');
      this.hideOptions();
      
      this.trigger.innerHTML = link.innerHTML
      this.setFormValue(value);
    }
    else {
      selectDefault();
    }
    
    this.hideOptions();
  },
  selectDefault: function() {
    link = this.optionList.select('a.selected').first();
    if (link) {
      this.selectOption(link);
    }
    else {
      this.setFormValue('');
      this.trigger.innerHTML = "Choose..."
    }
  },
  handleOverflow: function() {
    bottomOfOptions = this.optionList.cumulativeOffset().top + this.optionList.getHeight();
    bottomOfBoundingBox = this.options.boundingBox.cumulativeOffset().top + this.options.boundingBox.getHeight();
    
    if (bottomOfOptions > bottomOfBoundingBox) {
      overshoot = bottomOfOptions - bottomOfBoundingBox;
      targetHeight = this.optionList.getHeight() - overshoot;
      if (targetHeight > 20) {
        targetHeight = targetHeight - 20;
      }
      this.optionList.setStyle({
        height: targetHeight+"px"
      });
    }
    
  },
  setFormValue: function(value) {
    oldValue = this.hiddenField.value;
    this.hiddenField.value = value;
    if (!(oldValue == value)) {
      this.hiddenField.fire('faux_select_box:change');
    }
  }
});

Object.extend(TGK.Utility.SelectBox, {
  instances: [],
  
  attach: function(elements) {
    if (elements == undefined) {
      elements = $$(".faux_select_box");
    }
    elements.each(function(select_box){
      // new TGK.Utility.SelectBox(select_box, {boundingBox: $('build_and_buy_tab_carousel')});
      new TGK.Utility.SelectBox(select_box);
    });
  }
});

TGK.Utility.Tooltip = function() {
  return {
    attach: function(elements) {
      if (elements == undefined) {
        elements = $$(".tippable");
      }
      elements.each(function(tippable){
        new Tip(tippable, tippable.getAttribute('rel'), { style: 'tgkv5', hideOthers: true });
      });
    }
  };
}();

document.observe('dom:loaded', function(){
  TGK.Homepage.init();
  
  // Force users to use the sign in form in the page
  var sign_in_link = $('sign_in_link');
  if (sign_in_link) {
    sign_in_link.observe('click', function(event){
      event.stop();
    })
  }

  // Product Index Filters
  TGK.Products.Index.init();

  // Product Pages
  TGK.Products.Show.init();
  
  TGK.Builders.init();
  
  if ($('contents_show_page')) {
    if (location.pathname == '/c/faqs') {
      var answerCount = 1;
      
      $$(".section").each(function(section) {
        section.wrap(
          "div", {'class': "frame_content"}
        ).wrap(
          "div", {'class': "frame_bl"}
        ).wrap(
          "div", {'class': "frame_br"}
        ).wrap(
          "div", {'class': "frame_tr"}
        ).wrap(
          "div", {'class': "frame_tl pane"}
        );
        
        var answerDiv = null;
        
        section.childElements().each(function(child) {
          var tagName = child.tagName;
          
          if (tagName == 'H4') {
            var id = "answer_" + answerCount++;
            answerDiv = new Element('div', {'class': 'answer', 'id': id});
            child.insert({
              after: answerDiv
            });
            answerDiv.hide();
            
            var h4Content = child.innerHTML
            var anchor = new Element('a', {'href': "#"+id, 'class': 'question'});
            anchor.update(h4Content);
            child.update(anchor);
            anchor.observe('click', function(event){
              event.stop();
              question = event.findElement('h4')
              Effect.toggle(question.next('.answer'), 'slide', {duration: 0.1});
              return false;
            });
          }
          else if (tagName == 'H3') {}
          else {
            if (answerDiv) {
              answerDiv.insert({
                bottom: child
              });
            }
          }
        });
      });
    }
  }
});