/**
 * productDetailsAndCart.js
 *
 * Custom javascript module for the index page of the allurent-checkout  and product details
 * applications.
 */

// off switch uncomment
//disableArc20 = true;


//========================================================================
// Utility functions
//========================================================================

function arc_launch_checkout() {
        _arc_debug(" arc_launch_checkout ");
        arc.dispatchEvent({
                type: 'showCheckout',
                topic: 'client',
                className: 'com.allurent.arc.events.ClientEvent',
                data: { context: 'external' }
        });
}



/**
 * State of "shopping bag" link.
 */
var cartLinkEnabled = true;
var cartOpened = false;

// Counter for Inactive Shopping Bag
var cntrInactiveCart = 0;
var INACTIVE_CART_TIMER = 3;

/**
 * Handle mouse over on the shopping cart button.
 */
function handleCartMouseOver()
{
    if (arc.enabled)
    {
        updateCartLink();
        if ((cartClient!= null) && (!cartClient.visible)) handleCartClick();
    }
}

/**
 * Handle click on the shopping cart button.
 */
function handleCartClick(addTimer)
{
    _arc_debug( " *** handleCartClick " +  arc.clientMgr.clients["cart"].visible );
    _arc_debug(" handleCartClick: " );
    // Prevent opening with 0 items
    //if (cartItemCount() == 0) return;
    
    // Prevent click abuse
    if (cartClient.visible && cartLinkEnabled)
    {
        openOrCloseCartClient(false);
    }
    else if (cartLinkEnabled)
    {
        switch (arc.enabled)
        {
        case true:
            if (cartOpened)
            {
              // Update the cart state
              arc.dispatchEvent({
                      type: 'orderItemAdded',
                      topic: 'order',
                      className: 'com.allurent.arc.events.OrderEvent'
              });
            }
            cartOpened = true;
            if (addTimer!= null && addTimer == true)
            {
                openOrCloseCartClient(true, true);
            }
            else
            {
                openOrCloseCartClient(true);
            }
            
            break;
        case false:
            // If can't run Allurent app, redirect to placeholder.
            window.location.href = arc20CheckoutPage;
            break;
        default:
            // richAppEnabled not yet set.  Do nothing.
        }
    }
}


/**
 * Send a message to the cart client, telling it to open or close.
 */
function openOrCloseCartClient(open, addTimer)
{
    var timerDuration = 0;
    if (addTimer != null && addTimer == true)
    {
        cartClient.listenInactiveCart = true;
    }
    else
    {
        cartClient.listenInactiveCart = false;
    }

    _arc_debug(" IN openOrCloseCartClient , open boolean = " + open);
    arc.dispatchEvent({
        type: open ? 'showCart' : 'hideCart',
        topic: 'client',
        className: 'com.allurent.arc.events.ClientEvent',
        data: { context: 'external' }
    });
    disableCartLink();
}

/**
 * Temporarily disable the "shopping bag" link, to give the cart open/close
 * animation a chance to finish.
 */
function disableCartLink()
{
    cartLinkEnabled = false;
    setCartLinkTitle("");
    
    // Re-enable cart link
    setTimeout("reenableCartLink();", 1000);
}

function reenableCartLink()
{
    cartLinkEnabled = true;
    updateCartLink();
}

/**
 * Update the state of the "shopping bag" link.
 */
function updateCartLink()
{
   if (cartItemCount() == 0)
    {
        //cartLinkEnabled = false;
        document.getElementById("richInLineCart").className = "topnavDisabledLink";
        setCartLinkTitle("No items in bag");
    }
    else
    {
        cartLinkEnabled = true;
        document.getElementById("richInLineCart").className = "topnavLink";
        setCartLinkTitle(cartClient.visible ? "Click to close" : "");
    }
}

/**
 * Set the title (tooltip text) on the cart link.
 */
function setCartLinkTitle(title)
{
    document.getElementById("richInLineCart").title = title;
}

/*
 * On client update to shoppping cart state, display an new order item count.
 */
arc.addEventListener("cartState", function(event)
{
    requestOrderItemCount();
});


/**
 * Fetch the current order item count from the server.
 */
function requestOrderItemCount() 
{
    // Get the order item count from the server
    var ajax = new Ajax.Request(arc20ItemCountPage + "?salt=" + (new Date().getTime()), {method: 'get', 
                                onComplete: handleOrderItemCount});
}


