dojo.require("dojo.fx");
dojo.require("dojo.back");
dojo.require("dojox.timing._base");

function getCountofSelectedItems(formName){

	var listOfItems = document.forms[formName].selectedItems;
	var count = 0;
    
    if (listOfItems.length == null){
    	count=1;
    }
    
    for (var i=0; i<listOfItems.length; i++){
      if (listOfItems[i].checked){
            count++;	            	
       }
    }

	return count;
}

function checkSelectionOnChange(formName, selected, maxSelection){

	var form = document.forms[formName];
	var count = getCountofSelectedItems(formName);

    if (selected.checked == true){        
                     
	   if (count == maxSelection){
	     disableNotSelected(formName, true);	   
	   }
	}
	else {	   
	   if (count < maxSelection){
	     disableNotSelected(formName, false);
	   }	
	}		
	
	if (count == 0){
       return false;
	}	
}

function disableNotSelected(formName, flag){

	var form = document.forms[formName];	
    var listOfItems = document.forms[formName].selectedItems;	    
		
	for (var i=0; i<listOfItems.length; i++){
	    if (flag == true){
		    if (listOfItems[i].checked == false){
		        listOfItems[i].disabled = flag;
		    }
	    }
	    else{
	    	if (listOfItems[i].disabled == true){
		        listOfItems[i].disabled = flag;
		    }
	    }
	}
}

function submitPartSelection(formName){
	
	//var pageLoadPopup = null;
	var form = document.forms[formName];
	var listOfItems = document.forms[formName].selectedItems;

	if (getCountofSelectedItems(formName) == 0){
		return false;
	}
	
	if (listOfItems.length == null){
		if (listOfItems.checked == false){
			return false;
		}
	}

	disablePartSelection(true);
	disableSearch(true);
	
	var op = dojo.byId("output");
	
	//if(dojo.style(op, "display") == "block") {
		dojo.fadeOut({node:op,duration: 250}).play();
	//}
	
	var wait = null;
	
	var elapsed = 0;
	var timeout = document.forms["dist_inv_form"].timeout.value;
	
	dojo.xhrPost({
			url: 'submit_part_selections.do',
			form: form,
			timeout: timeout,			
			handleAs: "text",
			load: function(data){								     	
		     	disableSearch(false);				     	
			 	handleServerResponseData(data);					 	
			    saveData(data);				
			},
			error: function(response, ioArgs) { 
				dojo.xhrPost({
					url: 'error.do',									
					load: function(data){										
					 	resetArray();
					 	disableSearch(false);									 	
					 	handleServerResponseData(data);	
					}			
				});
			}		
	});
}

function disablePartSelection(flag){
	
	dojo.byId("selectButton1").disabled = flag;
	dojo.byId("selectButton2").disabled = flag;
	disableNotSelected("part_selection_form", flag);
}
