var SCLoadAjax;

//-------------------------------------------------------------------------------------------------------------------
//called on body load, to retrieve content of shopping cart.
function LoadShoppingCart()
{

  document.getElementById('shoppingcartindicator').style.visibility = "visible"

  strUrl  = "ajax/home_shoppingcart.php";
  strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
  strUrl += "&func=scLoad" ;

  SCLoadAjax = ajaxagb(strUrl, LoadShoppingCartCB);
}

function LoadShoppingCartCB()
{
   if (SCLoadAjax && (SCLoadAjax.readyState==4))
  { if (SCLoadAjax.status==200)
    {

     document.getElementById('shoppingcartindicator').style.visibility =  "hidden"

     ResultRows = SCLoadAjax.responseText.split('\n');

      if(ResultRows[0]=="SC_CONTENT")
      {
        for(i=1, imax=ResultRows.length;i<imax;i++)
        {
          ResultRowCells = ResultRows[i].split('|');
          AddAssetToSc(ResultRowCells[0], ResultRowCells[6], ResultRowCells[1], "userfiles/thumbs/" + ResultRowCells[3], ResultRowCells[2], ResultRowCells[4], ResultRowCells[5], ResultRowCells[7])
        }
      }
      
      if(ResultRows[0]=="SC_NO_SHOPPING_CART")
      {
        document.getElementById('shoppingcartlegend').style.display = "block"
      }
        SCLoadAjax=null;
    }
  }

}




var scTempImg; //@@@@ to keep a reference to the dropped image while waiting for ajax.



//Called when an item is dropped on the shopping cart.
function ShoppingCartDrop(img)
{

  document.getElementById('shoppingcartindicator').style.visibility = "visible"
  scTempImg = img;  //keep ref.

  strUrl  = "ajax/home_shoppingcart.php";
  strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
  strUrl += "&func=scAddItem" ;                                 
  strUrl += "&assetID=" + escape(img.dsID) ;
  strUrl += "&searchstring=" ;

  if(img.origin && (img.origin=="search")) //if image was dragged from results
  { strUrl += escape(document.getElementById('searchtext').value) ; }

  ajaxag(strUrl, ShoppingCartDropCB);
  
}

function ShoppingCartDropCB()
{
   if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {

    document.getElementById('shoppingcartindicator').style.visibility = "hidden"
    scResultRows = xmlData.responseText.split('\n');
    switch (scResultRows[0])
    {
        case "SC_NEW_SET_COOKIE":
          SetCookie("scart",scResultRows[1],365);
          //hide legend
          document.getElementById('shoppingcartlegend').style.display = "none"
          EmptyDiv(document.getElementById("sctable"));
          AddAssetToSc(scTempImg.dsID, scTempImg.dsType, scTempImg.title, scTempImg.src, scTempImg.dsPicFileName, scTempImg.dsShortDesc, scTempImg.dsLongDesc, scResultRows[2]);
          break

        case "SC_NEW_NO_COOKIE":
          //hide legend
          document.getElementById('shoppingcartlegend').style.display = "none"
          EmptyDiv(document.getElementById("sctable"));
          AddAssetToSc(scTempImg.dsID, scTempImg.dsType, scTempImg.title, scTempImg.src, scTempImg.dsPicFileName, scTempImg.dsShortDesc, scTempImg.dsLongDesc, scResultRows[2]);
          break

        case "SC_ADDITEM_OK":
          AddAssetToSc(scTempImg.dsID, scTempImg.dsType, scTempImg.title, scTempImg.src, scTempImg.dsPicFileName, scTempImg.dsShortDesc, scTempImg.dsLongDesc, scResultRows[2]);
           break

        case "SC_ITEM_DUPLICATE":
            alert('The item is already on your shopping cart.');
           break

        default:

    }

    }
  }
}


