﻿Muti_Po = new Class({
	options: {
		isImportWinePO:false
	},

	initialize: function(ele,options) {
		this.element = ele;
		this.setOptions(options);
        this.POheaderEle = ele.getElement('div');
        this.PODetailInfoEle = this.POheaderEle.getNext();
        this.ProductListEle = this.PODetailInfoEle.getNext();        
        this.PONotesEle = this.ProductListEle.getElement('div').getNext().getNext().getNext().getElement('div').getElement('td');
        this.POSummaryEle = this.PONotesEle.getNext();
        this.POControlEleTr = this.ProductListEle.getElement('div').getNext().getNext().getNext().getElement('tr').getNext().getNext().getNext().getNext(); 
		this.RushOrderControl = this.ProductListEle.getElement('div').getNext().getNext().getNext().getElement('tr').getNext().getNext();
        this.POControlEle = this.POControlEleTr.getElement("div");
        this.POheader = new POHeader(this.POheaderEle, this.PODetailInfoEle,this);
        this.POSummary = new POSummary(this.POSummaryEle);
		this.PaymentMethodEle = this.POSummaryEle.getElement('table').getElement('tbody').getLast('tr');
		this.defaultpaymentmethodid = -1;
//		this.paymethodeaskagainele =  this.PaymentMethodEle.get('selector').getNext('span').getNext('span');
//        this.paymethodlastchoiceele = this.PaymentMethodEle.get('selector').getNext('span').getNext('span').getNext('span');
		//alert(this.PaymentMethodEle.get('html'))
		 
	}

});
Muti_Po.implement(new Options, new Events);

Muti_PendingPo = new Class({
	options: {

	},
	initialize: function(ele,options) {
	        this.SysCwUid="14c16894-aeb2-4f5d-84a1-094d83d25ccb";
		this.element = ele;
		this.options = options;
		var pouid = this.element.getPrevious('span');
		this.pouid= pouid.get('text');
		var isSinglePO = pouid.getPrevious('span');
		this.isSingle = isSinglePO.get('text');
		this.POheaderEle = ele.getElement('div');
		this.warehouseEle = this.POheaderEle.getElement('div').getNext('div').getNext('div').getElement('select');
		this.PODetailInfoEle = this.POheaderEle.getNext();
		this.ProductListEle = this.PODetailInfoEle.getNext();  
		this.POSummaryEle = this.ProductListEle.getElement('div').getNext('table').getElement('tbody').getElement('tr').getElement('td').getNext('td');
		this.POSummary = new POSummary(this.POSummaryEle);
		this.PaymentMethodEle = this.POSummaryEle.getElement('table').getElement('tbody').getLast('tr');
		var controlfisttr = this.ProductListEle.getElement('div').getNext('table').getNext('table').getElement('tbody').getElement('tr');
		this.POControlEle = controlfisttr.getNext('tr').getNext('tr').getNext('tr');
		this.RushOrderControl = controlfisttr.getNext('tr');
		this.rushordercheck = controlfisttr.getNext('tr').getElement('td').getElement('div');
		this.cancelPoButton = this.POControlEle.getElement('td').getElement('a');
		var contentOfwindow = this.cancelPoButton.getParent().getParent().getNext('div');
		this.contentOfwindow= contentOfwindow;
		this.invoiceControlEle = this.POControlEle.getElement('td').getNext('td');
		this.readyToshipEle = this.invoiceControlEle.getElement('div').getElement('div').getNext('div').getNext('div').getElement('input');
		this.invoiceNoteEle = this.POSummaryEle.getPrevious('td').getElement('div').getElement('table').getElement('tbody').getElement('tr').getNext('tr').getNext('tr').getElement('td').getNext('td').getNext('td').getElement('span');
		this.generateInvoiceButton = this.invoiceControlEle.getElement('div').getElement('div').getNext('div').getElement('a');
		this.RushOrderButton =  this.generateInvoiceButton.getParent('li').getNext('li').getElement('a');
		this.tipsEle = this.POControlEle.getNext('tr').getElement('div').getElement('span');
		this.paymentlabel = this.PaymentMethodEle.getElement('span');
		this.paymentselector = this.paymentlabel.getNext();
		this.paymenttext = this.paymentselector.getNext();
		/*****************************/
		this.warehouseaskagainele = this.warehouseEle.getParent().getNext('span');
//		alert(this.warehouseEle.get('id'));
//		alert(this.warehouseaskagainele.get('text'));
        this.warehouselastchoiceele = this.warehouseaskagainele.getNext('span');
        this.LicenseeName=this.warehouselastchoiceele.getNext('span').get('text');
        this.defaultwarehouseid=this.warehouseEle.get('value');
        
        this.paymethodeaskagainele =  this.paymentselector.getNext('span').getNext('span');
        this.paymethodlastchoiceele = this.paymethodeaskagainele.getNext('span');
        this.defaultpaymentmethodid=this.paymentselector.get('value');
        this.isanyinvoice=this.warehouselastchoiceele.getNext('span').getNext('span').get('text');
		/*****************************/
		if(this.warehouseEle.value ==this.SysCwUid)
		{
		    this.ShowPayment();
		}
		else
		{
			this.HidePayment();
		}
		this.RushOrderButton.addEvent('click',function(e){
			new Event(e).stop();
			 this.Isrushorder=this.RushOrderControl.getElement('div').getElement('input').get('checked');
		    this.rushorderDate=this.RushOrderControl.getElement('div').getNext('div').getElement('input').get('value');
		    this.rushorderNote=this.RushOrderControl.getElement('div').getNext('div').getNext('div').getElement('input').get('value');
		    this.invoicenotechoice = this.invoiceNoteEle.get('text');
			new ContainerWorld(this.pouid,1,1,this.Isrushorder,this.rushorderDate,this.rushorderNote,this.invoicenotechoice,this.paymentselector.get('value'),this.paymentselector.options[this.paymentselector.selectedIndex].text,this);
			
		}.bind(this));
		this.paymentselector.addEvent('change',function(e){
		    new Event(e).stop();
		    this.ChangePaymentmethod();
		}.bind(this));
		this.warehouseEle.addEvent('change',function(e){
			new Event(e).stop();
//			if(this.RushOrderControl.getElement('div').getLast('span').get('text') == 'false')
//			{
//				return;
//			}
            if(this.isanyinvoice=="false")
             {
                if(this.defaultwarehouseid != this.warehouseEle.get('value'))
                {
                    this.GetLastChoiceAndDoOperation("Warehouse");
  
                }
            }
			var isAllowrushorder = this.RushOrderControl.getElement('div').getLast('span').get('text');
			
			if(this.warehouseEle.value ==  this.SysCwUid)
			{
			    
				if(isAllowrushorder != "false")
				{
					this.generateInvoiceButton.setStyle('display','none');
					this.RushOrderButton.setStyle('display','');
					this.readyToshipEle.getParent().setStyle('display','none');
					if(this.RushOrderControl)
					{
						this.RushOrderControl.setStyle('display','');
					}
					if(this.rushordercheck.getElement('input').checked)
					{
						this.rushordercheck.getNext('div').setStyle('display','');
						this.rushordercheck.getNext('div').getNext('div').setStyle('display','');
						
					}
				}
				this.ShowPayment();
			}
			else
			{
				if(isAllowrushorder != "false")
				{
					this.generateInvoiceButton.setStyle('display','');
					this.RushOrderButton.setStyle('display','none');
					this.readyToshipEle.getParent().setStyle('display','');
					if(this.RushOrderControl)
					{
						this.RushOrderControl.setStyle('display','none');
					}
					if(this.rushordercheck.getElement('input').checked)
					{
						this.rushordercheck.getNext('div').setStyle('display','');
						this.rushordercheck.getNext('div').getNext('div').setStyle('display','');
						
					}
				}
				this.HidePayment();
			}
		}.bind(this));
		
		
		this.generateInvoiceButton.addEvent('click',function(e){
			new Event(e).stop();
			if(this.generateInvoiceButton.hasClass('disabled'))
			{
				return;
			}
			if(this.readyToshipEle.getProperty('checked') == true)
			{
				var confirmStr = " Finalizing this invoice, no further changes will be allowed.<br><P><strong>Do you want to finalize this invoice?</strong></p>";
				var titleOfWindow = "Finilize Invoice";
			}
			else
			{
				var confirmStr = " Generate new invoice, no further po changes will be allowed.<br><P><strong>Do you want to generate new invoice?</strong></p>";
				var titleOfWindow = "Generate Invoice";
			}
			new ConfirmWindow(titleOfWindow,confirmStr, {ConfirmText: 'Yes',
																CancelText:'No',
																onConfirm: (this.FinilizeOperation).bind(this),
																onCancel: (this.CancelOperation).bind(this)
							});
		}.bind(this));
            
		//alert(this.generateInvoiceButton.get('text') );
		this.cancelPoButton.addEvent('click',function(e){
			new Event(e).stop();
			this.opeType = "cancelPO";
			this.currentButton = this.deletePoButtonContainerEle;
			var confirmStr = "<p>Canceling this purchase order will mark each item as cancelled and prevent any further changes.</p>";
			this.cancelpoWindow=new CancelWindow("Cancel Purchase Order",confirmStr, {ConfirmText: 'Yes',
																						CancelText:'No',
																						windowHeight: 434,
																						windowWidth :400,
																						onConfirm: (this.ConfirmOperation).bind(this),
																						onCancel: (this.CancelOperation).bind(this)
                                                 
												});
			}.bind(this));
        this.LineItems =this.ProductListEle.getElement('div').getElement('table').getElement('tbody').getElements('.ForpojsStyle');
		this.LineItems.each(function(el){
				new Muti_PendingPoLineItem(el,this.pouid,this.POSummary,this.element,this.LineItems,options);
			}.bind(this));
	},
	/// <name>GetLastChoiceAndDoOperation</name>
    /// <summary>
    /// Judge how to do the operation : pop up window or update or do nothing
    /// </summary>
    /// <param name="operationType">warehouse or payment method</param>
    GetLastChoiceAndDoOperation: function (operationType)
    {
        var reqURL = 'SetDefaultWarehouseOrPaymentMethod.aspx?PurchaseOrderUID='+ this.pouid + '&operationType=getwpset&askmeagain=false&ischangedefualt=false&defaultwarehouseid='+this.warehouseEle.get('value')+'&methodid=null';
        var opeReq = new Request.JSON({url: reqURL,
            onSuccess:function(data){
                if(operationType=="Warehouse")
                {
                    if(data.warehouseaskagain=="true" && data.warehouselastchoice=="true")
                    {
                        this.UpdateMethod("true","true","Warehouse");                        
                    }
                    else if(data.warehouseaskagain=="false")
                    {
                        this.OpenNewWindow("Warehouse");
                    }
                }
                else
                {
                    if(data.paymethodeaskagain=="true" && data.paymethodlastchoice=="true")
                    { 
                        this.UpdateMethod("true","true","payment method");                        
                    }
                    else if(data.paymethodeaskagain=="false")
                    {
                        this.OpenNewWindow("Payment Method ");
                    }
                }

        }.bind(this)}).send();
    },
	
	ChangePaymentmethod : function()
    {
		if(this.isanyinvoice=="false")
		{           
            if(this.defaultpaymentmethodid != this.paymentselector.get('value'))
            {
                this.GetLastChoiceAndDoOperation("Payment Method ");
            }
        }
    },
    /// <name>OpenNewWindow</name>
    /// <summary>
    /// pop up window when change warehouse or payment method
    /// </summary>
    /// <param name="operationType">warehouse or payment method</param>
    OpenNewWindow : function OpenNewWindow(operationType)
    {
        var paramName;
        if(operationType=="Warehouse")
        {
            paramName=this.warehouseEle.options[this.warehouseEle.selectedIndex].text;
        }
        else
        {
            var paysel=this.paymentselector;
            paramName=paysel.options[paysel.selectedIndex].text;
        }
        new Popupwindow("Update Default "+operationType,createTabel(paramName,this.LicenseeName,operationType),{windowHeight:150,windowWidth:410,footerHeight:80});
       
        var buttondiv = createbuttondiv(operationType);
        var confirmButton = buttondiv.getElement('li');
        var cancelButton=confirmButton.getNext('li');
        var checkbox = buttondiv.getParent('div').getParent('div').getParent('div').getParent('div').getParent('div').getNext('div').getElement('input');
        
        confirmButton.addEvent('click',function()
        {
            this.UpdateMethod(checkbox.checked,"true",operationType);

        }.bind(this));
        cancelButton.addEvent('click',function()
        {
            this.UpdateMethod(checkbox.checked,"false",operationType);
        }.bind(this));
    },
    /// <name>UpdateMethod</name>
    /// <summary>
    ///  update default warehouse or payment method
    /// </summary>
    /// <param name="askmeagain">whether check 'don't ask me again'</param>
    /// <param name="ischangedefualt">whether update when change</param>
    /// <param name="operationType">warehouse or payment method</param>
    UpdateMethod : function(askmeagain,ischangedefualt,operationType)
    {
        var methodid;
        if(operationType!="Warehouse")
        {
            methodid= this.paymentselector.get('value');
            operationType = "payment";
        }
        var reqURL = 'SetDefaultWarehouseOrPaymentMethod.aspx?PurchaseOrderUID='+ this.pouid + '&operationType=' + operationType+'&askmeagain='+askmeagain+'&ischangedefualt='+ischangedefualt+'&defaultwarehouseid='+this.warehouseEle.get('value')+'&methodid='+methodid;
        var opeReq = new Request({url: reqURL,
            onSuccess:function(responseText){
                if(responseText == 'success')
                {
                    this.defaultwarehouseid = this.warehouseEle.get('value');
                    if(operationType == "Warehouse")
                    {
                        this.warehouseaskagainele.set('text',askmeagain);
                        this.warehouselastchoiceele.set('text',ischangedefualt);
                        this.defaultwarehouseid = this.warehouseEle.get('value');
                    }
                    else
                    {
                        this.paymethodeaskagainele.set('text',askmeagain);
                        this.paymethodlastchoiceele.set('text',ischangedefualt);
                        this.defaultpaymentmethodid = methodid;
                    }
                }
                else if(responseText == "notChange")
                {
                    if(operationType == "Warehouse")
                    {
                        this.warehouseaskagainele.set('text',askmeagain);
                        this.warehouselastchoiceele.set('text',ischangedefualt);
                    }
                    else
                    {
                        this.paymethodeaskagainele.set('text',askmeagain);
                        this.paymethodlastchoiceele.set('text',ischangedefualt);
                    }
                }
                closePopWindow();
            }.bind(this)
        }).send();
    } ,
    
	ShowPayment: function()
	{
	    if(this.paymentselector.length > 1)
	    {
	         this.paymentlabel.setStyle('display','');
	         this.paymentselector.setStyle('display','');
	    }
	    else if(this.paymentselector.length == 1)
	    {
	        this.paymentlabel.setStyle('display','');
	        this.paymenttext.setStyle('display','');   
	        
	    }
		else
		{
			//this.paymenttext.set('text','Payment method is Required, please set the payment methods for this licensee before send an order to Container World.');
	        this.paymenttext.setStyle('display','');   
	        this.RushOrderButton.addEvent('mouseover',function(){
               return false;
            });;
	        this.RushOrderButton.getParent('li').addClass("disabled");
		}
	},
	HidePayment: function()
	{
	    this.paymentlabel.setStyle('display','none');
		this.paymentselector.setStyle('display','none');
		this.paymenttext.setStyle('display','none');
	},
		ConfirmOperation :function()
			{
				this.CancelReason = this.cancelpoWindow.getReason();
				this.DoOperationForPO(this.opeType,this.CancelReason); 
			},
		CancelOperation:function()
			{
				return;
			},
		FinilizeOperation:function(){
			this.invoiceNote = this.invoiceNoteEle.get('text');
			this.readtToship = this.readyToshipEle.getProperty('checked');
			var newDateString = (new Date()).toDateString();
			var arry = newDateString.split(' ');
			var form60date = arry[1]+' '+ arry[2]+', '+arry[3];
			var operationType = 'generateIvoice';
			var reqURL = 'CancelPendingPO.aspx?PurchaseOrderUID='+ this.pouid + '&operationType=' + operationType+'&InvoiceNote=' + this.invoiceNote+'&readtToship=' + this.readtToship+'&warehouseUid='+this.warehouseEle.get('value')+'&form60Date='+form60date;
			var opeReq = new Request.JSON({url: reqURL,
										onComplete:function(responseText){
										if(responseText.returnValue=='generateIvoiceOK' && this.isSingle != 'true')
										{
											this.generateInvoiceButton.set('style','FFButton disabled');
											this.generateInvoiceButton.getParent('li').setProperty('class','disabled');
											this.generateInvoiceButton.setProperty('disabled','disabled');
											this.tipsEle.set('html',responseText.tips);
											this.tipsEle.setStyle('display', '');
											this.readyToshipEle.setStyle('display', 'none');
											this.readyToshipEle.getNext('label').setStyle('display', 'none');
											var numberOfNewPO = document.getElement('.headerMessage');
											numberOfNewPO.fireEvent('refresh');
											var numbertoInt = parseInt(numberOfNewPO.getElement('span').get('text'));
											if(numbertoInt == 1)
											{
												window.location.href = 'PurchaseOrders.aspx'; 
											}
										}
										if(responseText.returnValue=='generateIvoiceOK' && this.isSingle == 'true')
										{
											window.location.href = responseText.singlePoGenarete; 
										}
										else if(responseText.returnValue=='finalizeOK')
										{
											this.element.setStyle('display', 'none');
											if(this.isSingle == 'true')
											{
												window.location.href = responseText.singlePoFinalize; 
											}
										}
										if(responseText.invoiceUID != "nothing" && this.isSingle == 'false')
										{	
											var reqURLForm60 = 'OpenForm60.aspx?InvoiceUID='+responseText.invoiceUID;
											window.open(reqURLForm60,"","height=0, width=0, toolbar= no, menubar=no, scrollbars=no, resizable=no, location=no, status=no");
											var numberOfNewPO = document.getElement('.headerMessage');
											numberOfNewPO.fireEvent('refresh');
											var numbertoInt = parseInt(numberOfNewPO.getElement('span').get('text'));
											if(numbertoInt == 1)
											{
												window.location.href = 'PurchaseOrders.aspx'; 
											}
											else
											{
//												window.location.href = reqURLForm60;

											}
										}
                                      
									}.bind(this)
								}).get();
			},
		DoOperationForPO:function(operationType,reason){
			var reqURL = 'CancelPendingPO.aspx?PurchaseOrderUID='+ this.pouid + '&operationType=' + operationType+'&cancelReason=' + reason;
			var opeReq = new Request.JSON({url: reqURL,
										onComplete:function(responseText){
										if(responseText.returnValue=='poCancelled')
										{
											this.element.setStyle('display', 'none');
											var numberOfNewPO = document.getElement('.headerMessage');
											numberOfNewPO.fireEvent('refresh');
											var numbertoInt = parseInt(numberOfNewPO.getElement('span').get('text'));
											if(numbertoInt == 1)
											{
												window.location.href = 'PurchaseOrders.aspx'; 
											}
											
										}
										if(responseText.returnValue=='poCancelled' && this.isSingle == 'true')
										{
										
											window.location.href = 'PurchaseOrder.aspx?PurchaseOrderUID='+this.pouid;
										}
										
									}.bind(this)
								}).get();
		} 
		
});
		
