Skip to content

Instantly share code, notes, and snippets.

@bittersweetryan
Created October 20, 2011 14:42
Show Gist options
  • Save bittersweetryan/1301315 to your computer and use it in GitHub Desktop.
Save bittersweetryan/1301315 to your computer and use it in GitHub Desktop.
js code to review
var directPurchase = (function(window, document, undefined){
var directPurchaseModal = "",
directPurchaseForm = "",
isSetup = false;
function setupDirectPurchaseLink(){
$("#directPurchaseLink").live("click",function(e){
directPurchaseModal.dialog( "open" );
//stop all event propigation and bubbling!
return false;
});
}
//it'd be nice to have one get data for direct purchase json method that returnd an array of structs
//ie [{"measures":[{},{},{},{}]},{"materialTypes": [{},{},{}]}, {"inventoryTypes" : [{},{},{},{}]}]
//then we would only be making on http call instead of seprate ones and clean up this code a bit
function getMeasures(){
var jobID = utilities.getUrlVars()["jobId"],
measureData,
select = $("#jobMeasureID");
select.after("<span id='loading' style='width:16px; height:16px; padding: 10px;' class='ui-autocomplete-loading'></div>");
$.ajax({
url: "index.cfm?fuse=Job.getMeasuresJSON&json=true&jobId=" + jobID,
cache: false,
success: function(data){
measureData = data;
setMeasures();
select.removeClass("ui-autocomplete-loading");
}
});
var setMeasures = function(){
var len = measureData.length; //cache the length property
for(var i = 0; i < len; i++){
//check if the opiton exists
if(!select.find("option[value='415']").length){
select.append(
$("<option></option>").val(measureData[i]["ID"]).html(measureData[i]["VALUE"])
);
}
}
select.next().remove();
};
}
function populateSupportDataDropDown (target,id){
var supportDataValues;
$.ajax({
url: "index.cfm?fuse=SupportData.getSupportDataListJSON&json=true&supportDataTypeId=" + id,
success: function(data){
supportDataValues = data;
setSupportData();
}
});
var setSupportData = function(){
var len = supportDataValues.length; //cache the length property
for(var i = 0; i < len; i++){
target.append(
$("<option></option>").val(supportDataValues[i]["ID"]).html(supportDataValues[i]["VALUE"])
);
}
};
}
function setupDirectPurchaseModal(){
directPurchaseModal.dialog({
autoOpen: false,
height: 550,
width: 600,
modal: true,
create: function(){
populateSupportDataDropDown($("#reasonCodeID"),supportData.REASONCODE);
populateSupportDataDropDown($("#materialTypeID"),supportData.MATERIALTYPE);
populateSupportDataDropDown($("#inventoryUnitID"),supportData.INVENTORYUNIT);
},
buttons: {
"Create Direct Purchase": function() {
if(! directPurchaseForm.valid()){
return false;
}
//i want to make this more dynamic
var postData = directPurchaseForm.toObject({skipEmpty : false});
//i have to manually set this becuse the toObject function always setting it to null
postData.createPO = $("input:radio[name='createPO']:checked").val();
$.ajax({
type : "post",
url: "index.cfm?fuse=PurchaseOrder.addDirectPurchaseAJAX&json=true",
data: postData,
success: function(retData){
if(retData && typeof retData === 'object' && "jobMaterialInventoryID" in retData){
addMaterialToMeasure(postData,false);
}
else if(retData && typeof retData === 'object' && "jobMaterialID" in retData){
addMaterialToMeasure(postData,true);
}
else if(retData && typeof retData === 'object' && "purchaseOrderSaved" in retData) {
if(retData.purchaseOrderSaved){
addMessage("Purchase Order Added",$("#messages"),false);
}
else{
addMessage("Purchase not added",$("#messages"),true);
}
}
else{
if(retData && typeof retData === 'object' && "error" in retData){
addMessage(retData.error,$("#mesages"),true);
}
else{
addMessage("Error saving direct purchase",$("#mesages"),true);
}
}
},
error: function(e){
alert("Direct Purchase was not added!");
}
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
require();
$("#directPurchaseForm select:disabled").attr("disabled",false);
clearFields();
},
open: function(){
getMeasures();
require();
}
});
}
function clearFields(){
//clear text fields
directPurchaseForm.find("input:text").val('').
end().find("input:radio").attr("checked",false).
end().find("select").attr('selectedIndex', 0);
}
function addMaterialToMeasure(material,showMaterialName){
var materialRows= $(".details_for_" + material.jobMeasureID + "_" + material.materialID),
materialRow = materialRows.first(),
newRow = null,
newHeaderRow = null;
//first check for a material header
if($("tr[class*='material']").length === 0){
console.log('creating new header row');
newHeaderRow = $(".header.labor").clone();
newHeaderRow.children(":first").html("Material").end().addClass("material").removeClass("labor");
materialRow = $(".header.labor").next();
materialRow.children(":first").attr("colspan",2).next().remove();
}
//first look for any matching rows for this material and this mearsure
//if no rows were found then its a unique material
if(!materialRow.length){
materialRow = $("table[summary='Measure Information'] > tbody tr.material_" + material.jobMeasureID).next();
}
newRow = materialRow.clone();
//clear the name
newRow.find("td").first().html(material.materialDescription)
.next().html(utilities.formatCurrency(material.unitPrice)).append(getInformationSpan())
.next().html(material.qtyneeded)
.next().html('')
.next().html(utilities.formatCurrency(parseInt(material.unitPrice,10) * parseInt(material.qtyneeded,10)))
.next().html(utilities.formatCurrency(material.extendedPrice));
if(!showMaterialName){
newRow.find("td").first().remove();
rowspan = parseInt(materialRow.find("td").first().attr("rowspan"),10) || 1;
materialRow.find("td").first().attr("rowspan",++rowspan);
}
newRow.hide();
console.log(newHeaderRow);
if(newHeaderRow){
$(".applyCharge").before(newHeaderRow);
newHeaderRow.after(newRow).next().fadeIn("slow");
}
else if(materialRows.length){
materialRows.last().after(newRow).next().fadeIn("slow");
}
else{
$("tr[class*='details_for_" + material.jobMeasureID + "_" + "']:last").after(newRow).next().fadeIn("slow");
}
function getInformationSpan(){
return $(".information:first").clone();
}
}
function addMessage(message,target,error){
var okClass = 'ui-state-highlight ui-corner-all',
errorClass= 'ui-state-error ui-corner-all',
okIconClass = 'ui-icon ui-icon-info',
errorIconClass = 'ui-icon ui-icon-alert',
msgDiv = $('<div style="padding: 0.6em;"><span style="float: left; margin-right: .3em;"></span>' + message + '<br /></div>');
if(error){
msgDiv.addClass(errorClass).find(">span").addClass(errorIconClass);
}
else{
msgDiv.addClass(okClass).find(">span").addClass(errorIconClass);
}
target.append(msgDiv).fadeIn();
}
function autoCompleteMaterials(){
var materials = [];
$("#materialDescription").autocomplete({
source : function(req, add){
$.getJSON("index.cfm?fuse=material.getMaterialListJSON&json=true&description=" + req.term, function(data){
var len = data.length;
var suggestions = [];
materials = data;
for(var i = 0; i < len; i++){
suggestions.push(data[i].description);
}
add(suggestions);
}).error(function(){
console.log("Error");
}); //end getjson callback
},
minLength : 2,
select : function(e, ui){
var len = materials.length;
var thisval = ui.item.value;
for(var i = 0; i < len; i++){
if(thisval === materials[i]["description"]){
$(":radio[name='nonInventoryItem'][value='true']").attr("checked",true);
//set the id of the material
$("#materialID").val(materials[i]["materialID"]);
//select this materials materialtype and disable
if(materials[i].materialTypeID || (materials[i].materialTypeID = -1)) {
$("#materialTypeID").attr("disabled",true).filter("option[value='" + materials[i].materialTypeID + "']").attr("selected",true);
}
if(materials[i].inventoryUnitID || (materials[i].inventoryUnitID = -1)) {
//selete this materials invertory unit
$("#inventoryUnitID").attr("disabled",true).filter("option[value='" + materials[i].inventoryUnitID + "']").attr("selected",true);
}
break;
}
}
}
});
}
function autoCompleteVendors(){
var vendors = [];
$("#vendorName").autocomplete({
source : function(req, add){
$.getJSON("index.cfm?fuse=vendor.getVendorListJSON&json=true&description=" + req.term, function(data){
var len = data.length;
var suggestions = [];
vendors = data;
for(var i = 0; i < len; i++){
suggestions.push(data[i].name);
}
add(suggestions);
}).error(function(){
console.log("Error");
}); //end getjson callback
},
minLength : 2,
select : function(e, ui){
var len = vendors.length;
var thisval = ui.item.value;
for(var i = 0; i < len; i++){
if(thisval === vendors[i]["name"]){
//set the id of the material
$("#vendorID").val(vendors[i]["vendorID"]);
break;
}
}
}
});
}
function require(){
directPurchaseForm.find(".require").each(function(i, elem){
var inputElement = $(this);
var curRule;
if(inputElement.attr("validate") && /\brequired\:.true\b/.test(inputElement.attr("validate"))){
console.log("inputElement");
inputElement.removeAttr("validate","required: true")
.removeClass("ui-state-highlight")
.prev().find("em").remove().end()
.parent().find(".errormessage").remove();
}
else{
if(inputElement.hasClass("require")){
curRule = inputElement.attr("validate");
curRule = (curRule) ? curRule + "," : "";
inputElement.attr("validate", curRule + "required: true")
.prev().append("<em>*</em>");
}
}
});
directPurchaseForm.validate();
}
function setupPONumber() {
var theInputs = $("input:radio[name='createPO']");
theInputs.change(function(){
if(theInputs.filter(":checked").val() === "true"){
$("#PONumberDisplay").fadeIn();
}
else{
$("#PONumberDisplay").fadeOut();
}
});
}
function setup(){
if(!isSetup){
setupDirectPurchaseLink();
setupDirectPurchaseModal();
autoCompleteMaterials();
autoCompleteVendors();
setupPONumber();
isSetup = true;
}
}
return {
init : function(){
//cache links to the elements
directPurchaseModal = $("#directPurchaseDiv");
directPurchaseForm = directPurchaseModal.find("#directPurchaseForm");
//i dont want to do this stuff until the page is fully loaded so init is called in the document ready function
setup();
}
};
}(this, this.document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment