<commit_before>/**
 *
 * created by Daniel Bernstein
 */

var centerLayout;
var servicesListPane;
var detailPane;
$(document).ready(function() {

	//alert("starting jquery execution");
	var serviceDetailPaneId = "#service-detail-pane";
	var detailPaneId = "#detail-pane";
	var servicesListViewId = "#services-list-view";
	var servicesListId = "#services-list";

	centerLayout = $('#page-content').layout({
		west__size:				800
	,   west__paneSelector:     servicesListViewId
	,   west__onresize:         "servicesListPane.resizeAll"
	,	center__paneSelector:	detailPaneId
	,   center__onresize:       "detailPane.resizeAll"
	});

	var servicesListPaneLayout = {
			north__paneSelector:	".north"
		,   north__size: 			35
		,	center__paneSelector:	".center"
		,   resizable: 				false
		,   slidable: 				false
		,   spacing_open:			0
		,	togglerLength_open:		0
	};

	servicesListPane = $(servicesListViewId).layout(servicesListPaneLayout);

	//detail pane's layout options
	var detailLayoutOptions = {
				north__paneSelector:	".north"
				,   north__size: 			200
				,	center__paneSelector:	".center"
				,   resizable: 				false
				,   slidable: 				false
				,   spacing_open:			0
				,	togglerLength_open:		0

	};

	detailPane = $(detailPaneId).layout(detailLayoutOptions);

	var resolveServiceCssClass = function(services){
		return "service-replicate";
	};

	var loadDeploymentDetail = function(service,deployment){

		if(service == null){

			$(detailPaneId).fadeOut("slow", function(){
				$(this).html('');
			});
			return;
		};
		var serviceDetailPane = $(serviceDetailPaneId).clone();

		//set the title of the pane
		$(".service-name", serviceDetailPane.first()).html(service.displayName);
		$(".service-version", serviceDetailPane.first()).html(service.serviceVersion);
		$("#deployment-id", serviceDetailPane.first()).val(deriveDeploymentId(service,deployment));

		var centerPane = $(".center",serviceDetailPane.first());
		centerPane.html("");

		//deploy/undeploy switch definition and bindings
		$(".deploy-switch",serviceDetailPane.first()).onoffswitch({
			   		initialState: "on"
								, onStateClass: "on left"
								, onIconClass: "checkbox"
								, offStateClass: "off right"
								, offIconClass: "x"
								, onText: "Deploy"
								, offText: "Undeploy"
		}).bind("turnOff", function(evt, future){

			var callback = {
					begin: function(){
						dc.busy("Undeploying " + service.displayName);
					},

					success: function(){
						dc.done();
						$(servicesListId).selectablelist("removeById", deriveDeploymentId(service,deployment));
						future.success();
					},

					failure: function(text){
						dc.done();
						alert("failed to undeploy service!");
						if(future.failure != undefined){
							future.failure(text);
						}
					}
			};

			dc.service.Undeploy(service, deployment,callback);
		});

		$(".reconfigure-button",serviceDetailPane.first()).click(function(){
			$("#reconfigure-service-dialog").dialog("open");
		});

		dc.service.GetServiceDeploymentConfig(service, deployment, {
			failure: function(message){
				alert("Failed to get service deployment details: " + message);
			},

			success: function(response){
				var config = response.properties;
				var data = new Array();
				for(i = 0; i < config.length; i++){
					data[i] = [config[i].name, config[i].value];
				}

				centerPane.prepend(
						$.fn.create("div")
						.tabularexpandopanel(
							{
							  title: "Details",
							  data:  data
			                }
						)
					);
			},
		});

		centerPane.append(
			$.fn.create("div")
			.tabularexpandopanel(
				{title: "Configuration",
				 data: convertUserConfigsToArray(deployment.userConfigs)
                 }
			)
		);

		$(detailPaneId).replaceContents(serviceDetailPane, detailLayoutOptions);

	};

	var convertUserConfigsToArray = function(userConfigs){
		var a = new Array();
		for(u in userConfigs){
			var uc = userConfigs[u];
			a.push([uc.displayName, resolveUserConfigValue(uc)]);
		}

		return a;
	};

	////////////////////////////////////////////////////////
	///util functions for handling service deployment element ids
	var deriveDeploymentId = function(service, deployment){
		return service.id + "-" + deployment.id;
	};

	var extractServiceId = function(id){
		return id.split("-")[0];
	};

	var extractDeploymentId = function(id){
		return id.split("-")[1];
	};

	var resolveUserConfigValue =  function (uc){
		if(uc.displayValue != undefined){
			return uc.displayValue;
		}else {
			if(uc.options != undefined){
    			var options = uc.options[0];
    			var count =	 0;
    			for(var i = 0; i < options.length; i++){
    				var option = options[i];
    				if(option.selected.toString() == "true"){
    					if(count > 0) value+=", ";
	    				value += option.displayName;
	    				count++;
    				}
    			}

    			return value;
			}else{
				var value = "no value";
			}
		}
	};

	var loadDeployedServiceList = function(services){
		//alert("services count = " + services.length);
		var servicesList = $(servicesListId);
		var panel = $("#deployed-services");
		var table = $("#deployed-services-table");

		table.hide();
		$(".dc-message", panel).remove();

		servicesList.selectablelist({selectable: false});
		servicesList.selectablelist("clear");

		if(services == null || services == undefined || services.length == 0){
			panel.append($.fn.create("span").addClass("dc-message").html("No services are currently deployed."));
			return;
		}

		for(i in services){
			var service = services[i];
			for(d in service.deployments){
				var deployment = service.deployments[d];
				var item =  $.fn.create(("tr"))
								.attr("id", deriveDeploymentId(service,deployment))
								.addClass("dc-item")
								.addClass(resolveServiceCssClass(service))
								.append($.fn.create("td").addClass("icon").append($.fn.create("div")))
								.append($.fn.create("td").html(service.displayName + " - " + service.serviceVersion))
								.append($.fn.create("td").html(deployment.hostname))
								.append($.fn.create("td").html(deployment.status[0]));

				servicesList.selectablelist('addItem',item,{service:service, deployment:deployment});
			}
		}

		table.show();
		//bind for current item change listener
		servicesList.bind("currentItemChanged", function(evt,state){
			var currentItem = state.currentItem;
			var service = null;
			var deployment = null;
			if(currentItem != null){
				var data = currentItem.data;
				if(data != null || data != undefined){
					service = data.service;
					deployment = data.deployment;
				}
			}
			loadDeploymentDetail(service,deployment);
		});

	};

	var refreshDeployedServices = function(){

		dc.service.GetDeployedServices({
			begin: function(){
				dc.busy("Retrieving services...");
			},
			success: function(data){
				dc.done();
				loadDeployedServiceList(data.services);
				var id = $(detailPaneId + " #deployment-id").val();
				if(id != null && id != undefined){
					$(servicesListId).selectablelist("setCurrentItemById", id, true);
				}else{
					$(servicesListId).selectablelist("setFirstItemAsCurrent");
				}
			},
			failure: function(text){
				dc.done();
				alert("get available services failed: " + text);
			},
		});
	};

	//dialogs
	var dialogLayout;

	var deployServiceConfig = $("#deploy-service-config").serviceconfig({});

	$('#available-services-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		closeOnEscape:true,
		modal: true,
		width:700,

		buttons: {
			Cancel: function(){
				$(this).dialog("close");
			},
			Next: function(){
				var currentItem = $("#available-services-list").selectablelist("currentItem");
				if(currentItem == null || currentItem == undefined){
					alert("You must select a service.");
					return;
				}

				$(this).dialog("close");

				var service = currentItem.data;
				deployServiceConfig.serviceconfig("load", service);
				$("#configure-service-dialog").dialog("open");
			}

		},
		close: function() {

		},

		open: function(e){
			var that = this;

			if(!dialogLayout){
				dialogLayout = $(this).layout({
					resizeWithWindow:	false	// resizes with the dialog, not the window
					,  spacing_open:  0
					,  spacing_closed: 0
					,	west__spacing_open:		6
					,	west__spacing_closed:	6
					,	west__size:			300
					,   north__resizable: 			false
					,	north__slidable: 			false
					,   west__slidable: 		true
					,   west__resizable:        true

				});
			}

			$("#available-services-dialog").listdetailviewer(
				{
						selectableListId: "available-services-list"
					,	detailId:  "service-detail"
					,   detailPreparer: function(data){
							return $.fn.create("div")
										.append($.fn.create("h2").html(data.displayName))
										.append($.fn.create("p").html(data.description));
						}
				}
			);

			dc.service.GetAvailableServices({
				begin: function(){
					$("#available-services-dialog .dc-message").html("Loading...");
				},
				success: function(data){
					$("#available-services-dialog .dc-message").html("");
					var services = data.services;
					if(services == undefined){
						$("#available-services-dialog .dc-message").html("There are no available services.");
						return;
					}
					for(i in services){
						var service = services[i];

						$("#available-services-list")
							.selectablelist("addItem", $.fn.create("tr")
												.attr("id", service.id)
												.addClass(dc.getServiceTypeImageClass(service.serviceName))
												.append($.fn.create("td").addClass("icon").append($.fn.create("div")))
												.append($.fn.create("td").html(service.displayName)), service);

					}
				},
				failure: function(text){
					$("#available-services-dialog .dc-message").hide();
					$("#available-services-dialog .dc-message").html("Unable to load services: " + text);
				},
			});

		},

	});

	$(".deploy-service-button").click(function(){
		$("#available-services-dialog").dialog("open");
	});

	var serviceConfig = $("#reconfigure-service-config").serviceconfig({});

	$('#reconfigure-service-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		width:700,
		closeOnEscape:true,
		modal: true,
		buttons: {
			"Redeploy": function(){

				var data = serviceConfig.serviceconfig("data");
				$("#reconfigure-service-dialog").dialog("close");

				var form = $("#reconfigure-service-dialog form");
				var formData = form.serialize();
				dc.busy("Reploying " + data.service.displayName);
				dc.ajax({
					url: "/duradmin/services/service?method=reconfigure",
					data: formData,
					type: "POST",
					success: function(data){
						dc.done();
						refreshDeployedServices();
					},
				    failure: function(textStatus){
						dc.done();
				    	alert("failed: " + textStatus);
				    },
				});

			},

			"Cancel": function(){
				$("#reconfigure-service-dialog").dialog("close");
			}
		},

		close: function() {

		},
		open: function(e){
			var currentItem = $(servicesListId).selectablelist("currentItem");

			if(currentItem == null || currentItem == undefined){
				$(this).dialog("close");
				alert("You must select a service deployment.");
				return;
			}

			var data = currentItem.data;

			serviceConfig.serviceconfig("load", data.service, data.deployment);

		},
	});

	$('#configure-service-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		width:700,
		closeOnEscape:true,
		modal: true,
		close: function() {

		},

		buttons: {
			"< Back": function(){
				$("#configure-service-dialog").dialog("close");
				$("#available-services-dialog").dialog("open");
			},

			"Deploy": function(){

				var service = deployServiceConfig.serviceconfig("data").service;
				$("#configure-service-dialog").dialog("close");

				var form = $("#configure-service-dialog form");
				var data = form.serialize();
				dc.busy("Deploying " + service.displayName);
				dc.ajax({
					url: "/duradmin/services/service?method=deploy",
					data: data,
					type: "POST",
					success: function(data){
						dc.done();
						loadDeploymentDetail(data.serviceInfo, data.deployment);
						refreshDeployedServices();
					},

				    failure: function(textStatus){
						dc.done();
				    	alert("failed: " + textStatus);
				    },
				});

			},

			"Cancel": function(){
				$("#configure-service-dialog").dialog("close");
			}
		},

		open: function(e){
		},
	});

	$(".ui-dialog-titlebar").hide();

	setTimeout(function(){
		refreshDeployedServices();
	}, 1000);

});<commit_msg>filtering the exclusions based on the value of the exclusion definition in the static configuration view<commit_after>/**
 *
 * created by Daniel Bernstein
 */

