/*

This js file allows to mark a space as a favourite (global or personal) by clicking the star icon.
Since this function is used in a couple places, the code was moved into a seperate include file.

NOTE: When using this javascript include, you will have to make sure that the context fullfills the following requirements:

- contextPath variable has to be set (otherwise the action can not be found).

*/

var operationInProgressArray = new Array(); // use this array to prevent the user from triggering off another labelling operation when one is in progress

function toggleStar(imgElement)
{
   var imagePath = imgElement.src;
   if (imgElement.src.indexOf("star_grey.gif") != -1)
       imgElement.src = contextPath + '/images/icons/star_yellow.gif';
   else
       imgElement.src = contextPath + '/images/icons/star_grey.gif';
}

function addOrRemoveFromFavourites(spaceKey, imgElement)
{
   if (operationInProgressArray[imgElement.id] == null) {

       operationInProgressArray[imgElement.id] = true;

       var url;

       if (imgElement.src.indexOf("star_yellow.gif") != -1) { // if on
           url = contextPath + "/labels/removespacefromfavourites.action";
       }
       else {
           url = contextPath + "/labels/addspacetofavourites.action";
       }

       AJS.safe.ajax({
           url: url,
           type: "POST",
           data: { "key" : spaceKey },
           success: function() {
               toggleStar(imgElement);
               operationInProgressArray[imgElement.id] = null;
           },
           error: function(xhr, text, error) {
               alert("Error : " + text);
               operationInProgressArray[imgElement.id] = null;
            }
       });
   }
}

// if the user switches tabs while spaces are still being labelled, this function will prevent this from happening.
// allowing a location change in the middle of xmlhttp requests causes exceptions to be thrown in firefox (although, they seem to be ignored by ie).
// this is important in high latency environments where users may get impatient.
function gotoUrl(url)
{
   for (var elementId in operationInProgressArray)
   {
       if (operationInProgressArray[elementId] == true)
           return;
   }
   window.location = url;
}
