<commit_before>(function(w, d, $) {

	var state = {};
	state.dom = {};
	state.canScroll = true; // For page scroll checks
	state.sliderIndex = 0; // For slider rotations

	state.resetScroll = function() {
		state.canScroll = false;
		setTimeout(function() {
			return state.canScroll = true;
		}, 600);
	 };

	// Gather elements
	var collectDom = function() {
		state.dom.responsiveNavButton = d.getElementById("responsive-nav-button");
		state.dom.slider = d.getElementById("slider");
		state.dom.splashDownArrow = d.getElementById("splash-down-arrow");
		state.dom.logo = d.getElementById("logo");
		state.dom.contactForm = d.forms["contact-form"];
		state.dom.contactFormErrorMessage = d.getElementById("contact-form-error-message");
		state.dom.formSubmissionOverlay = d.getElementById("successful-form-submission-overlay");
		state.dom.$navigators = $("[data-navigate]");
		state.dom.$parallaxImages = $(".parallax > img");
		state.dom.$footerLinks = $("footer ul li:not(:last-child)");
	};

	// Navigation for desktop and mobile
	var controlNavigation = function() {
		var $responsiveNav = $("header nav").clone();
		$(d).on(services.interaction(), "[data-navigate]", function() {
			var section = $(this).attr("data-navigate");
			if (section === "home") {
				services.navigate(0);
			} else {
				var scrollTo = $("#" + section + "-content").offset().top;
				services.navigate(scrollTo - 80); // -80 here accounts for adjustments in CSS for the sticky header
			}
		});

		// Create/control responsive nav menu
		$responsiveNav
			.insertAfter("header")
			.attr("id", "responsive-menu")
			.attr("class", "responsive-menu");

		$(state.dom.responsiveNavButton).on(services.interaction(), function() {
			services.show("#responsive-menu", true);
		});

		$("#responsive-menu li, header .logo").on(services.interaction(), function() {
			services.hide("#responsive-menu");
		});

		$(w).resize(function() {
			if ($(this).width() > 740 && $("#responsive-menu").hasClass("SHOW")) services.hide("#responsive-menu");
		});

	};

	// Control parallax banner
	var controlParallax = function() {
		if (!services.isMobile()) {
			$(w)
				.scroll(function() {
					if ($(this).width() > 1000) {
						services.parallax();
					} else {
						state.dom.$parallaxImages.css("top", "0px");
					}
				})
				.resize(function() {
					if ($(this).width() > 1000) state.dom.$parallaxImages.css("top", "0px");
				});
		}
	};

	// Control slider animations
	var controlSlider = function() {

		var curHeight = w.innerHeight;
		var slides = d.querySelectorAll("#slider .slide");
		var list = d.getElementById("slider-bullets");

		$(state.dom.slider).height(curHeight - 80); // -80 here accounts for adjustments in CSS for the sticky header

		$(w).resize(function() {
			if ($(this).height() > curHeight) {
				$(state.dom.slider).height(w.innerHeight - 80);
				curHeight = w.innerHeight;
			}
		})
		.on("load resize", function() {
			if ($(this).width() <= 760) {
				var minHeight = $("#responsive-slide").height() + 150;
				$(state.dom.slider).css("min-height", minHeight + "px");
			}
		})
		.on("orientationchange", function() {
			var newHeight = w.innerHeight - 80;
			$(state.dom.slider)
				.height(newHeight)
				.css("min-height", newHeight);
		});

		// Build bullets
		for (var i = 0; i < slides.length; i++) {
			var bullet = d.createElement("li");
			if (i === 0) bullet.className = "SELECTED";
			list.appendChild(bullet);
		}

		// Auto rotations
		function rotate() {
			var bullets = d.querySelectorAll("#slider-bullets li");
			state.sliderIndex++;
			if (state.sliderIndex === slides.length) state.sliderIndex = 0;
			services
				.hide("#slider .slide")
				.show(slides[state.sliderIndex])
				.deselect("#slider-bullets li")
				.select(bullets[state.sliderIndex]);
			setTimeout(rotate, 8000); // Recursively trigger rotation every 8 seconds
		};
		setTimeout(rotate, 8000); // Init slider
	};

	// Contact form validation
	var validateContactForm = function() {

		var hasErrors;
		var name = state.dom.contactForm["name"];
		var email = state.dom.contactForm["email"];
		var subject = state.dom.contactForm["subject"];
		var comments = state.dom.contactForm["comments"];

		function validate(selector, regx) {
			if (!selector.value.match(regx)) {
				if (!hasErrors) hasErrors = true;
				selector.className = "invalid";
			} else {
				selector.className = "";
			}
		};

		$(state.dom.contactForm).on("submit", function() {

			hasErrors = false;

			validate(name, /^\s*\S/);
			validate(email, /^\S+@\S+$/);
			validate(subject, /^\s*\S/);
			validate(comments, /^\s*\S/);

			if (hasErrors) {
				if (!$(state.dom.contactFormErrorMessage).hasClass("SHOW")) services.show(state.dom.contactFormErrorMessage);
				return false;
			} else {
				if ($(state.dom.contactFormErrorMessage).hasClass("SHOW")) services.hide(state.dom.contactFormErrorMessage);
			}

		});
	};

	// Control successful form submission overlay
	var controlFormSubmissionOverlay = function() {
		if (state.dom.formSubmissionOverlay !== null) {
			var closeButton = d.querySelector("#successful-form-submission-overlay .close-button");
			$(closeButton).on(services.interaction(), function() {
				return w.location.href = "http://www.drzwebdev.com/sites/StreamYourAd/";
			});
		}
	};

	// Control automatic header > nav > ul > li "SELECTED" states updates while scrolling
	var controlSelectedStates = function() {

		$(w).scroll(function() {

			if (state.canScroll) { // Necessary to prevent weird transition errors after clicking/tapping on nav items

				var scrolled = $(w).scrollTop();
				var threshold = ($(w).height() * 0.4);
				var aboutOffset = $("#about-content").offset().top;
				var servicesOffset = $("#services-content").offset().top;
				var contactOffset = $("#contact-content").offset().top;

				if (aboutOffset - scrolled < threshold) {
					services
						.deselect("[data-navigate]")
						.select("[data-navigate='about']"); // How it Works

					if (servicesOffset - scrolled < threshold) {
						services
							.deselect("[data-navigate]")
							.select("[data-navigate='services']"); // Our Services

						if (contactOffset - scrolled < threshold) {
							services
								.deselect("[data-navigate]")
								.select("[data-navigate='contact']"); // Contact Us
						}
					}

				} else {
					services
						.deselect("[data-navigate]")
						.select("[data-navigate='home']"); // Home
				}

			} // End state.canScroll check
		});

		// Control "SELECTED" states in header > nav > ul > li based on user location
		state.dom.$navigators.on(services.interaction(), function() {
			var section = $(this).attr("data-navigate");
			services
				.deselect("[data-navigate]")
				.select("[data-navigate='" + section + "']");
			state.resetScroll();
		});

		$(state.dom.logo).on(services.interaction(), function() {
			services
				.deselect("[data-navigate]")
				.select("[data-navigate='home']");
			state.resetScroll();
		});

		$(state.dom.splashDownArrow).on(services.interaction(), function() {
			services
				.deselect("[data-navigate='home']")
				.select("[data-navigate='about']");
			state.resetScroll();
		});

	};

	// "Privacy Policy" / "Terms & Conditions" alerts
	var controlAlerts = function() {
		state.dom.$footerLinks.on(services.interaction(), function() {
			var delay = ("ontouchend" in d) ? 50 : 0;
			setTimeout(function() {
				alert("'StreamYourAd' the company no longer exists as a legal entity, thus I am prohibited from sharing any legal bric-a-brac on the site. This site now serves as a dummy practice environment for my portfolio :)");
			}, delay);
		});
	};

	// Create hover/active states
	var setMousables = function() {
		return $("nav li, #responsive-nav-button, .blue-button, footer ul li:not(:last-child)").mouseable();
	};

	// Start
	var init = function() {
		collectDom();
		controlNavigation();
		controlParallax();
		controlSlider();
		validateContactForm();
		controlAlerts();
		controlFormSubmissionOverlay();
		controlSelectedStates();
		setMousables();
	};

	$(d).ready(init);

})(window, document, jQuery);<commit_msg>Update stream-your-ad.js<commit_after>(function(w, d, $) {

	var state = {};
	state.dom = {};
	state.canScroll = true; // For page scroll checks
	state.sliderIndex = 0; // For slider rotations

	state.resetScroll = function() {
		state.canScroll = false;
		setTimeout(function() {
			return state.canScroll = true;
		}, 600);
	};

	// Gather elements
	var collectDom = function() {
		state.dom.responsiveNavButton = d.getElementById("responsive-nav-button");
		state.dom.slider = d.getElementById("slider");
		state.dom.splashDownArrow = d.getElementById("splash-down-arrow");
		state.dom.logo = d.getElementById("logo");
		state.dom.contactForm = d.forms["contact-form"];
		state.dom.contactFormErrorMessage = d.getElementById("contact-form-error-message");
		state.dom.formSubmissionOverlay = d.getElementById("successful-form-submission-overlay");
		state.dom.$navigators = $("[data-navigate]");
		state.dom.$parallaxImages = $(".parallax > img");
		state.dom.$footerLinks = $("footer ul li:not(:last-child)");
	};

	// Navigation for desktop and mobile
	var controlNavigation = function() {
		var $responsiveNav = $("header nav").clone();
		$(d).on(services.interaction(), "[data-navigate]", function() {
			var section = $(this).attr("data-navigate");
			if (section === "home") {
				services.navigate(0);
			} else {
				var scrollTo = $("#" + section + "-content").offset().top;
				services.navigate(scrollTo - 80); // -80 here accounts for adjustments in CSS for the sticky header
			}
		});

		// Create/control responsive nav menu
		$responsiveNav
			.insertAfter("header")
			.attr("id", "responsive-menu")
			.attr("class", "responsive-menu");

		$(state.dom.responsiveNavButton).on(services.interaction(), function() {
			services.show("#responsive-menu", true);
		});

		$("#responsive-menu li, header .logo").on(services.interaction(), function() {
			services.hide("#responsive-menu");
		});

		$(w).resize(function() {
			if ($(this).width() > 740 && $("#responsive-menu").hasClass("SHOW")) services.hide("#responsive-menu");
		});

	};

	// Control parallax banner
	var controlParallax = function() {
		if (!services.isMobile()) {
			$(w)
				.scroll(function() {
					if ($(this).width() > 1000) {
						services.parallax();
					} else {
						state.dom.$parallaxImages.css("top", "0px");
					}
				})
				.resize(function() {
					if ($(this).width() > 1000) state.dom.$parallaxImages.css("top", "0px");
				});
		}
	};

	// Control slider animations
	var controlSlider = function() {

		var curHeight = w.innerHeight;
		var slides = d.querySelectorAll("#slider .slide");
		var list = d.getElementById("slider-bullets");

		$(state.dom.slider).height(curHeight - 80); // -80 here accounts for adjustments in CSS for the sticky header

		$(w).resize(function() {
			if ($(this).height() > curHeight) {
				$(state.dom.slider).height(w.innerHeight - 80);
				curHeight = w.innerHeight;
			}
		})
		.on("load resize", function() {
			if ($(this).width() <= 760) {
				var minHeight = $("#responsive-slide").height() + 150;
				$(state.dom.slider).css("min-height", minHeight + "px");
			}
		})
		.on("orientationchange", function() {
			var newHeight = w.innerHeight - 80;
			$(state.dom.slider)
				.height(newHeight)
				.css("min-height", newHeight);
		});

		// Build bullets
		for (var i = 0; i < slides.length; i++) {
			var bullet = d.createElement("li");
			if (i === 0) bullet.className = "SELECTED";
			list.appendChild(bullet);
		}

		// Auto rotations
		function rotate() {
			var bullets = d.querySelectorAll("#slider-bullets li");
			state.sliderIndex++;
			if (state.sliderIndex === slides.length) state.sliderIndex = 0;
			services
				.hide("#slider .slide")
				.show(slides[state.sliderIndex])
				.deselect("#slider-bullets li")
				.select(bullets[state.sliderIndex]);
			setTimeout(rotate, 8000); // Recursively trigger rotation every 8 seconds
		};
		setTimeout(rotate, 8000); // Init slider
	};

	// Contact form validation
	var validateContactForm = function() {

		var hasErrors;
		var name = state.dom.contactForm["name"];
		var email = state.dom.contactForm["email"];
		var subject = state.dom.contactForm["subject"];
		var comments = state.dom.contactForm["comments"];

		function validate(selector, regx) {
			if (!selector.value.match(regx)) {
				if (!hasErrors) hasErrors = true;
				selector.className = "invalid";
			} else {
				selector.className = "";
			}
		};

		$(state.dom.contactForm).on("submit", function() {

			hasErrors = false;

			validate(name, /^\s*\S/);
			validate(email, /^\S+@\S+$/);
			validate(subject, /^\s*\S/);
			validate(comments, /^\s*\S/);

			if (hasErrors) {
				if (!$(state.dom.contactFormErrorMessage).hasClass("SHOW")) services.show(state.dom.contactFormErrorMessage);
				return false;
			} else {
				if ($(state.dom.contactFormErrorMessage).hasClass("SHOW")) services.hide(state.dom.contactFormErrorMessage);
			}

		});
	};

	// Control successful form submission overlay
	var controlFormSubmissionOverlay = function() {
		if (state.dom.formSubmissionOverlay !== null) {
			var closeButton = d.querySelector("#successful-form-submission-overlay .close-button");
			$(closeButton).on(services.interaction(), function() {
				return w.location.href = "http://www.drzwebdev.com/sites/StreamYourAd/";
			});
		}
	};

	// Control automatic header > nav > ul > li "SELECTED" states updates while scrolling
	var controlSelectedStates = function() {

		$(w).scroll(function() {

			if (state.canScroll) { // Necessary to prevent weird transition errors after clicking/tapping on nav items

				var scrolled = $(w).scrollTop();
				var threshold = ($(w).height() * 0.4);
				var aboutOffset = $("#about-content").offset().top;
				var servicesOffset = $("#services-content").offset().top;
				var contactOffset = $("#contact-content").offset().top;

				if (aboutOffset - scrolled < threshold) {
					services
						.deselect("[data-navigate]")
						.select("[data-navigate='about']"); // How it Works

					if (servicesOffset - scrolled < threshold) {
						services
							.deselect("[data-navigate]")
							.select("[data-navigate='services']"); // Our Services

						if (contactOffset - scrolled < threshold) {
							services
								.deselect("[data-navigate]")
								.select("[data-navigate='contact']"); // Contact Us
						}
					}

				} else {
					services
						.deselect("[data-navigate]")
						.select("[data-navigate='home']"); // Home
				}

			} // End state.canScroll check
		});

		// Control "SELECTED" states in header > nav > ul > li based on user location
		state.dom.$navigators.on(services.interaction(), function() {
			var section = $(this).attr("data-navigate");
			services
				.deselect("[data-navigate]")
				.select("[data-navigate='" + section + "']");
			state.resetScroll();
		});

		$(state.dom.logo).on(services.interaction(), function() {
			services
				.deselect("[data-navigate]")
				.select("[data-navigate='home']");
			state.resetScroll();
		});

		$(state.dom.splashDownArrow).on(services.interaction(), function() {
			services
				.deselect("[data-navigate='home']")
				.select("[data-navigate='about']");
			state.resetScroll();
		});

	};

	// "Privacy Policy" / "Terms & Conditions" alerts
	var controlAlerts = function() {
		state.dom.$footerLinks.on(services.interaction(), function() {
			var delay = ("ontouchend" in d) ? 50 : 0;
			setTimeout(function() {
				alert("'StreamYourAd' the company no longer exists as a legal entity, thus I am prohibited from sharing any legal bric-a-brac on the site. This site now serves as a dummy practice environment for my portfolio :)");
			}, delay);
		});
	};

	// Create hover/active states
	var setMousables = function() {
		return $("nav li, #responsive-nav-button, .blue-button, footer ul li:not(:last-child)").mouseable();
	};

	// Start
	var init = function() {
		collectDom();
		controlNavigation();
		controlParallax();
		controlSlider();
		validateContactForm();
		controlAlerts();
		controlFormSubmissionOverlay();
		controlSelectedStates();
		setMousables();
	};

	$(d).ready(init);

})(window, document, jQuery);
<|endoftext|>


