/* BDI LIBRARY*/
/* BDI-Specific functions */

function loadingajax(){
alert('Please wait while each row is validated');
$('#buttonrow').hide();
$('#buttonrow2').addClass('ac_loading2');
return;
}

function SearchBDIPart(Part){
var Part1;
var Part2;
Part1 = $("#"+Part).val().length;

Part2 = document.LANSA.MINLENGTH.value;
if (Part1 >= Part2) {

LANSAObj.search2(Part);
}
else
{alert('You must key in at least ' + Part2 + ' characters.');
}
}
function SearchCustPart(Part){
var Part1;
var Part2;
Part1 = $("#"+Part).val().length;
Part2 = document.LANSA.MINLENGTH.value;
if (Part1 >= Part2) {

LANSAObj.search3(Part);
}
else
{alert('You must key in at least ' + Part2 + ' characters.');
}
}
// Global functions begin here.
var g_strTableRowTemplate = '';
var BDIlib = 
{
	global : 
	{
		init : function()
		{
			//$('.numeric').numeric();
			BDIlib.global.attachUpdateDescriptionModal();			
		},
		loadPageLevelFunctions : function(strWAMName, strWRName)
		{
			strWAMName = strWAMName.toUpperCase();
			strWRName = strWRName.toUpperCase()
			if(typeof(BDILoadLib[strWAMName]) != 'undefined')
			{
				if(typeof(BDILoadLib[strWAMName][strWRName]) != 'undefined')
				{
					var objPage = BDILoadLib[strWAMName][strWRName];
					objPage.init();
				}
			}			
		},
		attachUpdateDescriptionModal : function()
		{
  			// Update Description
			$('#UpdateDescription1,a.SaveCart').click(function (e) {
  				e.preventDefault();
  				$('#upddscpopup').modal({
      					close:(true), 
      					containerCss: ({width:'600px',height:'50px'}),
      					onShow: function (dialog) {                
         						// if the user clicks close image
         						dialog.data.find('#upddscpopupclose').click(function () {
            					// close the dialog
            					$.modal.close();
         					});
         					var objDialogData = dialog.data;
         					dialog.data.find('#updatebutton').click(function () {
            					var strValue = objDialogData.find('.LW3CTDESC1').val();
            					InsertHidden(document.LANSA, "LW3CTDESC", strValue);            
            					document.LANSA.LW3CTDESC.value = strValue;
            					InsertHidden(document.LANSA, "LW3OP20ST", 'V');          
            					document.LANSA.LW3OP20ST.value = 'V';
            					HandleEvent('WCURORD1', 'wrCRTSAV1');
         					});       
        				}      
      			});
 			});
		}
	},
	confirmBox :
	{ 
		init : function(strMessage, strWAM, strWR, STDRENTRY)
		{
			$('.confirmBox').click(function(e)
			{
				e.preventDefault();
				jConfirm(strMessage, '' , function(r){
					if(r)
					{
						InsertHidden(document.LANSA, "STDRENTRY", STDRENTRY);
						document.LANSA.STDRENTRY.value = STDRENTRY;
						submitForm(document.LANSA, strWAM, strWR, '', '');
					}
				});
			});
		}
	},
	ajxGetShipTo :
	{
		attachTrigger : function()
		{
            	$('span.ShipToPopupTrigger').click(function(){
               		var strValue = $(this).attr('nanum');
               		InsertHidden(document.LANSA, "ADNUM", strValue);
               		document.LANSA.ADNUM.value = strValue; 
               		ajxGetShipTo();
            	});
		},
		onload : function()
		{
  			var strText = this.req.responseText;
  			var dataEvl = eval(strText);
  			var list = dataEvl.LANSA.lists.LWBOD09L2;
  
  			var tmp = [];
  			tmp[0] = "<tbody id='ShipToTableBody'>";
  
  			for (var i=1;i <= list.length; i++)
  			{                             
    				var objListEntry = list[i-1];
     				tmp[i] = '<tr><td>' + objListEntry.ADNAME.value + '</td><td>';
      				if(objListEntry.ADADR1.value != ''){tmp[i] += objListEntry.ADADR1.value + '<br />';} 
					if(objListEntry.ADADR2.value != ''){tmp[i] += objListEntry.ADADR2.value + '<br />';}
					if(objListEntry.ADADR3.value != ''){tmp[i] += objListEntry.ADADR3.value + '<br />';}
					if(objListEntry.ADADR4.value != ''){tmp[i] += objListEntry.ADADR4.value;}
					tmp[i] += '</td></tr>';
  			}
  			tmp[tmp.length] = '</tbody>'
  			$('#ShipToTableBody').replaceWith(tmp.join(''));                                                                        
  			$('#ShipToTableBody tr:even').addClass('bdi-list-e');
  			$('#ShipToTableBody tr:odd').addClass('bdi-list-o');
  
  			$('#ShipToPopupContainer').modal({
     				close:(true), 
     				containerCss: ({height:'300px',width:'400px'}),
     				onShow: function (dialog) {                
        				// if the user clicks close image
        				dialog.data.find('.PopupClose').click(function () {
        					// close the dialog
        					$.modal.close();
        				});

     				}         
  			});            
		}
	},
	ajxGetItemDetails :
	{		
		onload : function()
		{
		
			var objTd = null;
			var strValue = '';
			//alert('onload');
			var dataEvl = eval(this.req.responseText);
			//alert(this.req.responseText);
			var strLine = dataEvl.LANSA.fields.LW3LINES.value;		
			//alert(strLine);
			// Go to line
			var objLine = $('td.LW3LINES[__cellvalue='+strLine+']');
			
			// BDI Product	
			objTd = objLine.siblings('td.LW3CUSPRD').eq(0);		
			if(objTd.children('.getCustPartAutocompleteOff').val() == '')
			{	
			//	strValue = dataEvl.LANSA.fields.PGPRDC.value;
			//	objTd = objLine.siblings('td.PGPRDC').eq(0);
			//BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
			//strValue = dataEvl.LANSA.fields.LW3CUSPRD.value;
			//objTd = objLine.siblings('td.LW3CUSPRD').eq(0);
			}
			else
			{
				strValue = dataEvl.LANSA.fields.LW3CUSPRD.value;
				objTd = objLine.siblings('td.LW3CUSPRD').eq(0);
				BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
				//strValue = dataEvl.LANSA.fields.PGPRDC.value;
				//objTd = objLine.siblings('td.PGPRDC').eq(0);

			}
//			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
			

			// Description
			strValue = dataEvl.LANSA.fields.PGPRDC.value;
			objTd = objLine.siblings('td.PGPRDC').eq(0);
			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
if(document.LANSA.W_TOGGLE[1].checked)
      {
//strValue = dataEvl.LANSA.fields.LW3CUSPRD.value;
//			objTd = objLine.siblings('td.LW3CUSPRD').eq(0);
//			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
}
			strValue = dataEvl.LANSA.fields.PGDESC.value;
			objTd.children('.description').text(strValue);
//			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
			objTd = objLine.siblings('td.LW3CUSPRD').eq(0);
			objTd.children('.description').text(strValue);
//strValue = dataEvl.LANSA.fields.PGPRDC.value;
//objTd.children('.partnum').text(strValue);

			// Manufacturer
			objTd = objLine.siblings('td.CTMANC').eq(0);
var manlst = dataEvl.LANSA.lists.LS_MANF;
//alert(manlst.length);
if(manlst.length > 0)
{
//alert(dataEvl.LANSA.fields.W_MANCD.value);
strValue = '<select name="LW3LISTV2.00' + strLine + '.W_MANCD" style="width:300px;" onchange="document.LANSA.STDROWNUM.value=' + strLine + ';ajxGetItemDetails();"><option> </option>';
for(var i=0; i < manlst.length; i++)
{
strValue += '<option value="' + manlst[i].W_MANFC.value + '"'
if(manlst[i].W_MANFC.value == dataEvl.LANSA.fields.W_MANCD.value)
strValue += 'selected="selected"';
strValue += '>' + manlst[i].W_MANFD.value + '</option>';
}
strValue += '</select>';
//alert(strValue);
BDIlib.ajxGetItemDetails.setCellValue(objTd, '');
objTd.html(strValue);

}
else
{
			strValue = dataEvl.LANSA.fields.CTMAND.value;
objTd.html(strValue);
			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);

}
			

			// Manufacturer Code
			objTd = objLine.siblings('td.WRKMANC').eq(0);
			strValue = dataEvl.LANSA.fields.WRKMANC.value;
			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);

			// Price
			objTd = objLine.siblings('td.LW3LPRICE').eq(0);
			strValue = dataEvl.LANSA.fields.LW3LPRICE.value;
			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);

			// Stock Level
			objTd = objLine.siblings('td.LW3STKAVL').eq(0);
			strValue = dataEvl.LANSA.fields.LW3STKAVL.value;
			BDIlib.ajxGetItemDetails.setCellValue(objTd, strValue);
