/*
dialog for displaying product image and description and field for editing quantity in cart.

to use, include this file and provide class and id attributes for any element for which a
mouseover should cause the dialog to appear, i.e.:

  <link rel="stylesheet" href="/jsp/catalog/templates/ProductDialog.css" />         
  <script type='text/javascript' src='/jsp/catalog/templates/ProductDialog.js'></script>
  ...
  <a href='...' class='itemPopUp' id='D2-FILL'>D2-FILL</a>

ids should be valid part numbers.

requires the following in the client page (is included by the template in most cases):
  <script src="/js/scriptaculous/lib/prototype.js" type="text/javascript"></script>
  <script src="/js/scriptaculous/src/scriptaculous.js" type="text/javascript"></script>    
*/
var ProductDialog = {
    showDialogTimer: null,
    hideDialogTimer: null,
    hlElement: null,
    itemToLoad: null,
    
    pageIndex: null,
    displayMode: null,
    
    mouseObserveEvent: null,
    mouseX: null,
    mouseY: null,

	/*
	observer started when dialog displayed to monitor cusror position
	for tracking / blocking hiding of dialog.
	*/
    mouseObserver: function(event)
        {
        mouseX = Event.pointerX(event);
        mouseY = Event.pointerY(event);
        },
        
	/*
	clear timer if mouse moved off of a hot link
	*/
	cancelShow: function()
	    {
        if ( ProductDialog.showDialogTimer )
            {
            window.clearTimeout ( ProductDialog.showDialogTimer );
            }        
	    },
          
	/*
	set timer for display of dialog when a hot link is moved over.
	*/
	show: function ( event, el, link, delay, index, mode )
	    {            
        Event.observe ( document, 'mousemove', ProductDialog.mouseObserver );        
        if ( ProductDialog.showDialogTimer )
            {
            window.clearTimeout ( ProductDialog.showDialogTimer );
            }
	    hlElement = el;
	    itemToLoad = link;
        pageIndex = index;
        displayMode = mode;
	    ProductDialog.showDialogTimer = window.setTimeout ( "ProductDialog.requestProductInfo()", delay );
	    },
    
	/*
	send request for product data.
	*/            
	requestProductInfo: function()
	    {
	    var myAjax = new Ajax.Request(
	        "/ajax?",
	        {
	        method: 'get',
	        parameters: { fctype:'adc.falcon.FormControllers.ProductDisplayFormCtrl', 
	                      cmd:'getProductInfo', 
	                      itemCode:itemToLoad },
	        onFailure: ProductDialog.showError,
	        onComplete: ProductDialog.showDialog
	        });                
	    },
	    
	/*
	display msg if error occurs loading product data.
	*/
	showError: function ()
	    {
	    Element.update ( $('productInfoDialogTitleBar'), 'Error loading product info...' );
	    },
	
	/*
	process response from item data request.
	*/
	showDialog: function ( data )
	    {
        //console.log ( 'got some data....' );
	    var item = data.responseText.evalJSON();
	    //if ( $('productInfoDialog') == null )
	    //    {
        //   //console.log ( 'building dialog...' );
	    //    ProductDialog.build();
	    //    }
        //console.log ( 'loading...' );
	    ProductDialog.load ( item );
        //console.log ( 'positioning...' );
	    ProductDialog.position();
        //console.log ( 'showing....' );
        $('productInfoDialog').setStyle ( { display:'block' } );
        ProductDialog.startHideTimer();
	    },
	    
    /*
    when displayed, start timer, check every 5 seconds, if cursor
    over dialog reset timer otherwise hide the window...    
    */
    startHideTimer: function()
        {
        if ( ProductDialog.hideDialogTimer )
            {
            window.clearTimeout ( ProductDialog.hideDialogTimer );
            }
        window.setTimeout ( "ProductDialog.hideIfInactive()", 5000 );
        },

	/*
	hide the product information dialog if it is inactive.  it is considered
    inactive if the cursor isn't over the dialog or the hot link.
	*/
	hideIfInactive: function()
	    {
        if ( ProductDialog.hideDialogTimer )
            {
            window.clearTimeout ( ProductDialog.hideDialogTimer );
            }
        if ( $('productInfoDialog').style.display == 'block' )
	        {
            var mouseOverHotLink = ProductDialog.mouseOverElement($('productInfoDialog'));
            var mouseOverDialog = ProductDialog.mouseOverElement($(hlElement));
            if ( !(mouseOverHotLink || mouseOverDialog) )
                {
                ProductDialog.hideDialog();
                }
            else
                {
                hideDialogTimer = window.setTimeout ( "ProductDialog.hideIfInactive()", 5000 );
                }
            }
	    },

    /*
    see if cursor is over the element specified.<b> 
    */
    mouseOverElement: function ( el )
        {
        var elementLeft = $(el).cumulativeOffset().left;
        var elementTop = $(el).cumulativeOffset().top;
        var elementRight = elementLeft + $(el).getDimensions().width;
        var elementBottom = elementTop + $(el).getDimensions().height;
        var xInElement = mouseX >= elementLeft && mouseX <= elementRight;
        var yInElement = mouseY >= elementTop && mouseY <= elementBottom;
        return xInElement && yInElement;
        },
     
    /*
    hide the product information dialog.
    */   
    hideDialog: function()
        {
        if ( $('productInfoDialog') != null )
            {
            $('productInfoDialog').setStyle ( { display:'none' } );
            }
        Event.stopObserving ( document, 'mousemove', ProductDialog.mouseObserver );
        },
        
	/*
	load data into the dialog
	*/
	load: function ( item )
	    {
        // TODO: cache product data....
        //console.log ( 'item_cd' );
	    $('item_cd').update ( item.item_cd );
        //console.log ( 'list_price' );
	    $('list_price').update ( item.list_price );
        //console.log ( 'tree_path' );
	    $('tree_path').href = '/adc/Shopping'+item.tree_path
                              + '?iCatalogPage='+pageIndex
                              + '&displayMode='+displayMode;
        
        //console.log ( 'image_file_name' );
	    $('image_file_name').src = item.image_file_name;
        //console.log ( 'long_desc' );
	    $('long_desc').update ( item.long_desc.length > 256 ? item.long_desc.substring(0,256)+"..." : 
	                                                          item.long_desc );
        //$('documentationURL').update ( "" );
	    //if ( item.documentationURL != "" )
	    //    {
        //    console.log ( 'documentationURL' );
	    //    $('documentationURL').update ( "<a href='"+item.documentationURL+"'>Online Manual</a>" );
	    //    }
        //console.log ( 'quantity' );
        $('cartEditDiv').setStyle ( { display:('true'==item.orderable_flg?'block':'none') } );
	    $('quantity').value = item.quantity=="" ? "0" : item.quantity;
	    },
	
	/*
	position the dialog and make it visible.
	*/            
    position: function ()    
	    {
        var gap = 5;
        //console.log ( 'positioning...' );
	    $('productInfoDialog').setStyle ( {display:'none'} );
	    var cOffset = Element.cumulativeOffset($(hlElement));
	    var leftPxPos = cOffset.left + Element.getWidth($(hlElement)) + gap;
	    var topPxPos = cOffset.top + 15 + gap;
	    // work on positioning --> below/above, right/left.....
        var bottomOfViewport = document.viewport.getScrollOffsets().top + document.viewport.getHeight()
	    if ( topPxPos+215 > bottomOfViewport )
	        {
            if ( topPxPos-230 > 0 )
                {
                topPxPos -= 230;
                }
            // TODO: go above hot link unless not enough room (default is below)
	        // topPxPos--;
	        }
        var rightOfViewport = document.viewport.getScrollOffsets().left + document.viewport.getWidth();
        while ( leftPxPos+410 > rightOfViewport )
            {
            // TODO: go left of hot link unless not enough room (default is below)
            leftPxPos--;
            }
	    // if off right side, go left of hot link unless not enough room...
	    $('productInfoDialog').setStyle ( { left:leftPxPos+'px', top:topPxPos+'px' } );
        //console.log ( 'done positioning...' );
	    },
	  
	/*
	create html for the dialog.
	*/
	/*
	build: function()
	    {
	    var prodDialog = new Element ( 'div', { id:'productInfoDialog',
	                                            style:'z-index:100;height:220px;width:400px;display:none;position:absolute'
                                              } ); 
	    prodDialog.update ( 
                          "<div><b class='rcBlack'><b class='rcBlack1'><b></b></b><b class='rcBlack2'><b></b></b><b class='rcBlack3'></b><b class='rcBlack4'></b><b class='rcBlack5'></b></b>" +
                          "<div style='padding-left:2px;padding-right:2px' class='rcBlackfg'>" +
                          
	                      "<table width='100%' cellpadding='0' cellspacing='0'>" +
                          "  <tr>" +
                          "      <td valign='top' align='left' style='font-size:10pt;font-weight:bold;padding:2px;color:white;background:#00AADD'>" +
                          "        <span id='item_cd'></span>" +
                          "        &nbsp;&nbsp;-&nbsp;&nbsp;" +
                          "        $<span id='list_price'></span>" +
                          "      </td>" +
                          "      <td align='right' style='padding:2px;color:white;background:#00AADD'>" +
                          "        <img src='/images/icons/smallClose.gif' width='16' height='16' onclick='javascript:ProductDialog.hideDialog()'/>" +
                          "      </td>" +
                          "  </tr>" +
                          "</table>" +
                          "<div style='background-color:#FFFFFF'>" +
                          "<table width='100%' cellspacing='8'>" +
	                      "  <tr> " + 
	                      "    <td width='10%' valign='top' rowspan='3' nowrap> " + 
	                      "        <img id='image_file_name'/> " + 
	                      "    </td> " +
	                      "    <td width='90%' valign='top'> " + 
	                      "        <div id='long_desc'></div> " +                            
                          "    </td>" +
                          "  </tr>" +
                          "  <tr>" +
                          "    <td align='center'> " + 
                          "        <div id='cartEditDiv'> " +
	                      "        Cart Qty: <input id='quantity' size='5' " +
                          "                         onkeydown=\"javascript:style.backgroundColor='aqua'\"></input> " + 
	                      "        <input type='button' value='Update' onclick='ProductDialog.addToCart()'></input> " + 
                          "        </div> " +
	                      "    </td> " + 
	                      "  </tr> " +
                          "  <tr>" +
                          "    <td valign='bottom'>" +
                          "        <hr>For stock status, special notes and other information please " + 
                          "        see this product's <a id='tree_path' href='#'>detailed information page.</a> " + 
                          "    </td>" +
                          "  </tr>" +
	                      "</table>" +
                          
                          "</div>" +
                          "</div>" +
                          "<b class='rcBlack'><b class='rcBBlack5'></b><b class='rcBBlack4'></b><b class='rcBBlack3'></b><b class='rcBlack2'><b></b></b><b class='rcBlack1'><b></b></b></b></div>"
                          );
        $(document.body).insert ( prodDialog );
	    },
	*/
	    
    /*
    Submit command to add an item to the shopping cart.
    */
    addToCart: function ()
        {
	    var cartURLBase = 'https://'+window.location.hostname+'/adc/Cart/Cart?';
	    var cartPageURL = 
	            cartURLBase +
	            "fctype=adc.falcon.FormControllers.CartFormCtrl" +
	            "&cmd=UpdateCartQuantities" +
                "&success_url="+escape(window.location.href) +
	            "&TxnNumber=-1" +
	            "&partno_0=" + $('item_cd').innerHTML +
	            "&qty_0=" + $('quantity').value +
                "&cartCount=1" +
                "&iCat=true";
        document.location.href = cartPageURL;
        }
    
    };


