(function($){

 /******
  F'n
  ***/
  var scroll_remainder = function(){
    return $(document).height() - $(window).height() + $(window).scrollTop();
  };
  

  var open_close_time = 292,
      footer_open = false;
  var open_footer = function(){
    footer_open = true;
    var h = $('#home-container').height()-100;
    $('#ft-container').animate({height:130}, open_close_time);
    $('#home-container').animate({height:(h > 509)? h : 509},
                                 open_close_time,
                                 function(){ body_height-=100;} );
    $('html,body').animate({scrollTop:100 + scroll_remainder()}, open_close_time);
  };
  
  var close_footer = function(){
    footer_open = false;
    $('#home-container').animate({height:$('#home-container').height()+100},
                                 open_close_time,
                                 function(){ body_height+=100; } );
    $('#ft-container').animate({height:30}, open_close_time);
  };
  
  var body_height;
  
  var adjust_body = function(){
    if(typeof body_height == 'undefined') body_height = $('#home-container').height();    
    var diff = $(window).height() - $('#ft-container').height() - body_height,
	      h = body_height + diff;
    if(diff > 0) $('#home-container').css('height', (h > 509)? h : 509);
    
    var nw = (w = $(window).width(), w < 970 ) ? 970 : w;
    $('#home-container, #ft-container').width(nw).css('overflow', 'hidden');
  }; 
  
  var toggle_results = function(e){
    e.preventDefault();
    if ( $('.results-header .close-results').toggleClass('closed').hasClass('closed') ) {
      $('#results, .results-pagination').hide();
      $('a.hide-results').text('Show Results');
    } else {
      $('#results, .results-pagination').show();
      $('a.hide-results').text('Hide Results');
    }
  };
  
  var page_size = 10,
      page_num;
  var paginate_results = function(){
    var all = $('#all-results li.selected'),
        pages = Math.floor( all.size() / page_size ) + ((all.size() % page_size == 0) ? 0 : 1),
        results = $('#results').html(''),
        next = $('.results-pagination .next');
        
    $('.results-pagination .num').remove();
    
    for (n=0; n < pages; n++) (function(num){
      var els = all.slice( num*page_size, (num+1)*page_size );
      els.each(function(i,tem){
        var kore = $(tem);
        kore.removeClass('a').removeClass('b');
        if(i%2==0) kore.addClass('a');
        else kore.addClass('b');
      });
      var ul = $('<ul/>')
        .addClass('results')
        .attr('id', 'results-page-'+(num+1))
          .append(els.clone())
        .appendTo(results);
          
      var a = $('<a href="#" />')
        .addClass('num')
        .text( num + 1 )
        .insertAfter(next)
        .click(function(e){
          e.preventDefault();
          show_page(num);
        });
        
    })(n);
    
    page_num = 0;
    show_page(0);
  };
  
  var show_page = function(n){
    var nums = $('.results-pagination .num'),
        total = nums.size(),
        num = (n < 0)? 0 : (n >= total)? total - 1 : n;
    nums.filter(':eq(' + (total - num - 1) + ')')
      .addClass('selected')
      .siblings('.num')
        .removeClass('selected');
        
    $('#results .results:eq(' + num + ')')
      .show()
      .siblings('.results')
        .hide();
        
    if (num == 0) $('.results-pagination .prev').hide();
    else $('.results-pagination .prev').show();
    
    if (num+1 == total) $('.results-pagination .next').hide();
    else $('.results-pagination .next').show();
    page_num = num;
  };
  
  var next_page = function(e){
    if(e) e.preventDefault();
    show_page( page_num + 1 );
  };
  
  var prev_page = function(e){
    if(e) e.preventDefault();
    show_page( page_num - 1 );
  };
  
  var auto_val = function(){
    $('input.text.default, textarea.default').each( function(i,tem){
      var kore = $(tem);      
      kore[0].default_val = kore.val();
      kore.focus(function(){
          if ( $(this).val() == this.default_val )
            $(this).val('').removeClass('default');
          })
        .blur(function(){
          if ( $(this).val().match(/^\s*$/gm) )
            $(this).val(this.default_val).addClass('default');
          });
    } );
  };

  
  var init_store_gallery = function(){
    var thumbs = $('.store-thumbnails .thumbs li a'),
        con = $('.store-image');
    thumbs.each(function(i,tem){
      var kore = $(tem),
      img = $('<img />')
        .load(function(){
          $(this).fadeIn();
          })
        .css({position:'absolute', top:'0px', left:'0px', 'z-index':30})
        .appendTo(con)
        .hide()
        .attr('src', kore.attr('href'));
      kore.click(function(e){
        e.preventDefault();
        store_swap_image(i);
      });
      if(i==0) img.css('z-index', 40);
    });
  };
  
  var store_swap_image = function(n){
    $('.store-image img:eq('+n+')').css('z-index',40).siblings('img').css('z-index',30);
  };
  
  var store_open_lightbox = function(n){
    
  };
  
  var hd_height;
  var stretch_body = function(){
    var wh = $(window).height(),
        hd = $('#hd-container'),
        bd = $('#bd-container'),
        ct = $('#content');
    
    bd[0].style.height = null;
    ct[0].style.height = null;
    
    if (typeof hd_height == 'undefined') hd_height = hd.height();
    bd[0].natural_height = bd.height();
    if (hd_height + bd[0].natural_height < wh){
      bd.css('height', wh - hd_height);
      ct.css('height', wh - hd_height - 102);
    } else {
      bd[0].style.height = null;
      ct[0].style.height = null;
    }
  };

  // Bridal Resource
  var bridal_stores,
      bridal_tooltippin = true;
  var bridal_alphabetize = function(els){
    return $( $.makeArray( els )
      .sort(function(a,b){ return ($(a).find('.store-link').text().toLowerCase() < $(b).find('.store-link').text().toLowerCase()) ? -1 : 1; })
    );
  };
    
  var bridal_hide_tooltip = function(){
    if (bridal_tooltippin) return;
    $('.select-store-tooltip').hide();
    $('.bridal-stores-buttons').show();
    $('.bridal-selected-stores ul').show();
    bridal_tooltippin = true;
  };
  
  var bridal_show_tooltip = function(){
    if (!bridal_tooltippin) return;
    $('.select-store-tooltip').show();
    $('.bridal-stores-buttons').hide();
    $('.bridal-selected-stores ul').hide();
    bridal_tooltippin = false;
  };
  
  var bridal_add_store = function(slug){   
    if ($('.selected-store-'+slug).size()) return;
    
    var storeCount = $("li.store-box").size() + 1;
    var store = $('.store-'+slug),
        img = store.find('.image-url').attr('href'),
        default_text = 'Enter Requested items from ' + store.find('.store-link').text();
    
    var textarea, store_key, store_slug;
    if ($("#id_store_slug_" + storeCount).size() == 0) {
        textarea = $('<textarea type="text" name="store_list" id="id_store_list_' + storeCount + '">' + default_text + '</textarea>'),
        store_key = $('<input type="hidden" name="store_key" value="' + $('li.store-' + slug + ' > input[type="hidden"]').val() + '" id="id_store_key_' + storeCount + '" />');
        store_slug = $('<input type="hidden" name="store_slug" value="' + slug + '" id="id_store_slug_' + storeCount + '" />');
    } else {
        textarea = $("#id_store_list_" + storeCount).remove();
        store_key = $("#id_store_key_" + storeCount).remove();
        store_slug = $("#id_store_slug_" + storeCount).remove();    
    }
      
    textarea[0].default_text = default_text;
    textarea.focus(function(){ if ($(this).val() == this.default_text) $(this).val(''); });

	$('<li class="store-box selected-store-'+slug+'" />').append(
        $('<div class="store-image" />').append(
          $('<img />').attr('src', img))
        ).append(textarea).append(store_key).append(store_slug)
      .appendTo('.bridal-selected-stores ul:first');
      
      adjust_body();
  };
  
  var bridal_add_recip = function() {
      var recipCount = $("input[name='recipient_name']").size() + 1;
      var recip = $('<tr><td><label for="id_recipient_name_' + recipCount + '">Name</label>' +
          '<input id="id_recipient_name_' + recipCount + '" type="text" value="" name="recipient_name" /></td>' +
          '<td><label for="id_recipient_email_' + recipCount + '">Email</label>' +
          '<input id="id_recipient_email_' + recipCount + '" type="text" value="" name="recipient_email" /></td>');
      recip.insertBefore("#add-recip-row");
      return false;
  };
  
  var bridal_remove_store = function(slug){
    return $('.selected-store-'+slug).remove();
  };
  
  var bridal_save_list = function() {
    $(".bridal_form").submit();
    return false;
  }
  
  var bridal_reorder_list = function(){
    var ul = $('.bridal-stores-list'),
        checked = ul.find('input:checked').closest('li');
        
    ul.find('li').removeClass('selected');

    bridal_alphabetize( checked
      .remove()
      .addClass('selected')
    ).prependTo(ul);
      
    var unchecked = ul.find('li').not('.selected');
    bridal_alphabetize( unchecked.remove() ).appendTo(ul);
    
    ul.find('input[type=checkbox]')
      .unbind('click')
      .click(bridal_reorder_list);
     
    checked.each(function(i,tem){ bridal_add_store(tem.className.match(/store-([a-z0-9-]+)/)[1]); });
    unchecked.each(function(i,tem){ bridal_remove_store(tem.className.match(/store-([a-z0-9-]+)/)[1]); });
    
    if (checked.size()) bridal_hide_tooltip();
    else bridal_show_tooltip();
    
    $("#add-recip").click(bridal_add_recip);
    
    $("#save-your-list").click(bridal_save_list);
    
  };
  
  
  
  var bridal_init = function(){
    bridal_stores = $('.bridal-available-stores li');
    $('#send-your-list').click(function(e){ e.preventDefault(); $('.bridal-send-form').show(); });
    bridal_reorder_list();
    
    //Upon an initial load we have an extra set, remove them
    if ($("#id_store_slug_1").val() == '') {
        $("#id_store_slug_1").remove();
        $("#id_store_list_1").remove();
        $("#id_store_key_1").remove();
    } else {
        $("#send-your-list").click();
    }
    
    //Take the ones that are left and check boxes if need be and arrange them
    $("input[name='store_slug']").each(function(i,tem) {
        $(".store-" + $(tem).val() + " > input[type='checkbox']").attr("checked", "checked");
        bridal_reorder_list();
    });
    
    
  };

  
 /******
  DOM Ready
  ***/
  $(function(){
    if($('#home').size()){
      adjust_body();
      $(window).resize(adjust_body);
      
      var butan = $('<a href="#" id="open-close-footer">Open</a>')
        .appendTo($('#ft'))
        .click(function(e){
          e.preventDefault();
          if($(this).toggleClass('close').hasClass('close'))
            open_footer();
          else
            close_footer();
        });
        
    } else {
      $(window).resize(stretch_body);
      stretch_body();
    }
    
    if($('#map-wrap #map').size()){        
      $('#directory-search-form .select select').show().elect();
      var storez = $('#all-results li');
      $(window).load(function(){
        var map = window.map = Mappu({stores: storez,
                            aux: '#all-aux .aux',
                            container: '#map'
                            });
        window.search = SearchJockey({mappu: map, tags: '#tags'});
        window.info = InfoJockey(map);
      });
                                                    
      $('.results-header .hide-results, .results-header .close-results').click(toggle_results);
      paginate_results();
      
      $('.results-pagination .next').click(next_page);
      $('.results-pagination .prev').click(prev_page);
      
      $('#directory-search-form .all button').click(function(e){
        if ( list = $('#all-listings'), list.toggleClass('enabled').hasClass('enabled') )
          list.show();
        else
          list.hide();
      });
      
    }
    
    if ( $('.store-thumbnails').size() ){
      init_store_gallery();
    }
    
    $('input[name=notice]').filter(':first').each(function(i,tem){
      var notice = $('<div id="notice"><p>'+$(tem).val()+'</p></div>')
        .insertAfter($('#content h3, #content h1').filter(':first'));
      setTimeout(function(){ notice.fadeOut(192); }, 4920);
    });
    
    auto_val();
    
    $('#nav-bar ul.nav li').hover(function(){
      $(this).addClass('hover');
    }, function(){
      $(this).removeClass('hover');
    });
    
    if($.browser.msie)
    $('#nav-bar ul.nav li a').hover(function(){
      $(this).parent().addClass('hover');
    });
    
    
    var do_search = function(num){
      var n = num || 0,
          kore = $('#type-ahead-input'),
          tags = kore[0].all_tags,
          stores = [];
      window.search.enabled_tags = {};
      $('.sticky').removeClass('sticky');
      window.map.unstick_tooltip();
      if ( kore[0].current_val && (kore[0].current_val == kore.val()) ) return;
      if ( tags.length ) {
        if (window.map.tooltip_expanded) window.map.collapse_tooltip();
        window.map.really_hide_tooltip();
        kore.val(tags[n]);
        kore[0].current_val = tags[n];
        window.search.go_tag(tags[n]);
        stores = window.search.enabled_stores();
        $('#all-results li').removeClass('selected');
        for(n=0; n<stores.length; n++)
          $('#all-results #store-'+stores[n].slug).addClass('selected');
        paginate_results();
        $('#directory-search-results').show();
        $('#map-tabs .count').show();
        stretch_body();
      } else {
        kore.val('');
        kore[0].all_tags = [];
        window.search.apply_tags();
      }
      
      $('#all-listings').removeClass('enabled').hide();
      
      $('.results-header .results-num').text(stores.length);
      var upper = 0, lower = 0, middle = 0;
      for (n=0; n<stores.length; n++ ) {
       if (stores[n].level == 0) lower++;
       else if (stores[n].level == 1) middle++;
       else if (stores[n].level == 2) upper++;
      }
      
      
      
      $('#map-tabs .first .count').text(lower);
      $('#map-tabs .second .count').text(middle);
      $('#map-tabs .third .count').text(upper);
      $('.results-header span strong').text(kore.val());
      $('#type-ahead ul').hide();
    };
    
    $('#type-ahead-input').after('<div id="type-ahead"><ul></ul></div>');
    
    $('#directory-search-form .search form').submit(function(e){ e.preventDefault(); return false; })
    
    $('#type-ahead-input').keyup(function(e){
      var kore = $(this);
      // Enter
      if((e.keyCode == 13)) {
        do_search(kore[0].current_n);
        e.preventDefault();
        e.stopPropagation();
      // Esc
      } else if (e.keyCode == 27) {
        kore[0].all_tags = [];
        $('#type-ahead ul').hide();
      // Up
      } else if (e.keyCode == 38) {
        if(kore[0].current_n == null) return;
        kore[0].current_n--;
        if(kore[0].current_n < 0) kore[0].current_n = 0;
        $('#type-ahead ul li').removeClass('hover').eq(kore[0].current_n).addClass('hover');
      // Down
      } else if (e.keyCode == 40) {
        if(kore[0].current_n == null) kore[0].current_n = 0;
        else kore[0].current_n++;
        var total = $('#type-ahead ul li').size();
        if(kore[0].current_n >= total) kore[0].current_n = total-1;
        $('#type-ahead ul li').removeClass('hover').eq(kore[0].current_n).addClass('hover');
      } else {
        kore[0].current_n = null;
        input_val(kore);
      }
    }).blur(function(){
      setTimeout(function(){$('#type-ahead ul').hide();}, 0);
    });
    
    $('#directory-search-form .search button').click(function(e){ do_search(); });
    
    function input_val(kore) {
      var val = kore.val(),
          tags = window.search.quick_search(val),
          ul = $('#type-ahead ul').html('').show();
          
      kore[0].all_tags = [];
      if(tags.length == 0)
        ul.append('<li class="no-results">No Results Found</li>');
      else {
        tags = tags.slice(0,10);
        for (n=0; n<tags.length; n++) (function(num){
          var li =
            $('<li class="result">' + tags[n] + '</li>')
              .appendTo(ul)
              .mousedown(function(e){ e.stopPropagation(); e.preventDefault(); do_search(num);})
              .hover(function(){ $(this).addClass('hover') }, function(){ $(this).removeClass('hover') });
        })(n);
        kore[0].all_tags = tags;
      }
    }
    
    if (! $('#map-wrap #map').size()) {
      $('select').elect(); }
    
    if ($('#map-wrap #map').size()) {
        
      $('#map-tabs li.first').click(function(e){
        window.map.zoom_out();
        setTimeout(function(){window.map.swap_level(0);}, 200);
        $(this).addClass('selected');
        $('#map-tabs li.third, #map-tabs li.second').removeClass('selected');
      });
      $('#map-tabs li.second').click(function(e){
        window.map.zoom_out();
        setTimeout(function(){window.map.swap_level(1);}, 200);
        $(this).addClass('selected');
        $('#map-tabs li.first, #map-tabs li.third').removeClass('selected');
      });
      $('#map-tabs li.third').click(function(e){
        window.map.zoom_out();
        setTimeout(function(){window.map.swap_level(2);}, 200);
        $(this).addClass('selected');
        $('#map-tabs li.first, #map-tabs li.second').removeClass('selected');
      });

      $('#zoom .zoom-out')
        .click(function(e){
          e.preventDefault();
          map.zoom_out();
          $(this).hide();
          $('#zoom .zoom-in').show();
        })
        .hide();
      $('#zoom .zoom-in')
        .click(function(e){
          e.preventDefault();
          map.zoom_in();
          $(this).hide();
          $('#zoom .zoom-out').show();
        });
      
      $('<img id="parking-map" src="/media/images/parking-map.png" />')
        .hide()
        .appendTo('#map-wrap #map');
     
      $('#amenities .amenity').each(function(i,tem){
        var k = $(tem),
            text = k.find('a:first').text();
        k.hover(function(){
          $('#amenities-tooltip').css({top:i*39+8}).show().find('span:first').text(text);
        }, function(){
          $('#amenities-tooltip').hide();
        }).click(function(e){
          var kore = $(this),
              type = kore[0].className.replace('amenity ', '');
          e.preventDefault();
          kore.toggleClass('on').siblings('li.amenity').removeClass('on');
          $('#map-wrap #map .amenity').hide();
          if (kore.hasClass('on')) $('#map-wrap #map .'+type).fadeIn(124);
        });
        
      });
        
      // Columnize all listings
      // var dummy = $('.all-listings-inner .col-1')
      //               .clone()
      //               .css({position:'absolute',top:-30000})
      //               .show()
      //               .appendTo('body'),
      //     total_height = dummy.height(),
      //     cats = $('#all-listings .listing-cat').remove(),
      //     h_per_col = Math.ceil( total_height / 4 ) - 100,
      //     inner = $('#all-listings .all-listings-inner');
      // inner.find('.col-1').remove();
      // dummy.remove();
      // var n_all = 0;
      // for(n=0; n<4; n++){
      //   var div = $("<div class='col-"+(n+1)+" listing-col' />")
      //     .css({position:'absolute',top:-30000})
      //     .appendTo('body');
      //   while ((div.outerHeight() < h_per_col) && (n_all<cats.size())) {
      //     cats.eq(n_all).clone().appendTo(div);
      //     n_all++;
      //   }
      //   div
      //     .css({position:'relative',top:0})
      //     .appendTo(inner);
      // }
    }
    
        
    // Sort Stores alphabetically
    $( $.makeArray( $("#all-results li").remove() )
      .sort(function(a,b){ return (a.id < b.id) ? -1 : 1; })
    ).appendTo('#all-results');
    
    
    $('.listings-heading .close-listings').click(function(e){
      e.preventDefault();
      if ( list = $('#all-listings'), list.toggleClass('enabled').hasClass('enabled') )
        list.show();
      else
        list.hide();
    });
    
    $('#directory-search-form .select select').change(function(){
      var val = $(this).val(),
          str = $('#directory-search-form .select option[value='+val+']').text();
      if ( !val.match(/^\s*$/) && !(typeof val == 'undefined') ) {
        try {
          var store = window.map.get_store(val);
          
          if (this.preselected) {
            $('#map-tabs li:eq('+store.level+')').click();
            this.preselected = false;
          } else {
            window.location = store.url;
            return true;
          }
          
          $('.sticky').removeClass('sticky');
          window.map.unstick_tooltip();
          window.search.enabled_tags = {};
          window.search.go_tag(str);
          window.search.apply_tags();
          if (!store) return;
          $('#directory-search-results').hide();
          $('#map-tabs .count').hide();
          window.map.hold_ups = 0;
          if (store.level == 0)
            $('#map-tabs .lower').click()
              .find('.count').html('&bull;').show();
          else
            $('#map-tabs .upper').click()
              .find('.count').html('&bull;').show();
          $('#directory-search-form .select .elect-value').text(store.name);
          window.map.show_tooltip(store.slug);
          stretch_body();
        } catch(e) {}
      }
      $('#all-listings').removeClass('enabled').hide();
    });
    
    var filter_events = function(k, v) {
      var url = window.location.href.split('?')[0],
          search = window.location.search.substr(1),
          key = encodeURIComponent(k), val = encodeURIComponent(v);
      if (v.match(/^\s*$/) || (v == null))
        search = search.replace(new RegExp('&?' + key + '=[^&]*'), '')
      else if (search.length == 0)
        search = key + '=' + val;
      else if (search.match(key))
        search = search.replace(new RegExp(key + '=[^&]*'), key+'='+val);
      else
        search += '&'+key+'='+val;
      window.location.search = '?'+search;
    };
    
    $('select#event-time-frame').change(function(){
        filter_events('time_frame', $(this).val());
    });
    
    $('select#event-categories').change(function(){
        filter_events('category', $(this).val());
    });
    
    
    // Create Share This popup
    var stp =
      $('<div id="share-this" />').appendTo('body').hide()
        .append('<div class="shadow" />')
        .append('<div class="inner">' + 
                  '<h3>Share</h3>' +
                  '<a class="target email" href="#" target="_blank">Email</a>' + 
                  '<a class="target facebook" href="#" target="_blank">Facebook</a>' + 
                  '<a class="target twitter" href="#" target="_blank">Twitter</a>' +
                '</div>');
    $('<a class="close" href="#">&times;</a>')
      .appendTo(stp.find('.inner'))
      .click(function(e){
        e.preventDefault();
        $('#share-this').hide();
      });
    
    var load_share_this = function(url, title, tiny){
      
      $('#share-this a.facebook').attr('href', "http://www.facebook.com/share.php?u="+url+"&t="+title);
      $('#share-this a.email').attr('href', "mailto:?body="+url+"&subject="+title);
      $('#share-this a.twitter').attr('href', "http://twitter.com/home?status="+title+"%20"+tiny);
      
        $('#share-this').show();
    };
    
    $('a.share-this').click(function(e){
      e.preventDefault();
      var kore = $(this);
      $.getJSON('http://api.bit.ly/shorten?longUrl=' + kore.attr('href') +   
                   '&version=2.0.1&login=gardensmall' +
                   '&apiKey=R_88c152f84eafa34ba6adbcd7b0c0ab3b' +
                   '&format=json&callback=?',
                   function(data){
                     var tiny;
                     for(var i in data.results)
                       tiny = encodeURIComponent(data.results[i].shortUrl);
                     load_share_this(kore.attr('href'), kore.attr('title'), tiny);
                   });                     
    });
    
    $('ul.nav li').click(function(e){
      if(a = $(this).find('a'), a.size() && a.attr('href'))
        window.location = a.attr('href');
    });
        
    var mall = ((match = window.location.hostname.match(/(gardens|waterside|somerset|millenia)/), match) ? match :
                window.location.href.match(/\/-\/(gardens|waterside|somerset|millenia)/))[1];
    
    $('.rich-text a, #item-list a').each(function(){
      var in_host = new RegExp("//[^/]+" + mall),
          in_path = new RegExp("/-/" + mall);
      if (!this.href.match(in_host) && !this.href.match(in_path))
        $(this).attr('target', '_blank');
    });
    
    if(window.location.hash.match(/^#[a-z0-9-]+$/i))
      $(window).load(function(){
        var select = $('#directory-search-form .select select').val(window.location.hash.substr(1));
        select[0].preselected = true;
        setTimeout(function(){ select.change(); }, 0);
      });
    
    
    // Bridal Resource init
    if ($('#bridal-list-widget').size()) bridal_init();
    
    if ($(".bridal-send-form").size()) {
        $("#add-recip").click(bridal_add_recip);
    }
    
    if ($("#download-bridallist-pdf").size()) {
        $("#download-bridallist-pdf").click(function() {
            window.location.href = window.location + "/pdf";
            return false;
        });
    }
    
    
    // Even out adjacent blocks of directions on directions page
    if ($('.directions-blocks').size()) {
      $('.directions-blocks div.left').each(function(i,tem){
        var kore = $(tem),
            kore_h = kore.outerHeight(),
            tsugi = kore.next('.right'),
            tsugi_h = kore.outerHeight();
        kore.add(tsugi).css({ height: (tsugi_h > kore_h) ? tsugi_h : kore_h });
      });
    }
    
  });
  
 /******
  Fully Loaded
  ***/
  $(window).load(function(){
      
    if($('#home-container').size()) adjust_body();
    else stretch_body();
  });


})(jQuery);



(function($) {
    if (!window['forbes']) {
	    window['forbes'] = {};
    }
    
    forbes.isNumeric = function(val) {
        if ((val - 0) == val && val.length > 0) {
            return true;
        }
        return false;
    }
    
    forbes.updateTotals = function() {
        var total = 0;
		var purchase_fee = 0;

        $("input[name='card_value']").each(function(i) {
            var tr = $(this).closest('tr');
            var value = $(this).val().replace(/\$/g, '');
            $(this).val(value);
            var qty = tr.find("input[name='card_quantity']").eq(0).val();
            
            if (forbes.isNumeric(value) && forbes.isNumeric(qty)) {
                var sub_total = parseFloat(value) * parseInt(qty);
                // $(this).nextAll("span[name='sub_total']").text("$" + sub_total.toFixed(2));
                tr.find('span[name=sub_total]').text("$" + (sub_total + 0).toFixed(2));
                total += sub_total;
				purchase_fee += (2 * parseInt(qty));
            }

        });
		total += purchase_fee
        
        if ($("input[name='shipping_method']:checked").length > 0) {
            total += parseFloat($("input[name='shipping_method']:checked").val());
        }

		$("#purchase-fee").text("$" + purchase_fee.toFixed(2));
        $("#total").text("$" + total.toFixed(2));

    }
    
    forbes.bindBlur = function(e, obj) {
        var val = $(obj).val()
        
        if (!forbes.isNumeric(val)) {
            // alert('Please enter an number.');
            // console.log('Please enter an number.');
            //e.preventDefault();
            // var id = $(obj).attr("id");
            // setTimeout (function() { $("#" + id).get(0).focus(); }, 10 );
            
            // return false;
        }
        forbes.updateTotals();
    }
    
    forbes.parseErrors = function(){
        
        if ($("input[name='shipping_same']:checked").length > 0) {
            $("#shipping_info").hide();
        }

        var boxes = $('#gift_cards, #shipping_method, #billing-information, #shipping-information, #cc-information, #terms');
                
        boxes.each(function(i,tem){
          var dis = $(tem),
              errors = [];
          dis.find('.errors').each(function(n, met){
            var kore = $(met);
            if (!kore.text().match(/^\s*$/gim)) {
                // SPECIAL CASE FOR SHIPPING METHOD
                // if (dis.attr('id').match('shipping_method')) {
                //     errors.push('Shipping Method'+': '+kore.text());
                // } else {
                    errors.push(kore.next('label').text()+': '+kore.text());
                // }
            }
          });
          
          if (errors.length) {
            dis.addClass('errored-box').show();
          
            var ul = $('<ul class="gift-card-errors"></ul>')
              .appendTo('#sub-sidebar')
              .css({top: dis.offset().top - 160 + 20 });
            for (var i=0; i<errors.length; i++)
              ul.append('<li>' + errors[i] + '</li>');
          }
          
        });
    };
    
    $(document).ready(function() {
        
        var fix_share_this_links = function(){
          $('a.share-this').each(function(i, tem){
            if ($(tem).attr('href').match(/^\/\//) != null)
              $(tem).attr('href', window.location.protocol + $(tem).attr('href'));
          });
        };
        
        fix_share_this_links();
        
        function remove_card(e){
          if(e) e.preventDefault();
          if(!this.tagName || (this.tagName.toLowerCase() != 'a')) return;
          
          if ($(this).closest('tr').find("#add_another").size() == 1) {
              $(this).closest('tr').find("#add_another").closest('td').remove().appendTo($(this).closest('tr').prev('tr'));
              $("#add_another").click(add_another);
          }
          $(this).closest('tr').remove();
          if ($("td.card-val").size() == 1) {
              // Can't remove the last row
              $("a.remove-card").closest('td').hide();

          }
          forbes.updateTotals();

          return false;
        }
        
        $("#add_another").click(add_another);
        $("a.remove-card").click(remove_card);
          
        function add_another(v,q) {
            // var cloneCount = $("input[name='card_value']").length + 1;
            var cloneCount = $("td.card-val").size() + 1;
            if (cloneCount > 1) $("a.remove-card").closest('td').show();
            var val = (typeof v == 'string') ? v : '',
                quantity = q || '';
            var cloneFields = $('\
                <tr> \
                  <td class="card-val"><div class="row"> \
                    <label for="id_card_value_' + cloneCount + '">Card Value</label> \
                    <input type="text" name="card_value" value="'+val+'" id="id_card_value_' + cloneCount + '" /> \
                  </div></td> \
                  <td class="card-quantity"><div class="row"> \
                    <label for="id_card_quantity_' + cloneCount + '">Quantity</label> \
                    <input type="text" name="card_quantity" value="'+quantity+'" id="id_card_quantity_' + cloneCount + '" /> \
                  </div></td> \
                  <td class="card-subtotal"><div class="row"> \
                    <label for="subtotal_' + cloneCount + '">Subtotal</label> \
                    <span id="sub_total_' + cloneCount + '" name="sub_total">$0.00</span> \
                  </div></td> \
                  <td class="add-another"><a href="#" class="remove-card">Remove</a></td> \
                  <td class="add-another"></td> \
                </tr>'
            );
        
            cloneFields.find(".remove-card").click(remove_card);
            $("#gift_cards_table").append(cloneFields);
            
            //$('<a href="#" class="remove-card">Remove</a>').insertAfter('#add_another').click(remove_card);
            $('#add_another').remove().appendTo($('#gift_cards_table td.add-another:last')).click(add_another);
            
            $("#id_card_value_" + cloneCount + ",#id_card_quantity_" + cloneCount).blur(function(e) {
                forbes.bindBlur(e, this);
            });

            forbes.updateTotals();
            
            return false;
        }
        
        $("#id_shipping_same").click(function() {
            if ($("#id_shipping_same").attr("checked")) {
                $("#shipping_info").hide();
            } else {
                $("#shipping_info").show();
            }
        });
        
        $("input[name='card_value'],input[name='card_quantity']").blur(function(e) {
            forbes.bindBlur(e, this);
        });
        
        $("input[name='shipping_method']").click(function() {
            $(".gift-card-shipping label").removeClass('selected');
            $(this).parent('label').addClass('selected');
            forbes.updateTotals();
        });
        
        if ($("input[name='shipping_method']:checked").length == 0) {
        	$("#id_shipping_method_0").click();
        }
        
        $('.shipping-same-toggle label').addClass('selected').click(function(){
          $(this).toggleClass('selected');
        });
        
        if ($('#gift_cards_table .card-val input').size() > 1) {
          $('#gift_cards_table .card-val input:gt(0)').each( function(i,tem){
            add_another( $(tem).val(),
                         $('#gift_cards_table .card-quantity input:eq('+(i+1)+')').val() );
                         
          } );
          $('#gift_cards_table .card-val:first input:gt(0)').remove();
          $('#gift_cards_table .card-quantity:first input:gt(0)').remove();
        }
        
        forbes.updateTotals();
        
        $(".gift_card_form").submit(function() {
        	if ($("#submit").val() == 'Submitting...') {
        		return false;
        	} else {
        		$("#submit").val('Submitting...').attr("disabled", "disabled");
            	return true;
        	}
        });
        
        forbes.parseErrors();
        $('.errored-box').click(function(){
          $(this).removeClass('errored-box');
        });
        
        if(!$('.shipping-same-toggle input').attr('checked')){
          $('.shipping-same-toggle label').removeClass('selected');
          $('#shipping-information').show();
        }
        
        // tab order
        var tab_indices = {billing: [0,2,4,7,1,3,5,6,8], shipping:[0,2,4,1,3,5,6,7]};
        $('#billing-information input').each(function(i,tem){
          $(tem).attr('tabindex', tab_indices.billing[i] + 50);
        });
        $('#shipping-information input, #shipping-information textarea').each(function(i,tem){
          $(tem).attr('tabindex', tab_indices.shipping[i] + 100);
        });
        $('#cc-information input').attr('tabindex', 150);
        
        
        $('input[type=radio]').each(function(i,tem){
          var dis = $(tem);
          if(dis.attr('checked')) dis.parent().addClass('selected');
        });
        
        $('.gift-card-toggle-terms').click(function(){
           $('#gift-card-terms').toggle();
           return false ;
        });
        
    }); 
})(jQuery);

$(window).load(function(){
  if ($('.errored-box').size()) {
    $('body').animate({scrollTop: $('.errored-box:first').offset().top });
  }
});