<commit_before>//'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:SystemservicesCtrl
 * @description
 * # SystemservicesCtrl
 * Controller of the clientApp
 */

angular.module('clientApp')
  .controller('SystemservicesCtrl',function (
    $location,
    $scope,
  //  $parse,
    $interval,
    $http
  ) {
    servicelocation = "https://" + $location.$$host + "/api/";

    $scope.systemsettings = {};
      var stopped = "stopped";
      var notrunning = "not running";
      var running = "is running";
      $scope.checkServiceStatus = function() {
          var data = "servicename=elasticsearch";
          var config = {headers:{
            "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
          }};
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.elasticsearchstatusbit=(data==="true");
              });
           data = "servicename=logstash";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.logstashstatusbit=(data==="true");
              });
           data = "servicename=kibana4";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.kibanastatusbit=(data==="true");
              });
      };

    $http.post(servicelocation+"GetTimeZone",data,config)
      .success(function(data)
        {
          $scope.systemsettings.timezone = data;
        });

    console.log("Get Service Status")
    var data = "servicename=elasticsearch";
    var config = {headers:{
      "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
    }};

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.elasticsearchstatusbit = true;
           }
        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatusbit=(data==="true");
        });
    data = "servicename=logstash";
    $http.post(servicelocation+"GetServiceStatus",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatus=data;
               var str = data;
               if(str.match(stopped)){
                 console.log(data + ' service stopped');
                $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(notrunning)){
                 console.log(data + ' service stopped');
                  $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(running)){
                 console.log(data + ' service running');
                  $scope.systemsettings.logstashstatusbit = true;
               }
            });
    $http.post(servicelocation+"IsServiceRunning",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatusbit=(data==="true");
            });
    data = "servicename=kibana4";

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.kibanastatusbit = true;
           }

        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatusbit=(data==="true");
        });

    $scope.saveTimeZone = function(timezone) {
      $scope.selectedTimezone = timezone;
      var data = "timezone=" + timezone;
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      $http.post(servicelocation+"UpdateTimeZone",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
    };

    $scope.updateStatus = function(status, service)//status: Boolean running/not running, service: "serviceName"
    {
        if(status)
        {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Stop";
          var status = document.getElementsByName(service + 'Status');
        }
        else {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Start";
          var status = document.getElementsByName(service + 'Status');
        }
    };

    $scope.cycleElasticSearch = function() {
      var data = "servicename=elasticsearch";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.elasticsearchstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
      $scope.systemsettings.elasticsearchstatusbit = !$scope.systemsettings.elasticsearchstatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.elasticsearchstatusbit,'elastic');
    };

    $scope.cycleKibana = function() {
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};
      var data = "servicename=kibana4";

      var method = "StartService";
      if($scope.systemsettings.kibanastatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
      $scope.systemsettings.kibanastatusbit = !$scope.systemsettings.kibanastatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.kibanastatusbit,'kibana');
    };

    $scope.cycleLogstash = function() {
      var data = "servicename=logstash";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.logstashstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $scope.systemsettings.logstashstatusbit = !$scope.systemsettings.logstashstatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.logstashstatusbit,'logstash');
    };
  });
