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

Prototype.Browser.IE6=Prototype.Browser.IE && 
    parseInt(navigator.userAgent.substring (navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7=Prototype.Browser.IE && !Prototype.Browser.IE6;

var singlePid = "";
var productsLength = 0;
var skuNotAdded;
var detailsSwfOff =
{ 
    elementStyle: {position:"absolute" , 
                   top:"-10px", 
                   left:"200px" ,
                   width:"498px" , 
                   height:"0px" ,
                   paddingTop:"0px",
                   paddingLeft:"0px",
                   paddingBottom:"0px",
                   paddingRight:"0px" },
    width: 0,
    height:0
}
var detailsSwfOn = 
{ 
    elementStyle: { position:"absolute"  ,
                    width:"598px" , 
                    height:"498px",					          
                    backgroundImage:(!Prototype.Browser.IE6)?'url(/arc/images/allurent_598_498_shadow.png)':'',
                    backgroundRepeat:"no-repeat",
                    backgroundPosition:"0px 0px" ,
                    paddingTop:"0px",
                    paddingLeft:"0px",
                    paddingBottom:(!Prototype.Browser.IE6 && !Prototype.Browser.IE7)?"8px":"0px",
                    paddingRight:(!Prototype.Browser.IE6 && !Prototype.Browser.IE7)?"8px":"0px"
                     },
    width: 598,
    height:498
}


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

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

    arc.debug(" ***  onload(ed)");
    arc.webCallActive = false;

    // CART AND PRODUCT DETAILS 
    // CART AND PRODUCT DETAILS 

	
    detailsClient = new arc.ClientDesc(
            "details",
            ARC_SWF_URL,
            detailsSwfOff,
            [ "showCart", "editNewOrderItem", "editExistingOrderItem","editNewOrderItemAdded","parked"]
    );
    // this needs to be derived as the carousel products are
        
    var carousel = GSI.carousel || "";
    var attribs = GSI.attribs || "";
    detailsClient.flashvars = {configUrl:ARC_SWF_CONFIG,productCarousel:carousel,storeAttribs:attribs,cartClient:true,editNewClient:true,editExistingClient:true,confirmationClient:true};
    // flag the indicates that the arc client manager should preload this client
    detailsClient.preload=false;
    // listen for readiness
    arc.addEventListener("arcLoadComplete", function(event) {
            arc.debug(" *** in client(details) arcLoadComplete");
    });
    detailsClient.states = [ "showCart", "editNewOrderItem", "editExistingOrderItem","editNewOrderItemAdded","parked"]
    ;
    
    // override preShow method to handle scrim and recalculate the client's position
    detailsClient.preShow = function () {
//        GSI.lightbox.show();
        /*
				arc.debug(" IN pre show "+ typeof($(this.swfDiv)),"red");
				if ( $(this.swfDiv) ) {
				   $(this.swfDiv).setStyle( this.params.elementStyle );
        }
        // center in current viewport
        $(this.params.elementStyle).left =
                (document.viewport.getWidth()/2 - this.params.width/2) + 
                 document.viewport.getScrollOffsets().left ;     
                 */   
    }

        
    //launching cart form product page - overriding ajaxAddToCart
    arc.addEventListener("arcStartComplete", function(event) {  
    	
            //active express shop show button - overriding showButton
            window.showButton = function(buttonNumber) {
                document.getElementById(buttonNumber).style.display="";
            }
            // init swf for readiness
            arcInitSwf();
            // over ride add to bad behavior
            window.ajaxAddToCart = function (formObject) {
                
                if(arc.webCallActive){
                }else{
                        arc.webCallActive = true;
                        //build products object
                        var products = {};
                        for(var i=0;i < formObject.elements.length;i++){
                            var elem = $(formObject.elements[i]);
                            if(elem.name.match(/prod_/)){
                                var index = parseInt(elem.name.replace(/prod_/,''))
                                    
                                    if(formObject['qty_'+index]) {
                                        if(formObject['qty_'+index].value){
                                            
                                            if (products[elem.value.split('|')[0]]) {
                                            } else {
                                                products[elem.value.split('|')[0]] = []
                                            }
                                            
                                            products[elem.value.split('|')[0]].push({
                                                    sku: elem.value.split('|')[1],
                                                    qty: formObject['qty_'+index].value
                                                });
                                        }
                                    }
                            }
                        }
                                        
                        //build xml string from products object
						productsLength = 0;
                        var xmlString = ''
                        for (var p in products) {
							productsLength ++;
							if(productsLength ==1) {
								singlePid = p;
								skuNotAdded = ''+p;
							}
                            xmlString += '<product>'
                            xmlString += '<productId>' + p + '</productId>'
                            xmlString += '<skus>'
                            for (var i=0; i < products[p].length; i++){
								skuNotAdded += '_'+products[p][i].sku;
                                xmlString += '<sku>'
                                xmlString += '<skuId>' + products[p][i].sku + '</skuId>'
                                xmlString += '<quantity>' + products[p][i].qty + '</quantity>'
                                xmlString += '</sku>'
                            }
                            xmlString += '</skus>'
                            xmlString += '</product>'
                        }
                        var post = [
                                    '<?xml version="1.0" encoding="UTF-8"?>',
                                    '<addToCartRequest xmlns="http://www.gsicommerce.com/XMLSchema">',
                                    '<requestHeader>',
                                    '<format>XML</format>',
                                    '<storeCode>BBW</storeCode>',
                                    '<locale>en_US</locale>',
                                    '</requestHeader>',
                                    '<products>',
                                    xmlString,
                                    '</products>',
                                    '</addToCartRequest>'
                                    ].join('');
                        
                        var addtocart = new Ajax.Request('/svc/cart',{
                                contentType: 'text/xml',
                                encoding: 'UTF-8',
                                method: 'post',
                                postBody: post,
                                onFailure: function(xhr, e) {
                                    arc.webCallActive = false;
                                    //alert(e)
                                    window.verifyFields('',false)
                                },
                                onException: function(xhr, e) {
                                    arc.webCallActive = false;
                                    //    alert(e)
                                    window.verifyFields('',false)
                                },
                                onSuccess: function(response) {
                                    
                                    
                                    //var xml = $(response.responseXML)
                                    try{
                                        var xml = $(response.responseXML)
                                        var codes = xml.documentElement.getElementsByTagName("code")
                                    }catch(e){
                                        try{
                                            var xml = (new DOMParser()).parseFromString( response.responseXML, "text/xml");
                                            var codes = xml.documentElement.getElementsByTagName("code")
                                        }catch(ee){
                                            
                                        }
                                    }
                                                    
                                    var error = false
                                    loopy:
                                    for(var i=0; i < codes.length; i++) {
                                        if(codes[i].childNodes[0].nodeValue !== "OK") {
                                            error = true            
                                            break loopy
                                        }
                                    }
                                    
                                    if(error){
										if(productsLength == 1) {
											window.location = '/product/index.jsp?productId='+singlePid+'&skusNotAdded='+skuNotAdded;

										}else {
	                                        window.location = '/cart/index.jsp'
										}
                                    } else {
                                        //window.handleCartClick();
                                        window.arcConfirmation()
                                        arc.webCallActive = false;
                                    }
                                }
                            });
                }
            }
        });
    
    
    arc.dispatchEvent({
            type: 'showCheckout',
                topic: 'client',
                className: 'com.allurent.arc.events.ClientEvent',
                data: { context: 'external' }
            });
    
    // now that the client is described we can begin
    arc.initialize();

});// end window observe load