/**
 * Handle the Ajax request
 */
function handleOrderItemCount(request) 
{
    document.getElementById("bagTextLink").innerHTML = request.responseText;
    updateCartLink();
}

/**
* Non-Ajax "page scrape" way to get the number of items in the cart
*/
function cartItemCount()
{
    var m = /[0-9]+/.exec(document.getElementById('bagTextLink').innerHTML);
    return parseInt(m[0]);
}

/**
 * Handle click on the checkout button.
 */
function openCheckout()
{
    window.location.href = arc20CheckoutPage;
}


/**
 * Main invoker for product details
 */
function arcDetailsLaunch(productId, nodeId, initValues, color)
{
    if ( ! arc.enabled ) 
    {
        return;
    }

    _arc_debug( " *** arcDetailsLaunch " +  arc.clientMgr.clients["cart"].visible );
    // close the cart
    if (  arc.clientMgr.clients["cart"].visible ) 
        openOrCloseCartClient(false);
            
    var prodUri;
    prodUri = "arc://catalog/product/" + productId;

    if (color == null)
    {
        var formNode = document["frm"+productId];
        color = (formNode != null && formNode.colorName != null) ? formNode.colorName.value : "";
    }    


    // If rich apps are not enabled then do a submit on the button node
    switch (arc.enabled)
        {
        case true:
            var editNewOrderItemEvent = {
                type: "editNewUrbanOrderItem",
                topic: "order",
                className: "com.allurent.arcx.app.events.OrderVariantEvent",
                data: { productUri: prodUri,
                        colorCode: color,
                        context: "external" }
            };
            arc.dispatchEvent(editNewOrderItemEvent);
            break;
        case false:
            // The HTML sites' default behavior has a dsp:form for each catalog item.
            // the nodeId is a string id to that form ( 'frm'+ productId )
            document[nodeId].submit();
            break;
        default:
            // richAppEnabled not yet set.  Do nothing.
    }
}

    // WINDOW INIT 
    // WINDOW INIT 
    // WINDOW INIT 

var preserveFunction = window.onload;
var cartClient,editNewClient;

window.onload = function()
{
    _arc_debug(" window.onload ");

       windowInterface = _arc_getWindowState();

       var _b = new arc.Util.page();

       if (  _arc_startMode=="product")
        {  

            // page that are of product mode have 3 client descriptors
            // editNew , editExisting , inlineCart 

            /** initialize client descriptors here so we can use this library across 
              * multiple page. Each page can have thier own config triggered by the _arc_startMode string as to identifier
              * Checkout page would be the other major mode.
              */

            // ****  EDIT NEW & EXISTING  client descriptor
            editNewClient = new arc.ClientDesc(
                "editNew",
                ARC_20_SWF,
                {
                    width: 777,
                    height: 582,
                    left:95,
                    paddingFromTop:80,
                    modal: true,
                    parentElement:"arcStageFF",
                    bgWindowStyleName:ARC_BG_STYLENAME
                },
                [ "editNewOrderItem", "editExistingOrderItem", "editNewUrbanOrderItem" ]
        
            );
            /*STATIC_PRODUCTPICKER_CONFIG_URL*/
            editNewClient.flashvars = {  configUrl:  ARC_20_SWF_CONFIG ,launchPageUrl: escape(window.location.href)};
            // Mac/Safaris Preload bug workaround
            editNewClient.preload=true;//_b.browser.isNot( ["Mac","Safari"]);

            // ***  CART client descriptor
            cartClient = new arc.ClientDesc(
                "cart",
                ARC_20_SWF,
                {
                    anchorElement:"richInLineCart",
                    xoffset: getExceptionOffset(),
                    yoffset: 11,
                    width: 435,
                    height: 400,
                    modal: false
                },
                [ "showCart" ]
            );            
            cartClient.flashvars = {configUrl:ARC_20_SWF_CONFIG, launchPageUrl: escape(window.location.href)};            
            cartClient.visible = false;
            // Mac/Safaris Preload bug workaround
            cartClient.preload= true; //_b.browser.isNot( ["Mac","Safari"]);
            // ONLY initialize if a mode is declared.
            // disable Mac Opera / won't send client close events
            if ( _b.browser.isNot( ["Mac","Opera"]) )
                arc.initialize();


            // fixes Mac Safari by not adding listeners till arc creation is complete
            arcInitListeners();
        }
    
    // call any function(s) that may have been in the window.onload before we took it over.
    if ( typeof (preserveFunction) == "function" ) preserveFunction();

}