document.LANSA.test.value = "";
$('#ajaximg').hide();
QOEToggle();

		},
		presubmit : function()
		{
			//alert('presubmit');
		},
		setCellValue : function(obj, str)
		{
			obj.attr('__cellvalue', str);
			obj.find('.value').text(str);
			obj.find('input').val(str);					
		}
	},
	personal_catalog_page :	
	{
		init : function()
		{
			BDIlib.confirmBox.init('Are you sure you would like to delete?',g_lxmlWAMName,g_lxmlWRName,'X');
		}
	},
	quick_order_entry_page :
	{
		init : function()
		{
			var objTable = $('#LW3LISTV2').eq(0);
			$('#LW3LISTV2').live('keyup', function(event){
				var objTarget = $(event.target);
				BDIlib.quick_order_entry_page.disableAssociatedInput(objTarget);
				BDIlib.quick_order_entry_page.setSTDROWNUM(objTarget);
			}).live('keydown', function(event){
				var objTarget = $(event.target);
				BDIlib.quick_order_entry_page.disableAssociatedInput(objTarget);
				BDIlib.quick_order_entry_page.setSTDROWNUM(objTarget);
			}).live('blur', function(event){
				var objTarget = $(event.target);
				BDIlib.quick_order_entry_page.disableAssociatedInput(objTarget);
				BDIlib.quick_order_entry_page.setSTDROWNUM(objTarget);
			});
			BDIlib.quick_order_entry_page.attachAutocomplete();
			BDIlib.quick_order_entry_page.attachErrorTooltip(objTable);

			$('#AddRowsButton').bind('click', function(){
				var arrHTML = [];
				var objFirstRow = objTable.find('tbody tr:first');

				if(g_strTableRowTemplate != '')
				{
					var strTemplate = g_strTableRowTemplate;
				}
				else
				{
					var strTemplate =	objFirstRow.html();

					// Clean Template
					strTemplate = strTemplate.replace(/<span class="?value"?>(.*?)<\/span>/gi, '<span class="value"></span>');			
					strTemplate = strTemplate.replace(/<div class="?description"?>(.*?)<\/div>/gi, '<div class="description"></div>');
					strTemplate = strTemplate.replace(/<div class="?partnum"?>(.*?)<\/div>/gi, '<div class="partnum"></div>');
					strTemplate = strTemplate.replace(/<td class="?CTMANC"?(.*?)<\/td>/i, '<td class="CTMANC" align="center" valign="Top"></td>');
					g_strTableRowTemplate = strTemplate;
				}
				var objLastRow = objTable.find('tbody tr:last');
				var intRow = objLastRow.attr('__stdrownum') * 1;
				var strEvenClass = objFirstRow.attr('__evenrc');
				var strOddClass = objFirstRow.attr('__oddrc');
				var objTbody = objTable.find('tbody');				

				var i = 0;
				for(i=1;i<=5;i++)
				{
					intRow += 1;
					var strClass = (intRow%2 == 1) ? strOddClass : strEvenClass;					
					arrHTML.push('<tr class="_dirty_ '+strClass+'" __stdrownum="'+intRow+'">');										
					var strRowNum = intRow.zeropad(4);
					var strmakdirty = "makedirty(" + strRowNum + ")";
					arrHTML.push(strTemplate.replace(/0001/g, strRowNum)
						.replace(/"01"/g, intRow)
						.replace(/>01</g, '>'+intRow+'<').replace(/value="?01"?/g, 'value="'+intRow+'"')
						.replace(/0001/g, strRowNum).replace('makedirty(1)', strmakdirty)
						);
					
					arrHTML.push('</tr>');
				
				}

document.LANSA.formvalid.value += '00000';
//alert(arrHTML);
				objTbody.append(arrHTML.join(''));
				$('tr._dirty_').each(function(){
					$(this).removeClass('_dirty_');
					$(this).find('.getBDIPartAutocomplete, .getCustPartAutocompleteOff, .numeric').val('');
				});
				BDIlib.quick_order_entry_page.attachAutocomplete();
if(strRowNum == '0035'){
alert('Maximum Rows allowed reached, please validate, add to Cart and Return to page to add more items');
$('#AddRowsButton').hide();
}
				QOEToggle();
			});
		},
		setSTDROWNUM : function(objTarget)
		{
			if(objTarget.is('input'))
			{
				var strValue = objTarget.parents('tr:first').attr('__stdrownum');
	//			alert(strValue);
				InsertHidden(document.LANSA, "STDROWNUM", strValue);
				document.LANSA.STDROWNUM.value = strValue;
			}
		},
		disableAssociatedInput : function(objTarget)
		{
			if(objTarget.is('input.getBDIPartAutocomplete'))
			{
				var objCustPart = objTarget.parents('tr:first').find('input.getCustPartAutocompleteOff');
				(objTarget.val() != '') ? objCustPart.get(0).disabled = 1 : objCustPart.get(0).disabled = 0;
			}
			else if(objTarget.is('input.getCustPartAutocompleteOff'))
			{
				var objBDIPart = objTarget.parents('tr:first').find('input.getBDIPartAutocomplete');
				(objTarget.val() != '') ? objBDIPart.get(0).disabled = 1 : objBDIPart.get(0).disabled = 0;
			}
		},
		attachErrorTooltip : function(objTable)
		{
		try
  {
objTable.find('.error[title]').qtip({
				show: 'mouseover',
				hide: 'mouseout',
				position: {
					corner: {
						target: 'topRight',
						tip: 'bottomLeft'
					}
				},
				style: {
					name: 'cream',
					tip: true
				}
			});
  }
catch(err)
  {
 // do nothing
  }
			
		},
		attachAutocomplete : function()
		{
			$(".getBDIPartAutocomplete").autocomplete({close: function(event, ui){ ajxGetItemDetails();$(".getBDIPartAutocomplete").autocomplete("disable");}
                        });
			$(".getBDIPartAutocomplete").autocomplete("disable"),
			$(".getCustPartAutocompleteOff").autocomplete({close: function(event, ui){ ajxGetItemDetails();$(".getCustPartAutocomplete").autocomplete("disable")}
                        });
			$(".getCustPartAutocompleteOff").autocomplete("disable");
}
			}
		

		};


