/*
dialog for displaying a form for entering BOM name and BOM note.

requires the following in the client page:
 <script src="/js/scriptaculous/lib/prototype.js" type="text/javascript"></script>         
*/
var AddItemToBOMDialog = {
    imgElement: null,
    hlElement: null,
    itemCode: null,
    productId: null,
    showDialogTimer: null,
    hideDialogTimer: null,
    mouseX: null,
    mouseY: null,
    isFavItem: null,
    tipMessage: null,
    newBundleOption: null,
    duration: 1.0,
    
	/*
	observer started when dialog displayed to monitor cusror position
	for tracking / blocking hiding of dialog.
	*/
    mouseObserver: function(event)
        {
        var element = Event.element(event); 
        //The option element does not have the desired mouseX and mouseY
        if(Element.descendantOf(element, $("bap.BOMList")))
        	{
        	return;
        	}
        this.mouseX = Event.pointerX(event);
        this.mouseY = Event.pointerY(event);
        //console.log ( 'mouseX=' + this.mouseX);
        //console.log ( 'mouseY=' + this.mouseY);
        },
     
     /*
	initialize the interface for the bundle creation dialog.
	*/            
	initialize: function()
		{
		$("bap.promptOption").selected = true;
        $('bap.addItemToBOMButton').disable();
	    $("bap.productQty").disable();
	    $("bap.productQty").value = "1";
	    $("bap.bundlenamediv").hide();
	    
		$('bap.addItemToBOMButton').setStyle ( { display:'inline' } );
 	    $('bap.cancelBOMButton').setStyle ( { display:'inline' } );
 	    $('bap.okBOMButton').setStyle ( { display:'none' } );
 	    $('bap.BOMMessage').innerHTML = "";
 	    $('bap.BOMMessage').setStyle ( { display:'none' } );
 	    $('bap.FavMessage').innerHTML = "  ";
 	    //$('bap.FavMessage').setStyle ( { display:'none' } );
 	    $('bap.bundleName').value="";
 	    $('bap.bundleNote').value="";
 	    $('bap.bundleNameInUse').innerHTML = "";
 	    $('bap.bundleNameInUse').setStyle ( { display:'none' } );
 	    $('bap.dialogTitle').innerHTML = this.itemCode;
 	    $('bap.addToBOMCkeckBox').checked = false;
 	    
 	    if(this.isFavItem)
	    	{
	    	$('bap.BOMList').disable();
	    	if('true' == this.isFavItem)
	    		{
	    		$('bap.addToFavorite').checked = true;
	    		}
	    	else
	    		{
	    		if($('bap.addToFavorite').checked == true)
		    		{
		    		$('bap.addToFavorite').checked = false; 
		    		}
	    		}
	    	$('bap.favTable').setStyle ( { display:'block' } );
	    	$('bap.contentTitle').setStyle ( { display:'none' } );
	    	}
	    else
	    	{
	    	$('bap.favTable').setStyle ( { display:'none' } );
	    	$('bap.contentTitle').setStyle ( { display:'block' } );
	    	//$('bap.BOMList').enable();
	    	}
		},
		 
    /*
	set timer for display of dialog when a hot link is moved over.
	*/
	showNow: function ( event, hlEl, imgEl, item, productId, isFavItem, tipId)
	    {            
	    //debugger;
	    //Event.observe ( document, 'mousemove', this.mouseObserver.bindAsEventListener(this) );        
        //if ( this.showDialogTimer )
        //    {
        //    window.clearTimeout ( this.showDialogTimer );
        //    }
	    this.hideDialog();
	    this.imgElement = $(imgEl);  //if don't use this keyword, imgElement will refer to a global variable, not the one defined in top.
	    this.hlElement = $(hlEl);
	    this.itemCode = item;
	    this.productId = productId;
	    this.isFavItem = isFavItem;	 
	    if(tipId)
	    	{
	    	this.tipMessage = $(tipId);   	
	    	}
        this.initialize();
	    this.showDialog();
	    this.populateBOMList();
	    //if(!this.isFavItem)
		//    {
	    //	$('bap.BOMList').enable();	
		//    }
	    },
	                 
	/*
	set timer for display of dialog when a hot link is moved over.
	*/
	show: function ( event, el, item)
	    {            
	    Event.observe ( document, 'mousemove', this.mouseObserver.bindAsEventListener(this) );        
        if ( this.showDialogTimer )
            {
            window.clearTimeout ( this.showDialogTimer );
            }
	    this.imgElement = $(el);
	    this.itemCode = item;
        this.initialize();
	    this.showDialogTimer = window.setTimeout ( "AddItemToBOMDialog.showDialog()", 500 );
	    },
    
    /*
	clear timer if mouse moved off of a hot link
	*/
	cancelShow: function()
	    {
        if ( this.showDialogTimer )
            {
            window.clearTimeout ( this.showDialogTimer );
            }        
	    },
          
    /*
    Removed the "bundle in use" message 
	*/
	hideNameUsedMessage: function()
		{
		if($('bap.bundleNameInUse').innerHTML.length > 0)
			{
			$('bap.bundleNameInUse').innerHTML = "";
	 	    $('bap.bundleNameInUse').setStyle ( { display:'none' } );
	 	    $('bap.addItemToBOMButton').enable();
	 	    }
		},
    /*
	check if the user-entered bundle name is in use.
	*/            
	checkBundleName: function()
	    {
	    if($("bap.BOMList").value == '-10' && $('bap.bundleName').value.length > 0)
	    	{
		    var myAjax = new Ajax.Request(
		        "/ajax?",
		        {
		        method: 'get',
		        asynchronous: false,
		        parameters: { fctype:'adc.falcon.FormControllers.FavoritesFormControl', 
		                      cmd:'CheckBundleName', 
		                      bundleName:$('bap.bundleName').value },
		        onFailure: AddItemToBOMDialog.showError,
		        onSuccess: function(response) 
				 	{
				 		if(response.responseText.length > 0)
				 		{
				 		$('bap.bundleNameInUse').innerHTML = "BOM name already in use.";
				 		$('bap.bundleNameInUse').setStyle ( { display:'block', color:'red' } );
				 		$('bap.addItemToBOMButton').disable();
				 		}
				 		else
				 		{
				 		$('bap.bundleNameInUse').innerHTML = "";
				 		$('bap.bundleNameInUse').setStyle ( { display:'none' } );
				 		$('bap.addItemToBOMButton').enable();
				 		}
				 	}.bind(this)
		        }); 	 
		    }               
	    },
	    
	/*
	display msg if error occurs loading product data.
	*/
	showError: function ()
	    {
	    $('bap.BOMMessage').innerHTML = "Error in adding product to BOM.";
	    $('bap.BOMMessage').setStyle ( { display:'block', color:'red' } );
	    this.enableDialog();
	    },
	
	/*
	process response from item data request.
	*/
	showDialog: function ( data )
	    {
        //console.log ( 'positioning...' );
	    this.position();
        //console.log ( 'showing....' );
        $('bap.AddItemToBOM').setStyle ( { display:'block' } );
        //this.startHideTimer();
	    },
	  
	/*
    when displayed, start timer, check every 5 seconds, if cursor
    over dialog reset timer otherwise hide the window...    
    */
    startHideTimer: function()
        {
        if ( this.hideDialogTimer )
            {
            window.clearTimeout ( this.hideDialogTimer );
            }
        window.setTimeout ( "AddItemToBOMDialog.hideIfInactive()", 4000 );
        },

	/*
	hide the dialog if it is inactive.  it is considered
    inactive if the cursor isn't over the dialog or the hot link.
	*/
	hideIfInactive: function()
	    {
        if ( this.hideDialogTimer )
            {
            window.clearTimeout ( this.hideDialogTimer );
            }
        if ( $('bap.AddItemToBOM').style.display == 'block' )
	        {
            var mouseOverDialog = this.mouseOverElement($('bap.AddItemToBOM'));
            var mouseOverHotLink = this.mouseOverElement(this.imgElement);
            if ( !(mouseOverHotLink || mouseOverDialog ) )
                {
                this.hideDialog();
                }
            else
                {
                hideDialogTimer = window.setTimeout ( "AddItemToBOMDialog.hideIfInactive()", 4000 );
                }
            }
	    },

    /*
    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 = this.mouseX >= elementLeft && this.mouseX <= elementRight;
        var yInElement = this.mouseY >= elementTop && this.mouseY <= elementBottom;
        return xInElement && yInElement;
        },
     
    /*
    hide the dialog.
    */   
    hideDialog: function()
        {
        if ( $('bap.AddItemToBOM') != null )
            {
            $('bap.AddItemToBOM').setStyle ( { display:'none' } );
            }
        Event.stopObserving ( document, 'mousemove', this.mouseObserver );
        },    
        
    /*
    handle the event that the selected item changed.
    */   
    selectChanged: function()
        {
        if ( $("bap.BOMList").value == '-1' || $("bap.BOMList").value == 'incart' || $("bap.BOMList").value == 'shared')
            {
            $("bap.productQty").disable();
            $('bap.addItemToBOMButton').disable();
            $("bap.bundlenamediv").hide();
            if($("bap.BOMList").value == 'incart' || $("bap.BOMList").value == 'shared')
            	{
            	if($("bap.BOMList").value == 'incart')
            		{
            		$('bap.BOMMessage').innerHTML = "BOM in cart or quote, can not be modified. You can make a copy that can be modified.";
            		}
            	else
            		{
            		$('bap.BOMMessage').innerHTML = "BOM belongs to another user, can not be modified. You can make a copy that can be modified.";
            		}	
		 	    $('bap.BOMMessage').setStyle ( { display:'block' } );
		 	    new Effect.Highlight('bap.BOMMessage', {duration: this.duration});
            	}
            else
            	{
            	$('bap.BOMMessage').innerHTML = "";
            	$('bap.BOMMessage').setStyle ( { display:'none' } );
            	}
            }
            
        else if ( $("bap.BOMList").value == '-10' )
        	{
        	$("bap.productQty").enable();
            $('bap.addItemToBOMButton').enable();
            $("bap.bundlenamediv").show();
            $('bap.BOMMessage').innerHTML = "";
            $('bap.BOMMessage').setStyle ( { display:'none' } );
        	}
        else
	        {
	        $("bap.productQty").enable();
            $('bap.addItemToBOMButton').enable();
            $("bap.bundlenamediv").hide();
            $('bap.BOMMessage').innerHTML = "";
            $('bap.BOMMessage').setStyle ( { display:'none' } );
	        }
        },
        
    /*
    handle the event that the "Add to a BOM" checkbox checked/unchecked.
    */   
    addToBOMOptionChanged: function()
        {
        if($('bap.addToBOMCkeckBox').checked)
        	{
        	$('bap.BOMList').enable();
        	//this.populateBOMList();
        	this.selectChanged()
        	}
        else
        	{
        	$('bap.BOMList').disable();
        	$("bap.productQty").disable();
            $('bap.addItemToBOMButton').disable();
        	}
        },
        
    /*
     * validate the product quantity field 
     */
    productQuantityChanged: function(quantity)
	    {
	    if(!this.isValidQuantity(quantity))
	     	{
	     	$('bap.BOMMessage').innerHTML = 'Invalid quantity';
	     	$('bap.BOMMessage').setStyle ( { display:'block', color:'red' } );
	     	}
	     else
		     {
		     $('bap.BOMMessage').innerHTML = '';
	     	$('bap.BOMMessage').setStyle ( { display:'none' } );
		     }
	    },
        
    /*
     * Populate the BOM selection options 
     */
    populateBOMList: function(async)
    {
    	if($("bap.BOMList").length > 1)
    	 	{
    		return
    	 	}
    	if(!async)
    	{
    		async = true;
    	}
    	this.disableDialog();
	    var myAjax = new Ajax.Request(
	        "/ajax?",
	        {
	        method: 'get',
	        asynchronous: async,
	        parameters: { fctype:'adc.falcon.FormControllers.FavoritesFormControl', 
	                      cmd:'GetEditableBundleListAsJSON'
	                      },
	        onFailure: function(response)
	        	{
	        	$('bap.FavMessage').innerHTML = "Error in populating BOM list.";
	    		$('bap.FavMessage').setStyle ( { display:'block', color:'red' } );
	    		this.enableDialog();
	        	}.bind(this),
	        onSuccess: function(response) 
			 	{
	        	if($("bap.BOMList").length > 1)
	        	 	{
	        		return
	        	 	}
        		var bundleList = response.responseText.evalJSON();
        		bundleList.push({bundleName: "New BOM", bundleId: "-10"});
        		for ( var i=0; i < bundleList.length; i++ )
        			{
	        		if(Prototype.Browser.IE) 
				 	    {
				 	    var optionElem=document.createElement("option");
						optionElem.setAttribute("value", bundleList[i].bundleId);
						optionElem.setAttribute("label", bundleList[i].bundleName);
						if(bundleList[i].bundleId == "shared" || bundleList[i].bundleId == "incart")
							{
								$(optionElem).setStyle({color: 'gray'});
							}
						if(bundleList[i].bundleId == "-10")
							{
							this.newBundleOption = optionElem;	
							}
				 	    $("bap.BOMList").add(optionElem);
					 	}
				 	else
					 	{
				 		var opt = new Option(bundleList[i].bundleName, bundleList[i].bundleId);
				 		if(bundleList[i].bundleId == "shared" || bundleList[i].bundleId == "incart")
				 			{
							$(opt).setStyle({color: 'gray'});
				 			}
				 		if(bundleList[i].bundleId == "-10")
							{
							this.newBundleOption = opt;	
							}
		        		$("bap.BOMList").add(opt, null);	
				 	    }

        			}
		 		this.enableDialog();
			 	}.bind(this)
	        }); 	 	
    	},
	    
    /*
     * add or remove the product to or from the favorite list 
     */
    addRemoveFav: function()
	    {
	    this.disableDialog();
	    var myAjax = new Ajax.Request(
	        "/ajax?",
	        {
	        method: 'get',
	        asynchronous: false,
	        parameters: { fctype:'adc.falcon.FormControllers.FavoritesFormControl', 
	                      cmd:'AddRemoveFav', 
	                      itemCode: this.itemCode,
	                      productId: this.productId,
	                      isAdd: $F('bap.addToFavorite')
	                      },
	        onFailure: function(response)
	        	{
	        	$('bap.FavMessage').innerHTML = "Error in adding/removing product to/from favorites.";
	    		$('bap.FavMessage').setStyle ( { display:'block', color:'red' } );
	    		this.enableDialog();
	        	}.bind(this),
	        onSuccess: function(response) 
			 	{
			 	if($F('bap.addToFavorite'))
				 	{
				 	//debugger;
				 	this.imgElement.setAttribute('src', '/images/icons/page_favorite.gif');
				 	this.hlElement.stopObserving('click');
				 	this.hlElement.observe('click', 
				 		this.showNow.bindAsEventListener(this, this.hlElement, this.imgElement, this.itemCode, this.productId, 'true', this.tipMessage));
				 	if(this.tipMessage)
				 		{
				 		this.tipMessage.stopObserving('mouseover');
				 		this.tipMessage.observe('mouseover', this.favoriteAdded);
				 		}
				 	}
				else
				 	{
				 	//debugger;
				 	this.imgElement.setAttribute('src', '/images/icons/page_edit.gif');
				 	this.hlElement.stopObserving('click');
				 	this.hlElement.observe('click', 
				 		this.showNow.bindAsEventListener(this, this.hlElement, this.imgElement, this.itemCode, this.productId, 'false', this.tipMessage));
				 	if(this.tipMessage)
				 		{
				 		this.tipMessage.stopObserving('mouseover');
				 		this.tipMessage.observe('mouseover', this.favoriteRemoved);
				 		}
				 	}
				 	
		 		$('bap.FavMessage').innerHTML = response.responseText;
		 		$('bap.FavMessage').setStyle ( { display:'block' } );
		 		new Effect.Highlight('bap.FavMessage', {duration: this.duration});
		 		this.enableDialog();
			 	}.bind(this)
	        }); 	 
	    },
	    
	/*
	 * Handler for tip message change when a product is added to favorite list.
	 */
	 favoriteAdded : function(e)
		 {
		 stm(Text[0]=['Fav/BOM','Product is in favorites. Click to remove it from favorites, or add it to a BOM'],getTMTStyle('align_right'))
		 },
		 
	/*
	 * Handler for tip message change when a product is removed to favorite list.
	 */
	 favoriteRemoved : function(e)
		 {
		 stm(Text[0]=['Fav/BOM','Product not in favorites. Click to add it to favorites, or add it to a BOM'],getTMTStyle('align_right'));
		 },
	    
    /*
	 *  Check to see if quantity is a valid numeric value.
	 */
    isNum: function ( quantity )
        {
        if ( quantity.length == 0 )
            {
            return false;
            }
        for ( var i = 0; i < quantity.length; i++ )
            {
            var c = quantity.charAt(i);
            if ( !((c >= '0') && (c <= '9')))
                {
                return false;
                }
            }
        return true;
        },
		    
    /*
     *  Routine to validate a item quantity.
     */
    isValidQuantity: function ( quantity )
        {
        var isValid = this.isNum(quantity) &&
                      quantity >= 1 &&
                      quantity <= 9999;
        return isValid;
        },
       	
	/*
	position the dialog and make it visible.
	*/            
    position: function ()    
	    {
        var gap = 5;
        //console.log ( 'positioning...' );
	    $('bap.AddItemToBOM').setStyle ( {display:'none'} );
	    var cOffset = Element.cumulativeOffset(this.imgElement);
	    var leftPxPos = cOffset.left;
	    var topPxPos = cOffset.top + Element.getHeight(this.imgElement) +20;
	    //console.log ( 'leftPxPos....' + leftPxPos + '  topPxPos...' + topPxPos );
	    // work on positioning --> below/above, right/left.....
        var bottomOfViewport = document.viewport.getScrollOffsets().top + document.viewport.getHeight()
	    while ( topPxPos+320 > bottomOfViewport )
	        {
            // TODO: go above hot link unless not enough room (default is below)
	         topPxPos--;
	        }
        var rightOfViewport = document.viewport.getScrollOffsets().left + document.viewport.getWidth();
        //console.log ( 'bottomOfViewport....' + bottomOfViewport + '  rightOfViewport...' + rightOfViewport );
        while ( leftPxPos+360 > 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...
	    //console.log ( 'leftPxPos....' + leftPxPos + '  topPxPos...' + topPxPos );
	    $('bap.AddItemToBOM').setStyle ( { left:leftPxPos+'px', top:topPxPos+'px' } );
        //console.log ( 'done positioning...' );
	    },
	  	    
    /*
    Submit command to create a BOM, and add the product to the created BOM.
    */
    addItemToBOM: function ()
        {
        if($('bap.bundleNameInUse').innerHTML.length > 0)
	        {
	        	return false;
	        }
	     if(!this.isValidQuantity($("bap.productQty").value))
	     	{
	     	$('bap.BOMMessage').innerHTML = 'Invalid quantity';
	     	$('bap.BOMMessage').setStyle ( { display:'block', color:'red' } );
	     	return false;
	     	}
	     this.disableDialog();
	     //debugger;
	     //prompt($("bap.BOMList").options[$("bap.BOMList").selectedIndex].label);
	     var selectedBundleName = $("bap.BOMList").options[$("bap.BOMList").selectedIndex].text;
	     if(selectedBundleName == "")
	     	{
	     	selectedBundleName = $("bap.BOMList").options[$("bap.BOMList").selectedIndex].label;
	     	}
	     
	     var myAjax = new Ajax.Request(
	        "/ajax?",
	        {
	        method: 'get',
	        parameters: { fctype:'adc.falcon.FormControllers.FavoritesFormControl', 
	                      cmd: 'AddItemToBundle', 
	                      bundleName: $("bap.BOMList").value == '-10' ? $F('bap.bundleName') : selectedBundleName, 
	                      bundleNote: $('bap.bundleNote').value,
	                      itemCode: this.itemCode,
	                      productId: this.productId,
	                      quantity: $("bap.productQty").value,
	                      bundleId: $("bap.BOMList").value
	                      },
	        onFailure: AddItemToBOMDialog.showError,
	        onSuccess: function(response) 
			 	{
			 		//console.log (response.responseText);
			 		var bundleInfo = response.responseText.evalJSON();
			 	    $('bap.addItemToBOMButton').setStyle ( { display:'none' } );
			 	    $('bap.cancelBOMButton').setStyle ( { display:'none' } );
			 	    $('bap.okBOMButton').setStyle ( { display:'block' } );
			 	    $('bap.BOMMessage').innerHTML = bundleInfo.message;
			 	    $('bap.BOMMessage').setStyle ( { display:'block' } );
			 	    new Effect.Highlight('bap.BOMMessage', {duration: this.duration});
			 	    if ( $("bap.BOMList").value == '-10' )  //new BOM
				 	    {
				 	    if(Prototype.Browser.IE) 
					 	    {
					 	    var optionElem=document.createElement("option");
							optionElem.setAttribute("value", bundleInfo.bundleId);
							optionElem.setAttribute("label", bundleInfo.bundleName);
					 	    $("bap.BOMList").insertBefore(optionElem, $(this.newBundleOption));
						 	}
					 	else
						 	{
	                		$("bap.BOMList").insertBefore(new Option(bundleInfo.bundleName, bundleInfo.bundleId), $(this.newBundleOption));	
					 	    }
					 	}
				 	if($('ItemLists'))
				 	    {
				 	    if(Prototype.Browser.IE) 
					 	    {
					 	    var optionElem=document.createElement("option");
							optionElem.setAttribute("value", "b:"+bundleInfo.bundleId);
							optionElem.setAttribute("label", bundleInfo.bundleName);
					 	    $("ItemLists").insertBefore(optionElem, null);
						 	}
					 	else
						 	{
				 	    	$('ItemLists').insertBefore(new Option(bundleInfo.bundleName, "b:"+bundleInfo.bundleId), null);
				 	    	}
				 	    }
				 	this.enableDialog();
			 	}.bind(this)
	        }); 	     
        },
        
        /*
        Disable input fields on the dialog to prevent multiple submissions
        if controls are double clicked.
        */
        disableDialog: function()
            {
            $('bap.addToBOMCkeckBox').disabled = true;
		    $('bap.addToFavorite').disabled = true;
		    $('bap.BOMList').disabled = true;
		    $('bap.productQty').disabled = true;
		    $('bap.bundleName').disabled = true;
		    $('bap.bundleNote').disabled = true;
		    $('bap.addItemToBOMButton').disabled = true;
		    $('bap.cancelBOMButton').disabled = true;
		    $('bap.okBOMButton').disabled = true;
		    window.document.body.style.cursor = 'wait';
            },
        
        /*
        Enable input fields on the dialog.
        */
        enableDialog: function()
            {
            $('bap.addToBOMCkeckBox').disabled = false;
		    $('bap.addToFavorite').disabled = false;
		    if($('bap.addToBOMCkeckBox').checked == true || !this.isFavItem)
		    	{
			    $('bap.BOMList').disabled = false;
			    }
		    $('bap.bundleName').disabled = false;
		    $('bap.bundleNote').disabled = false;
		    if ( $("bap.BOMList").value != '-1' && $("bap.BOMList").value != 'incart' && $("bap.BOMList").value != 'shared')
		    	{
		    	$('bap.addItemToBOMButton').disabled = false;
		    	$('bap.productQty').disabled = false;
		    	}
		    $('bap.cancelBOMButton').disabled = false;
		    $('bap.okBOMButton').disabled = false;
		    window.document.body.style.cursor = 'default';
            }
    };
    
    