var submitJMML = function(form, url) {
  $.ajax({
    data:$.param($(form).serializeArray()),
    type:'post',
    url:url,
    success: function(response) {
      $('#jmml-form').replaceWith(response);
    }
  });
};

$(document).ajaxSend(function(e, xhr, options) {
  var token = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);
});
/*
*/
$(function() {
  $('#flash_success .close a').live('click', function(){
    $('#flash_success').slideUp('slow');
    return false;
    });
  $('#flash_error .close a').live('click', function(){
    $('#flash_error').slideUp('slow');
    return false;
    });
  $('#flash_notice .close a').live('click', function(){
    $('#flash_notice').slideUp('slow');
    return false;
    });
});

// Displays a message as a flash message.
// Params: message - message text
//         messageType - 'error' || 'success' || 'notice'
function showMessage(message, messageType){
  if (typeof messageType == 'undefined') messageType = 'error'
  var messageDiv = '<div id="flash_' + messageType + '" style="display:none;"><div class="close"><a href="#">Close</a></div><p>';
  messageDiv += message + '</p></div>';
  $("#flash").html(messageDiv);
  $("#flash_"+messageType).slideDown('fast');
}

var verifyLoginAndRedirect = function(url) {
  if ($('.fb_button').length > 0) {
    window.location = $('.fb_button').attr('href') + '?back=' + escape(url);
  } else {
    window.location = url;
  }
}

var initTooltips = function() {
	if (!$('.tooltip').length) {return;}
	var $tt_title;
	var $tt = $('#tooltip_outer');
	var $tt_i = $('#tooltip_inner');
	if (!$tt.length) {
		$('body').append('<div id="tooltip_outer" style="display: none;"><div id="tooltip_inner"></div></div>');
		$tt = $('#tooltip_outer');
		$tt_i = $('#tooltip_inner');
	}
	$('.tooltip').live('hover',
	function(event) {
		if (event.type == 'mouseover') {
			if ($(this).attr('title')) {
				$tt_title = $(this).attr('title');
				$(this).attr('title', '');
			}
			$tt_i.html($tt_title);
			$tt.show();
		}
		else {
			$tt.hide();
			$tt_i.html('');
			if ($tt_title) {
				$(this).attr('title', $tt_title);
			}
		}
	}).live('mousemove',
		function(ev) {
			var $ev_x = ev.pageX;
			var $ev_y = ev.pageY;
			var $tt_x = $tt.outerWidth();
			var $tt_y = $tt.outerHeight();
			var $bd_x = $('body').outerWidth();
			var $bd_y = $('body').outerHeight();
			$tt.css({
				'top': $ev_y + $tt_y > $bd_y ? $ev_y - $tt_y : $ev_y,
				'left': $ev_x + $tt_x + 20 > $bd_x ? $ev_x - $tt_x - 10 : $ev_x + 15
			});
		}
	).live('click',
		function(ev) {
			$tt.hide();
			$tt_i.html('');
			if ($tt_title) {
				$(this).attr('title', $tt_title);
			}
		}
	);
};

$(initTooltips);

