/*
success: function(r) { alert($(r).text()) }, 
error: function(xhr, desc, e){ alert(xhr.responseText); }
*/

var loc = document.location.toString();

$(document).ready(function(){

	$('body').append('<div id="app-alerts" style="display: none;"></div>');
	$('#top-search-box').fieldHelp('Search all of Society6');

	$('#menu-user').hover(
		function() { $("#menu-user-dropdown").show(); },
		function() { $("#menu-user-dropdown").hide(); }
	);

	$('.tooltip').tooltip({showURL: false});

	//facebook_onload(false);
	
});




jQuery.appError = function(message) { $.showAlert(message, 'error'); }
jQuery.appConfirm = function(message) { $.showAlert(message, 'confirm'); }
jQuery.showAlert = function(message, type)
{
	$('#app-alerts').html('<span class="'+type+'">'+message+'</span>');
	$('#app-alerts').css('display', 'block');
	t = window.setTimeout("$('#app-alerts').fadeOut('slow')", 2000);
}


/**
 * Form Field TIP
 * @param {Object} text
 */
jQuery.fn.fieldHelp = function(text){
    return this.each(function(){

		if (this.type != 'text' && this.type != 'textarea') {
			return;
		}

		var fld_current = this;

        if(this.value=='' || this.value == text) {
			this.value = text;
			$(this).addClass('helper');
		} else {
			return;
		}

		$(this).focus(function() {
			if (this.value == text || this.value == '') {
				this.value = '';
				$(this).removeClass('helper');
			}
		});

		$(this).blur(function() {
			if (this.value == text || this.value == '') {
				$(this).addClass('helper');
				this.value = text;
			}
		});
		
		$(this).parents('form').each(function() {
			$(this).submit(function() {
				if(fld_current.value == text) { fld_current.value = ''; }
			});
		});

    });

};




jQuery.fn.toggle = function() {
	return this.each(function(){
		$(this).click(function(){
			if ($(this).is('.toggled')) {
				$(this).removeClass('toggled');
				$(this).next().slideUp('fast');
			} else {
				$(this).addClass('toggled');
				$(this).next().slideDown('fast');
			}
		});
    });
};




jQuery.fn.toggleFade = function(id) {
	return this.each(function(){
		$(this).click(function(){
			if ($(this).is('.toggled')) {
				$(this).removeClass('toggled');
				$(id).slideUp('fast');
			} else {
				$(this).addClass('toggled');
				$(id).slideDown('fast');
			}
		});
    });
};




