var CurrentLightBoxId;
var LoggedOrAssumed = false;

//-------------------------------------------------------------------------------------------------------------------
var LBLoadAjax;
function LoadLightBox()
{
  document.getElementById('lightboxindicator').style.visibility = "visible"

  strUrl  = "ajax/home_lightbox.php";
  strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
  strUrl += "&func=filllb" ;                                    // Call to filllb

  LBLoadAjax = ajaxagb(strUrl, LoadLightBoxCB);
}

function LoadLightBoxCB()
{
if (LBLoadAjax && LBLoadAjax.readyState==4)
 { if (LBLoadAjax.status==200)
 {

  document.getElementById('lightboxindicator').style.visibility = "hidden"

  lbResult = LBLoadAjax.responseText;

  ResultRows = lbResult.split('\n');

  if(ResultRows[0]=="RESULTS_OK")
  {
  EmptyDiv(document.getElementById('lightboxcontainer'));   //Clear "You must login to use lb"
  document.getElementById('lightboxtoolbar').style.display = 'block'; //Show Lbtoolbar

  LoggedOrAssumed = true;
  oSelect = document.getElementById('ligthboxselect');
  oDetailSelect = document.getElementById('detailsligthboxselect');

  EmptyCombo(oSelect);
  EmptyCombo(oDetailSelect);

  currentLbName = '';
  currentLbValue = 1;

  for(i=1, imax=ResultRows.length;i<imax;i++)
  {
    ResultRowCells = ResultRows[i].split('|');

    //Extract here variables taken from the return array.
    dslbName = ResultRowCells[2];
    dslbNum = ResultRowCells[1];
    dsUserLastlb = ResultRowCells[0];


    // Add options to the select
    if(dslbName !=currentLbName)
    {
      // Add lightbox title to select
      var oOption = document.createElement("OPTION");
      var oOptionLB = document.createElement("OPTION"); //For detail add to lightbox
      oOption.text=dslbName;
      oOption.value=currentLbValue;
      oOption.dslbNum = dslbNum;

      oOptionLB.text=dslbName;
      oOptionLB.value=currentLbValue;
      oOptionLB.dslbNum = dslbNum;


      if(window.ActiveXObject)//IE
      { oSelect.add(oOption);  //Lightbox toolbar select
        oDetailSelect.add(oOptionLB); //asset detail select
      }
      else // All others
      { oSelect.appendChild(oOption);
        oDetailSelect.appendChild(oOptionLB);
      }

      currentLbName = dslbName;
      currentLbValue++;
      }

      if(dslbNum==dsUserLastlb)
      {
        dsAssetId = ResultRowCells[3];
        dsAssetTitle = ResultRowCells[4];
        dsAssetPicFileName = ResultRowCells[5];
        dsAssetThumbFileName = "userfiles/thumbs/" + ResultRowCells[6];
        dsAssetType = ResultRowCells[9];
        dsAssetShortDesc = ResultRowCells[7];
        dsAssetLongDesc = ResultRowCells[8];

        // Add assets to lightbox
        if(dsAssetId!="")
        {
          AddAssetToLb(dsAssetId, dsAssetType, dsAssetTitle, dsAssetThumbFileName, dsAssetPicFileName, dsAssetShortDesc, dsAssetLongDesc, ResultRowCells[10]);
        }
      }
    }

    //if there are no assets in the lightbox, display legend
    if(document.getElementById('lightboxcontainer').childNodes.length == 0)
    {
      AddLightboxLegend("Drop media here to add to lightbox", false);
    }



    // Select last used lightbox
    for(i=0,imax=oSelect.childNodes.length;i<imax;i++)
    {
      if(oSelect.childNodes[i].dslbNum==dsUserLastlb)
      { oSelect.childNodes[i].selected = true;}
    }

    CurrentLightBoxId = dsUserLastlb;
  } //if(RESULTS_OK)
  else
  {
    document.getElementById('lightboxtoolbar').style.display = 'none';
    AddLightboxLegend('You must log in to use the Lightbox', true);
  }

  LBLoadAjax = null;
}
}


}