Muti_PendingPo.implement(new Options, new Events);

Muti_PendingPoLineItem = new Class({
options: {
	
	},

	initialize: function(ele,pouid,POSummary,element,LineItems,options) {
		this.el = ele;
		this.pouid = pouid;
		this.options=options;
		this.POSummary = POSummary;
		this.element = element;
		this.LineItems =LineItems;
		this.numberOfcancel = 0;
		this.isProcessed = false ;
	
		if((this.el.getElements('td')).length > 3)
			{
				var cancellbutton = this.el.getLast('td').getElement('a');
				var LineItemUid = cancellbutton.getNext('span').get('text');
				this.LineItemUid = LineItemUid;
				this.cancellbutton =cancellbutton ;
				this.numberOfcancel = 0;
				this.cancellbutton.addEvent('click',function(e){
				new Event(e).stop();
				var numOfcancelButton=0;
				this.LineItems.each(function(uncancelEle){
				var numEle = uncancelEle.getLast('td').getPrevious('td').getElement('span');
				var checkCancelNum = uncancelEle.getLast('td').getElement('a');
					if($chk(checkCancelNum.hasClass('forcancelwindow')))
					{
							numOfcancelButton = numOfcancelButton+1;
					}
					if(numEle.get('text') != 'Unprocessed' && numEle.get('text') != 'Cancelled')
					{
					
						this.isProcessed = true;
					}
				}.bind(this));
				var confirmStr = '';
				if(numOfcancelButton<=1  && this.isProcessed != true )
				{
					confirmStr = 'Cancel this order line item will Cancel this Purchase Order. Are you sure you want to cancel this purchase order line item?';
				}
				else if(numOfcancelButton <=1 && this.isProcessed == true)
				{
					confirmStr = 'Cancel this order line item will set this Purchase Order as Processed. Are you sure you want to cancel this purchase order line item?';
				}
				else{
					confirmStr = 'Are you sure you want to cancel this purchase order line item?';
				}
				var titleOfWindow = 'Cancel product item!';
				this.CancelLineItemWindow=new ConfirmWindow(titleOfWindow,confirmStr, {ConfirmText: 'Yes',
															CancelText:'No',
															onConfirm: (this.CancelLineItem).bind(this),
															onCancel: (this.CancelOperation).bind(this)
						});
					}.bind(this));
				}
	},
	CancelLineItem:function(){
				var reqURL = 'CancelLineItemOfPendingPO.aspx?LineItemUid='+this.LineItemUid+'&pouid='+this.pouid;
				var opeReq = new Request.JSON({url: reqURL,
												onComplete:function(data){
														if(data.statusOfOperation == 'CanceledAll' || data.statusOfOperation == 'ProcessedAll')
														{
															this.element.setStyle('display', 'none');
														}
														else if(data.statusOfOperation == 'StillPending')
														{
															var status =this.cancellbutton.getParent('td').getPrevious('td').getElement('span');
															status.set('text','Cancelled');
															this.cancellbutton.setStyle('display', 'none');
															this.cancellbutton.removeClass('forcancelwindow');
															this.POSummary.DataLoaded(data);
														}
															var numberOfNewPO = document.getElement('.headerMessage');
															numberOfNewPO.fireEvent('refresh');
															var numbertoInt = parseInt(numberOfNewPO.getElement('span').get('text'));
														if(numbertoInt == 1 && data.statusOfOperation != 'StillPending')
														{
															window.location.href = 'PurchaseOrders.aspx'; 
														}
													}.bind(this)
											}).get();
		},
	CancelOperation:function()
		{
			return;
		}
});

Muti_PendingPoLineItem.implement(new Options, new Events);

Muti_NewPo = new Class({
		Extends: Muti_Po,
		initialize: function(element,options) {
		this.parent(element,options);
		var pouid = this.element.getPrevious('span');
		this.POUID = pouid.get('text');
		var isSinglePO = pouid.getPrevious('span');
		this.isSingle = isSinglePO.get('text');
		this.ProductList = new ProductList(this.ProductListEle, this,
		{
			isImportWinePO : this.options.isImportWinePO
		});
		var NotesOfNewPO =this.PONotesEle.getElement('span').getNext('span').get('text');
		this.deletePoButtonContainerEle = this.POControlEle.getElement('td').getElement('a');
		this.finalizePoButtonContainerEle =this.POControlEle.getElement('td').getNext().getElement('a');
		
		
		this.PONotes = new PONotes(this.PONotesEle,this,
		{
			NoteValue:NotesOfNewPO,
			POUID : this.POUID
		}
	);
	this.deletePoButtonContainerEle.addEvent('click',function(e){
			new Event(e).stop();
			this.opeType = "DeletePO";
			this.currentButton = this.deletePoButtonContainerEle;
			var confirmStr = "<P><strong>Are you sure you want to delete the purchase order?</strong></p>";
			new ConfirmWindow("Delete PO",confirmStr, {ConfirmText: 'OK',
														onConfirm: (this.ConfirmOperation).bind(this),
														onCancel: (this.CancelOperation).bind(this)
							});
		}.bind(this));
	this.finalizePoButtonContainerEle.addEvent('click',function(e){
		new Event(e).stop();
		this.opeType = "FinalizePO";
		this.currentButton = this.deletePoButtonContainerEle;
		var text="";
		var title;
		//bug 6463
		if(this.options.isImportWinePO)
		{
		title="Send PO to LDB";
		text="<P>Sending this purchase order to the LDB will finalize it, preventing further changes.</p><p><strong>Do you want to send this purchase order?</strong></p>";
		}
		else
		{
		title="Finalize PO";
		text="<P>Finalizing this purchase order will prevent further changes.</p><p><strong>Do you want to finalize this purchase order?</strong></p>";
//        title="Send PO";
//		text="<P>Sending this purchase order will prevent further changes.</p><p><strong>Do you want to send this purchase order?</strong></p>";
		}
		var confirmStr = text;
		new ConfirmWindow(title,confirmStr, {ConfirmText: 'OK',
														onConfirm: (this.ConfirmOperation).bind(this),
														onCancel: (this.CancelOperation).bind(this)
							});
			}.bind(this));
	},
	
	updatePO: function(productUID, quantity,LineItemUid) {
	var HiddenLineItem_Uid = LineItemUid.get('text');
	//alert(HiddenLineItem_Uid)
	//alert('DoOprationLicenseePurchaseOrder.aspx?poUID='+this.POUID+'&ProductUID='+productUID+'&ProductQuantity='+quantity+'&LineItemUID='+HiddenLineItem_Uid)
	var data = AjaxServer.TransToAjaxServer('DoOprationLicenseePurchaseOrder.aspx?poUID='+this.POUID+'&ProductUID='+productUID+'&ProductQuantity='+quantity+'&LineItemUID='+HiddenLineItem_Uid);
	if(data != null && data != '')
	{
		data = eval('('+data+')');
//	var reqURL = 'DoOprationLicenseePurchaseOrder.aspx?poUID='+this.POUID+'&ProductUID='+productUID+'&ProductQuantity='+quantity+'&LineItemUID='+HiddenLineItem_Uid;
//	var updateRequest = new Request.JSON({
//						url: reqURL,
//						onComplete: function(data){
						var importwines = $$('.classForImportWine');
						if(data.toString() == 'false')
						{
//							alert('This purchase order statu has been changed by another contact!');
//							window.location.reload();
						}
						else
						{
							this.DataRefresh(data);
							if(data.opration == 'deleteProductForImportWinePo')
							{
								LineItemUid.set('text','0');
								LineItemUid.getParent('tr').setStyle('display','none');
								
							}
							if(data.opration == 'delete')
							{
								LineItemUid.set('text','0');
								//LineItemUid.getParent('tr').setStyle('display','none');
								
							}
							if(data.opration == 'deletePO')
							{
								//LineItemUid.set('text','0');
								//LineItemUid.getParent('tr').setStyle('display','none');
								$('ctl00_BodyContent_hiddenLicenseeUID').set('text','');
								$('ctl00_BodyContent_hasImportWinePoforLicensee').setStyle('display','none');
								$$('.ForpojsStyle').each(function(element,index){	
													if(!element.hasClass('NotAgentPo'))
													element.destroy();
											 });
								var numberOfNewPO = document.getElement('.headerMessage');
								numberOfNewPO.fireEvent('refresh');
								if(importwines != null)
								{
								 importwines.each(function(element,index){
													var quantityTd = element.getElement('td').getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext();
													quantityTd.getElement('input').set('value','0');
													quantityTd.getElement('input').setStyle('background-color','#ffffff');
													quantityTd.getElement('input').getParent('div').getNext().getElement('div').getNext().addClass('disabled');
													quantityTd.getNext().getElement('span').set('text','');
													
												}); 
								}
								return;
							}
							if(data.opration == 'create')
							{
								LineItemUid.set('text',data.poLineItemUID);
							}
						}
						if(this.options.isImportWinePO)
						{
							$('ctl00_BodyContent_QuantityLabel').set('html','Quantity: '+data.totalQuantity + '&nbsp;&nbsp;');
							$('ctl00_BodyContent_totalHeadLabel').set('text','Total: '+data.POTotal);
						}
						if(importwines!=null)
						{
							for(var i=0;i<importwines.length;i++)
								{
									var currentItemNameTD = importwines[i].getElement('td').getNext().getNext();
									var itempuid = currentItemNameTD.getElement('span').get('text');
									var quantityTD = currentItemNameTD.getNext().getNext().getNext().getNext().getNext().getNext();
									var priceEle = currentItemNameTD.getNext().getNext().getNext();
									var price = parseFloat(priceEle.getElement('span').get('text').replace('$',''));
									if(itempuid == productUID)
									{
										quantityTD.getElement('input').set('value',quantity);
										quantityTD.getNext().getElement('span').set('text',this.formatCurrency(quantity * price));
									}
									
								}
						}
//					}.bind(this)
//				}).get();
		}
      
	},
	DataRefresh :function(data)
	{
		this.POSummary.DataLoaded(data);
	},
	ConfirmOperation :function()
	{
		
		if(this.opeType != 'DeletePO')
		{
			window.setTimeout(function(){this.currentButton.focus();}.bind(this),50);
		}
		this.DoOperationForPO(this.opeType); 
	 //alert(this.opeType);
	},
	CancelOperation:function()
	{
		window.setTimeout(function(){this.currentButton.focus();}.bind(this),50);
		return;
	},
	DoOperationForPO:function(operationType){
		var newDateString = (new Date()).toDateString();
		var arry = newDateString.split(' ');
		var form60date = arry[1]+' '+ arry[2]+', '+arry[3];
		var isrushorder = false;
		if(this.RushOrderControl.getElement('div'))
		{
			isrushorder = this.RushOrderControl.getElement('div').getElement('input').checked;
		}
		if(isrushorder)
		{
			var rushorderdate = this.RushOrderControl.getElement('div').getNext('div').getElement('input').get('value');
			var rushordernote = this.RushOrderControl.getElement('div').getNext('div').getNext('div').getElement('input').get('value');
			rushorderdate=encodeURIComponent(rushordernote);
		}
		var reqURL = 'DoOperationForPO.aspx?PurchaseOrderUID='+ this.POUID + '&operationType=' + operationType+'&form60Date='+form60date+'&isrushorder='+isrushorder+'&rushorderdate='+rushorderdate+'&rushordernote='+rushordernote;
		var opeReq = new Request({url: reqURL,
										onSuccess:function(responseText){
										if(responseText == 'true')
										{
											this.element.setStyle('display', 'none');
											var numberOfNewPO = document.getElement('.headerMessage');
											numberOfNewPO.fireEvent('refresh');
											var numbertoInt = parseInt(numberOfNewPO.getElement('span').get('text'));
											if(numbertoInt == 1 || this.isSingle == 'true')
											{
											window.location.href = 'PurchaseOrders.aspx'; 
											}
											
										}
										else if(responseText == 'deleteLargePO')
										{
											var numberOfNewPO = document.getElement('.headerMessage');
											numberOfNewPO.fireEvent('refresh');
											 $('ctl00_BodyContent_hiddenLicenseeUID').set('text','');
											 $('ctl00_BodyContent_hasImportWinePoforLicensee').setStyle('display','none');
											  $$('.ForpojsStyle').each(function(element,index){	
													if(!element.hasClass('NotAgentPo'))
													element.destroy();
											 });
											 $$('.classForImportWine').each(function(element,index){
													var quantityTd = element.getElement('td').getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext();
													
													//quantityTd.getElement('input').setStyle('background-color','#ffffff');
													//quantityTd.getElement('input').getParent('div').getNext().getElement('div').getNext().addClass('disabled');
													if(quantityTd.getElement('input').value != '0')
													{
														quantityTd.getElement('input').set('value','0');
														quantityTd.getElement('input').focus();
														quantityTd.getElement('input').blur();
													}
													//quantityTd.getNext().getElement('span').set('text','');
													
												}); 
											
										}
										else{
											window.location.reload();
										}
									}.bind(this)
								}).send();
	},
	formatCurrency: function(strValue)
    {
     strValue = strValue.toString().replace(/\$|\,/g,'');
     dblValue = parseFloat(strValue);

     blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
     dblValue = Math.floor(dblValue*100+0.50000000001);
     intCents = dblValue%100;
     strCents = intCents.toString();
     dblValue = Math.floor(dblValue/100).toString();
     if(intCents<10)
      strCents = "0" + strCents;
     for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
      dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
      dblValue.substring(dblValue.length-(4*i+3));
     return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
    }
});
Muti_NewPo.implement(new Options, new Events);