//========================================================================
// Event handlers
// Event handlers
// Event handlers
//========================================================================


function arcInitListeners(){

/*
 * Handle capability test failure.
 */
arc.addEventListener("arcInitFailed", function(event) {
    arc.Util.setCookie("checkoutFlag", "arcInitFailed");
    arc.disableRichApps();
//    richAppEnabled = false;
});

/*
 * Handle start of preloading.
 */
arc.addEventListener("arcLoadStarted", function(event) {

});

/*
 * Handle preloading failure.
 */
arc.addEventListener("arcLoadFailed", function(event) {
    alert(event.reason);   // preload is not expected to fail
    arc.Util.setCookie("checkoutFlag", "arcLoadFailed");
    arc.disableRichApps(); //richAppEnabled = false;
});

/*
 * Handle successful initialization.
 */

//alert(" adding arcLoadComplete " + typeof ( arc.addEventListener ) );
arc.addEventListener("arcLoadComplete", function(event) {

        _arc_debug(" *** arcLoadComplete function " );
      
        // Make sure the JSESSIONID cookie is set
        var sessCookie = arc.Util.getCookie("JSESSIONID");
        if ((sessCookie == null || sessCookie == "") && (window.location.href.indexOf("jsessionid") > 0))
        {
            // Reset is based on the URL
            arc.Util.setCookie("JSESSIONID", (((window.location.href.split('?', 1))[0]).split('='))[1]);
        }

        // place holder image(s) we introduced in _catalog_category_itemLink.jsp
        var arcImgBuyArray = document.getElementsByName("arcBuyLink");
        // write in the "buy now" images now that we can launch PD
        for (i = 0; i < arcImgBuyArray.length; i++)
            {

                arcImgBuyArray[i].src = STATIC_ARC_URL + "images/quickLink_out.gif";
                arcImgBuyArray[i].onmouseover=function(){window.status = "Quick view";return true;};
                arcImgBuyArray[i].onmouseout=function(){window.status = "";return true;};
                // Uncomment this line to assign a mouse over image for the quick view image
                //$(arcImgBuyArray[i]).onmouseover=function(){this.src=STATIC_ARC_URL+"images/quickLink_over.png";};
                // Uncomment this line to assign a mouse out image for the quick view image
                //$(arcImgBuyArray[i]).onmouseout=function(){this.src=STATIC_ARC_URL+"images/quickLink_out.gif";};

                parentAnchor =  $(arcImgBuyArray[i]).parentNode;
                if ( parentAnchor ) {
                    parentAnchor.title="quickview";
                }

                parentDiv =  $($(arcImgBuyArray[i]).parentNode).parentNode;
                if ( parentDiv ) {
                    Element.setStyle( parentDiv , { 
                                                    "filter":"alpha(opacity=100)",
                                                    "opacity":"1.0",
                                                    "-moz-opacity":"1.00",
                                                    "left":"-1px" ,
                                                    "top":"-30px" ,
                                                    "position":"absolute"} );
                 
                }
            }

         // check URL and cookies to see if we need to pop up the PD window
        var showRichEditor = arc.Util.getUrlParameter('showRichEditor');
        if (showRichEditor.length > 0)
            {
                var initValues = arc.Util.getCookie("arcRichEditorInit");
                if (initValues != "")
                    {
                        initValues = initValues.split('&');
                        var pid = null;
                        var operation = null;
                        for (i = 0; i < initValues.length; i++)
                            {
                                if(initValues[i].indexOf('productId=') == 0)
                                    {
                                        pid = initValues[i].slice(10);
                                    }
                                else if(initValues[i].indexOf('operation=') == 0)
                                    {
                                        operation = initValues[i].slice(10);
                                    }
                            }
                        if (pid != null && operation != null && showRichEditor == operation)
                            {
                                arcDetailsLaunch(pid, null, initValues);
                            }
                    }
            }
        
        // UPDATE shopping bag link to rich functionality
        if ( bagLink = document.getElementById("richInLineCart")) 
            {
                _arc_debug(" found richInLinecart href=" + bagLink.href ) ;
                bagLink.href="javascript:handleCartClick()";
                //bagLink.onmouseover=handleCartMouseOver;
            }

    // Show Inline cart when adding product from HTML details page
    if (cartClient.showCart)
    {
        handleCartClick(true);
    }

    enableRichApps();

});

/* 
 * Handle client request to show the checkout UI.
 */
arc.addEventListener("showCheckout", openCheckout);

// Flag to track if the cart should be open after a details close. 
// Normally opened for editExisting only
var reopenCart = false;

/*
 * Additional handling of order item editor launch.
 */
arc.addEventListener("editExistingOrderItem", function(event)
{
    // Close the shopping cart.
    openOrCloseCartClient(false);
    reopenCart = true;
    handleProductDetailsS7(true);
});


arc.addEventListener("editNewOrderItem", function(event)
{
    // Do not open cart
    reopenCart = false;
    
    // Set this flag to force all clients to reload state after an
    // add to bag and shopper opens the cart
    cartOpened = true;
});

 
/*
 * Additional handling of client close event.
 */

arc.addEventListener("arcCloseClient", function(event)

{
    switch (event.sourceClientId)
    {
    case cartClient.clientId:

        // While cart closes, disable the "shopping bag" link.
        disableCartLink();
        break;

    case editNewClient.clientId:

        // When order item editor closes, re-open the cart.
        // TODO - once cart is enabled
        if (reopenCart)
        {
          openOrCloseCartClient(true);
          handleProductDetailsS7(false);
        }
        break;
     
    }
});

arc.addEventListener("openCart", function(event)
{
    openOrCloseCartClient(true, true);
    handleProductDetailsS7(false);
});
/**
 * Handle wishlist manage request
 */
arc.addEventListener("wishlistManage", function(event)
{
    window.location.href = "/anthro/wishlist/wishlist.jsp";
});

/**
 * Handle tell a friend
 */
arc.addEventListener("tellAFriend", function(event)
{
  var launchPageUrl = window.location.href;
  launchPageUrl = launchPageUrl.split('&showRichEditor=addToWishList').join('');
  if (launchPageUrl.indexOf("showRichEditor=tellAFriend") == -1)
  {
      if(launchPageUrl.indexOf('?') > -1)
      {
          launchPageUrl += '&showRichEditor=tellAFriend';
      }
      else
      {
          launchPageUrl += '?showRichEditor=tellAFriend';
      }
  }
  // URL encode launchPageUrl, additionally escape the '+' symbol
  launchPageUrl = escape(launchPageUrl).split('+').join('%2B');
  
  var tellAFriendUrl = arc20TellAFriendPage + '?productId=' + event.data.productId + '&cCode=' + event.data.colorCode + '&launchPageUrl=' + launchPageUrl;
  window.location.href = tellAFriendUrl;
});



/**
 * Handle Inactive Cart
 */
arc.addEventListener("arcCartInactive", function(event)
{
    if (cartClient.listenInactiveCart)
    {
        cntrInactiveCart++;
        if (cntrInactiveCart >= INACTIVE_CART_TIMER)
        {
            cntrInactiveCart = 0;
            cartClient.listenInactiveCart = false;
            openOrCloseCartClient(false);
        }
    }
});

/**
 * Rest Inactive Cart
 */
arc.addEventListener("arcCartInactiveReset", function(event)
{
    if (cartClient.listenInactiveCart)
    {
        cntrInactiveCart = 0;
    }
});
} // end registering event 


function handleProductDetailsS7(show)
{

    if (document.location.href.indexOf("productdetail.jsp") > -1 ){ 
        s7 = document.getElementById("scene7viewer") ;
        if ( show) 
            {
                s7.style.display = "none";
                s7.style.visible = "hide";
            }
        else 
            {
                s7.style.display = "inline";
                s7.style.visible = "visible";
                
            }
    }

}
function getExceptionOffset()
{

    return  (document.location.href.indexOf("productdetail.jsp") > -1 ) ? -243 : -315 ; 

}

/**
 * Enable rich shopping cart and product details applications.
 */
function enableRichApps()
{
    // Enable the product rollover buttons.
    //richAppEnabled = true;
    prodFx.enabled = true;
}

function openCart()
{
    if (arc.enabled)
    {
        updateCartLink();
        if ((cartClient!= null) && (!cartClient.visible)) handleCartClick();
    }
    
}

