/**
 * WPIT addTagTrigger
 * set up the trigger
 * @param {Object} element: element to monitor
 */

var tagCount = 0;
var WPITtags = {};
WPITtags.tagging = false;
WPITtags.rete = 0;

function tagExists(tag, tagCloud) {
    var tags = jQuery(tagCloud).children("div");
	jQuery(tags).each(function() {
        if(jQuery(this).html() == tag) return true;
	});
    return false;
}

function tagGetFromCloud(tag, tagCloud) {
    var tags = jQuery(tagCloud).children("a");
	jQuery(tags).each(function() {
        if(jQuery(this).html() == tag) return jQuery(this);
	});
    return false;
}

function WPIT_sendTempTag(sender) {
	jQuery("#addTagCallToAction").hide();
	var tag = jQuery('#tag_text').val();		
	if (tag.replace(" ","") === "") return;
	var tagCloud = jQuery("#tagCloud");
	
	if (jQuery("#tagCloudSubmitter").length == 0) {		
		jQuery('#tagSaveContainer').append("<div class='tagCloudSubmitter' id='tagCloudSubmitter' onclick='WPIT_sendTags(this)'>Tag completed</div>");
	}

	if (!tagExists(tag, tagCloud)) {
		var x = jQuery("#x").val();
		var y = jQuery("#y").val();
		var photo_id = jQuery("#photo_id").val();
		tagCount++;
		var tagLink = "<div rel='"+tagCount+"_"+photo_id+"_"+x+"_"+y+"' onmouseover='WPIT_showTag(this, "+x+","+y+")' onmouseout='WPIT_clearShowTag(this)' onclick='WPIT_removeTempTag(this)' class='normalTag pendingTag'>"+tag+"</div> ";
		tagCloud.addClass('pending');			
		jQuery(tagCloud).append(tagLink);
	}

	// Elimina l'area di tag
	var tagTarget = jQuery("#tagTarget");
	var tagEditor = jQuery("#tagEditor");
	jQuery(tagTarget).remove();
	jQuery(tagEditor).remove();

}

function WPIT_removeTempTag(sender){
	jQuery(sender).animate({"opacity": "0"}, 800, "linear", function() {
		jQuery(sender).remove();
		if (jQuery(".pendingTag").length == 0)
			jQuery("#tagCloudSubmitter").remove();
	});
}

function WPIT_addTagTrigger(element){
	// Add wrapper
	// jQuery(element).wrap("<div class='tagWrapper' style='width: "+(jQuery(element).width()-20)+"px;'></div>");
	jQuery(element).wrap("<div class='tagWrapper' id='tagWrapper'></div>");
	jQuery("<div class='tagCloud' id='tagCloud'></div>").appendTo(jQuery(element).parent());
	jQuery("<p id='tagSaveContainer'></p>").appendTo(jQuery(element).parent());
	// Get all tags related to picture
	var photo_id = jQuery(element).attr('id').replace('wpit_picture_','').replace(' ','');	
	// Populate tag cloud
	WPIT_tagCloud(photo_id, element);
}

function WPIT_addClickTrigger() {
	WPITtags.tagging = true;
	// Add information area
	//jQuery('#tagWrapper').children('p').remove();
	
	var element = jQuery("#tagWrapper").children("img");
	var container = jQuery("#tagWrapper");
	// Monitor an element for clickin' action
	jQuery(element).click(function(event) {
		
		var offsetTop = Math.round(jQuery(element).offset().top - jQuery(container).offset().top); 
		var offsetLeft = Math.round(jQuery(element).offset().left - jQuery(container).offset().left);
		var tagX  = event.pageX - Math.round(jQuery(container).offset().left);
		var tagY  = event.pageY - Math.round(jQuery(container).offset().top);
		
		if(parseInt(tagY)<64){
			tagY = 64
		}
		if(parseInt(tagY)>300){
			tagY = 300
		}
		if(parseInt(tagX)<243){
			tagX = 243
		}		
		if(parseInt(tagX)>599){
			tagX = 599
		}	
		
		
		// Calls the tagger function
		WPIT_addTag(element.parent(), tagX, tagY, element.attr('id').replace('wpit_picture_',''));
	});
	jQuery(jQuery("#tagCloud")).addClass('pending')

	var offsetTop = jQuery(element).offset().top - jQuery(container).offset().top; 
	var offsetLeft = jQuery(element).offset().left - jQuery(container).offset().left;
	var tagY = offsetTop+Math.round(jQuery(element).height()/2);
	var tagX = offsetLeft+Math.round(jQuery(element).width()/2);


	WPIT_addTag(element.parent(), tagX, tagY, element.attr('id').replace('wpit_picture_',''));
}