// Temp ImgRef, used for keeping a reference to the asset being added to lb
var tempImgRef;

//-------------------------------------------------------------------------------------------------------------------
function LightBoxDrop(img)
{ // Recieves a reference to the image object dropped
  if( (LoggedOrAssumed == true) &&  (img.origin != 'lightbox') )  // logged or assumed and not dropped from lightbox
  {
    document.getElementById('lightboxindicator').style.visibility = "visible";
    tempImgRef = img;
    AddAssetToUserLb(img.dsID) // ajax to update db

  }
}

//-------------------------------------------------------------------------------------------------------------------
function AddAssetToUserLb(dsAssetID)
{
    strUrl  = "ajax/home_lightbox.php";
    strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       /* Hard way to avoid caching */
    strUrl += "&func=lbAddItem" ;                                    /* Call to lbContent */
    strUrl += "&lbnum=" + escape(CurrentLightBoxId) ;               /* lbID */
    strUrl += "&assetId=" + escape(dsAssetID) ;               /* AssetId */

    ajaxag(strUrl, AddAssetToUserLbCB);
}

//-------------------------------------------------------------------------------------------------------------------
function AddAssetToUserLbCB() //Callback
{
 if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {
      document.getElementById('lightboxindicator').style.visibility = "hidden";
      if(xmlData.responseText == "LB_ADD_ITEM_OK")  // Case OK
      {
        //Remove legend
        if(document.getElementById('lightboxcontainer').childNodes.length == 1)
        {
          if(document.getElementById('lightboxcontainer').childNodes[0].IsLegend)
          {
            EmptyDiv(document.getElementById('lightboxcontainer'));
          }
        }



        AddAssetToLb(tempImgRef.dsID, tempImgRef.dsType, tempImgRef.title, tempImgRef.src, tempImgRef.dsPicFileName, tempImgRef.dsShortDesc, tempImgRef.dsLongDesc, '10'  )
      }

      if(xmlData.responseText == "LB_ADD_ITEM_DUPLICATE")  // Case asset already is on lb.
      {
        alert("You already have that media on this lightbox");
      }


    }
  }
}

//-------------------------------------------------------------------------------------------------------------------
function AddAssetToLb(dsID, dsType, dsTitle, dsThumbFileName, dsPicFileName, dsShortDesc, dsLongDesc, dsStatus  )
{
    //Creates a new asset in the lightbox
    Lbox = document.getElementById('lightboxcontainer');
    nextItemNr = Lbox.childNodes.length + 1

    NewDiv = document.createElement("div");
    NewDiv.className = 'LightboxItem';
    NewDiv.lbContainer = true;
    NewDiv.id = 'lb_item' + nextItemNr;

    NewImage = document.createElement("img");
    NewImage.id = 'lb_image' + nextItemNr;
    
    if (dsStatus == "10") {
      NewImage.src = dsThumbFileName;
    } else {
      NewImage.src = "/images/myassets_unknown.gif";
    }

    NewImage.className = 'LightboxImage';
    NewImage.dsID = dsID;
    NewImage.dsType = dsType;                    /* digitalshow's assetType */
	  NewImage.setAttribute('title',dsTitle);
	  NewImage.origin = 'lightbox';        // used for identifying where was it dragged from
    NewImage.dsPicFileName = dsPicFileName;
    NewImage.dsShortDesc = dsShortDesc;
    NewImage.dsLongDesc = dsLongDesc;

    // Resize image
    LightboxSizeProportion = 0.70;

    if (NewImage.width != 0) {
      // IE
      NewImage.width = LightboxSizeProportion * NewImage.width;
      NewImage.height = LightboxSizeProportion * NewImage.height;
    } else {
      // Firefox, while loading the image, has a width of 0. Change size in Onload
      NewImage.onload = function(e){
        if (isSafari()) {
          ReRender();
        }
        shrinkImage(this, LightboxSizeProportion);
      };
    }


    if (dsStatus == "10") {
      NewImage.onmousedown = imgMDown ;
      NewImage.onclick = function(e){imgShowDetails(e,this);};
    } else {
      NewImage.onclick = function(e) {alert("This asset has been taken back to approval process.");};
    }

    NewTypeH2 = document.createElement("H2");
    NewTypeH2.className = dsType;
    // Special case, CSS class can't start with a number
    if (dsType == "3D") { NewTypeH2.className = "DD"; }


    RemoveFromLbLink = document.createElement('a');
    RemoveFromLbLink.setAttribute('href', '#');
    RemoveFromLbLink.onclick = remove_from_lb;
    RemoveFromLbLink.dsAssetId = dsID;

    RemoveLinkCaption = document.createTextNode('Remove');
    RemoveFromLbLink.appendChild(RemoveLinkCaption);

    NewDiv.appendChild(NewTypeH2);
    NewDiv.appendChild(NewImage);
    NewDiv.appendChild(RemoveFromLbLink);

    Lbox.appendChild(NewDiv);

    new Draggable('lb_image' + nextItemNr , {revert:true,DragCopy: true,srcParentId:"lightboxcontainer"});

//    new Draggable('lb_image' + nextItemNr , {revert:true});
}



