// Function that will use the FULL_BASE_URL from CakePHP to add to the URL
function url(u) {
	return FULL_BASE_URL + u;
}

/**
 * Loads in a URL into a specified divName, and applies the function to
 * all the links inside the pagination div of that page (to preserve the ajax-request)
 * @param string href The URL of the page to load
 * @param string divName The name of the DOM-element to load the data into
 * @return boolean False To prevent the links from doing anything on their own.
 */
function loadPiece(href,divName) {
    $(divName).load(href, {}, function(){
        var divPaginationLinks = divName+" #pagination a";
        $(divPaginationLinks).click(function() {
            var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            return false;
        });
    });
}

function in_array(needle, haystick) {

	for (i = 0; i < haystick.length; i++)
		if (haystick[i] == needle) return true;
	return false;

}

function checkSavedPersonalGroups() {

		// Mouseover for message rows
		$("#messages TR").hover(function () {
			$(this).addClass('selected');
		}, function () {
			$(this).removeClass('selected');
		});

		var key = "PersonalgroupState";

		if (!$.cookie(key)) return;

		// Check the cookie
		var groups = $.cookie(key).split(",");

		if (groups != null) {

			// Because the default is that all the groups are open. The array will determine
			// which items will be left open and others are closed
//			alert(groups);
			$('.Personalgroup.hasFriends').each( function () {
				var id = "#"+$(this).attr('title');
				if (!in_array(id, groups)) {
					$(id).hide();
				}
			});

		}
		else {
			// Default is all open
		}

}

function saveOpenPersonalgroups() {

	var key = "PersonalgroupState";
	var ids = new Array();

	$('a.Personalgroup.hasFriends').each(function (n) {
		var id = "#"+$(this).attr('title');
		if ($(id).css('display') == 'block') ids[ids.length] = id;
	});

	$.cookie(key, null);
	$.cookie(key, ids);

}

function removeInviteClick(el) {

	// Remove the hidden field  ...
	var id = el.parent().attr('rel');
	$('#'+id).remove();

	// .. and this
	el.parent().remove();

	// Show 'empty' message when no items are left
	if ($("DIV.invitedlist .removeInvite").length == 0) {
		$('.no-invites').show();
	}
	else {
		$('.no-invites').hide();
	}

}

// Invite , adding e-mails
var inviteCounter = 0; // Needed to create a unique ID for the added e-mail (hidden field)