<commit_msg>define checkServiceStatus as a public function<commit_after>//'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:SystemservicesCtrl
 * @description
 * # SystemservicesCtrl
 * Controller of the clientApp
 */

angular.module('clientApp')
  .controller('SystemservicesCtrl',function (
    $location,
    $scope,
  //  $parse,
    $interval,
    $http
  ) {
    servicelocation = "https://" + $location.$$host + "/api/";

    $scope.systemsettings = {};
      var stopped = "stopped";
      var notrunning = "not running";
      var running = "is running";
      checkServiceStatus = function() {
          var data = "servicename=elasticsearch";
          var config = {headers:{
            "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
          }};
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.elasticsearchstatusbit=(data==="true");
              });
           data = "servicename=logstash";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.logstashstatusbit=(data==="true");
              });
           data = "servicename=kibana4";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.kibanastatusbit=(data==="true");
              });
      };

    $http.post(servicelocation+"GetTimeZone",data,config)
      .success(function(data)
        {
          $scope.systemsettings.timezone = data;
        });

    console.log("Get Service Status")
    var data = "servicename=elasticsearch";
    var config = {headers:{
      "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
    }};

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.elasticsearchstatusbit = true;
           }
        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatusbit=(data==="true");
        });
    data = "servicename=logstash";
    $http.post(servicelocation+"GetServiceStatus",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatus=data;
               var str = data;
               if(str.match(stopped)){
                 console.log(data + ' service stopped');
                $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(notrunning)){
                 console.log(data + ' service stopped');
                  $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(running)){
                 console.log(data + ' service running');
                  $scope.systemsettings.logstashstatusbit = true;
               }
            });
    $http.post(servicelocation+"IsServiceRunning",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatusbit=(data==="true");
            });
    data = "servicename=kibana4";

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.kibanastatusbit = true;
           }

        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatusbit=(data==="true");
        });

    $scope.saveTimeZone = function(timezone) {
      $scope.selectedTimezone = timezone;
      var data = "timezone=" + timezone;
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      $http.post(servicelocation+"UpdateTimeZone",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
    };

    $scope.updateStatus = function(status, service)//status: Boolean running/not running, service: "serviceName"
    {
        if(status)
        {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Stop";
          var status = document.getElementsByName(service + 'Status');
        }
        else {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Start";
          var status = document.getElementsByName(service + 'Status');
        }
    };

    $scope.cycleElasticSearch = function() {
      var data = "servicename=elasticsearch";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.elasticsearchstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
      $scope.systemsettings.elasticsearchstatusbit = !$scope.systemsettings.elasticsearchstatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.elasticsearchstatusbit,'elastic');
    };

    $scope.cycleKibana = function() {
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};
      var data = "servicename=kibana4";

      var method = "StartService";
      if($scope.systemsettings.kibanastatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
      $scope.systemsettings.kibanastatusbit = !$scope.systemsettings.kibanastatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.kibanastatusbit,'kibana');
    };

    $scope.cycleLogstash = function() {
      var data = "servicename=logstash";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.logstashstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $scope.systemsettings.logstashstatusbit = !$scope.systemsettings.logstashstatusbit;
      checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.logstashstatusbit,'logstash');
    };
  });
<|endoftext|>


<commit_before>/*globals define: false */
define(['lib/underscore', 'immutable', 'defer'], function(_, immutable, defer) {
	'use strict';

	var slice = Array.prototype.slice;

	_.mixin({defer: defer}); // override underscore defer
	_.mixin(immutable);       // add immutable methods

	function fmap(m, fn) {
		var x = {};
		_.each(m, function (v, k) { x[k] = fn(v, k); });
		return x;
	}

	// Return function that takes an array
	function apply(fn, self) {
		return fn.apply.bind(fn, self);
	}

	// Create array from arguments
	function array() {
		return _.toArray(arguments);
	}

	// Concat array with following arguments
	function concat(arr) {
		return arr.concat(slice.call(arguments, 1));
	}

	function pluckPaths(paths, obj) {
		return _.fmap(paths, _.partial(_.get_in, obj));
	}

	function pluckPathsArray(paths, obj) {
		return _.map(paths, _.partial(_.get_in, obj));
	}

	function partition_n(arr, n, step, pad) {
		var i, last, len, ret = [];

		step = step || n;
		for (i = 0; i < arr.length; i += step) {
			ret.push(arr.slice(i, i + n));
		}

		last = ret[ret.length - 1];
		if (last) {
			len = last.length;
			if (pad && len < n) {
				ret[ret.length - 1] = last.concat(pad.slice(0, n - len));
			}
		}
		return ret;
	}

	_.mixin({
		fmap: fmap,
		apply: apply,
		pluckPaths: pluckPaths,
		pluckPathsArray: pluckPathsArray,
		array: array,
		concat: concat,
		partition_n: partition_n
	});

	return _;
});
<commit_msg>Util for making sets.<commit_after>/*globals define: false */
define(['lib/underscore', 'immutable', 'defer'], function(_, immutable, defer) {
	'use strict';

	var slice = Array.prototype.slice;

	_.mixin({defer: defer}); // override underscore defer
	_.mixin(immutable);       // add immutable methods

	function fmap(m, fn) {
		var x = {};
		_.each(m, function (v, k) { x[k] = fn(v, k); });
		return x;
	}

	// Return function that takes an array
	function apply(fn, self) {
		return fn.apply.bind(fn, self);
	}

	// Create array from arguments
	function array() {
		return _.toArray(arguments);
	}

	// Concat array with following arguments
	function concat(arr) {
		return arr.concat(slice.call(arguments, 1));
	}

	function pluckPaths(paths, obj) {
		return _.fmap(paths, _.partial(_.get_in, obj));
	}

	function pluckPathsArray(paths, obj) {
		return _.map(paths, _.partial(_.get_in, obj));
	}

	function partition_n(arr, n, step, pad) {
		var i, last, len, ret = [];

		step = step || n;
		for (i = 0; i < arr.length; i += step) {
			ret.push(arr.slice(i, i + n));
		}

		last = ret[ret.length - 1];
		if (last) {
			len = last.length;
			if (pad && len < n) {
				ret[ret.length - 1] = last.concat(pad.slice(0, n - len));
			}
		}
		return ret;
	}

	function object_fn(keys, fn) {
		return _.reduce(keys, function (acc, k) {
			acc[k] = fn(k);
			return acc;
		}, {});
	}

	_.mixin({
		fmap: fmap,
		apply: apply,
		pluckPaths: pluckPaths,
		pluckPathsArray: pluckPathsArray,
		array: array,
		concat: concat,
		partition_n: partition_n,
		object_fn: object_fn
	});

	return _;
});
<|endoftext|>


<commit_before>/* utils/backbone.js
 * custom backbone extension */
'use strict';

define([
    //'lib/backbone/backbone-amd.min',
    '/js/lib/backbone/backbone-min',
    'moment',
    'underscore'
], function( Backbone, moment, _ ) {

    Backbone.View = (function(View) {
        return View.extend({
            constructor : function( options ) {
                this.options = options || {}
                View.apply(this, arguments)
            }
        })
    })(Backbone.View)

    Backbone.View.prototype.close = function() {
        this.$el.empty()
        this.stopListening()
        this.undelegateEvents()
        if ( this.spinner ) {
            this.spinner.detach()
        }
        if ( this.onClose ) {
            this.onClose()
        }
    }

    Backbone.Model.prototype.makeHtmlDate = function(dateString, onlyYear) {
        var res = [],
            d = parseInt(dateString, 10)

        d = new Date(d)

        res[0] = d.getFullYear()
        if (onlyYear) {
            return res[0]
        }
        res[1] = d.getMonth() + 1
        res[2] = d.getDate()
        return res.join("-")
    }

    Backbone.Model.prototype.parseDate = function(dateString) {
        return moment( new Date( parseInt(dateString, 10) ) )
    }

    Backbone.dispatcher = _.extend( {}, Backbone.Events )

    return Backbone
})
<commit_msg>adds js extension to backbone loader<commit_after>/* utils/backbone.js
 * custom backbone extension */