//-------------------------------------------------------------------------------------------------------------------
function btnNewLightBox_click()
{
  document.getElementById('newLightbox').style.visibility = 'visible';
  document.getElementById('newLightboxText').value = "";
  document.getElementById('newLightboxText').focus() ;

  return false;
}

//-------------------------------------------------------------------------------------------------------------------
function newLightboxOK_click()
{

  document.getElementById('lightboxindicator').style.visibility = "visible"

  newName = document.getElementById('newLightboxText').value

  strUrl  = "ajax/home_lightbox.php";
  strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
  strUrl += "&func=lbNew" ;                                    // Call to lbNew()
  strUrl += "&lbName=" + escape(newName) ;               //lightbox name

  ajaxag(strUrl, newLightboxOKCB);

  return false;
}


//-------------------------------------------------------------------------------------------------------------------
function newLightboxOKCB()  //newLightboxOK_click callback
{
 if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {
      lbResult = xmlData.responseText;

      document.getElementById('lightboxindicator').style.visibility = "hidden"

      if(lbResult=="LB_ADD_OK")
      {
        document.getElementById('newLightbox').style.visibility = 'hidden';
        LoadLightBox();  // Reloads the lightbox,

      }
      else
      {
        if(lbResult=="LB_ADD_ALREADY_EXISTS")
        {
          alert("You already have a Lightbox with that name. Please choose another name.");
        }

        if(lbResult=="LB_ADD_EMPTY_NAME")
        {
          alert("You must specify a name.");
        }
      }

    }
  }

}



//-------------------------------------------------------------------------------------------------------------------
function newLightboxCancel_click()
{
  document.getElementById('newLightbox').style.visibility = 'hidden';
  return false;
}


//-------------------------------------------------------------------------------------------------------------------
// Delete lightbox button.
function btnDeleteLightBox_click()
{

  conf = confirm("Are you sure?");
  if (conf)
  {

  document.getElementById('lightboxindicator').style.visibility = "visible"

  strUrl  = "ajax/home_lightbox.php";
  strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
  strUrl += "&func=lbDelete" ;                                    // Call to lbNew()
  strUrl += "&lbNum=" + escape(CurrentLightBoxId) ;               //lightbox num

  ajaxag(strUrl, DeleteLightBoxCB);
  }


  return false;

}

//-------------------------------------------------------------------------------------------------------------------
function DeleteLightBoxCB()  //Callback
{
 if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {
      lbResult = xmlData.responseText;

      document.getElementById('lightboxindicator').style.visibility = "hidden"

      //alert(lbResult);

      if(lbResult=="DELETE_LB_OK")
      {
        LoadLightBox();  // Reloads the lightbox,
      }
      else
      {
        if(lbResult=="DELETE_ERROR_LAST_LB")
        {
          alert("You have only one Lightbox. You can't delete it.");
        }
      }
    }
  }
}