PO = new Class({
		Extends: Muti_Po,
		initialize: function(options){
		//this executes the initialize() function in the Muti-PO Class
		//let's also pass the options to the parent's initialize function 
		this.parent(options); 
		this.isAgentPo = $('ctl00_BodyContent_isWineAgentValue').get('value');
		if(this.isAgentPo == 'true')
		{
			$('PoHeaderDiv').setStyle('background-color','#3F7B00');
			this.options.isImportWinePO=true ;
		}
		this.POControl = new POControl(this.POControlEle,this);
		this.PONotes = new PONotes(this.PONotesEle,this,
		{
                NoteValue:'',
                POUID : '0'
                
            }
		);
		this.POUID =" ";
		this.ProductList = new ProductList(this.ProductListEle, this);
		this.disable();
      
	},    
	disable: function()
    {
        this.POUID = "";
        this.ProductList.disable();
        this.POSummary.hide();
        this.POheader.hide();
    },

    getPO: function(wineryid, licenssid) {
        this.disable();
        this.licenssid = licenssid;
        var reqURL = 'GetWineryPurchaseOrder.aspx?LicenseeUID='+licenssid;
              
        var jsonRequest = new Request.JSON({
			url: reqURL,
			onComplete: function(data){
			    this.getResult(data);
				this.updatepaymentmethod(data);
			}.bind(this)
		}).get();
		//Show loading
	},
    updatepaymentmethod:function(data)
    {
		
    	var selector = this.PaymentMethodEle.getElement('select');
				selector.length = 0;
				
				if(data.hasPO != 'false')
				{
					
 				    if(data.paymentmethods == undefined || data.paymentmethods == null ||  data.paymentmethods == '')
				    {
				       selector.setStyle("display","none");
				       selector.getPrevious().setStyle("display","none");
				       selector.getNext().set('html',"No Payment methods are available. Go to the menu <a href='PaymentMethods.aspx' style='color:red !important;'>Winery / Payment Methods</a> to add Payment Methods. ");
				       if(data.nopaymentstatu == 'Licensees')
				       {
				         selector.getNext().set('html',"No Payment methods are available for this Licensee. Go to the <a href='LicenseeEdit.aspx?LicenseeUID="+this.licenssid+"' style='color:red !important;'>Licensee setting page</a> to add a Payment Method. ");
				      
				       }
				        selector.getNext().setStyle("display","");
				        this.POControl.sendTocontainerWorldButton.addEvent('mouseover',function(){
                           return false;
                        });;
				        this.POControl.sendTocontainerWorldButton.getParent("li").addClass("disabled");
    				    
				    }
				    else 
				    {
				       this.POControl.sendTocontainerWorldButton.removeEvent('mouseover');
				       this.POControl.paymethodeaskagainele.set('text',data.paymethodAskAgain);
					   this.POControl.paymethodlastchoiceele.set('text',data.paymethodLastchoice);
    				   selector.setStyle("display","");
				       selector.getPrevious().setStyle("display","");
				        selector.getNext().setStyle("display","none");
                        this.POControl.sendTocontainerWorldButton.getParent("li").removeClass("disabled");
				        for(var i = 0;i<data.paymentmethods.length;i++)
				        {
					        var option = new Option(data.paymentmethods[i].Name,data.paymentmethods[i].Methodid);
					        selector.options.add(option);
				        }
				        if(data.defaultmethod!=-1)
				        {
					        selector.set('value',data.defaultmethod);
					        this.defaultpaymentmethodid = data.defaultmethod;
				        }
				        if(data.paymentmethods.length==1)
				        {
				           selector.setStyle("display","none");
				           selector.getNext().set('text',data.paymentmethods[0].Name);
				            selector.getNext().setStyle("display","");
				        }
				        else 
				        {
				            selector.setStyle("display","");
				            selector.getNext().setStyle("display","none");
				            selector.removeEvents();
				            selector.addEvent('change',function(e){
					             new Event(e).stop();
					             this.POControl.ChangePaymentmethod(data);
				            }.bind(this));
				        }
				    }
				   if(this.isAgentPo == 'true' || data.isImportWine)
				    {
				        selector.getNext().setStyle("display","none");
				        selector.setStyle("display","none");
				         selector.getPrevious().setStyle("display","none");
				    }
				}
    },
    updatePO: function(productUID, quantity,LineItemUid) {
      var reqURL = 'GetWineryPurchaseOrder.aspx?LicenseeUID='+this.licenssid+'&ProductUID='+productUID+'&ProductQuantity='+quantity;
      var jsonRequest = new Request.JSON({
			url: reqURL,
			onComplete: function(data){
				this.getResult(data, true);
				 //alert(this.PO.isAgentPo + "   " +data.isImportWine )
				this.updatepaymentmethod(data);
			}.bind(this)
		}).get();
    },

	getResult: function(data, update){
		//Get PO information
		//If PO is not empty
		if(data.LicenseeUID != this.licenssid)
		{
		    return;
		}
         
         //list the Products List for the Licensee
         this.ProductList.LoadProducts(data.ProductsList);
         
		if(data.hasNewOrder)
		{
		    this.POUID = data.POUID;
		    this.PONotes.DataLoaded(data);
		    this.POSummary.DataLoaded(data);
		    if(data.isupdatepo == "false")   // if update the old po, do not need to load po header and control again
		    {
				this.POControl.DataLoaded(data); 
				this.POheader.DataLoaded(data);
			}
		    if(update != true)
		    {
		        this.ProductList.DataLoaded(data);
		        this.ProductList.SetFocus();
		    }
		}
		else
		{    
		    this.POheader.hide();
		    this.ProductList.enable();		    
		    this.PONotes.hide();
		    this.POSummary.hide();
		    this.POControl.hide();
		    this.ProductList.SetFocus();
		}

		//hide loading
	}
	});
	
	PO.implement(new Options, new Events);

	

noteDropDownList = new Class({
		options: {
		},

		initialize: function(ele, options) {
			this.options = options;
			this.element = ele;
			var notedetails = ele.getParent().getNext('td').getElement('span');
			this.notedetails = notedetails;
			ele.removeEvents();
			ele.addEvent('click', function(e){
			this.ValueChanged();
			new Event(e).stop();
			}.bind(this));
			},
			ValueChanged : function()
			{
			
				this.notedetails.set('text',this.element.get('value'));
			 
			}
		});
		noteDropDownList.implement(new Options, new Events);
		window.addEvent('domready', function(){
			$$('.noteDropDownList').each(function(element,index){
				new noteDropDownList(element);
			}); 
		});