// LISTENERS

/**
 * Listener for analytic events.
 */
arc.addEventListener("analytic", function(event)
                     {
    arc.debug("analytic event");    
    handleAnalyticData($($(event).data));
});
/**
 *  CartStateEvent tells us about cart quantity changes
 */
arc.addEventListener("cartState", function(event)
{
    arc.debug("cartState event");    
    handleOrderItemCount(event.data.cartTotalQuantity);
});


/**
 *  Navigation event with url information
 */
arc.addEventListener("productDetailsRedirect", function(event)
{
    arc.debug("productDetailsRedirect event");    
    document.location.href = $($(event).data).productDetailsUrl;
});

/**
 *  NavigationRequestEvent data object will contain a keyValue  to indicate the 
 *  type of request. Some types may have more information like a PID.
 */
arc.addEventListener("navigationRequest", function(event)
{
    arc.debug(" *** navigationRequest:"+event.data.keyValue);
    var url;
    switch (event.data.keyValue)
    {
            case ("htmlCart"):
                url="/cart/index.jsp";
                break;
            case ("productPage"):
                url="/product/index.jsp?productId="+event.data.PID;
                break;                
            case ("checkout"):
              url="/cart/index.jsp";
                break;         
            case ("appError"):
              url="/";
                break;
            default:
                arc.debug("unhandled navigation request");             
    }
    if (url) 
    {
        window.location.href=url;
    }
});

