
/***************FORM Functions**************/

//Function editRequest
//Hide-Show Content Panels
//Enable-Disable Input Fields
function editRequest (requestType) {
var lovValue = requestType;
	switch(requestType){
   			case 'algn':
			$('#'+requestType).removeAttr("checked");
			lovValue = 'prds';
			$('#'+lovValue).attr('checked', 'checked');
			//Display different description
			$('#algnRequestDesc').removeClass('hideElement');
			break;
			case 'qual':
			$('#'+requestType).removeAttr("checked");
			lovValue = 'pspc';			
			$('#'+lovValue).attr('checked', 'checked');
			$('#qualRequestDesc').removeClass('hideElement');
			//Display different description
			break;
			case 'prds':
			//Display different description
			if ($('#algnRequestDesc').hasClass('hideElement')){
				null;
				}
			else {
			$('#algnRequestDesc').addClass('hideElement');			
			}
			break;	
			case 'pspc':
			//Display different description
			if ($('#qualRequestDesc').hasClass('hideElement')){
				null;
				}
			else {
			$('#qualRequestDesc').addClass('hideElement');			
			}
			break;	
			default:			
			null;
			}		


//Hide-show content panel
$('#'+lovValue+'_content').toggleClass('hideElement');

//Enable-Disable Input Fields based on parent div
	if( $('#'+lovValue+'_content').is(':visible') ) {
	    // it's visible remove disabled attribute
		$('#'+lovValue+'_content :input').filter(':input').removeAttr('disabled');

		//Show Close Panel button on the panel header
		$('#sel_'+lovValue+'_lov .closePanel').removeClass('hideElement');

		//Remove class and hide all other LOV options
		$('#sel_'+lovValue+'_lov').removeClass('lov');	
		$('.lov').addClass('hideElement');		
	}
	else {
    	// it's not visible set the disabled attribute
		$('#'+lovValue+'_content :input').filter(':input').attr('disabled', true);

		//Show Close Panel button on the panel header
		$('#sel_'+lovValue+'_lov .closePanel').addClass('hideElement');

		//Add class back on and show all other LOV options
		$('#sel_'+lovValue+'_lov').addClass('lov');
		$('.lov').removeClass('hideElement');		
	}
}




//Handles all the form validation
//Adds an Error Class when a required field is not populated.
//parameter limits the div to search
function validateInputs(element){
var lovPanel = element;
//if error return one message and highlight it related label
var errorCount = 0;

	$('#'+lovPanel+' :input:enabled').filter('.required').each(function() {

		switch($(this).attr('type')){
   			case 'textarea':		
				if ($(this).attr('value')==""|| $(this).attr('value')==null) {
					//Add Error Class to Labels - Product Finder and Others					 
					 if ($(this).attr('id').substr(4)=='_prod_code') {
						 var pfButton = 'pcf_'+$(this).attr('id').substring(0,4);
						 //Add class to label that is now on the button image
						 $('#'+pfButton).children().children().addClass('errorLabel');
					 }
					 else {
						 $(this).prev().addClass('errorLabel'); 
					 }	
					 
					 errorCount = errorCount + 1;					 
				}
				else {
   				   //Remove the Error Class since values have been added.					 
					if ($(this).attr('id').substr(4)=='_prod_code') {
						 var pfButton = 'pcf_'+$(this).attr('id').substring(0,4);
						 //Remove error class from the label text
						 $('#'+pfButton).children().children().removeClass('errorLabel');				 
					 }
					 else {
						 $(this).prev().removeClass('errorLabel'); 
					 }					 					
				}
			break;
			case 'checkbox':		
			//Get all checked inputs that have the same name attribute, if its greater than 1 it passes.			
			var elementName = $(this).attr('name');
			var checkedElements = $('#'+lovPanel+' :input[type="checkbox"][@name='+elementName+']:enabled:checked').filter('.required').length;
			
			if (checkedElements > 0) {
				$(this).parent().removeClass('errorLabel');	
			}
			else {
				//apply class on parent div
				$(this).parent().addClass('errorLabel');
  				 errorCount = errorCount + 1;					 				
			}

			break;	
			case 'radio':		
			//Get all checked inputs that have the same name attribute, if its greater than 1 it passes.			
			var elementName = $(this).attr('name');
			var checkedElements = $('#'+lovPanel+' :input[type="radio"][@name='+elementName+']:enabled:checked').filter('.required').length;
			
			if (checkedElements > 0) {
				$(this).parent().removeClass('errorLabel');	
			}
			else {
				//apply class on parent div
				$(this).parent().addClass('errorLabel');
  				 errorCount = errorCount + 1;					 				
			}

			break;	
			default:			
				if ($(this).attr('value')==""|| $(this).attr('value')==null) {
					 $(this).prev().addClass('errorLabel'); 				 
					 errorCount = errorCount + 1;					 
				}
				else {
   				   //Remove the Error Class since values have been added.					 
  					 $(this).prev().removeClass('errorLabel'); 
				}
	
	
		    }		
		});
		
		if (errorCount > 0) {
		//Return a false do not add to the Selection status
			return false;
		}
		else{
			return true;
		}		
}