POHeader = new Class({
	options: {

	},

    initialize: function(headerele, detailele, PO, options) {
        this.SysCwUid="14c16894-aeb2-4f5d-84a1-094d83d25ccb";
        this.defaultwarehouseid = '0';
        this.headerele = headerele;
        this.detailele = detailele;
        this.PO = PO;
        this.options = options;
        this.PONumberDiv = this.headerele.getElement('div');
        this.PODateDiv = this.PONumberDiv.getNext();
        //this.LicenseeDiv  = this.PODateDiv.getNext();
        this.WarehouseDiv  = this.PODateDiv.getNext(); 
        this.DisplayDetailsDiv = this.WarehouseDiv.getNext();
       
        this.PONumberEle = this.PONumberDiv.getElement('span');
        this.PONumberEditEle = this.PONumberEle.getNext();
        this.PODateEle = this.PODateDiv.getElement('span').getElement('span').getNext('span');
        //this.LicenseeEle= this.LicenseeDiv.getElement('span').getElement('span');
        this.WarehouseEle= this.WarehouseDiv.getElement('span').getElement('select');
        if(this.WarehouseEle)
        {
            this.warehouseaskagainele = this.WarehouseEle.getNext('span');
            this.warehouselastchoiceele = this.warehouseaskagainele.getNext('span');
        }
        this.LicenseeNameEle = this.detailele.getElement('table').getElement('tbody').getElement('tr').getElement('td').getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getElement('span');
        this.LicenseeAddressEle = this.LicenseeNameEle.getNext().getNext();
        this.LicenseePhoneEle = this.LicenseeAddressEle.getNext().getNext();
        
        this.LDBTableEle = this.detailele.getElement('table');
        this.WineryNameEle = this.detailele.getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getElement('span');
        this.isSpan = this.WineryNameEle.getNext();
        //alert(this.isSpan.getElement("input"))
        this.LDBshiptomeButton = this.isSpan.getElement("input");
		this.LDBshiptomeLabel = this.isSpan.getElement("input").getNext();
		this.WineryAddressEle = this.isSpan.getNext('span');
        
		this.LDBpickupButton = this.WineryAddressEle.getNext('span').getElement("input");
		this.LDBpickupLabel =  this.WineryAddressEle.getNext('span').getElement("input").getNext();
		this.WineryPhoneEle = this.WineryAddressEle.getNext('span').getNext('span');
		if(this.WineryPhoneEle.getNext())
		{
			this.WineryPhoneEle.getNext().setStyle('display','none');
		}
//		if(navigator.userAgent.indexOf("MSIE")>0)
//		   {
//			 this.isSpan.getNext().setStyle('display','none');
//			 this.WineryAddressEle.getNext('span').getNext().setStyle('display','none');
//	                
//			}
        this.POStatusEle =this.detailele.getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getNext().getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getElement('span');
        this.POOrderByEle =this.detailele.getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getNext().getElement('table').getElement('tbody').getElement('tr').getNext().getElement('td').getNext().getElement('span');
        this.POCreatedByEle =this.detailele.getElement('table').getElement('tbody').getElement('tr').getElement('td').getNext().getNext().getElement('table').getElement('tbody').getElement('tr').getNext().getNext().getElement('td').getNext().getElement('span');

 // alert(this.PONumberEditEle);
        this.PONmuberEditor = new InlineEditor(this.PONumberEditEle, {maxLength: 12, onChanged: (this.UpdatePONumber).bind(this)}); 
        this.PODateEle.addClass('date');
        new InlineEditor(this.PODateEle, {onChanged: (this.UpdatePODate).bind(this)});
    },

    hide:function(){
        this.headerele.setStyle('display', 'none');
        this.detailele.setStyle('display', 'none');
    },

    show:function(){
        this.headerele.setStyle('display', 'block');
        this.detailele.setStyle('display', 'block');
    },
    UpdatePONumber:function(PONumber){  
         var updatePoNumURL = 'UpdatePONumber.aspx?target=number&PONumber='+ PONumber + '&PurchaseOrderUID=' + this.PO.POUID;
         var reqUpdate = new Request({url:updatePoNumURL}).send();    
         //this.PO.UpdatePONumber(PONumber);
    },

    UpdatePODate:function(PODate){
         var updatePoDateURL = 'UpdatePONumber.aspx?target=date&PODate='+ PODate + '&PurchaseOrderUID=' + this.PO.POUID;
         var reqUpdate = new Request({url:updatePoDateURL}).send();    
    },

    DataLoaded:function(data){        
         //this.PONumberEle.set('text',"PO Number: " + data.PONumber);
         
         this.PONumberEditEle.set('text',data.PONumber);
         this.PONmuberEditor.value=data.PONumber;
         
         //this.PODateEle.set('text',data.PODate); 
         
        var oldTime = data.PODate;
		var oldDate = new Date(oldTime);
		var newDate = new Date(oldTime);
		//alert(data.POStatus + this.POStatusEle)
		newDate.setHours((oldDate.getHours() - newDate.getTimezoneOffset()/60),oldDate.getMinutes(),oldDate.getSeconds() ,oldDate.getMilliseconds());
		var newDateString = newDate.toDateString();
		var arry = newDateString.split(' ');
		this.PODateEle.set('html',arry[1]+' '+ arry[2]+', '+arry[3]);
         
//         alert(this.LicenseeNameEle +  ", "+this.LicenseeAddressEle +  ", "+this.LicenseePhoneEle +  ", "+ this.WineryNameEle+  ", "+this.WineryAddressEle+  ", "+this.WineryPhoneEle+  ", "+this.POStatusEle);
         this.LicenseeNameEle.set('html',data.LicenseeName);
         this.LicenseeAddressEle.set('html',data.LicenseeAddress);
         this.LicenseePhoneEle.set('html',data.LicenseePhone);
         this.WineryNameEle.set('html',data.WineryName);
         this.WineryAddressEle.set('html',data.WineryAddress);
         this.WineryPhoneEle.set('html',data.WineryPhone);
         this.POStatusEle.set('html',data.POStatus);
         this.POOrderByEle.set('html',data.ContactName);
         this.POCreatedByEle.set('html',"Winery");
         //alert(this.PO.isAgentPo +"  "+ data.isImportWine)
         if(this.PO.isAgentPo == 'true' || data.isImportWine)
         {
			this.WineryNameEle.setStyle('display','none');
			this.WineryAddressEle.setStyle('display','none');
			this.WineryPhoneEle.setStyle('display','none');
			this.LDBshiptomeButton .setStyle('display','');
			this.LDBshiptomeLabel.setStyle('display','');
			this.LDBpickupButton.setStyle('display','');
			this.LDBpickupLabel.setStyle('display','');
			if(data.Pickupplaceuid != "")
			{
			    this.WineryPhoneEle.getNext('div').getElement('select').value = data.Pickupplaceuid;
			    this.WineryPhoneEle.getNext('div').getElement('select').getNext('span').set('html',data.PickupplaceAddress);
			}
			this.WineryPhoneEle.getNext('div').getLast('span').set('text',data.POUID);
			this.WineryPhoneEle.getNext('div').getLast('span').getPrevious('span').set('text',data.Ispickup);
			new LdbOrWineryTable(this.LDBTableEle);
			//this.WineryPhoneEle.getNext('table').setStyle('display','');
         } 
         else
         {
			this.WineryNameEle.setStyle('display','');
			this.WineryAddressEle.setStyle('display','');
			this.WineryPhoneEle.setStyle('display','');
			 this.isSpan.setStyle('display','none');
			 this.WineryAddressEle.getNext('span').setStyle('display','none');
//			this.LDBshiptomeButton .setStyle('display','none');
//			this.LDBshiptomeLabel.setStyle('display','none');
//			this.LDBpickupButton.setStyle('display','none');
//			this.LDBpickupLabel.setStyle('display','none');
         }
         if(data.isImportWine)
         {
			
         }
         else{
			 var warehouses = data.WareHousesObject;
			 this.WarehouseEle.length = 0;
			 if(data.isWineAgent == "true")
			 {
				this.WarehouseEle.setStyle('display','none');
				this.WarehouseEle.getPrevious('span').setStyle('display','none');
			 }	
			 for(var i=0; i<warehouses.length; i++){
				var warehouse = warehouses[i];            
				var option = new Element("option");
				//var option=document.createElement("option")
				option.value = warehouse.UID;
				option.text = warehouse.Name;
			   if(navigator.userAgent.indexOf("MSIE")>0)
			   {
//					 if(warehouse.isdefault == 'True')
//						 {
//							option.selected = true;
//							this.defaultwarehouseid = option.value;
//						 }
                     if(option.value == data.defaultwarehouseuid)
                     {
                          option.selected = true;
					      this.defaultwarehouseid = option.value;
                     }
					 this.WarehouseEle.add(option);
	                 
	                
				}
				else
				{
//				     if(warehouse.isdefault == 'True')
//					 {
//						option.selected = true;
//						this.defaultwarehouseid = option.value;
//					 }
					 if(option.value == data.defaultwarehouseuid)
                     {
                          option.selected = true;
					      this.defaultwarehouseid = option.value;
                     }
				  option.inject(this.WarehouseEle);
				}  
	                   
			 }
			// if(data.IsManager  && data.isWineAgent != 'true') bug 7392
			 if( data.isWineAgent != 'true')
			 {
				if(this.WarehouseEle.value == this.SysCwUid)
				{
					this.PO.PaymentMethodEle.setStyle('display','');
				}
				else
				{
					this.PO.PaymentMethodEle.setStyle('display','none');
				}
				this.WarehouseEle.removeEvents();
				this.WarehouseEle.addEvent('change',function(e){
					 new Event(e).stop();
					this.PO.POControl.ChangeWarehouse(this.WarehouseEle.value,data);
				}.bind(this));
			 }
			// alert(data.wareAskAgain);
			 this.warehouseaskagainele.set('html',data.wareAskAgain);
			 this.warehouselastchoiceele.set('html',data.wareLastchoice);
	     }
         if(data.isWineAgent == 'true')
         {
			this.POCreatedByEle.setStyle('display','none');
			this.POCreatedByEle.getParent().getPrevious('td').setStyle('display','none');
         }   
        //Show
        this.show();
    }    
});
POHeader.implement(new Options, new Events);


ProductItem = new Class({
    options: {
    
       isImportWinePO:false
    },

    initialize: function(productele, PO, options) {
		this.setOptions(options);
        this.productele = productele;
        this.isImportWinePO = this.options.isImportWinePO;
        this.PO = PO;
        this.cspcEle = this.productele.getElement('td');
        this.productNameEle = this.cspcEle.getNext();
        
        if(this.isImportWinePO)
        {
			this.priceEle = this.productNameEle.getNext().getNext().getNext();
		}
		else
		{
			this.priceEle = this.productNameEle.getNext().getNext();
		}
        
        
        this.minimumEle = this.priceEle.getNext();
        this.mutipleEle = this.minimumEle.getNext();
        this.quantitycontrolele = this.mutipleEle.getNext();
        this.amountele = this.quantitycontrolele.getNext().getElement('span');
        this.productUID = this.productNameEle.getElement('span').get('text');
        this.price = parseFloat(this.priceEle.getElement('span').get('text').replace('$',''));
        this.minimum = this.minimumEle.getElement('span').get('text');
        this.mutiple = this.mutipleEle.getElement('span').get('text');
		this.quantitycontrol = this.quantitycontrolele.getElement('div').getElement('div'); 
        var defualtValue = this.quantitycontrol.getElement('div').getElement('input');
        var initValue = defualtValue.get('value');
        this.amount = this.amountele.get('text');
        this.hiddenLineItemUid = this.amountele.getNext('span');
        this.overridable = this.hiddenLineItemUid.getNext('span').get('text');
        this.quantiy = new SpinButton(this.quantitycontrol,
            {
                Minimum: parseInt(this.minimum),
                Multiple: parseInt(this.mutiple),
                onValueChanged: (this.onValueChanged).bind(this),
                InitValue : initValue,
                InitializedWithEnable : this.PO.POUID,
                overrideable : this.overridable
            }
        ); 
        //alert(this.price + "," + this.price.substring(1,this.price.length));      
        this.initialized = true;
    },

    setQuantity: function(amount){
        this.quantiy.setQuantity(amount);
        this.updateAmount();
    },

    updateAmount: function()
    {       
       this.amount = this.formatCurrency(this.quantiy.value * this.price);          
       if(this.quantiy.value == 0)
       {
            this.amountele.set('text', '');
       }
       else
       {
            this.amountele.set('text',this.amount);
       }
 
    },

    onValueChanged: function(){
      if(!$chk(this.initialized)) return;
      this.updateAmount();
      //Infor PO to update
        this.PO.updatePO( this.productUID, this.quantiy.value,this.hiddenLineItemUid);
    },
    enable: function(){
        this.quantiy.enable();
    },
    disable: function()
    {
        this.amout = 0;
        this.amountele.set('text', '');
        this.quantiy.disable();
    },
    formatCurrency: function(strValue)
    {
     strValue = strValue.toString().replace(/\$|\,/g,'');
     dblValue = parseFloat(strValue);

     blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
     dblValue = Math.floor(dblValue*100+0.50000000001);
     intCents = dblValue%100;
     strCents = intCents.toString();
     dblValue = Math.floor(dblValue/100).toString();
     if(intCents<10)
      strCents = "0" + strCents;
     for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
      dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
      dblValue.substring(dblValue.length-(4*i+3));
     return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
    }
});
ProductItem.implement(new Options, new Events);


ProductList = new Class({
    options: {
		isImportWinePO:false
    },

    initialize: function(productlistele, PO, options) {
        this.productlistele = productlistele;
        this.PO = PO;
        this.setOptions(options);
        this.productItemList = new Hash();
        this.initializeProductList();
    },
    createItem: function(tr,quatity,itemuid,itemAmount)
    {
		var quatityTd = tr.getElement('td').getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext();
		quatityTd.getElement('input').set('value',quatity);
		quatityTd.getNext().getElement('span').set('text',itemAmount);
		quatityTd.getNext().getElement('span').getNext('span').set('text',itemuid);
		tr.getElement('td').destroy();
		tr.removeClass('classForImportWine');
		tr.addClass('ForpojsStyle');
		tr.inject(this.productlistele.getFirst().getNext().getNext().getElement('tbody'));
		this.initializeProductList();
    },
    initializeProductList : function()
    {
		this.productlistele.getFirst().getNext().getNext().getElements('.ForpojsStyle').each(function(el){
            if((el.getElements('td')).length > 3)
            {
           
		        var product = new ProductItem(el, this.PO,
		        {isImportWinePO:this.options.isImportWinePO }
		        );
		        this.productItemList.set(product.productUID ,product);
		    }
		    //alert(el.get('html'));
	    }.bind(this));
    },
    SetFocus: function()
    {
        var itemArray = this.productItemList.getValues();
        var i=0;
        this.FirstProductItem = null;
        for(;i < itemArray.length; i++)
        {
            var product = itemArray[i];
            if(product.productele.getStyle('display') != 'none')
            {
                this.FirstProductItem = product;
                break;
            }
        }
        if(this.FirstProductItem == null)
        {
            //No visible product
            return;
        }
        this.FirstQuantiy = this.FirstProductItem.quantiy;
        this.FirstQuantiyInput = this.FirstQuantiy.inputEle;
        var disabled = this.FirstQuantiyInput.getProperty('disabled');
        if(disabled == null || disabled == false)
        {
            window.setTimeout(function(){this.FirstQuantiyInput.focus();this.FirstQuantiyInput.select();}.bind(this),50);
        }
    },

    enable: function()
    {
        this.productItemList.each(function(product){
		      product.enable();
	    }.bind(this));
    },

    disable: function()
    {
        this.productItemList.each(function(product){
		      product.disable();
	    }.bind(this));
    },
    DataLoaded : function(data)
    {
        this.enable();
        //For each product
        var records = data.records;
        for(var i=0; i<records.length; i++){
            var record = records[i];
            var product = this.productItemList.get(record.ProductUID);
            //if product uid matched
            if(product)
            {
		        product.setQuantity(record.ProductQuantity);
		    }
	    }
    },
    LoadProducts:function(productsList)
    {
       var  Table = this.productlistele.getFirst().getNext().getNext().getElement('table');
         for(var i=Table.rows.length-1;i>0;i--)
          {
                //Table.deleteRow(i);
                var currentProductRow = Table.rows[i]; 
                var productUid=  currentProductRow.getElement('td').getNext().getElement('span').get('text');
                var hasThisProduct = 0;
                for(var j=0;j<productsList.length;j++)
                {
                    if(productsList[j].UID == productUid)
                    {
                      hasThisProduct = 1; 
                      break;
                    }
                 }
                if(hasThisProduct == 0)
                {
                    currentProductRow.setStyle('display','none');
                }else
                {
                   currentProductRow.setStyle('display','');
                } 
                
           }
    }
});
ProductList.implement(new Options, new Events);