$(document).ready(function() {

	$(".removeInvite").each(function () {
		$(this).click(function () { removeInviteClick($(this)); });
	});

	$('#invitebutton').click(function () {

		var email = $('#InviteEmail');
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.val())){

				inviteCounter++; // Increase counter

				$("DIV.invitedlist").find(".no-invites").hide();

				var closeIcon = $("<img class='removeInvite' src='/img/icons/removeinvite.gif'>");
				closeIcon.click(function () { removeInviteClick($(this)); });

				var person = $("<div>"+email.val()+"</div>");
				closeIcon.prependTo(person); // Add the icon

				person.addClass('invited');
				person.attr('rel','invitedemail' + inviteCounter); // Must know something about target

				person.prependTo($("DIV.invitedlist"));

				var hiddenemailadres = $("<input name='data[Invite][emails][]' id='invitedemail" + inviteCounter + "' type='hidden' value='"+email.val()+"'>");
				hiddenemailadres.appendTo("FORM.clean");

				// Clean the field contents
				email.val('');
				email.removeClass('error');

		}
		else {
			email.addClass('error');
		}

	});


	// Show/hide   enddate => current_date options
	$(".endNow").click(function () {

		var state = $(this).attr('checked');
		if (state == true) {
			$(this).parent().parent().find("DIV.date").hide();
		}
		else {
			$(this).parent().parent().find("DIV.date").show();
		}

	});


	// Show/hide an information outline for the field you're editing

	$('.profileclean INPUT, .profileclean TEXTAREA').focus(function () {
		$(this).parent().parent().parent().addClass('selected');
	});

	$('.profileclean SELECT').focus(function () {
		$(this).parent().parent().addClass('selected');
	});

	$('.profileclean INPUT, .profileclean TEXTAREA').blur(function () {
		$(this).parent().parent().parent().removeClass('selected');
	});

	$('.profileclean SELECT').blur(function () {
		$(this).parent().parent().removeClass('selected');
	});

	// Init the helpboxes
	$(".helpbox").each( function (n) {

		var help = $(this).attr('rel');
		var el = $("<div class='helpbox'>"+help+"</div>");
		el.hide();
		el.appendTo($(this));
		el.css('position','absolute');
		el.css('left',$(this).position().left + 10);
		el.css('top',$(this).position().top);

	});

	$(".helpbox").mouseover(function () {
		$(this).find("DIV.helpbox").show();
	}).mouseout(function () {
		$(this).find("DIV.helpbox").hide();
	});

	// HELP

	$('#helpcentre .helpanswer').hide();

	$('#OpenAllHelpGroups').click(function () {
		$('#helpcentre .helpanswer').fadeIn('slow');
	});
	$('#CloseAllHelpGroups').click(function () {
		$('#helpcentre .helpanswer').fadeOut('slow');
	});

	$('#helpcentre .helptopic A').click(function () {
		$(this).parent().parent().find(".helpanswer").toggle();
	});


	// End of HELP

	$('#Interestgroup-clearlist').click(function () {
		$("#results").empty();
		$("#findinterestgroupbox").val('');
	});

	// Flash message generated from CakePHP
	$('.flash_success a.close').click(function () {
		$(this).parent().hide();
	});
	$('.flash_failure a.close').click(function () {
		$(this).parent().hide();
	});
	$('.flash a.close').click(function () {
		$(this).parent().hide();
	});

	// Mouseover for tablecells
	$('TABLE.personalgroupsindex TD .users TD').hover(function () {
		$(this).parent().addClass('selected');
	},function() {
		$(this).parent().removeClass('selected');
	});


	$('#OpenAllPersonalGroups').click(function () {
		$('div.personalgroupusers').fadeIn('slow');
	});
	$('#CloseAllPersonalGroups').click(function () {
		$('div.personalgroupusers').fadeOut('slow');
	});

	$('a.Personalgroup.hasFriends').click(function(e) {
		var el = $("#"+$(this).attr('title'));

		if (el.css('display') == 'block') el.hide();
		else el.show();

		saveOpenPersonalgroups(); // When effects are used, this function could be
								  // called before the effect is done. This results in
								  // an array with the 'being-hidden-element' in it.

	});

	checkSavedPersonalGroups();

	// Operationeel
	$(".help_answerblock").css('display','none'); // Graceful degrading javascript

	$(".help_question").click(function() {
		$(this).parent().find("p").toggle();
	});

	$('#languageselector').change(function() {
		document.location = url("languages/change/" + $(this).val());
	});

	// Degrading javascript
	$(".profilegroup .groupoptions").css('display','none');

	$("<div class='spacer'>&nbsp;</div>").insertAfter("div.groupoptions");
	$(".profilegroup .spacer").css('display','block');

	$(".profilegroup").hover(function() {
		$(this).find(".spacer").css('display','none');
		$(this).find(".groupoptions").css('display','block');
	}, function () {
		$(this).find(".spacer").css('display','block');
		$(this).find(".groupoptions").css('display','none');
	});

	var resultsTimer;
	// AJAX search for interestgroups on the network
	$('#findinterestgroupbox').keyup(function (e) {
		if ($(this).val() !== "") { // When not empty
			if (e.keyCode >= 65 && e.keyCode <= 97) { // Alphanumeric respons only
				$("#results").show();
				loadPiece(url('/interestgroups/search/'+$("#findinterestgroupbox").val()), "#results");
			}
		}
	});

	// AJAX search for friends on the network
	$('#findbox').keyup(function (e) {
		if ($(this).val() !== "") { // When not empty
			if (e.keyCode >= 65 && e.keyCode <= 97) { // Alphanumeric respons only
				loadPiece(url('/contacts/search/'+$("#findbox").val()), "#results");
			}
		}
	});

	// AJAX search for activities on the network
	$('#findactivities').keyup(function (e) {
		if ($(this).val() !== "") { // When not empty
			if (e.keyCode >= 65 && e.keyCode <= 97) { // Alphanumeric respons only
				var personal = $('#findonlypersonal').attr('checked');
				var extra = "";
				if (personal) extra = "/private";

				loadPiece(url('/events/search/'+$("#findactivities").val()+extra), "#results");
			}
		}
	});

	$("#loader").bind("ajaxSend", function(){
           $(this).show();
     }).bind("ajaxComplete", function(){
           $(this).hide();
     });


	/* Personal message change */
	var canChangePersonalMessage = true;
	$('.personalprofile #personalmessage-input').css('display','none');
	$(".personalprofile #personalmessage-input .loader").css('display','none');

	$(".personalprofile #personalmessage").hover(function () {
		$(this).addClass("selected");
	}, function() {
		$(this).removeClass("selected");
	});

	$('.personalprofile #personalmessage').click(function () {
		if (canChangePersonalMessage) {
			$('#personalmessage').hide();
			$('#personalmessage-input').css('display','block');
			canChangePersonalMessage = false;
		}
	});

	$('.personalprofile #cancelPersonalMessage').click(function () {

		$('#personalmessage-input').hide();
		$('#personalmessage').css('display','block');
		canChangePersonalMessage = true;

	});

	$('.personalprofile #savePersonalMessage').click(function () {

		if ($("#personalmessage-input INPUT").val() !== "") {
			$("#personalmessage-input .loader").css('display','block');
			$("#personalmessage-input .options").hide();

			// Save personal message and set the label
			$.get(url('/profile/changePersonalMessage/' + $("#personalmessage-input INPUT").val()), {}, function (data) {

				$("#personalmessage").html($("#personalmessage-input INPUT").val());

				canChangePersonalMessage = true;
				$("#personalmessage-input .options").css('display','block');
				$("#personalmessage-input .loader").hide();
				$('#personalmessage-input').hide();
				$('#personalmessage').css('display','block');
			});
		}
	});
	/* End personal message change */

	$('TABLE.clean TR').hover( function () {
		$(this).find("> TD").css('background-color','#ddd');
	},function () {
		$(this).find("> TD").css('background-color','white');
	});

	/* Personal name change */
	var canChangeName = true;
	$('.personalprofile #name-input').hide();
	$(".personalprofile #name-input .loader").hide();

	$(".personalprofile #name").hover(function () {
		$(this).addClass("selected");
	}, function() {
		$(this).removeClass("selected");
	});

	$('.personalprofile #name').click(function () {
		if (canChangeName) {
			$('#name').hide();
			$('#name-input').css('display','block');
			canChangeName = false;
		}
	});

	$('.personalprofile #cancelName').click(function () {

		$('#name-input').hide();
		$('#name').css('display','block');
		canChangeName = true;

	});

	$('.personalprofile #saveName').click(function () {

		if ($("#name-input INPUT").val() !== "") {
			$("#name-input .loader").css('display','block');
			$("#name-input .options").hide();

			// Save personal message and set the label
			$.get(url('/profiles/changeName/' + $("#name-input INPUT").val()), {}, function (data) {

				$("#name").html($("#name-input INPUT").val());

				canChangeName = true;
				$("#name-input .options").show();
				$("#name-input .loader").hide();
				$('#name-input').hide();
				$('#name').show();
			});
		}

	});
	/* End personal name change */

});