/*
manager for attaching event listeners.

init function is used for setting values used in iCatalog to specify
     page and display mode for building return to iCatalog links... 
*/
var Displayer = {
    index: 0,
    mode: 0,
    init: function(i,m) {
        Displayer.index = i;
        Displayer.mode = m;
        },
    display: function(e,el) {
        ProductDialog.show ( e, el, el.id, 300, Displayer.index, Displayer.mode );
        },
    hide: function(e,el) {
        ProductDialog.cancelShow();
        },
    attachItemPopUps: function() {
        var items = $$('.itemPopUp').each ( 
	        function(el) 
	            {
	            // attach pop up to item links only (not category links).
		        if ( /iCatalog\(\'item\',/.test(el.href) )
		            {
		            $(el).setStyle ( {cursor:"pointer"} );
		            $(el).observe ( 'mouseover', Displayer.display.bindAsEventListener(Displayer,el) );
		            $(el).observe ( 'mouseout', Displayer.hide.bindAsEventListener(Displayer,el) );
		            $(el).observe ( 'click', Displayer.hide.bindAsEventListener(Displayer,el) );
		            }
	            } ); 
        }
    }

/*
attach pop ups after document is loaded.
*/
document.observe ( 'dom:loaded', Displayer.attachItemPopUps );

    
    