// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var FT = {};

FT.initMediaWidget = function() {
  $(function() {
    // TODO: make the video links unobtrusive as well
  	$('#picture_list .icon').click(function(e) { return FT.viewImage(e); });
  });
};

FT.viewImage = function(e) {
  id = "#picture_" + $(e.target).attr("id").replace(/icon_/,"");
  $('#viewer').contents().replaceWith($(id).contents().clone());
  return false;
};

FT.playVideo = function(sourceId, targetId) {
  if (typeof(sourceId)=='string') {sourceId=document.getElementById(sourceId);}
  if (typeof(targetId)=='string') {targetId=document.getElementById(targetId);}
  targetId.innerHTML=sourceId.innerHTML;
  return false;
};

FT.make_primary_video = function(video_rand_id) {
	$('.video_hidden_primary').attr('value', 0);
	$('#video_hidden_' + video_rand_id).attr('value', 1);
};
FT.make_primary_attached_image = function(rand_id) {
	$('.attached_image_hidden_primary').attr('value', 0);
	$('#attached_image_hidden_' + rand_id).attr('value', 1);
};

FT.initRemoveButtons = function() {
  $(function() {
  	$('.remove').click(function(e) {
  	  // TODO handle returned error conditions
  		$.post(e.target.href, { '_method': 'delete' }, $(e.target).closest('.fields').fadeOut('slow', function() { $(this).remove(); }), "json");
  		return false;
  	});
  });
};

FT.flash = function(name, msg) {
  var flash_containter = $('div#flash_' + name);
  if (flash_containter.length) {    
    flash_containter.html(msg);
  } else {
    $('div.grid_12').prepend('<div id="flash_' + name + '">' + msg + '</div>');
  }
}
// Like buttons behaviour

FT.likeButton = function(link_id, replacing_link) {
  $('a#' + link_id).replaceWith(replacing_link);
}

FT.likeSelect = function(select_id, replacing_select) {
  $('select#' + select_id).replaceWith(replacing_select);
}

FT.autocomplete = function () {
  var input = $(this);
  var model = input.attr('id').match(/(food_type|source_type)/)[0] + 's';
  //this adds some local caching to improve performance
  var cache = {};
  // conditions for autocomplete
  var conditions = {
    minLength: 1,
    source: function(request, response) {
      if ( request.term in cache ) {
              response( cache[request.term] );
              return;
      }
    
      $.ajax({
              url: '/' + model + '/autocomplete',
              dataType: "json",
              data: { 'term': extractLast(request.term) },
              success: function( data ) {
                      cache[ request.term ] = data;
                      response( data );
              }
      });
    },
  }
  // extend for multiple select
  if ( model == 'food_types' ) {
    $.extend( conditions, {
                           focus: function() {
                             // prevent value inserted on focus
                             return false;
                           },
                           select: function(event, ui) {
                             var terms = input.attr('value').split(/,\s*/);
                             terms.pop();
                             terms.push( ui.item.value );
                             terms.push('');
                             input.attr('value', terms.join(', '));
                             return false;
                           }
    });
  }

  input.autocomplete(conditions);
  
  function split(val) {
      return val.split(/,\s*/);
  }
  function extractLast(term) {
      return split(term).pop();
  }
              
};

$(function() {
  $('input.autocomplete').each(FT.autocomplete);

  $('a.like').live('click', function () {
    var link = $(this);
    $.ajax({
      url: link.attr('href'),
      type: link.attr('href').match(/unlike/) ? 'DELETE' : 'POST',
      dataType: 'script'
    });
    return false;
  });
  
  $('select.like').live('change', function () {
    var select = $(this);
    $.ajax({
      url: ['/foodtrees', select.attr('value'), select.attr('id').match(/^[a-z]+/)[0], select.attr('id').match(/\d+/)[0], 'like'].join('/'),
      type: 'POST',
      dataType: 'script'
    });
    return false;
  });
  
  $('#item_tabs').tabs();
  
  $('ul.foodtree_tabs a').click(function () {
    $('div.map_canvas').hide();
    if (!$(this).is('[href=#foodtree_new]')) {
      var map_id = 'map_canvas_'+ $(this).attr('href').match(/\d+$/)[0]
      $('div#' + map_id).show();
      for(var i in window.google_maps) { google.maps.event.trigger(window.google_maps[i], 'resize') };
    }
  });
  
  //clear search fields
  $('input.q').focus(function () {
    $(this).attr('value', '');
    $(this).unbind('focus');
    return false;
  });

  //user activity avatar placement
  //$('.photo img').each(function () {
  //  var property = $(this).height() < $(this).width() ? 'height' : 'width';
  //  $(this).css(property, '50px');
  //});
});

//This function applies facebook javascript SDK that provides Graph features without iframe
FT.initFacebookJavascriptSDK = function (app_id) {
  $('body').prepend('<div id="fb-root"></div>');
  
  window.fbAsyncInit = function() {
    FB.init({appId: app_id, status: true, cookie: true,
             xfbml: true});
  };
  
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
}

// Let's add authenticity token to all Ajax requests. 
if (typeof(jQuery) != "undefined") {
  (function(jQuery){
    var originalAjax = jQuery.ajax;
    jQuery.extend({
      ajax: function(o) {
        if (!(o.type && o.type.toUpperCase()=="GET")) {
          o.data = o.data || {};
          if (typeof(o.data)==="string") {
            o.data += "&authenticity_token="+_token;
          } else {
            o.data.authenticity_token = _token;
          }
        }
        return originalAjax.call(this, o);
      }
    });
  })(jQuery);
}