ReviewWindow = new Class({
		options: {
		WidthOfWindow:645,
		HeightOfWindow:518
		},
		initialize: function(ele, options) {
			this.setOptions(options);
			this.element = ele;
			var contentContainer = ele.getNext('div');
			var content =  contentContainer.getElement('span');
			var title = content.getNext('span');
			this.content = content;
			this.title = title; 
			ele.removeEvents('click');
			ele.addEvent('click', function(e){
				this.ShowContentWindow();
				new Event(e).stop();
			}.bind(this));
		},
		ShowContentWindow: function() {
			var yValue= (window.screen.availHeight -this.options.HeightOfWindow)/2 +document.documentElement.scrollTop - 150  ;
			if(yValue <0 )
			{
				yValue = 0 ;
			}
			var xValue= (window.screen.availWidth-this.options.WidthOfWindow)/2;
			if(navigator.userAgent.indexOf("MSIE")>0)
			{
				xValue= (document.getSize().x-this.options.WidthOfWindow)/2;
			}
			var clone = new IFrame({
				src: 'blank.html',
				styles: {
							width: this.options.WidthOfWindow,
							height: this.options.HeightOfWindow,
							border: '0px'
						},
				events: {
							load: function(){
								get_iframe_container(clone).innerHTML = this.content.get('html');
							}.bind(this)
						}
			});

			var tips =this.title.clone();
			var showTitle;
			if(clone)
				clone.setStyle('display','');
			if(tips)
				showTitle=tips.get('text');
			var openWindow = $('WineReviewWindow');
			if(openWindow){
				MochaUI.closeWindow(openWindow);
				(function(){
					new MochaUI.Window({
							id: 'WineReviewWindow',
							title:showTitle,
							content: clone,
							resizable: false,
							resrict: false,
							draggable:false,
							width: this.options.WidthOfWindow,
							height: this.options.HeightOfWindow,
							padding: { top: 0, right: 0, bottom: 0, left: 0 },
							scrollbars: false,
							x: xValue,
							y:yValue
					});
				}.bind(this)).delay(150);
			}
			else{
				new MochaUI.Window({
					id: 'WineReviewWindow',
					title: showTitle,
					content: clone,
					resizable: false,
					resrict: false,
					draggable:false,
					width: this.options.WidthOfWindow,
					height: this.options.HeightOfWindow,
					padding: { top: 0, right: 0, bottom: 0, left: 0 },
					scrollbars: false,
					x: xValue,
					y:yValue
	                
				});
				clone.getChildren().erase('style');
			}
		}
	});
ReviewWindow.implement(new Options, new Events);
	window.addEvent('domready', function(){
				$$('.ReviewWindow').each(function(element,index){
				new ReviewWindow(element);
			}); 
		});
       
   
WineReview = new Class({
		Extends: ReviewWindow,
		ShowContentWindow: function() 
		{
			this.parent();
			this.element.getParent().getParent().setStyle('display','none');	
		}	
	});
	window.addEvent('domready', function(){
			$$('.WineReview').each(function(element,index){
				new WineReview(element,{WidthOfWindow: 645,
										HeightOfWindow:345
				});  
		}); 
	});
       
LicenseeNewPO = new Class({
		options: {
			},
		initialize: function(PO, options) {
			this.options = options;
			this.PO = PO;
			//alert($('LicenseeNumber'));
			this.licenseeNumberEle = $('LicenseeNumber');
			if(this.licenseeNumberEle == null)
			{
				this.HiddenLicenseeUIDEle = document.getElement('.HiddenLicenseeUID');
				var curLicenseeUID = this.HiddenLicenseeUIDEle.value;
				if(curLicenseeUID.length > 0)
				{
					this.GetNewPO(curLicenseeUID,curLicenseeUID);                       
				}
                     //alert(this.PO.ProductList);
                     //this.PO.ProductList.SetFocus();
				return;
			}
			this.licenseeNameEle = $('LicenseeName');
			var onNumberSelected = (this.NumberSelected).bind(this);
			var onNameSelected = (this.NameSelected).bind(this);
									{
										window.setTimeout(function(){this.licenseeNumberEle.focus();this.licenseeNumberEle.select();}.bind(this),50);
									}
			this.licenseeNumberAC = new Autocompleter.Request.HTML(this.licenseeNumberEle, 'LicenseeSearchSuggest.aspx', {
				'indicatorClass': 'autocompleter-loading', // class added to the input during request
				onSelection : onNumberSelected
			});
			this.licenseeNameAC = new Autocompleter.Request.HTML(this.licenseeNameEle, 'LicenseeSearchSuggestByName.aspx', {
				'indicatorClass': 'autocompleter-loading', // class added to the input during request
				onSelection : onNameSelected
			});    
                /*
                new Autocompleter.Request.HTML(inputWord, 'adsd.apsx', {
		            'indicatorClass': 'autocompleter-loading' // class added to the input during request
		            //on selected, SearchNewPO(wineryid, licenssid, licenseeName, licenseeNumber)
	            });
                */
                
                //var curLicenseeUID = this.HiddenLicenseeUIDEle.value;
                
               /* if(curLicenseeUID.length > 0)
                {
                    this.SelectLicenseeDiv.setStyle('display','none');
                    this.LicenseeSeniorSearchDiv.setStyle('display','none');
                    this.LicenseeSeniorSearchBodyDiv.setStyle('display','none');
                    this.GetNewPO(curLicenseeUID,curLicenseeUID);
                }*/
                
              
			this.licenseeNumberEle.addEvent('blur',function(e){                   
					new Event(e).stop(); 
					//this.SearchByLicenseeNumber();
			}.bind(this)); 
            },
			SearchByLicenseeNumber: function (){
		
			this.LicenseeNumber = this.licenseeNumberEle.get('value');
               
			var reqURL = 'SearchLicenseeByLicenseeNumber.aspx?licenseeNumber='+this.LicenseeNumber;
               
			if(this.LicenseeNumber.length > 0) 
			{
				var jsonRequest = new Request.JSON({
												url: reqURL,
												onComplete: function(licenseeInfo){
												this.GetLicensee(licenseeInfo);
												}.bind(this)
									}).get();
			}
		        
		      /*  if(this.LicenseeNumber.length > 0) 
                {
                    var searchRequest = new Request({
			            url: reqURL,
			            onSuccess: function(responseText){
				            this.GetLicensee(responseText);
			            }.bind(this)
		            }).get();
		        }*/
		        
		        
            },
            
           /* GetLicensee: function (responseText){
              
               if(responseText.length > 0)
               { //alert(responseText.length);
                 this.licenseeNumberAC.prefetch();
               }
               
            },*/            
            
			GetLicensee: function (licenseeInfo){
				this.licenseeNumberAC.observer.setValue(licenseeInfo.LicenseeNumber);
				this.licenseeNameAC.observer.setValue(licenseeInfo.LicenseeName);
				//this.GetNewPO(licenseeInfo.WineryID,licenseeInfo.LicenseeUID);
			},
            
            
			NumberSelected: function (element, selected, value, input){
				var licenssid = selected.getProperty('id');
				var licenseeName = selected.getProperty('lname');
				var wineryid = selected.getProperty('wid');
				this.licenseeNameAC.observer.setValue(licenseeName); 
                //$('SelectedLicenseeUID').value=licenssid;
		        //$('WineryID').value=wineryid;
                //Invoke SearchNewPO
				this.GetNewPO(wineryid,licenssid);
			},
            
			NameSelected: function (element, selected, value, input){
                var licenssid = selected.getProperty('id');
                var licenseeNumber = selected.getProperty('lnumber');
                var wineryid = selected.getProperty('wid');
                this.licenseeNumberAC.observer.setValue(licenseeNumber); 
                //$('SelectedLicenseeUID').value=licenssid;
		        //$('WineryID').value=wineryid;
                //Invoke SearchNewPO
                this.GetNewPO(wineryid,licenssid);
            },
         
            /*SearchNewPO: function(wineryid, licenssid, licenseeName, licenseeNumber) {
                this.licenseeNumberAC.observer.setValue(licenseeNumber);
                this.licenseeNameAC.observer.setValue(licenseeName);
                this.GetNewPO(licenssid, wineryid);
            },*/
            SearchNewPO: function(myLinkElem) {
                var ele = $(myLinkElem.id);
                SearchDisplayDetail();
                this.licenseeNumberAC.observer.setValue(ele.getProperty('lnumber'));
                this.licenseeNameAC.observer.setValue(ele.getProperty('lname'));
                this.GetNewPO(myLinkElem.getProperty('wid'),ele.getProperty('id'));
            },

            GetNewPO: function(wineryid, licenssid) {
                if(wineryid != "" && licenssid != "")
                {
                    this.PO.getPO(wineryid, licenssid);
                }
                //New request to get PO Detail and Product list
                //With parameter: this.wineryid, this.licenssid
                //on Load: involke onContentLoaded

                //Show loading
                //alert(licenseeName);
            },

            onContentLoaded: function() {
                //hide loading
                //update the content
            }
        });
        LicenseeNewPO.implement(new Options, new Events);
        
        
PONotes = new Class({
    options: {
        NoteValue:'',
        POUID : '0'
    },

    initialize: function(notesele,PO,options) {
        this.notesele = notesele; 
        this.setOptions(options);      
        this.PO = PO;
       
        this.options = options;
        this.PoUidEle = this.notesele.getElement('input');
        this.NotesEle = this.notesele.getElement('textarea');
        this.notes = this.NotesEle.value; 
           
        this.NotesEle.addEvent('blur',function(e){
             new Event(e).stop();
             this.SaveNotes();
             }.bind(this))
        if(this.options.POUID != '0')
        {   
        
          this.notes = this.options.NoteValue;
          this.NotesEle.set('value',this.options.NoteValue); 
          this.show();
          
        }
        else{ 
        this.hide();
        }         
         
    },

    hide:function(){
        this.notesele.setStyle('display', 'none');        
    },

    show:function(){
        this.notesele.setStyle('display', 'block');        
    },
    
    DataLoaded:function(data){       
        this.NotesEle.set('value',data.PONotes); 
        this.show();
    },
    SaveNotes:function(){ 
         this.notes = this.NotesEle.value;
         this.notes =encodeURIComponent(this.notes);
         var reqURL = 'SavePurchaseOrderNotes.aspx?poNotes='+ this.notes.replace(/\n/g,"<br/>") + '&PurchaseOrderUID=' + this.PO.POUID;
         //alert(reqURL)
        // var req = new Request({url:reqURL}).send();    
        var jsonRequest = new Request({
			            url: reqURL,
			            onSuccess: function(checkValue){
			             if(checkValue == 'true')
			             {
			             }
			             else
			             {
			               alert(checkValue);
			               window.location.reload();
			             }
			            }.bind(this)
		            }).send();
    }
});
PONotes.implement(new Options, new Events);

POSummary = new Class({
    options: {

    },

    initialize: function(posummaryele,options) {
        this.posummaryele = posummaryele;        
        this.options = options;
        var spans = this.posummaryele.getElements('span');
        this.subtotalEle = spans[1];
        this.discountFactorEle = spans[2];
        this.discountTotalEle = spans[3];
        this.litterEle = spans[5];
        this.TotalEle = spans[7];
    },

    hide:function(){
        this.posummaryele.setStyle('display', 'none');        
    },

    show:function(){
        this.posummaryele.setStyle('display', 'block');        
    },
    
    DataLoaded:function(data){
       this.subtotalEle.set('text', data.POSubtotal);
       this.discountFactorEle.set('text', 'Discount ('+data.PODiscountFactor+'):');
       this.discountTotalEle.set('text', data.PODiscountTotal);
       this.litterEle.set('text', data.POLitter);
       this.TotalEle.set('text', data.POTotal);
       this.show();
   }
});
POSummary.implement(new Options, new Events);