'use strict';

define([
    //'lib/backbone/backbone-amd.min',
    '/js/lib/backbone/backbone-min.js',
    'moment',
    'underscore'
], function( Backbone, moment, _ ) {

    Backbone.View = (function(View) {
        return View.extend({
            constructor : function( options ) {
                this.options = options || {}
                View.apply(this, arguments)
            }
        })
    })(Backbone.View)

    Backbone.View.prototype.close = function() {
        this.$el.empty()
        this.stopListening()
        this.undelegateEvents()
        if ( this.spinner ) {
            this.spinner.detach()
        }
        if ( this.onClose ) {
            this.onClose()
        }
    }

    Backbone.Model.prototype.makeHtmlDate = function(dateString, onlyYear) {
        var res = [],
            d = parseInt(dateString, 10)

        d = new Date(d)

        res[0] = d.getFullYear()
        if (onlyYear) {
            return res[0]
        }
        res[1] = d.getMonth() + 1
        res[2] = d.getDate()
        return res.join("-")
    }

    Backbone.Model.prototype.parseDate = function(dateString) {
        return moment( new Date( parseInt(dateString, 10) ) )
    }

    Backbone.dispatcher = _.extend( {}, Backbone.Events )

    return Backbone
})
<|endoftext|>


<commit_before>/**
The default theme for metro start.
*/
define(() => {
    return {
        init: function () {},

        // defaultFonts: ['system', 'raleway', 'source', 'wire one', 'im fell'],

        defaultFonts: [
            'raleway',
            'kurale',
            'wire One',
            'im fell english',
            'source serif pro',
            'monoton',
            'inconsolata',
        ],

        defaultWebservice: 'https://metro-start.azurewebsites.net/api',

        defaultTodos: [{
            'name': 'use the wrench to get started. . . ',
            'done': false,
        }],

        // The default theme for the app.
        defaultTheme: {
            'themeContent': {
                'font-chooser': 'system',
                'fontfamily-chooser': 'system',
                'fontweight-chooser': 'normal',
                'fontvariant-chooser': 'normal',
                'fontreadability-chooser': 'off',

                'palette-chooser': 'custom',
                'baseColor': '#aaffaa',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'optionsColor': '#ff0000',
                'backgroundColor': '#000000',

                'background-chooser': 'none',
                'trivariance-chooser': 'uniform',
                'trisize-chooser': 'medium',
                'tristyle-chooser': 'monochromatic',
            },
            'title': 'metro start',
            'author': 'metro start',
        },

        // The default sorting for pages.
        defaultSort: {
            'todos': false,
            'apps': false,
            'bookmarks': false,
            'themes': false,
        },

        // The default weather location.
        defaultWeather: {
            'city': 'vancouver, bc',
            'units': 'celsius',
            'visible': true,
        },

        systemThemes: [{
                'title': 'randomize',
                'author': 'metro start',

                'optionsColor': '#ff0000',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'backgroundColor': '#000000',

                'online': true,
            },
            {
                'title': 'metro start',
                'author': 'metro start',

                'optionsColor': '#ff0000',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'backgroundColor': '#000000',

                'online': true,
            },
        ],
    };
});<commit_msg>Spacing.<commit_after>/**
The default theme for metro start.
*/
define(() => {
    return {
        init: function() {},

        // defaultFonts: ['system', 'raleway', 'source', 'wire one', 'im fell'],

        defaultFonts: [
            'raleway',
            'kurale',
            'wire One',
            'im fell english',
            'source serif pro',
            'monoton',
            'inconsolata',
        ],

        defaultWebservice: 'https://metro-start.azurewebsites.net/api',

        defaultTodos: [{
            'name': 'use the wrench to get started. . . ',
            'done': false,
        }],

        // The default theme for the app.
        defaultTheme: {
            'themeContent': {
                'font-chooser': 'system',
                'fontfamily-chooser': 'system',
                'fontweight-chooser': 'normal',
                'fontvariant-chooser': 'normal',
                'fontreadability-chooser': 'off',

                'palette-chooser': 'custom',
                'baseColor': '#aaffaa',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'optionsColor': '#ff0000',
                'backgroundColor': '#000000',

                'background-chooser': 'none',
                'trivariance-chooser': 'uniform',
                'trisize-chooser': 'medium',
                'tristyle-chooser': 'monochromatic',
            },
            'title': 'metro start',
            'author': 'metro start',
        },

        // The default sorting for pages.
        defaultSort: {
            'todos': false,
            'apps': false,
            'bookmarks': false,
            'themes': false,
        },

        // The default weather location.
        defaultWeather: {
            'city': 'vancouver, bc',
            'units': 'celsius',
            'visible': true,
        },

        systemThemes: [{
                'title': 'randomize',
                'author': 'metro start',

                'optionsColor': '#ff0000',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'backgroundColor': '#000000',

                'online': true,
            },
            {
                'title': 'metro start',
                'author': 'metro start',

                'optionsColor': '#ff0000',
                'mainColor': '#ffffff',
                'titleColor': '#4a4a4a',
                'backgroundColor': '#000000',

                'online': true,
            },
        ],
    };
});
<|endoftext|>


<commit_before>/*! validator - v0.1.0 - 2014-04-15
* https://github.com/filamentgroup/validator
* Copyright (c) 2014 Filament Group; Licensed MIT */
/* global Validator:true */
/* global jQuery:true */
(function( $, window, undefined ) {

	var pluginName = "validator",
		dataKey = pluginName,
		formSubmitErrorEventName = 'error.validator',
		initSelector = "[required],[data-validate]";

	$.fn[ pluginName ] = function(){
		return this.each(function(){
			var $el = $( this );

			if( $el.data( dataKey ) ) {
				return;
			}

			var validator = new Validator( this, {
				applyElement: $el.closest( ".form-group" ),
				getErrorAnchor: function() {
					return this.$element.closest( "input:not([type=checkbox]), textarea, .btn, label.checkbox, .custom-select" );
				}
			});

			$el.data( dataKey, validator );

			$el.bind( "blur", function() {
				validator.validate();
				if( this.checkValidity ){
					this.checkValidity();
				}
			});

			$el.bind( "invalid", function(){
				if( !(this.validity && this.validity.patternMismatch) ){
					validator.invalidate();
				}
			});

			$el.closest( "form" ).bind( "submit", function( e ){
				if( !validator.validate() ){
					if( !e.isDefaultPrevented() ) {
						$( this ).trigger( formSubmitErrorEventName );
					}
					e.preventDefault();
				}
			});
		});
	};

	// auto-init on enhance (which is called on domready)
	$( document ).bind( "enhance", function( e ){
		$( initSelector, e.target )[ pluginName ]();
	});

}( jQuery, this ));
<commit_msg>Closes #30<commit_after>/*! validator - v0.1.0 - 2014-04-15
* https://github.com/filamentgroup/validator
* Copyright (c) 2014 Filament Group; Licensed MIT */
/* global Validator:true */
/* global jQuery:true */
(function( $, window, undefined ) {

	var pluginName = "validator",
		dataKey = pluginName,
		formSubmitErrorEventName = 'error.validator',
		initSelector = "[required],[data-validate]";

	$.fn[ pluginName ] = function(){
		return this.each(function(){
			var $el = $( this );

			if( $el.data( dataKey ) ) {
				return;
			}

			var validator = new Validator( this, {
				applyElement: $el.closest( ".form-group" ),
				getErrorAnchor: function() {
					return this.$element
						.closest( "input, textarea, .btn, label.checkbox, .custom-select" )
						.not( "input[type=checkbox]" );
				}
			});

			$el.data( dataKey, validator );

			$el.bind( "blur", function() {
				validator.validate();
				if( this.checkValidity ){
					this.checkValidity();
				}
			});

			$el.bind( "invalid", function(){
				if( !(this.validity && this.validity.patternMismatch) ){
					validator.invalidate();
				}
			});

			$el.closest( "form" ).bind( "submit", function( e ){
				if( !validator.validate() ){
					if( !e.isDefaultPrevented() ) {
						$( this ).trigger( formSubmitErrorEventName );
					}
					e.preventDefault();
				}
			});
		});
	};

	// auto-init on enhance (which is called on domready)
	$( document ).bind( "enhance", function( e ){
		$( initSelector, e.target )[ pluginName ]();
	});

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


<commit_before>var metaMpgData    = {};
var vehicleRequest = {};

var $vehicleDefer  = $.Deferred();
vehicleRequest.index = function() {
    var $carYear      = $('.carYear');
    var $carMake      = $('.carMake');
    var $carModel     = $('.carModel');
    var $carVersion   = $('.carVersion');
    var $avgMpg       = $('.avgMpg');
    var $minMpg       = $('.minMpg');
    var $maxMpg       = $('.maxMpg');
    var $errorVehicle = $('.errorVehicle');

    var date = new Date();
    var currentYear = date.getFullYear();
    for (ii = 1984; ii <= currentYear; ii++) {
        $carYear.append('<option>' + ii + '</option>')
    };

    $carYear.on('change', function() {
        console.log('carYear event fires');
        var userSelectedYear = ""
        $(".carYear option:selected").each(function() {
            userSelectedYear += $(this).text();
        });
        var ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=' + userSelectedYear,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {
            $(xml).find("value").each(function() {
                    $carMake.append('<option>' + $(this).text() + '</option>');
                })
                // $vehicleDefer.resolve();
        });
    });
    //MODELSd
    $carMake.change(function() {
        console.log('carMake event fires');
        var userSelectedMake = "";
        $(".carMake option:selected").each(function() {
            userSelectedMake += $(this).text();
        });

        ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/model?year=2012&make=' + userSelectedMake,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {
            $(xml).find("value").each(function() {
                    $carModel.append('<option>' + $(this).text() + '</option>');
                })
                // $vehicleDefer.resolve();
                //        console.log("vehicleDefer resolved");

        });
    });

    $carModel.on('change', function() {
        userCarVersion();
    });
    function userCarVersion() {
        userYear    = $(".carYear option:selected").text();
        userMake    = $(".carMake option:selected").text();
        userModel   = $(".carModel option:selected").text();
        ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/options?year=' + userYear + '&make=' + userMake + '&model=' + userModel,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {

            $(xml).find("text").each(function() {
                $carVersion.append('<option>' + $(this).text() + '</option>');
            });
            var vehicleID = $(xml).find("text:contains('" + $carVersion.val() + "')").next("value").text();

            console.log(vehicleID);

            $carVersion.on('change', function() {
                userCarId();
            });

            function userCarId() {
                console.log(vehicleID);
                ajaxRequest = $.ajax({
                    type: "GET",
                    url: 'http://www.fueleconomy.gov/ws/rest/ympg/shared/ympgVehicle/' + vehicleID,
                    dataType: "xml",
                    statusCode: {
                        404: function() {
                            //resets and error message in drop down section
                            $errorVehicle.append('Sorry, we could not find that vehicle.')
                            $carYear.val(0);
                            $carMake.val(0);
                            $carModel.val(0);
                            $carVersion.val(0);
                        }
                    }
                });
                console.log(xml);
                ajaxRequest.done(function(xml) {
                    $(xml).find("avgMpg").each(function() {
                        metaMpgData.avgmpg = Math.round(parseInt($(this).text()));
                        console.log(metaMpgData.avgmpg);
                        $avgMpg.append($(this).text());
                    });
                    $(xml).find("maxMpg").each(function() {
                        metaMpgData.maxmpg = $(this).text();
                        $maxMpg.append($(this).text());
                    });
                    $(xml).find("minMpg").each(function() {
                        metaMpgData.minmpg = $(this).text();
                        $minMpg.append($(this).text());
                        console.log(metaMpgData);
                    });
                    $vehicleDefer.resolve();
                    console.log("vehicle defer resolved");

                })
            } //userCarId
        }); //ajax done #1
    } //userCarVersion
}; //vehicleRequest closed
vehicleRequest.index();
<commit_msg>fixed logic to handle if car version contains only one result<commit_after>var metaMpgData    = {};
var vehicleRequest = {};