//Function addRequest
//Hides sel_xxxx_lov divs
//Hides content panel divs
//Adds request to Current Selection Status portlet
//Copies values to selection status portlet
function addRequest(requestType){
var lovValue = requestType.substr(4);
var lovPanel = lovValue+'_content';
var requestName = $('#sel_'+lovValue+'_lov .requestName').text();
var errorMsg = "Please fill in the indicated fields.";

//Call Validation code and if true add request to selection, pass in container panel id
	if (validateInputs(lovPanel)) {
	
		//if prds or pspc, hide algn and qual requests and remove the lov class
		if (lovValue == 'prds') {
		  $('#sel_algn_lov').addClass('hideElement').removeClass('lov');	
		}
		if (lovValue == 'pspc') {
		  $('#sel_qual_lov').addClass('hideElement').removeClass('lov');
		}
		
		
		//Hides sel_xxxx_lov divs and close icon
		$('#sel_'+lovValue+'_lov .closePanel').addClass('hideElement');
		$('#sel_'+lovValue+'_lov').addClass('hideElement');
		//Show all other LOVs
		$('.lov').removeClass('hideElement');		
		//Hides content panel divs
		$('#'+lovValue+'_content').addClass('hideElement');
		
		//Hide Default Selection Message
		$('#selMessage').hide();
		
		
		//Adds request to Current Selection Status portlet
		var addReq = '<tr id="'+lovValue+'selStatusRow" class="requestAdded"><td class="selStatusTd">'+requestName+'</td><td class="selStatusTd selStatusActions"><a href="#" onclick="removeRequest(this.id)" id="'+lovValue+'Remove"><img src="/xxcchtml/images/remove.gif" alt="Remove" /></a></td></tr>';
		
		$('#selStatus tbody').prepend(addReq); 
	
	}
	else {
		alert(errorMsg);
	}


}

