/*
 * $RCSfile: $
 *
 * Digibug4CPG - a plugin for Coppermine gallery to create photo prints, and print product gift items
 * Copyright (C) 2006 Digibug Express, Inc. 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */
/**
 * @version $Revision: $ $Date: $
 * @package Digibug4CPG
 * @author James Andrews <jandrews@digibug.com> for Digibug Express, Inc. http://www.digibug.com/
 */

// Global javascript variables that we need for processing.
var digibugVisibleDiv = null;
var digibugImageCart = null;

/* **************************************************
 * Function to display the image cart
 ***************************************************/
function digibugOpenViewCart() {
    if(digibugVisibleDiv != null) {
      document.GetElementById(digibugVisibleDiv).style.display="none";
    }
    document.getElementById("digibug-cartview").style.display="block";
    digibugVisibleDiv="digibug-cartview";
} // end: dapiOpenViewCart()


/* **************************************************
 * Function to display the image cart
 ***************************************************/
function digibugCloseViewDivs(divId) {
    document.getElementById(divId).style.display="none";
    digibugVisibleDiv=null;
} // end: dapiCloseViewCart()

function digibugOpenViewImageOnItem() {
    if(digibugVisibleDiv != null) {
      document.GetElementById(digibugVisibleDiv).style.display="none";
    }
    document.getElementById("digibug-itemview").style.display="block";
    digibugVisibleDiv="digibug-itemview";
} // end: function digibugOpenViewItem()

function digibugProcessImageInCart(thumb,tWidth,tHeight,raw,rWidth,rHeight,status) {
      // Get the XML object.
      var xmlhttp =  xmlHttpRequestObj();

      // Open a post to the inquire_contact.pbp page.
      xmlhttp.open('post',digibugSiteUrl+'/plugins/Digibug4CPG/cart_control.php',true);

      // The callback function
      xmlhttp.onreadystatechange = function() {

          // When the readyState is for we are ready to give the user a response.
          if (xmlhttp.readyState == 4) {

              // if the xml status is 200 then clear the form and change the visible div.
              if (xmlhttp.status == 200) {
                xmldata = xmlhttp.responseXML;
                digibugPostProcessAddRemoveSequence(xmldata);
                digibugRebuildCartDisplay();
                if(document.getElementById('digibug-cartarea').firstChild == document.getElementById('digibug-cart-clear')){
                    digibugCloseViewDivs('digibug-cartview');
                }
              }
          }
      }

      if(status == "+ Cart"){
          queryString = 'thumbnail='+thumb+'&tWidth='+tWidth+'&tHeight='+tHeight+'&rawimage='+raw+'&rWidth='+rWidth+'&rHeight='+rHeight+'&action=Add';
      }else{
          queryString = 'thumbnail='+thumb+'&tWidth='+tWidth+'&tHeight='+tHeight+'&rawimage='+raw+'&rWidth='+rWidth+'&rHeight='+rHeight+'&action=Remove';
      }

      // Prepare the header
      xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

      xmlhttp.send(queryString);

    
} // end: digibugProcessImageInCart(thumb,tWidth,tHeight,raw,rWidth,rHeight)