var $vehicleDefer  = $.Deferred();
vehicleRequest.index = function() {
    var $carYear      = $('.carYear');
    var $carMake      = $('.carMake');
    var $carModel     = $('.carModel');
    var $carVersion   = $('.carVersion');
    var $avgMpg       = $('.avgMpg');
    var $minMpg       = $('.minMpg');
    var $maxMpg       = $('.maxMpg');
    var $errorVehicle = $('.errorVehicle');

    var date = new Date();
    var currentYear = date.getFullYear();
    for (ii = 1984; ii <= currentYear; ii++) {
        $carYear.append('<option>' + ii + '</option>')
    };

    $carYear.on('change', function() {
        console.log('carYear event fires');
        var userSelectedYear = ""
        $(".carYear option:selected").each(function() {
            userSelectedYear += $(this).text();
        });
        var ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=' + userSelectedYear,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {
            $carMake.html('');
            $carMake.append('<option>Make</option>');
            $(xml).find("value").each(function() {
                $carMake.append('<option>' + $(this).text() + '</option>');
            })
                // $vehicleDefer.resolve();
            });
    });
    //MODELSd
    $carMake.change(function() {
        console.log('carMake event fires');
        var userSelectedMake = "";
        $(".carMake option:selected").each(function() {
            userSelectedMake += $(this).text();
        });

        ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/model?year=2012&make=' + userSelectedMake,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {
            $carModel.html('');
            $carModel.append('<option>Model</option>');
            $(xml).find("value").each(function() {
                $carModel.append('<option>' + $(this).text() + '</option>');
            })
                // $vehicleDefer.resolve();
                //        console.log("vehicleDefer resolved");

            });
    });

    $carModel.on('change', function() {
        userCarVersion();
    });
    function userCarVersion() {
        userYear    = $(".carYear option:selected").text();
        userMake    = $(".carMake option:selected").text();
        userModel   = $(".carModel option:selected").text();
        ajaxRequest = $.ajax({
            type: "GET",
            url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/options?year=' + userYear + '&make=' + userMake + '&model=' + userModel,
            dataType: "xml",
        });
        ajaxRequest.done(function(xml) {

            $(xml).find("text").each(function() {
                $carVersion.append('<option>' + $(this).text() + '</option>');
            });

            if($carVersion.children().length===1){
                var vehicleID = $(xml).find("text:contains('" + $carVersion.val() + "')").next("value").text();
                console.log(vehicleID);
                userCarId(vehicleID);
            }

            $carVersion.on('change', function() {
                var vehicleID = $(xml).find("text:contains('" + $carVersion.val() + "')").next("value").text();
                userCarId(vehicleID);
            });

            function userCarId(vehicleID) {
                console.log(vehicleID);
                ajaxRequest = $.ajax({
                    type: "GET",
                    url: 'http://www.fueleconomy.gov/ws/rest/ympg/shared/ympgVehicle/' + vehicleID,
                    dataType: "xml",
                    statusCode: {
                        404: function() {
                            //resets and error message in drop down section
                            $errorVehicle.append('Sorry, we could not find the information about vehicle.')
                            $carYear.val(0);
                            $carMake.val(0);
                            $carModel.val(0);
                            $carVersion.val(0);
                        }
                    }
                });
                console.log(xml);
                ajaxRequest.done(function(xml) {
                    $(xml).find("avgMpg").each(function() {
                        metaMpgData.avgmpg = Math.round(parseInt($(this).text()));
                        console.log(metaMpgData.avgmpg);
                        $avgMpg.append($(this).text());
                    });
                    $(xml).find("maxMpg").each(function() {
                        metaMpgData.maxmpg = $(this).text();
                        $maxMpg.append($(this).text());
                    });
                    $(xml).find("minMpg").each(function() {
                        metaMpgData.minmpg = $(this).text();
                        $minMpg.append($(this).text());
                        console.log(metaMpgData);
                    });
                    $vehicleDefer.resolve();
                    console.log("vehicle defer resolved");

                })
            } //userCarId
        }); //ajax done #1
    } //userCarVersion
}; //vehicleRequest closed
vehicleRequest.index();
<|endoftext|>


<commit_before>var app = app || {};

app.UserEdit = Backbone.View.extend({
	tagName: 'div',

	template: _.template($('#user-edit-template').html()),

	events: {
        'submit': 'saveValues'
	},

	initialize: function(){
        // Re-render table when collection changes
        //this.listenTo(this.model, 'change', this.render);
        this.$body = $("#body");
        this.$body.append(this.$el);
        this.render();
	},

	render: function(){
        if (this.model){
            this.$el.html( this.template({ data: this.model.attributes }) );
        } else {
            this.$el.html( this.template({ data: {} }) );
        }
		return this;
	},

    saveValue: function(){

    }
});<commit_msg>Added setting of new model values.<commit_after>var app = app || {};

app.UserEdit = Backbone.View.extend({
	tagName: 'div',

	template: _.template($('#user-edit-template').html()),

	events: {
        'submit': 'saveValues'
	},

	initialize: function(){
        // Re-render table when collection changes
        //this.listenTo(this.model, 'change', this.render);
        this.$body = $("#body");
        this.$body.html(this.el);
        this.render();
	},

	render: function(){
        if (this.model){
            this.$el.html( this.template({ data: this.model.attributes }) );
        } else {
            this.$el.html( this.template({ data: {} }) );
        }
		return this;
	},

    saveValue: function(){
        var values = {
            name: this.$el.find('.name').val(),
            first_name: this.$el.find('first-name').val(),
            last_name: this.$el.find('last-name').val(),
            email: this.$el.find('email').val(),
            birthday: this.$el.find('birthday').val()
        };

        // Update model with new values
        this.model.set(values);
    }
});<|endoftext|>


<commit_before>import bootstrapWidgets from './bootstrapWidgets'
import {loadScriptAsync, getBackendUrl} from './utils'

;(async () => {
  const backendUrl = getBackendUrl(document)

  const params = {
    backendUrl
  }

  await loadScriptAsync(`${backendUrl}/nice2/javascript/nice2-react.release.js`)
  await bootstrapWidgets(params)
})()
<commit_msg>feat(widget-utils): run bootstrap script after dom loaded<commit_after>import bootstrapWidgets from './bootstrapWidgets'
import {loadScriptAsync, getBackendUrl} from './utils'