//Function removeRequest
//Remove request from status portlet
//Unhide LOV from select list.
function removeRequest(requestType){
var lovValue = requestType.substring(0,4);
//Check if the user has any panels open, make sure to close the panel first, add the lov class back, uncheck the box, and show other lovs - added to fix bug
if  ( $('.PanelContent').is(':visible') ) {
var activePanel = $('.PanelContent:visible').attr('id');
var activeRequest = activePanel.substr(0,4);
var activeLov =  'sel_'+activeRequest+'_lov';
	$('#'+activePanel).addClass('hideElement');
	$('#'+activeLov).addClass('lov');
	$('#'+activeRequest).removeAttr("checked");
	//Hide Close Panel button on the panel header	
    $('#'+activeLov+' .closePanel').addClass('hideElement');
    $('.lov').removeClass('hideElement');
	//Disable Inputs so it doesn't submit through
	$('#'+activePanel+' :input').filter(':input').attr('disabled', true);
}

//Remove line in status portlet
$('#'+lovValue+'selStatusRow').remove();
//remove checkbox
$('#'+lovValue).removeAttr("checked");
//Hide open panel
$('#'+lovValue+'_content').addClass('hideElement');
//Add's Class back on LOV
$('#sel_'+lovValue+'_lov').addClass('lov');

//if prds or pspc, also show the algn and qual requests
	if (lovValue == 'prds') {
	  $('#sel_algn_lov').removeClass('hideElement').addClass('lov');	
	}
	if (lovValue == 'pspc') {
	  $('#sel_qual_lov').removeClass('hideElement').addClass('lov');
	}
//Show request selection(remove Class)
$('#sel_'+lovValue+'_lov').removeClass('hideElement'); 

//Disable Inputs so it doesn't submit through
$('#'+lovValue+'_content :input').filter(':input').attr('disabled', true);

//if there is nothing selected then display the default message
	if ($('#selStatus tbody tr').length == 1 ) {
		$('#selMessage').show();
	}

}




/**************PRODUCT FINDER FUNCTIONS******************/


//Enable the input fields related to the product finder
//Display Product Finder
//Clear out selected results so its not cached
//Ensure that previous hide classes are removed from searches.
//Clear out search terms if defaultvalue is not listed
//Append in the search results div the request type input
//Get the request specific selection arrays
//check requestType Array, if empty, check selProdFirst array to add to selected area and handle UI
function prodFinder(requestType){
var lovValue = requestType.substr(4);
var prodSearchFieldDefault = $('#prodSearchField').val();
var manualProdCodeDefault = $('#manualProdCode').val();
//Enable the input fields related to the product finder
$('#prodFinder :input').removeAttr('disabled'); 

//Display Product Finder Pop-up
$('#greyLayer, #prodFinder').show();

//Clear out selected results so its not cached
$('#selectedData tbody').empty();
//Ensure that previous hide classes are removed from searches.
$('#prodData tbody tr').each(function(){  
	  	$(this).removeClass('hideElement');	
		//Hide the no results row, but display all the other rows 
		if ($(this).attr('id') != 'noResults') {
			$(this).css('display', '');
		}
		else {
			$(this).css('display', 'none');
		}	
	});

//Clear out searched terms if defaultvalue is not listed
	if ($('#prodSearchField').val() != prodSearchFieldDefault) {
		$('#prodSearchField').val(prodSearchFieldDefault);
	}	
	if ($('#manualProdCode').val() != manualProdCodeDefault) {
		$('#manualProdCode').val(manualProdCodeDefault);
	}		
//Append in the search results div the request type input
$('#requestProdFinder').attr('value', lovValue);

	//Get the request specific selection arrays
	reqProdCodeArray = getRequestArray(lovValue);

	//check requestType Array, if empty, check selProdFirst array to add to selected area	
	if (reqProdCodeArray.length == 0) {
		
		//Copy request array values to the selProdFirst
		for(i = 0; i < selProdFirst.length; i++) {	
  			//We store manual inputs with a prefix and handle the addition separately.
			if (selProdFirst[i].substring(0,4) == 'man_') {
			manualAddProdCode(selProdFirst[i]);		
			}
			else {
			//adding prefix that is stripped out in function  
			addProdCode('sel_'+selProdFirst[i]);		
			}
		
		}
		
	}	
	else {
	//Otherwise use request array values	
		for(i = 0; i < reqProdCodeArray.length; i++) {	
			//We store manual inputs with a prefix and handle the addition separately.
			if (reqProdCodeArray[i].substring(0,4) == 'man_') {
			manualAddProdCode(reqProdCodeArray[i]);		
			}
			else {
			//adding prefix that is stripped out in function  
			addProdCode('sel_'+reqProdCodeArray[i]);		
			}		  
		}	
	}


}



