
// ensure jQuery is loaded and execute callback
var ensureJQuery = function(callback) {
  // set our vars
  this.callback = callback;
  this.interval = 50;
  this.max_time = 5000;  // 5 seconds
  this.elapsed = 0;
  this.jquery_url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
  
  // if jQuery is loaded, run it
  if (typeof jQuery == 'function') {
    return this.callback(jQuery,true); // native jQuery == true
  }

  // insert jquery load script tag
  var script = document.createElement('script')
  script.setAttribute('type','text/javascript')
  script.setAttribute('src',this.jquery_url)
  if (typeof script != 'undefined') {
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  // interval our check and run callback when jQuery loaded
  this.jquery_check = setInterval(function() {
    this.elapsed += this.interval;
    if (typeof jQuery == 'function') {
      clearInterval(this.jquery_check);
      return this.callback(jQuery,false); // native jQuery == false
    }
    if (this.elapsed > this.max_time) { 
      clearInterval(this.jquery_check);
      return false;
    }
  },this.interval);          
}


ensureJQuery(function($,jQuery_is_native) {
  $(function() {
    var _script = $('script#gravity_import_script');
    var config = {
      domain: 'http://www.gravity.com',
      search_url: 'http://www.gravity.com/search/related',
      search_char_limit: 600,
      count: Math.abs(_script.attr('data-result-count')) <= 10 ? Math.abs(_script.attr('data-result-count')) : 5,
      selectors: _script.attr('data-selectors') || 'title,h1,h2,h3,a[rel="tag"]',
      add_keywords: _script.attr('data-add-keywords') || ! _script.attr('data-selectors'),
      add_description: _script.attr('data-add-description') || ! _script.attr('data-selectors'),
      horizontal: _script.attr('data-horizontal') == 'true',
      debug: _script.attr('data-debug') == 'true'
    };
    var markup = {
      wrapper: $('<div id="gravity_related_conversations" />'),
      stylesheet: $(
        '<style type="text/css" media="screen">'
        +'#gravity_related_conversations * { text-align: left; float:none; margin: 0; padding: 0; border: 0; outline: 0; text-indent: 0; line-height:1.3; font-weight: inherit; font-style: inherit; font-size: 11px; font-family: inherit; vertical-align: baseline; }'
        +'#gravity_related_conversations { margin:0 0 30px; width:200px; background:#fff; position:relative; }'
        +'#gravity_header {  margin:10px 0; font-weight:bold; font-size:12px; }'
        +'#gravity_import ul { list-style: none; }'
        +'#gravity_import img { width:28px; height:auto; margin:4px 10px 4px 0; float: left; clear:left; }'
        +'#gravity_import .title { font-weight:bold; }'
        +'#gravity_import ul li { margin:10px 0; padding:2px;}'
        +'#gravity_tagline { text-align:left; }'
        +'.gravity_logo { width:20px; display:inline-block; margin:0 2px -6px 0 !important; }'
        +'#gravity_beta_description { position:absolute; top:-5px; left:25px; z-index:999; background:white; padding:6px; border:1px solid #ddd; width:200px; }'
        +'.horizontal { width:auto !important; }'
        +'.horizontal ul li { float:left !important; width:200px; vertical-align:top; margin:2px !important; }'
        +'.horizontal #gravity_tagline { float:right !important; }'
        +'</style>'
      ),
      header: $('<div id="gravity_header"><img class="gravity_logo" src="'+config.domain+'/assets/images/g_bubble.jpg" /> Related Conversations</div>'),
      import_target: $('<div id="gravity_import">loading...<br /><br /></div>'),
      tagline: $('<div id="gravity_tagline">powered by <a href="'+config.domain+'" target="_blank">gravity.com</a></div>'),
      error_template: $('<p>more at <a href="'+config.domain+'" target="_blank">gravity.com</a><br /><br /></p>'),
      description: $('<div id="gravity_beta_description" style="display:none;"><img class="gravity_logo" src="'+config.domain+'/assets/images/g_bubble.jpg" /> <span style="font-weight:bold">Gravity.com</span> (beta) is a place for conversations.  This is a few selected conversations that we think are related to this web page.</div>')
    };
    var strings = [];
    var limit_regex = new RegExp('^.{1,'+config.search_char_limit+'}.*?\\b');
    var log_it = function(string) {
      if (config.debug && typeof console != 'undefined') {
        console.log(string);
      }
    };
    
    log_it((jQuery_is_native ? 'Native' : 'Remote')+' jQuery version '+$.prototype.jquery+' used');
    
    if (config.horizontal) {
      markup.wrapper.addClass('horizontal');
      markup.tagline.before('<br style="clear:both;" />');
    }
    
    // insert the markup
    _script
      .after(markup.wrapper)  
      .after(markup.stylesheet);      

    $('#gravity_related_conversations')
      .append(markup.header)
      .append(markup.import_target)
      .append(markup.tagline)
      .append(markup.description);
          
    $('.gravity_logo').hover(function() {
      $(this).animate({opacity: .5},100,function() {
        $('#gravity_beta_description').fadeIn(100);
      });
    }, function() {
      $(this).animate({opacity: 1},100);
      $('#gravity_beta_description').hide();
    });

    log_it('Building search query');

    // build a list of search terms
    if (config.add_keywords) {
      log_it('Including keywords');
      strings.push($('meta[name="keywords"]').attr('content'));      
    }
    if (config.add_description) {
      log_it('Including description');
      strings.push($('meta[name="description"]').attr('content'));
    }
    // splitting the selectors out to allow for giving precendence
    // so "h1, h2" will scrape all h1's before loading h2's
    // default jQuery behavior is dom order
    $(config.selectors.split(/\s*,\s*/)).each(function(i,element) {
      log_it('Including '+element);
      $(element).each(function() {
        strings.push($(this).text());
      });
    });
    
    // console.log(strings);  
    
    // filter strings before sending
    strings = strings
      .join(' ')
      .replace(/[^a-z0-9\.,!\?'’@]+/ig,' ') // strip out not useful characters
      .replace(/^\s|\s$/g,'') // trim any spaces from beginning and end 
      .match(limit_regex)[0]; // only use the first n characters
    
    log_it('Search query: ('+strings+')');
      
    // load the search results 
    $.ajax({
      type: 'GET',
      dataType: 'jsonp',
      data: { q: strings, ct: config.count },
      url: config.search_url,
      success: function(r) {
        $('#gravity_import').html(r.status == 'success' ? r.template : markup.error_template);
        $('.gravity_logo').animate({opacity: .5},150,function() {
          $(this).animate({opacity: 1},150);
        });
      },
      error: function() {
        $('#gravity_import').html(markup.error_template);
      }
    });
    
  });
});