/**
 * WPIT tagCloud
 * generate tag cloud referred to the image
 * @param {Object} photo_id: id of the photo
 * @param {Object} element: image element
 */
function WPIT_tagCloud(photo_id, element) {
	var tagCloud = jQuery("#tagCloud");
	// Get height
	var tagCloudHeight = jQuery(tagCloud).height();
	//jQuery(tagCloud).css('height', tagCloudHeight);
	jQuery(tagCloud).html("");
	
	jQuery.post(wpit_ajax+"wpimgtagger.php",
	{
		'action': 'gettags',
		'sender': jQuery(element).parent().parent().attr("class"),
		'photo_id': photo_id	,
		'rete':WPITtags.rete	
	}, function(tags) {
		
		var tag = "";
		for (i=0; i<tags.length; i++) {
			var is_user = (tags[i].tagged_user_id !== '0')?true:false;	
				
			tagCount++;
			if (is_user)
				tag += "<div rel='"+tagCount+"_"+photo_id+"_"+tags[i].x+"_"+tags[i].y+"' href='#' onmouseover='WPIT_showTag(this, "+tags[i].x+","+tags[i].y+")' onmouseout='WPIT_clearShowTag(this)' class='user-tag' onclick='window.location = \""+base_url+"/members/"+tags[i].tag+"\"'>"+tags[i].tag+"</div> ";			
			else
				tag += "<div rel='"+tagCount+"_"+photo_id+"_"+tags[i].x+"_"+tags[i].y+"' href='#' onmouseover='WPIT_showTag(this, "+tags[i].x+","+tags[i].y+")' onmouseout='WPIT_clearShowTag(this)'>"+tags[i].tag+"</div> ";			

			if (tags[i].canRemove)
				tag += "(<div class='tag-remove'  onmouseover='WPIT_showTag(this, "+tags[i].x+","+tags[i].y+")' onmouseout='WPIT_clearShowTag(this)' onclick='WPIT_removeTag(this, "+tags[i].id+", "+photo_id+")'>rimuovi</div>)";
			tag += " | ";
			// alert(jQuery(element).parent().children(".tagCloud").children(".tagCloudSubmitter").attr("class"));
			jQuery(tagCloud).css('height', '');
		}
		if(tag==""){
			tag = '<div id="addTagCallToAction" onclick="WPIT_addClickTrigger()" id="tagThisPhoto" class="tagThisPhoto">No tags for this picture, do it now!</div>';
		}
		else{
			tag = "Tags: "+tag;
		}
		jQuery(tagCloud).html(tag);
	},
	'json');
}

/**
 * WPIT addTag
 * add the target of the tag element
 * @param {Object} tagWrapper: container
 * @param {Object} x: x position of the tag
 * @param {Object} y: y position of the tag
 */
function WPIT_addTag(tagWrapper, x, y, photo_id) {
	
	jQuery(tagWrapper).children("#tagContainer").remove();
	
	var tagContainer = jQuery("<div class='tagContainer' id='tagContainer' style='top: "+(y)+"px; left: "+(x)+"px;'></div>");
	var tagElement = jQuery("<div class='tagTarget' id='tagTarget'></div>");
	jQuery(tagContainer).appendTo(tagWrapper);
	jQuery(tagElement).appendTo(tagContainer);
	jQuery("#tagTarget").fadeIn("800");
	// Show the tagger panel
	WPIT_showTagger(tagContainer, x, y, photo_id, "");
}

/**
 * WPIT showTagger
 * show the tagger form
 * @param {Object} element: wrapper element
 * @param {Object} x: x position of the tag
 * @param {Object} y: y position of the tag
 * @param {Object} photo_id: id of the photo
 */
function WPIT_showTagger(element, x, y, photo_id) {
	var tagEditor =
	"<div class='tagEditor' id='tagEditor'>"+	
	"    <input type='hidden' id='photo_id' name='photo_id' value='"+photo_id+"' />"+
	"    <input type='hidden' id='x' name='x' value='"+x+"' />"+
	"    <input type='hidden' id='y' name='y' value='"+y+"' />"+
	"    <label for='tag'>Tag:</label>"+
	"    <input type='text' name='tag' id='tag_text' onkeyup='WPIT_checkEmpty(jQuery(this))' onkeydown='false' />"+
	"  <div class='tagEditorButtonBar'>"+
	"    <div class='closeButton tagEditorButton' id='closeButton' href='javascript://' class='tagEditorButton' onclick='WPIT_closeTagger(this)'></div>"+
	"    <div class='saveButton tagEditorButton tagEditorButtonDisabled' id='saveButton' href='javascript://' class='tagEditorButton' onclick='WPIT_sendTempTag(this)'></div>"+
	"  </div>"+
	"</div>";
	jQuery(tagEditor).appendTo(element);
	jQuery("#tag").focus();
	WPIT_autocompleteFriends(jQuery("#tag"));
}