var centerLayout;
var servicesListPane;
var detailPane;
$(document).ready(function() {

	//alert("starting jquery execution");
	var serviceDetailPaneId = "#service-detail-pane";
	var detailPaneId = "#detail-pane";
	var servicesListViewId = "#services-list-view";
	var servicesListId = "#services-list";

	centerLayout = $('#page-content').layout({
		west__size:				800
	,   west__paneSelector:     servicesListViewId
	,   west__onresize:         "servicesListPane.resizeAll"
	,	center__paneSelector:	detailPaneId
	,   center__onresize:       "detailPane.resizeAll"
	});

	var servicesListPaneLayout = {
			north__paneSelector:	".north"
		,   north__size: 			35
		,	center__paneSelector:	".center"
		,   resizable: 				false
		,   slidable: 				false
		,   spacing_open:			0
		,	togglerLength_open:		0
	};

	servicesListPane = $(servicesListViewId).layout(servicesListPaneLayout);

	//detail pane's layout options
	var detailLayoutOptions = {
				north__paneSelector:	".north"
				,   north__size: 			200
				,	center__paneSelector:	".center"
				,   resizable: 				false
				,   slidable: 				false
				,   spacing_open:			0
				,	togglerLength_open:		0

	};

	detailPane = $(detailPaneId).layout(detailLayoutOptions);

	var resolveServiceCssClass = function(services){
		return "service-replicate";
	};

	var loadDeploymentDetail = function(service,deployment){

		if(service == null){

			$(detailPaneId).fadeOut("slow", function(){
				$(this).html('');
			});
			return;
		};
		var serviceDetailPane = $(serviceDetailPaneId).clone();

		//set the title of the pane
		$(".service-name", serviceDetailPane.first()).html(service.displayName);
		$(".service-version", serviceDetailPane.first()).html(service.serviceVersion);
		$("#deployment-id", serviceDetailPane.first()).val(deriveDeploymentId(service,deployment));

		var centerPane = $(".center",serviceDetailPane.first());
		centerPane.html("");

		//deploy/undeploy switch definition and bindings
		$(".deploy-switch",serviceDetailPane.first()).onoffswitch({
			   		initialState: "on"
								, onStateClass: "on left"
								, onIconClass: "checkbox"
								, offStateClass: "off right"
								, offIconClass: "x"
								, onText: "Deploy"
								, offText: "Undeploy"
		}).bind("turnOff", function(evt, future){

			var callback = {
					begin: function(){
						dc.busy("Undeploying " + service.displayName);
					},

					success: function(){
						dc.done();
						$(servicesListId).selectablelist("removeById", deriveDeploymentId(service,deployment));
						future.success();
					},

					failure: function(text){
						dc.done();
						alert("failed to undeploy service!");
						if(future.failure != undefined){
							future.failure(text);
						}
					}
			};

			dc.service.Undeploy(service, deployment,callback);
		});

		$(".reconfigure-button",serviceDetailPane.first()).click(function(){
			$("#reconfigure-service-dialog").dialog("open");
		});

		dc.service.GetServiceDeploymentConfig(service, deployment, {
			failure: function(message){
				alert("Failed to get service deployment details: " + message);
			},

			success: function(response){
				var config = response.properties;
				var data = new Array();
				for(i = 0; i < config.length; i++){
					data[i] = [config[i].name, config[i].value];
				}

				centerPane.prepend(
						$.fn.create("div")
						.tabularexpandopanel(
							{
							  title: "Details",
							  data:  data
			                }
						)
					);
			},
		});

		centerPane.append(
			$.fn.create("div")
			.tabularexpandopanel(
				{title: "Configuration",
				 data: convertUserConfigsToArray(deployment.userConfigs)
                 }
			)
		);

		$(detailPaneId).replaceContents(serviceDetailPane, detailLayoutOptions);

	};

	var resolveUserConfigValue =  function(uc, delim, showRaw){
		showRaw = (showRaw == undefined ? false : showRaw);
		delim   = (delim == undefined ? ", " : delim);
		if(uc.inputType == "TEXT"){
			return uc.displayValue;
		}else {
			var value = "";
			if(uc.options != undefined){
    			var options = uc.options;
    			var count =	 0;
    			for(var i = 0; i < options.length; i++){
    				var option = options[i];
    				if(option.selected.toString() == "true"){
    					if(count > 0) value+=delim;
	    				value += (showRaw ? option.value : option.displayName);
	    				count++;
    				}
    			}
    			return value;
			}else{
				var value = "no value";
			}
		}
	};

	var convertUserConfigsToArray = function(userConfigs){
		var a = new Array();
		var defs = new Array();
		var uc;
		for(u in userConfigs){
			uc = userConfigs[u];
			if(uc.exclusion == "EXCLUSION_DEFINITION"){
				defs.push(uc);
			}
		}

		for(u in userConfigs){
			uc = userConfigs[u];
			var row = [uc.displayName, resolveUserConfigValue(uc)];
			var addRow = false;
			if(uc.exclusion != undefined && uc.exclusion != "EXCLUSION_DEFINITION"){
				var exclusions = uc.exclusion.split("|");
				var k,m,n,defVals;
				for(k in defs){
					defVals = resolveUserConfigValue(defs[k], "|", true);
					defVals = defVals.split("|");
					for(m in exclusions){
						for(n in defVals){
							if(exclusions[m] == defVals[n]){
								addRow = true;
								break;
							}
						}
						if(addRow) break;
					}
					if(addRow) break;
				}
			}else{
				addRow = true;
			}

			if(addRow){
				a.push(row);
			}
		}
		return a;
	};

	////////////////////////////////////////////////////////
	///util functions for handling service deployment element ids
	var deriveDeploymentId = function(service, deployment){
		return service.id + "-" + deployment.id;
	};

	var extractServiceId = function(id){
		return id.split("-")[0];
	};

	var extractDeploymentId = function(id){
		return id.split("-")[1];
	};

	var loadDeployedServiceList = function(services){
		//alert("services count = " + services.length);
		var servicesList = $(servicesListId);
		var panel = $("#deployed-services");
		var table = $("#deployed-services-table");

		table.hide();
		$(".dc-message", panel).remove();

		servicesList.selectablelist({selectable: false});
		servicesList.selectablelist("clear");

		if(services == null || services == undefined || services.length == 0){
			panel.append($.fn.create("span").addClass("dc-message").html("No services are currently deployed."));
			return;
		}

		for(i in services){
			var service = services[i];
			for(d in service.deployments){
				var deployment = service.deployments[d];
				var item =  $.fn.create(("tr"))
								.attr("id", deriveDeploymentId(service,deployment))
								.addClass("dc-item")
								.addClass(resolveServiceCssClass(service))
								.append($.fn.create("td").addClass("icon").append($.fn.create("div")))
								.append($.fn.create("td").html(service.displayName + " - " + service.serviceVersion))
								.append($.fn.create("td").html(deployment.hostname))
								.append($.fn.create("td").html(deployment.status[0]));

				servicesList.selectablelist('addItem',item,{service:service, deployment:deployment});
			}
		}

		table.show();
		//bind for current item change listener
		servicesList.bind("currentItemChanged", function(evt,state){
			var currentItem = state.currentItem;
			var service = null;
			var deployment = null;
			if(currentItem != null){
				var data = currentItem.data;
				if(data != null || data != undefined){
					service = data.service;
					deployment = data.deployment;
				}
			}
			loadDeploymentDetail(service,deployment);
		});

	};

	var refreshDeployedServices = function(){

		dc.service.GetDeployedServices({
			begin: function(){
				dc.busy("Retrieving services...");
			},
			success: function(data){
				dc.done();
				loadDeployedServiceList(data.services);
				var id = $(detailPaneId + " #deployment-id").val();
				if(id != null && id != undefined){
					$(servicesListId).selectablelist("setCurrentItemById", id, true);
				}else{
					$(servicesListId).selectablelist("setFirstItemAsCurrent");
				}
			},
			failure: function(text){
				dc.done();
				alert("get available services failed: " + text);
			},
		});
	};

	//dialogs
	var dialogLayout;

	var deployServiceConfig = $("#deploy-service-config").serviceconfig({});

	$('#available-services-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		closeOnEscape:true,
		modal: true,
		width:700,

		buttons: {
			Cancel: function(){
				$(this).dialog("close");
			},
			Next: function(){
				var currentItem = $("#available-services-list").selectablelist("currentItem");
				if(currentItem == null || currentItem == undefined){
					alert("You must select a service.");
					return;
				}

				$(this).dialog("close");

				var service = currentItem.data;
				deployServiceConfig.serviceconfig("load", service);
				$("#configure-service-dialog").dialog("open");
			}

		},
		close: function() {

		},

		open: function(e){
			var that = this;

			if(!dialogLayout){
				dialogLayout = $(this).layout({
					resizeWithWindow:	false	// resizes with the dialog, not the window
					,  spacing_open:  0
					,  spacing_closed: 0
					,	west__spacing_open:		6
					,	west__spacing_closed:	6
					,	west__size:			300
					,   north__resizable: 			false
					,	north__slidable: 			false
					,   west__slidable: 		true
					,   west__resizable:        true

				});
			}

			$("#available-services-dialog").listdetailviewer(
				{
						selectableListId: "available-services-list"
					,	detailId:  "service-detail"
					,   detailPreparer: function(data){
							return $.fn.create("div")
										.append($.fn.create("h2").html(data.displayName))
										.append($.fn.create("p").html(data.description));
						}
				}
			);

			dc.service.GetAvailableServices({
				begin: function(){
					$("#available-services-dialog .dc-message").html("Loading...");
				},
				success: function(data){
					$("#available-services-dialog .dc-message").html("");
					var services = data.services;
					if(services == undefined){
						$("#available-services-dialog .dc-message").html("There are no available services.");
						return;
					}
					for(i in services){
						var service = services[i];

						$("#available-services-list")
							.selectablelist("addItem", $.fn.create("tr")
												.attr("id", service.id)
												.addClass(dc.getServiceTypeImageClass(service.serviceName))
												.append($.fn.create("td").addClass("icon").append($.fn.create("div")))
												.append($.fn.create("td").html(service.displayName)), service);

					}
				},
				failure: function(text){
					$("#available-services-dialog .dc-message").hide();
					$("#available-services-dialog .dc-message").html("Unable to load services: " + text);
				},
			});

		},

	});

	$(".deploy-service-button").click(function(){
		$("#available-services-dialog").dialog("open");
	});

	var serviceConfig = $("#reconfigure-service-config").serviceconfig({});

	$('#reconfigure-service-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		width:700,
		closeOnEscape:true,
		modal: true,
		buttons: {
			"Redeploy": function(){

				var data = serviceConfig.serviceconfig("data");
				$("#reconfigure-service-dialog").dialog("close");

				var form = $("#reconfigure-service-dialog form");
				var formData = form.serialize();
				dc.busy("Reploying " + data.service.displayName);
				dc.ajax({
					url: "/duradmin/services/service?method=reconfigure",
					data: formData,
					type: "POST",
					success: function(data){
						dc.done();
						refreshDeployedServices();
					},
				    failure: function(textStatus){
						dc.done();
				    	alert("failed: " + textStatus);
				    },
				});

			},

			"Cancel": function(){
				$("#reconfigure-service-dialog").dialog("close");
			}
		},

		close: function() {

		},
		open: function(e){
			var currentItem = $(servicesListId).selectablelist("currentItem");

			if(currentItem == null || currentItem == undefined){
				$(this).dialog("close");
				alert("You must select a service deployment.");
				return;
			}

			var data = currentItem.data;

			serviceConfig.serviceconfig("load", data.service, data.deployment);

		},
	});

	$('#configure-service-dialog').dialog({
		autoOpen: false,
		show: 'fade',
		hide: 'fade',
		resizable: false,
		height: 500,
		width:700,
		closeOnEscape:true,
		modal: true,
		close: function() {

		},

		buttons: {
			"< Back": function(){
				$("#configure-service-dialog").dialog("close");
				$("#available-services-dialog").dialog("open");
			},

			"Deploy": function(){

				var service = deployServiceConfig.serviceconfig("data").service;
				$("#configure-service-dialog").dialog("close");

				var form = $("#configure-service-dialog form");
				var data = form.serialize();
				dc.busy("Deploying " + service.displayName);
				dc.ajax({
					url: "/duradmin/services/service?method=deploy",
					data: data,
					type: "POST",
					success: function(data){
						dc.done();
						loadDeploymentDetail(data.serviceInfo, data.deployment);
						refreshDeployedServices();
					},

				    failure: function(textStatus){
						dc.done();
				    	alert("failed: " + textStatus);
				    },
				});

			},

			"Cancel": function(){
				$("#configure-service-dialog").dialog("close");
			}
		},

		open: function(e){
		},
	});

	$(".ui-dialog-titlebar").hide();

	setTimeout(function(){
		refreshDeployedServices();
	}, 1000);

});<|endoftext|>