POControl = new Class({
    options: {

    },

    initialize: function(pocontrolele,PO,options) {
        this.SysCwUid="14c16894-aeb2-4f5d-84a1-094d83d25ccb";
        this.pocontrolele = pocontrolele;
        this.PO = PO;       
        this.options = options;

        this.deletePoButtonContainerEle = this.pocontrolele.getElement('td').getElement('div');
        this.generateInvoiceContainer = this.pocontrolele.getElement('td').getNext().getElement('div').getElement('div');
        this.shipCheckBoxContainerEle = this.generateInvoiceContainer.getElement('div');
        this.generateInvoiceButtonContainerEle = this.shipCheckBoxContainerEle.getNext();
       
        this.generatePoOnlyButtonContainerEle = this.generateInvoiceContainer.getNext().getNext();
        this.viewPoButtonContainerEle = this.generatePoOnlyButtonContainerEle.getNext().getNext();
        //alert(this.viewPoButtonContainerEle.get('html'));        
        this.deletePoButtonEle = this.deletePoButtonContainerEle.getElement('a');
        this.shipCheckBoxEle = this.shipCheckBoxContainerEle.getElement('input');
        this.generateInvoiceButtonEle = this.generateInvoiceButtonContainerEle.getElement('a');
        this.finalizePoButtonContainerEle = this.generateInvoiceButtonContainerEle.getNext();
         this.sendToContainerWorldEle = this.finalizePoButtonContainerEle.getNext();
        this.finalizePoButtonEle = this.finalizePoButtonContainerEle.getElement('a');
        this.generatePoOnlyButtonEle = this.generatePoOnlyButtonContainerEle.getElement('a');
        this.sendTocontainerWorldButton = this.sendToContainerWorldEle.getElement('a');
        this.viewPoButtonEle = this.viewPoButtonContainerEle.getElement('a');        
         //alert(this.shipCheckBoxEle.checked);         
         this.shipCheckBoxEle.checked = true;
         this.POheader = this.PO.POheader;
        this.WarehouseEle = this.POheader.WarehouseEle;
        this.paymethodeaskagainele =  this.PO.PaymentMethodEle.getElement('select').getNext('span').getNext('span');
        this.paymethodlastchoiceele = this.paymethodeaskagainele.getNext('span');
        //alert(this.WarehouseEle.get('html')); 
//         this.warehouseaskagainele =  this.POheader.warehouseaskagainele;
//         this.warehouselastchoiceele = this.POheader.warehouselastchoiceele;
         this.initializeEvents();  
        
        this.hide();
    },
    initializeEvents: function(){
               this.deletePoButtonEle.addEvent('click',function(e){
                 new Event(e).stop();
                 this.opeType = "DeletePO";
                 this.currentButton = this.deletePoButtonEle;
                 var confirmStr = "<P><strong>Are you sure you want to delete the purchase order?</strong></p>";
                  new ConfirmWindow("Delete PO",confirmStr, {ConfirmText: 'OK',
                                                 onConfirm: (this.ConfirmOperation).bind(this),
                                                 onCancel: (this.CancelOperation).bind(this)
                                               });  
             /* if(confirm("Are you sure you want to delete the purchase order")){
                  this.DoOperationForPO("DeletePO");                  
                 }*/
            }.bind(this));
            this.generateInvoiceButtonEle.addEvent('click',function(e){
                 new Event(e).stop();
                   this.opeType = "GenerateInvoice";
                   this.currentButton = this.generateInvoiceButtonEle;
                   var confirmStr = "This purchase order will be finalized and a new invoice against it will be generated.  No further changes will be allowed to the P.O.\n     <p><strong>Do you want to generate this invoice?</strong><p>";
                 if(this.shipCheckBoxEle.checked){
                   var confirmStr = "This purchase order will be finalized and a new invoice and Form 60 against it will be generated.  No further changes will be allowed to the P.O. or the invoice.\n   <p><strong>Do you want to generate this invoice?</strong></p>";

                 }
                 new ConfirmWindow("Generate Invoice",confirmStr, {ConfirmText: 'Generate',
                                                 onConfirm: (function(){
                                                  //disable button after click once 12-31
		                                          this.generateInvoiceButtonEle.getParent().addClass('disabled');
		                                          this.generateInvoiceButtonEle.setProperty('disabled','disabled');
		                                          this.generateInvoiceButtonEle.removeEvents();
		                                          this.generateInvoiceButtonEle.addEvent('click',function(e){new Event(e).stop();});
                                                  this.ConfirmOperation();
                                                  }).bind(this),
                                                 onCancel: (this.CancelOperation).bind(this)
                                               });                 
                 /*
                 if(confirm(confirmStr)){                 
                    this.DoOperationForPO("GenerateInvoice"); 
                  }*/
            }.bind(this));
            this.generatePoOnlyButtonEle.addEvent('click',function(e){
                 new Event(e).stop(); 
                 this.opeType = "GeneratePOOnly";
                 this.currentButton = this.generatePoOnlyButtonEle;
                 var confirmStr = " Finalizing this purchase order will prevent further changes.\n <p><strong> Do you want to finalize this purchase order?</p></strong>";
                  new ConfirmWindow("Finalize PO",confirmStr, {ConfirmText: 'Finalize',
                                                 onConfirm: (function(){
                                                 //disable button after click once 12-31
		                                             this.generatePoOnlyButtonEle.getParent().addClass('disabled');
		                                             this.generatePoOnlyButtonEle.setProperty('disabled','disabled');
		                                             this.generatePoOnlyButtonEle.removeEvents();
		                                             this.generatePoOnlyButtonEle.addEvent('click',function(e){new Event(e).stop();});
                                                     this.ConfirmOperation();
                                                 }).bind(this),
                                                 onCancel: (this.CancelOperation).bind(this)
                                               });  
                /* if(confirm(" Finalizing this purchase order will prevent further changes.\n <p><strong> Do you want to finalize this purchase order?</p></strong>")){                 
                    this.DoOperationForPO("GeneratePOOnly"); 
                  }  */             
            }.bind(this));
            this.viewPoButtonEle.addEvent('click',function(e){
                new Event(e).stop();                
                this.DoOperationForPO("ViewPO");
           }.bind(this));
           
            this.sendTocontainerWorldButton.addEvent('click',function(e){
                new Event(e).stop();   
                this.Isrushorder=this.PO.RushOrderControl.getElement('div').getElement('input').get('checked');
		        this.rushorderDate=this.PO.RushOrderControl.getElement('div').getNext('div').getElement('input').get('value');
		        this.rushorderNote=this.PO.RushOrderControl.getElement('div').getNext('div').getNext('div').getElement('input').get('value');
		        var payment= this.PO.PaymentMethodEle.getElement('select').options[this.PO.PaymentMethodEle.getElement('select').selectedIndex].text;
		        var paymentid= this.PO.PaymentMethodEle.getElement('select').get('value');
                new ContainerWorld(this.PO.POUID,1,0,this.Isrushorder,this.rushorderDate,this.rushorderNote,$('ctl00_BodyContent_invoiceNoteDetail').get('text'),paymentid,payment,this);
           }.bind(this));
           
           this.finalizePoButtonEle.addEvent('click',function(e){
                new Event(e).stop();    
                //alert(this.PO.options.isImportWinePO); 
                var text; 
                var title;
                var confirmtext;
                if(this.PO.options.isImportWinePO)
                {
                 title="Send PO to LDB";
		         text="Sending this purchase order to the LDB will finalize it, preventing further changes.\n<p></p><p></p> <p><strong> Do you want to send this purchase order?</p></strong>";
		         confirmtext="Ok";
		        }
		        else
		        {
		        title="Finalize PO";
		        text=" Finalizing this purchase order will prevent further changes.\n<p></p><p></p> <p><strong> Do you want to finalize this purchase order?</p></strong>";  
		        confirmtext="Finalize";
		        }       
                this.opeType = "FinalizeLargePo";
                 this.currentButton = this.finalizePoButtonEle;
                 var confirmStr = text;
                  new ConfirmWindow(title,confirmStr, {ConfirmText:confirmtext ,
                                                 onConfirm: (function(){ 
                                                     //disable button after click once 12-31
                                                      this.finalizePoButtonEle.setProperty('disabled','disabled');
                                                      this.finalizePoButtonEle.getParent().addClass('disabled');
                                                      this.finalizePoButtonEle.removeEvents();
                                                      this.finalizePoButtonEle.addEvent('click',function(e){new Event(e).stop();});
                                                      this.ConfirmOperation();
                                                 
                                                 }).bind(this),
                                                 onCancel: (this.CancelOperation).bind(this)
                                               });  
           }.bind(this));
           /*this.generatePoOnlyButtonEle.addEvent('blur',function(e){
                new Event(e).stop();                
                this.ReSetFocus();
           }.bind(this));
          this.viewPoButtonEle.addEvent('blur',function(e){
                new Event(e).stop();                
                this.ReSetFocus();
           }.bind(this));*/
    },
    removerAllEvents: function()
    {
        this.deletePoButtonEle.removeEvent('click');
         this.generateInvoiceButtonEle.removeEvent('click');
        this.generatePoOnlyButtonEle.removeEvent('click');
        this.viewPoButtonEle.removeEvent('click');
        this.sendTocontainerWorldButton.removeEvent('click');
        this.finalizePoButtonEle.removeEvent('click');
    },
    
    ReSetFocus:function(){
      
        this.PO.ProductList.SetFocus();        
    },

    
    hide:function(){
        this.pocontrolele.setStyle('display', 'none');        
    },

    show:function(){
        this.pocontrolele.setStyle('display', 'block');        
    }, 
    
    DataLoaded:function(data){
       //alert(!$chk(this.PO.POUID) + ',' + this.PO.POUID);
       if(!$chk(this.PO.POUID))
       {       
            return;  
       }
       else
       {
         if(data.IsManager && data.isWineAgent != 'true' && data.showRushOrder != 'true')
         { 
           this.viewPoButtonContainerEle.setStyle('display','none');  
           
           this.finalizePoButtonContainerEle.setStyle('display','none');   
            this.generateInvoiceContainer.setStyle('display','');      
			this.generatePoOnlyButtonContainerEle.setStyle('display','');
			this.sendToContainerWorldEle.setStyle('display','none');
			this.generateInvoiceButtonContainerEle.setStyle('display','');
			 this.shipCheckBoxContainerEle.setStyle('display','');
			 this.PO.RushOrderControl.setStyle('display','none');

         }
         else if( !data.IsManager && data.isWineAgent != 'true')
         {      
           this.deletePoButtonContainerEle.setStyle('display','none');
           this.generateInvoiceContainer.setStyle('display','none');
           this.generatePoOnlyButtonContainerEle.setStyle('display','none');
           this.finalizePoButtonContainerEle.setStyle('display','none');

         }
         else if(data.IsManager && data.showRushOrder == 'true')
         {    
			this.viewPoButtonContainerEle.setStyle('display','none');  
			 this.PO.RushOrderControl.setStyle('display',''); 
           this.generateInvoiceContainer.setStyle('display','');
           //this.generatePoOnlyButtonContainerEle.setStyle('display','none');
           this.generatePoOnlyButtonContainerEle.setStyle('display','');
           this.finalizePoButtonContainerEle.setStyle('display','none');
           this.shipCheckBoxContainerEle.setStyle('display','none');
           this.sendToContainerWorldEle.setStyle('display','');
           this.sendTocontainerWorldButton.setStyle('display','');
           this.generateInvoiceButtonContainerEle.setStyle('display','none');

         }
         else
         {
           this.generateInvoiceButtonEle.setStyle('display','none');
           this.generatePoOnlyButtonContainerEle.setStyle('display','none');
           this.viewPoButtonContainerEle.setStyle('display','none');  
           this.shipCheckBoxContainerEle.setStyle('display','none');
           $('ctl00_BodyContent_InvoicenotesEditPanel').setStyle('display','none');
         }
         this.show();
       }       
    },
    
	ConfirmOperation:function(){
		
		window.setTimeout(function(){this.currentButton.focus();}.bind(this),50);
		this.DoOperationForPO(this.opeType);        
	},
   
   CancelOperation:function(){
		
        window.setTimeout(function(){this.currentButton.focus();}.bind(this),50);
        return;             
    }, 
    
   PageRedirect:function(urlStr){
       window.location.href = urlStr;       
    }, 
    
   DoOperationForPO:function(operationType){
    //alert(this.PO.POUID+ "," + operationType + "," + this.shipCheckBoxEle.checked);
        if(operationType == "ViewPO"){
            window.location.href = "../winery/purchaseordereditor.aspx?PurchaseOrderUID=" + this.PO.POUID;
           /* var reqURL = 'DoOperationForPO.aspx?PurchaseOrderUID='+ this.PO.POUID + '&operationType=' + operationType + '&shipChecked=none';
            alert(reqURL);
            var opeReq = new Request({url: reqURL,
                                      onSuccess:function(responseText){window.location.href = responseText;}
                                      }).send();*/
              
        }
        else{
            this.Isrushorder=this.PO.RushOrderControl.getElement('div').getElement('input').get('checked');
	        this.rushorderDate=this.PO.RushOrderControl.getElement('div').getNext('div').getElement('input').get('value');
	        this.rushorderNote=this.PO.RushOrderControl.getElement('div').getNext('div').getNext('div').getElement('input').get('value');
			var newDateString = (new Date()).toDateString();
			var arry = newDateString.split(' ');
			var form60date = arry[1]+' '+ arry[2]+', '+arry[3];
            var invoicenotes = $('ctl00_BodyContent_invoiceNoteDetail').get('text');
            var reqURL = 'DoOperationForPO.aspx?PurchaseOrderUID='+ this.PO.POUID + '&operationType=' + operationType + '&shipChecked=' + this.shipCheckBoxEle.checked +'&warehouseUID=' + this.WarehouseEle.value + '&invoicesNotes='+ invoicenotes+'&form60Date='+form60date+'&Isrushorder='+this.Isrushorder+'&rushorderDate='+this.rushorderDate+'&rushorderNote='+this.rushorderNote;
            var opeReq = new Request({url: reqURL,
                                      onSuccess:function(responseText){
                                        var str = responseText.split('#');
                                        responseText = str[0];
                                            if(responseText == 'onhold')
                                            {
                                                new Popupwindow("Warning:","You cannot create an invoice for "+str[1]+" while this Licensee is 'On Hold'",{ ConfirmText: 'OK'});
                                                this.removerAllEvents();
                                                this.initializeEvents();
                                                this.generatePoOnlyButtonEle.getParent().setProperty('disabled','');
                                                this.generatePoOnlyButtonEle.getParent().setProperty('class','');
                                                this.generatePoOnlyButtonEle.getParent().addClass('FFButton');  
                                                 this.generateInvoiceButtonEle.getParent().setProperty('disabled','');
                                                this.generateInvoiceButtonEle.getParent().setProperty('class','');
                                                this.generateInvoiceButtonEle.getParent().addClass('FFButton');                                             
                                            }
                                            else
                                            {
                                                window.location.href = responseText;
                                            }
                                        }.bind(this)
                                      }).send();
        }  
   },
   	/// <name>GetLastChoiceAndDoOperation</name>
    /// <summary>
    /// Judge how to do the operation : pop up window or update or do nothing
    /// </summary>
    /// <param name="operationType">warehouse or payment method</param>
    GetLastChoiceAndDoOperation: function (operationType)
    {
        var reqURL = 'SetDefaultWarehouseOrPaymentMethod.aspx?PurchaseOrderUID='+ this.PO.POUID + '&operationType=getwpset&askmeagain=false&ischangedefualt=false&defaultwarehouseid='+this.PO.POheader.WarehouseEle.get('value')+'&methodid=null';
        var opeReq = new Request.JSON({url: reqURL,
            onSuccess:function(data){
                if(operationType=="Warehouse")
                {
                    if(data.warehouseaskagain=="true" && data.warehouselastchoice=="true")
                    {
                        this.UpdateMethod("true","true","Warehouse");                        
                    }
                    else if(data.warehouseaskagain=="false")
                    {
                        this.OpenNewWindow("Warehouse");
                    }
                }
                else
                {
                    if(data.paymethodeaskagain=="true" && data.paymethodlastchoice=="true")
                    { 
                        this.UpdateMethod("true","true","payment method");                        
                    }
                    else if(data.paymethodeaskagain=="false")
                    {
                        this.OpenNewWindow("Payment Method ");
                    }
                }

        }.bind(this)}).send();
    },
    
   ChangePaymentmethod : function(data)
   {
	   if(this.PO.defaultpaymentmethodid != this.PO.PaymentMethodEle.getElement('select').get('value'))
		{
		     this.GetLastChoiceAndDoOperation("Payment Method ")
        }
   },
   
   ChangeWarehouse : function(text,data)
   {
		if(text == this.SysCwUid && data.allowRushOrder == 'true')
		{
			data.showRushOrder = 'true';
		}
		else
		{
			data.showRushOrder = 'false';
		}
		if(text == this.SysCwUid)
		{
			this.PO.PaymentMethodEle.setStyle('display','');
		}
		else
		{
			this.PO.PaymentMethodEle.setStyle('display','none');
		}
		this.SetDefaultWareHouse();
		this.DataLoaded(data);
   },
   
    SetDefaultWareHouse : function()
    {
        if(this.PO.POheader.defaultwarehouseid != this.PO.POheader.WarehouseEle.get('value'))
        {
             this.GetLastChoiceAndDoOperation("Warehouse");
        }
    },
    /// <name>OpenNewWindow</name>
    /// <summary>
    /// pop up window when change warehouse or payment method
    /// </summary>
    /// <param name="operationType">warehouse or payment method</param>
    OpenNewWindow : function(operationType)
    {
        var paramName;
        if(operationType=="Warehouse")
        {
            paramName=this.PO.POheader.WarehouseEle.options[this.PO.POheader.WarehouseEle.selectedIndex].text;
        }
        else
        {
            var paysel=this.PO.PaymentMethodEle.getElement('select');
            paramName=paysel.options[paysel.selectedIndex].text;
        }
        new Popupwindow("Update Default "+operationType,createTabel(paramName,this.PO.POheader.LicenseeNameEle.get('text'),operationType),{windowHeight:150,windowWidth:410,footerHeight:80});
        
        var buttondiv = createbuttondiv(operationType);
        var confirmButton = buttondiv.getElement('li');
        var cancelButton=confirmButton.getNext('li');
        var checkbox = buttondiv.getParent('div').getParent('div').getParent('div').getParent('div').getParent('div').getNext('div').getElement('input');
        confirmButton.addEvent('click',function()
        {
            this.UpdateMethod(checkbox.checked,"true",operationType);
        }.bind(this));
        cancelButton.addEvent('click',function()
        {
            this.UpdateMethod(checkbox.checked,"false",operationType);
        }.bind(this));
    },
    /// <name>UpdateMethod</name>
    /// <summary>
    ///  update default warehouse or payment method
    /// </summary>
    /// <param name="askmeagain">whether check 'don't ask me again'</param>
    /// <param name="ischangedefualt">whether update when change</param>
    /// <param name="operationType">warehouse or payment method</param>
    UpdateMethod : function(askmeagain,ischangedefualt,operationType)
    {
        var methodid;
        if(operationType!="Warehouse")
        {
            methodid= this.PO.PaymentMethodEle.getElement('select').get('value');
            operationType = "payment";
        }
        var reqURL = 'SetDefaultWarehouseOrPaymentMethod.aspx?PurchaseOrderUID='+ this.PO.POUID + '&operationType=' + operationType+'&askmeagain='+askmeagain+'&ischangedefualt='+ischangedefualt+'&defaultwarehouseid='+this.PO.POheader.WarehouseEle.get('value')+'&methodid='+methodid;
        var opeReq = new Request({url: reqURL,
            onSuccess:function(responseText){
                if(responseText == 'success')
                {
                    this.PO.POheader.defaultwarehouseid = this.PO.POheader.WarehouseEle.get('value');
                    if(operationType == "Warehouse")
                    {
                        this.PO.POheader.warehouseaskagainele.set('text',askmeagain);
                        this.PO.POheader.warehouselastchoiceele.set('text',ischangedefualt);
                        this.PO.POheader.defaultwarehouseid = this.PO.POheader.WarehouseEle.get('value');
                    }
                    else
                    {
                        this.paymethodeaskagainele.set('text',askmeagain);
                        this.paymethodlastchoiceele.set('text',ischangedefualt);
                        this.PO.defaultpaymentmethodid = methodid;
                    }
                }
                else if(responseText == "notChange")
                {
                    if(operationType == "Warehouse")
                    {
                        this.PO.POheader.warehouseaskagainele.set('text',askmeagain);
                        this.PO.POheader.warehouselastchoiceele.set('text',ischangedefualt);
                    }
                    else
                    {
                        this.paymethodeaskagainele.set('text',askmeagain);
                        this.paymethodlastchoiceele.set('text',ischangedefualt);
                    }
                }
                closePopWindow();
            }.bind(this)
        }).send();
    } 
});
POControl.implement(new Options, new Events);