function WPIT_checkEmpty(element) {
    var stringa = jQuery(element).val();
	while (stringa.substring(0,1) == ' '){
        stringa = stringa.substring(1, stringa.length);
    }
    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
        stringa = stringa.substring(0,stringa.length-1);
    }
    if (stringa === "")
		jQuery('.tagEditorButtonBar').children('.saveButton').addClass('tagEditorButtonDisabled');
	else
		jQuery('.tagEditorButtonBar').children('.saveButton').removeClass('tagEditorButtonDisabled');
}

/**
 * WPIT closeTagger
 * close the tagger form
 * @param {Object} element: element related to form
 */
function WPIT_closeTagger(element) {
	WPITtags.tagging = false;
	var tagEditor = jQuery("#tagEditor");
	var tagTarget = jQuery("#tagTarget");
	jQuery("#tagCloud").removeClass('pending');
	jQuery(tagEditor).fadeOut("500", function() {jQuery(tagEditor).remove()});
	jQuery(tagTarget).fadeOut("500", function() {jQuery(tagTarget).remove()});
}

function WPIT_sendTags(sender) {
	var tagCloud = jQuery('#tagCloud');
	var i=0;
	var max=jQuery(tagCloud).children(".pendingTag").length;
	jQuery(tagCloud).children(".pendingTag").each(function() {
		i = i+1;
		WPIT_sendTag(jQuery(this), i, max);
	});
	jQuery(tagCloud).parent().children('p').children('.tagCloudSubmitter').remove();
	jQuery(tagCloud).parent().children('img').unbind("click");
	jQuery(tagCloud).removeClass('pending')
	WPITtags.tagging = false;
}

/**
 * WPIT sendTag
 * send the tag to database
 * @param {Object} sender: "save" button
 * @param {Object} count: current pointer position
 * @param {Object} max: stack size
 */
function WPIT_sendTag(tag, count, max) {
	// Get the parameters
	var id_pieces = jQuery(tag).attr('rel').split("_");
	var photo_id = id_pieces[1];
	var x = id_pieces[2];
	var y = id_pieces[3];
	
	var tag = jQuery(tag).html();
	
	jQuery.post(wpit_ajax+"wpimgtagger.php",
	{
		'action': 'addtag',
		'x': x,
		'y': y,
		'tag': tag,
		'photo_id': photo_id,
		'rete':WPITtags.rete
	},
	function() {
		WPIT_tagCloud(photo_id, jQuery("#wpit_picture_"+photo_id));
	});
}

/**
 * WPIT removeTag
 * remove tag from database
 * @param {Object} sender: "remove" link
 * @param {Object} id: id of the tag to remove to
 * @param {Object} photo_id: photo related to tag
 */
function WPIT_removeTag(sender, id, photo_id) {
	jQuery.post(wpit_ajax+"wpimgtagger.php",
	{
		'action': 'removetag',
		'tag_id': id,
		'rete':WPITtags.rete
	},
	function() {
		WPIT_tagCloud(photo_id, jQuery(sender).parent().parent().children("img"));
	});
}

/**
 * WPIT showTag
 * preview the tag on mouseover
 * @param {Object} element: element related to tag
 * @param {Object} x: x position of the tag
 * @param {Object} y: y position of the tag
 */
function WPIT_showTag(element, x, y) {
	var tagWrapper = jQuery("#tagWrapper");
	if (jQuery(tagWrapper).children(".tagEditor").length == 0) {
		jQuery(tagWrapper).children(".tagTarget").remove();
		
		var tagElement = "<div class='tagTarget' style='top: "+(y)+"px; left: "+(x)+"px;position:absolute;'></div></div>";
		jQuery(tagElement).appendTo(tagWrapper);
		jQuery(".tagTarget").fadeIn("8000");
	}
}

/**
 * WPIT clearShowTag
 * delete the previewed tag on mouseout
 * @param {Object} element: element related to tag
 */
function WPIT_clearShowTag(element) {
	var tagWrapper = jQuery(element).parent().parent();
	if (jQuery(tagWrapper).children("#tagEditor").length == 0)
		jQuery(tagWrapper).children(".tagTarget").remove();
}

function WPIT_formatFriend(row, i) {
	return row[i].id+" "+row[i].name;
}

function WPIT_autocompleteFriends(element) {
	jQuery("#tag_text").SimpleSuggest({
		"proxy": wpit_ajax+"wpimgtagger.php",
		"proxy_params": {"action": "getfriends"},
		"proxy_method": "post"
	});
}

/**
 * On Page Load
 */
jQuery(function() {
	// Add the tagger function
	jQuery("[rel='tagger']").each(function() {		
		WPIT_addTagTrigger(jQuery(this));
	});
});
