/*

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 xmlhttp = getXmlHttp();
       if (imgElement.src.indexOf("star_yellow.gif") != -1) // if on
           var url = contextPath + "/labels/removespacefromfavourites.action?key=" + spaceKey;
       else
           var url = contextPath + "/labels/addspacetofavourites.action?key=" + spaceKey
       xmlhttp.open("GET", url);
       xmlhttp.onreadystatechange = function()
       {
           if (xmlhttp.readyState == 4)
           {
               try
               {
                   if (xmlhttp.status == 200)
                   {
                       toggleStar(imgElement);
                       operationInProgressArray[imgElement.id] = null;
                   }
                   else
                   {
                       alert("$action.getText('error.occured.adding.to.favourites') " + xmlhttp.responseText);
                   }
               }
               catch(e)
               {
                   alert("Exception thrown: " + e);
               }
           }
       }
       xmlhttp.send(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;
}