// handle placeholder text in input fields.
var initPlaceholders = function () {
	$('[placeholder]').focus(function() {
	  var input = $(this);
	  if (input.val() == input.attr('placeholder')) {
	    input.val('');
	    input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $(this);
	  if (input.val() == '') {
	    input.addClass('placeholder');
	    input.val(input.attr('placeholder'));
	  }
	}).blur().parents('form').submit(function() {
	  $(this).find('[placeholder]').each(function() {
	    var input = $(this);
	    if (input.val() == input.attr('placeholder')) {
	      input.val('');
	    }
	  })
	});
};

var scrollMap = function() {}; // turning this feature off 
var old_scrollMap = function () {
  $(window).scroll(function() {
    mapOffset = $('#results-map').offset();
    windowTop = $(window).scrollTop();
    parentTop = $('#side-content').offset().top;
    if ( windowTop >= parentTop) {
      $('#results-map').offset({left: mapOffset.left, top: windowTop + 30});
    } else {
      $('#results-map').offset({left: mapOffset.left, top: parentTop});
    }
  });
};


var setListPrivacy = function (make_public_url, make_private_url, is_public, callback) {
  //alert(is_public);

  if (! callback) {
    callback = function () {};
  }

  var url = is_public ? make_public_url : make_private_url;

  $.ajax({
    type: 'put',
    url: url,
    success: callback
  })
};


var friendFinder = function(friendList) {
  var results = [];
  $('#friend-search-input').keyup(function(e) {
    //checks to see if the last keystroke was a backspace
    //if it was, we reset the search
    if (e.which == 8) {
      results = [];
    }

    var key = $('#friend-search-input').val().trim();

    if (key == '') {
      $('.friend').hide();
      $('#friend-results-dropdown').toggle(false);
      return;
    }

    //If there are no results yet, either as a result of a backspace or this being the first keystroke
    //we do a search on the full list
    if (results.length == 0) {
      results = searchFriends(key, friendList);
    } else {
      results = searchFriends(key, results);
    }

    // toggle show on the results
    if (results.length > 0) {
      var size = results.length < 5 ? results.length : 5;
      $('.friend').hide();
      // no-op if no dropdown
      $('#friend-results-dropdown').toggle(true);
      $(results.slice(0, size)).each(function() {
       $("#" + this['facebook_id'])
          .show()
          .children('img')
            .attr('src', 'https://graph.facebook.com/' + this['facebook_id'] + '/picture?type=square');
      });
    }
  });
};

var searchFriends = function(searchKey, friendList) {

  var results = [];
  $(friendList).each(function(index, friend) {

    var name = friend['name'];
    var id = friend['facebook_id'];
    var searchExp = new RegExp(searchKey, 'i');
    var fullName = name.split(' ');

    if (searchKey.search(' ') != -1 ) {
      if (name.slice(0, searchKey.length).match(searchExp)) {
        results.push(friend);
      }
      //If we do not match on the full string, we still need to check
      //firstName lastName and ignore any middle names
      else {
        var firstLast = fullName[0] + ' ' + fullName[fullName.length];
        if (firstLast.slice(0, searchKey.length).match(searchExp)) {
          results.push(friend);
        }
      }
    } else {
      $(fullName).each(function() {
        if (this.slice(0, searchKey.length).match(searchExp)) {
          results.push(friend);
          return;
        } 
      });
    }
  });

  return results;
};


var fbPost = function(friendID, pic, name, link, message) {
  FB.ui({ method: 'feed',
        picture: pic,
        name: name,
        link: link,
        caption: "Discover and share your favorite places!",
        message: message,
        to: friendID
  });
};


//linkBuilder
//when passed a set of results, it puts the top 5 into the ul friend-results
var friendDropdownBuilder = function(friendsList, friendLnkList, fbPostPic, fbPostName, fbPostLink, fbPostMessage) {
  //On click of the object, calls fbPost with the id of the fb user
  $('.friend').live('click', function(e) {
    fbPost($(this).attr('id'), fbPostPic, fbPostName, fbPostLink, fbPostMessage);
    $('.friend').hide();
    $('#friend-results-dropdown').toggle(false);
    e.preventDefault();
  });

  $(friendsList).each(function(index, friend) {
    var link = "<li class='friend' id='"+ friend['id'] +"'> <a href='#'>"+ friend['name'] +"</a></li>";
    $(link).hide().appendTo('#friend-results')
  });
};

var friendBuilder = function(friends, fbPostPic, fbPostName, fbPostLink, fbPostMessage) {
  $('#friends').empty();

  $('.friend-button').live('click', function(e) {
    fbPost($(this).attr('name'), fbPostPic, fbPostName, fbPostLink, fbPostMessage); 
    e.preventDefault();
  });

  $(friends).each(function(index, friend) {
    var img = new Image();
    var person = $("<div class='friend place person' id='" + friend['facebook_id'] + "'></div>");
    person.hide().appendTo('#friends');
    $(img).appendTo(person);
    if (friend['url'] == undefined) {
      var name = "<h3><a class='friend-button' name='"+friend['facebook_id'] +"'href='#'>" + friend['name'] + "</a></h3>";
      var button =  "<input type='button' class='friend-button' name='"+friend['facebook_id'] +"' value='Invite!'/>";
      $(name).appendTo(person);
      $(button).appendTo(person);
    } else {
      var name = "<h3><a href='"+ friend['url'] +"'>" + friend['name'] + "</a></h3>";
      $(name).appendTo(person);
    }
  });
}

var showNewList = function(list) {
  var container = $("<li class='list'></li>");
  var del  = $("<ul><li><a href='/lists/"+list['id']+"' class='delete-button'>Delete List</a></ul></li>");
  var atag = $("<a href='/lists/"+list['id']+"'></a>");
  var name = $("<h3>" + list['name'] + "</h3>");
  var desc = $("<p>" + list['description'] + "</p>");
  atag.append(name);
  container.append(del);
  container.append(atag);
  container.append(desc);
  container.hide().insertBefore($('.list:first')).slideDown();
};

var resetListDropdown = function() {
  $('.save-btn').val('Save');
  $('#spinner').hide();
  $('.save-dialog input[type=text]').each(function() {
    $(this).val('');
  });
  $('#new-list-drop input[type=text]').each(function() {
    $(this).val('');
  });
}

var submitSave = function(listID, placeID) {
  $('.list-dialog-btn').val('Saving...');
  $('#spinner').show();
  $.post('/lists/' + listID + '/add', {'place_id' : placeID}, function() {
    $('.list-dialog-btn').val('Saved!');
    $('#spinner').hide();
  });
}

var createList = function(name, desc, user_url, callback) {
  $('.save-btn').val('Creating...');
  $('#spinner').show();
  $.post(user_url, {name: name, description: desc}, function(data) {
    showNewList(data['list']);
    showMessage(data['message'], 'success');
    $('.save-dialog ul').append('<li><label><input type="checkbox" id='+ data['list']['id'] +' value='+ data['list']['name'] +' />'+ data['list']['name'] +"</label></li>");
    if (callback) {
      callback(data['list']['id']);
    }
  });
}

var dropDownMenu = function($target, $menu, callback) {
  $close = $('.close-btn');
  $target.click(function() {
    resetListDropdown();
    $menu.detach().insertAfter($(this));
    $menu.position($(this).position());
    $menu.slideDown('fast');
    if ($menu.children($close.selector).length > 0) {
      $close.click(function() {
        $menu.slideUp('fast');
        return false;
      });
    }
    $('body').click(function(evt) {
      var tgt = $(evt.target);
      if (!(tgt.is($target.selector) || tgt.is($menu.selector) || tgt.parents($menu.selector).length !== 0)) {
        $menu.slideUp('fast');
        resetListDropdown();
      }
    });
    return false;
  });

  if (callback) {
    callback(this);
  }
}

$(function() {
  $('.save-button').click(function() {
    $('.list-dialog-btn').attr('data-place-id', $(this).attr('data-place-id'));
    $('.list-dialog-btn').attr('data-user-url', $(this).attr('data-user-url'));
  });

  $('.list-dialog-btn').click(function() {
    var placeID = $(this).attr('data-place-id');
    var userURL = $(this).attr('data-user-url');
    $('.save-dialog input[type=checkbox]:checked').each(function() {
      submitSave($(this).attr('id'), placeID);
    });

    var tbs = $('.save-dialog input[type=text]').map(function(){ return this.value }).get();
    var joined = tbs.join(' ').trim();
    if (joined != '') {
      createList(tbs[0], tbs[1], userURL, function(listID) {
        submitSave(listID, placeID);
      });
    }
  });
});