ConfirmWindow = new Class({
    options: {
        windowID: 'ConfirmWindow',
        ConfirmText: 'OK',
        CancelText: 'Cancel',
        onConfirm: $empty,
        onCancel: $empty,
        windowHeight : 150,
        windowWidth :400
    },
    
    initialize: function(title,confirmStr, options){
        this.title = title;
        this.confirmStr = confirmStr;
        this.setOptions(options);

        var contentWrapper = new Element('div');
        this.contentWrapper = contentWrapper;
        var content = new Element('div');
        content.set('html', confirmStr);
        content.inject(contentWrapper);

        var buttonWrapper = new Element('div');
        buttonWrapper.setStyles({
		    'text-align': 'center',
		    'position' : 'absolute',
		    width: this.options.windowWidth,
		    left: 0,
		    bottom : 45
		});
        buttonWrapper.inject(contentWrapper);

        var confirmButton = new Element('a');
        confirmButton.addClass('FFButton');
        // window.setTimeout(function(){confirmButton.focus();}.bind(this),50);
        confirmButton.inject(buttonWrapper);
        confirmButton.set( 'text', this.options.ConfirmText);
        confirmButton.set( 'href', '#');
        confirmButton.set( 'tabindex', '1');
        confirmButton.addEvent('click',function(e){
             new Event(e).stop();
             this.confirm();
        }.bind(this));
        confirmButton.addEvent('blur',function(e){
                new Event(e).stop();                
                window.setTimeout(function(){this.cancelButton.focus();}.bind(this),50);
		}.bind(this));
        new FFButton(confirmButton,{center: true});
        this.confirmButton = confirmButton;

        var cancelButton = new Element('a');
        cancelButton.addClass('FFButton');
        cancelButton.set( 'text', this.options.CancelText);
        cancelButton.set( 'href', '#');
        cancelButton.inject(buttonWrapper);
        cancelButton.set( 'tabindex', '1');
        cancelButton.addEvent('click',function(e){
             new Event(e).stop();
             this.cancel();
        }.bind(this));
        cancelButton.addEvent('blur',function(e){
                new Event(e).stop();                
                window.setTimeout(function(){this.confirmButton.focus();}.bind(this),50);
		}.bind(this));
        new FFButton(cancelButton,{center: true});
        this.cancelButton = cancelButton;


        var yValue= (window.screen.availHeight   -150)/2 +document.documentElement.scrollTop - 250; 
        this.window = new MochaUI.Window({
					id: this.options.windowID,
					title: title,
					content: contentWrapper,
					closable: false,
					type: 'modal',
					//headerStartColor: [0,0,22],
					//headerStopColor: [0,0,22],
					width: this.options.windowWidth,
					height: this.options.windowHeight,
					y: yValue
				});
		this.setDefaultFocus();

	},
	setDefaultFocus: function(){
		window.setTimeout(function(){this.confirmButton.focus();}.bind(this),500);
	},
	confirm: function(){
	    var openWindow = $(this.options.windowID);
	    this.removeAllEvents();
	    MochaUI.closeWindow(openWindow);
	    //alert(this.options.onConfirm);
	    (function(){this.fireEvent('onConfirm');}.bind(this)).delay(200);
	},
	cancel: function(){
	    var openWindow = $(this.options.windowID);
	    this.removeAllEvents();
	    MochaUI.closeWindow(openWindow);
	    //alert(this.options.onCancel);
	    (function(){this.fireEvent('onCancel');}.bind(this)).delay(200);
	},
	removeAllEvents: function(){
		this.cancelButton.removeEvents('blur');
		this.cancelButton.removeEvents('blur');
	}
});

ConfirmWindow.implement(new Options, new Events);

CancelWindow = new Class({
	Extends: ConfirmWindow,
	initialize: function(title,confirmStr,options) {
		this.parent(title,confirmStr,options); 
		var reasonText = new Element('div');
		reasonText.set('html','<br/> <strong>Cancelation Reason: </strong>');
		this.textAreaEle = new Element('textarea');
		this.textAreaEle.set('style','width:360px;height:250px');
		this.textAreaEle.inject(reasonText);
		var tailText =  new Element('div');
		tailText.set('html','<strong>Do you want to cancel this purchase order?</strong>');
		tailText.inject(reasonText);
		reasonText.inject(this.contentWrapper);
		this.removeAllEvents();

		this.textAreaEle.addEvent('blur',function(e){
				new Event(e).stop();				
				window.setTimeout(function(){this.confirmButton.focus();}.bind(this),50);
		}.bind(this));


		this.confirmButton.addEvent('blur',function(e){
				new Event(e).stop();				
				window.setTimeout(function(){this.cancelButton.focus();}.bind(this),50);
		}.bind(this));

		this.cancelButton.addEvent('blur',function(e){
				new Event(e).stop();				
				window.setTimeout(function(){this.textAreaEle.focus();}.bind(this),50);
		}.bind(this));
		
	},
    getReason : function(){
		return this.textAreaEle.get('value');
	},
	setDefaultFocus: function(){
		window.setTimeout(function(){this.textAreaEle.focus();}.bind(this),500);
	}
});
CancelWindow.implement(new Options, new Events);	


window.addEvent('domready', function(){
    MochaUI.Modal = new MochaUI.Modal();
});


 
PreReview = new Class({
		options: {
			WidthOfWindow:645,
			HeightOfWindow:518
		},

		initialize: function(ele, options) {
			this.setOptions(options);
			this.element = ele;
			this.contentContainer = ele.getPrevious('table');
			var title = ele.getNext('span');
			this.title = title; 
			ele.addEvent('click', function(e){
				this.ShowContentWindow();
				new Event(e).stop();
			}.bind(this));
		},
            
		ShowContentWindow: function() {
                    
			var yValue= (window.screen.availHeight   -this.options.HeightOfWindow)/2 +document.documentElement.scrollTop - 150  ;
			if(yValue <0 )
			{
				yValue = 0 ;
			}
			var xValue= (window.screen.availWidth-this.options.WidthOfWindow)/2;
			if(navigator.userAgent.indexOf("MSIE")>0)
			{
				xValue= (document.getSize().x-this.options.WidthOfWindow)/2;
			}

			var content =  this.contentContainer.getElement('iframe');//.getElement('div').getNext('div');
			var data = get_iframe_data(content);
			var tips =this.title.clone();
			var showTitle;
			if(tips)
				showTitle=tips.get('text');
			var clone = new IFrame({
			src: 'blank.html',
			styles: {
				width: this.options.WidthOfWindow,
				height: this.options.HeightOfWindow,
				border: '0px'
				},
			events: {
				load: function(){;
				get_iframe_container(clone).innerHTML = data;
				}

			}
		});  
			if(clone)
				clone.setStyle('display','');
			new MochaUI.Window({
				id: 'WineReviewWindow',
				title: showTitle,
				content: clone,
				resizable: false,
				resrict: false,
				draggable:false,
				width: this.options.WidthOfWindow,
				height:this.options.HeightOfWindow,
				padding: { top: 0, right: 0, bottom: 0, left: 0 },
				scrollbars: false,
				x: xValue,
				y:yValue
	                
			});
			clone.getChildren().erase('style');
           }
	});
PreReview.implement(new Options, new Events);
window.addEvent('domready', function(){
			$$('.PreReview').each(function(element,index){
			new PreReview(element);
		}); 
	});