/**
 * Handle analytics data received from SWF
 */
function handleAnalyticData(data) 
{
    arc.debug(" *** handleAnalyticData:" + $(data).tagType , "green");
    switch ($(data).tagType)
    {
        case "productViewed":
            break;
            
        case "detailsSelected":
                if (typeof (  allurentDetailsSelected ) == "function" )
                allurentDetailsSelected($(data).productId);
            break;
            
        case "linkToProductPage":
                if (typeof (  allurentLinkToProductPage ) == "function" )
                allurentLinkToProductPage($(data).productId);
            break;
            
        case "addToCart":
                if (typeof (  allurentAddToCart ) == "function" )
                allurentAddToCart($(data).productId, $(data).quantity, $(data).unitPrice, $(data).source);
            break;
            
        case "shuffleRack":
                if (typeof (  allurentShuffleRack ) == "function" )
                allurentShuffleRack($(data).productId, $(data).action);
            break;
            
        case "inlineCartAction":
                if (typeof (  allurentInlineCartAction ) == "function" )
                {
                	if (  " close,checkout,maincart ".indexOf($(data).action) == -1 )
                    	allurentInlineCartAction($(data).productId || "" , $(data).action);
                }
                arc.debug("***** :" + $(data).action ,"green");
        	 break;
        case "applicationStateChange":
                arc.debug("***** :" + $(data).state ,"green");
                arc.ClientMgr.handleClientStateChange ( $(data).state );
        	break;                                                
    }
}


Object.extend( arc.ClientMgr , {

	handleClientStateChange:function(state){
		
		arc.debug( " *** arc.ClientMgr.handleClientStateChange" , "brown" ) ;
		arc.ClientMgr._clients.each(
		     function(client){
		     	if ( client.states ) {
		     		
		     		arc.debug(" ClientMgr found '" +client.id + "' that contains states");
		     		$A(client.states).each( function(clientState) {  
		     			if (clientState == state )
		     			{
		     				arc.debug("found matching state:" +state, "white");
		     				client.changeState(state);
		     			}
		     		})
		     	}
                            
		});
		
	}
});

Object.extend ( arc.ClientDesc.prototype ,{
	state:"",
	states:[],
	handleClose:function(){ arc.debug("override handleClose for all clients ") },
  changeState:function(newState)
  {
    arc.debug ( " this state is " + this.state + " new state is XXX" + newState +"XXX" );
    if ( true /*this.state != newState*/) {

      var c = this.swfDiv;  
      
      //var size={height:498,width:598};
      switch ( newState )
      {
        case "parked":
		this.params = detailsSwfOff;
         	$(this.swfDiv).setStyle ( { height:"0px"} );
                $(this.swfDiv).setStyle ( this.params.elementStyle  );
         	//$(this.swfDiv).setStyle ( { width:this.params.elementStyle.width} );
         	$(this.swfDiv).setStyle ( { left:"-10px" } );
         	$(this.swfDiv).setStyle ( {height:"0px"} );
		GSI.lightbox.hide();
         	if ( Prototype.Browser.IE6 )
                    {
                        $("details").width="1";
                    }
                //$(this.swfDiv).hide();
        break;
        default:
		this.params = detailsSwfOn;
         	$(this.swfDiv).setStyle ( { width:this.params.elementStyle.width} );
         	$(this.swfDiv).setStyle ( { left:((document.viewport.getWidth()/2 - this.params.width/2) + 
                                                  document.viewport.getScrollOffsets().left )+"px"
                                           });
         	$(this.swfDiv).setStyle ( {height:this.params.elementStyle.height} );
         	$(this.swfDiv).setStyle ( this.params.elementStyle  );
	        GSI.lightbox.show();
                
                if ( Prototype.Browser.IE6 )
                    {
                        $("details").width="598";
                    }
                // $(this.swfDiv).show();
         break;   

      }
    }
    this.state = newState;
  }
});
    