/* BDI LOAD LIBRARY*/
/* Page-specific function load setup */
var BDILoadLib = 
{
	WACTSEL2 :
	{
		WRMAIN : 
		{
			init : function()
			{
				BDIlib.ajxGetShipTo.attachTrigger();
			}
		}
	},
	WQUICKOE :
	{
		WRMAIN :
		{
			init : function()
			{
				BDIlib.quick_order_entry_page.init();

			}
		
		}


	},
	WPERCAT1 :
	{
		WRMAIN :
		{
			init : function()
			{
				BDIlib.personal_catalog_page.init();
			}
		}
	}
}

  

function endSession() {  
 // Browser or broswer tab is closed  
 // Do sth here ...  
 $.ajax({
url: "/CGI-BIN/lansaweb?webapp=WLOGOFF1+webrtn=wrMain+ml=LANSA:XHTML+part=" + g_lxmlPartition + "+lang=ENG"
});
$.cookie("wdr", null);
}  

   

function wireUpEvents() {  
var validNavigation = false;

 /*  

 * For a list of events that triggers onbeforeunload on IE  

 * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx  

 */ 

 

   

// Attach the event keypress to exclude the F5 refresh 
 $('window').bind('keypress', function(e) { 
if(window.event && window.event.keyCode == 116)  
{ 
// Capture and remap F5  
window.event.keyCode = 505; 
 }
if(window.event && window.event.keyCode == 505)  
{ // New action for F5  
return false;  
// Must return false or the browser will refresh anyway  
}
  });  
 $('html').bind('keypress', function(e) {  

var code = (e.keyCode ? e.keyCode : e.which);

if (code == 116){  
      validNavigation = true;  
    }  
  });  

 // Attach the event click for all links in the page  
 $("a").bind("click", function() {  

 validNavigation = true;  
 });  
   
 // Attach the event submit for all forms in the page  

 $("form").bind("submit", function() {  
  validNavigation = true;  
  });  
 $("body").bind("refresh", function() {  
  validNavigation = true;  
  });  
 // Attach the event click for all inputs in the page  

 $("input[type=submit]").bind("click", function() {  
  validNavigation = true;  
 });  
 
window.onunload = function() {  
//alert(validNavigation);
    if (!validNavigation) {  
        endSession();  
     }  
} 

}  