Undo = new Class({
    options: {

    },
    initialize: function(ele, options) {
        this.element = ele;
        this.options = options;
        this.removeLink = ele.getElement('input');
        this.productNameEle = this.removeLink.getNext('span').getNext('span');
        this.productName = this.productNameEle.get('text'); 
		this.checkIfIsUndo = this.productNameEle.getNext('span').get('text');
		this.isWinelist = this.productNameEle.getNext('span').getNext('span').getNext('span').get('text') ;
        this.removeLink.addEvent('click', function(e){
			new Event(e).stop();
			this.typeEle = this.productNameEle.getNext('span').getNext('span');
			this.operationtype = this.typeEle.get('text');
			this.productUID = this.removeLink.getNext('span').get('text');
			this.ButtonClick(this.productUID,this.operationtype);
			}.bind(this));
		},
		
	ButtonClick : function(productuid,operationtype)
	{
		var operationType = operationtype;
		var reqURL = 'AddOrRemoveWineList.aspx?operationType=' + operationType+'&ProductUid=' + productuid;
		var opeReq = new Request({url: reqURL,
									//async:false,
									link : 'ignore',
									onSuccess:function(responseText){
									//alert(responseText + ":" + this.isWinelist);
									if(responseText=='RemoveOK' && this.isWinelist == 'true')
									{
										this.undoPanel =$('ctl00_BodyContent_idForUndo');
										var undoText = this.undoPanel.getElement('span');
										undoText.set('html',this.productName+' has been removed from the Wine list.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
										this.undoPanel.setStyle('display','');
										this.element.setStyle('display','none');
										this.undoButton =this.undoPanel.getElement('a');
										this.undoButton.removeEvents();
										this.undoButton.addEvent('click', function(e){
											new Event(e).stop();
											this.ButtonClick(productuid,"Add");
										}.bind(this));
									}
									if(responseText=='AddOK'  && this.isWinelist == 'true')
										{
											this.undoPanel =$('ctl00_BodyContent_idForUndo');
											this.element.setStyle('display','');
											this.undoPanel.setStyle('display','none');
										}
									if(responseText=='RemoveOK' && this.isWinelist == 'false')
									{
										this.removeLink.setProperty('src','../Images/Icons/IconAdd.gif');
										this.typeEle.set('text','Add');
										if($chk(this.removeLink.getPrevious('img')))
										{
											this.removeLink.getPrevious('img').destroy();
											this.removeLink.getParent('td').setProperty('align','center');
										}
									}
									if(responseText=='AddOK' && this.isWinelist == 'false')
									{
										this.removeLink.setProperty('src','../Images/Icons/IconDelete.gif');
										this.typeEle.set('text','Remove');
										var BottleImgEle = new Element('img');
										this.BottleImgEle = BottleImgEle;
										this.BottleImgEle.setProperty('src','../Images/Icons/IconWineBottle.gif');
										this.BottleImgEle.setStyles(
												{
													border: 0,
													padding:'0px 5px 0px 0px'
												}
										);
										this.BottleImgEle.inject(this.removeLink,'before');
										this.removeLink.getParent('td').setProperty('align','left');
									}
								}.bind(this)
							}).send();
	}

	});
Undo.implement(new Options, new Events);

/*********************************************BCS Comments*********************************************/	
	/// <name>UTC time to local time</name>
	/// <summary>
	/// 1.Save as UTC time but show up as local time.
	/// 2.the data will reload when domready
	/// </summary>
	/// <param name="ele">The label hidden after date label</param>
/*****************************************************************************************************/

UtcTimeToLocal = new Class({
	options: {
	
	},

	initialize: function(ele, options) {
		 this.element = ele;
         this.options = options;
         var oldTime =  this.element.get('text');
		 var oldDate = new Date(oldTime);
		  //alert(oldDate);
		  var newDate = new Date(oldTime);
		  var test = new Date();
		  newDate.setHours((oldDate.getHours() - newDate.getTimezoneOffset()/60),oldDate.getMinutes(),oldDate.getSeconds() ,oldDate.getMilliseconds());
		  var newDateString = newDate.toDateString();
		  var arry = newDateString.split(' ');
		  //alert(test+' and' +test.getTimezoneOffset()/60);
		  var spanToshow =  this.element.getPrevious('span');
		  if(this.element.hasClass('invoice'))
		  {
			spanToshow.set('text',arry[1]+' '+ arry[2]+', '+arry[3]);
		  }
		  else if(this.element.hasClass('form55'))
		  {
			spanToshow.set('text','Return Date: '+arry[1]+' '+ arry[2]+', '+arry[3]);
		  }	
		  else
		  {
			spanToshow.set('text','PO Date: '+arry[1]+' '+ arry[2]+', '+arry[3]);
		  }
	}
	

});
UtcTimeToLocal.implement(new Options, new Events);

MidAirResolve = new Class({
	Implements: [Options, Events],
		options: {
			UID:'',
			Page:'',
			UpdateTime:''
		},
	initialize: function(ele,MidAirHref,options){
		this.setOptions(options);
		this.ele = ele;
		this.MidAirHref = MidAirHref;
		this.ele.addEvent('click', function(e) {
				 new Event(e).stop();
		        var strhost = window.location.host;
		        var hostUrl = "";
		        var pageUrl = "";
		        if(strhost.indexOf('localhost') != -1 || strhost.indexOf('127.0.0.1') != -1)
		        {
					hostUrl = "http://"+window.location.host+"/Ood.Website";
					pageUrl = this.options.Page.substr(12);
		        }
		        else
		        {
					pageUrl = this.options.Page;
					hostUrl = "http://"+window.location.host;
		        }
		        var reqURL = hostUrl+'/CheckIfIsMidAirError.aspx?uid='+this.options.UID+'&updateTime='+this.options.UpdateTime+'&page='+pageUrl;
				var opeReq = new Request.JSON({url: reqURL,
												onComplete:function(data){
														if(data.isMidAir=='True')
														{
															var oldDate = new Date(data.returnDate);
															var newDate = new Date(oldDate);
															newDate.setHours((oldDate.getHours() - newDate.getTimezoneOffset()/60),oldDate.getMinutes(),oldDate.getSeconds() ,oldDate.getMilliseconds());
															var dateStr = dateFormat(newDate,"mmmm dS");
															var timeStr = dateFormat(newDate,"h:MM TT");
															var titleOfWindow = "Update conflict";
															var confirmStr = "<div style='text-align:center; font-weight:bold; font-size:12pt;height:200px'><br />";
															confirmStr += "<label> This Page has been modified by another person since you opened it.</label><br /><br />";
															confirmStr += "The change was made on <label style='color:#104C7B'> "+dateStr+" </label>at <label style='color:#104C7B'>"+timeStr+"</label>";
															confirmStr += "<br /><br /><br /><br />";
															confirmStr += "<label style='color:#104C7B;padding-top:50px'>Are you sure you want to overwrite their changes?</label></div>";
															new ConfirmWindow(titleOfWindow,confirmStr, {ConfirmText: 'Yes, save your changes',
																												CancelText:'No, load their changes',
																												windowHeight:250,
																												windowWidth:560,
																												onConfirm: (this.OverWrite).bind(this),
																												onCancel: (this.CancelOperation).bind(this)
																				});
															return;
														}
														else
														{
															window.location.href=this.MidAirHref;
														}
													}.bind(this)
											}).get();
		           
	          } .bind(this));
	        
	},
	OverWrite : function()
	{
		window.location.href=this.MidAirHref;
	},
	CancelOperation : function()
	{
		var url = document.URL;
		if(url.indexOf('?') != -1)
		{
			window.location.href = url+'&random='+ Math.random()*100;
		}
		else
		{
			window.location.href = url+'?random='+ Math.random()*100;
		}
	}
});

ImportWine_Po = new Class({
		Implements: [Options, Events],
		options: {
		},

		initialize: function(ele, options) {
			this.element = ele;
			this.pouid = $('ctl00_BodyContent_hiddenLicenseeUID').get('text');
			 var hiddenTr =$('ctl00_BodyContent_poproductView').getElement('tr').getNext('tr');
			 if(hiddenTr != null && $('ctl00_BodyContent_hasImportWinePoforLicensee').style.display == 'none')
			 {
				hiddenTr.destroy();
			 }
			this.wineListEle = this.element.getElement('td');
			this.productUid = this.wineListEle.getElement('span').get('text');
			this.priceEle = this.element.getElement('td').getNext().getNext().getNext().getNext().getNext();
			this.price = parseFloat(this.priceEle.getElement('span').get('text').replace('$',''));
			this.minimumEle = this.priceEle.getNext();
			this.minimum = this.minimumEle.getElement('span').get('text');
			this.mutipleEle = this.minimumEle.getNext();
			this.mutiple = this.mutipleEle.getElement('span').get('text');
			this.quantitycontrol = this.mutipleEle.getNext().getElement('div').getElement('div'); 
			this.defualtValue = this.quantitycontrol.getElement('div').getElement('input');
			var initValue = this.defualtValue.get('value');
			this.isgreyshow = this.defualtValue.getNext().getNext().getNext().getNext();
			this.overridable = 'false';
			this.amountele = this.mutipleEle.getNext().getNext().getElement('span');
			this.amount = this.amountele.get('text');
			//bug 6895
			var finalizePOButton = $('ctl00_BodyContent_FinalizePOButton')
			if(finalizePOButton!=null)
			finalizePOButton.set('html','Send to LDB');
			
			//alert('this.pouid ='+this.pouid+' this.productUid= '+this.productUid+' this.minimum='+this.minimum+' this.mutiple='+this.mutiple+' initValue='+initValue)
			this.quantiy = new SpinButton(this.quantitycontrol,
				{
					Minimum: parseInt(this.minimum),
					Multiple: parseInt(this.mutiple),
					onValueChanged: (this.onValueChanged).bind(this),
					InitValue : initValue,
					overrideable : this.overridable,
					InitializedWithEnable : this.pouid
				}
			); 
			if(this.isgreyshow.get('text')=='true')
			{
				this.quantiy.upButton.DisableButton();
			}
			this.initialized = true;
		    new Undo(this.wineListEle);
	},
	setQuantity: function(amount){
        this.quantiy.setQuantity(amount);
        this.updateAmount();
    },

    updateAmount: function()
    {       
       this.amount = this.formatCurrency(this.quantiy.value * this.price);          
       if(this.quantiy.value == 0)
       {
            this.amountele.set('text', '');
       }
       else
       {
            this.amountele.set('text',this.amount);
       }
 
    },

    onValueChanged: function(){
      if(!$chk(this.initialized)) return;
      this.updateAmount();
      //Infor PO to update
        this.doPoUpdate();
    },
    enable: function(){
        this.quantiy.enable();
    },
    disable: function()
    {
        this.amout = 0;
        this.amountele.set('text', '');
        this.quantiy.disable();
    },
    formatCurrency: function(strValue)
    {
     strValue = strValue.toString().replace(/\$|\,/g,'');
     dblValue = parseFloat(strValue);

     blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
     dblValue = Math.floor(dblValue*100+0.50000000001);
     intCents = dblValue%100;
     strCents = intCents.toString();
     dblValue = Math.floor(dblValue/100).toString();
     if(intCents<10)
      strCents = "0" + strCents;
     for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
      dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
      dblValue.substring(dblValue.length-(4*i+3));
     return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
    },
	doPoUpdate: function() {
	if(this.quantiy.value > this.defualtValue.getNext('span').get('text') )
        {
			if(this.defualtValue.getNext('span').getNext('span').get('text') == 'True')
			{
				alert('You only have  '+this.defualtValue.getNext('span').get('text')+ ' bottles remaining in your Allocation')
			}
			else
			{
				alert('You can only order up to '+this.defualtValue.getNext('span').get('text')+ ' bottles of '+this.defualtValue.getNext('span').getNext('span').getNext('span').get('text'))
			}
			 window.setTimeout(function(){this.quantiy.inputEle.focus();this.quantiy.inputEle.select();}.bind(this),50);
			 return;
        }
	var currentpouid = $('ctl00_BodyContent_hiddenLicenseeUID').get('text');
	var data = AjaxServer.TransToAjaxServer('DoOprationImportWinePurchaseOrder.aspx?poUID='+currentpouid+'&ProductUID='+this.productUid+'&ProductQuantity='+this.quantiy.value);
	if(data != null && data != '')
	{
		data = eval('('+data+')');
	//var reqURL = 'DoOprationImportWinePurchaseOrder.aspx?poUID='+currentpouid+'&ProductUID='+this.productUid+'&ProductQuantity='+this.quantiy.value;
//	var updateRequest = new Request.JSON({
//						url: reqURL,
//						onComplete: function(data){
						var items = $$('.ForpojsStyle');
						if(data.toString() == 'false')
						{
//							alert('This purchase order statu has been changed by another contact!');
//							window.location.reload();
						}
						else
						{
							if(data.opration == 'update')
							{
								for(var i=0;i<items.length;i++)
								{
									var currentItemNameTD = items[i].getElement('td').getNext();
									var itempuid = currentItemNameTD.getElement('span').get('text');
									var quantityTD = currentItemNameTD.getNext().getNext().getNext().getNext().getNext().getNext();
									if(itempuid == this.productUid)
									{
										quantityTD.getElement('input').set('value',this.quantiy.value);
										quantityTD.getNext().getElement('span').set('text',this.formatCurrency(this.quantiy.value * this.price));
//										quantityTD.getElement('input').focus();
//										quantityTD.getElement('input').blur();
									}
									
								}
							}
							if(data.opration == 'create')
							{
									var TrForNew = new Element('tr');
									var tds = this.element.getElements('td');
									
									for(var i= 0 ;i<tds.length;i++)
									{
										var newtd = new Element('td');
										
										newtd.set('html',tds[i].get('html'));
										if(i==3||i==4||i==6||i==7)
										{
											newtd.setProperty('align','center');
										}
										if(i==9 || i==5)
										{
											newtd.setProperty('align','right');
										}
										newtd.inject(TrForNew);
									}
									
									tempPO.ProductList.createItem(TrForNew,this.quantiy.value,data.lineitemUID,this.formatCurrency(this.quantiy.value * this.price));
								
							}
							if(data.opration == 'deleteProduct')
							{
								for(var i=0;i<items.length;i++)
								{
								var currentItemNameTD = items[i].getElement('td').getNext();
								 var itempuid = currentItemNameTD.getElement('span').get('text');
								 if(itempuid == this.productUid)
									{
										items[i].destroy();
									}
								}
							}
							tempPO.DataRefresh(data);
							$('ctl00_BodyContent_QuantityLabel').set('html','Quantity: '+data.totalQuantity + '&nbsp;&nbsp;');
							$('ctl00_BodyContent_totalHeadLabel').set('text','Total: '+data.POTotal);
							if(data.opration == 'createPoAndLineItem')
							{
								tempPO.POUID = data.POUID;
								tempPO.POheader.DataLoaded(data);
								var numberOfNewPO = document.getElement('.headerMessage');
								numberOfNewPO.fireEvent('refresh');
								 $('ctl00_BodyContent_hiddenLicenseeUID').set('text',data.POUID)
								 $('ctl00_BodyContent_hasImportWinePoforLicensee').setStyle('display','');
								 if(getCookie('hiddenPoheader') == 'no')
                                  {
			                            switchHeader.displayHeader();
                                  }
								 else
								 {
								        switchHeader.DontDispalyHeader();
								 }
								 this.pouid = data.POUID;
								var TrForNew = new Element('tr');
									var tds = this.element.getElements('td');
									
									for(var i= 0 ;i<tds.length;i++)
									{
										var newtd = new Element('td');
										
										newtd.set('html',tds[i].get('html'));
										if(i==3||i==4||i==6||i==7)
										{
											newtd.setProperty('align','center');
										}
										if(i==9 || i==5)
										{
											newtd.setProperty('align','right');
										}
										newtd.inject(TrForNew);
									}
									
									tempPO.ProductList.createItem(TrForNew,this.quantiy.value,data.lineitemUID,this.formatCurrency(this.quantiy.value * this.price));
							}
							if(data.opration == 'deletePO')
							{
								for(var i=0;i<items.length;i++)
								{
								var currentItemNameTD = items[i].getElement('td').getNext();
								 var itempuid = currentItemNameTD.getElement('span').get('text');
								 if(itempuid == this.productUid)
									{
										items[i].destroy();
									}
								}
								 $('ctl00_BodyContent_hiddenLicenseeUID').set('text','');
								 $('ctl00_BodyContent_hasImportWinePoforLicensee').setStyle('display','none');
								 return;
							}
							
						}
      
		}
	}
});

SwitchDetailView = new Class({
    options: {

    },

    initialize: function(ele, options) {
        this.element = ele;
        this.options = options;
         var DetailsInfoDiv = ele.getParent().getParent().getNext('div');
         this.DetailsInfoDiv = DetailsInfoDiv;
         var imageArrow = ele.getElement('img');
         this.productListEle = this.DetailsInfoDiv.getNext().getElement('div').getNext().getNext();
         this.noteAndSummarryEle = this.productListEle.getNext('table').getElement('tr');
         this.imageArrow = imageArrow;
         if(getCookie('hiddenPoheader') == 'no')
         {
			this.displayHeader();
         }
         ele.addEvent('click', function(e){
                this.SwitchContentWindow();
			    new Event(e).stop();
		        }.bind(this));

        },
        SwitchContentWindow : function()
        {
         if(this.DetailsInfoDiv.style.display == "none"){
				SetCookie('hiddenPoheader','no');
                this.displayHeader();
          }else{ 
				SetCookie('hiddenPoheader','yes');               
               this.DontDispalyHeader();
          }
        },
        displayHeader : function()
        {
			this.DetailsInfoDiv.style.display ="";  
            this.productListEle.style.display ="";  
            this.noteAndSummarryEle.style.display ="";                
            this.imageArrow.src="../Images/Icons/IconDetailhide.gif";
        },
        DontDispalyHeader : function()
        {
			this.DetailsInfoDiv.style.display ="none";
            this.productListEle.style.display ="none";  
            this.noteAndSummarryEle.style.display ="none";  
            this.imageArrow.src = "../Images/Icons/IconDetaildisplay.gif";
        }
        });
     SwitchDetailView.implement(new Options, new Events);
     
      function SetCookie(name,value)
		{
		var Days = 30;
		var exp   = new Date();
		exp.setTime(exp.getTime() + Days*24*60*60*1000);
		document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
		}
		function getCookie(name)  
		{
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
			if(arr != null) return unescape(arr[2]); return null;
		}
		function delCookie(name)
		{
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval=getCookie(name);
		if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
		}
		
    
