/*=======================================*\
             THE WISH LIST BOX
\*=======================================*/

/* Edit In Place - http://15daysofjquery.com/edit-in-place-with-ajax-using-jquery-javascript-library/15/ */

var editing = false;

$(document).ready(function() {
  SetEditAndDeleteHandler();
});

function SetEditAndDeleteHandler() {
  $('.wishlistItem .edit').click(function() {
    if (editing) return;

    var originalContent = $(this).parent().children('.enquiry').html();
    //alert(originalContent);
    var textarea = '<div><textarea class="taEnquiry">' + originalContent + '</textarea>';
    var button = '<div><input type="button" value="Save" class="saveButton" /> <input type="button" value="Cancel" class="cancelButton" /></div></div>';
    var revert = originalContent;
    $(this).parent().children('.enquiry').after(textarea + button).remove();
    $('.saveButton').click(function() { saveChanges(this, false); });
    $('.cancelButton').click(function() { saveChanges(this, revert); });
    editing = true;
  });

  $('.wishlistItem .remove').click(function() {
    // AJAX save here
    var url = appPath + "WishlistFunctions.aspx?delete=1&id=" + $(this).parent().attr('id');
    //alert(url);
    $.post(url);

    $(this).parent().hide('normal');
  });
}

function saveChanges(obj, cancel) {
	if(!cancel) {
		var t = $(obj).parent().siblings(0).val();
		
		// AJAX save here
		var url = appPath + "WishlistFunctions.aspx?edit=1&id=" + $(obj).parent().parent().parent().attr('id');
		//alert(url);
		
		$.post(url, { comment: t });
	}
	else {
		var t = cancel;
	}
	$(obj).parent().parent().after('<div class="enquiry">' + t + '</div>').remove();
	editing = false;
}


/*=======================================*\
              OTHER FUNCTIONS
\*=======================================*/

function AddToWishlist(itemCode) {
  var url = appPath + "WishlistFunctions.aspx?add=1&itemCode=" + itemCode;

  $.post(url, {}, function(txt) {
    UpdateWishlist(txt);
    SetEditAndDeleteHandler();
  });
}

function ClearWishlist() {
  if (confirm('This will delete all items and comments from your wish list.')) {
    var url = appPath + "WishlistFunctions.aspx?clear=1";

    $.post(url, {}, function(txt) {
      UpdateWishlist(txt);
    });
  }
}

function UpdateWishlist(wishlistHtml) {
  $("#divWishlist").html(wishlistHtml);
}