<commit_before>'use strict';

angular.module('app').controller('rgiNewRefDialogCtrl', function (
    $scope,
    $route,
    $timeout,
    FileUploader,
    ngDialog,
    rgiNotifier,
    rgiAnswerMethodSrvc,
    rgiRequestSubmitterSrvc
) {
    $scope.answer_update = $scope.$parent.answer;
    ////TODO REPLACE WITH EXISITING REFERENCE SET
    //$scope.existing_ref = [
    //    {text: 'Add Document', value: 'document'},
    //    {text: 'Add Webpage', value: 'webpage'},
    //    {text: 'Add Interview', value: 'interview'}
    //];

    function isURLReal(fullyQualifiedURL) {
        var URL = encodeURIComponent(fullyQualifiedURL),
            dfd = $.Deferred(),
            checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22' + URL + '%22&format=json');

        checkURLPromise
            .done(function(res) {
                // results should be null if the page 404s or the domain doesn't work
                if (res.query.results) {
                    dfd.resolve(true);
                } else {
                    dfd.reject(false);
                }
            })
            .fail(function () {
                dfd.reject('failed');
            });
        return dfd.promise();
    }

    $scope.fileUrl = '';

    $scope.uploadFileByUrl = function() {
        var handleFileUploadStatus = function(response) {
            $scope.uploader.queue[$scope.uploader.queue.length - 1].progress = response.data.completion * 100;

            if(response.data.completion < 1) {
                $timeout(function() {
                    rgiRequestSubmitterSrvc.get('/api/remote-file/upload-progress/' + response.data._id).then(handleFileUploadStatus);
                });
            } else {
                uploader.onCompleteItem({}, {}, null);
            }
        };

        isURLReal($scope.fileUrl)
            .fail(function () {
                rgiNotifier.error('The remote file is not found');
            })
            .done(function () {
                rgiRequestSubmitterSrvc.get('/api/remote-file-upload?url=' + encodeURIComponent($scope.fileUrl)).then(function(response) {
                    $scope.uploader.queue.push({
                        file: {
                            name: $scope.fileUrl.split('/')[$scope.fileUrl.split('/').length - 1],
                            size: response.data.size
                        },
                        isUploading: true,
                        progress: response.data.completion * 100
                    });
                    handleFileUploadStatus(response);
                });
            });
    };

    //DATEPICKER OPTS
    $scope.date_format = 'MMMM d, yyyy';
    var today = new Date();
    $scope.date_default = today;
    $scope.date_max_limit = today;

    var uploader = $scope.uploader = new FileUploader({
        isHTML5: true,
        withCredentials: true,
        url: 'file-upload'
    });
    uploader.filters.push({
        name: 'customFilter',
        fn: function () {
            return this.queue.length < 1;
        }
    });

    uploader.onCompleteItem = function (fileItem, response, status) {
        if (status === 400) {
            $scope.uploader.queue = [];
            rgiNotifier.error(response.reason);
        } else {// TODO add cancel upload after initial document pass
            $scope.new_document = response;

            $scope.uploader.queue = [];

            $scope.value = true;
            var scope = $scope.$parent;
            scope.new_document = $scope.new_document;
            ngDialog.close('ngdialog1');
            ngDialog.open({
                template: 'partials/dialogs/new-document-dialog',
                controller: 'rgiNewDocumentDialogCtrl',
                className: 'ngdialog-theme-default',
                scope: scope
            });
        }

    };

    $scope.webRefSubmit = function () {
        var new_answer_data = $scope.answer_update,
            current_user = $scope.$parent.current_user,
            url, access_date;

        if(!new_answer_data.web_ref_url || !new_answer_data.web_ref_title) {
            rgiNotifier.error('You must enter a title and a url!');
        } else {
            if (new_answer_data.web_ref_url.split('://')[0] === 'http' || new_answer_data.web_ref_url.split('://')[0] === 'https') {
                url = new_answer_data.web_ref_url;
            } else {
                url = 'http://' + new_answer_data.web_ref_url;
            }
            if(!new_answer_data.web_ref_access_date) {
                access_date = $scope.date_default.toISOString();
            } else {
                access_date = new Date(new_answer_data.web_ref_access_date).toISOString();
            }
            isURLReal(url)
                .fail(function () {
                    rgiNotifier.error('Website does not exists');
                })
                //TODO Take a snapshot of url and add as a document ref
                .done(function () {
                    var new_ref_data = {
                        title: new_answer_data.web_ref_title,
                        URL: url,
                        access_date: access_date,
                        comment: {
                            date: new Date().toISOString(),
                            author: current_user._id,
                            author_name: current_user.firstName + ' ' + current_user.lastName,
                            role: current_user.role
                        }
                    };
                    if ($scope.answer_update.web_ref_comment !== undefined) {
                        new_ref_data.comment.content = $scope.answer_update.web_ref_comment;
                    }
                    new_answer_data.references.web.push(new_ref_data);

                    rgiAnswerMethodSrvc.updateAnswer(new_answer_data).then(function () {
                        $scope.closeThisDialog();
                        rgiNotifier.notify('Reference added!');
                        $route.reload();
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
                });
        }
    };

    $scope.humanRefSubmit = function () {

        var new_answer_data = $scope.answer_update,
            current_user = $scope.$parent.current_user,
            new_ref_data, contact_date;

        if (!new_answer_data.human_ref_first_name || !new_answer_data.human_ref_first_name) {
            rgiNotifier.error('You must enter an interviewee first and last name!');
        } else if (!new_answer_data.human_ref_email) {
            rgiNotifier.error('You must enter a valid email address!');
        } else {
            var email_domain = 'http://' + new_answer_data.human_ref_email.split('@')[1];
            if (email_domain === 'http://undefined') {
                rgiNotifier.error('You must enter a valid email address!');
            } else {
                if(!new_answer_data.human_ref_contact_date) {
                    contact_date = $scope.date_default.toISOString();
                } else {
                    contact_date = new Date(new_answer_data.human_ref_contact_date).toISOString();
                }
                new_ref_data = {
                    first_name: new_answer_data.human_ref_first_name,
                    last_name: new_answer_data.human_ref_last_name,
                    phone: new_answer_data.human_ref_phone,
                    email: new_answer_data.human_ref_email,
                    contact_date: contact_date,
                    comment: {
                        date: new Date().toISOString(),
                        author: current_user._id,
                        author_name: current_user.firstName + ' ' + current_user.lastName,
                        role: current_user.role
                    }
                };

                if (new_answer_data.human_ref_comment !== undefined) {
                    new_ref_data.comment.content = new_answer_data.human_ref_comment;
                }

                new_answer_data.references.human.push(new_ref_data);

                rgiAnswerMethodSrvc.updateAnswer(new_answer_data).then(function () {
                    $scope.closeThisDialog();
                    rgiNotifier.notify('Reference added!');
                    $route.reload();
                }, function (reason) {
                    rgiNotifier.error(reason);
                });
            }
        }
        //
        ////TODO validate that email domain exists
        //if (email_domain === 'http://undefined') {
        //    rgiNotifier.error('You must enter a valid email address!')
        //} else {
        //    //isURLReal(email_domain)
        //    //    .fail(function (res) {
        //    //        console.log(res);
        //    //        rgiNotifier.error('Email Domain does not appear to be valid');
        //    //    })
        //    //    .done(function (res) {
        //    //        console.log(res);
        //    //    });
        //
        //}
    };

    $scope.closeDialog = function () {
        $scope.$parent.ref_selection = '';
        ngDialog.close();
    };
});

<commit_msg>increase file upload progress poll interval<commit_after>'use strict';

angular.module('app').controller('rgiNewRefDialogCtrl', function (
    $scope,
    $route,
    $timeout,
    FileUploader,
    ngDialog,
    rgiNotifier,
    rgiAnswerMethodSrvc,
    rgiRequestSubmitterSrvc
) {
    $scope.answer_update = $scope.$parent.answer;
    ////TODO REPLACE WITH EXISITING REFERENCE SET
    //$scope.existing_ref = [
    //    {text: 'Add Document', value: 'document'},
    //    {text: 'Add Webpage', value: 'webpage'},
    //    {text: 'Add Interview', value: 'interview'}
    //];

    function isURLReal(fullyQualifiedURL) {
        var URL = encodeURIComponent(fullyQualifiedURL),
            dfd = $.Deferred(),
            checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22' + URL + '%22&format=json');

        checkURLPromise
            .done(function(res) {
                // results should be null if the page 404s or the domain doesn't work
                if (res.query.results) {
                    dfd.resolve(true);
                } else {
                    dfd.reject(false);
                }
            })
            .fail(function () {
                dfd.reject('failed');
            });
        return dfd.promise();
    }

    $scope.fileUrl = '';

    $scope.uploadFileByUrl = function() {
        var handleFileUploadStatus = function(response) {
            $scope.uploader.queue[$scope.uploader.queue.length - 1].progress = response.data.completion * 100;

            if(response.data.completion < 1) {
                $timeout(function() {
                    rgiRequestSubmitterSrvc.get('/api/remote-file/upload-progress/' + response.data._id).then(handleFileUploadStatus);
                }, 1000);
            } else {
                uploader.onCompleteItem({}, {}, null);
            }
        };

        isURLReal($scope.fileUrl)
            .fail(function () {
                rgiNotifier.error('The remote file is not found');
            })
            .done(function () {
                rgiRequestSubmitterSrvc.get('/api/remote-file-upload?url=' + encodeURIComponent($scope.fileUrl)).then(function(response) {
                    $scope.uploader.queue.push({
                        file: {
                            name: $scope.fileUrl.split('/')[$scope.fileUrl.split('/').length - 1],
                            size: response.data.size
                        },
                        isUploading: true,
                        progress: response.data.completion * 100
                    });
                    handleFileUploadStatus(response);
                });
            });
    };

    //DATEPICKER OPTS
    $scope.date_format = 'MMMM d, yyyy';
    var today = new Date();
    $scope.date_default = today;
    $scope.date_max_limit = today;

    var uploader = $scope.uploader = new FileUploader({
        isHTML5: true,
        withCredentials: true,
        url: 'file-upload'
    });
    uploader.filters.push({
        name: 'customFilter',
        fn: function () {
            return this.queue.length < 1;
        }
    });

    uploader.onCompleteItem = function (fileItem, response, status) {
        if (status === 400) {
            $scope.uploader.queue = [];
            rgiNotifier.error(response.reason);
        } else {// TODO add cancel upload after initial document pass
            $scope.new_document = response;

            $scope.uploader.queue = [];

            $scope.value = true;
            var scope = $scope.$parent;
            scope.new_document = $scope.new_document;
            ngDialog.close('ngdialog1');
            ngDialog.open({
                template: 'partials/dialogs/new-document-dialog',
                controller: 'rgiNewDocumentDialogCtrl',
                className: 'ngdialog-theme-default',
                scope: scope
            });
        }

    };

    $scope.webRefSubmit = function () {
        var new_answer_data = $scope.answer_update,
            current_user = $scope.$parent.current_user,
            url, access_date;

        if(!new_answer_data.web_ref_url || !new_answer_data.web_ref_title) {
            rgiNotifier.error('You must enter a title and a url!');
        } else {
            if (new_answer_data.web_ref_url.split('://')[0] === 'http' || new_answer_data.web_ref_url.split('://')[0] === 'https') {
                url = new_answer_data.web_ref_url;
            } else {
                url = 'http://' + new_answer_data.web_ref_url;
            }
            if(!new_answer_data.web_ref_access_date) {
                access_date = $scope.date_default.toISOString();
            } else {
                access_date = new Date(new_answer_data.web_ref_access_date).toISOString();
            }
            isURLReal(url)
                .fail(function () {
                    rgiNotifier.error('Website does not exists');
                })
                //TODO Take a snapshot of url and add as a document ref
                .done(function () {
                    var new_ref_data = {
                        title: new_answer_data.web_ref_title,
                        URL: url,
                        access_date: access_date,
                        comment: {
                            date: new Date().toISOString(),
                            author: current_user._id,
                            author_name: current_user.firstName + ' ' + current_user.lastName,
                            role: current_user.role
                        }
                    };
                    if ($scope.answer_update.web_ref_comment !== undefined) {
                        new_ref_data.comment.content = $scope.answer_update.web_ref_comment;
                    }
                    new_answer_data.references.web.push(new_ref_data);

                    rgiAnswerMethodSrvc.updateAnswer(new_answer_data).then(function () {
                        $scope.closeThisDialog();
                        rgiNotifier.notify('Reference added!');
                        $route.reload();
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
                });
        }
    };

    $scope.humanRefSubmit = function () {

        var new_answer_data = $scope.answer_update,
            current_user = $scope.$parent.current_user,
            new_ref_data, contact_date;

        if (!new_answer_data.human_ref_first_name || !new_answer_data.human_ref_first_name) {
            rgiNotifier.error('You must enter an interviewee first and last name!');
        } else if (!new_answer_data.human_ref_email) {
            rgiNotifier.error('You must enter a valid email address!');
        } else {
            var email_domain = 'http://' + new_answer_data.human_ref_email.split('@')[1];
            if (email_domain === 'http://undefined') {
                rgiNotifier.error('You must enter a valid email address!');
            } else {
                if(!new_answer_data.human_ref_contact_date) {
                    contact_date = $scope.date_default.toISOString();
                } else {
                    contact_date = new Date(new_answer_data.human_ref_contact_date).toISOString();
                }
                new_ref_data = {
                    first_name: new_answer_data.human_ref_first_name,
                    last_name: new_answer_data.human_ref_last_name,
                    phone: new_answer_data.human_ref_phone,
                    email: new_answer_data.human_ref_email,
                    contact_date: contact_date,
                    comment: {
                        date: new Date().toISOString(),
                        author: current_user._id,
                        author_name: current_user.firstName + ' ' + current_user.lastName,
                        role: current_user.role
                    }
                };

                if (new_answer_data.human_ref_comment !== undefined) {
                    new_ref_data.comment.content = new_answer_data.human_ref_comment;
                }

                new_answer_data.references.human.push(new_ref_data);

                rgiAnswerMethodSrvc.updateAnswer(new_answer_data).then(function () {
                    $scope.closeThisDialog();
                    rgiNotifier.notify('Reference added!');
                    $route.reload();
                }, function (reason) {
                    rgiNotifier.error(reason);
                });
            }
        }
        //
        ////TODO validate that email domain exists
        //if (email_domain === 'http://undefined') {
        //    rgiNotifier.error('You must enter a valid email address!')
        //} else {
        //    //isURLReal(email_domain)
        //    //    .fail(function (res) {
        //    //        console.log(res);
        //    //        rgiNotifier.error('Email Domain does not appear to be valid');
        //    //    })
        //    //    .done(function (res) {
        //    //        console.log(res);
        //    //    });
        //
        //}
    };

    $scope.closeDialog = function () {
        $scope.$parent.ref_selection = '';
        ngDialog.close();
    };
});

<|endoftext|>


<commit_before>//check if an image exists
function imageExists(image_url){
    var http = new XMLHttpRequest();
    http.open('HEAD', image_url, false);
    http.send();
    return http.status != 404;
}

function fixFeaturedMediaOffset(){
	    if ($(window).width() >= 1200 && ($('.featured-media .figure').height() >= 5 )  ) {
		console.log(">1200");
		var mediaHeight=  $('.featured-media .figure').outerHeight();
			console.log(mediaHeight);
		var sectionHeight=  $(".featured-media .ad-box").outerHeight();;
				console.log(sectionHeight);
		if (  (sectionHeight - mediaHeight) >= 0) {
			console.log("islarger difference is :" +(sectionHeight - mediaHeight) + "px");

		    var mediamargin =  mediaHeight - sectionHeight + 30;
					console.log("margin is" +mediamargin);
		    $("section.featured-media").css("margin-bottom", mediamargin);
		}
	    } else {
		 $("section.featured-media").css("margin-bottom", "inherit");
	    }
	}
// Wrap IIFE around your code
(function($, viewport){
    $(document).ready(function() {
	//fix offset

var windowWidth = $(window).width();

	fixFeaturedMediaOffset();

        //Do not kill the dropdowns when users click in them)
        $('.dropdown-menu').children().click(function(e){
            e.stopPropagation();
        });

        //*======= ALLOW MULTIPLE NAV ITEMS TO BE OPEN AT ONCE IN MOBILE
        if ($(window).width() < 992){
            $('.dropdown.keep-open').on({
                "shown.bs.dropdown": function() { this.closable = false; },
                    "click":             function() { this.closable = true; },
                    "hide.bs.dropdown":  function() { return this.closable; }
            });
        } else {
// this function not related to above just piggybacking on the if statement. It pushes the main content down when latest stories is open
var menuheight = 0;
		$('.col-sm-12 .dropdown').on('show.bs.dropdown', function(event) {
			if ($(window).width() > 991) {
			menuheight = $(this).children(".dropdown-menu").outerHeight();
			$(".article__header").animate({
				marginTop: "+=" +menuheight
				 }, 250, function() {
  			  // Animation complete.
 				 });
			}
		});
		$('.col-sm-12 .dropdown').on('hide.bs.dropdown', function(event) {
			if ($(window).width() > 991) {
				$(".article__header").animate({
				marginTop: "-=" +menuheight
				 }, 250, function() {
  			  // Animation complete.
 				 });
			}
			});
		}
		// resets margin-top on .article__header when window resized to prevent stuck margin on resize/orientation shift
function resizedw(){
//modified to fire after only 100ms so that it doesn't go multiple times per resize
    // Store the window width
    // Resize Event
        // Check window width has actually changed and it's not just iOS triggering a resize event on scroll
        if ($(window).width() != windowWidth) {
            // Update the window width for next time
            windowWidth = $(window).width();
            // Do stuff here
    $(".open").removeClass("open");
   $(".article__header").css("margin-top", 0);
   fixFeaturedMediaOffset();
        }
        // Otherwise do nothing
};
var doit;
window.onresize = function(){
  clearTimeout(doit);
  doit = setTimeout(resizedw, 100);
};

        //Moves focus directly to search field when user begins typing
        $('.search-block').on('show.bs.dropdown', function(event) {

		   setTimeout(function(){
 				$('input#menu__search--input').focus();
				}, 500);
        });

        //LATEST STORIES

        jQuery.fn.reverse = function() {
            return this.pushStack(this.get().reverse(), arguments);
        };

        //GLOBALS
        var totalStoryPositions;
        var counter =0;
        var topCounter = 0;
        var bottomCounter = 0;
        var response;
        var recentItems;
        var returnedStories = [];
        var storyObjects = [];
        var firstStory;
        var topPrevCounter = 0;
        var bottomPrevCounter = 0;

        //make storyObjects global, so I don't have to keep hitting the API
        storyObjects = storyObjects;

        //Returned stories from the API
        function getLatestStories(){
            storiesRequested = 50;
            returnedStories = $.ajax({
                method: 'POST',
                url: 'http://api.thetyee.ca/v1/latest/' + storiesRequested,
                dataType: 'jsonp',
                data: response,
                crossDomain: true,
                success: function(response){
                    //console.log(response);
                    returnedStories = returnedStories.responseJSON.hits.hits;
                    //pass data to the create function so I can create my own story objects
                    recentItems = createStoryObjects(returnedStories);
                    return recentItems;
                },
                error: function(){
                    //console.log('NO DICE SISTER');
                }
            });
        }//end lateststories()

        //Format the json data for ease of manipulation
        function createStoryObjects(returnedStories, callback){
            //remove the placeholder classes
            $('.latest-stories__hed').removeClass('hed_preload_placeholder');
            $('.latest-stories__dek').removeClass('dek_preload_placeholder');

            //API data, to feed into an array of custom story objects
            recentItems = returnedStories;

            //for each item from the API, plug info into a story object
            $.each(recentItems, function(key, value){

                latestStoryImage = value._source.related_media[0].uri;

				// get the smallest image > 200px available
				var bestWidth = value._source.related_media[0].width;
				for (var key in value._source.related_media[0].thumbnails) {
				  var thumb = value._source.related_media[0].thumbnails[key];
				  					thumb.uri = thumb.uri.replace("thetyee.cachefly.net", "thetyee.ca");
					if (
					// re-enable live to filter out not yet published thumbnails
		//			imageExists(thumb.uri) == true &&
					 thumb.width >= 200 && thumb.width <= bestWidth) {
					bestWidth = thumb.width;
					latestStoryImage = thumb.uri;  }
				}

                //Format the API img uri's so they don't point at cachefly
                latestStoryImage = latestStoryImage.replace("thetyee.cachefly.net", "thetyee.ca");

                //Use moment.js to format the date
                formattedDate = moment(value._source.storyDate).format("DD MMM");

                //Set default values for the Story object
                var Story = {
                    urlPath : 'link',
                    hed : 'title',
                    image : 'image',
                    dek : 'test',
                    date : 'date',
                    authour : 'authour'
                };

                //Populate Story objects with API data
                Story.urlPath = value._source.path;
                Story.hed = value._source.title;
                Story.image = latestStoryImage;
                Story.dek = value._source.teaser;
                Story.date = formattedDate;
                Story.authour = value._source.byline;

                //Put all objects into a new array for easier handling
                storyObjects.push(Story);
            });
            // on load, populate the DOM
            $('.latest-stories__media-wrapper').each(function(key, index){
                $(this).parent().find('li').each(function(i, details){

                    if (key === 0){
                        // TODO swap this out when closer to production
                        //$(this).find('a').attr('href', '#');
                        // Old value
                        $(this).find('a').attr('href', "http://thetyee.ca" + storyObjects[topCounter].urlPath);
                        $(this).find('img').attr('src', storyObjects[topCounter].image);
                        $(this).find('h4').html(storyObjects[topCounter].hed);
                        $(this).find('p').html(storyObjects[topCounter].dek);
                        $(this).find('.latest-stories__date').html(storyObjects[topCounter].date);
                        $(this).find('.latest-stories__authour').html(storyObjects[topCounter].authour);
                        topCounter++;
                    }
                    if (key == 1){
                        // TODO swap this out when closer to production
                        $(this).find('a').attr('href', '#');
                        // Old value
                        // $(this).find('a').attr('href', storyObjects[topCounter].urlPath);
                        $(this).find('img').attr('src', storyObjects[bottomCounter].image);
                        $(this).find('h4').html(storyObjects[bottomCounter].hed);
                        $(this).find('p').html(storyObjects[bottomCounter].dek);
                        $(this).find('.latest-stories__date').html(storyObjects[bottomCounter].date);
                        $(this).find('.latest-stories__authour').html(storyObjects[bottomCounter].authour);
                        bottomCounter++;

                    }

                });
            });
            //control the scrolling
            scrollLatestStories();
        }

        //Make Ajax call and put data into the returnedStories var for manipulation.
        getLatestStories();

        //takes parameters of current slider
        function scrollLatestStories(){
            //Get the next group of stories on click

            //console.log(key + ' ' + value);
            $('.latest-stories__media-wrapper').each(function(key, index){
                $(this).on('click', '.next', function(event){
                    //	console.log($(this).find('li'));

                    $(this).parent().find('li').each(function(i, details){

                        if (key === 0){
                            $(this).find('a').attr('href', storyObjects[topCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[topCounter].image);
                            $(this).find('h4').html(storyObjects[topCounter].hed);
                            $(this).find('p').html(storyObjects[topCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[topCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[topCounter].authour);

                            topCounter++;

                            if (topCounter >=50){
                                topCounter = 0;
                            }

                        }

                        if (key == 1){

                            $(this).find('a').attr('href', storyObjects[bottomCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[bottomCounter].image);
                            $(this).find('h4').html(storyObjects[bottomCounter].hed);
                            $(this).find('p').html(storyObjects[bottomCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[bottomCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[bottomCounter].authour);
                            bottomCounter++;

                            if (bottomCounter >=50){
                                bottomCounter = 0;
                            }
                        }

                    });
                    //reset the counter so I can scroll the other way
                    topPrevCounter = topCounter - 7;
                    bottomPrevCounter = bottomCounter - 7;

                    //reset the click event

                });

                $(this).on('click', '.prev', function(event){
                    $(this).parent().find('li').reverse().each(function(i, details){
                        //infinite backwards scroll
                        if (topPrevCounter <=0){
                            topPrevCounter = 49;
                        }
                        if (key === 0){
                            $(this).find('a').attr('href', storyObjects[topPrevCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[topPrevCounter].image);
                            $(this).find('h4').html(storyObjects[topPrevCounter].hed);
                            $(this).find('p').html(storyObjects[topPrevCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[topPrevCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[topPrevCounter].authour);
                            topPrevCounter--;
                        }

                        if (bottomPrevCounter <= 0){
                            bottomPrevCounter = 49;
                        }

                        if (key == 1){
                            //console.log('left click - ' + bottomPrevCounter);
                            $(this).find('a').attr('href', storyObjects[bottomPrevCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[bottomPrevCounter].image);
                            $(this).find('h4').html(storyObjects[bottomPrevCounter].hed);
                            $(this).find('p').html(storyObjects[bottomPrevCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[bottomPrevCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[bottomPrevCounter].authour);
                            bottomPrevCounter--;
                        }

                    });
                    //reset the counter so i can go the other way
                    topCounter = topPrevCounter + 7;
                    bottomCounter = bottomPrevCounter + 7;
                    //reset the counter for infinite scrolling

                });
            });

        }//END LATEST STORIES SCROLLER

        // Show Disqus comments
        $(".comments-section .btn").click(function(e) {
            e.preventDefault();
            var el = $('.comments-section');
            var disqus_div = $('#disqus_thread');
            var anim_height = disqus_div.height() + 40;
            el.css({
                "height": 400,
                "max-height": 9999
            })
            .animate({
                "height": anim_height
            });

            // fade out read-more
            $('.read-more').fadeOut();
        });

    });

})(jQuery, ResponsiveBootstrapToolkit);
<commit_msg>Remove console.log and reformat<commit_after>//check if an image exists
function imageExists(image_url){
    var http = new XMLHttpRequest();
    http.open('HEAD', image_url, false);
    http.send();
    return http.status != 404;
}

function fixFeaturedMediaOffset(){
    if ($(window).width() >= 1200 && ($('.featured-media .figure').height() >= 5 )  ) {
        var mediaHeight=  $('.featured-media .figure').outerHeight();
        var sectionHeight=  $(".featured-media .ad-box").outerHeight();;
        if (  (sectionHeight - mediaHeight) >= 0) {
            var mediamargin =  mediaHeight - sectionHeight + 30;
            $("section.featured-media").css("margin-bottom", mediamargin);
        }
    } else {
        $("section.featured-media").css("margin-bottom", "inherit");
    }
}
// Wrap IIFE around your code
(function($, viewport){
    $(document).ready(function() {
        //fix offset

        var windowWidth = $(window).width();

        fixFeaturedMediaOffset();

        //Do not kill the dropdowns when users click in them)
        $('.dropdown-menu').children().click(function(e){
            e.stopPropagation();
        });

        //*======= ALLOW MULTIPLE NAV ITEMS TO BE OPEN AT ONCE IN MOBILE
        if ($(window).width() < 992){
            $('.dropdown.keep-open').on({
                "shown.bs.dropdown": function() { this.closable = false; },
                    "click":             function() { this.closable = true; },
                    "hide.bs.dropdown":  function() { return this.closable; }
            });
        } else {
            // this function not related to above just piggybacking on the if statement. It pushes the main content down when latest stories is open
            var menuheight = 0;
            $('.col-sm-12 .dropdown').on('show.bs.dropdown', function(event) {
                if ($(window).width() > 991) {
                    menuheight = $(this).children(".dropdown-menu").outerHeight();
                    $(".article__header").animate({
                        marginTop: "+=" +menuheight
                    }, 250, function() {
                        // Animation complete.
                    });
                }
            });
            $('.col-sm-12 .dropdown').on('hide.bs.dropdown', function(event) {
                if ($(window).width() > 991) {
                    $(".article__header").animate({
                        marginTop: "-=" +menuheight
                    }, 250, function() {
                        // Animation complete.
                    });
                }
            });
        }
        // resets margin-top on .article__header when window resized to prevent stuck margin on resize/orientation shift
        function resizedw(){
            //modified to fire after only 100ms so that it doesn't go multiple times per resize
            // Store the window width
            // Resize Event
            // Check window width has actually changed and it's not just iOS triggering a resize event on scroll
            if ($(window).width() != windowWidth) {
                // Update the window width for next time
                windowWidth = $(window).width();
                // Do stuff here
                $(".open").removeClass("open");
                $(".article__header").css("margin-top", 0);
                fixFeaturedMediaOffset();
            }
            // Otherwise do nothing
        };
        var doit;
        window.onresize = function(){
            clearTimeout(doit);
            doit = setTimeout(resizedw, 100);
        };

        //Moves focus directly to search field when user begins typing
        $('.search-block').on('show.bs.dropdown', function(event) {

            setTimeout(function(){
                $('input#menu__search--input').focus();
            }, 500);
        });

        //LATEST STORIES

        jQuery.fn.reverse = function() {
            return this.pushStack(this.get().reverse(), arguments);
        };

        //GLOBALS
        var totalStoryPositions;
        var counter =0;
        var topCounter = 0;
        var bottomCounter = 0;
        var response;
        var recentItems;
        var returnedStories = [];
        var storyObjects = [];
        var firstStory;
        var topPrevCounter = 0;
        var bottomPrevCounter = 0;

        //make storyObjects global, so I don't have to keep hitting the API
        storyObjects = storyObjects;

        //Returned stories from the API
        function getLatestStories(){
            storiesRequested = 50;
            returnedStories = $.ajax({
                method: 'POST',
                url: 'http://api.thetyee.ca/v1/latest/' + storiesRequested,
                dataType: 'jsonp',
                data: response,
                crossDomain: true,
                success: function(response){
                    returnedStories = returnedStories.responseJSON.hits.hits;
                    //pass data to the create function so I can create my own story objects
                    recentItems = createStoryObjects(returnedStories);
                    return recentItems;
                },
                error: function(){
                }
            });
        }//end lateststories()

        //Format the json data for ease of manipulation
        function createStoryObjects(returnedStories, callback){
            //remove the placeholder classes
            $('.latest-stories__hed').removeClass('hed_preload_placeholder');
            $('.latest-stories__dek').removeClass('dek_preload_placeholder');

            //API data, to feed into an array of custom story objects
            recentItems = returnedStories;

            //for each item from the API, plug info into a story object
            $.each(recentItems, function(key, value){

                latestStoryImage = value._source.related_media[0].uri;

                // get the smallest image > 200px available
                var bestWidth = value._source.related_media[0].width;
                for (var key in value._source.related_media[0].thumbnails) {
                    var thumb = value._source.related_media[0].thumbnails[key];
                    thumb.uri = thumb.uri.replace("thetyee.cachefly.net", "thetyee.ca");
                    if (
                        // re-enable live to filter out not yet published thumbnails
                        //			imageExists(thumb.uri) == true &&
                        thumb.width >= 200 && thumb.width <= bestWidth) {
                            bestWidth = thumb.width;
                            latestStoryImage = thumb.uri;  }
                }

                //Format the API img uri's so they don't point at cachefly
                latestStoryImage = latestStoryImage.replace("thetyee.cachefly.net", "thetyee.ca");

                //Use moment.js to format the date
                formattedDate = moment(value._source.storyDate).format("DD MMM");

                //Set default values for the Story object
                var Story = {
                    urlPath : 'link',
                    hed : 'title',
                    image : 'image',
                    dek : 'test',
                    date : 'date',
                    authour : 'authour'
                };

                //Populate Story objects with API data
                Story.urlPath = value._source.path;
                Story.hed = value._source.title;
                Story.image = latestStoryImage;
                Story.dek = value._source.teaser;
                Story.date = formattedDate;
                Story.authour = value._source.byline;

                //Put all objects into a new array for easier handling
                storyObjects.push(Story);
            });
            // on load, populate the DOM
            $('.latest-stories__media-wrapper').each(function(key, index){
                $(this).parent().find('li').each(function(i, details){

                    if (key === 0){
                        // TODO swap this out when closer to production
                        //$(this).find('a').attr('href', '#');
                        // Old value
                        $(this).find('a').attr('href', "http://thetyee.ca" + storyObjects[topCounter].urlPath);
                        $(this).find('img').attr('src', storyObjects[topCounter].image);
                        $(this).find('h4').html(storyObjects[topCounter].hed);
                        $(this).find('p').html(storyObjects[topCounter].dek);
                        $(this).find('.latest-stories__date').html(storyObjects[topCounter].date);
                        $(this).find('.latest-stories__authour').html(storyObjects[topCounter].authour);
                        topCounter++;
                    }
                    if (key == 1){
                        // TODO swap this out when closer to production
                        $(this).find('a').attr('href', '#');
                        // Old value
                        // $(this).find('a').attr('href', storyObjects[topCounter].urlPath);
                        $(this).find('img').attr('src', storyObjects[bottomCounter].image);
                        $(this).find('h4').html(storyObjects[bottomCounter].hed);
                        $(this).find('p').html(storyObjects[bottomCounter].dek);
                        $(this).find('.latest-stories__date').html(storyObjects[bottomCounter].date);
                        $(this).find('.latest-stories__authour').html(storyObjects[bottomCounter].authour);
                        bottomCounter++;

                    }

                });
            });
            //control the scrolling
            scrollLatestStories();
        }

        //Make Ajax call and put data into the returnedStories var for manipulation.
        getLatestStories();

        //takes parameters of current slider
        function scrollLatestStories(){
            //Get the next group of stories on click

            $('.latest-stories__media-wrapper').each(function(key, index){
                $(this).on('click', '.next', function(event){

                    $(this).parent().find('li').each(function(i, details){

                        if (key === 0){
                            $(this).find('a').attr('href', storyObjects[topCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[topCounter].image);
                            $(this).find('h4').html(storyObjects[topCounter].hed);
                            $(this).find('p').html(storyObjects[topCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[topCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[topCounter].authour);

                            topCounter++;

                            if (topCounter >=50){
                                topCounter = 0;
                            }

                        }

                        if (key == 1){

                            $(this).find('a').attr('href', storyObjects[bottomCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[bottomCounter].image);
                            $(this).find('h4').html(storyObjects[bottomCounter].hed);
                            $(this).find('p').html(storyObjects[bottomCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[bottomCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[bottomCounter].authour);
                            bottomCounter++;

                            if (bottomCounter >=50){
                                bottomCounter = 0;
                            }
                        }

                    });
                    //reset the counter so I can scroll the other way
                    topPrevCounter = topCounter - 7;
                    bottomPrevCounter = bottomCounter - 7;

                    //reset the click event

                });

                $(this).on('click', '.prev', function(event){
                    $(this).parent().find('li').reverse().each(function(i, details){
                        //infinite backwards scroll
                        if (topPrevCounter <=0){
                            topPrevCounter = 49;
                        }
                        if (key === 0){
                            $(this).find('a').attr('href', storyObjects[topPrevCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[topPrevCounter].image);
                            $(this).find('h4').html(storyObjects[topPrevCounter].hed);
                            $(this).find('p').html(storyObjects[topPrevCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[topPrevCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[topPrevCounter].authour);
                            topPrevCounter--;
                        }

                        if (bottomPrevCounter <= 0){
                            bottomPrevCounter = 49;
                        }

                        if (key == 1){
                            $(this).find('a').attr('href', storyObjects[bottomPrevCounter].urlPath);
                            $(this).find('img').attr('src', storyObjects[bottomPrevCounter].image);
                            $(this).find('h4').html(storyObjects[bottomPrevCounter].hed);
                            $(this).find('p').html(storyObjects[bottomPrevCounter].dek);
                            $(this).find('.latest-stories__date').html(storyObjects[bottomPrevCounter].date);
                            $(this).find('.latest-stories__authour').html(storyObjects[bottomPrevCounter].authour);
                            bottomPrevCounter--;
                        }

                    });
                    //reset the counter so i can go the other way
                    topCounter = topPrevCounter + 7;
                    bottomCounter = bottomPrevCounter + 7;
                    //reset the counter for infinite scrolling

                });
            });

        }//END LATEST STORIES SCROLLER

        // Show Disqus comments
        $(".comments-section .btn").click(function(e) {
            e.preventDefault();
            var el = $('.comments-section');
            var disqus_div = $('#disqus_thread');
            var anim_height = disqus_div.height() + 40;
            el.css({
                "height": 400,
                "max-height": 9999
            })
            .animate({
                "height": anim_height
            });

            // fade out read-more
            $('.read-more').fadeOut();
        });

    });

})(jQuery, ResponsiveBootstrapToolkit);
<|endoftext|>


<commit_before>'use strict';

angular.module('brewApp.controllers')
    .controller('LogsCtrl', ['$scope',  'logger', 'notifications', logsController]);

function logsController($scope, logger, notifications) {
    var logs = {};

    logs.testFunc = function() {
        alert('got delete');
    }

    $scope.loadData = function() {
        return logger.getLogs().then(function(data) {

            return options = {
                data: data.map(function(i) {
                   return [i._id, convertUTC(i.logdate), i.level, i.url, i.userid, i.message];
                }),
                columns: [
                    { title: 'Id' },
                    { title: 'Date/Time' },
                    { title: 'Level' },
                    { title: 'URL' },
                    { title: 'User' },
                    { title: 'Message' },
                    {
                        data: null,
                        defaultContent: 'Delete'
                    }
                    ]
            }
        });
    };

    logs.deleteLog = function(id) {
        if (confirm('Are you sure you wish to delete id = ' + id + '?')) {
            logger.deleteLog(id).then(function(data) {
                notifications.info('Log entry deleted');
            }, function(err) {
                console.log(err);
                notifications.error('Error deleting');
            });
        }
    };

    logs.logLevel = logger.getLogLevel().name;

    var convertUTC = function(d) {
        var dateString = (new Date(d)).toString();
        return dateString;
    };

    $scope.logs = logs;
}<commit_msg>renames prepareData<commit_after>'use strict';

angular.module('brewApp.controllers')
    .controller('LogsCtrl', ['$scope',  'logger', 'notifications', logsController]);

function logsController($scope, logger, notifications) {
    var logs = {};

    logs.testFunc = function() {
        alert('got delete');
    }

    $scope.prepareData = function() {
        return logger.getLogs().then(function(data) {

            return options = {
                data: data.map(function(i) {
                   return [i._id, convertUTC(i.logdate), i.level, i.url, i.userid, i.message];
                }),
                columns: [
                    { title: 'Id' },
                    { title: 'Date/Time' },
                    { title: 'Level' },
                    { title: 'URL' },
                    { title: 'User' },
                    { title: 'Message' },
                    {
                        data: null,
                        defaultContent: 'Delete'
                    }
                    ]
            }
        });
    };

    logs.deleteLog = function(id) {
        if (confirm('Are you sure you wish to delete id = ' + id + '?')) {
            logger.deleteLog(id).then(function(data) {
                notifications.info('Log entry deleted');
            }, function(err) {
                console.log(err);
                notifications.error('Error deleting');
            });
        }
    };

    logs.logLevel = logger.getLogLevel().name;

    var convertUTC = function(d) {
        var dateString = (new Date(d)).toString();
        return dateString;
    };

    $scope.logs = logs;
}<|endoftext|>


<commit_before>var classSet = require('chessground').util.classSet;

function prefixInteger(num, length) {
  return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

function bold(x) {
  return '' + x + '';
}

function formatClockTime(trans, time) {
  var date = new Date(time);
  var minutes = prefixInteger(date.getUTCMinutes(), 2);
  var seconds = prefixInteger(date.getSeconds(), 2);
  var str = '';
  if (time >= 86400 * 1000) {
    var days = date.getUTCDate() - 1;
    str += (days === 1 ? trans('oneDay') : trans('nbDays', days)) + ' ';
    if (time === 86400 * 1000 || days > 1) return str;
    str += ' & ';
  }
  str += bold(prefixInteger(date.getUTCHours(), 2)) + ':' + bold(minutes);
  if (time < 3600 * 1000) str += ':' + bold(seconds);
  return str;
}

module.exports = function(ctrl, trans, color, position, runningColor) {
  var time = ctrl.data[color];
  return m('div', {
    class: 'correspondence clock clock_' + color + ' clock_' + position + ' ' + classSet({
      'outoftime': !time,
      'running': runningColor === color,
      'emerg': time < ctrl.data.emerg
    })
  }, [
    ctrl.data.showBar ? m('div.bar',
      m('span', {
        style: {
          width: Math.max(0, Math.min(100, (time / ctrl.data.barTime) * 100)) + '%'
        }
      })
    ) : null,
    m('div.time', m.trust(formatClockTime(trans, time * 1000)))
  ]);
}
<commit_msg>Improve correspondence clock<commit_after>var classSet = require('chessground').util.classSet;

function prefixInteger(num, length) {
  return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

function bold(x) {
  return '' + x + '';
}

function formatClockTime(trans, time) {
  var date = new Date(time);
  var minutes = prefixInteger(date.getUTCMinutes(), 2);
  var seconds = prefixInteger(date.getSeconds(), 2);
  var str = '';
  if (time >= 86400 * 1000) {
    // days : hours
    var days = date.getUTCDate() - 1;
    var hours = date.getUTCHours();
    str += (days === 1 ? trans('oneDay') : trans('nbDays', days)) + ' ';
    str += (hours === 1 ? 'one hour' : hours + ' hours');
  } else if (time >= 3600 * 1000) {
    // hours : minutes
    var hours = date.getUTCHours();
    str += bold(prefixInteger(hours, 2)) + ':' + bold(minutes);
  } else {
    // minutes : seconds
    str += bold(minutes) + ':' + bold(seconds);
  }
  return str;
}

module.exports = function(ctrl, trans, color, position, runningColor) {
  var time = ctrl.data[color];
  return m('div', {
    class: 'correspondence clock clock_' + color + ' clock_' + position + ' ' + classSet({
      'outoftime': !time,
      'running': runningColor === color,
      'emerg': time < ctrl.data.emerg
    })
  }, [
    ctrl.data.showBar ? m('div.bar',
      m('span', {
        style: {
          width: Math.max(0, Math.min(100, (time / ctrl.data.barTime) * 100)) + '%'
        }
      })
    ) : null,
    m('div.time', m.trust(formatClockTime(trans, time * 1000)))
  ]);
}
<|endoftext|>