;(() => {
  const backendUrl = getBackendUrl(document)

  const params = {
    backendUrl
  }

  // guarantee to initalize all widgets on the page
  document.addEventListener('DOMContentLoaded', async () => {
    await loadScriptAsync(`${backendUrl}/nice2/javascript/nice2-react.release.js`)
    await bootstrapWidgets(params)
  })
})()
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import isBrowser from 'utils/isBrowser';

import PropTypes from 'prop-types';

import Loading from './Loading';

export default class Instance extends PureComponent {
  static propTypes = {
    prefix: PropTypes.string,
    className: PropTypes.string,
    float: PropTypes.bool,
    show: PropTypes.bool,
    showDelay: PropTypes.number,
    zIndex: PropTypes.number,
    containerClass: PropTypes.string,
  };

  static defaultProps = {
    prefix: 'zent',
    className: '',
    // FIXME: use defaultProps when we drop support for static
    // float: false,
    show: false,
    showDelay: 0,
    zIndex: 9998,
    containerClass: '',
  };

  componentDidMount() {
    this.renderLoading();
  }

  // 因为需要确保内部元素已经 render 完毕，所以使用 did，但是因此带来额外的对 show 字段的判断逻辑
  componentDidUpdate() {
    this.renderLoading();
  }

  componentWillUnmount() {
    if (this.instance) {
      this.instance.then(({ container }) => {
        ReactDOM.unmountComponentAtNode(container);
        container.parentNode.removeChild(container);
      });
    }
  }

  // 通过以下函数与组件通信
  renderLoading(target) {
    // static 方式，loading 将存在于文档流中
    if (!isFloat(this.props)) {
      return;
    }

    if (!this.instance) {
      if (!target) {
        target = ReactDOM.findDOMNode(this);
      }
      this.instance = newInstance({
        ...this.props,
        target,
      });
    } else if (this.instance) {
      this.instance.then(({ show }) => {
        show && show(this.props);
      });
    }
  }

  render() {
    const float = isFloat(this.props);

    if (!isFloat(this.props)) {
      return (
        <Loading {...this.props} float={float}>
          {this.props.children}
        </Loading>
      );
    }

    // Return null to make React happy if Loading has no children
    return this.props.children || null;
  }
}

function newInstance(props) {
  if (!isBrowser) return;

  let div = document.createElement('div');
  div.className = `${props.prefix}-loading-container ${props.containerClass}`;
  document.body.appendChild(div);

  return new Promise(resolve => {
    ReactDOM.render(
      <Loading
        {...props}
        ref={loading => {
          if (loading) {
            resolve({
              show: loading.show,
              container: div,
            });
          }
        }}
      />,
      div
    );
  });
}

// FIXME: remove support for props.static
function isFloat(props) {
  const hasStatic = props.hasOwnProperty('static');
  const hasFloat = props.hasOwnProperty('float');

  if (hasFloat) {
    return props.float;
  }

  return hasStatic ? !props.static : false;
}
<commit_msg>doc: update comment<commit_after>import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import isBrowser from 'utils/isBrowser';

import PropTypes from 'prop-types';

import Loading from './Loading';

export default class Instance extends PureComponent {
  static propTypes = {
    prefix: PropTypes.string,
    className: PropTypes.string,
    float: PropTypes.bool,
    show: PropTypes.bool,
    showDelay: PropTypes.number,
    zIndex: PropTypes.number,
    containerClass: PropTypes.string,
  };

  static defaultProps = {
    prefix: 'zent',
    className: '',
    // FIXME: use defaultProps when we drop support for static
    // float: false,
    show: false,
    showDelay: 0,
    zIndex: 9998,
    containerClass: '',
  };

  componentDidMount() {
    this.renderLoading();
  }

  // 因为需要确保内部元素已经 render 完毕，所以使用 did，但是因此带来额外的对 show 字段的判断逻辑
  componentDidUpdate() {
    this.renderLoading();
  }

  componentWillUnmount() {
    if (this.instance) {
      this.instance.then(({ container }) => {
        ReactDOM.unmountComponentAtNode(container);
        container.parentNode.removeChild(container);
      });
    }
  }

  // 通过以下函数与组件通信
  renderLoading(target) {
    // static 方式，loading 将存在于文档流中
    if (!isFloat(this.props)) {
      return;
    }

    if (!this.instance) {
      if (!target) {
        target = ReactDOM.findDOMNode(this);
      }
      this.instance = newInstance({
        ...this.props,
        target,
      });
    } else if (this.instance) {
      this.instance.then(({ show }) => {
        show && show(this.props);
      });
    }
  }

  render() {
    const float = isFloat(this.props);

    if (!isFloat(this.props)) {
      return (
        <Loading {...this.props} float={float}>
          {this.props.children}
        </Loading>
      );
    }

    // Return null to make React happy if Loading has no children
    return this.props.children || null;
  }
}

function newInstance(props) {
  if (!isBrowser) return;

  let div = document.createElement('div');
  div.className = `${props.prefix}-loading-container ${props.containerClass}`;
  document.body.appendChild(div);

  return new Promise(resolve => {
    ReactDOM.render(
      <Loading
        {...props}
        ref={loading => {
          if (loading) {
            resolve({
              show: loading.show,
              container: div,
            });
          }
        }}
      />,
      div
    );
  });
}

// Backward compatible with `static`
function isFloat(props) {
  const hasStatic = props.hasOwnProperty('static');
  const hasFloat = props.hasOwnProperty('float');

  if (hasFloat) {
    return props.float;
  }

  return hasStatic ? !props.static : false;
}
<|endoftext|>


<commit_before>/* Модуль сжатия js-скриптов, css-стилей, html-файлов и
 * конвертации картинок в css-стилях
 * в base64 и помещения их в файл стилей
 */

console.log('minify.js loaded...');

/* функция сжимает js-скрипты
 * и сохраняет их с именем .min.js
 */

var fs = require('fs');
var path=require('path');

var MinFolder='min/';
/* function clear MinFolder
 * if we could not create
 * directory and it is
 * not exist
 */
var folderExist = function(pError, pStat){
    "use strict";
    /*file found and it's directory */
    if(!pError && pStat.isDirectory())
        console.log('folder exist: ' + MinFolder);
    else MinFolder='/';
};

/*
 * function says thet folder created
 * if everything is OK, or
 * moves to folderExist function
 */
var makeFolder = function(pError){
    "use strict";
    /*folder created successfully*/
    if(!pError)
        console.log('folder created: min');
    else fs.stat(MinFolder,folderExist);
};

/* Trying to create folder min
 * where woud be minifyed versions
 * of files 511(10)=777(8)
 * rwxrwxrwx
 */
fs.mkdir(MinFolder,511,makeFolder);

exports.MinFolder = MinFolder;
exports.Cache    = {};

/* function which minificate js-files
 * @pJSFiles_a              - varible, wich contain array
 *                            of js file names or string, if name
 *                            single, or object if postProcessing neaded
 *                              { Name:'1.js', Func: function(pFinalCode){} }
 * @pCache_b                - if true files do not writes on disk, just saves
 *                              in Minify Cache
 */