//-------------------------------------------------------------------------------------------------------------------
function ligthboxselect_change()
{
  for(i=0,imax=this.childNodes.length;i<imax;i++)
  {
    if(this.childNodes[i].selected)
    {

      EmptyDiv(document.getElementById('lightboxcontainer'));

      //alert(this.childNodes[i].text + ' ' + this.childNodes[i].dslbNum);
      newlbNum=this.childNodes[i].dslbNum;

      CurrentLightBoxId = newlbNum;   //Kept for later

      document.getElementById('lightboxindicator').style.visibility = "visible"

      strUrl  = "ajax/home_lightbox.php";
      strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
      strUrl += "&func=lbContent" ;                                    // Call to lbContent
      strUrl += "&lbnum=" + escape(newlbNum) ;               //lightbox number

      ajaxag(strUrl, updateLb);


    }
  }
}

//-------------------------------------------------------------------------------------------------------------------
function updateLb()
{
 if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {
      lbResult = xmlData.responseText;
      ResultRows = lbResult.split('\n');

//      alert(lbResult);

      for(i=1, imax=ResultRows.length;i<imax;i++)
      {
        ResultRowCells = ResultRows[i].split('|');
        dsAssetId = ResultRowCells[0];
        if(dsAssetId!="")
        {
          dsAssetTitle = ResultRowCells[1];
          dsAssetPicFileName = ResultRowCells[2];
          dsAssetThumbFileName = "userfiles/thumbs/" + ResultRowCells[3];
          dsAssetType = ResultRowCells[6];
          dsAssetShortDesc = ResultRowCells[4];
          dsAssetLongDesc = ResultRowCells[5];

          // Add assets to lightbox
          AddAssetToLb(dsAssetId, dsAssetType, dsAssetTitle, dsAssetThumbFileName, dsAssetPicFileName, dsAssetShortDesc, dsAssetLongDesc, ResultRowCells[7]  );
        }
      }

    if(document.getElementById('lightboxcontainer').childNodes.length == 0)
    {
      AddLightboxLegend("Drop media here to add to lightbox", false);
    }

        document.getElementById('lightboxindicator').style.visibility = "hidden"

    }
  }


}

//-------------------------------------------------------------------------------------------------------------------
function remove_from_lb()
{

    document.getElementById('lightboxindicator').style.visibility = "visible"

    strUrl  = "ajax/home_lightbox.php";
    strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       /* Hard way to avoid caching */
    strUrl += "&func=lbRemoveItem" ;                                   
    strUrl += "&lbnum=" + escape(CurrentLightBoxId) ;
    strUrl += "&assetId=" + escape(this.dsAssetId) ;

    ajaxag(strUrl, remove_from_lbCB);

    this.parentNode.parentNode.removeChild(this.parentNode);

    if(document.getElementById('lightboxcontainer').childNodes.length == 0)
    {
      AddLightboxLegend("Drop media here to add to lightbox", false);
    }

    return false;
}

//-------------------------------------------------------------------------------------------------------------------
function remove_from_lbCB()
{
 if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {
      document.getElementById('lightboxindicator').style.visibility = "hidden";
    }
  }
}

//-------------------------------------------------------------------------------------------------------------------
function AddLightboxLegend(strLegend, bLinkToLogin)
{
//Creates a div inside the lightbox container
//the div is lost when lbcontent is refreshed

  var NewLBTextLegend = document.createTextNode(strLegend);

  if (bLinkToLogin) {
    var NewLBLoginLink = document.createElement("a");
    NewLBLoginLink.setAttribute("href", "login.php");
    NewLBLoginLink.className = "underline";
    NewLBLoginLink.appendChild(NewLBTextLegend)

    NewLBTextLegend = NewLBLoginLink; // Assign to this variable, so that when added to the DIV, the corresponding one will be taken.
  }

  var NewLBDivLegend = document.createElement("DIV");
  NewLBDivLegend.id = "lightboxlegend";
  NewLBDivLegend.IsLegend = true; //property for identifying the legend
  NewLBDivLegend.className = "lightboxlegend";
  NewLBDivLegend.appendChild(NewLBTextLegend)
  
  document.getElementById('lightboxcontainer').appendChild(NewLBDivLegend)
}
