/*!
 * OBMG scripts
 * Copyright (c) 2009-2012 Dialect Communications Group (dialect.ca)
 * $Package: OBMG $
 */

/*jslint browser: true, white: true, plusplus: false, newcap: true,
    eqeqeq: true, evil: true, nomen: false, regexp: true, undef: true,
    onevar: true, indent: 2 */

/*global jQuery,OBMG,Mustache,Modernizr,window,log,_gaq */
(function ($, OBMG, document, window, undefined) {
  OBMG.isMobile = function () {
    return Modernizr.mq('only screen and (max-width: 900px)');
  };

  OBMG.preloadImage = function (src, onload, onerror) {
    log('OBMG.preloadImage', src);
    var img = new Image();
    if (typeof onload === 'function') {
      img.onload = onload;
    }

    if (typeof onerror === 'function') {
      img.onerror = onerror;
    }

    img.src = src;
  };

  OBMG.trackPageView = function (href) {
    try {
      log('trackPageView', href);
      _gaq.push(['_trackPageview', href]);
    } catch (e) { }
  };

  OBMG.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) {
    try {
      log('trackEvent', category, action, opt_label, opt_value, opt_noninteraction);
      _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]);
    } catch (e) { }
  };

  // Domains for internal Google Analytics tracking
  OBMG.TRACKABLE_DOMAINS_RE = /[\.\/](obmg|painterslodge|aprilpoint|canadianprincess|mvcharlotteprincess|mvmarabell|mvsalmonseeker|kingsalmonresort|capesantamaria|pedderbaymarina|marinarestaurant)\./i;



  /*
   * Add Google Analytics tracking across domains.
   */
  OBMG.addOutboundLinkTracking = function () {
    $('.fb-findus').bind('click.obmg', function () {
      OBMG.trackEvent('Social Links', 'Facebook', $(this).attr('href'));
      return true;
    });
  
    $('.twitter32').bind('click.obmg', function () {
      OBMG.trackEvent('Social Links', 'Twitter', $(this).attr('href'));
      return true;
    });

    //return;
    $('a').bind('click.obmg', function () {
    
      var href = $(this).attr('href');
      // don't track relative links
      if (href.indexOf('http:') !== 0 && href.indexOf('https:') !== 0) {
        return true;
      }

      if (OBMG.isTrackableLink(href)) {
        try {
          if (typeof($.cookie) !== 'undefined') {
            if ($.cookie('off_site_ref')) {
              OBMG.trackPageView(this.href + '?src=' + $.cookie('off_site_ref'));
              return false;
            }
          }
        
          OBMG.trackPageView(this.href);
          return false;
        } catch (e) { }
      }

      return true;
    });
  };

  OBMG.tocHighlight = function (el) {
    $(el).stop(false, true).animate({'backgroundColor': '#F4F4F4'}, 250);
  
  };

  OBMG.tocUnlight = function (el) {
    $(el).stop(false, true).animate({'backgroundColor': '#FFF'}, 250);    
  };

  /**
   * Add hover and click behaviours to the inline child TOCs.
   */
  OBMG.initTOCs = function () {
    $('.toc li, #home_toc li').hover( 
      function () {
        OBMG.tocHighlight(this);
      },
      function () {
        OBMG.tocUnlight(this);
      }
    );
  };

  OBMG.initFFCForm = function () {
    var t = $('table.ffc-order'),
        f = null;
    
    if (t.length < 1) {
      return false;
    } 
  
    f = t.parents('form').first();
    if (f.length < 1) {
      return false;
    } 

    // clone the row and increase the index
    $('.another', t).live('click', function (evt) {
      evt.preventDefault();
      var row = $(this).closest('tr'), 
          new_row = row.clone(true),
          row_index = parseInt(row.data('itemindex'), 10);
    
      row_index += 1;

      new_row.addClass('cloned');
      new_row.data('itemindex', row_index);
    
      $('select, input', new_row).each(function (idx, el) {
        el.name = el.name.replace(/(\[[0-9]+\])$/, '[' + row_index + ']');
      });
        
      new_row.insertAfter(row);
      return false;
    });

    // set up indexes for items that allow multiple orders
    $('.multi', t).data('itemindex', 0);
    $('.multi select, .multi input', t).each(function (idx, el) {
      el.name += '[0]';
    });
  
    $('.multi input', t).bind('keyup', function () {
      var cell = $(this).parent(),
          row = cell.closest('tr'),
          row_index = parseInt(row.data('itemindex'), 10);
    
      if (parseInt($(this).val(), 10) > 0) {
        if ($('.another', cell).length < 1) {
          cell.append('<a href="#" class="another">add another size?</a>'); // .insertAfter(this);
        }
      } else {
        if (row.hasClass('cloned')) {
          row.remove();
        } else {
          $('.another', cell).remove();
        }
      }
    });
  };

  OBMG.initOEmbed = function () {
    var oembed_toc = $('.toc.oembed');
  
    if (oembed_toc.length > 0) {
      log('OBMG.initOEmbed');
      $.getScript('/inc/jquery.oembed.min.js', function () {
        $.getScript('/inc/app.oembed-toc.min.js', function () {
          OBMG.OembedTOC.init(oembed_toc);
          // check for a hash that corresponds with a [rel] link
          // if found, load that content immediately
          var hash = window.location.hash,
              l = null;
    
          if (hash.length > 0) {
            l = $('a[rel=' + hash.substr(1) + ']:first', oembed_toc);
            if (l.length > 0) {
              OBMG.OembedTOC.load(l.attr('href'));
            }
          }
        });
      });
    }
  };

  $(document).on('ready', function () {
    OBMG.addOutboundLinkTracking();
    OBMG.initFFCForm();
    OBMG.initTOCs();
    OBMG.initOEmbed();  
  });
}(jQuery, OBMG || {}, document, window));

window.fbAsyncInit = function () {
  if (typeof window.FB !== 'undefined') {
    var body = document.body,
        html = document.documentElement,
        height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
    window.FB.Canvas.setSize({height: height + 500}); // add padding so we don't wait for images to load
  }
};