//Add selected Prod Code to the selectedData
//Remove selected row from prodData
function addProdCode(id){
var prodCode = id.substr(4);		
var prodDesc = $('#desc_'+prodCode).text();
var itemCode = $('#item_'+prodCode).text();


//Remove selected row from prodData
//	$('#'+prodCode).animate({opacity: 0},500, function(){ $(this).addClass('hideElement');  });
	$('#add_'+prodCode).addClass('hideElement'); 


//Add selected Prod Code to the selectedData
	$('#selectedData tbody').prepend('<tr id="sel_'+prodCode+'" onclick="removeProdCode(this.id);"><td class="pfActions"><a href="#" id="rem_'+prodCode+'" ><img src="/xxcchtml/images/remove.gif" alt="Remove" /></a></td><td>'+prodCode+' '+prodDesc+' '+itemCode+'</td></tr>');

}

//Remove selected row from selectedData
//Add the row back to prodData for selection
function removeProdCode(id){
var prodCode = id.substr(4);		
var prodText = $('#prod_'+prodCode).text();

//Remove selected row from selectedData
	$('#sel_'+prodCode).remove();
	
//Add the row back to prodData for selection
	$('#add_'+prodCode).removeClass('hideElement');	
	
}


//Used with manually adding a product code, added to select_data
function manualAddProdCode(id){
//Replace spaces for use with ID's	
var prodCode = id.split(' ').join('__');
var prodDesc = id;

//if the id already has a prefix, it means is in an array and being called when the product finder is opening.
if (id.substring(0,4) == 'man_') {
	prodCode = prodCode.substr(4);
	//Replace underscores with spaces for the display name.
	prodDesc = prodDesc.substr(4).split('__').join(' ');
}

//Add selected Prod Code to the selectedData
	$('#selectedData tbody').prepend('<tr id="man_'+prodCode+'" onclick="manualRemoveProdCode(this.id);"><td class="pfActions"><a href="#" id="rem_'+prodCode+'" ><img src="/xxcchtml/images/remove.gif" alt="Remove" /></a></td><td class="manualProdCodeDisplay">'+prodDesc+'</td></tr>');

}


//Remove selected row from selectedData
//Add the row back to prodData for selection
function manualRemoveProdCode(id){
var prodCode = id.substr(4);		
//Remove selected row from selectedData
	$('#man_'+prodCode).remove();	
}