//-------------------------------------------------------------------------------------------------------------------
// This function creates all the dom objects to display a new shopping cart item. No ajax here.
function AddAssetToSc(dsID, dsType, dsTitle, dsThumbFileName, dsPicFileName, dsShortDesc, dsLongDesc, dsPrice)
{

//Add a row to the shoppingcarttable with the asset info.



        // creates <table> and <tbody> elements
        oscTable = document.getElementById("sctable");
        mytablebody = document.createElement("tbody");

        mycurrent_row = document.createElement("tr");

        //DM: Set price to Row, to be able to get it easily
        mycurrent_row.AssetPrice = dsPrice;
        
    // First column: Asset type
        mycurrent_cell = document.createElement("td");
        mycurrent_cell.className = "assetType";
        
        //Asset type icon
        imgAssetType = document.createElement("img");
        imgAssetType.src = "/images/shoppingcart_type_" + dsType + ".gif";
        mycurrent_cell.appendChild(imgAssetType);
        mycurrent_row.appendChild(mycurrent_cell);

    // 4th column: Remove asset
        mycurrent_cell = document.createElement("td");
        mycurrent_cell.className = "removeAsset";
        //Asset title link

        RemoveFromLbLink = document.createElement('a');
        RemoveFromLbLink.setAttribute('href', '#');
        RemoveFromLbLink.onclick = remove_from_sc;
        RemoveFromLbLink.dsAssetId = dsID;

        RemoveLinkCaption = document.createTextNode('Remove');
        RemoveFromLbLink.appendChild(RemoveLinkCaption);

        mycurrent_cell.appendChild(RemoveFromLbLink);
        mycurrent_row.appendChild(mycurrent_cell);

    // Second column: Asset title
        mycurrent_cell = document.createElement("td");
        mycurrent_cell.className = "assetTitle";
        //Asset title link

        NewTitleLink = document.createElement('a');
        NewTitleLink.setAttribute('href', '#');

        NewTitleLink.src = dsThumbFileName;
        NewTitleLink.dsID = dsID;
        NewTitleLink.dsType = dsType;                    // digitalshow's assetType
    	  NewTitleLink.setAttribute('title',dsTitle);
        NewTitleLink.dsPicFileName = dsPicFileName;
        NewTitleLink.dsShortDesc = dsShortDesc;
        NewTitleLink.dsLongDesc = dsLongDesc;


        NewTitleLink.onclick = function(){showOverlayBox(this); return false;};

        NewTitleData = document.createTextNode(dsTitle);
        NewTitleLink.appendChild(NewTitleData);

 /*       NewSep = document.createElement("DIV");
        NewSep.className = "divDots";
        NewSep.innerHTML = "------"; //@@@@ divDots */

        mycurrent_cell.appendChild(NewTitleLink);
      /*  mycurrent_cell.appendChild(NewSep);*/
        mycurrent_row.appendChild(mycurrent_cell);

    // 3rd column: Asset Price

        mycurrent_cell = document.createElement("td");
        mycurrent_cell.className = "assetPrice";

        pricetext = document.createTextNode(dsPrice + " credits"); //@@@@ price
        mycurrent_cell.appendChild(pricetext);
        mycurrent_row.appendChild(mycurrent_cell);

        mytablebody.appendChild(mycurrent_row);
        oscTable.appendChild(mytablebody);

        // Update total price
        scUpdateTotal();
        
}

//-------------------------------------------------------------------------------------------------------------------
function scitem_click_ShowDetails(e, linkref)
{
  alert('Details');
}





//-------------------------------------------------------------------------------------------------------------------

var scRemoveItemRef; //Reference to the div to be deleted

function remove_from_sc()
{

    document.getElementById('shoppingcartindicator').style.visibility =  "visible"

    strUrl  = "ajax/home_shoppingcart.php";
    strUrl += "?unid=" + Math.round(Math.random()* 10000) ;       // Hard way to avoid caching
    strUrl += "&func=scRemoveItem" ;
    strUrl += "&assetID=" + escape(this.dsAssetId) ;


    //Set reference to the div to be deleted.

    scRemoveItemRef = this.parentNode.parentNode.parentNode;

    ajaxag(strUrl, remove_from_scCB);


    return false;

}

function remove_from_scCB()
{

   if (xmlData.readyState==4)
  { if (xmlData.status==200)
    {

    document.getElementById('shoppingcartindicator').style.visibility = "hidden";
    scDeleteResult = xmlData.responseText.split('\n');
    switch (scDeleteResult[0])
    {
        case "SC_LAST_ITEM_DELETE_COOKIE":
          DeleteCookie("scart");
          document.getElementById('sctable').removeChild(scRemoveItemRef);
          scUpdateTotal(); // Update total price
          document.getElementById('shoppingcartlegend').style.display = "block"
          break

        case "SC_DELETE_OK_LAST_ITEM":
          document.getElementById('sctable').removeChild(scRemoveItemRef);
          scUpdateTotal(); // Update total price
          document.getElementById('shoppingcartlegend').style.display = "block"
          break

        case "SC_DELETE_OK":
          document.getElementById('sctable').removeChild(scRemoveItemRef);
          scUpdateTotal(); // Update total price
          break

        case "SC_BAD_SHOPPING_CART":
           //@@@@ reload shopping cart
           break

        default:

    }

    }
  }

}



//-------------------------------------------------------------------------------------------------------------------
// function btnChekcOut_click(). Assigned to the onclick event of the input type button id=btnCheckOut (Check Out Button)
function btnCheckOut_click()
{

  // Check whether there are items in the Shopping Cart
  oscTable = document.getElementById("sctable");
  ChildRows = oscTable.getElementsByTagName("tr");

  if (ChildRows.length > 0) {
    window.location.href = 'checkout.php';
  } else {
    alert('The shopping cart is empty.');
  }

}


//-------------------------------------------------------------------------------------------------------------------
// Updates the Shopping Cart Total Amount. (called every time the shopping cart contents are updated)
function scUpdateTotal()
{

  var TotalAmt = 0;
  var i=0;

  var oscTable = document.getElementById("sctable");
  var ChildRows = oscTable.getElementsByTagName("tr");

  for (i=0; i<ChildRows.length; i++) {
    TotalAmt += parseInt(ChildRows[i].AssetPrice);
  }

  document.getElementById("shoppingcarttotal").innerHTML = TotalAmt + " credits";

}




