/*
dialog for displaying product image and description and field for editing quantity in cart.

to use, access through the jspc:component defined in ProductDialog.jspf

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 ) {
	    var item = data.responseText.evalJSON();
	    ProductDialog.load ( item );
	    ProductDialog.position();
        $('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 ) {
	    $('item_cd').update ( item.item_cd );
	    $('list_price').update ( item.list_price );
	    $('tree_path').href = '/adc/Shopping'+item.tree_path;
        
	    $('image_file_name').src = item.image_file_name;
	    $('long_desc').update ( item.long_desc.length > 256 ? item.long_desc.substring(0,256)+"..." : 
	                                                          item.long_desc );
        $('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;
	    $('productInfoDialog').setStyle ( {display:'none'} );
	    var cOffset = Element.cumulativeOffset($(hlElement));
	    var leftPxPos, topPxPos;    
	    if ( "area" == $(hlElement).tagName.toLowerCase() ) {
  	        //area->map->image coords are needed...
  	        //var imgSelector = 'img:[usemap="#' + $(hlElement).up().id + '"]';
  	        //alert ( imgSelector );
  	        //var anchorImg =  $$(imgSelector);
  	        //alert ( anchorImg );
  	        //alert ( anchorImg.up() );
  	        //anchorImg.up().makePositioned();
            //var imgOffset = Element.cumulativeOffset(anchorImg);
            //alert ( imgOffset );
            //leftPxPos = cOffset.left + imgOffset.left + gap;
            //topPxPos = cOffset.top + imgOffset.top + gap;
            var coords = $(hlElement).coords.split(",");
            leftPxPos = cOffset.left + parseInt(coords[2]) + gap;
            topPxPos = cOffset.top + parseInt(coords[1]) + gap;
	    }
	    else {
            leftPxPos = cOffset.left + Element.getWidth($(hlElement)) + gap;
            topPxPos = cOffset.top + 15 + gap;
        }
        var bottomOfViewport = document.viewport.getScrollOffsets().top + document.viewport.getHeight()
        var dlgHeight = $('productInfoDialog').getHeight();
	    if ( topPxPos+dlgHeight > bottomOfViewport ) {
            if ( topPxPos-dlgHeight > 0 ) {
                topPxPos -= dlgHeight;
            }
	    }
        var rightOfViewport = document.viewport.getScrollOffsets().left + document.viewport.getWidth();
        var dlgWidth = $('productInfoDialog').getWidth();
        while ( leftPxPos > 0 && leftPxPos+dlgWidth > rightOfViewport ) {
            leftPxPos--;
        }
	    $('productInfoDialog').setStyle ( { left:leftPxPos+'px', top:topPxPos+'px' } );
	},
	  
    /*
    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();
    },
    
    // TODO: - modify this method to take a list (need to retrieve list based on different
    //         criteria here from iCatalog)...
    //       - resolve any other differences between this and the iCatalog version
    //         and combine code...
    attachItemPopUps: function() {
        // TODO: attach to other elements?...
        //$$('.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) );
		//        }
	    //    } ); 
        $$('a:[href^=\/pn\/]').each ( 
            function(el) {
                // attach pop up to item links only (not category links).
                $(el).setStyle ( {cursor:"pointer"} );
                $(el).id = el.href.substr(el.href.lastIndexOf("/")+1);
                //$(el).class = 'map itemPopUp';
                $(el).addClassName = ( 'map' );
                $(el).addClassName = ( 'itemPopUp' );
                $(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 );

    
    