//Get the RequestType
//Get the request specific selection arrays
//Ensure array is empty to add new values
//Empty Field first before adding new product codes
//Get all id's in selectedData
//Add selected prod codes to the hidden input with a delimiter. 
//Add to the the request specific array
//Add to selProdFirst if this is is the first request added
//Hide Prod Finder Divs
function addSelections (){
	
//Get the RequestType
var requestType = $('#requestProdFinder').val();
var reqProdCodeDisplay = '#'+requestType+'ProdCodeDisplay';
var reqProdCodeInput = '#'+requestType+'_prod_code';

	//Get the request specific selection arrays
	reqProdCodeArray = getRequestArray(requestType);
	//Ensure array is empty to add new values
	reqProdCodeArray.splice(0,reqProdCodeArray.length);
	
	//Empty Field display and input first before adding new product codes
	$(reqProdCodeDisplay).empty();
	$(reqProdCodeInput).empty();


//Get all id's in selectedData
   $('#selectedData tbody tr').each(function(){ 
		
		if ($(this).attr('id').substring(0,4) == 'man_') {
			var productId = $(this).attr('id');						
			var productDesc = $('#'+productId+' .manualProdCodeDisplay').text();
			$(reqProdCodeDisplay).append(productDesc+', ');	
		   //Add selected prod codes to the hidden input with a delimiter.  Remove 'man_' so its not submitted. 
		   $(reqProdCodeInput).append(productId.substr(4).split('__').join(' ')+', ');	
		}
		else {		
			var productId = $(this).attr('id').substr(4);		
		   $(reqProdCodeDisplay).append(productId.split('__').join(' ')+', ');
   		   //Add selected prod codes to the hidden input with a delimiter. 
		   $(reqProdCodeInput).append(productId.split('__').join(' ')+', ');	
		}
	   
	   //remove class on span element
		$(reqProdCodeDisplay).parent().parent().removeClass('hideElement');
	   
		//Add to the the request specific array
		if (reqProdCodeArray.length == 0) {
			reqProdCodeArray[0] = productId;
		}
		else {
			reqProdCodeArray[reqProdCodeArray.length] = productId;		
		}
	
	});

	//Add to selProdFirst if this is is the first request added
	if (selProdFirst.length == 0) {
		//Copy request array values to the selProdFirst
		for(i = 0; i < reqProdCodeArray.length; i++) {	
		  selProdFirst.push(reqProdCodeArray[i]); 		  
		  //handle the stripping out of the manual prefix
		  if (reqProdCodeArray[i].substring(0,4) == 'man_') {
			  var prodCode =  reqProdCodeArray[i].substr(4).split('__').join(' ');
		  }
		  else {
			  var prodCode =  reqProdCodeArray[i].split('__').join(' ');
		  }		  
		//Copy the selProdFirst Values to All the other inputs, remove the class to make it visible
		//Do not copy the value to this particular requestType and any request that does not have a LOV class.  This means it is in the selected request portlet.
		  $('.displayProdCodes textarea').each(function(){
				var lovValue = $(this).attr('id').substring(0,4);										
				if (lovValue != requestType && $('#sel_'+lovValue+'_lov').hasClass('lov')) {				
					$(this).append(prodCode+', ');
					$(this).parent().parent().removeClass('hideElement');					
				}				
			});
		  
		  //Append in the prod codes into the Input field
			$('.prodCodeInput').each(function(){
				var lovValue = $(this).attr('id').substring(0,4);											  
				if (lovValue != requestType && $('#sel_'+lovValue+'_lov').hasClass('lov')) {									
					$(this).append(prodCode+', ');					
				}										  
   		    }); 
		  
		}
		
	}	



//Hide Prod Finder Divs and disable inputs
$('#greyLayer, #prodFinder').hide();
$('#prodFinder :input').attr('disabled', 'disabled'); 

}



//Based on Request Type, Return the related array name
function getRequestArray (requestType){
	var arrayName;
	switch(requestType){
	case 'artg':
	  arrayName = selProdArtg;
	break;
	case 'cofa':
	  arrayName = selProdCofa;
	break;
	case '9545':
	  arrayName = selProd9545;
	break;
	case 'dmfr':
	  arrayName = selProdDmfr;
	break;
	case 'irsc':
	  arrayName = selProdIrsc;
	break;
	case 'kosh':
	  arrayName = selProdKosh;
	break;	
	case 'msds':
	  arrayName = selProdMsds;
	break;
	case 'nutr':
	  arrayName = selProdNutr;
	break;	
	case 'prds':
	  arrayName = selProdPrds;
	break;
	case 'pspc':
	  arrayName = selProdPspc;
	break;
	case 'pdye':
	  arrayName = selProdPdye;
	break;
	case 'quan':
	  arrayName = selProdQuan;
	break;
	case 'quax':
	  arrayName = selProdQuax;
	break;
	case 'rcps':
	  arrayName = selProdRega;
	break;
	case 'rega':
	  arrayName = selProdRega;
	break;
	case 'stab':
	  arrayName = selProdStab;
	break;
	case 'test':
	  arrayName = selProdTest;
	break;
	case 'uspu':
	  arrayName = selProdUvrf;
	break;	
	case 'uvrf':
	  arrayName = selProdUvrf;
	break;
	case 'genc':
	  arrayName = selProdGenc;
	break;
	case 'genq':
	  arrayName = selProdGenq;
	break;
	case 'genr':
	  arrayName = selProdGenr;
	break;		
	default:
	  null;
	}
	return arrayName;	
}