/* Onload */
$(document).ready(function(){
	//wireUpEvents();
	BDIlib.global.init();
	BDIlib.global.loadPageLevelFunctions(g_lxmlWAMName, g_lxmlWRName);
LANSAObj = {
		  	
                        search2: function(id){
		    	var obj = $("#"+id);
			$(obj).addClass('ac_loading').blur();
 	       		obj.autocomplete("option", "source", 
                           function(request, response){
                              var elm = obj;
                              $.ajax({
                                 url: "/CGI-BIN/lansaweb?webapp=WQUICKOEA+webrtn=ajxGetBDIPart+ml=LANSA:XHTML+part=" + g_lxmlPartition + "+lang=ENG+f(PINPUT)="+elm.val(),
		                                 success: function(data){
				    $(obj).removeClass('ac_loading');
				    var theData = eval(data);
                                    response(theData);
				                               	}
                              });
                           }
                        );

	       		obj.autocomplete("enable").autocomplete("search")},

		search3: function(id){
	    	var obj = $("#"+id);
		$(obj).addClass('ac_loading').blur();
 	       		obj.autocomplete("option", "source", 
                           function(request, response){
                              var elm = obj;
                              $.ajax({
                                 url: "/CGI-BIN/lansaweb?webapp=WQUICKOEA+webrtn=ajxGetCustPart+ml=LANSA:XHTML+part=" + g_lxmlPartition + "+lang=ENG+f(PINPUT)="+elm.val(),
                                 success: function(data){
					$(obj).removeClass('ac_loading');
                                    var theData = eval(data);
                                    response(theData);
				                        }
                              });
                           }
                        );

	       		obj.autocomplete("enable").autocomplete("search");
		                        }

    	};	
	
});
//
// Validate each item row and then un-hide the button row.
// formvalid field is used to determine if the value of a given row is invalid or not .. if a 1 then is invalid and needs to be validated (old logic re-used)
// Af 10/25/10
//
function validateGetDetails(){

var str = document.LANSA.formvalid.value;
var v=1000;
	var z = 0;
	for (b=0;b<str.length;b++)
	{ 
		if(str.charAt(b) == '1')
		{
	
	var v= v + 1000;

	
			InsertHidden(document.LANSA, "STDROWNUM", b+1);
			document.LANSA.STDROWNUM.value = b+1;
	 ajxGetItemDetails();
		}
	
	}
$('#buttonrow').show();
setTimeout('closetimer();',v);
}

function closetimer(){
$('#buttonrow2').removeClass('ac_loading2');
}
