/**
 * 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;

/**
 * Handle click on the shopping cart button.
 */
function handleCartClick()
{
    _arc_debug(" handleCartClick: " );

    // Prevent opening with 0 items
    //if (cartItemCount() == 0) return;
    
    if (cartLinkEnabled)
    {
        switch (arc.enabled)
        {
        case true:
            // Prevent click abuse
		    if (cartClient.visible)
		    {
		        openOrCloseCartClient(false);
		    }
            else if (cartOpened)
            {
              // Update the cart state
              arc.dispatchEvent({
                      type: 'orderItemAdded',
                      topic: 'order',
                      className: 'com.allurent.arc.events.OrderEvent'
              });
            }
            cartOpened = true;
            openOrCloseCartClient(true);
            break;
        case false:
            // If can't run Allurent app, open checkout.
            openCheckout();
            break;
        default:
            // richAppEnabled not yet set.  Do nothing.
        }
    }
}



/**
 * Send a message to the cart client, telling it to open or close.
 */
function openOrCloseCartClient(open)
{
    _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) 
{
	var itemsInBag = "( " + request.responseText + " )";

	//document.getElementById("bagTextLink").innerHTML = itemsInBag;
    document.getElementById("richInlineCart2").innerHTML = itemsInBag;

    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 (m != null) ? parseInt(m[0]) : 0;
}

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


/**
 * Main invoker for product details
 */
function arcDetailsLaunch(productId, nodeId, initValues)
{
    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;
	
	//var clrCode = document["frml"+productId].colorName.value;
	var clrCode;
	if (document["frml"+productId]) {
		clrCode = document["frml"+productId].colorName.value;
	} else {
		for (var i=0; i<document.forms.length; i++) {
			var cur = document.forms[i].name;
			if (cur.indexOf(productId) > 0) {
				clrCode = document[cur].colorName.value;
				break;
			}			
		}	
    }
     
    // 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: clrCode, 
                        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 cartClient,editNewClient;
var CART_WIDTH = 157;

Event.observe ( window , "load" , function (event) {

    _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

            /** CROSS-SELL INSTRUCTIONS
	     * Change 'height' to 565 when Cross-Sell is enabled.  Set to 444 when Cross-Sell is off
	     * Change <crossSellEnabled> to true in config.jsp to actually turn on it on
	     */
            editNewClient = new arc.ClientDesc(
                "editNew",
                ARC_20_SWF,
                {
                    width: 532,
                    height: 444,
                    paddingFromTop: 100,
                    showEffect: { type: "fadeIn", duration: 1 }, 
                    hideEffect: { type: "fadeOut", duration: 1 },
                    modal: true,
                    parentElement:"arcStageFF"
                },
                [ "editNewOrderItem", "editExistingOrderItem", "editNewUrbanOrderItem" ]
		
            );
            
            // Add observer to close client when you click outside it
			Event.observe (document, "click", function(event){
				// We check to make sure the element id is not "editNew" here because of a Mac 10.5
				// Safari 3 bug (9415).  In Safari, the click event bubbles up to Javascript
				// even if the click was inside the SWF client.  All clicks inside the SWF 
				// register to the "editNew" element - thus the exception.  
				if (editNewClient.visible && Event.element(event).id != 'editNew')
					arc.clientMgr.closeClient('editNew');
		
			})

            /*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
/*
xoffset: getExceptionOffset(),
                    anchorElement:"bagTextLink",
                    xoffset: 0,
                    yoffset: 0,

*/
			cartClient = new arc.ClientDesc(
                "cart",
                ARC_20_SWF,
                {
                    anchorElement:"bagTextLink",
                    xoffset: calcXOffset('bagTextLink'),
                    yoffset: 20,
					width: CART_WIDTH,
                    height: 322,
                    modal: false,
					showEffect: { type: "blindDown", duration: 0.5 }, 
					hideEffect: { type: "blindUp", duration: 0.4 } 
                },
                [ "showCart" ]
            );  
			
			// Add observer to close client when you click outside it
			Event.observe (document, "click", function(event){
				// We check to make sure the element id is not "cart" here because of a Mac 10.5
				// Safari 3 bug (9415).  In Safari, the click event bubbles up to Javascript
				// even if the click was inside the SWF client.  All clicks inside the SWF 
				// register to the "cart" element - thus the exception.  
				if (cartClient.visible && Event.element(event).id != 'cart')
					arc.clientMgr.closeClient('cart');	
			})
			
            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();
        }
});


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


function arcInitListeners(){

/*
 * Handle capability test failure.
 */
arc.addEventListener("arcInitFailed", function(event) {
    arc.Util.setCookie("cartLoadFlag", "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("cartLoadFlag", "arcLoadFailed");
    arc.disableRichApps(); //richAppEnabled = false;
});

/*
 * Handle successful initialization.
 */

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

        _arc_debug(" *** arcLoadComplete function " );
      
/*
        // 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
		//alert("arcImgBuyArray len: " + arcImgBuyArray.length);
        for (i = 0; i < arcImgBuyArray.length; i++)
            {

                arcImgBuyArray[i].src = STATIC_ARC_URL + "images/snapshot_off.gif";
                arcImgBuyArray[i].onmouseover=function(){window.status = "Snapshot";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/snapshot_over.gif";};
                // Uncomment this line to assign a mouse out image for the quick view image
                arcImgBuyArray[i].onmouseout=function(){this.src=STATIC_ARC_URL+"images/snapshot_on.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()";
                if (document.getElementById("richInLineCart2"))
                {
					document.getElementById("richInLineCart2").href = "javascript:handleCartClick()";
                }
            }

		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;
});

arc.addEventListener("editNewUrbanOrderItem", 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:

		// no-op for now
        break;
    }
});

arc.addEventListener("openCart", function(event)
{
	openOrCloseCartClient(true);
	handleProductDetailsS7(false);
});


/**
 * 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;
});


} // 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 : -30 ; 
	return (8);
}

var richAppEnabled;

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

/**
 * Find x-pos & y-pos of an element on screen
 */
/*
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	var pos = new Object();
	pos.x = curleft;
	pos.y = curtop;
	return pos; //[curleft,curtop];
}

function findXPos(obj) {
	var curleft = 0;

	do {
			curleft += obj.offsetLeft;
		} while (obj = obj.offsetParent);

	return curleft;
}

function findYPos(obj) {
	var curtop = 0;

		do {
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);

	return curtop;
}
*/

function calcXOffset(elem)
{
	var xOff = document.getElementById(elem).offsetWidth - CART_WIDTH;
	return xOff;
}