/**
 * This is a good place to log browser/player and bandwidth information
 */
/*
arc.addEventListener("arcSniffComplete", function(event)
{
    var downLoadRate = arc.util.getCookie(arc.config.cookies['sniffCookie']);
    var flashVersion = deconcept.SWFObjectUtil.getPlayerVersion();
    var flashVersionStr = flashVersion.major + "." + flashVersion.minor + "." + flashVersion.rev;
});
*/



// HELPER FUNCTIONS
// HELPER FUNCTIONS
// HELPER FUNCTIONS
function arc_findBagLink(){
    
    // cache
    if ( arc.temp_clientSourceObject ) 
        return  arc.temp_clientSourceObject;
    // search
    arc.temp_clientSourceObject = [];
    
    if ( $('shopping').firstDescendant() != null )
        arc.temp_clientSourceObject.push($($('shopping').firstDescendant())) ;

    if ($('headerCartLink').firstDescendant() != null )
        arc.temp_clientSourceObject.push($($('headerCartLink').firstDescendant()));
    // return
    return arc.temp_clientSourceObject;
}

/**
 * Handle click on the shopping cart button.
 */
function handleCartClick()
{
    arc.debug(" *** handleCartClick ");
    switch (arc.enabled)
        {
        case true:
            arc.dispatchEvent({
                type:'showCart',
                topic: 'client',
                className: 'com.allurent.arc.events.ClientEvent',
                data: { context: 'external' }
            });
            break;
        default:
            // arc.enabled not yet set. Do nothing.
            // the default link behavior may link to cart.jhtml
        }
}


/**
 * Handle the CartStateEvent
 */
function handleOrderItemCount(count) 
{
    $('cartItemCount').innerHTML = count;
}




/**
 * Handle click on the checkout button.
 */
function arc_openCheckout()
{
    // called from with inline cart
    if ( activeArcClients["checkout"] ) {
        window.location.href = ARC_CHECKOUT_URL;
    } else {
        window.location.href = ARC_CHECKOUT_URL_HTML;
    }
}


function arcProdDetails (pid) {
   arc.ClientMgr.getClientDesc('details').params = detailsSwfOn;
    var editNewOrderItemEvent = {
        type: "editNewOrderItem",
        topic: "order",
        className: "com.allurent.arc.events.OrderEvent",
        data: { productUri: "gsi://catalog/product/" + pid, context: "external"}
    };
    arc.dispatchEvent(editNewOrderItemEvent);
    // record event 
    handleAnalyticData({tagType:"detailsSelected",productId:pid});
}

function arcConfirmation() {
		arc.ClientMgr.getClientDesc('details').params = detailsSwfOn;
    var orderItemAddedConfirmationEvent = {
        type: "editNewOrderItemAdded",
        topic: "order",
        className: "com.allurent.arcx.app.event.OrderItemAddedEvent",
        data: {context: "external"}
    };
    arc.dispatchEvent(orderItemAddedConfirmationEvent);
} 

 
function arcInitSwf() {
    var preintitializeEvent = {
        type: "parked",
        topic: "client",
        className: "com.allurent.arcx.app.event.SimpleLaunchEvent",
        data: {context: "external"}
    };
    arc.dispatchEvent(preintitializeEvent);
 } 
 
