<commit_before>$(function() {

  // array of elements; prevent repetitive DOM requestsa
  var e = {
    document: $(document),
    window: $(window),
    html: $("html"), body: $("body"),
    footer: $("footer"),
    header: $("header"),
    shoutButton: $(".shoutText > button"),
    shoutBox: $(".shoutBox"),
    mainNav: $("#mainNav"),
    dropdown: $(".dropdown"),
    dropdownLinks: $(".dropdownLinks"),
    facebookShareButton: $("#facebookShareButton"),
    twitterShareButton: $("#twitterShareButton"),
    googlePlusShareButton: $("#googlePlusShareButton"),
    revealButton: $(".revealButton"),
    categoryListItem: $(".categoryListItem"),
    titleImage: $(".titleImage"),
    sideNav: $("#sideNav"),
    sideNavSearch: $("#sideNavSearch"),
    searchButton: $(".searchButton"),
    menuButtons: $(".closeMenuButton, .openMenuButton"),
    searchTerm: $("#searchTerm"),
    searchResults: $("#searchResults"),
    searchSearch: $("#searchSearch"),
    searchIcon: $(".searchIcon"),
    mainSearchIcon: $(".mainSearchIcon"),
    mainSearch: $("#mainSearch"),
    upButton: $("#upButton"),
    downButton: $("#downButton")
  };

  // accessory functions
  var getPxValue = function(input) {
    return parseInt(input.substring(0, input.length-2));
  };
  var search = function(input) {
    if(input.trim() != "")
      window.location.href = "search/?" + encodeURIComponent(input);
  };

  // reposition the footer
  var docWidth, docHeight;
  var resizeFunction = function() {
    var extraPadding = e.shoutButton.length > 0 ? 0 : 50;
    e.body.css({ paddingTop: Math.floor(e.header.height() + e.mainNav.height()) });
    docWidth = e.document.width() > e.window.width() ? e.document.width() : e.window.width();
    docHeight = e.document.height() > e.window.height() ? e.document.height() : e.window.height();
    // resize triangular part if applicable
    if(e.titleImage.length == 1) {
      if(!e.titleImage.prev().is("h1:not(#title)")) {
        $("h1:not(#title)").first().after(e.titleImage);
      }
      if(e.hasOwnProperty("triangle")) {
        e.triangle.css({ borderWidth: "1.6em " + (e.window.width()/2+2) + "px" });
      } else {
        e.titleImage.append($("

"));
        e.triangle = $(".triangle").css({ borderWidth: "1.6em " + (e.window.width()/2+2) + "px" });
      }
    }
    // resize size of #sideNav links for mobile
    e.sideNav.children().css({ height: Math.ceil(e.window.height()/8), lineHeight: Math.ceil(e.window.height()/8) + "px" });
    // make main search bar full width
    e.mainSearch.innerWidth(e.window.width() - e.mainSearchIcon.innerWidth());
    // resize search icon
    e.mainSearchIcon.css({ height: e.dropdown.innerHeight() || e.mainSearch.innerHeight() });

    // get positions of shoutBox (for scrolling effects)
    if(e.shoutBox.length > 0) {
      topPositions = [];
      e.shoutBox.each(function() {
        topPositions.push($(this).position().top);
      });
    }

    // set height of shoutBoxes for mobile
    if(e.window.height() <= 750 && e.shoutBox.length > 0 && e.shoutBox.height() < e.window.height())
      e.shoutBox.height(e.window.height());

  };
  // dropdown code
  e.dropdown.each(function() {
    var thisElement = $(this), dropdown = $("#dropdown" + thisElement.data("dropdown"));
    thisElement.hover(function() {
      e.dropdown.removeClass("linger");
      e.dropdownLinks.addClass("hidden");
      thisElement.addClass("linger");
      dropdown.css({ top: e.mainNav.height(), left: thisElement.position().left }).removeClass("hidden");
    }, function() {
      e.document.mousemove(function(event) {
        var x = event.pageX, y = event.pageY-(e.mainNav.hasClass("fixed") ? e.body.scrollTop() : 0), minX = dropdown.position().left, minY = e.mainNav.position().top, maxX = minX + dropdown.width(), maxY = minY + e.mainNav.height() + dropdown.height();
        if(x < minX || x > maxX || y < minY || y > maxY) {
          dropdown.addClass("hidden");
          e.document.off("mousemove");
          thisElement.removeClass("linger");
        }
      });
    });
  });
  // popups to share
  e.body.on("click", ".shareButtonLink", function() {
    window.open($(this).attr("href"), "", "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=500,width=500");
    return false;
  });
  e.facebookShareButton.attr({ href: "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(window.location.href) });
  e.twitterShareButton.attr({ href: "https://twitter.com/intent/tweet?text=" + encodeURIComponent("Come visit at Nutmeg Bowl for the best bowling in Fairfield County! " + window.location.href) });
  e.googlePlusShareButton.attr({ href: "https://plus.google.com/share?url=" + encodeURIComponent(window.location.href) });
  // scrolling menu
  e.window.scroll(function() {
    if(e.body.scrollTop() > e.header.height())
      e.mainNav.addClass("fixed");
    else
      e.mainNav.removeClass("fixed");
  });
  // clickable .shoutButton for the homepage
  e.shoutButton.click(function() {
    window.location.href = $(this).data("href");
  });
  // .reveal functionality
  e.revealButton.click(function() {
    $(this).parent().toggleClass("revealed");
    $(this).next().slideToggle();
  });
  // clickable links for .categoryListItem for listing pages
  e.categoryListItem.click(function() {
    window.location.href = $(this).data("href");
  });
  // set footer margin top (0 if homepage)
  if(e.shoutButton.length > 0)
    e.footer.css({ marginTop: 0 });
  // mobile menu open/close
  e.menuButtons.click(function() {
    e.sideNav.slideToggle();
  });
  // search capability
  e.sideNavSearch.keyup(function(event) {
    if(event.which == 13)
      e.searchButton.click();
  });
  e.searchButton.click(function() {
    search(e.sideNavSearch.val());
  });
  // search function
  if(e.searchTerm.length == 1) {
    var urlParameter = /\?(.+)$/.exec(window.location.href);
    if(urlParameter) {
      var query = decodeURIComponent(urlParameter[1]).toLowerCase() || false;
      var searchResultsString = "";
      $.getJSON("res/search.json", function(data) {
        for(page in data) {
          if(data[page].title.toLowerCase() == query)
            window.location.href = data[page].url;
          if(data[page].url.indexOf("index") > 0 || data[page].title == "Search")
            continue;
          var pageString = data[page].string;
          var stringAround = "";
          if(pageString.toLowerCase().indexOf(query) > 0) {
            var regex = new RegExp(query, "ig");
            var match;
            var length = query.length;
            while(match = regex.exec(pageString)) {
              var start = (match.index-25 < 0) ? 0 : match.index-25;
              var end = (match.index+length+25 > pageString.length) ? pageString.length : match.index+length+25;
              stringAround += "
" + pageString.substring(start, match.index) + "" + match[0] + "" + pageString.substring(match.index+length, end);
              stringAround += "
";
            }
            searchResultsString += "

" + data[page].title + "
" + stringAround + "
";
          }
        }
        e.searchTerm.text(query);
        e.searchResults.html(searchResultsString || "
No matches found.
");
      });
    } else {
      e.searchTerm.text(" ");
      e.searchResults.html("
Please enter search terms to perform a search.
");
    }
    e.document.on("click", ".searchPageMatch", function() {
      window.location.href = $(this).data("href");
    });
    e.searchSearch.click(function() {
      $(this).parent().addClass("shadow");
    });
    e.searchSearch.blur(function() {
      $(this).parent().removeClass("shadow");
    });
    e.searchSearch.keyup(function(event) {
      if(event.which == 13)
        e.searchIcon.click();
    });
    e.searchIcon.click(function() {
      search(e.searchSearch.val());
    });
  }
  // desktop search tools
  e.mainSearchIcon.click(function() {
    search(e.mainSearch.val());
    if(e.mainSearch.hasClass("hidden")) {
      e.mainSearch.focus();
      e.mainSearch.removeClass("hidden");
    } else {
      e.mainSearch.blur();
      e.mainSearch.addClass("hidden");
    }
    e.mainSearchIcon.toggleClass("active");
    e.dropdown.toggleClass("hidden");
  });
  e.mainSearch.keyup(function(event) {
    if(event.which == 13 || $(this).val() == "")
      e.mainSearchIcon.click();
  });

  // homepage scrolling effects; only for desktop
  var topPositions = [], currentIndex = -1, lastScrollTop = e.body.scrollTop(), scrollOk = true;
  if(e.shoutBox.length > 0 && e.window.width() > 750) {
    var scrollToIndex = function() {
      if(currentIndex >= 0 && currentIndex < topPositions.length)
        e.body.animate({ scrollTop: (topPositions[currentIndex]+(1080-e.window.height())/2) + "px" }, 500);
      if(currentIndex < 1)
        e.upButton.fadeOut();
      else
        e.upButton.fadeIn();
      if(currentIndex >= topPositions.length-1)
        e.downButton.fadeOut();
      else
        e.downButton.fadeIn();
      scrollOk = false;
      setTimeout(function() {
        scrollOk = true;
      }, 550);
      lastScrollTop = e.body.scrollTop();
    };
    e.window.scroll(function() {
      if(!scrollOk) {
        lastScrollTop = e.body.scrollTop();
        return;
      }
      if(currentIndex >= 0 && currentIndex < topPositions.length) {
        if(e.body.scrollTop() < lastScrollTop)
          currentIndex--;
        else if(e.body.scrollTop() > lastScrollTop)
          currentIndex++;
        else
          return;
      } else {
        if(currentIndex == -1 && e.body.scrollTop()+e.window.height() > topPositions[0] && e.body.scrollTop() > lastScrollTop)
          currentIndex = 0;
        else if(currentIndex >= topPositions.length && e.body.scrollTop() < topPositions[topPositions.length-1] + 1080 && e.body.scrollTop() < lastScrollTop)
          currentIndex = topPositions.length-1;
      }
      scrollToIndex();
    });
    e.upButton.click(function() {
      if(!scrollOk)
        return;
      currentIndex--;
      scrollToIndex();
    });
    e.downButton.click(function() {
      if(!scrollOk)
        return;
      currentIndex++;
      scrollToIndex();
    });
    e.body.keydown(function(event) {
      if(event.which == 40 && e.downButton.css("display") == "block") {
        event.preventDefault();
        e.downButton.click();
      } else if(event.which == 38 && e.upButton.css("display") == "block") {
        event.preventDefault();
        e.upButton.click();
      }
    });
  }

  // resize a little later
  setTimeout(function() {
    e.window.resize(resizeFunction).resize();
    currentIndex = 0;
    scrollToIndex();
  }, 100);
});
<commit_msg>Added scrolling safeguards<commit_after>$(function() {

  // array of elements; prevent repetitive DOM requestsa
  var e = {
    document: $(document),
    window: $(window),
    html: $("html"), body: $("body"),
    footer: $("footer"),
    header: $("header"),
    shoutButton: $(".shoutText > button"),
    shoutBox: $(".shoutBox"),
    mainNav: $("#mainNav"),
    dropdown: $(".dropdown"),
    dropdownLinks: $(".dropdownLinks"),
    facebookShareButton: $("#facebookShareButton"),
    twitterShareButton: $("#twitterShareButton"),
    googlePlusShareButton: $("#googlePlusShareButton"),
    revealButton: $(".revealButton"),
    categoryListItem: $(".categoryListItem"),
    titleImage: $(".titleImage"),
    sideNav: $("#sideNav"),
    sideNavSearch: $("#sideNavSearch"),
    searchButton: $(".searchButton"),
    menuButtons: $(".closeMenuButton, .openMenuButton"),
    searchTerm: $("#searchTerm"),
    searchResults: $("#searchResults"),
    searchSearch: $("#searchSearch"),
    searchIcon: $(".searchIcon"),
    mainSearchIcon: $(".mainSearchIcon"),
    mainSearch: $("#mainSearch"),
    upButton: $("#upButton"),
    downButton: $("#downButton")
  };

  // accessory functions
  var getPxValue = function(input) {
    return parseInt(input.substring(0, input.length-2));
  };
  var search = function(input) {
    if(input.trim() != "")
      window.location.href = "search/?" + encodeURIComponent(input);
  };

  // reposition the footer
  var docWidth, docHeight;
  var resizeFunction = function() {
    var extraPadding = e.shoutButton.length > 0 ? 0 : 50;
    e.body.css({ paddingTop: Math.floor(e.header.height() + e.mainNav.height()) });
    docWidth = e.document.width() > e.window.width() ? e.document.width() : e.window.width();
    docHeight = e.document.height() > e.window.height() ? e.document.height() : e.window.height();
    // resize triangular part if applicable
    if(e.titleImage.length == 1) {
      if(!e.titleImage.prev().is("h1:not(#title)")) {
        $("h1:not(#title)").first().after(e.titleImage);
      }
      if(e.hasOwnProperty("triangle")) {
        e.triangle.css({ borderWidth: "1.6em " + (e.window.width()/2+2) + "px" });
      } else {
        e.titleImage.append($("

"));
        e.triangle = $(".triangle").css({ borderWidth: "1.6em " + (e.window.width()/2+2) + "px" });
      }
    }
    // resize size of #sideNav links for mobile
    e.sideNav.children().css({ height: Math.ceil(e.window.height()/8), lineHeight: Math.ceil(e.window.height()/8) + "px" });
    // make main search bar full width
    e.mainSearch.innerWidth(e.window.width() - e.mainSearchIcon.innerWidth());
    // resize search icon
    e.mainSearchIcon.css({ height: e.dropdown.innerHeight() || e.mainSearch.innerHeight() });

    // get positions of shoutBox (for scrolling effects)
    if(e.shoutBox.length > 0) {
      topPositions = [];
      e.shoutBox.each(function() {
        topPositions.push($(this).position().top);
      });
    }

    // set height of shoutBoxes for mobile
    if(e.window.height() <= 750 && e.shoutBox.length > 0 && e.shoutBox.height() < e.window.height())
      e.shoutBox.height(e.window.height());

  };
  // dropdown code
  e.dropdown.each(function() {
    var thisElement = $(this), dropdown = $("#dropdown" + thisElement.data("dropdown"));
    thisElement.hover(function() {
      e.dropdown.removeClass("linger");
      e.dropdownLinks.addClass("hidden");
      thisElement.addClass("linger");
      dropdown.css({ top: e.mainNav.height(), left: thisElement.position().left }).removeClass("hidden");
    }, function() {
      e.document.mousemove(function(event) {
        var x = event.pageX, y = event.pageY-(e.mainNav.hasClass("fixed") ? e.body.scrollTop() : 0), minX = dropdown.position().left, minY = e.mainNav.position().top, maxX = minX + dropdown.width(), maxY = minY + e.mainNav.height() + dropdown.height();
        if(x < minX || x > maxX || y < minY || y > maxY) {
          dropdown.addClass("hidden");
          e.document.off("mousemove");
          thisElement.removeClass("linger");
        }
      });
    });
  });
  // popups to share
  e.body.on("click", ".shareButtonLink", function() {
    window.open($(this).attr("href"), "", "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=500,width=500");
    return false;
  });
  e.facebookShareButton.attr({ href: "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(window.location.href) });
  e.twitterShareButton.attr({ href: "https://twitter.com/intent/tweet?text=" + encodeURIComponent("Come visit at Nutmeg Bowl for the best bowling in Fairfield County! " + window.location.href) });
  e.googlePlusShareButton.attr({ href: "https://plus.google.com/share?url=" + encodeURIComponent(window.location.href) });
  // scrolling menu
  e.window.scroll(function() {
    if(e.body.scrollTop() > e.header.height())
      e.mainNav.addClass("fixed");
    else
      e.mainNav.removeClass("fixed");
  });
  // clickable .shoutButton for the homepage
  e.shoutButton.click(function() {
    window.location.href = $(this).data("href");
  });
  // .reveal functionality
  e.revealButton.click(function() {
    $(this).parent().toggleClass("revealed");
    $(this).next().slideToggle();
  });
  // clickable links for .categoryListItem for listing pages
  e.categoryListItem.click(function() {
    window.location.href = $(this).data("href");
  });
  // set footer margin top (0 if homepage)
  if(e.shoutButton.length > 0)
    e.footer.css({ marginTop: 0 });
  // mobile menu open/close
  e.menuButtons.click(function() {
    e.sideNav.slideToggle();
  });
  // search capability
  e.sideNavSearch.keyup(function(event) {
    if(event.which == 13)
      e.searchButton.click();
  });
  e.searchButton.click(function() {
    search(e.sideNavSearch.val());
  });
  // search function
  if(e.searchTerm.length == 1) {
    var urlParameter = /\?(.+)$/.exec(window.location.href);
    if(urlParameter) {
      var query = decodeURIComponent(urlParameter[1]).toLowerCase() || false;
      var searchResultsString = "";
      $.getJSON("res/search.json", function(data) {
        for(page in data) {
          if(data[page].title.toLowerCase() == query)
            window.location.href = data[page].url;
          if(data[page].url.indexOf("index") > 0 || data[page].title == "Search")
            continue;
          var pageString = data[page].string;
          var stringAround = "";
          if(pageString.toLowerCase().indexOf(query) > 0) {
            var regex = new RegExp(query, "ig");
            var match;
            var length = query.length;
            while(match = regex.exec(pageString)) {
              var start = (match.index-25 < 0) ? 0 : match.index-25;
              var end = (match.index+length+25 > pageString.length) ? pageString.length : match.index+length+25;
              stringAround += "
" + pageString.substring(start, match.index) + "" + match[0] + "" + pageString.substring(match.index+length, end);
              stringAround += "
";
            }
            searchResultsString += "

" + data[page].title + "
" + stringAround + "
";
          }
        }
        e.searchTerm.text(query);
        e.searchResults.html(searchResultsString || "
No matches found.
");
      });
    } else {
      e.searchTerm.text(" ");
      e.searchResults.html("
Please enter search terms to perform a search.
");
    }
    e.document.on("click", ".searchPageMatch", function() {
      window.location.href = $(this).data("href");
    });
    e.searchSearch.click(function() {
      $(this).parent().addClass("shadow");
    });
    e.searchSearch.blur(function() {
      $(this).parent().removeClass("shadow");
    });
    e.searchSearch.keyup(function(event) {
      if(event.which == 13)
        e.searchIcon.click();
    });
    e.searchIcon.click(function() {
      search(e.searchSearch.val());
    });
  }
  // desktop search tools
  e.mainSearchIcon.click(function() {
    search(e.mainSearch.val());
    if(e.mainSearch.hasClass("hidden")) {
      e.mainSearch.focus();
      e.mainSearch.removeClass("hidden");
    } else {
      e.mainSearch.blur();
      e.mainSearch.addClass("hidden");
    }
    e.mainSearchIcon.toggleClass("active");
    e.dropdown.toggleClass("hidden");
  });
  e.mainSearch.keyup(function(event) {
    if(event.which == 13 || $(this).val() == "")
      e.mainSearchIcon.click();
  });

  // homepage scrolling effects; only for desktop
  var topPositions = [], currentIndex = -1, lastScrollTop = e.body.scrollTop(), scrollOk = true;
  if(e.shoutBox.length > 0 && e.window.width() > 750) {
    var scrollToIndex = function() {
      if(currentIndex >= 0 && currentIndex < topPositions.length)
        e.body.animate({ scrollTop: (topPositions[currentIndex]+(1080-e.window.height())/2) + "px" }, 500);
      if(currentIndex < 1)
        e.upButton.fadeOut();
      else
        e.upButton.fadeIn();
      if(currentIndex >= topPositions.length-1)
        e.downButton.fadeOut();
      else
        e.downButton.fadeIn();
      scrollOk = false;
      setTimeout(function() {
        scrollOk = true;
      }, 700);
      lastScrollTop = e.body.scrollTop();
    };
    var winScroll = function() {
      if(!scrollOk) {
        lastScrollTop = e.body.scrollTop();
        return;
      }
      if(currentIndex >= 0 && currentIndex < topPositions.length) {
        if(e.body.scrollTop() < lastScrollTop)
          currentIndex--;
        else if(e.body.scrollTop() > lastScrollTop)
          currentIndex++;
        else
          return;
      } else {
        if(currentIndex == -1 && e.body.scrollTop()+e.window.height() > topPositions[0] && e.body.scrollTop() > lastScrollTop)
          currentIndex = 0;
        else if(currentIndex >= topPositions.length && e.body.scrollTop() < topPositions[topPositions.length-1] + 1080 && e.body.scrollTop() < lastScrollTop)
          currentIndex = topPositions.length-1;
      }
      scrollToIndex();
    };
    e.upButton.click(function() {
      if(!scrollOk)
        return;
      currentIndex--;
      scrollToIndex();
    });
    e.downButton.click(function() {
      if(!scrollOk)
        return;
      currentIndex++;
      scrollToIndex();
    });
    e.body.keydown(function(event) {
      if(event.which == 40 && e.downButton.css("display") == "block") {
        event.preventDefault();
        e.downButton.click();
      } else if(event.which == 38 && e.upButton.css("display") == "block") {
        event.preventDefault();
        e.upButton.click();
      }
    });
    setTimeout(function() {
      currentIndex = 0;
      scrollToIndex();
    }, 150);
    setTimeout(function() {
      e.window.scroll(winScroll);
    }, 700);
  }

  // resize a little later
  setTimeout(function() {
    e.window.resize(resizeFunction).resize();
  }, 100);
});
<|endoftext|>


<commit_before>$(document).ready(function () {
    //添加提示框
    $('#add-card-modal').modal({
        backdrop: 'static',
        show: false
    });

    //新建
    $(".add_card").click(function () {
        $("#add-card-modal").modal('show');
        $('#giftBook').change(function () {
            $('.gift_show_price').html(13)
        })
        $("#giftcard-order-btn").die().live('click', function () {
            $(".alert-label-error").text('');
            var flag = true;
            var start_num = $('#start_num');
            var end_num = $('#end_num');
            var isNum = /^[0-9]*$/;

            if (start_num.val() == '' || !isNum.test(start_num.val())) {
                flag = flag & false;
                start_num.parents('tr').find('.alert-label-error').html('请填写正确的开始号码');
            }

            if (end_num.val() == '' || !isNum.test(end_num.val())) {
                flag = flag & false;
                end_num.parents('tr').find('.alert-label-error').html('请填写正确的结束号码');
            }

            if (flag) {
                var gift_json = {};
                gift_json.start_num = $.trim(start_num.val());
                gift_json.end_num = $.trim(end_num.val());
                gift_json.num = Number(gift_json.end_num) - Number(gift_json.start_num) + 1;
                if(gift_json.num<=0){
                    end_num.parents('tr').find('.alert-label-error').html('结束号码段不能比开始的小！');
                    return ;
                }
                giftArr.push(gift_json);
                rendGiftList();
                $("#add-card-modal").modal('hide');
            }
        });
    })

    function inArray(arr, id) {
        var datakey = -1;
        $(arr).each(function (key, val) {
            if (val.gift_book_id == id) {
                datakey = key;
            }
        })
        return datakey;
    }

    function rendGiftList() {
        var tdStr = '';
        $(giftArr).each(function (key, val) {
            tdStr = '
';
            tdStr += '' + val.start_num + '	'
                   + '' + val.end_num + '	'
                   + '' + val.num + '	'
                   + '删除	'
            tdStr += '
'
        })
        $('#add_gift_list_tb tbody').html(tdStr);

        $('.del_gift_list').off('click').click(function () {
            var tr = $(this).parents('tr');
            var id = tr.attr('id');
            var inkey = inArray(giftArr, id);
            if (inkey != -1) {
                giftArr.splice(inkey, 1);
            }
            rendGiftList();
        })
    }

    $('#a_trade_date').datepicker({
        minDate: new Date(),
        dateFormat: "yy-mm-dd"
    });
    $('#a_expiration_date').datepicker({
        minDate: new Date(),
        dateFormat: "yy-mm-dd"
    });

    $(".chzn_a").chosen({
        allow_single_deselect: true
    });
    //成功提示框设置
    $('#alert-success').modal({
        backdrop: false,
        show: false
    });

    //客户选择监听
    $("#a_customer").live('change',function(e){
       e.preventDefault();
       for(i in customerArr){
           if(customerArr[i].id==$(this).val()){
                $("#a_contact_person").val(customerArr[i].name);
                $("#a_telephone").val(customerArr[i].phone);
                $("#a_address").val(customerArr[i].address);
            }
       }
    });

    //客户选择监听
    $("#giftBook").live('change',function(e){
       e.preventDefault();
       for(i in giftBook){
           if(giftBook[i].id==$(this).val()){
                $("#price").val(giftBook[i].sale_price);
            }
       }
    });

    $("#giftcard-order-ok").die().live('click', function () {
        var flag = true;
        var sales = $("#a_sales").val();
        var cancel_date = $('#a_cancel_date').val();
        var customer = $('#a_customer').val();
        var contact_person = $('#a_contact_person').val();
        var enduser = $('#a_enduser').val();
        var telephone = $('#a_telephone').val();
        var address = $('#a_address').val();
        var remark = $.trim($("textarea[name=a_remark]").val());
        var is_mobile = /^(?:13\d|15\d|18\d)\d{5}(\d{3}|\*{3})$/;
        var is_phone = /^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;

        if (sales == '' || sales == undefined) {
            flag = flag & false;
            alertError("#alert-error", '销售员不能为空！');
            return;
        }
        if (cancel_date == '' || cancel_date == undefined) {
            flag = flag & false;
            alertError("#alert-error", '退卡日期不能为空！');
            return;
        }
        if (customer == '' || customer == undefined) {
            flag = flag & false;
            alertError("#alert-error", '请选择客户！');
            return;
        }
        if (contact_person == '' || contact_person == undefined) {
            flag = flag & false;
            alertError("#alert-error", '联系人不能为空！');
            return;
        }

        if (telephone == '' || (!is_phone.test(telephone) && !is_mobile.test(telephone))) {
            flag = flag & false;
            alertError("#alert-error", '请输入正确的电话！');
            return;
        }

        if (address == '' || address == undefined) {
            flag = flag & false;
            alertError("#alert-error", '地址不能为空！');
            return;
        }
        if (remark == '' || remark == undefined) {
            flag = flag & false;
            alertError("#alert-error", '备注不能为空！');
            return;
        }

        if (!giftArr.length) {
            flag = flag & false;
            alertError("#alert-error", '请添加退卡段号！');
            return;
        }

        if (flag) {
            $.post('/giftcard_manage/do_cancel_giftcard',
                {
                    sales: sales,
                    cancel_date: cancel_date,
                    customer: customer,
                    contact_person: contact_person,
                    enduser:enduser,
                    telephone: telephone,
                    address: address,
                    remark: remark,
                    code_arr: giftArr
                }, function (ret) {
                    var d = $.parseJSON(ret);
                    if (d.errCode == 0) {
                        alertSuccess("#alert-success", '/giftcard_manage/cancel_giftcard');
                    } else {
                        alertError("#alert-error", d.msg);
                    }
            });
        }

    });
});

<commit_msg>fix bug<commit_after>$(document).ready(function () {
    //添加提示框
    $('#add-card-modal').modal({
        backdrop: 'static',
        show: false
    });

    //新建
    $(".add_card").click(function () {
        $("#add-card-modal").modal('show');
        $('#giftBook').change(function () {
            $('.gift_show_price').html(13)
        })
        $("#giftcard-order-btn").die().live('click', function () {
            $(".alert-label-error").text('');
            var flag = true;
            var start_num = $('#start_num');
            var end_num = $('#end_num');
            var isNum = /^[0-9]*$/;

            if (start_num.val() == '' || !isNum.test(start_num.val())) {
                flag = flag & false;
                start_num.parents('tr').find('.alert-label-error').html('请填写正确的开始号码');
            }

            if (end_num.val() == '' || !isNum.test(end_num.val())) {
                flag = flag & false;
                end_num.parents('tr').find('.alert-label-error').html('请填写正确的结束号码');
            }

            if (flag) {
                var gift_json = {};
                gift_json.start_num = $.trim(start_num.val());
                gift_json.end_num = $.trim(end_num.val());
                gift_json.num = Number(gift_json.end_num) - Number(gift_json.start_num) + 1;
                if(gift_json.num<=0){
                    end_num.parents('tr').find('.alert-label-error').html('结束号码段不能比开始的小！');
                    return ;
                }
                giftArr.push(gift_json);
                rendGiftList();
                $("#add-card-modal").modal('hide');
            }
        });
    })

    function inArray(arr, id) {
        var datakey = -1;
        $(arr).each(function (key, val) {
            if (val.gift_book_id == id) {
                datakey = key;
            }
        })
        return datakey;
    }

    function rendGiftList() {
        var tdStr = '';
        $(giftArr).each(function (key, val) {
            tdStr = '
';
            tdStr += '' + val.start_num + '	'
                   + '' + val.end_num + '	'
                   + '' + val.num + '	'
                   + '删除	'
            tdStr += '
'
        })
        $('#add_gift_list_tb tbody').html(tdStr);

        $('.del_gift_list').off('click').click(function () {
            var tr = $(this).parents('tr');
            var id = tr.attr('id');
            var inkey = inArray(giftArr, id);
            if (inkey != -1) {
                giftArr.splice(inkey, 1);
            }
            rendGiftList();
        })
    }

    $('#a_trade_date').datepicker({
        minDate: new Date(),
        dateFormat: "yy-mm-dd"
    });
    $('#a_expiration_date').datepicker({
        minDate: new Date(),
        dateFormat: "yy-mm-dd"
    });

    $(".chzn_a").chosen({
        allow_single_deselect: true
    });
    //成功提示框设置
    $('#alert-success').modal({
        backdrop: false,
        show: false
    });

    //客户选择监听
    $("#a_customer").live('change',function(e){
       e.preventDefault();
       for(i in customerArr){
           if(customerArr[i].id==$(this).val()){
                $("#a_contact_person").val(customerArr[i].name);
                $("#a_telephone").val(customerArr[i].phone);
                $("#a_address").val(customerArr[i].address);
            }
       }
    });

    //客户选择监听
    $("#giftBook").live('change',function(e){
       e.preventDefault();
       for(i in giftBook){
           if(giftBook[i].id==$(this).val()){
                $("#price").val(giftBook[i].sale_price);
            }
       }
    });

    $("#giftcard-order-ok").die().live('click', function () {
        var flag = true;
        var sales = $("#a_sales").val();
        var cancel_date = $('#a_cancel_date').val();
        var customer = $('#a_customer').val();
        var contact_person = $('#a_contact_person').val();
        var enduser = $('#a_enduser').val();
        var telephone = $('#a_telephone').val();
        var address = $('#a_address').val();
        var is_sales = $('#a_status').val();
        var remark = $.trim($("textarea[name=a_remark]").val());
        var is_mobile = /^(?:13\d|15\d|18\d)\d{5}(\d{3}|\*{3})$/;
        var is_phone = /^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;

        if (sales == '' || sales == undefined) {
            flag = flag & false;
            alertError("#alert-error", '销售员不能为空！');
            return;
        }
        if (cancel_date == '' || cancel_date == undefined) {
            flag = flag & false;
            alertError("#alert-error", '退卡日期不能为空！');
            return;
        }
        if (customer == '' || customer == undefined) {
            flag = flag & false;
            alertError("#alert-error", '请选择客户！');
            return;
        }
        if (contact_person == '' || contact_person == undefined) {
            flag = flag & false;
            alertError("#alert-error", '联系人不能为空！');
            return;
        }

        if (telephone == '' || (!is_phone.test(telephone) && !is_mobile.test(telephone))) {
            flag = flag & false;
            alertError("#alert-error", '请输入正确的电话！');
            return;
        }

        if (address == '' || address == undefined) {
            flag = flag & false;
            alertError("#alert-error", '地址不能为空！');
            return;
        }
        if (remark == '' || remark == undefined) {
            flag = flag & false;
            alertError("#alert-error", '备注不能为空！');
            return;
        }

        if (!giftArr.length) {
            flag = flag & false;
            alertError("#alert-error", '请添加退卡段号！');
            return;
        }

        if (flag) {
            $.post('/giftcard_manage/do_cancel_giftcard',
                {
                    sales: sales,
                    cancel_date: cancel_date,
                    customer: customer,
                    contact_person: contact_person,
                    enduser:enduser,
                    telephone: telephone,
                    address: address,
                    remark: remark,
                    is_sales:is_sales,
                    code_arr: giftArr
                }, function (ret) {
                    var d = $.parseJSON(ret);
                    if (d.errCode == 0) {
                        alertSuccess("#alert-success", '/giftcard_manage/cancel_giftcard');
                    } else {
                        alertError("#alert-error", d.msg);
                    }
            });
        }

    });
});

<|endoftext|>


<commit_before>var Miner = {
    sourceId: null,
    execute: function (creep) {
        var sources = creep.room.find(FIND_SOURCES);

        for (var id in sources) {
            var source = sources[id];

            var harvest = creep.harvest(source);

            switch (harvest) {
                case ERR_NOT_IN_RANGE: creep.moveTo(source); creep.say('Moving'); return;
                case OK: return;
                default: break;
            }
        }
    }
};

module.exports = Miner;
<commit_msg>feat: force miners to choose single source<commit_after>var Utility = require('utility');

var Miner = {
    sourceId: null,
    execute: function (creep) {
        var sources = creep.room.find(FIND_SOURCES);

        if (!creep.memory.harvestSourceId) {
            var miners = Utility.getCreepsByRole('miner');
            var takenIds = miners.map(m => m.memory.harvestSourceId);

            var sources = creep.room.find(FIND_SOURCES, {filter: s => {
                return takenIds.map(id => s.id != id).reduce((a,b) => a&b);
            }});

            if (sources.length) {
                creep.memory.harvestSourceId = sources[0].id;
            }
        }

        var source = Game.getObjectById(creep.memory.harvestSourceId);
        if (source) {
            var harvest = creep.harvest(source);

            switch (harvest) {
                case ERR_NOT_IN_RANGE: creep.moveTo(source); creep.say('Moving'); break;
            }
        }

        // for (var id in sources) {
        //     var source = sources[id];

        //     var harvest = creep.harvest(source);

        //     switch (harvest) {
        //         case ERR_NOT_IN_RANGE: creep.moveTo(source); creep.say('Moving'); return;
        //         case OK: return;
        //         default: break;
        //     }
        // }
    }
};

module.exports = Miner;
<|endoftext|>


<commit_before>var teams = {};
var matches = {};

var uploadStack;

var showID = "ID0";

$(document).ready(function(){
    //showID = "ID0";
    //show(showID);

    //document.getElementsByClassName('addTeam')[0].style.display = "block";
    //document.getElementById("ID0").style.display = "block";

    //teams = {};
    //matches = {};

    $(document).resize(function(){

    });
});

function show(id){
  document.getElementById(showID).style.display = "none";
  document.getElementById(id).style.display = "block";
  showID = id;
}

function windowclose(){

}

function addMatch(){

    var len = matches.length;

    if(len == undefined){
      len = -1;
    }

    matches[len+1] = "M" + (len+1);

    var newMatch = document.createElement("div");

    newMatch.innerHTML = document.getElementById("emptyMatch").innerHTML;
    newMatch.id = "M"+(len+1);

    document.getElementById("container").appendChild(newMatch);

    show("M"+(len+1));

}

function addTeam(){

    var len = teams.length;

    if(len == undefined){
      len = -1;
    }

    teams[len+1] = "T" + (len+1);

    var newTeam = document.createElement("div");

    newTeam.innerHTML = document.getElementById("emptyTeam").innerHTML;
    newTeam.id = "T"+(len+1);

    document.getElementById("container").appendChild(newTeam);

    show("T"+(len+1));
}

function setMatch(){

}

function setTeam(){

}

function dissapear(){
  active.style.display = "none";
}

// addMatch;
// addTeam;
// optionsTitle;
<commit_msg>Fixed second bug, duplicating team and match divs when clicking on the same create button multiple times<commit_after>var teams = [];
var matches = [];

var uploadStack;

var showID = "ID0";

$(document).ready(function(){
    //showID = "ID0";
    //show(showID);

    //document.getElementsByClassName('addTeam')[0].style.display = "block";
    //document.getElementById("ID0").style.display = "block";

    //teams = {};
    //matches = {};

    $(document).resize(function(){

    });
});

function show(id){
  document.getElementById(showID).style.display = "none";
  document.getElementById(id).style.display = "block";
  showID = id;
}

function windowclose(){

}

function addMatch(){
    document.getElementById(showID).style.display = "none";

    var len = matches.length;

    matches[len] = "M" + len;

    var newMatch = document.createElement("div");

    newMatch.innerHTML = document.getElementById("emptyMatch").innerHTML;
    newMatch.id = "M"+len;

    document.getElementById("container").appendChild(newMatch);

    showID = "M"+ len;
}

function addTeam(){
    document.getElementById(showID).style.display = "none";

    var len = teams.length;

    teams[len] = "T" + len;

    var newTeam = document.createElement("div");

    newTeam.innerHTML = document.getElementById("emptyTeam").innerHTML;
    newTeam.id = "T"+len;

    document.getElementById("container").appendChild(newTeam);

    showID = "T"+len;
}

function setMatch(){

}

function setTeam(){

}

function dissapear(){
  active.style.display = "none";
}

// addMatch;
// addTeam;
// optionsTitle;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Agoo.com.co <http://www.agoo.com.co>.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree or translated in the assets folder.
 */

/**
 * Module dependencies
 */
var logger = require('../config/logger').logger;
var moment = require('moment');

/**
 * setupRouter
 *
 * @description Configure all routes on express router
 *
 * @param {express.Router}      router      The varaible router used by the server
 */
function SetupRouter (router){

    // logger for all request will first hits this middleware
    router.use(function (req, res, next) {
        var now = moment(new Date());

        var date = now.format("DD-MM-YYYY HH:mm");
        logger.info('%s %s %s', req.method, req.url, date);
        next();
    });

    /**
     *  Declare all routes
     */
    var adminRoutes         = require('./admins');
    var authRoutes          = require('./auth');
    var cityRoutes          = require('./cities');
    var clientRoutes        = require('./clients');
    var contentTypeRoutes   = require('./contentTypes');
    var countryRoutes       = require('./countries');
    var lessonRoutes        = require('./lessons');
    var courseRoutes        = require('./courses');
    var currencyRoutes      = require('./currencies');
    var oauth2Routes        = require('./oauth2');
    var permissionRoutes    = require('./permissions');
    var programRoutes       = require('./programs');
    var roleRoutes          = require('./roles');
    var stateRoutes         = require('./states');
    var userRoutes          = require('./users');

    /**
     *  Document:  USERS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /admin
    router.route('/admin')
        .get(authRoutes.isAdminAuthenticated, adminRoutes.getAdmin)
        .post(adminRoutes.postAdmin);
    //.post(authRoutes.isAuthenticated, adminRoutes.postAdmin);

    // ENDPOINT: /admin/:id
    // ENDPOINT: /admin/count
    // ENDPOINT: /admin/count?initialDate=yyyy-mm-dd&endDate=yyyy-mm-dd
    router.route('/admin/:id')
        .get(authRoutes.isAdminAuthenticated, adminRoutes.getUserById)
        .put(authRoutes.isAdminAuthenticated, adminRoutes.putUser)
        .patch(authRoutes.isAdminAuthenticated, adminRoutes.patchUser)
        .delete(authRoutes.isAdminAuthenticated, adminRoutes.deleteUser);

    // ENDPOINT: /admin/login
    router.route('/admin/login')
        .get(authRoutes.isAdminLoginAuthenticated, adminRoutes.getLogin);

    // ENDPOINT: /admin/password/reset
    router.route('/admin/password/reset')
        .post(authRoutes.isAdminAuthenticated, adminRoutes.postPasswordReset);

    // ENDPOINT: /admin/password/reset/:code
    router.route('/admin/password/reset/:code')
        .patch(authRoutes.isAdminAuthenticated, adminRoutes.PatchPasswordReset);

    /**
     * ====================================================================
     */

    /**
     *  Document:  CITIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /cities
    router.route('/cities')
        .get(authRoutes.isAuthenticated, cityRoutes.getCities)
        .post(authRoutes.isAuthenticated, cityRoutes.postCity);

    // ENDPOINT: /cities/:id
    router.route('/cities/:id')
        .get(authRoutes.isAuthenticated, cityRoutes.getCityById)
        .put(authRoutes.isAuthenticated, cityRoutes.putCity)
        .patch(authRoutes.isAuthenticated, cityRoutes.patchCity)
        .delete(authRoutes.isAuthenticated, cityRoutes.deleteCity);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CLIENTS.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /clients
    router.route('/clients')
        .get(authRoutes.isAuthenticated, clientRoutes.getClientByIdClient)
        .post(authRoutes.isAuthenticated, clientRoutes.postClient);

    // ENDPOINT: /clients/:id
    router.route('/clients/:id')
        .delete(authRoutes.isAuthenticated, clientRoutes.deleteClient);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CONTENTTYPES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /types/content
    router.route('/types/content')
        .get(authRoutes.isAuthenticated, contentTypeRoutes.getContentTypes)
        .post(authRoutes.isAuthenticated, contentTypeRoutes.postContentType);

    // ENDPOINT: /types/content/:id
    router.route('/types/content/:id')
        .get(authRoutes.isAuthenticated, contentTypeRoutes.getContentTypeById)
        .put(authRoutes.isAuthenticated, contentTypeRoutes.putContentType)
        .patch(authRoutes.isAuthenticated, contentTypeRoutes.patchContentType)
        .delete(authRoutes.isAuthenticated, contentTypeRoutes.deleteContentType);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COUNTRIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /countries
    router.route('/countries')
        .get(authRoutes.isAuthenticated, countryRoutes.getCountries)
        .post(authRoutes.isAuthenticated, countryRoutes.postCountry);

    // ENDPOINT: /countries/:id
    router.route('/countries/:id')
        .get(authRoutes.isAuthenticated, countryRoutes.getCountryById)
        .put(authRoutes.isAuthenticated, countryRoutes.putCountry)
        .patch(authRoutes.isAuthenticated, countryRoutes.patchCountry)
        .delete(authRoutes.isAuthenticated, countryRoutes.deleteCountry);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COURSELEVELS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /lessons
    router.route('/lessons')
        .get(authRoutes.isAuthenticated, lessonRoutes.getCourseLessons)
        .post(authRoutes.isAuthenticated, lessonRoutes.postCourseLesson);

    // ENDPOINT: /lessons/:id
    router.route('/lessons/:id')
        .get(authRoutes.isAuthenticated, lessonRoutes.getCourseLessonById)
        .put(authRoutes.isAuthenticated, lessonRoutes.putCourseLesson)
        .patch(authRoutes.isAuthenticated, lessonRoutes.patchCourseLesson)
        .delete(authRoutes.isAuthenticated, lessonRoutes.deleteCourseLesson);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COURSES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /courses
    router.route('/courses')
        .get(authRoutes.isAuthenticated, courseRoutes.getCourses)
        .post(authRoutes.isAuthenticated, courseRoutes.postCourse);

    // ENDPOINT: /courses/:id
    router.route('/courses/:id')
        .get(authRoutes.isAuthenticated, courseRoutes.getCourseById)
        .put(authRoutes.isAuthenticated, courseRoutes.putCourse)
        .patch(authRoutes.isAuthenticated, courseRoutes.patchCourse)
        .delete(authRoutes.isAuthenticated, courseRoutes.deleteCourse);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CURRENCIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /currencies
    router.route('/currencies')
        .get(authRoutes.isAuthenticated, currencyRoutes.getCurrencies)
        .post(authRoutes.isAuthenticated, currencyRoutes.postCurrency);

    // ENDPOINT: /currencies/:id
    router.route('/currencies/:id')
        .get(authRoutes.isAuthenticated, currencyRoutes.getCurrencyById)
        .put(authRoutes.isAuthenticated, currencyRoutes.putCurrency)
        .patch(authRoutes.isAuthenticated, currencyRoutes.patchCurrency)
        .delete(authRoutes.isAuthenticated, currencyRoutes.deleteCurrency);
    /**
     * ====================================================================
     */

    /**
     *  Document:  OAUTH2.JS
     *  Create endpoint handlers for oauth2 authorize
     */
        // ENDPOINT: /oauth2/authorize
    router.route('/oauth2/authorize')
        .get(authRoutes.isAuthenticated, oauth2Routes.authorization)
        .post(authRoutes.isAuthenticated, oauth2Routes.decision);

    // ENDPOINT: /oauth2/token
    router.route('/oauth2/token')
        .post(authRoutes.isClientAuthenticated, oauth2Routes.token);
    /**
     * ====================================================================
     */

    /**
     *  Document:  PERMISSIONS.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /permissions
    router.route('/permissions')
        .get(authRoutes.isAuthenticated, permissionRoutes.getPermissions)
        .post(authRoutes.isAuthenticated, permissionRoutes.postPermission);

    // ENDPOINT: /permissions/:id
    router.route('/permissions/:id')
        .get(authRoutes.isAuthenticated, permissionRoutes.getPermissionById)
        .put(authRoutes.isAuthenticated, permissionRoutes.putPermission)
        .patch(authRoutes.isAuthenticated, permissionRoutes.patchPermission)
        .delete(authRoutes.isAuthenticated, permissionRoutes.deletePermission);
    /**
     * ====================================================================
     */

    /**
     *  Document:  PROGRAMS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /programs
    router.route('/programs')
        .get(authRoutes.isAuthenticated, programRoutes.getPrograms)
        .post(authRoutes.isAuthenticated, programRoutes.postProgram);

    // ENDPOINT: /programs/:id
    router.route('/programs/:id')
        .get(authRoutes.isAuthenticated, programRoutes.getProgramById)
        .put(authRoutes.isAuthenticated, programRoutes.putProgram)
        .patch(authRoutes.isAuthenticated, programRoutes.patchProgram)
        .delete(authRoutes.isAuthenticated, programRoutes.deleteProgram);
    /**
     * ====================================================================
     */

    /**
     *  Document:  ROLES.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /roles
    router.route('/roles')
       .get(authRoutes.isAuthenticated, roleRoutes.getRoles)
       .post(authRoutes.isAuthenticated, roleRoutes.postRol);

    // ENDPOINT: /roles/:id
    router.route('/roles/:id')
       .get(authRoutes.isAuthenticated, roleRoutes.getRolById)
       .put(authRoutes.isAuthenticated, roleRoutes.putRol)
       .patch(authRoutes.isAuthenticated, roleRoutes.patchRol)
       .delete(authRoutes.isAuthenticated, roleRoutes.deleteRol);
    /**
     * ====================================================================
     */

    /**
     *  Document:  STATES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /states
    router.route('/states')
        .get(authRoutes.isAuthenticated, stateRoutes.getStates)
        .post(authRoutes.isAuthenticated, stateRoutes.postState);

    // ENDPOINT: /states/:id
    router.route('/states/:id')
        .get(authRoutes.isAuthenticated, stateRoutes.getStateById)
        .put(authRoutes.isAuthenticated, stateRoutes.putState)
        .patch(authRoutes.isAuthenticated, stateRoutes.patchState)
        .delete(authRoutes.isAuthenticated, stateRoutes.deleteState);
    /**
     * ====================================================================
     */

    /**
     *  Document:  USERS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /users
    router.route('/users')
        .get(authRoutes.isAuthenticated, userRoutes.getUsers)
        .post(userRoutes.postUser);
        //.post(authRoutes.isAuthenticated, userRoutes.postUser);

    // ENDPOINT: /users/:id
    // ENDPOINT: /users/count
    // ENDPOINT: /users/count?initialDate=yyyy-mm-dd&endDate=yyyy-mm-dd
    router.route('/users/:id')
        .get(authRoutes.isAuthenticated, userRoutes.getUserById)
        .put(authRoutes.isAuthenticated, userRoutes.putUser)
        .patch(authRoutes.isAuthenticated, userRoutes.patchUser)
        .delete(authRoutes.isAuthenticated, userRoutes.deleteUser);

    // ENDPOINT: /login
    router.route('/login')
        .get(authRoutes.isLoginAuthenticated, userRoutes.getLogin);

    // ENDPOINT: /password/reset
    router.route('/password/reset')
        .post(authRoutes.isAuthenticated, userRoutes.postPasswordReset);

    // ENDPOINT: /password/reset/:code
    router.route('/password/reset/:code')
        .patch(authRoutes.isAuthenticated, userRoutes.PatchPasswordReset);

    /**
     * ====================================================================
     */
}

// Export the function that initialize all routes
module.exports.SetupRouter = SetupRouter;<commit_msg>fixed error with method in api declataion<commit_after>/**
 * Copyright (c) 2016-present, Agoo.com.co <http://www.agoo.com.co>.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree or translated in the assets folder.
 */

/**
 * Module dependencies
 */
var logger = require('../config/logger').logger;
var moment = require('moment');

/**
 * setupRouter
 *
 * @description Configure all routes on express router
 *
 * @param {express.Router}      router      The varaible router used by the server
 */
function SetupRouter (router){

    // logger for all request will first hits this middleware
    router.use(function (req, res, next) {
        var now = moment(new Date());

        var date = now.format("DD-MM-YYYY HH:mm");
        logger.info('%s %s %s', req.method, req.url, date);
        next();
    });

    /**
     *  Declare all routes
     */
    var adminRoutes         = require('./admins');
    var authRoutes          = require('./auth');
    var cityRoutes          = require('./cities');
    var clientRoutes        = require('./clients');
    var contentTypeRoutes   = require('./contentTypes');
    var countryRoutes       = require('./countries');
    var lessonRoutes        = require('./lessons');
    var courseRoutes        = require('./courses');
    var currencyRoutes      = require('./currencies');
    var oauth2Routes        = require('./oauth2');
    var permissionRoutes    = require('./permissions');
    var programRoutes       = require('./programs');
    var roleRoutes          = require('./roles');
    var stateRoutes         = require('./states');
    var userRoutes          = require('./users');

    /**
     *  Document:  USERS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /admin
    router.route('/admin')
        .get(authRoutes.isAdminAuthenticated, adminRoutes.getAdmin)
        .post(adminRoutes.postAdmin);
    //.post(authRoutes.isAuthenticated, adminRoutes.postAdmin);

    // ENDPOINT: /admin/:id
    // ENDPOINT: /admin/count
    // ENDPOINT: /admin/count?initialDate=yyyy-mm-dd&endDate=yyyy-mm-dd
    router.route('/admin/:id')
        .get(authRoutes.isAdminAuthenticated, adminRoutes.getAdminById)
        .put(authRoutes.isAdminAuthenticated, adminRoutes.putAdmin)
        .patch(authRoutes.isAdminAuthenticated, adminRoutes.patchAdmin)
        .delete(authRoutes.isAdminAuthenticated, adminRoutes.deleteAdmin);

    // ENDPOINT: /admin/login
    router.route('/admin/login')
        .get(authRoutes.isAdminLoginAuthenticated, adminRoutes.getLogin);

    // ENDPOINT: /admin/password/reset
    router.route('/admin/password/reset')
        .post(authRoutes.isAdminAuthenticated, adminRoutes.postPasswordReset);

    // ENDPOINT: /admin/password/reset/:code
    router.route('/admin/password/reset/:code')
        .patch(authRoutes.isAdminAuthenticated, adminRoutes.PatchPasswordReset);

    /**
     * ====================================================================
     */

    /**
     *  Document:  CITIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /cities
    router.route('/cities')
        .get(authRoutes.isAuthenticated, cityRoutes.getCities)
        .post(authRoutes.isAuthenticated, cityRoutes.postCity);

    // ENDPOINT: /cities/:id
    router.route('/cities/:id')
        .get(authRoutes.isAuthenticated, cityRoutes.getCityById)
        .put(authRoutes.isAuthenticated, cityRoutes.putCity)
        .patch(authRoutes.isAuthenticated, cityRoutes.patchCity)
        .delete(authRoutes.isAuthenticated, cityRoutes.deleteCity);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CLIENTS.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /clients
    router.route('/clients')
        .get(authRoutes.isAuthenticated, clientRoutes.getClientByIdClient)
        .post(authRoutes.isAuthenticated, clientRoutes.postClient);

    // ENDPOINT: /clients/:id
    router.route('/clients/:id')
        .delete(authRoutes.isAuthenticated, clientRoutes.deleteClient);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CONTENTTYPES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /types/content
    router.route('/types/content')
        .get(authRoutes.isAuthenticated, contentTypeRoutes.getContentTypes)
        .post(authRoutes.isAuthenticated, contentTypeRoutes.postContentType);

    // ENDPOINT: /types/content/:id
    router.route('/types/content/:id')
        .get(authRoutes.isAuthenticated, contentTypeRoutes.getContentTypeById)
        .put(authRoutes.isAuthenticated, contentTypeRoutes.putContentType)
        .patch(authRoutes.isAuthenticated, contentTypeRoutes.patchContentType)
        .delete(authRoutes.isAuthenticated, contentTypeRoutes.deleteContentType);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COUNTRIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /countries
    router.route('/countries')
        .get(authRoutes.isAuthenticated, countryRoutes.getCountries)
        .post(authRoutes.isAuthenticated, countryRoutes.postCountry);

    // ENDPOINT: /countries/:id
    router.route('/countries/:id')
        .get(authRoutes.isAuthenticated, countryRoutes.getCountryById)
        .put(authRoutes.isAuthenticated, countryRoutes.putCountry)
        .patch(authRoutes.isAuthenticated, countryRoutes.patchCountry)
        .delete(authRoutes.isAuthenticated, countryRoutes.deleteCountry);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COURSELEVELS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /lessons
    router.route('/lessons')
        .get(authRoutes.isAuthenticated, lessonRoutes.getCourseLessons)
        .post(authRoutes.isAuthenticated, lessonRoutes.postCourseLesson);

    // ENDPOINT: /lessons/:id
    router.route('/lessons/:id')
        .get(authRoutes.isAuthenticated, lessonRoutes.getCourseLessonById)
        .put(authRoutes.isAuthenticated, lessonRoutes.putCourseLesson)
        .patch(authRoutes.isAuthenticated, lessonRoutes.patchCourseLesson)
        .delete(authRoutes.isAuthenticated, lessonRoutes.deleteCourseLesson);
    /**
     * ====================================================================
     */

    /**
     *  Document:  COURSES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /courses
    router.route('/courses')
        .get(authRoutes.isAuthenticated, courseRoutes.getCourses)
        .post(authRoutes.isAuthenticated, courseRoutes.postCourse);

    // ENDPOINT: /courses/:id
    router.route('/courses/:id')
        .get(authRoutes.isAuthenticated, courseRoutes.getCourseById)
        .put(authRoutes.isAuthenticated, courseRoutes.putCourse)
        .patch(authRoutes.isAuthenticated, courseRoutes.patchCourse)
        .delete(authRoutes.isAuthenticated, courseRoutes.deleteCourse);
    /**
     * ====================================================================
     */

    /**
     *  Document:  CURRENCIES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /currencies
    router.route('/currencies')
        .get(authRoutes.isAuthenticated, currencyRoutes.getCurrencies)
        .post(authRoutes.isAuthenticated, currencyRoutes.postCurrency);

    // ENDPOINT: /currencies/:id
    router.route('/currencies/:id')
        .get(authRoutes.isAuthenticated, currencyRoutes.getCurrencyById)
        .put(authRoutes.isAuthenticated, currencyRoutes.putCurrency)
        .patch(authRoutes.isAuthenticated, currencyRoutes.patchCurrency)
        .delete(authRoutes.isAuthenticated, currencyRoutes.deleteCurrency);
    /**
     * ====================================================================
     */

    /**
     *  Document:  OAUTH2.JS
     *  Create endpoint handlers for oauth2 authorize
     */
        // ENDPOINT: /oauth2/authorize
    router.route('/oauth2/authorize')
        .get(authRoutes.isAuthenticated, oauth2Routes.authorization)
        .post(authRoutes.isAuthenticated, oauth2Routes.decision);

    // ENDPOINT: /oauth2/token
    router.route('/oauth2/token')
        .post(authRoutes.isClientAuthenticated, oauth2Routes.token);
    /**
     * ====================================================================
     */

    /**
     *  Document:  PERMISSIONS.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /permissions
    router.route('/permissions')
        .get(authRoutes.isAuthenticated, permissionRoutes.getPermissions)
        .post(authRoutes.isAuthenticated, permissionRoutes.postPermission);

    // ENDPOINT: /permissions/:id
    router.route('/permissions/:id')
        .get(authRoutes.isAuthenticated, permissionRoutes.getPermissionById)
        .put(authRoutes.isAuthenticated, permissionRoutes.putPermission)
        .patch(authRoutes.isAuthenticated, permissionRoutes.patchPermission)
        .delete(authRoutes.isAuthenticated, permissionRoutes.deletePermission);
    /**
     * ====================================================================
     */

    /**
     *  Document:  PROGRAMS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /programs
    router.route('/programs')
        .get(authRoutes.isAuthenticated, programRoutes.getPrograms)
        .post(authRoutes.isAuthenticated, programRoutes.postProgram);

    // ENDPOINT: /programs/:id
    router.route('/programs/:id')
        .get(authRoutes.isAuthenticated, programRoutes.getProgramById)
        .put(authRoutes.isAuthenticated, programRoutes.putProgram)
        .patch(authRoutes.isAuthenticated, programRoutes.patchProgram)
        .delete(authRoutes.isAuthenticated, programRoutes.deleteProgram);
    /**
     * ====================================================================
     */

    /**
     *  Document:  ROLES.JS
     *  Define routes where they are stored endpoints
     */
        // ENDPOINT: /roles
    router.route('/roles')
       .get(authRoutes.isAuthenticated, roleRoutes.getRoles)
       .post(authRoutes.isAuthenticated, roleRoutes.postRol);

    // ENDPOINT: /roles/:id
    router.route('/roles/:id')
       .get(authRoutes.isAuthenticated, roleRoutes.getRolById)
       .put(authRoutes.isAuthenticated, roleRoutes.putRol)
       .patch(authRoutes.isAuthenticated, roleRoutes.patchRol)
       .delete(authRoutes.isAuthenticated, roleRoutes.deleteRol);
    /**
     * ====================================================================
     */

    /**
     *  Document:  STATES.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /states
    router.route('/states')
        .get(authRoutes.isAuthenticated, stateRoutes.getStates)
        .post(authRoutes.isAuthenticated, stateRoutes.postState);

    // ENDPOINT: /states/:id
    router.route('/states/:id')
        .get(authRoutes.isAuthenticated, stateRoutes.getStateById)
        .put(authRoutes.isAuthenticated, stateRoutes.putState)
        .patch(authRoutes.isAuthenticated, stateRoutes.patchState)
        .delete(authRoutes.isAuthenticated, stateRoutes.deleteState);
    /**
     * ====================================================================
     */

    /**
     *  Document:  USERS.JS
     *  Define routes where they are stored endpoints
     */
    // ENDPOINT: /users
    router.route('/users')
        .get(authRoutes.isAuthenticated, userRoutes.getUsers)
        .post(userRoutes.postUser);
        //.post(authRoutes.isAuthenticated, userRoutes.postUser);

    // ENDPOINT: /users/:id
    // ENDPOINT: /users/count
    // ENDPOINT: /users/count?initialDate=yyyy-mm-dd&endDate=yyyy-mm-dd
    router.route('/users/:id')
        .get(authRoutes.isAuthenticated, userRoutes.getUserById)
        .put(authRoutes.isAuthenticated, userRoutes.putUser)
        .patch(authRoutes.isAuthenticated, userRoutes.patchUser)
        .delete(authRoutes.isAuthenticated, userRoutes.deleteUser);

    // ENDPOINT: /login
    router.route('/login')
        .get(authRoutes.isLoginAuthenticated, userRoutes.getLogin);

    // ENDPOINT: /password/reset
    router.route('/password/reset')
        .post(authRoutes.isAuthenticated, userRoutes.postPasswordReset);

    // ENDPOINT: /password/reset/:code
    router.route('/password/reset/:code')
        .patch(authRoutes.isAuthenticated, userRoutes.PatchPasswordReset);

    /**
     * ====================================================================
     */
}

// Export the function that initialize all routes
module.exports.SetupRouter = SetupRouter;<|endoftext|>


<commit_before>var router = require('express').Router();
var request = require('request');

var baiduKey = process.env.baiduKey;
var expressAPI = process.env.expressAPI;
var busAPIOne = process.env.busAPIOne;
var busAPITwo = process.env.busAPITwo;
var busAPIThree = process.env.busAPIThree;

router.get('/weather', function(req, res, next) {
  var option = {
    url: 'http://api.map.baidu.com/telematics/v3/weather',
    qs: {
      ak: baiduKey,
      location: 'shanghai',
      output: 'json'
    }
  }

  request(option, function(error, response, body){
    var resData = JSON.parse(body);
    var tipt = resData.results[0].index[0];
    var weather = resData.results[0].weather_data[0];
    weather.tipt = tipt;
    res.send(weather);
  });
});

router.get('/express/:type/:postId', function(req, res, next){
  var type = req.params.type;
  var postId = req.params.postId;
  var option = {
    url: expressAPI,
    qs: {
      type: type,
      postid: postId
    }
  }

  request(option, function(error, response, body){
    res.send(JSON.parse(body));
  });
});

router.get('/bus/:name', function(req, res, next){
  var name = req.params.name;
  var option = {
    url: busAPIOne,
    qs: { name: name }
  }

  var busLine = {};
  request(option, function(error, response, body){
    console.error(response);
    body = JSON.parse(body);
    for(key in body) {
      busLine[key] = body[key].trim();
    }

    var op = {
      url: busAPITwo,
      qs: {
        name: busLine.line_name,
        lineid: busLine.line_id
      }
    }

    request(op, function(error, response, bd){
      bd = JSON.parse(bd);
      console.error(bd);
      bd.busLine = busLine;
      res.send(bd);
    });
  });
});

router.get('/busstop/:name/:lineid/:stopid/:direction', function(req, res, next){
  var name = req.params.name;
  var lineId = req.params.lineid;
  var stopId = req.params.stopid;
  var direction = req.params.direction;

  var option = {
    url: busAPIThree,
    qs: {
      name: name,
      lineid: lineId,
      stopid: stopId,
      direction: direction
    }
  }

  request(option, function(error, response, body){
    res.send(JSON.parse(body));
  });
});

router.get('/test', function(req, res, next){
  var options = {
    url: 'http://shanghaicity.openservice.kankanews.com/public/bus/Getstop',
    method: 'POST',
    form: {
      "stoptype": "0",
      "stopid": "28.",
      "sid": "bdaa9e802140ad0cf15c76d99297ea78"
    },
    headers: {
      // "Accept":"*/*",
      // "Accept-Encoding":"gzip, deflate",
      // "Accept-Language":"en-US,en;q=0.8",
      // "Connection":"keep-alive",
      // "Cookie":"_gat=1; Hm_p1vt_6f69830ae7173059e935b61372431b35=eSgsNFikSKqHeAcCLA73Ag==; _gscu_1404343399=86868522excy7e19; _gscs_1404343399=87161531ep563l45; _gscbrs_1404343399=1; Hm_lvt_ba907373475281ec79b64ad73e7c9a36=1486868523,1487161532; Hm_lpvt_ba907373475281ec79b64ad73e7c9a36=1487161532; Hm_1vt_6f69830ae7173059e935b61372431b35=eSgsNFikSMOHRQcAK8v+Ag==; Hm_lvt_6f69830ae7173059e935b61372431b35=1484570870,1486865066,1487161514; Hm_lpvt_6f69830ae7173059e935b61372431b35=1487161541; HH=23a7585e35a29341870c1a8c3b6e04cef4246657; HK=4fd85a5b595e54f6af68afa3ec3c47e7cd37abeb; HG=4510645f2d85d4fcd17b14d420561fb3bcfa3ff4; HA=3f6a87a8575a21e45e7a2c1ba91bddf13b310805; HB=M2Y2YTg3YTg1NzVhMjFlNDVlN2EyYzFiYTkxYmRkZjEzYjMxMDgwNQ==; HC=532cefec396e8301dd11750304c7594cdde103b2; HD=MjAxNzAyMTU=; HY=MjAxNzAyMTU=4fd85a5b595e54f6af68afa3ec3c47e7cd37abeb4510645f2d85d4fcd17b14d420561fb3bcfa3ff436c5289719b116ec8478a464f0542d8db3a67e23; HO=TWpBeE56QXlNVFU9MjBNVEV5TmpVPTI1VFc5NmFXeHNZUzgxTGpBZ0tHbFFhRzl1WlRzZ1ExQlZJR2xRYUc5dVpTQlBVeUE1WHpFZ2JHbHJaU0JOWVdNZ1QxTWdXQ2tnUVhCd2JHVlhaV0pMYVhRdk5qQXhMakV1TkRZZ0tFdElWRTFNTENCc2FXdGxJRWRsWTJ0dktTQldaWEp6YVc5dUx6a3VNQ0JOYjJKcGJHVXZNVE5DTVRReklGTmhabUZ5YVM4Mk1ERXVNU0IzWldOb1lYUmtaWFowYjI5c2N5OHdMakUwTGpFME1Ea3dNQ0JOYVdOeWIwMWxjM05sYm1kbGNpOTFibVJsWm1sdVpXUWdUR0Z1WjNWaFoyVXZlbWhmUTA0Z2QyVmlkbWxsZHk4dzM2YzUyODk3MTliMTE2ZWM4NDc4YTQ2NGYwNTQyZDhkYjNhNjdlMjM=; _ga=GA1.2.765580975.1486868517",
      // "Host":"shanghaicity.openservice.kankanews.com",
      // "Origin":"http://shanghaicity.openservice.kankanews.com",
      // "Referer":"http://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/bdaa9e802140ad0cf15c76d99297ea78",
      // "User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/0.14.140900 MicroMessenger/undefined Language/zh_CN webview/0",
      // "X-Requested-With":"XMLHttpRequest"
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate",
      "Accept-Language": "zh-CN,zh;q=0.8",
      "Connection": "keep-alive",
      "Cookie": "Hm_p1vt_6f69830ae7173059e935b61372431b35=eSgsNFikSKqHeAcCLA73Ag==; _gscu_1404343399=86868522excy7e19; _gscbrs_1404343399=1; Hm_lvt_ba907373475281ec79b64ad73e7c9a36=1486868523,1487161532; Hm_lpvt_ba907373475281ec79b64ad73e7c9a36=1487161532; Hm_1vt_6f69830ae7173059e935b61372431b35=eSgsNFikSMOHRQcAK8v+Ag==; Hm_lvt_6f69830ae7173059e935b61372431b35=1484570870,1486865066,1487161514; Hm_lpvt_6f69830ae7173059e935b61372431b35=1487161541; HH=23a7585e35a29341870c1a8c3b6e04cef4246657; HK=4fd85a5b595e54f6af68afa3ec3c47e7cd37abeb; HG=4510645f2d85d4fcd17b14d420561fb3bcfa3ff4; HA=3f6a87a8575a21e45e7a2c1ba91bddf13b310805; HB=M2Y2YTg3YTg1NzVhMjFlNDVlN2EyYzFiYTkxYmRkZjEzYjMxMDgwNQ==; HC=532cefec396e8301dd11750304c7594cdde103b2; HD=MjAxNzAyMTU=; HY=MjAxNzAyMTU=4fd85a5b595e54f6af68afa3ec3c47e7cd37abeb4510645f2d85d4fcd17b14d420561fb3bcfa3ff436c5289719b116ec8478a464f0542d8db3a67e23; HO=TWpBeE56QXlNVFU9MjBNVEV5TmpVPTI1VFc5NmFXeHNZUzgxTGpBZ0tHbFFhRzl1WlRzZ1ExQlZJR2xRYUc5dVpTQlBVeUE1WHpFZ2JHbHJaU0JOWVdNZ1QxTWdXQ2tnUVhCd2JHVlhaV0pMYVhRdk5qQXhMakV1TkRZZ0tFdElWRTFNTENCc2FXdGxJRWRsWTJ0dktTQldaWEp6YVc5dUx6a3VNQ0JOYjJKcGJHVXZNVE5DTVRReklGTmhabUZ5YVM4Mk1ERXVNU0IzWldOb1lYUmtaWFowYjI5c2N5OHdMakUwTGpFME1Ea3dNQ0JOYVdOeWIwMWxjM05sYm1kbGNpOTFibVJsWm1sdVpXUWdUR0Z1WjNWaFoyVXZlbWhmUTA0Z2QyVmlkbWxsZHk4dzM2YzUyODk3MTliMTE2ZWM4NDc4YTQ2NGYwNTQyZDhkYjNhNjdlMjM=; _ga=GA1.2.765580975.1486868517",
      "Host": "shanghaicity.openservice.kankanews.com",
      "Origin": "http://shanghaicity.openservice.kankanews.com",
      "Referer": "http://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/bdaa9e802140ad0cf15c76d99297ea78",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/0.14.140900 MicroMessenger/undefined Language/zh_CN webview/0",
      "X-Requested-With": "XMLHttpRequest"
    }
  };

  request(options, function(error, response, body){
    console.error(error);
    console.error(response.statusCode)
    res.send(JSON.parse(body));
  });
});

module.exports = router;
<commit_msg>add bus names<commit_after>var router = require('express').Router();
var request = require('request');

var baiduKey = process.env.baiduKey;
var expressAPI = process.env.expressAPI;
var busAPIOne = process.env.busAPIOne;
var busAPITwo = process.env.busAPITwo;
var busAPIThree = process.env.busAPIThree;

router.get('/weather', function(req, res, next) {
  var option = {
    url: 'http://api.map.baidu.com/telematics/v3/weather',
    qs: {
      ak: baiduKey,
      location: 'shanghai',
      output: 'json'
    }
  }

  request(option, function(error, response, body){
    var resData = JSON.parse(body);
    var tipt = resData.results[0].index[0];
    var weather = resData.results[0].weather_data[0];
    weather.tipt = tipt;
    res.send(weather);
  });
});

router.get('/express/:type/:postId', function(req, res, next){
  var type = req.params.type;
  var postId = req.params.postId;
  var option = {
    url: expressAPI,
    qs: {
      type: type,
      postid: postId
    }
  }

  request(option, function(error, response, body){
    res.send(JSON.parse(body));
  });
});

router.get('/bus/:name', function(req, res, next){
  var name = req.params.name;
  var option = {
    url: busAPIOne,
    qs: { name: name }
  }

  var busLine = {};
  request(option, function(error, response, body){
    console.error(response);
    body = JSON.parse(body);
    for(key in body) {
      busLine[key] = body[key].trim();
    }

    var op = {
      url: busAPITwo,
      qs: {
        name: busLine.line_name,
        lineid: busLine.line_id
      }
    }

    request(op, function(error, response, bd){
      bd = JSON.parse(bd);
      console.error(bd);
      bd.busLine = busLine;
      res.send(bd);
    });
  });
});

router.get('/busstop/:name/:lineid/:stopid/:direction', function(req, res, next){
  var name = req.params.name;
  var lineId = req.params.lineid;
  var stopId = req.params.stopid;
  var direction = req.params.direction;

  var option = {
    url: busAPIThree,
    qs: {
      name: name,
      lineid: lineId,
      stopid: stopId,
      direction: direction
    }
  }

  request(option, function(error, response, body){
    res.send(JSON.parse(body));
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var Weather = require('../modules/openweathermap');
var express = require('express');
var util = require('util');
var router = express.Router();

//new Weather API using the key defaulted from the environment
var weather = new Weather();

/* GET home page. */
router.post('/weather', function(req, res, next) {
	var zip = req.body.text;
	if (!zip || !isValidUSZip(zip.trim())) {
		res.json({
			text: "I'm sorry I didn't understand.  Please use a US zip"
		});
	}
	weather.getWeatherByZip(zip.trim(), function handleResponse(err, result) {
		if (err) {
			res.json({
				text: "I'm sorry I couldn't process your request.  Please try again later"
			});
		} else {
			res.json({
				response_type: "in_channel",
				text: util.format('Here\'s the weather in %s\n%s°F %s',
					result.city,
					result.tempF.toFixed(1),
					result.description.join(', '))
			});
		}
	});

});

function isValidUSZip(zip) {
	return /^\d{5}(-\d{4})?$/.test(zip);
}

module.exports = router;<commit_msg>Addded quick alternate command for Celsius<commit_after>var Weather = require('../modules/openweathermap');
var express = require('express');
var util = require('util');
var router = express.Router();

//new Weather API using the key defaulted from the environment
var weather = new Weather();

/* GET home page. */
router.post('/weather', function(req, res, next) {
	var zip = req.body.text;
	var fahrenheit = !req.body.command.includes('c');
	if (!zip || !isValidUSZip(zip.trim())) {
		res.json({
			text: "I'm sorry I didn't understand.  Please use a US zip"
		});
	}
	weather.getWeatherByZip(zip.trim(), function handleResponse(err, result) {
		if (err) {
			res.json({
				text: "I'm sorry I couldn't process your request.  Please try again later"
			});
		} else {
			res.json({
				response_type: "in_channel",
				text: util.format('Here\'s the weather in %s\n%s°%s %s',
					result.city,
					fahrenheit ? result.tempF.toFixed(1) : result.tempC.toFixed(1),
					fahrenheit ? 'F' : 'C',
					result.description.join(', '))
			});
		}
	});

});

function isValidUSZip(zip) {
	return /^\d{5}(-\d{4})?$/.test(zip);
}

module.exports = router;<|endoftext|>


<commit_before>var fs = require('fs');
var mongoose = require('mongoose');
var basic = require('basic-auth');
var routesUtilities = require('../utilities/routes.js');

var Form = mongoose.model('Form');
var Traveler = mongoose.model('Traveler');
var TravelerData = mongoose.model('TravelerData');
var TravelerNote = mongoose.model('TravelerNote');

var WRITE_API_USER = 'api_write';

/**
 * Checks if the api user who is logged in has write access.
 *
 * @param req - Request object
 * @param res - Response object
 * @param next - Callback to be called when successful
 * @returns {*|ServerResponse} error when no permissions exist for writing
 */
function checkWritePermissions(req, res, next){
    var credentials = basic(req);
    if (credentials.name !== WRITE_API_USER) {
      return res.json(401, {
        error: 'Write permissions are needed to create a form'
      });
    } else {
      next();
    }
}

/**
 * Performs error checking, displays proper message back to user returns the data resulted from the mongo query
 * When successful, responds to user with the data or performs callback.
 *
 * @param err - Error from the mongo query
 * @param data - Data resulting from the mongo query
 * @param res - Response object
 * @param successCB - Optional call back variable will be executed when specified.
 * @returns {*} Error object or data object. Nothing when callback is performed
 */
function performMongoResponse(err, data, res, successCB){
  if (err) {
    console.error(err);
    return res.send(500, err.message);
  }
  if (!data) {
    return res.send(410, 'gone');
  }
  if (successCB === undefined) {
    return res.json(200, data);
  } else {
    successCB();
  }
}

/**
 * Performs a search of parent entity and search of child entity. Displays any error messages if applicable.
 * When successful, responds to user with content entit(y/ies) referenced in the parent entity.
 *
 * @param parentEntity The parent entity object in which the content entity is referenced
 * @param parentEntityKey The key of the parent entity which references the content entity
 * @param contentEntity The entity for which is being requested that is referenced from parent entity
 * @param contentEntityKeys The keys that will be fetched from the db of the contnet entity
 * @param res Response object
 */
function performFindEntityReferencedContentsByParentEntityId(parentEntity, parentEntityId, parentEntityKey, contentEntity, contentEntityKeys, res) {
  parentEntity.findById(parentEntityId, function (parentErr, parentObj) {
    performMongoResponse(parentErr, parentObj, res, function () {
      contentEntity.find({
        _id: {
          $in: parentObj[parentEntityKey]
        }
      }, contentEntityKeys).lean().exec(function (contentErr, contentObj) {
        performMongoResponse(contentErr, contentObj, res);
      });
    });
  });
}

module.exports = function (app) {
  app.get('/apis/travelers/', function (req, res) {
    var search = {
      archived: {
        $ne: true
      }
    };
    if (req.query.hasOwnProperty('device')) {
      search.devices = {
        $in: [req.query.device]
      };
    }
    Traveler.find(search, 'title status devices createdBy clonedBy createdOn deadline updatedBy updatedOn sharedWith finishedInput totalInput').lean().exec(function (err, travelers) {
      performMongoResponse(err, travelers, res);
    });
  });

  app.get('/apis/forms/', function (req, res){
    Form.find({}, function(err, forms){
      performMongoResponse(err,forms, res);
    });
  });

  app.get('/apis/forms/:id/', function (req, res){
    Form.findById(req.params.id, function(err, forms){
      performMongoResponse(err,forms, res);
    });
  });

  app.get('/apis/travelers/:id/', function (req, res) {
    Traveler.findById(req.params.id, function(travelerErr, traveler){
      performMongoResponse(travelerErr, traveler, res);
    });
  });

  app.get('/apis/travelers/:id/data/', function (req, res) {
    var travelerId = req.params.id;
    var travelerDataKeys = 'name value inputType inputBy inputOn';
    performFindEntityReferencedContentsByParentEntityId(Traveler, travelerId, 'data', TravelerData, travelerDataKeys, res);
  });

  app.get('/apis/travelers/:id/notes/', function (req, res) {
    var travelerId = req.params.id;
    var noteDataKeys = 'name value inputBy inputOn';
    performFindEntityReferencedContentsByParentEntityId(Traveler, travelerId, 'notes', TravelerNote, noteDataKeys, res);
  });

  app.get('/apis/data/:id/', function (req, res) {
    TravelerData.findById(req.params.id).lean().exec(function (err, data) {
      performMongoResponse(err, data, res, function(){
        if (data.inputType === 'file') {
          fs.exists(data.file.path, function (exists) {
            if (exists) {
              return res.sendfile(data.file.path);
            }
            return res.send(410, 'gone');
          });
        } else {
          res.json(200, data);
        }
      });
    });
  });

  app.post('/apis/create/form/', routesUtilities.filterBody(['formName', 'userName', 'html'], true), checkWritePermissions, function (req, res) {
    var formName = req.body.formName;
    var userName = req.body.userName;
    var html = req.body.html;
    routesUtilities.form.createForm(formName, userName, html, function (err, newForm) {
      performMongoResponse(err, newForm, res, function(){
        return res.json(201, newForm);
      });
    });
  });

  app.post('/apis/update/traveler/:id/', routesUtilities.filterBody(['userName', 'title', 'description', 'deadline', 'status'], true), checkWritePermissions, function (req, res) {
    try {
      var status = parseFloat(req.body.status);
    } catch (ex) {
      return res.json(400, {error: "Status provided was of invalid type. Expected: Float."});
    }

    Traveler.findById(req.params.id, function(travelerErr, traveler){
      performMongoResponse(travelerErr, traveler, res, function () {
        routesUtilities.traveler.updateTravelerStatus(req, res, traveler, status, false, function() {
          var deadline = req.body.deadline;
          if (deadline == "") {
            traveler.deadline = undefined;
          } else {
            traveler.deadline = deadline;
          }
          traveler.title = req.body.title;
          traveler.description = req.body.description;
          traveler.updatedBy = req.body.userName;
          traveler.updatedOn = Date.now();
          traveler.save(function(err) {
            performMongoResponse(err, traveler, res, function() {
              return res.json(200, traveler);
            })
          });
        });
      });
    });
  });

  app.post('/apis/create/traveler/', routesUtilities.filterBody(['formId', 'title', 'userName', 'devices'], true), checkWritePermissions, function (req, res) {
    Form.findById(req.body.formId, function(formErr, form){
      performMongoResponse(formErr,form,res, function () {
        var title = req.body.title;
        var userName = req.body.userName;
        var devices = req.body.devices;
        routesUtilities.traveler.createTraveler(form, title, userName, devices, function(newTravelerErr, newTraveler){
          performMongoResponse(newTravelerErr, newTraveler, res, function () {
            return res.json(201, newTraveler);
          });
        });
      });
    });
  });
};
<commit_msg>Add api functionality to get binder, binders, create binder, add work to binder.<commit_after>var fs = require('fs');
var mongoose = require('mongoose');
var basic = require('basic-auth');
var routesUtilities = require('../utilities/routes.js');

var Form = mongoose.model('Form');
var Traveler = mongoose.model('Traveler');
var Binder = mongoose.model('Binder');
var TravelerData = mongoose.model('TravelerData');
var TravelerNote = mongoose.model('TravelerNote');

var WRITE_API_USER = 'api_write';

/**
 * Checks if the api user who is logged in has write access.
 *
 * @param req - Request object
 * @param res - Response object
 * @param next - Callback to be called when successful
 * @returns {*|ServerResponse} error when no permissions exist for writing
 */
function checkWritePermissions(req, res, next){
    var credentials = basic(req);
    if (credentials.name !== WRITE_API_USER) {
      return res.json(401, {
        error: 'Write permissions are needed to create a form'
      });
    } else {
      next();
    }
}

/**
 * Performs error checking, displays proper message back to user returns the data resulted from the mongo query
 * When successful, responds to user with the data or performs callback.
 *
 * @param err - Error from the mongo query
 * @param data - Data resulting from the mongo query
 * @param res - Response object
 * @param successCB - Optional call back variable will be executed when specified.
 * @returns {*} Error object or data object. Nothing when callback is performed
 */
function performMongoResponse(err, data, res, successCB){
  if (err) {
    console.error(err);
    return res.send(500, err.message);
  }
  if (!data) {
    return res.send(410, 'gone');
  }
  if (successCB === undefined) {
    return res.json(200, data);
  } else {
    successCB();
  }
}

/**
 * Performs a search of parent entity and search of child entity. Displays any error messages if applicable.
 * When successful, responds to user with content entit(y/ies) referenced in the parent entity.
 *
 * @param parentEntity The parent entity object in which the content entity is referenced
 * @param parentEntityKey The key of the parent entity which references the content entity
 * @param contentEntity The entity for which is being requested that is referenced from parent entity
 * @param contentEntityKeys The keys that will be fetched from the db of the contnet entity
 * @param res Response object
 */
function performFindEntityReferencedContentsByParentEntityId(parentEntity, parentEntityId, parentEntityKey, contentEntity, contentEntityKeys, res) {
  parentEntity.findById(parentEntityId, function (parentErr, parentObj) {
    performMongoResponse(parentErr, parentObj, res, function () {
      contentEntity.find({
        _id: {
          $in: parentObj[parentEntityKey]
        }
      }, contentEntityKeys).lean().exec(function (contentErr, contentObj) {
        performMongoResponse(contentErr, contentObj, res);
      });
    });
  });
}

module.exports = function (app) {
  app.get('/apis/travelers/', function (req, res) {
    var search = {
      archived: {
        $ne: true
      }
    };
    if (req.query.hasOwnProperty('device')) {
      search.devices = {
        $in: [req.query.device]
      };
    }
    Traveler.find(search, 'title status devices createdBy clonedBy createdOn deadline updatedBy updatedOn sharedWith finishedInput totalInput').lean().exec(function (err, travelers) {
      performMongoResponse(err, travelers, res);
    });
  });

  app.get('/apis/forms/', function (req, res){
    Form.find({}, function(err, forms){
      performMongoResponse(err,forms, res);
    });
  });

  app.get('/apis/forms/:id/', function (req, res){
    Form.findById(req.params.id, function(err, forms){
      performMongoResponse(err,forms, res);
    });
  });

  app.get('/apis/binders/', function (req, res){
      Binder.find({}, function(err, binders){
          performMongoResponse(err,binders, res);
      });
  });

  app.get('/apis/binders/:id/', function (req, res){
      Binder.findById(req.params.id, function(err, binder){
          performMongoResponse(err,binder, res);
      });
  });

  app.post('/apis/create/binders/', routesUtilities.filterBody(['binderTitle', 'description', 'userName'], true), checkWritePermissions, function (req, res) {
      var binderTitle = req.body.binderTitle;
      var userName = req.body.userName;
      var description = req.body.description;

      routesUtilities.binder.createBinder(binderTitle, description, userName, function (err, newBinder) {
          performMongoResponse(err, newBinder, res, function(){
              return res.json(201, newBinder);
          });
      });
  });

  app.post('/apis/addWork/binders/:id/', routesUtilities.filterBody(['travelerIds', 'userName'], true), checkWritePermissions, function (req, res) {
      Binder.findById(req.params.id, function(err, binder){
          performMongoResponse(err,binder, res, function () {
            userName = req.body.userName;
            routesUtilities.binder.addWork(binder, userName, req, res);
          });
      });
  });

  app.get('/apis/travelers/:id/', function (req, res) {
    Traveler.findById(req.params.id, function(travelerErr, traveler){
      performMongoResponse(travelerErr, traveler, res);
    });
  });

  app.get('/apis/travelers/:id/data/', function (req, res) {
    var travelerId = req.params.id;
    var travelerDataKeys = 'name value inputType inputBy inputOn';
    performFindEntityReferencedContentsByParentEntityId(Traveler, travelerId, 'data', TravelerData, travelerDataKeys, res);
  });

  app.get('/apis/travelers/:id/notes/', function (req, res) {
    var travelerId = req.params.id;
    var noteDataKeys = 'name value inputBy inputOn';
    performFindEntityReferencedContentsByParentEntityId(Traveler, travelerId, 'notes', TravelerNote, noteDataKeys, res);
  });

  app.get('/apis/data/:id/', function (req, res) {
    TravelerData.findById(req.params.id).lean().exec(function (err, data) {
      performMongoResponse(err, data, res, function(){
        if (data.inputType === 'file') {
          fs.exists(data.file.path, function (exists) {
            if (exists) {
              return res.sendfile(data.file.path);
            }
            return res.send(410, 'gone');
          });
        } else {
          res.json(200, data);
        }
      });
    });
  });

  app.post('/apis/create/form/', routesUtilities.filterBody(['formName', 'userName', 'html'], true), checkWritePermissions, function (req, res) {
    var formName = req.body.formName;
    var userName = req.body.userName;
    var html = req.body.html;
    routesUtilities.form.createForm(formName, userName, html, function (err, newForm) {
      performMongoResponse(err, newForm, res, function(){
        return res.json(201, newForm);
      });
    });
  });

  app.post('/apis/update/traveler/:id/', routesUtilities.filterBody(['userName', 'title', 'description', 'deadline', 'status'], true), checkWritePermissions, function (req, res) {
    try {
      var status = parseFloat(req.body.status);
    } catch (ex) {
      return res.json(400, {error: "Status provided was of invalid type. Expected: Float."});
    }

    Traveler.findById(req.params.id, function(travelerErr, traveler){
      performMongoResponse(travelerErr, traveler, res, function () {
        routesUtilities.traveler.updateTravelerStatus(req, res, traveler, status, false, function() {
          var deadline = req.body.deadline;
          if (deadline == "") {
            traveler.deadline = undefined;
          } else {
            traveler.deadline = deadline;
          }
          traveler.title = req.body.title;
          traveler.description = req.body.description;
          traveler.updatedBy = req.body.userName;
          traveler.updatedOn = Date.now();
          traveler.save(function(err) {
            performMongoResponse(err, traveler, res, function() {
              return res.json(200, traveler);
            })
          });
        });
      });
    });
  });

  app.post('/apis/create/traveler/', routesUtilities.filterBody(['formId', 'title', 'userName', 'devices'], true), checkWritePermissions, function (req, res) {
    Form.findById(req.body.formId, function(formErr, form){
      performMongoResponse(formErr,form,res, function () {
        var title = req.body.title;
        var userName = req.body.userName;
        var devices = req.body.devices;
        routesUtilities.traveler.createTraveler(form, title, userName, devices, function(newTravelerErr, newTraveler){
          performMongoResponse(newTravelerErr, newTraveler, res, function () {
            return res.json(201, newTraveler);
          });
        });
      });
    });
  });
};
<|endoftext|>


<commit_before>var express = require('express');
var apiRouter = express.Router();
var db = require('../database/data');
var passportAuth = require('./passport-auth')
var util = require('util')
var crypto = require('crypto')

apiRouter.get('/api/version', function(req, res) {
    res.json({
        'version': '1.0.0.0'
    });
});

apiRouter.get('/api/items', function(req, res) {
    res.json(db);
})

apiRouter.get('/api/items/:type', function(req, res) {
    var type = req.params.type;
    if (!type) {
        res.json(db);
    } else {
        res.json(db.filter(function(item) {
            return item.type === type;
        }));
    }
})

apiRouter.get('/api/item/:id', function(req, res) {
    var id = req.params.id;
    console.log(id);
    res.json(db.filter(function(item) {
        return item.id == id;
    }));
})

// GET /auth/qq
// QQ登录认证时 `state` 为必填参数
// 系client端的状态值，用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回
apiRouter.get('/api/auth/qq', function(req, res, next) {
    req.session = req.session || {};
    req.session.authState = crypto.createHash('sha1')
        .update(-(new Date()) + '')
        .digest('hex');
    passportAuth.authenticate('qq', {
        state: req.session.authState
    })(req, res, next);
});

// GET /auth/qq/callback
// 通过比较认证返回的`state`状态值与服务器端`session`中的`state`状态值
// 决定是否继续本次授权
apiRouter.get('/api/auth/qq/callback', function(req, res, next) {
    res.end(
        'authState: ' + req.session.authState + '  state:  ' + req.query.state
    )
    // if (req.session && req.session.authState && req.session.authState === req.query.state) {
    //     passportAuth
    //         .authenticate('qq', {
    //             failureRedirect: '/'
    //         })(req, res, next);
    // } else {
    //     return next(new Error('Auth State Mismatch'));
    // }
}, function(req, res) {
    res.redirect('/');
});

module.exports = apiRouter;<commit_msg>modified redirect<commit_after>var express = require('express');
var apiRouter = express.Router();
var db = require('../database/data');
var passportAuth = require('./passport-auth')
var util = require('util')
var crypto = require('crypto')

apiRouter.get('/api/version', function(req, res) {
    res.json({
        'version': '1.0.0.0'
    });
});

apiRouter.get('/api/items', function(req, res) {
    res.json(db);
})

apiRouter.get('/api/items/:type', function(req, res) {
    var type = req.params.type;
    if (!type) {
        res.json(db);
    } else {
        res.json(db.filter(function(item) {
            return item.type === type;
        }));
    }
})

apiRouter.get('/api/item/:id', function(req, res) {
    var id = req.params.id;
    console.log(id);
    res.json(db.filter(function(item) {
        return item.id == id;
    }));
})

// GET /auth/qq
// QQ登录认证时 `state` 为必填参数
// 系client端的状态值，用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回
apiRouter.get('/api/auth/qq', function(req, res, next) {
    req.session = req.session || {};
    req.session.authState = crypto.createHash('sha1')
        .update(-(new Date()) + '')
        .digest('hex');
    passportAuth.authenticate('qq', {
        state: req.session.authState
    })(req, res, next);
});

// GET /auth/qq/callback
// 通过比较认证返回的`state`状态值与服务器端`session`中的`state`状态值
// 决定是否继续本次授权
apiRouter.get('/api/auth/qq/callback', function(req, res, next) {
  res.redirect('/home');
    // if (req.session && req.session.authState && req.session.authState === req.query.state) {
    //     passportAuth
    //         .authenticate('qq', {
    //             failureRedirect: '/'
    //         })(req, res, next);
    // } else {
    //     return next(new Error('Auth State Mismatch'));
    // }
}, function(req, res) {
    res.redirect('/');
});

module.exports = apiRouter;<|endoftext|>