<commit_before>function IndexesCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexNames = [];
	$scope.errorMessage = null;

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};

	$scope.refreshIndexNames = function() {
		$http.get('/api/index').success(function(data) {
            var indexNames = [];
            for (var indexName in data.indexDefs.indexDefs) {
                indexNames.push(indexName)
            }
            $scope.indexNames = indexNames;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.deleteIndexNamed = function(name) {
		if(!confirm("Are you sure you want to permanenty delete the index '" + name + "'?")) {
			return;
		}
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + name).success(function(data) {
			$scope.refreshIndexNames();
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.refreshIndexNames();
}

function IndexCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexName = $routeParams.indexName;
	$scope.indexDocCount = 0;
	$scope.indexDefStr = "";
	$scope.indexParamsStr = "";
	$scope.tab = $routeParams.tabName;
	if($scope.tab === undefined || $scope.tab === "") {
		$scope.tab = "summary";
	}
	$scope.tabPath = '/static/partials/index/tab-' + $scope.tab + '.html';

	$scope.loadIndexDetails = function() {
		$http.get('/api/index/' + $scope.indexName).success(function(data) {
            $scope.indexDefStr = JSON.stringify(data.indexDef, undefined, 2);
            $scope.indexParamsStr = JSON.stringify(data.indexParams, undefined, 2);
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.loadIndexDocCount = function() {
		$http.get('/api/index/' + $scope.indexName + '/count').success(function(data) {
            $scope.indexDocCount = data.count;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	// always load the details
	$scope.loadIndexDetails();
	// tab specific loading
	if($scope.tab === "summary") {
		$scope.loadIndexDocCount();
	}

	$scope.indexDocument = function(id, body) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + $scope.indexName + "/doc/" + id, body).success(function(data) {
			$scope.successMessage = "Indexed Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.deleteDocument = function(id) {
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + $scope.indexName + "/" + id).success(function(data) {
			$scope.successMessage = "Deleted Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

    $scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}

function IndexNewCtrl($scope, $http, $routeParams, $log, $sce, $location) {
    $scope.newSourceParams = {};
    $scope.newIndexParams = {};
    $scope.newPlanParams = "";
    $scope.paramNumLines = {};

	$http.get('/api/managerMeta').success(function(data) {
		$scope.meta = data;

        for (var k in data.sourceTypes) {
            $scope.newSourceParams[k] =
                JSON.stringify(data.sourceTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newSourceParams[k].split("\n").length;
        }

        for (var k in data.indexTypes) {
            $scope.newIndexParams[k] =
                JSON.stringify(data.indexTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newIndexParams[k].split("\n").length;
        }

        $scope.newPlanParams = JSON.stringify(data.startSamples["planParams"], undefined, 2);
        $scope.paramNumLines["planParams"] = $scope.newPlanParams.split("\n").length;
	})

	$scope.errorMessage = null;

	$scope.newIndexNamed = function(sourceType, sourceName, sourceUUID, sourceParams,
									indexType, indexName, indexParams,
									planParams) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + indexName, "", {
			params: {
			    sourceType: sourceType,
			    sourceName: sourceName,
			    sourceUUID: sourceUUID || "",
			    sourceParams: sourceParams[sourceType],
			    indexType: indexType || "bleve",
			    indexName: indexName,
                indexParams: indexParams[indexType],
			    planParams: planParams,
		    }
		}).
		success(function(data) {
			$location.path('/indexes/' + indexName);
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}<commit_msg>JSON parse params & sourceParams for readability<commit_after>function IndexesCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexNames = [];
	$scope.errorMessage = null;

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};

	$scope.refreshIndexNames = function() {
		$http.get('/api/index').success(function(data) {
            var indexNames = [];
            for (var indexName in data.indexDefs.indexDefs) {
                indexNames.push(indexName)
            }
            $scope.indexNames = indexNames;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.deleteIndexNamed = function(name) {
		if(!confirm("Are you sure you want to permanenty delete the index '" + name + "'?")) {
			return;
		}
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + name).success(function(data) {
			$scope.refreshIndexNames();
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.refreshIndexNames();
}

function IndexCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexName = $routeParams.indexName;
	$scope.indexDocCount = 0;
	$scope.indexDefStr = "";
	$scope.indexParamsStr = "";
	$scope.tab = $routeParams.tabName;
	if($scope.tab === undefined || $scope.tab === "") {
		$scope.tab = "summary";
	}
	$scope.tabPath = '/static/partials/index/tab-' + $scope.tab + '.html';

	$scope.loadIndexDetails = function() {
		$http.get('/api/index/' + $scope.indexName).success(function(data) {
            data.indexDef.params = JSON.parse(data.indexDef.params)
            data.indexDef.sourceParams = JSON.parse(data.indexDef.sourceParams)
            $scope.indexDefStr = JSON.stringify(data.indexDef, undefined, 2);
            $scope.indexParamsStr = JSON.stringify(data.indexParams, undefined, 2);
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.loadIndexDocCount = function() {
		$http.get('/api/index/' + $scope.indexName + '/count').success(function(data) {
            $scope.indexDocCount = data.count;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	// always load the details
	$scope.loadIndexDetails();
	// tab specific loading
	if($scope.tab === "summary") {
		$scope.loadIndexDocCount();
	}

	$scope.indexDocument = function(id, body) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + $scope.indexName + "/doc/" + id, body).success(function(data) {
			$scope.successMessage = "Indexed Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.deleteDocument = function(id) {
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + $scope.indexName + "/" + id).success(function(data) {
			$scope.successMessage = "Deleted Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

    $scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}

function IndexNewCtrl($scope, $http, $routeParams, $log, $sce, $location) {
    $scope.newSourceParams = {};
    $scope.newIndexParams = {};
    $scope.newPlanParams = "";
    $scope.paramNumLines = {};

	$http.get('/api/managerMeta').success(function(data) {
		$scope.meta = data;

        for (var k in data.sourceTypes) {
            $scope.newSourceParams[k] =
                JSON.stringify(data.sourceTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newSourceParams[k].split("\n").length;
        }

        for (var k in data.indexTypes) {
            $scope.newIndexParams[k] =
                JSON.stringify(data.indexTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newIndexParams[k].split("\n").length;
        }

        $scope.newPlanParams = JSON.stringify(data.startSamples["planParams"], undefined, 2);
        $scope.paramNumLines["planParams"] = $scope.newPlanParams.split("\n").length;
	})

	$scope.errorMessage = null;

	$scope.newIndexNamed = function(sourceType, sourceName, sourceUUID, sourceParams,
									indexType, indexName, indexParams,
									planParams) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + indexName, "", {
			params: {
			    sourceType: sourceType,
			    sourceName: sourceName,
			    sourceUUID: sourceUUID || "",
			    sourceParams: sourceParams[sourceType],
			    indexType: indexType || "bleve",
			    indexName: indexName,
                indexParams: indexParams[indexType],
			    planParams: planParams,
		    }
		}).
		success(function(data) {
			$location.path('/indexes/' + indexName);
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}<|endoftext|>


<commit_before>function Modal(element, config) {
	this.overlay = document.createElement("div")
	this.overlay.classList.add("modal-overlay")

	if (config == null) {
		this.config = {keyboard: true}
	}

	else {
		this.config = config
	}

	if (element instanceof HTMLElement) {
		this.element = element
	}

	else {
		this.element = document.querySelector(element)
		if (this.element == null) {
			throw new Error("element does not exist.")
		}
		else if (!this.element.classList.contains("modal")) {
			throw new Error("element must have class modal")
		}
	}

	if (this.overlay.style.zIndex === undefined || this.overlay.style.zIndex === ""){
		this.overlay.style.zIndex = 0
	}

	this.element.style.zIndex = this.overlay.style.zIndex + 1

	buttonsEl = this.element.querySelector(".modal-buttons")
	if (buttonsEl != null){
		buttons = Array.prototype.slice.call(buttonsEl.childNodes)
		var _this = this

		document.addEventListener("keyup", function(event){
			if (_this.config.keyboard){
				if (event.keyCode == 27 && this.element.classList.contains("active")) {
					event.preventDefault()
					_this.hide()
				}
			}
		})
		buttons.forEach(function(button){
			//Checks if the button is actually an element.
			if (button.nodeType == 1){
				if (button.classList.contains("positive")){
					document.addEventListener("keyup", function(event){
						if (_this.config.keyboard){
							if (event.keyCode == 13 && _this.element.classList.contains("active")){ //Enter
								event.preventDefault()
								button.click()
							}
						}
					})
				}

				button.addEventListener("click", function(event){
					var mainEvent = new Event("pressed", {cancelable: true})
					mainEvent.el = this
					if (this.classList.contains("positive")){
						var secondaryEvent = new Event("positive-pressed", {cancelable: true})
					}

					else if (this.classList.contains("negative")){
						var secondaryEvent = new Event("negative-pressed", {cancelable: true})
					}

					_this.element.dispatchEvent(mainEvent)

					if (secondaryEvent != null){
						secondaryEvent.el = this
						_this.element.dispatchEvent(secondaryEvent)
					}

					if (!(mainEvent.defaultPrevented || (secondaryEvent != null && secondaryEvent.defaultPrevented))){
						_this.hide()
					}
				})
			}
		})
	}
}

Modal.prototype.show = function() {
	var event = new Event("show", {cancelable: true})
	this.element.dispatchEvent(event)
	if (!event.defaultPrevented){
		this.element.classList.add("active")
		document.body.appendChild(this.overlay)
		this.overlay.classList.add("active")
	}
}

Modal.prototype.hide = function() {
	var event = new Event("hide", {cancelable: true})
	this.element.dispatchEvent(event)
	if (!event.defaultPrevented){
		this.element.classList.remove("active")
		this.overlay.addEventListener("transitionend", function(event){
			this.remove()
		})
		this.overlay.classList.remove("active")
	}
}

Modal.prototype.toggle = function() {
	if (this.element.classList.contains("active")) {
		this.hide()
	}
	else {
		this.show()
	}
}

Modal.prototype.addEventListener = function(){
	this.element.addEventListener.apply(this, arguments)
}

<commit_msg>Run modal.js through jshint<commit_after>/*jshint eqnull: true */
function Modal(element, config) {
	this.overlay = document.createElement('div');
	this.overlay.classList.add('modal-overlay');
	if (config == null) {
		this.config = { keyboard: true };
	}

	else {
		this.config = config;
	}

	if (element instanceof HTMLElement) {
		this.element = element;
	}

	else {
		this.element = document.querySelector(element);
		if (this.element == null) {
			throw new Error('element does not exist.');
		}

		else if (!this.element.classList.contains('modal')) {
			throw new Error('element must have class modal');
		}
	}

	if (this.overlay.style.zIndex === undefined || this.overlay.style.zIndex === '') {
		this.overlay.style.zIndex = 0;
	}
	this.element.style.zIndex = this.overlay.style.zIndex + 1;
	buttonsEl = this.element.querySelector('.modal-buttons');

	if (buttonsEl != null) {
		buttons = Array.prototype.slice.call(buttonsEl.childNodes);
		var _this = this;
		document.addEventListener('keyup', function (event) {
			if (_this.config.keyboard) {
				if (event.keyCode == 27 && this.element.classList.contains('active')) {
					event.preventDefault();
					_this.hide();
				}
			}
		});
		buttons.forEach(function (button) {
			//Checks if the button is actually an element.
			if (button.nodeType == 1) {
				if (button.classList.contains('positive')) {
					document.addEventListener('keyup', function (event) {
						if (_this.config.keyboard) {
							if (event.keyCode == 13 && _this.element.classList.contains('active')) {
								//Enter
								event.preventDefault();
								button.click();
							}
						}
					});
				}

				button.addEventListener('click', function (event) {
					var mainEvent = new Event('pressed', { cancelable: true });
					var secondaryEvent = null;
					mainEvent.el = this;

					if (this.classList.contains('positive')) {
						secondaryEvent = new Event('positive-pressed', { cancelable: true });
					}

					else if (this.classList.contains('negative')) {
						secondaryEvent = new Event('negative-pressed', { cancelable: true });
					}

					_this.element.dispatchEvent(mainEvent);

					if (secondaryEvent !== null) {
						secondaryEvent.el = this;
						_this.element.dispatchEvent(secondaryEvent);
					}

					if (!(mainEvent.defaultPrevented || secondaryEvent != null && secondaryEvent.defaultPrevented)) {
						_this.hide();
					}
				});
			}
		});
	}
}

Modal.prototype.show = function () {
	var event = new Event('show', { cancelable: true });
	this.element.dispatchEvent(event);
	if (!event.defaultPrevented) {
		this.element.classList.add('active');
		document.body.appendChild(this.overlay);
		this.overlay.classList.add('active');
	}
};

Modal.prototype.hide = function () {
	var event = new Event('hide', { cancelable: true });
	this.element.dispatchEvent(event);
	if (!event.defaultPrevented) {
		this.element.classList.remove('active');
		this.overlay.addEventListener('transitionend', function (event) {
			this.remove();
		});
		this.overlay.classList.remove('active');
	}
};

Modal.prototype.toggle = function () {
	if (this.element.classList.contains('active')) {
		this.hide();
	}

	else {
		this.show();
	}
};

Modal.prototype.addEventListener = function () {
	this.element.addEventListener.apply(this, arguments);
};
<|endoftext|>


<commit_before>
//XXX: Purge JQuery
function changeAlertMsgForRWD(){
    $("#alert-message").css("left", function(){
        return $(window).width() / 2 - $(this).outerWidth() / 2;
    })
}

function alertWarning(type){
    alert_msg = $("#alert-message")
    alert_msg.text(type);
    changeAlertMsgForRWD();
    alert_msg.animate({top:"70px"}, 500);
}

function alertWarningClear(){
    alert_msg = $("#alert-message")
    changeAlertMsgForRWD();
    alert_msg.animate({top:"-50px"}, 500);
}

function warningColor(no){
    $($("input[type=\"pd\"]")[no]).css("border-color", "#ff0000");
    $($("input[type=\"pd\"]")[no]).css("box-shadow", "0 0 5px rgba(255, 000, 0, 0.4)");
}

function normalColor(no){
    $($("input[type=\"pd\"]"))[no].css("border-color", "");
    $($("input[type=\"pd\"]"))[no].css("box-shadow", "");
}
function resetColor(){
    $("input[type=\"pd\"]").css("border-color", "");
    $("input[type=\"pd\"]").css("box-shadow", "");
}

app.controller('order_main', function($scope, $http) {
    $scope.getNumber = function(num) {
        return new Array(num);
    };

    $scope.shipping_fee = 60
    $scope.fee_rate = 0.1

    $scope.item = [];
    $scope.item_count = 1;
    $scope.stage = 1;
    $scope.loading = false;

    $scope.increase_item_count = function(){
        $scope.item_count += 3;
    };

    $scope.go_to_stage = function(num){
        $scope.stage = num;
    };

    $scope.arrange_order = function(){
        order_list = "";

        for(item of $scope.item){
            order_list += item.pn + ":" + item.quantity + ",";
        }
        if(order_list != ""){
            order_list = order_list.slice(0, -1)
        }

        $scope.item_count = $scope.item.length;

        return order_list;
    }

    $scope.cancel_form = function(){
        if(confirm("您尚未提交訂單，確定要離開?")){
            window.location.href = "/";
        }
    };

    $scope.confirm_price = function(){
        $scope.loading = true;

        var order_list = $scope.arrange_order();
        if(order_list != ""){
            $scope.loading = true;
            $http.get("/digikey/price/?order_list=" + order_list)
                .then(function(response){
                        console.log(200);
                        var total = 0;

                        response.data.forEach(function(element, index){
                            $scope.item[index].unit_price = parseInt(element["unit_price"], 10)
                            $scope.item[index].price = parseInt(element["unit_price"], 10) * element["quantity"]
                            total += $scope.item[index].price;
                        });

                        $scope.fee = Math.ceil(total * $scope.fee_rate);
                        $scope.sum_price = total + $scope.fee + $scope.shipping_fee;

                        alertWarningClear();
                        resetColor();
                        $scope.stage = 2;

                        $scope.loading = false;
                    }, function(response){
                        if(response.status == 400){
                            console.log(400);
                            alertWarning("有不存在的料號、不可以1單位訂購的零件、沒有庫存的零件");
                            response.data.forEach(function(element, index){
                                if(element["unit_price"] <= 0){
                                    warningColor(index);
                                }
                            });
                        }else if(response.status == 500){
                            alertWarning("我們出錯了，請再試一次");
                        }

                        $scope.loading = false;
                    });
        }else{
            $scope.item_count = 1;
            alertWarning("尚未輸入任何訂單!")
        }
    };

    $scope.submit_form = function(){
        $scope.loading = true;
        $http.get("/digikey/order?order_list=" + $scope.arrange_order())
            .then(function(response){
                if(response.status == 200){
                    $scope.stage = 4
                $scope.loading = false;
                    //window.location.href = "/progress/";
                }
            });
    };
});

$(window).resize(function(){
    changeAlertMsgForRWD();
})
<commit_msg>fixed the bug that loading icon still showed if user do not input any chip<commit_after>
//XXX: Purge JQuery
function changeAlertMsgForRWD(){
    $("#alert-message").css("left", function(){
        return $(window).width() / 2 - $(this).outerWidth() / 2;
    })
}

function alertWarning(type){
    alert_msg = $("#alert-message")
    alert_msg.text(type);
    changeAlertMsgForRWD();
    alert_msg.animate({top:"70px"}, 500);
}

function alertWarningClear(){
    alert_msg = $("#alert-message")
    changeAlertMsgForRWD();
    alert_msg.animate({top:"-50px"}, 500);
}

function warningColor(no){
    $($("input[type=\"pd\"]")[no]).css("border-color", "#ff0000");
    $($("input[type=\"pd\"]")[no]).css("box-shadow", "0 0 5px rgba(255, 000, 0, 0.4)");
}

function normalColor(no){
    $($("input[type=\"pd\"]"))[no].css("border-color", "");
    $($("input[type=\"pd\"]"))[no].css("box-shadow", "");
}
function resetColor(){
    $("input[type=\"pd\"]").css("border-color", "");
    $("input[type=\"pd\"]").css("box-shadow", "");
}

app.controller('order_main', function($scope, $http) {
    $scope.getNumber = function(num) {
        return new Array(num);
    };

    $scope.shipping_fee = 60
    $scope.fee_rate = 0.1

    $scope.item = [];
    $scope.item_count = 1;
    $scope.stage = 1;
    $scope.loading = false;

    $scope.increase_item_count = function(){
        $scope.item_count += 3;
    };

    $scope.go_to_stage = function(num){
        $scope.stage = num;
    };

    $scope.arrange_order = function(){
        order_list = "";

        for(item of $scope.item){
            order_list += item.pn + ":" + item.quantity + ",";
        }
        if(order_list != ""){
            order_list = order_list.slice(0, -1)
        }

        $scope.item_count = $scope.item.length;

        return order_list;
    }

    $scope.cancel_form = function(){
        if(confirm("您尚未提交訂單，確定要離開?")){
            window.location.href = "/";
        }
    };

    $scope.confirm_price = function(){

        var order_list = $scope.arrange_order();
        if(order_list != ""){
            $scope.loading = true;
            $http.get("/digikey/price/?order_list=" + order_list)
                .then(function(response){
                        console.log(200);
                        var total = 0;

                        response.data.forEach(function(element, index){
                            $scope.item[index].unit_price = parseInt(element["unit_price"], 10)
                            $scope.item[index].price = parseInt(element["unit_price"], 10) * element["quantity"]
                            total += $scope.item[index].price;
                        });

                        $scope.fee = Math.ceil(total * $scope.fee_rate);
                        $scope.sum_price = total + $scope.fee + $scope.shipping_fee;

                        alertWarningClear();
                        resetColor();
                        $scope.stage = 2;

                        $scope.loading = false;
                    }, function(response){
                        if(response.status == 400){
                            console.log(400);
                            alertWarning("有不存在的料號、不可以1單位訂購的零件、沒有庫存的零件");
                            response.data.forEach(function(element, index){
                                if(element["unit_price"] <= 0){
                                    warningColor(index);
                                }
                            });
                        }else if(response.status == 500){
                            alertWarning("我們出錯了，請再試一次");
                        }

                        $scope.loading = false;
                    });
        }else{
            $scope.item_count = 1;
            alertWarning("尚未輸入任何訂單!")
        }
    };

    $scope.submit_form = function(){
        $scope.loading = true;
        $http.get("/digikey/order?order_list=" + $scope.arrange_order())
            .then(function(response){
                if(response.status == 200){
                    $scope.stage = 4
                $scope.loading = false;
                    //window.location.href = "/progress/";
                }
            });
    };
});

$(window).resize(function(){
    changeAlertMsgForRWD();
})
<|endoftext|>


<commit_before>/*****************************************************************************
 * FILE:    Manage Watersheds
 * DATE:    2/26/2015
 * AUTHOR:  Alan Snow
 * COPYRIGHT: (c) 2015 Brigham Young University
 * LICENSE: BSD 2-Clause
 *****************************************************************************/

/*****************************************************************************
 *                      LIBRARY WRAPPER
 *****************************************************************************/

var ERFP_MANAGE_WATERSHEDS = (function() {
    // Wrap the library in a package function
    "use strict"; // And enable strict mode for this library

    /************************************************************************
    *                      MODULE LEVEL / GLOBAL VARIABLES
    *************************************************************************/
    var m_uploading_data;

    /************************************************************************
    *                  INITIALIZATION / CONSTRUCTOR
    *************************************************************************/

    $(function() {
        //modlule variable
        m_uploading_data = false;
        //turn the select options into select2
        $(".data-store-select").each(function() {
            $(this).select2();
        });
        $(".geoserver-select").each(function() {
            $(this).select2();
        });

        //manage on change event for geoserver select
        $(".geoserver-select").change(function() {
            var geoserver_id = $(this).val();
            var row_container = $(this).parent().parent();
            if(geoserver_id == 1) {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').addClass('hidden');
                row_container.find('.shapefile').addClass('hidden');
                row_container.find('.kml').removeClass('hidden');
            } else {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').removeClass('hidden');
                if(row_container.find('#shp-upload-toggle').bootstrapSwitch('state')){
                    row_container.find('.shapefile').addClass('hidden');
                    row_container.find('.shapefile.upload').removeClass('hidden');
                } else {
                    row_container.find('.shapefile').removeClass('hidden');
                    row_container.find('.shapefile.upload').addClass('hidden');
                }
                row_container.find('.kml').addClass('hidden');
            }
        });
        //trigger change event to initialize page
        $(".geoserver-select").change();

        //show hide elements based on shape upload toggle selection
        $('.bootstrap-switch-id-shp-upload-toggle').on('switchChange.bootstrapSwitch', function(event, state) {
            var parent_row = $(this).parent().parent();
            if(state) {
                //show file upload
                parent_row.find('.shapefile').addClass('hidden');
                parent_row.find('.shapefile.upload').removeClass('hidden');
            } else {
                parent_row.find('.shapefile').removeClass('hidden');
                parent_row.find('.shapefile.upload').addClass('hidden');
            }

        });

        //handle the submit event
        $('.submit-update-watershed').click(function(){
            var safe_to_submit = {val: true};
            var parent_row = $(this).parent().parent().parent();
            //check data store input
            var watershed_id = parent_row.find('.watershed-id').text();
            var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit, "Error with watershed name.");
            var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit, "Error with subbasin name.");
            var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
            var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
            //initialize values
            var geoserver_drainage_line_layer = "";
            var geoserver_catchment_layer = "";
            var geoserver_gage_layer = "";
            var kml_drainage_line_layer = "";
            var kml_catchment_layer = "";
            var kml_gage_layer = "";
            var drainage_line_shp_files = [];
            var catchment_shp_files = [];
            var gage_shp_files = [];
            var drainage_line_kml_file = null;
            var catchment_kml_file = null;
            var gage_kml_file = null;

            if(geoserver_id==1){
                //kml upload
                drainage_line_kml_file = parent_row.find('.drainage-line-kml-upload-input')[0].files[0];
                catchment_kml_file = parent_row.find('.catchment-kml-upload-input')[0].files[0];
                gage_kml_file = parent_row.find('.gage-kml-upload-input')[0].files[0];

            } else if (!parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                //geoserver update
                geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.geoserver-drainage-line-input'),
                                                                             safe_to_submit,
                                                                             "Drainage line layer is required. Please add to continue.");
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
            } else {
                geoserver_drainage_line_layer = parent_row.find('.geoserver-drainage-line-input').val(); //optional if file uploaded
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
                //geoserver upload
                drainage_line_shp_files = parent_row.find('.drainage-line-shp-upload-input')[0].files;
                catchment_shp_files = parent_row.find('.catchment-shp-upload-input')[0].files;
                gage_shp_files = parent_row.find('.gage-shp-upload-input')[0].files;
            }

            //submit if the form is ok
            if(safe_to_submit.val && !m_uploading_data) {
                if (window.confirm("Are you sure? You will delete prediction files " +
                    "if the watershed or subbasin name are changed.")) {

                    var submit_button = $(this);
                    var submit_button_html = submit_button.html();
                    var xhr = null;
                    var xhr_catchment = null;
                    var xhr_gage = null;
                    //give user information
                    addInfoMessage("Submiting data. Please be patient! " +
                    "This may take a few minutes due to downloading prediction datasets.");
                    submit_button.text('Submitting ...');
                    //update database
                    if (geoserver_id == 1 || parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                        //file upload
                        if (drainage_line_kml_file != null || drainage_line_shp_files.length >= 4 ||
                            geoserver_drainage_line_layer.length > 0) {
                            var data = new FormData();
                            data.append("watershed_id", watershed_id);
                            data.append("watershed_name", watershed_name);
                            data.append("subbasin_name", subbasin_name);
                            data.append("data_store_id", data_store_id);
                            data.append("geoserver_id", geoserver_id);
                            data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                            data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                            data.append("geoserver_gage_layer", geoserver_gage_layer);
                            data.append("drainage_line_kml_file", drainage_line_kml_file);
                            data.append("catchment_kml_file", catchment_kml_file);
                            data.append("gage_kml_file", gage_kml_file);
                            for (var i = 0; i < drainage_line_shp_files.length; i++) {
                                data.append("drainage_line_shp_file", drainage_line_shp_files[i]);
                            }
                            var drainage_success_message = "Drainage Line Upload Success!";
                            if (drainage_line_kml_file != null || drainage_line_shp_files.length>=4) {
                                appendInfoMessage("Uploading Drainage Line ...", "message_drainage_line");
                            } else {
                                appendInfoMessage("Uploading Watershed Data ...", "message_drainage_line");
                                drainage_success_message = "Watershed Data Upload Success!"
                            }
                            //needs to be outside
                            xhr = ajax_update_database_multiple_files("submit",
                                                                      data,
                                                                      drainage_success_message,
                                                                      "message_drainage_line");

                            //upload catchment when drainage line finishes if catchment exist
                            jQuery.when(xhr).done(function (return_data) {
                                //upload catchment when  drainage line finishes if exists
                                if (catchment_kml_file != null || catchment_shp_files.length >= 4) {
                                    appendInfoMessage("Uploading Catchment ...", "message_catchment");
                                    var data = new FormData();
                                    data.append("watershed_id", watershed_id);
                                    data.append("watershed_name", watershed_name);
                                    data.append("subbasin_name", subbasin_name);
                                    data.append("data_store_id", data_store_id);
                                    data.append("geoserver_id", geoserver_id);
                                    if (return_data != null && typeof return_data != 'undefined') {
                                        if ('geoserver_drainage_line_layer' in return_data) {
                                            geoserver_drainage_line_layer = return_data['geoserver_drainage_line_layer'];
                                        }
                                        if ('drainage_line_kml_file' in return_data) {
                                            drainage_line_kml_file = return_data['drainage_line_kml_file'];
                                        }
                                    }
                                    data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                                    data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                                    data.append("geoserver_gage_layer", geoserver_gage_layer);
                                    data.append("drainage_line_kml_file", drainage_line_kml_file);
                                    data.append("catchment_kml_file", catchment_kml_file);
                                    data.append("gage_kml_file", gage_kml_file);
                                    for (var i = 0; i < catchment_shp_files.length; i++) {
                                        data.append("catchment_shp_file", catchment_shp_files[i]);
                                    }
                                    xhr_catchment = ajax_update_database_multiple_files("submit", data,
                                        "Catchment Upload Success!",
                                        "message_catchment");
                                }
                                //upload gage when catchment and drainage line finishes if gage exists
                                jQuery.when(xhr_catchment).done(function (catchment_data) {
                                    if (gage_kml_file != null || gage_shp_files.length >= 4) {
                                        appendInfoMessage("Uploading Gages ...", "message_gages");
                                        var data = new FormData();
                                        data.append("watershed_id", watershed_id)
                                        data.append("watershed_name", watershed_name);
                                        data.append("subbasin_name", subbasin_name);
                                        data.append("data_store_id", data_store_id);
                                        data.append("geoserver_id", geoserver_id);
                                        if (catchment_data != null && typeof catchment_data != 'undefined') {
                                            if ('geoserver_catchment_layer' in catchment_data) {
                                                geoserver_catchment_layer = catchment_data['geoserver_catchment_layer'];
                                            }
                                            if ('catchment_kml_file' in catchment_data) {
                                                catchment_kml_file = catchment_data['catchment_kml_file'];
                                            }
                                        }
                                        data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                                        data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                                        data.append("geoserver_gage_layer", geoserver_gage_layer);
                                        data.append("drainage_line_kml_file", drainage_line_kml_file);
                                        data.append("catchment_kml_file", catchment_kml_file);
                                        data.append("gage_kml_file", gage_kml_file);
                                        for (var i = 0; i < gage_shp_files.length; i++) {
                                            data.append("gage_shp_file", gage_shp_files[i]);
                                        }
                                        xhr_gage = ajax_update_database_multiple_files("submit", data,
                                            "Gages Upload Success!",
                                            "message_gages");
                                    }
                                    //when everything is finished
                                    jQuery.when(xhr, xhr_catchment, xhr_gage).done(function (drainage_line_return,
                                                                                catchment_return,
                                                                                gage_return) {
                                        if (drainage_line_return != null && drainage_line_return != 'undefined') {
                                            parent_row.find('.geoserver-drainage-line-input').val(drainage_line_return[0]['geoserver_drainage_line_layer']);
                                        }
                                        if (catchment_return != null && catchment_return != 'undefined') {
                                            parent_row.find('.geoserver-catchment-input').val(catchment_return[0]['geoserver_catchment_layer']);
                                        }
                                        if (gage_return != null && gage_return != 'undefined') {
                                            parent_row.find('.geoserver-gage-input').val(gage_return[0]['geoserver_gage_layer']);
                                        }
                                        //finishReset(return_data);
                                        //1) Clean file inputs
                                        parent_row.find('.drainage-line-shp-upload-input').val("");
                                        parent_row.find('.catchment-shp-upload-input').val('');
                                        parent_row.find('.gage-shp-upload-input').val('');
                                        //2) Change toggle to No
                                        $('#shp-upload-toggle').bootstrapSwitch('state', false);
                                        //update the input boxes to reflect change
                                        addSuccessMessage("Watershed Upload Complete!");
                                    })
                                    .always(function () {
                                        submit_button.html(submit_button_html);
                                        m_uploading_data = false;
                                    });
                                });

                            });
                        } else {
                            addErrorMessage("Need a drainage line to continue.");
                        }
                    } else {
                        var data = {
                                watershed_id: watershed_id,
                                watershed_name: watershed_name,
                                subbasin_name: subbasin_name,
                                data_store_id: data_store_id,
                                geoserver_id: geoserver_id,
                                geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                                geoserver_catchment_layer: geoserver_catchment_layer,
                                geoserver_gage_layer: geoserver_gage_layer,
                                };

                        var xhr = ajax_update_database("submit",data);
                    }
                    m_uploading_data = true;
                    jQuery.when(xhr).done(function(data) {
                            if(drainage_line_kml_file != null) {
                                parent_row.find('.drainage-line-layer').find('.help-block.upload').text('Current: ' + data['kml_drainage_line_layer']);
                            }if(catchment_kml_file != null) {
                                parent_row.find('.catchment-layer').find('.help-block.upload').text('Current: ' + data['kml_catchment_layer']);
                            }if(gage_kml_file != null) {
                                parent_row.find('.gage-layer').find('.help-block.upload').text('Current: ' + data['kml_gage_layer']);
                            }
                        })
                       .always(function(){
                            submit_button.html(submit_button_html);
                            m_uploading_data = false;
                    });
                } //window confirm
            }  else if (m_uploading_data) {
                addWarningMessage("Submitting Data. Please Wait.");
            } else {
                addErrorMessage(safe_to_submit.error);
            }

        });

        //handle the submit update event
        $('.submit-delete-watershed').click(function(){
            var data = {
                    watershed_id: $(this).parent().parent().parent()
                                    .find('.watershed-id').text(),
                    };
            //update database
            deleteRowData($(this),data);
        });
    }); //document ready
}()); // End of package wrapper
<commit_msg>Bug fixes.<commit_after>/*****************************************************************************
 * FILE:    Manage Watersheds
 * DATE:    2/26/2015
 * AUTHOR:  Alan Snow
 * COPYRIGHT: (c) 2015 Brigham Young University
 * LICENSE: BSD 2-Clause
 *****************************************************************************/

/*****************************************************************************
 *                      LIBRARY WRAPPER
 *****************************************************************************/

var ERFP_MANAGE_WATERSHEDS = (function() {
    // Wrap the library in a package function
    "use strict"; // And enable strict mode for this library

    /************************************************************************
    *                      MODULE LEVEL / GLOBAL VARIABLES
    *************************************************************************/
    var m_uploading_data;

    /************************************************************************
    *                  INITIALIZATION / CONSTRUCTOR
    *************************************************************************/

    $(function() {
        //modlule variable
        m_uploading_data = false;
        //turn the select options into select2
        $(".data-store-select").each(function() {
            $(this).select2();
        });
        $(".geoserver-select").each(function() {
            $(this).select2();
        });

        //manage on change event for geoserver select
        $(".geoserver-select").change(function() {
            var geoserver_id = $(this).val();
            var row_container = $(this).parent().parent();
            if(geoserver_id == 1) {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').addClass('hidden');
                row_container.find('.shapefile').addClass('hidden');
                row_container.find('.kml').removeClass('hidden');
            } else {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').removeClass('hidden');
                if(row_container.find('#shp-upload-toggle').bootstrapSwitch('state')){
                    row_container.find('.shapefile').addClass('hidden');
                    row_container.find('.shapefile.upload').removeClass('hidden');
                } else {
                    row_container.find('.shapefile').removeClass('hidden');
                    row_container.find('.shapefile.upload').addClass('hidden');
                }
                row_container.find('.kml').addClass('hidden');
            }
        });
        //trigger change event to initialize page
        $(".geoserver-select").change();

        //show hide elements based on shape upload toggle selection
        $('.bootstrap-switch-id-shp-upload-toggle').on('switchChange.bootstrapSwitch', function(event, state) {
            var parent_row = $(this).parent().parent();
            if(state) {
                //show file upload
                parent_row.find('.shapefile').addClass('hidden');
                parent_row.find('.shapefile.upload').removeClass('hidden');
            } else {
                parent_row.find('.shapefile').removeClass('hidden');
                parent_row.find('.shapefile.upload').addClass('hidden');
            }

        });

        //handle the submit event
        $('.submit-update-watershed').click(function(){
            var safe_to_submit = {val: true};
            var parent_row = $(this).parent().parent().parent();
            //check data store input
            var watershed_id = parent_row.find('.watershed-id').text();
            var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit, "Error with watershed name.");
            var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit, "Error with subbasin name.");
            var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
            var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
            //initialize values
            var geoserver_drainage_line_layer = "";
            var geoserver_catchment_layer = "";
            var geoserver_gage_layer = "";
            var kml_drainage_line_layer = "";
            var kml_catchment_layer = "";
            var kml_gage_layer = "";
            var drainage_line_shp_files = [];
            var catchment_shp_files = [];
            var gage_shp_files = [];
            var drainage_line_kml_file = null;
            var catchment_kml_file = null;
            var gage_kml_file = null;

            if(geoserver_id==1){
                //kml upload
                drainage_line_kml_file = parent_row.find('.drainage-line-kml-upload-input')[0].files[0];
                catchment_kml_file = parent_row.find('.catchment-kml-upload-input')[0].files[0];
                gage_kml_file = parent_row.find('.gage-kml-upload-input')[0].files[0];

            } else if (!parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                //geoserver update
                geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.geoserver-drainage-line-input'),
                                                                             safe_to_submit,
                                                                             "Drainage line layer is required. Please add to continue.");
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
            } else {
                geoserver_drainage_line_layer = parent_row.find('.geoserver-drainage-line-input').val(); //optional if file uploaded
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
                //geoserver upload
                drainage_line_shp_files = parent_row.find('.drainage-line-shp-upload-input')[0].files;
                catchment_shp_files = parent_row.find('.catchment-shp-upload-input')[0].files;
                gage_shp_files = parent_row.find('.gage-shp-upload-input')[0].files;
            }

            //submit if the form is ok
            if(safe_to_submit.val && !m_uploading_data) {
                if (window.confirm("Are you sure? You will delete prediction files " +
                    "if the watershed or subbasin name are changed.")) {

                    var submit_button = $(this);
                    var submit_button_html = submit_button.html();
                    var xhr = null;
                    var xhr_catchment = null;
                    var xhr_gage = null;
                    //give user information
                    addInfoMessage("Submiting data. Please be patient! " +
                    "This may take a few minutes due to downloading prediction datasets.");
                    submit_button.text('Submitting ...');
                    //update database
                    if (geoserver_id == 1 || parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                        //file upload
                        if (drainage_line_kml_file != null || drainage_line_shp_files.length >= 4 ||
                            geoserver_drainage_line_layer.length > 0) {
                            var data = new FormData();
                            data.append("watershed_id", watershed_id);
                            data.append("watershed_name", watershed_name);
                            data.append("subbasin_name", subbasin_name);
                            data.append("data_store_id", data_store_id);
                            data.append("geoserver_id", geoserver_id);
                            data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                            data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                            data.append("geoserver_gage_layer", geoserver_gage_layer);
                            data.append("drainage_line_kml_file", drainage_line_kml_file);
                            data.append("catchment_kml_file", catchment_kml_file);
                            data.append("gage_kml_file", gage_kml_file);
                            for (var i = 0; i < drainage_line_shp_files.length; i++) {
                                data.append("drainage_line_shp_file", drainage_line_shp_files[i]);
                            }
                            var drainage_success_message = "Drainage Line Upload Success!";
                            if (drainage_line_kml_file != null || drainage_line_shp_files.length>=4) {
                                appendInfoMessage("Uploading Drainage Line ...", "message_drainage_line");
                            } else {
                                appendInfoMessage("Uploading Watershed Data ...", "message_drainage_line");
                                drainage_success_message = "Watershed Data Upload Success!"
                            }
                            //needs to be outside
                            xhr = ajax_update_database_multiple_files("submit",
                                                                      data,
                                                                      drainage_success_message,
                                                                      "message_drainage_line");

                            //upload catchment when drainage line finishes if catchment exist
                            jQuery.when(xhr).done(function (return_data) {
                                //upload catchment when  drainage line finishes if exists
                                if (catchment_kml_file != null || catchment_shp_files.length >= 4) {
                                    appendInfoMessage("Uploading Catchment ...", "message_catchment");
                                    var data = new FormData();
                                    data.append("watershed_id", watershed_id);
                                    data.append("watershed_name", watershed_name);
                                    data.append("subbasin_name", subbasin_name);
                                    data.append("data_store_id", data_store_id);
                                    data.append("geoserver_id", geoserver_id);
                                    if (return_data != null && typeof return_data != 'undefined') {
                                        if ('geoserver_drainage_line_layer' in return_data) {
                                            geoserver_drainage_line_layer = return_data['geoserver_drainage_line_layer'];
                                        }
                                        if ('drainage_line_kml_file' in return_data) {
                                            drainage_line_kml_file = return_data['drainage_line_kml_file'];
                                        }
                                    }
                                    data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                                    data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                                    data.append("geoserver_gage_layer", geoserver_gage_layer);
                                    data.append("drainage_line_kml_file", drainage_line_kml_file);
                                    data.append("catchment_kml_file", catchment_kml_file);
                                    data.append("gage_kml_file", gage_kml_file);
                                    for (var i = 0; i < catchment_shp_files.length; i++) {
                                        data.append("catchment_shp_file", catchment_shp_files[i]);
                                    }
                                    xhr_catchment = ajax_update_database_multiple_files("submit", data,
                                        "Catchment Upload Success!",
                                        "message_catchment");
                                }
                                //upload gage when catchment and drainage line finishes if gage exists
                                jQuery.when(xhr_catchment).done(function (catchment_data) {
                                    if (gage_kml_file != null || gage_shp_files.length >= 4) {
                                        appendInfoMessage("Uploading Gages ...", "message_gages");
                                        var data = new FormData();
                                        data.append("watershed_id", watershed_id)
                                        data.append("watershed_name", watershed_name);
                                        data.append("subbasin_name", subbasin_name);
                                        data.append("data_store_id", data_store_id);
                                        data.append("geoserver_id", geoserver_id);
                                        if (catchment_data != null && typeof catchment_data != 'undefined') {
                                            if ('geoserver_catchment_layer' in catchment_data) {
                                                geoserver_catchment_layer = catchment_data['geoserver_catchment_layer'];
                                            }
                                            if ('catchment_kml_file' in catchment_data) {
                                                catchment_kml_file = catchment_data['catchment_kml_file'];
                                            }
                                        }
                                        data.append("geoserver_drainage_line_layer", geoserver_drainage_line_layer);
                                        data.append("geoserver_catchment_layer", geoserver_catchment_layer);
                                        data.append("geoserver_gage_layer", geoserver_gage_layer);
                                        data.append("drainage_line_kml_file", drainage_line_kml_file);
                                        data.append("catchment_kml_file", catchment_kml_file);
                                        data.append("gage_kml_file", gage_kml_file);
                                        for (var i = 0; i < gage_shp_files.length; i++) {
                                            data.append("gage_shp_file", gage_shp_files[i]);
                                        }
                                        xhr_gage = ajax_update_database_multiple_files("submit", data,
                                            "Gages Upload Success!",
                                            "message_gages");
                                    }
                                    //when everything is finished
                                    jQuery.when(xhr, xhr_catchment, xhr_gage).done(function (drainage_line_return,
                                                                                catchment_return,
                                                                                gage_return) {
                                        if (drainage_line_return != null && drainage_line_return != 'undefined') {
                                            parent_row.find('.geoserver-drainage-line-input').val(drainage_line_return[0]['geoserver_drainage_line_layer']);
                                        }
                                        if (catchment_return != null && catchment_return != 'undefined') {
                                            parent_row.find('.geoserver-catchment-input').val(catchment_return[0]['geoserver_catchment_layer']);
                                        }
                                        if (gage_return != null && gage_return != 'undefined') {
                                            parent_row.find('.geoserver-gage-input').val(gage_return[0]['geoserver_gage_layer']);
                                        }
                                        //finishReset(return_data);
                                        //1) Clean file inputs
                                        parent_row.find('.drainage-line-shp-upload-input').val("");
                                        parent_row.find('.catchment-shp-upload-input').val('');
                                        parent_row.find('.gage-shp-upload-input').val('');
                                        //2) Change toggle to No
                                        if (parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                                            parent_row.find('#shp-upload-toggle').bootstrapSwitch('toggleState');
                                        }
                                        //update the input boxes to reflect change
                                        addSuccessMessage("Watershed Upload Complete!");
                                    })
                                    .always(function () {
                                        submit_button.html(submit_button_html);
                                        m_uploading_data = false;
                                    });
                                });

                            });
                        } else {
                            addErrorMessage("Need a drainage line to continue.");
                        }
                    } else {
                        var data = {
                                watershed_id: watershed_id,
                                watershed_name: watershed_name,
                                subbasin_name: subbasin_name,
                                data_store_id: data_store_id,
                                geoserver_id: geoserver_id,
                                geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                                geoserver_catchment_layer: geoserver_catchment_layer,
                                geoserver_gage_layer: geoserver_gage_layer,
                                };

                        var xhr = ajax_update_database("submit",data);
                    }
                    m_uploading_data = true;
                    jQuery.when(xhr).done(function(data) {
                            if(drainage_line_kml_file != null) {
                                parent_row.find('.drainage-line-layer').find('.help-block.upload').text('Current: ' + data['kml_drainage_line_layer']);
                            }if(catchment_kml_file != null) {
                                parent_row.find('.catchment-layer').find('.help-block.upload').text('Current: ' + data['kml_catchment_layer']);
                            }if(gage_kml_file != null) {
                                parent_row.find('.gage-layer').find('.help-block.upload').text('Current: ' + data['kml_gage_layer']);
                            }
                        })
                       .always(function(){
                            submit_button.html(submit_button_html);
                            m_uploading_data = false;
                    });
                } //window confirm
            }  else if (m_uploading_data) {
                addWarningMessage("Submitting Data. Please Wait.");
            } else {
                addErrorMessage(safe_to_submit.error);
            }

        });

        //handle the submit update event
        $('.submit-delete-watershed').click(function(){
            var data = {
                    watershed_id: $(this).parent().parent().parent()
                                    .find('.watershed-id').text(),
                    };
            //update database
            deleteRowData($(this),data);
        });
    }); //document ready
}()); // End of package wrapper
<|endoftext|>


<commit_before>"use strict";
var PhotoStreamController = function($scope, $http, analytics, resourceCache) {

	$http({method: "GET", url: "/api/v1/hikes", cache: resourceCache}).
		success(function(data, status, headers, config) {
			$scope.hikes = data;
		}).
		error(function(data, status, headers, config) {});

	$scope.hikes = [];
};

PhotoStreamController.$inject = ["$scope", "$http", "analytics", "resourceCache"];<commit_msg>Enable logging in PhotoStreamController.js.<commit_after>"use strict";
var PhotoStreamController = function($scope, $http, $log, analytics, resourceCache) {

	$http({method: "GET", url: "/api/v1/hikes", cache: resourceCache}).
		success(function(data, status, headers, config) {
			$scope.hikes = data;
		}).
		error(function(data, status, headers, config) {
			$log.error(config);
		});

	$scope.hikes = [];
};

PhotoStreamController.$inject = ["$scope", "$http", "$log", "analytics", "resourceCache"];<|endoftext|>


<commit_before>/**
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.
 *
 * Camunda licenses this file to you under the MIT; you may not use this file
 * except in compliance with the MIT License.
 */

import React, { PureComponent } from 'react';

import {
  Modal
} from '../../primitives';

import css from './View.less';

class View extends PureComponent {
  render() {
    const {
      shortcuts,
      onClose
    } = this.props;

    return (
      <Modal className={ css.View } onClose={ onClose }>

Keyboard Shortcuts

          The following special shortcuts can be used on opened diagrams.

            {
              (shortcuts || []).map(s => {
                return

                  { s.label }
                  { s.binding }

;
              })
            }

          Find additional shortcuts on individual items in the application menu.

      </Modal>
    );
  }

}

export default View;<commit_msg>feat(keyboard-shortcuts): use modal structural components<commit_after>/**
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.
 *
 * Camunda licenses this file to you under the MIT; you may not use this file
 * except in compliance with the MIT License.
 */

import React, { PureComponent } from 'react';

import {
  Modal
} from '../../primitives';

import css from './View.less';

class View extends PureComponent {
  render() {
    const {
      shortcuts,
      onClose
    } = this.props;

    return (
      <Modal className={ css.View } onClose={ onClose }>

        <Modal.Header>
          <Modal.Title>Keyboard Shortcuts</Modal.Title>
          <Modal.Close onClick={ onClose } />
        </Modal.Header>

        <Modal.Body>

            The following special shortcuts can be used on opened diagrams.

              {
                (shortcuts || []).map(s => {
                  return

                    { s.label }
                    { s.binding }

;
                })
              }

            Find additional shortcuts on individual items in the application menu.

        </Modal.Body>

        <Modal.Footer>
          <button onClick={ onClose }>Close</button>
        </Modal.Footer>
      </Modal>
    );
  }

}

export default View;
<|endoftext|>


<commit_before>/**
 * Utilities used throughout StoryBase JavaScript apps
 */

Namespace('storybase.utils', {
  capfirst: function(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  /**
   * Geocode using the local geocoder.
   */
  geocode: function(address, options) {
    // TODO: Don't hardcode this URL
    $.ajax('/api/0.1/geocode/', {
      dataType: 'json',
      data: {
        q: address,
      },
      success: function(data, textStatus, jqXHR) {
        if (data.meta.total_count > 0) {
          // Found a point for the address
          options.success({
            'lat': data.objects[0].lat,
            'lng': data.objects[0].lng
          }, data.objects[0].place);
        }
        else {
          options.failure(address);
        }
      }
    });
  },

  /**
   * Return the root of a URL path.
   *
   * This is used to separate the portion of the array that represents
   * the base of a URL path from the portions that represent parameters.
   *
   * This is needed because a variable number of path elements might proceed
   * the part of the URL that represents the base, for example,
   * internatialization path prefixes.
   *
   * This function is useful for providing a value for the 'root' argument
   * to a call to Backbone.history.start().
   *
   * @param {String[]} bases An array of strings that will be used to
   *                         separate the root from the rest of the path.
   * @param {String} [path=window.location.pathname] Path to split, defaults
   *   to the current window's path.
   * @param {int} [extra=0] Extra path parts to include after the matching
   *                        part in the final path.
   *
   * @example
   * getRoot(['build'], '/en/build/f81eca996d754a549ae48cf8ef9622dc/');
   * // Returns '/en/build/'
   * getRoot(['build'], '/en/build/f81eca996d754a549ae48cf8ef9622dc/', 1);
   * // Returns '/en/build/f81eca996d754a549ae48cf8ef9622dc/'
   *
   */
  getRoot: function(bases, path, extra) {
    var pathParts;
    var len = bases.length;
    var i;
    var pos;
    var extraPos;
    if (_.isUndefined(path)) {
      path = window.location.pathname;
    }
    if (_.isUndefined(extra)) {
      extra = 0;
    }
    // Split the path into chunks.  Note that if there are a leading and
    // trailing '/', the first and last array elements will be empty
    // strings
    pathParts = path.split('/');
    for (i = len - 1, pos = -1; pos === -1 && i >= 0; i--) {
      pos = _.lastIndexOf(pathParts, bases[i]);
    }

    if (pos === -1) {
      // None of the base search strings were found.  This
      // shouldn't happen
      throw new Error("Base not found in location parts");
    }

    // Check if there are extra path chunks after the matching chunk
    // and include them
    extraPos = pos + extra;
    if (extraPos + 1 <= pathParts.length && pathParts[extraPos] != "") {
      pos = extraPos;
    }

    return _.first(pathParts, pos + 1).join('/') + '/';
  },

  /**
   * Convert the license value stored in the database (as a String) to
   * form parameters.
   *
   * The parameters keys try to match those of the Creative Commons
   * Web Services API. See http://wiki.creativecommons.org/Web_Services
   *
   * @param {String} [license='CC BY'] License string
   */
  licenseStrToParams: function(license) {
    license = license || 'CC BY';
    var ccLicenses = {
      'CC BY': {
        commercial: 'y',
        derivatives: 'y'
      },
      'CC BY-SA': {
        commercial: 'y',
        derivatives: 'sa'
      },
      'CC BY-ND': {
        commercial: 'y',
        derivatives: 'n'
      },
      'CC BY-NC': {
        commercial: 'n',
        derivatives: 'y'
      },
      'CC BY-NC-SA': {
        commercial: 'n',
        derivatives: 'sa'
      },
      'CC BY-NC-ND': {
        commercial: 'n',
        derivatives: 'n'
      }
    };
    return ccLicenses[license];
  },

  /**
   * Convert the license form parameters to a string to store
   * server-side.
   *
   * The parameters keys try to match those of the Creative Commons
   * Web Services API. See http://wiki.creativecommons.org/Web_Services
   *
   * @param {Object} params Form parameters corresponding to a
   *   particular Creative Commons license. The object must have
   *   'commercial' and 'derivatives' properties.
   */
  licenseParamsToStr: function(params) {
    var ccLicenses = {
      'y': {
        'y': 'CC BY',
        'sa': 'CC BY-SA',
        'n': 'CC BY-ND'
      },
      'n': {
        'y': 'CC BY-NC',
        'sa': 'CC BY-NC-SA',
        'n': 'CC BY-NC-ND'
      }
    };
    return ccLicenses[params['commercial']][params['derivatives']];
  },

  /**
   * Check if the Google Analytics tracking JavaScript has been initialized
   */
  hasAnalytics: function() {
    if (window._gaq) {
      return true;
    }
    else {
      return false;
    }
  }
});

/**
 * Translate a string in a template using Django's gettext Javascript API.
 * @param {String} message The string to be translated
 * @return {String} Translated string
 */
Handlebars.registerHelper('gettext', function(message) {
  return new Handlebars.SafeString(gettext(message));
});

/**
 * Translate a block of template text after first rendering the
 * contents of the template.
 * @return {string} Translated block of text
 */
Handlebars.registerHelper('blockgettext', function(options) {
  return gettext(options.fn(this));
});

/**
 * Return a singular or plural suffix
 * Works in a manner similar to Django's pluralize filter
 * @param {number} count The number used to determine if the singular or
 *    plural suffix should be returned.
 * @param {object} options Hash of options. Optionally contains one key,
 *     'suffix' which is either the plural suffix (e.g. 's') or a
 *     comma-separated list of the singular and plural suffixes
 *     (e.g. 'y,ies')
 * @return {string} Suffix
 */
Handlebars.registerHelper('pluralize', function(count, options) {
  var suffix;
  var defaults = {
    suffix: "s"
  };
  _.defaults(options.hash, defaults);
  var suffixes = options.hash.suffix.split(",");
  if (suffixes.length == 1) {
    // Only one suffix provided.  This likely means plurals are just
    // formed by appending an 's' to the end of the string and keeping
    // the singular as-is.
    // Fill the singular slot of our options with an empty string
    suffixes.unshift("");
  }
  if (count == 1) {
    suffix = suffixes[0];
  }
  else {
    suffix = suffixes[1];
  }

  return suffix;
});

Handlebars.registerHelper('firstparagraph', function(s, maxWords) {
   var result = null;
   var $el = $("

");
   // Toss the text in a dummy div
   $el.html(s);
   if ($el.find('p').length > 0) {
     // Found a paragraph tag.  Return its contents
     result = $el.find('p').html();
   }
   if (result === null) {
     // We didn't find a paragraph tag, try splitting on newlines
     result = s.split(/\r\n|\r|\n/)[0];
   }
   var words = result.split(/\s/);
   if (typeof maxWords === "number" && words.length > maxWords) {
     result = "";
     for (var i = 0; i <= maxWords; i++) {
         result += words[i] + " ";
     }
     result += "…"
   }
   return new Handlebars.SafeString("
" + result + "
");
});

/**
 * Iterate over a list and separate items with a comma. Use just like
 * the #each Handlebars block helper.
 *
 * @param {Array} items The context over which to iterate.
 * @param {Function} fn Compiled template. Passed by Handlebars.
 * @return {String} Resulting compiled comma-separated list.
 * @todo Allow for any separator.
 */
Handlebars.registerHelper('commaeach', function(items, fn) {
  return new Handlebars.SafeString(_.map(items, function(item) {
    return fn(item);
  }).join(', '));
});

Handlebars.registerHelper('default', function(str, ifEmpty) {
  if (str && str.length) {
    return new Handlebars.SafeString(str);
  }
  return new Handlebars.SafeString(ifEmpty);
});<commit_msg>Integrate localization gettext into "default" handlebars helper. (#616)<commit_after>/**
 * Utilities used throughout StoryBase JavaScript apps
 */

Namespace('storybase.utils', {
  capfirst: function(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  /**
   * Geocode using the local geocoder.
   */
  geocode: function(address, options) {
    // TODO: Don't hardcode this URL
    $.ajax('/api/0.1/geocode/', {
      dataType: 'json',
      data: {
        q: address,
      },
      success: function(data, textStatus, jqXHR) {
        if (data.meta.total_count > 0) {
          // Found a point for the address
          options.success({
            'lat': data.objects[0].lat,
            'lng': data.objects[0].lng
          }, data.objects[0].place);
        }
        else {
          options.failure(address);
        }
      }
    });
  },

  /**
   * Return the root of a URL path.
   *
   * This is used to separate the portion of the array that represents
   * the base of a URL path from the portions that represent parameters.
   *
   * This is needed because a variable number of path elements might proceed
   * the part of the URL that represents the base, for example,
   * internatialization path prefixes.
   *
   * This function is useful for providing a value for the 'root' argument
   * to a call to Backbone.history.start().
   *
   * @param {String[]} bases An array of strings that will be used to
   *                         separate the root from the rest of the path.
   * @param {String} [path=window.location.pathname] Path to split, defaults
   *   to the current window's path.
   * @param {int} [extra=0] Extra path parts to include after the matching
   *                        part in the final path.
   *
   * @example
   * getRoot(['build'], '/en/build/f81eca996d754a549ae48cf8ef9622dc/');
   * // Returns '/en/build/'
   * getRoot(['build'], '/en/build/f81eca996d754a549ae48cf8ef9622dc/', 1);
   * // Returns '/en/build/f81eca996d754a549ae48cf8ef9622dc/'
   *
   */
  getRoot: function(bases, path, extra) {
    var pathParts;
    var len = bases.length;
    var i;
    var pos;
    var extraPos;
    if (_.isUndefined(path)) {
      path = window.location.pathname;
    }
    if (_.isUndefined(extra)) {
      extra = 0;
    }
    // Split the path into chunks.  Note that if there are a leading and
    // trailing '/', the first and last array elements will be empty
    // strings
    pathParts = path.split('/');
    for (i = len - 1, pos = -1; pos === -1 && i >= 0; i--) {
      pos = _.lastIndexOf(pathParts, bases[i]);
    }

    if (pos === -1) {
      // None of the base search strings were found.  This
      // shouldn't happen
      throw new Error("Base not found in location parts");
    }

    // Check if there are extra path chunks after the matching chunk
    // and include them
    extraPos = pos + extra;
    if (extraPos + 1 <= pathParts.length && pathParts[extraPos] != "") {
      pos = extraPos;
    }

    return _.first(pathParts, pos + 1).join('/') + '/';
  },

  /**
   * Convert the license value stored in the database (as a String) to
   * form parameters.
   *
   * The parameters keys try to match those of the Creative Commons
   * Web Services API. See http://wiki.creativecommons.org/Web_Services
   *
   * @param {String} [license='CC BY'] License string
   */
  licenseStrToParams: function(license) {
    license = license || 'CC BY';
    var ccLicenses = {
      'CC BY': {
        commercial: 'y',
        derivatives: 'y'
      },
      'CC BY-SA': {
        commercial: 'y',
        derivatives: 'sa'
      },
      'CC BY-ND': {
        commercial: 'y',
        derivatives: 'n'
      },
      'CC BY-NC': {
        commercial: 'n',
        derivatives: 'y'
      },
      'CC BY-NC-SA': {
        commercial: 'n',
        derivatives: 'sa'
      },
      'CC BY-NC-ND': {
        commercial: 'n',
        derivatives: 'n'
      }
    };
    return ccLicenses[license];
  },

  /**
   * Convert the license form parameters to a string to store
   * server-side.
   *
   * The parameters keys try to match those of the Creative Commons
   * Web Services API. See http://wiki.creativecommons.org/Web_Services
   *
   * @param {Object} params Form parameters corresponding to a
   *   particular Creative Commons license. The object must have
   *   'commercial' and 'derivatives' properties.
   */
  licenseParamsToStr: function(params) {
    var ccLicenses = {
      'y': {
        'y': 'CC BY',
        'sa': 'CC BY-SA',
        'n': 'CC BY-ND'
      },
      'n': {
        'y': 'CC BY-NC',
        'sa': 'CC BY-NC-SA',
        'n': 'CC BY-NC-ND'
      }
    };
    return ccLicenses[params['commercial']][params['derivatives']];
  },

  /**
   * Check if the Google Analytics tracking JavaScript has been initialized
   */
  hasAnalytics: function() {
    if (window._gaq) {
      return true;
    }
    else {
      return false;
    }
  }
});

/**
 * Translate a string in a template using Django's gettext Javascript API.
 * @param {String} message The string to be translated
 * @return {String} Translated string
 */
Handlebars.registerHelper('gettext', function(message) {
  return new Handlebars.SafeString(gettext(message));
});

/**
 * Translate a block of template text after first rendering the
 * contents of the template.
 * @return {string} Translated block of text
 */
Handlebars.registerHelper('blockgettext', function(options) {
  return gettext(options.fn(this));
});

/**
 * Return a singular or plural suffix
 * Works in a manner similar to Django's pluralize filter
 * @param {number} count The number used to determine if the singular or
 *    plural suffix should be returned.
 * @param {object} options Hash of options. Optionally contains one key,
 *     'suffix' which is either the plural suffix (e.g. 's') or a
 *     comma-separated list of the singular and plural suffixes
 *     (e.g. 'y,ies')
 * @return {string} Suffix
 */
Handlebars.registerHelper('pluralize', function(count, options) {
  var suffix;
  var defaults = {
    suffix: "s"
  };
  _.defaults(options.hash, defaults);
  var suffixes = options.hash.suffix.split(",");
  if (suffixes.length == 1) {
    // Only one suffix provided.  This likely means plurals are just
    // formed by appending an 's' to the end of the string and keeping
    // the singular as-is.
    // Fill the singular slot of our options with an empty string
    suffixes.unshift("");
  }
  if (count == 1) {
    suffix = suffixes[0];
  }
  else {
    suffix = suffixes[1];
  }

  return suffix;
});

Handlebars.registerHelper('firstparagraph', function(s, maxWords) {
   var result = null;
   var $el = $("

");
   // Toss the text in a dummy div
   $el.html(s);
   if ($el.find('p').length > 0) {
     // Found a paragraph tag.  Return its contents
     result = $el.find('p').html();
   }
   if (result === null) {
     // We didn't find a paragraph tag, try splitting on newlines
     result = s.split(/\r\n|\r|\n/)[0];
   }
   var words = result.split(/\s/);
   if (typeof maxWords === "number" && words.length > maxWords) {
     result = "";
     for (var i = 0; i <= maxWords; i++) {
         result += words[i] + " ";
     }
     result += "…"
   }
   return new Handlebars.SafeString("
" + result + "
");
});

/**
 * Iterate over a list and separate items with a comma. Use just like
 * the #each Handlebars block helper.
 *
 * @param {Array} items The context over which to iterate.
 * @param {Function} fn Compiled template. Passed by Handlebars.
 * @return {String} Resulting compiled comma-separated list.
 * @todo Allow for any separator.
 */
Handlebars.registerHelper('commaeach', function(items, fn) {
  return new Handlebars.SafeString(_.map(items, function(item) {
    return fn(item);
  }).join(', '));
});

Handlebars.registerHelper('default', function(str, ifEmpty) {
  if (str && str.length) {
    return new Handlebars.SafeString(gettext(str));
  }
  return new Handlebars.SafeString(gettext(ifEmpty));
});<|endoftext|>


<commit_before>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'collections/shipments',
    'models/dewar',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, Shipments, Dewar, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountDisplay'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            courier: 'span.courier',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT')
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            this.ui.courier.html('<input type="text" name="DELIVERYAGENT_AGENTNAME" />')
            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                var h = self.history.at(0)
                if (h) self.ui.loc.val(h.get('STORAGELOCATION'))
            })
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountDisplay: function(event) {
            if (event.target.checked) {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', false)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', false)
            } else {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))
            }
        }
    })

})<commit_msg>revert: put code in its previous state<commit_after>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'collections/shipments',
    'collections/dewar',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, Shipments, Dewars, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountDisplay'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            courier: 'span.courier',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT')
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            this.ui.courier.html('<input type="text" name="DELIVERYAGENT_AGENTNAME" />')
            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                var h = self.history.at(0)
                if (h) self.ui.loc.val(h.get('STORAGELOCATION'))
            })
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountDisplay: function(event) {
            if (event.target.checked) {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', false)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', false)
            } else {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))
            }
        }
    })

})<|endoftext|>