exports.jsScripts=function jsScripts(pJSFiles_a, pCache_b){
    'use strict';
    /* подключаем модуль uglify-js
     * если его нет - дальнейшая
     * работа функции не имеет смысла
     */
    try{
        var jsp = require("uglify-js").parser;
        var pro = require("uglify-js").uglify;
    }catch(error){
        console.log('can\'n load uglify-js\n'                  +
            'to use js-minification you need to install uglify-js\n'    +
                'npm install uglify-js\n'                               +
                'https://github.com/mishoo/UglifyJS');
        return false;
    }
    /* Константы */
    var CLIENT_JS='client.js';
    var CLOUDFUNC_JS='lib/cloudfunc.js';

    /* if passed string, or object
     * putting it to array
     */
    if (typeof pJSFiles_a === 'string' ||
        !pJSFiles_a[0])
            pJSFiles_a=[pJSFiles_a];
    var dataReaded_f=function(pFileName, pData){
        /*
         * if postProcessing function exist
         * getting it from pFileName object
         */
        var lMoreProcessing_f;
        if(typeof pFileName === 'object'){
            var lName;
            for(lName in pFileName){
                break;
            }
            lMoreProcessing_f = pFileName[lName];
            pFileName = lName;
        }
        console.log('file ' + pFileName + ' readed');

        /*********************************/
        /* сжимаем код через uglify-js */
        var uglify_js=function(pDdata){
            var orig_code = pDdata.toString();
            var ast = jsp.parse(orig_code); // parse code and get the initial AST
            ast = pro.ast_mangle(ast); // get a new AST with mangled names
            ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
            var result_code = pro.gen_code(ast); // compressed code here
            return result_code;
        };
        /*********************************/
        var final_code=uglify_js(pData);

        var minFileName=pFileName.replace('.js','.min.js');

        /* если мы сжимаем client.js -
         * меняем строку cloudfunc.js на
         * cloudfunc.min.js и выводим сообщение
         *
         * меняем строку keyBinding.js на
         * keyBinding.min.js
         * если другой файл - ничего не деалем
         */

        /* if lMoreProcessing_f seeted up
         * and function associated with
         * current file name exists -
         * run it
         */
        if(lMoreProcessing_f                    &&
            typeof lMoreProcessing_f === "function"){
                final_code = lMoreProcessing_f(final_code);
        }

        minFileName = path.basename(minFileName);
        /* записываем сжатый js-скрипт
         * в кэш если установлен pCache_b
         * или на диск, если не установлен
         */
        if(pCache_b){
            exports.Cache[minFileName] = final_code;
            console.log('file ' + minFileName + ' saved to cache...');
        }
        else{
            /* minimized file will be in min file
             * if it's possible if not -
             * in root
             */
            minFileName = MinFolder + minFileName;

            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        }
    };

    /* moving thru all elements of js files array */
    for(var i=0; pJSFiles_a[i]; i++){
        /* if postProcessing function exist
         * getting file name and passet next
         */
        var lMoreProcessing_o = pJSFiles_a[i];
        var lName;
        if(typeof lMoreProcessing_o === 'object'){
            for(lName in lMoreProcessing_o){
            }
        }else lName = pJSFiles_a[i];
        console.log('reading file ' + lName + '...');

        fs.readFile(lName, fileReaded(pJSFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 * @pCSSFiles_a           - масив имен css файлов или строка,
 *                          если имя одно
 * @pImgConvertToBase64_b - булевый признак,
 *                          который отвечает за то, что быконвертировать
 *                          картинки в base64 и поместить в выходной css файл
 */
exports.cssStyles=function cssStyles(pCSSFiles_a, pImgConvertToBase64_b){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var cleanCSS;
     try{
        cleanCSS = require('clean-css');
    }catch(error){
        console.log('can\'n load clean-css \n'                          +
            'to use css-minification you need to install clean-css \n'  +
                'npm install clean-css\n'                               +
                'https://github.com/GoalSmashers/clean-css');
        return false;
    }

    if(typeof pCSSFiles_a === "string")
        pCSSFiles_a=[pCSSFiles_a];
    /* Varible contains information
     * about readed css file
     */
    var lCSSFiles_doneCount=0;

    var lAllStyle='';

    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var clean_css=function(pData){
            /* Сохраняем весь стиль в одну переменную*/
            return cleanCSS.process(pData);
        };
        /*********************************/
        var final_code=clean_css(pData);

        lAllStyle+=final_code;

        var minFileName=pFileName.replace('.css','.min.css');

        ++lCSSFiles_doneCount;

        /* if all files writed we
         * save all minimized css
         * to one file all.min.css
         */
        if(pCSSFiles_a.length === lCSSFiles_doneCount){
            /* если включена конвертация картинок в base64
             * вызываем её
             */
            if(pImgConvertToBase64_b)
                base64_images(lAllStyle);
            else
                fs.writeFile(MinFolder + 'all.min.css', lAllStyle, fileWrited(MinFolder + 'all.min.css'));
        }
         /* в другом случае - записываем сжатый css файл*/
        else{
            minFileName = MinFolder + path.basename(minFileName);
            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        }
    };

   /* moving thru all elements of css files array */
    for(var i=0;pCSSFiles_a[i];i++){
        console.log('reading file ' + pCSSFiles_a[i]+'...');
        fs.readFile(pCSSFiles_a[i],fileReaded(pCSSFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция сжимает html файлы
 * и сохраняет их с именем .min.html
 * @pHTMLFiles_a - массим имен html
 * файлов, или строка если имя одно
 */
exports.html=function(pHTMLFiles_a){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var htmlMinifier;
     try{
        htmlMinifier = require('html-minifier');
    }catch(error){
        console.log('can\'n load html-minifier \n'                 +
            'to use html-minification you need to install html-minifier\n'  +
                'npm install html-minifier\n'                               +
                'https://github.com/kangax/html-minifier');
        return false;
    }

    /* if html file names is not array
     * making it array
     */
    if (typeof pHTMLFiles_a === 'string' ||
        !pHTMLFiles_a[0])
            pHTMLFiles_a=[pHTMLFiles_a];
    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var html_minify=function(pData){
            /* Сохраняем весь стиль в одну переменную*/

            var lOptions={
                removeComments:                 true,
                removeCommentsFromCDATA:        true,
                removeCDATASectionsFromCDATA:   true,
                collapseWhitespace:             true,
                collapseBooleanAttributes:      true,
                removeAttributeQuotes:          true,
                removeRedundantAttributes:      true,
                useShortDoctype:                true,
                removeEmptyAttributes:          true,
                /* оставляем, поскольку у нас
                 * в элемент fm генерируеться
                 * таблица файлов
                 */
                removeEmptyElements:            false,
                removeOptionalTags:             true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true
            };

            return htmlMinifier.minify(pData,lOptions);
        };
        /*********************************/
        var final_code=html_minify(pData);

        var minFileName=pFileName.replace('.html','.min.html');

         /* adding Min folder to file path */
         minFileName = MinFolder + minFileName;
         /* записываем сжатый html файл*/
        fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

     /* moving thru all elements of html files array */
    for(var i=0;pHTMLFiles_a[i];i++){
        console.log('reading file ' + pHTMLFiles_a[i]+'...');
        fs.readFile(pHTMLFiles_a[i],fileReaded(pHTMLFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция переводит картинки в base64 и записывает в css-файл*/
function base64_images(pFileContent_s){
    'use strict';
     var b64img;
     try{
        b64img = require('css-b64-images');
    }catch(error){
        console.log('can\'n load clean-css \n'                 +
            'to use images to base64 convertation you need to install css-base64-images \n'  +
                'npm install -g css-b64-images\n'                               +
                'https://github.com/Filirom1/css-base64-images');
        return false;
    }
    b64img.fromString(pFileContent_s, '.','', function(err, css){
        console.log('images converted to base64 and saved in css file');
        fs.writeFile(MinFolder + 'all.min.css', css, fileWrited(MinFolder + 'all.min.css'));
    });
}

/* Функция создаёт асинхроную версию
 * для чтения файла
 * @pFileName - имя считываемого файла
 */
function fileReaded(pFileName,pCompressFunc){
    "use strict";
    return function(pError,pData){
        /* функция в которую мы попадаем,
         * если данные считались
         *
         * если ошибка - показываем её
         * иначе если переданная функция -
         * функция запускаем её
         */
        if(!pError)
            if (pCompressFunc && typeof pCompressFunc==="function")
                    pCompressFunc(pFileName,pData.toString());
        else console.log(pError);
    };
}

/*
 * Функция вызываеться после записи файла
 * и выводит ошибку или сообщает,
 * что файл успешно записан
 */
function fileWrited(pFileName){
    "use strict";
    return function(error){
        console.log(error?error:('file '+pFileName+' writed...'));
    };
}<commit_msg>added file hash checking<commit_after>/* Модуль сжатия js-скриптов, css-стилей, html-файлов и
 * конвертации картинок в css-стилях
 * в base64 и помещения их в файл стилей
 */

console.log('minify.js loaded...');

/* функция сжимает js-скрипты
 * и сохраняет их с именем .min.js
 */

var fs = require('fs');
var path=require('path');
var crypto = require('crypto');

var Hashes;

var MinFolder='min/';
/* function clear MinFolder
 * if we could not create
 * directory and it is
 * not exist
 */
var folderExist = function(pError, pStat){
    "use strict";
    /*file found and it's directory */
    if(!pError && pStat.isDirectory())
        console.log('folder exist: ' + MinFolder);
    else MinFolder='/';
};

/*
 * function says thet folder created
 * if everything is OK, or
 * moves to folderExist function
 */
var makeFolder = function(pError){
    "use strict";
    /*folder created successfully*/
    if(!pError)
        console.log('folder created: min');
    else fs.stat(MinFolder,folderExist);
};

/* Trying to create folder min
 * where woud be minifyed versions
 * of files 511(10)=777(8)
 * rwxrwxrwx
 */
fs.mkdir(MinFolder,511,makeFolder);

exports.MinFolder = MinFolder;
exports.Cache    = {};

/* function which minificate js-files
 * @pJSFiles_a              - varible, wich contain array
 *                            of js file names or string, if name
 *                            single, or object if postProcessing neaded
 *                              { Name:'1.js', Func: function(pFinalCode){} }
 * @pCache_b                - if true files do not writes on disk, just saves
 *                              in Minify Cache
 */
exports.jsScripts=function jsScripts(pJSFiles_a, pCache_b){
    'use strict';
    /* подключаем модуль uglify-js
     * если его нет - дальнейшая
     * работа функции не имеет смысла
     */
    try{
        var jsp = require("uglify-js").parser;
        var pro = require("uglify-js").uglify;
    }catch(error){
        console.log('can\'n load uglify-js\n'                  +
            'to use js-minification you need to install uglify-js\n'    +
                'npm install uglify-js\n'                               +
                'https://github.com/mishoo/UglifyJS');
        return false;
    }
    /* Константы */
    var CLIENT_JS='client.js';
    var CLOUDFUNC_JS='lib/cloudfunc.js';

    /* if passed string, or object
     * putting it to array
     */
    if (typeof pJSFiles_a === 'string' ||
        !pJSFiles_a[0])
            pJSFiles_a=[pJSFiles_a];

    var dataReaded_f=function(pFileName, pData){
        /*
         * if postProcessing function exist
         * getting it from pFileName object
         */
        var lMoreProcessing_f;
        if(typeof pFileName === 'object'){
            var lName;
            for(lName in pFileName){
                break;
            }
            lMoreProcessing_f = pFileName[lName];
            pFileName = lName;
        }
        console.log('file ' + pFileName + ' readed');

        if (!isFileChanged(pFileName, pData)) {
            console.log('file: ' + pFileName + ' do not changed...');
            return;
        }

        /*********************************/
        /* сжимаем код через uglify-js */
        var uglify_js=function(pDdata){
            var orig_code = pDdata.toString();
            var ast = jsp.parse(orig_code); // parse code and get the initial AST
            ast = pro.ast_mangle(ast); // get a new AST with mangled names
            ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
            var result_code = pro.gen_code(ast); // compressed code here
            return result_code;
        };
        /*********************************/
        var final_code=uglify_js(pData);

        var minFileName=pFileName.replace('.js','.min.js');

        /* если мы сжимаем client.js -
         * меняем строку cloudfunc.js на
         * cloudfunc.min.js и выводим сообщение
         *
         * меняем строку keyBinding.js на
         * keyBinding.min.js
         * если другой файл - ничего не деалем
         */

        /* if lMoreProcessing_f seeted up
         * and function associated with
         * current file name exists -
         * run it
         */
        if(lMoreProcessing_f                    &&
            typeof lMoreProcessing_f === "function"){
                final_code = lMoreProcessing_f(final_code);
        }

        minFileName = path.basename(minFileName);

        /* записываем сжатый js-скрипт
         * в кэш если установлен pCache_b
         * или на диск, если не установлен
         */
        if(pCache_b){
            exports.Cache[minFileName] = final_code;
            console.log('file ' + minFileName + ' saved to cache...');
        }
        else{
            /* minimized file will be in min file
             * if it's possible if not -
             * in root
             */
            minFileName = MinFolder + minFileName;

            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        }
    };

    /* moving thru all elements of js files array */
    for(var i=0; pJSFiles_a[i]; i++){
        /* if postProcessing function exist
         * getting file name and passet next
         */
        var lMoreProcessing_o = pJSFiles_a[i];
        var lName;
        if(typeof lMoreProcessing_o === 'object'){
            for(lName in lMoreProcessing_o){
            }
        }else lName = pJSFiles_a[i];
        console.log('reading file ' + lName + '...');

        fs.readFile(lName, fileReaded(pJSFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 * @pCSSFiles_a           - масив имен css файлов или строка,
 *                          если имя одно
 * @pImgConvertToBase64_b - булевый признак,
 *                          который отвечает за то, что быконвертировать
 *                          картинки в base64 и поместить в выходной css файл
 */
exports.cssStyles=function cssStyles(pCSSFiles_a, pImgConvertToBase64_b){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var cleanCSS;
     try{
        cleanCSS = require('clean-css');
    }catch(error){
        console.log('can\'n load clean-css \n'                          +
            'to use css-minification you need to install clean-css \n'  +
                'npm install clean-css\n'                               +
                'https://github.com/GoalSmashers/clean-css');
        return false;
    }

    if(typeof pCSSFiles_a === "string")
        pCSSFiles_a=[pCSSFiles_a];
    /* Varible contains information
     * about readed css file
     */
    var lCSSFiles_doneCount=0;

    var lAllStyle='';

    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var clean_css=function(pData){
            /* Сохраняем весь стиль в одну переменную*/
            return cleanCSS.process(pData);
        };
        /*********************************/
        var final_code=clean_css(pData);

        lAllStyle+=final_code;

        var minFileName=pFileName.replace('.css','.min.css');

        ++lCSSFiles_doneCount;

        /* if all files writed we
         * save all minimized css
         * to one file all.min.css
         */
        if(pCSSFiles_a.length === lCSSFiles_doneCount){
            /* если включена конвертация картинок в base64
             * вызываем её
             */
            if(pImgConvertToBase64_b)
                base64_images(lAllStyle);
            else
                fs.writeFile(MinFolder + 'all.min.css', lAllStyle, fileWrited(MinFolder + 'all.min.css'));
        }
         /* в другом случае - записываем сжатый css файл*/
        else{
            minFileName = MinFolder + path.basename(minFileName);
            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        }
    };

   /* moving thru all elements of css files array */
    for(var i=0;pCSSFiles_a[i];i++){
        console.log('reading file ' + pCSSFiles_a[i]+'...');
        fs.readFile(pCSSFiles_a[i],fileReaded(pCSSFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция сжимает html файлы
 * и сохраняет их с именем .min.html
 * @pHTMLFiles_a - массим имен html
 * файлов, или строка если имя одно
 */
exports.html=function(pHTMLFiles_a){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var htmlMinifier;
     try{
        htmlMinifier = require('html-minifier');
    }catch(error){
        console.log('can\'n load html-minifier \n'                 +
            'to use html-minification you need to install html-minifier\n'  +
                'npm install html-minifier\n'                               +
                'https://github.com/kangax/html-minifier');
        return false;
    }

    /* if html file names is not array
     * making it array
     */
    if (typeof pHTMLFiles_a === 'string' ||
        !pHTMLFiles_a[0])
            pHTMLFiles_a=[pHTMLFiles_a];
    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var html_minify=function(pData){
            /* Сохраняем весь стиль в одну переменную*/

            var lOptions={
                removeComments:                 true,
                removeCommentsFromCDATA:        true,
                removeCDATASectionsFromCDATA:   true,
                collapseWhitespace:             true,
                collapseBooleanAttributes:      true,
                removeAttributeQuotes:          true,
                removeRedundantAttributes:      true,
                useShortDoctype:                true,
                removeEmptyAttributes:          true,
                /* оставляем, поскольку у нас
                 * в элемент fm генерируеться
                 * таблица файлов
                 */
                removeEmptyElements:            false,
                removeOptionalTags:             true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true
            };

            return htmlMinifier.minify(pData,lOptions);
        };
        /*********************************/
        var final_code=html_minify(pData);

        var minFileName=pFileName.replace('.html','.min.html');

         /* adding Min folder to file path */
         minFileName = MinFolder + minFileName;
         /* записываем сжатый html файл*/
        fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

     /* moving thru all elements of html files array */
    for(var i=0;pHTMLFiles_a[i];i++){
        console.log('reading file ' + pHTMLFiles_a[i]+'...');
        fs.readFile(pHTMLFiles_a[i],fileReaded(pHTMLFiles_a[i],dataReaded_f));
    }

    return true;
};

/* функция переводит картинки в base64 и записывает в css-файл*/
function base64_images(pFileContent_s){
    'use strict';
     var b64img;
     try{
        b64img = require('css-b64-images');
    }catch(error){
        console.log('can\'n load clean-css \n'                 +
            'to use images to base64 convertation you need to install css-base64-images \n'  +
                'npm install -g css-b64-images\n'                               +
                'https://github.com/Filirom1/css-base64-images');
        return false;
    }
    b64img.fromString(pFileContent_s, '.','', function(err, css){
        console.log('images converted to base64 and saved in css file');
        fs.writeFile(MinFolder + 'all.min.css', css, fileWrited(MinFolder + 'all.min.css'));
    });
}

/* Функция создаёт асинхроную версию
 * для чтения файла
 * @pFileName - имя считываемого файла
 */
function fileReaded(pFileName,pCompressFunc){
    "use strict";
    return function(pError,pData){
        /* функция в которую мы попадаем,
         * если данные считались
         *
         * если ошибка - показываем её
         * иначе если переданная функция -
         * функция запускаем её
         */
        if(!pError)
            if (pCompressFunc && typeof pCompressFunc==="function")
                    pCompressFunc(pFileName,pData.toString());
        else console.log(pError);
    };
}

/*
 * Функция вызываеться после записи файла
 * и выводит ошибку или сообщает,
 * что файл успешно записан
 */
function fileWrited(pFileName){
    "use strict";
    return function(error){
        console.log(error?error:('file '+pFileName+' writed...'));
    };
}

/*
 * Function reads hach table of files
 * checks is file changed or not
 * and return result.
 * @pFileName - name of file
 * @pFileData - data of file
 * result: boolean
 */
function isFileChanged(pFileName, pFileData){
        var lReadedHash;

        if(!Hashes)
            try {
                /* try to read file with hashes */
                Hashes = require('hashes.json');
                for(var lFileName in Hashes)
                    /* if founded row with file name
                     * saving hash
                     */
                    if (lFileName === pFileName) {
                        lReadedHash = Hashes[pFileName];
                        break;
                    }
            }catch(pError) {
                Hashes={};
            }
        /* create md5 hash of file data */
        var lFileHash = crypto.createHash('sha1');
        lFileHash.update(pFileData);
        lFileHash = lFileHash.digest('hex');

        console.log(pFileName + ': ' + lFileHash);

        if(lReadedHash &&
            lReadedHash === lFileHash){
                /* file did not change */
                return false;
        }else{
            Hashes[pFileName] = lFileHash;
            console.log(Hashes);

            return true;
        }
}<|endoftext|>