jQuery.editField = function(obj, recordId, fieldName){ 
	var string = $(obj).text();
	string = string.replace(/"/g, '&quot;');
	var objId = $(obj).attr('id');
	var input = '<div id="editing-wrap-'+objId+'" class="editing-wrap"><input type="text" id="editing-'+objId+'" name="editing-'+objId+'" value="'+string+'" class="editing-field"></div>';
	$(obj).hide();
	$(obj).after(input);
	var editing = $('#editing-'+objId);
	editing.focus();
	editing.select();
	editing.blur( function() { resetField(); } );
	editing.keydown( function(e) {
		if (e.keyCode == 27) { resetField(); }
		if (e.keyCode == 13) { submitField( editing.val() ); }
	});
	function resetField() {
		$('#editing-wrap-'+objId).remove();
		$(obj).show();
	}
	function submitField(newString) {
		if (newString != string) {
			$.ajax({
				type: "POST",
				url: "/rest/"+recordId,
				data: "method=PUT&"+fieldName+"="+escape(newString),
				error: function(){ $(obj).text(string); appError('Error: editField'); }
			});
		}
		$(obj).text(newString);
		resetField();
	}

}

jQuery.openUser = function(username){
	window.location = 'http://www.society6.com/'+username;
}

jQuery.openStudio = function(studio){
	window.location = 'http://'+studio+'.society6.com/';
}


function uploadImage(obj, target) {
	$(obj).hide();
	$('.'+target).show();
}



jQuery.toggleLogin = function()
{
	$("#my-nav").css("display", "none");
	$("#top-search").css("display", "none");
	$("#top-login").fadeIn(function(){$("#side-username").focus()});
	return false;
}



function addComment(postId, targetUrl)
{
	var form = '<form action="'+targetUrl+'#comment-new" method="POST" onSubmit="return submitComment('+postId+')"><input id="done" name="done" type="hidden" value="1"/>';
	form += '<div class="input-wrap"><textarea id="comment_body" name="comment_body"/></textarea></div>';
	form += '<div class="buttons"><button type="submit">Add Comment</button></div>';
	form += '</form>';
	$('#post-comment-'+postId).html(form);
}

function submitComment(postId)
{
	$('#post-comment-'+postId+' button').text('Please Wait').attr('disabled', 'disabled');
	return true;
}



function acceptRequest(messageId)
{
	$.ajax({
		type: "POST",
		url: "/rest/messages/"+messageId,
		data: { method: "DELETE", action: 'accept' },
		success: function() { $.appConfirm('The request has been accepted'); },
		error: function(){ $.appError('Function: acceptRequest'); }
	});
	$('#message-'+messageId).fadeOut();
}


function denyRequest(messageId)
{
	$.ajax({
		type: "POST",
		url: "/rest/messages/"+messageId,
		data: { method: "DELETE", action: 'deny' },
		error: function(){ $.appError('Function: denyRequest'); }
	});
	$('#message-'+messageId).fadeOut();
}




/* Nominate Studio */
function nominate(grantId, studioId)
{
	var nominate = $('#nominate-'+grantId+'-'+studioId);
	nominate.addClass('nominated');
	nominate.removeClass('nominate');
	nominate.html('Studio Nominated');

	$.appConfirm('Your nomination has been submitted!');
	$.ajax({
		type: "POST",
		url: "/rest/nominations/"+grantId,
		data: { method: "POST", studio_id: studioId },
		error: function(){ $.appError('Function: nominate'); }
	});
}




// Post Promotions
jQuery.addPromotion = function(postId)
{
	var promo = $('#promo-'+postId);
	var count = $('.promo-count', promo);
	var promote = $('.status', promo);
	var countNum = 0;
	if (count.html() != '') var countNum = $('.promo-count strong', promo);
	countNum = (count.html() == '') ? 1 : parseInt($('strong', count).html())+1 ;
	count.fadeOut('fast', function() { $(this).html('<strong>'+countNum+'</strong>').fadeIn('fast'); });

	promote.removeAttr('onclick');
	promote.html('Promoted');
	promote.removeClass('promote');
	$.ajax({
		type: "POST",
		url: "/rest/posts/"+postId,
		data: { method: "POST", aHash: aHash, promotion: 1 },
		error: function(){ $.appError('Function: addPromotion'); }
	});
}




/* Subscribe Studio */
function subscribe(studioId){
	$('#btn-contact-'+studioId).html('<a class="remove" onclick="unsubscribe('+studioId+')">Remove Endorsement</a>');
	$.appConfirm('You are now endorsing this Studio');
	$.ajax({
		type: "POST",
		url: "/rest/subscribe/"+studioId,
		data: { method: 'POST' },
		error: function(){ $.appError('function: subscribe'); }
	});
}

function unsubscribe(studioId){
	$('#btn-contact-'+studioId).html('<a class="add" onclick="subscribe('+studioId+')">Endorse this Studio</a>');
	$.ajax({
		type: "POST",
		url: "/rest/subscribe/"+studioId,
		data: { method: 'DELETE' },
		error: function(){ $.appError('function: unsubscribe'); }
	});
}





/* Follow User */
function follow(userId, contactId) {
	$('#btn-contact-'+contactId).html('<a class="remove" onclick="unfollow('+userId+', '+contactId+')">Following</a>');
	$.appConfirm('This person\'s updates will appear on your Society');
	$.ajax({
		type: "POST",
		url: "/rest/follow/"+userId,
		data: { method: "POST", contact_user_id: contactId },
		error: function(){ $.appError('function: addContact'); }
	});
}

function unfollow(userId, contactId) {
	$('#btn-contact-'+contactId).html('<a class="add" onclick="follow('+userId+', '+contactId+')">Follow this person</a>');
	$.appConfirm('You are no longer following this person');
	$.ajax({
		type: "POST",
		url: "/rest/follow/"+userId,
		data: { method: "DELETE", contact_user_id: contactId },
		error: function(){ $.appError('function: removeContact'); }
	});
}


function deleteComment(commentId){
	var answer = confirm("Are you sure you want to delete this Comment?");
	if (answer){
		$.ajax({
			type: "POST",
			url: "/rest/comments/"+commentId,
			data: { method: "DELETE" },
			success: function(r) { $("#comment-"+commentId).hide(); },
			error: function(){ $.appError('function: deleteCommentt'); }
		});
	}
}

jQuery.deletePost = function(postId)
{
	var answer = confirm("Are You Sure?")
    if (answer){
		$.ajax({
			type: "POST",
			url: "/rest/posts/"+postId,
			data: { method: "DELETE" },
			success: function(r) { location.reload(); },
			error: function(){ $.appError('function: deletePost'); }
		});
	}
}