function xmlHttpRequestObj(){
  var req = null;
  if (window.XMLHttpRequest) {
    reqObj = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    reqObj = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return reqObj;
} // end: function xmlHttpRequestObj()

function digibugPostProcessAddRemoveSequence(responseXML){
    response = responseXML.getElementsByTagName('responsedata');
    if(response[0].getAttribute('success') == "true"){

        var buttonRefs = document.getElementsByName(response[0].getAttribute('processedimage'));

        for(cntr=0; cntr < buttonRefs.length; cntr++){
            if(response[0].getAttribute('action') == "Add" && buttonRefs[cntr].firstChild.data=='+ Cart'){
              buttonRefs[cntr].firstChild.data='- Cart'
            }else if(response[0].getAttribute('action') == "Remove" && buttonRefs[cntr].firstChild.data=='- Cart'){
              buttonRefs[cntr].firstChild.data='+ Cart'
            }else{
            }
        }

        digibugImageCart = responseXML.getElementsByTagName('imagedata');
        newTotal = digibugImageCart.length;
        if(newTotal == 0 || newTotal > 1 ){
            document.getElementById("digibug-cart-total").innerHTML=newTotal+' images';
        }else{
            document.getElementById("digibug-cart-total").innerHTML=newTotal+' image';
        }
    }
} //end: digibugPostProcessAddRemoveSequence(responseXML);

function digibugCheckout(){
    if(!digibugImageCart || digibugImageCart.length == 0){
        alert("Unable to checkout.  Your cart is empty.");
    }else{

      // Dynamically build the form so we can submit the data.
      digibugCheckoutForm = document.createElement('form');
      digibugCheckoutForm.method="post";
      digibugCheckoutForm.id="digibugCheckout";
      digibugCheckoutForm.action=digibugPostUrl;
      versionInput = document.createElement('input');
      versionInput.type="hidden";
      versionInput.name="digibug_api_version";
      versionInput.value="100";
      partnerInput = document.createElement('input');
      partnerInput.type="hidden";
      partnerInput.name="company_id";
      partnerInput.value=digibugCustomerId;
      priceListInput = document.createElement('input');
      priceListInput.type="hidden";
      priceListInput.name="event_id";
      priceListInput.value= digibugListId;
      commandInput = document.createElement('input');
      commandInput.type="hidden";
      commandInput.name="cmd";
      commandInput.value="adding";
      returnInput = document.createElement('input');
      returnInput.type="hidden";
      returnInput.name="return_url";
      returnInput.value=window.location;
      numInput = document.createElement('input');
      numInput.type="hidden";
      numInput.name="num_images";
      numInput.value=digibugImageCart.length;
      digibugCheckoutForm.appendChild(versionInput);
      digibugCheckoutForm.appendChild(partnerInput);
      digibugCheckoutForm.appendChild(priceListInput);
      digibugCheckoutForm.appendChild(commandInput);
      digibugCheckoutForm.appendChild(returnInput);
      digibugCheckoutForm.appendChild(numInput);
      for(cntr=0; cntr < digibugImageCart.length; cntr++){
        thumbImageInput = document.createElement('input');
        thumbImageInput.type="hidden";
        thumbImageInput.name="thumb_"+cntr;
        thumbImageInput.value=digibugImageCart[cntr].getAttribute('thumbnail');
        thumbWidthInput = document.createElement('input');
        thumbWidthInput.type="hidden";
        thumbWidthInput.name="thumb_width_"+cntr;
        thumbWidthInput.value=digibugImageCart[cntr].getAttribute('thumbwidth');
        thumbHeightInput = document.createElement('input');
        thumbHeightInput.type="hidden";
        thumbHeightInput.name="thumb_height_"+cntr;
        thumbHeightInput.value=digibugImageCart[cntr].getAttribute('thumbheight');
        rawImageInput = document.createElement('input');
        rawImageInput.type="hidden";
        rawImageInput.name="image_"+cntr;
        rawImageInput.value=digibugImageCart[cntr].getAttribute('rawimage');
        rawWidthInput = document.createElement('input');
        rawWidthInput.type="hidden";
        rawWidthInput.name="image_width_"+cntr;
        rawWidthInput.value=digibugImageCart[cntr].getAttribute('rawwidth');
        rawHeightInput = document.createElement('input');
        rawHeightInput.type="hidden";
        rawHeightInput.name="image_height_"+cntr;
        rawHeightInput.value=digibugImageCart[cntr].getAttribute('rawheight');
 /*       rawHeightInput = document.createElement('input');
        rawHeightInput.type="hidden";
        rawHeightInput.name="backtext_"+cntr;
        rawHeightInput.value=digibugImageCart[cntr].getAttribute('rawheight'); */
        digibugCheckoutForm.appendChild(thumbImageInput);
        digibugCheckoutForm.appendChild(thumbWidthInput);
        digibugCheckoutForm.appendChild(thumbHeightInput);
        digibugCheckoutForm.appendChild(rawImageInput);
        digibugCheckoutForm.appendChild(rawWidthInput);
        digibugCheckoutForm.appendChild(rawHeightInput);
      }
      hiddenDiv = document.getElementById("digibug-hidden-divs");
      hiddenDiv.appendChild(digibugCheckoutForm);

      var clearhttp =  xmlHttpRequestObj();
      // Open a post to the inquire_contact.pbp page.
      clearhttp.open('post',digibugSiteUrl+'/plugins/Digibug4CPG/cart_control.php?action=clear');
      // The callback function
      clearhttp.onreadystatechange = function() {
          // When the readyState is for we are ready to give the user a response.
          if (clearhttp.readyState == 4) {
              // if the xml status is 200 then clear the form and change the visible div.
              if (clearhttp.status == 200) {
                  document.getElementById("digibugCheckout").submit();
              }
          }
      }
      clearhttp.send(null);
    }
} // end: function digibugCheckout()

function digibugRebuildCartDisplay(){

    cartDiv = document.getElementById('digibug-cartarea');

    while(cartDiv.hasChildNodes()){
     cartDiv.removeChild(cartDiv.firstChild);
    }

    for(cntr=0; cntr < digibugImageCart.length; cntr++){ 

      cartDiv.appendChild(digibugCartItemElement(digibugImageCart[cntr].getAttribute('thumbnail'),digibugImageCart[cntr].getAttribute('thumbwidth'),digibugImageCart[cntr].getAttribute('thumbheight'),digibugImageCart[cntr].getAttribute('rawimage'),digibugImageCart[cntr].getAttribute('rawwidth'),digibugImageCart[cntr].getAttribute('rawheight')));

    }

    // Now that we have the image in the cart we need a clear div
    cleardiv = document.createElement("div");
    cleardiv.style.clear="both";
    cleardiv.id="digibug-cart-clear";
    cartDiv.appendChild(cleardiv);
} // end function digibugRebuildCartDisplay(xmldata)

function digibugCartItemElement(thumb,tWidth,tHeight,raw,rWidth,rHeight){
        tmpImg = document.createElement('img');
        tmpImg.src=thumb; //digibugImageCart[cntr].getAttribute('thumbnail');
        tmpImg.width=tWidth; // digibugImageCart[cntr].getAttribute('thumbwidth');
        tmpImg.height=tHeight; //digibugImageCart[cntr].getAttribute('thumbheight');
        tmpImg.alt="";

        tmpLnk = document.createElement('a');
        tmpLnk.appendChild(document.createTextNode("- Cart"));
        tmpLnk.href="javascript:digibugProcessImageInCart('"+thumb+"',"+tWidth+","+tHeight+",'"+raw+"',"+rWidth+","+rHeight+",'- Cart')";

        tmpDiv = document.createElement('div');
        tmpDiv.appendChild(tmpImg);
        tmpDiv.appendChild(document.createElement('br'));
        tmpDiv.appendChild(tmpLnk);
        tmpDiv.style.width=tWidth;
        tmpDiv.style.paddingRight="25px";
        tmpDiv.style.paddingBottom="15px";
        tmpDiv.style.cssFloat="left";
        tmpDiv.style.styleFloat="left";

        return tmpDiv;
} // end: function digibugCartItemElement()

function digibugInitializeCart(){
    // Get the XML object.
    var xmlhttp =  xmlHttpRequestObj();

    // Open a post to the inquire_contact.pbp page.
    xmlhttp.open('post',digibugSiteUrl+'/plugins/Digibug4CPG/cart_control.php',true);

    // The callback function
    xmlhttp.onreadystatechange = function() {

        // When the readyState is for we are ready to give the user a response.
        if (xmlhttp.readyState == 4) {
            // if the xml status is 200 then clear the form and change the visible div.
            if (xmlhttp.status == 200) {
               digibugImageCart=xmlhttp.responseXML.getElementsByTagName('imagedata');
               digibugRebuildCartDisplay();
            }
        }
    }

    // Create the query string.
    queryString = 'action='+"cartlist";

    // Prepare the header
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xmlhttp.send(queryString);
} // end: function digibugCartItemElement(thumb,tWidth,tHeight,raw,rWidth,rHeight)

function digibugClearLocalCart(){
      var clearhttp =  xmlHttpRequestObj();
      // Open a post to the inquire_contact.pbp page.
      clearhttp.open('post',digibugSiteUrl+'/plugins/Digibug4CPG/cart_control.php?action=clear');
      // The callback function
      clearhttp.onreadystatechange = function() {
          // When the readyState is for we are ready to give the user a response.
          if (clearhttp.readyState == 4) {
              // if the xml status is 200 then clear the form and change the visible div.
              if (clearhttp.status == 200) {
                  return true;
              }else{
                  return false;
              }
          }
      }
      clearhttp.send(null);
} // end: digibugClearLocalCart();

