<commit_before>/**
 * Icon Object
 * @type {Object}
 */
Icon = {
  /**
   * Get list icon via ajax and get back return array json from server
   * @param  {[type]} page   [description]
   * @param  {[type]} by     [description]
   * @param  {[type]} search [description]
   * @return {[type]}        [description]
   */
  getAll: function(page, by, search) {
    var self = this;
    var search = search ? search : "";

    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_all",
     cache: false,
     data: {page: page, by: by, search: search},
      // 'page=' + page + "&by=" + by + "&search=" + search,
     success: function(response){
        response = JSON.parse(response);
        //console.log(response);
        var items=[];
        var data = response.data;

        //populate data
        if(data.length > 0) {
          for(var i=0; i < data.length; i++) {
            //push data to content html
            self.setSingleContent(data[i], function(result) {
              items.push(result);
            });
          }
        } else {
          items.push('
Maaf, Icon tidak ditemukan
');
        }

        //and append all icons to display in page html
        $('#icon-list').append.apply($('#icon-list'), items);
        //set button loadmore
        self.setLoadMore(response.more, response.page);
     },
     error: function(){
      alert('Error while request..');
     }
    });
  },
  /**
   * get all icon on cart
   * @return {[type]} [description]
   */
  getCart: function() {
    var self = this;
    //clear list cart on page
    $('.dropdown-keranjang').html("");

    //set button download element
    var liDownload = '

';
    liDownload += '
';
    liDownload += '';
    liDownload += ' Download all Icons
';

    //set list element if cart empty
    var liEmpty = '
Cart Empty
';

    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_cart",
     cache: false,
     data: {},
     success: function(response){
        response = JSON.parse(response);
        //console.log(response);
        var items=[];
        var data = response.data;
        var limit = data.length < 3 ? data.length : 3; //limit only 3 icon show on cart

        //populate data
        if(data.length > 0) {
          for(var i=0; i < limit; i++) {
            //push data to content html
            var item = self.setSingleItemOnCart(data[i], function(result) {
              items.push(result);
            });

          }

          items.push(liDownload);
          $('.total-icons-keranjang').show();
        } else {
          $('.total-icons-keranjang').hide();
          items.push(liEmpty);
        }

        //and append all icons to display in cart list
        $('.dropdown-keranjang').append.apply($('.dropdown-keranjang'), items);
     },
     error: function(){
      alert('Error while request..');
     }
    });
  },
  /**
   * add icon to cart
   * @param {[type]} id   [description]
   * @param {[type]} name [description]
   */
  addToCart: function(id, name) {
    var self = this;
    //get token
    var token = sessionStorage.getItem('userNotRegistered');
    $('.download-icon[data-id="'+ id +'"]').html("");
    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/add_to_cart",
     cache: false,
     data: {id: id, token: token},
     success: function(response){
       response  = JSON.parse(response);
       if(response.status === true) {
          //refresh cart
          self.getCart();
          //toggle button action to icon item
          self.setBtnRemoveIcon(id, name, function(result) {
            $('.download-icon[data-id="'+ id +'"]').append(result);
          });
          /*swal(name, "ditambahkan ke keranjang", "success");*/
          var opts = {
            "debug": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
          };
          toastr.success("Success ditambahkan ke keranjang.", name, "Warning !", opts);
       }
     },
     error: function(){
      self.setBtnAddIcon(id, name, function(result) {
        $('.download-icon[data-id="'+ id +'"]').append(result);
      });
      /*sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");*/
          var opts = {
            "debug": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
          };
          toastr.success("Terjadi kesalahan pada sistem.", "Oops...", opts);
     }
    });
  },
  /**
   * remove icon selected from cart
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  removeFromCart: function(id, name) {
    var self = this;
    //get token
    var token = sessionStorage.getItem('userNotRegistered');

    //show alert warning before remove icon from cart
    swal({
      title: "Hapus Icon",
      text: "Ingin menghapus icon " + name + " dari cart?",
      type: "warning",
      showCancelButton: true,
      closeOnConfirm: false,
      showLoaderOnConfirm: true
    }, function () {
         $('.download-icon[data-id="'+ id +'"]').html("");
        //if clicked confirmation, call method to remove icon from cart
        $.ajax({
         type: "post",
         url: BASE_URL + "icon/remove_from_cart",
         cache: false,
         data: {id: id, token: token},
         success: function(response){
           response  = JSON.parse(response);
           // console.log(response);

           if(response.status === true) {
            /*
             swal("Deleted!",
              "Icons telah dihapus dari keranjang.",
              "success");
            */
            var opts = {
              "debug": false,
              "positionClass": "toast-bottom-right",
              "onclick": null,
              "showDuration": "300",
              "hideDuration": "1000",
              "timeOut": "5000",
              "extendedTimeOut": "1000",
              "showEasing": "swing",
              "hideEasing": "linear",
              "showMethod": "fadeIn",
              "hideMethod": "fadeOut"
            };
            toastr.success("Success dihapus dari keranjang.", "Icons" + name,  "Deleted !", opts);
             //toggle button action on icon item.
             self.setBtnAddIcon(id, name, function(result) {
                $('.download-icon[data-id="'+ id +'"]').append(result);
             });
          } else {
             swal("Error!",
              "Icons gagal dihapus dari keranjang.",
              "error");
             //toggle button action on icon item.
             self.setBtnRemoveIcon(id, name, function(result) {
                $('.download-icon[data-id="'+ id +'"]').append(result);
             });
          }

          //refresh cart
          Icon.getCart();
          Cart.getAll();
         },
         error: function(){
          self.setBtnRemoveIcon(id, name, function(result) {
            $('.download-icon[data-id="'+ id +'"]').append(result);
          });
          sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");
         }
        });
    });
  },
  /**
   * set element html for single item on cart list
   * @param {[type]} icon [description]
   */
  setSingleItemOnCart: function(icon, callback) {
    var liCart = document.createElement("li");
    var imgCart = document.createElement("img");
    var spanCart = document.createElement("span");
    var btnRemove = document.createElement("a");
    var iconRemove = document.createElement("i");
    var textRemove = document.createTextNode(" Hapus");

    btnRemove.setAttribute("class", "black-color btn-remove-cart");
    btnRemove.setAttribute("data-id", icon.id);
    btnRemove.setAttribute("data-name", icon.name);
    btnRemove.setAttribute("href", "javascript:void(0)");
    iconRemove.setAttribute("class", "green-color fa fa-trash");
    btnRemove.appendChild(iconRemove);
    btnRemove.appendChild(textRemove);
    spanCart.appendChild(btnRemove);

    imgCart.setAttribute("alt", icon.name);
    imgCart.setAttribute("src", icon.path);

    liCart.setAttribute("id", "item-cart-" + icon.id);
    liCart.appendChild(imgCart);
    liCart.appendChild(spanCart);

    callback(liCart);
    return true;
  },
  /**
   * set Element Html to display single icon on page
   * @param {[type]} icon [description]
   */
  setSingleContent: function(icon, callback) {
     var divIconItem = document.createElement("div");
     var spanDownloadIcon = document.createElement("span");
     var spanViewIcon = document.createElement("span");
     var divImgIcon = document.createElement("div");
     var imgIcon = document.createElement("img");
     var btnView = document.createElement("a");

     divIconItem.setAttribute("class", "col-md-2 col-xs-4 col-sm-3 icon-item");
     spanDownloadIcon.setAttribute("class", "download-icon");
     spanDownloadIcon.setAttribute("data-id", icon.id);
     spanViewIcon.setAttribute("class", "view-icon");

     if(icon.onCart === true) {
        this.setBtnRemoveIcon(icon.id, icon.name, function(result) {
          spanDownloadIcon.appendChild(result);
        });

     } else {
        this.setBtnAddIcon(icon.id, icon.name, function(result) {
          spanDownloadIcon.appendChild(result);
        });
     }

     divImgIcon.setAttribute("class", "text-center img-icon");
     imgIcon.setAttribute("src", icon.path);
     imgIcon.setAttribute("height", "80");
     imgIcon.setAttribute("data-icon-type", "cc");
     imgIcon.setAttribute("id", icon.id);
     divImgIcon.appendChild(imgIcon);

     btnView.setAttribute("data-id", icon.id);
     btnView.setAttribute("href", "javascript:void(0)");
     btnView.setAttribute("class", "fa fa-eye fa-lg btn-view-icon");
     spanViewIcon.appendChild(btnView);

     divIconItem.appendChild(spanDownloadIcon);
     divIconItem.appendChild(spanViewIcon);
     divIconItem.appendChild(divImgIcon);

     callback(divIconItem);
     return true;
  },
  /**
   * set button action add to cart on single content icon on page
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  setBtnAddIcon: function(id, name, callback) {
    var btnAdd = document.createElement("a");
    var iconAdd = document.createElement("i");
    btnAdd.setAttribute("class", "btn-add-cart");
    btnAdd.setAttribute("data-id", id);
    btnAdd.setAttribute("data-name", name);
    btnAdd.setAttribute("href", "javascript:void(0)");
    iconAdd.setAttribute("class", "fa fa-shopping-basket");
    btnAdd.appendChild(iconAdd);

    callback(btnAdd);
    return true;
  },
  /**
   * set button action remove from cart on single content icon on page
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  setBtnRemoveIcon: function(id, name, callback) {
    var btnRemove = document.createElement("a");
    var iconRemove = document.createElement("i");
    btnRemove.setAttribute("class", "btn-remove-cart");
    btnRemove.setAttribute("data-id", id);
    btnRemove.setAttribute("data-name", name);
    btnRemove.setAttribute("href", "javascript:void(0)");
    iconRemove.setAttribute("class", "fa fa-trash");
    btnRemove.appendChild(iconRemove);

    callback(btnRemove);
    return true;
  },
  /**
   * Set button loadmore, and show it to page or not
   * @param {[type]} more [description]
   * @param {[type]} page [description]
   */
  setLoadMore: function(more, page) {
    $('#content-loadmore').html('');

    if(more === true) {
      var btnLoadmore = document.createElement("a");
      var textLoadmore = document.createTextNode("LOAD MORE");
      btnLoadmore.setAttribute("class", "btn btn-primary btn-load-more");
      btnLoadmore.setAttribute("id", "btn-load-more");
      btnLoadmore.setAttribute("data-page", page);
      btnLoadmore.setAttribute("href", "javascript:void(0)");
      btnLoadmore.appendChild(textLoadmore);

      $('#content-loadmore').html(btnLoadmore);
      $('#content-loadmore').show();
    } else {
      $('#content-loadmore').hide();
    }
  },
  /**
   * Get All Icon with filter
   * @param  {[type]} by [description]
   * @return {[type]}    [description]
   */
  changefilter: function(by) {
    //first clear icon list
    this.clearList();
    //get params search
    var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search'): null;
    var search = paramSearch ? paramSearch : "";

    var page = 1;

    //call method to get icon list
    Icon.getAll(page, by, search);

    //redirect url with params
    if(search !== "") {
      window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
    } else {
      window.history.pushState("", "", BASE_URL + "?by=" +by);
    }
  },
  /**
   * Get Result All Icon from search form
   * @param  {[type]} search [description]
   * @return {[type]}        [description]
   */
  search: function(search) {
    //first clear icon list
    this.clearList();
    //set params
    var page = 1;
    var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by'): null;
    var by = paramBy ? paramBy : "newest";
    //call method to get all icon with search key
    Icon.getAll(page, by, search);
    //redirect url
    window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
  },
  /**
   * Clear Icon List from page
   * @return {[type]} [description]
   */
  clearList: function() {
    $('#icon-list').html("");
  },
  /**
   * view detail/large icon using modal element
   * @param  {[type]}   id       [description]
   * @param  {Function} callback [description]
   * @return {[type]}            [description]
   */
  view: function(id, callback) {
    $('#modal-content-large-icon').html("");
    //Ajax method to get icon detail
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_one",
     cache: false,
     data: {id: id},
     success: function(response){
        response = JSON.parse(response);
        var data = response.data;
        var imgIcon = '';
        $('#modal-content-large-icon').append(imgIcon);
        callback(response.status);
     },
     error: function(){
      sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");
     }
    });
  },
};<commit_msg>edit swal dialog will close if remove icon from cart success<commit_after>/**
 * Icon Object
 * @type {Object}
 */
Icon = {
  /**
   * Get list icon via ajax and get back return array json from server
   * @param  {[type]} page   [description]
   * @param  {[type]} by     [description]
   * @param  {[type]} search [description]
   * @return {[type]}        [description]
   */
  getAll: function(page, by, search) {
    var self = this;
    var search = search ? search : "";

    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_all",
     cache: false,
     data: {page: page, by: by, search: search},
      // 'page=' + page + "&by=" + by + "&search=" + search,
     success: function(response){
        response = JSON.parse(response);
        //console.log(response);
        var items=[];
        var data = response.data;

        //populate data
        if(data.length > 0) {
          for(var i=0; i < data.length; i++) {
            //push data to content html
            self.setSingleContent(data[i], function(result) {
              items.push(result);
            });
          }
        } else {
          items.push('
Maaf, Icon tidak ditemukan
');
        }

        //and append all icons to display in page html
        $('#icon-list').append.apply($('#icon-list'), items);
        //set button loadmore
        self.setLoadMore(response.more, response.page);
     },
     error: function(){
      alert('Error while request..');
     }
    });
  },
  /**
   * get all icon on cart
   * @return {[type]} [description]
   */
  getCart: function() {
    var self = this;
    //clear list cart on page
    $('.dropdown-keranjang').html("");

    //set button download element
    var liDownload = '

';
    liDownload += '
';
    liDownload += '';
    liDownload += ' Download all Icons
';

    //set list element if cart empty
    var liEmpty = '
Cart Empty
';

    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_cart",
     cache: false,
     data: {},
     success: function(response){
        response = JSON.parse(response);
        //console.log(response);
        var items=[];
        var data = response.data;
        var limit = data.length < 3 ? data.length : 3; //limit only 3 icon show on cart

        //populate data
        if(data.length > 0) {
          for(var i=0; i < limit; i++) {
            //push data to content html
            var item = self.setSingleItemOnCart(data[i], function(result) {
              items.push(result);
            });

          }

          items.push(liDownload);
          $('.total-icons-keranjang').show();
        } else {
          $('.total-icons-keranjang').hide();
          items.push(liEmpty);
        }

        //and append all icons to display in cart list
        $('.dropdown-keranjang').append.apply($('.dropdown-keranjang'), items);
     },
     error: function(){
      alert('Error while request..');
     }
    });
  },
  /**
   * add icon to cart
   * @param {[type]} id   [description]
   * @param {[type]} name [description]
   */
  addToCart: function(id, name) {
    var self = this;
    //get token
    var token = sessionStorage.getItem('userNotRegistered');
    $('.download-icon[data-id="'+ id +'"]').html("");
    //Ajax method
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/add_to_cart",
     cache: false,
     data: {id: id, token: token},
     success: function(response){
       response  = JSON.parse(response);
       if(response.status === true) {
          //refresh cart
          self.getCart();
          //toggle button action to icon item
          self.setBtnRemoveIcon(id, name, function(result) {
            $('.download-icon[data-id="'+ id +'"]').append(result);
          });
          /*swal(name, "ditambahkan ke keranjang", "success");*/
          var opts = {
            "debug": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
          };
          toastr.success("Success ditambahkan ke keranjang.", name, "Warning !", opts);
       }
     },
     error: function(){
      self.setBtnAddIcon(id, name, function(result) {
        $('.download-icon[data-id="'+ id +'"]').append(result);
      });
      /*sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");*/
          var opts = {
            "debug": false,
            "positionClass": "toast-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
          };
          toastr.success("Terjadi kesalahan pada sistem.", "Oops...", opts);
     }
    });
  },
  /**
   * remove icon selected from cart
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  removeFromCart: function(id, name) {
    var self = this;
    //get token
    var token = sessionStorage.getItem('userNotRegistered');

    //show alert warning before remove icon from cart
    swal({
      title: "Hapus Icon",
      text: "Ingin menghapus icon " + name + " dari cart?",
      type: "warning",
      showCancelButton: true,
      closeOnConfirm: true,
      showLoaderOnConfirm: true
    }, function () {
         $('.download-icon[data-id="'+ id +'"]').html("");
        //if clicked confirmation, call method to remove icon from cart
        $.ajax({
         type: "post",
         url: BASE_URL + "icon/remove_from_cart",
         cache: false,
         data: {id: id, token: token},
         success: function(response){
           response  = JSON.parse(response);
           // console.log(response);

           if(response.status === true) {
            /*
             swal("Deleted!",
              "Icons telah dihapus dari keranjang.",
              "success");
            */
            var opts = {
              "debug": false,
              "positionClass": "toast-bottom-right",
              "onclick": null,
              "showDuration": "300",
              "hideDuration": "1000",
              "timeOut": "5000",
              "extendedTimeOut": "1000",
              "showEasing": "swing",
              "hideEasing": "linear",
              "showMethod": "fadeIn",
              "hideMethod": "fadeOut"
            };
            toastr.success("Success dihapus dari keranjang.", "Icons" + name,  "Deleted !", opts);
             //toggle button action on icon item.
             self.setBtnAddIcon(id, name, function(result) {
                $('.download-icon[data-id="'+ id +'"]').append(result);
             });
          } else {
             swal("Error!",
              "Icons gagal dihapus dari keranjang.",
              "error");
             //toggle button action on icon item.
             self.setBtnRemoveIcon(id, name, function(result) {
                $('.download-icon[data-id="'+ id +'"]').append(result);
             });
          }

          //refresh cart
          Icon.getCart();
          Cart.getAll();
         },
         error: function(){
          self.setBtnRemoveIcon(id, name, function(result) {
            $('.download-icon[data-id="'+ id +'"]').append(result);
          });
          sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");
         }
        });
    });
  },
  /**
   * set element html for single item on cart list
   * @param {[type]} icon [description]
   */
  setSingleItemOnCart: function(icon, callback) {
    var liCart = document.createElement("li");
    var imgCart = document.createElement("img");
    var spanCart = document.createElement("span");
    var btnRemove = document.createElement("a");
    var iconRemove = document.createElement("i");
    var textRemove = document.createTextNode(" Hapus");

    btnRemove.setAttribute("class", "black-color btn-remove-cart");
    btnRemove.setAttribute("data-id", icon.id);
    btnRemove.setAttribute("data-name", icon.name);
    btnRemove.setAttribute("href", "javascript:void(0)");
    iconRemove.setAttribute("class", "green-color fa fa-trash");
    btnRemove.appendChild(iconRemove);
    btnRemove.appendChild(textRemove);
    spanCart.appendChild(btnRemove);

    imgCart.setAttribute("alt", icon.name);
    imgCart.setAttribute("src", icon.path);

    liCart.setAttribute("id", "item-cart-" + icon.id);
    liCart.appendChild(imgCart);
    liCart.appendChild(spanCart);

    callback(liCart);
    return true;
  },
  /**
   * set Element Html to display single icon on page
   * @param {[type]} icon [description]
   */
  setSingleContent: function(icon, callback) {
     var divIconItem = document.createElement("div");
     var spanDownloadIcon = document.createElement("span");
     var spanViewIcon = document.createElement("span");
     var divImgIcon = document.createElement("div");
     var imgIcon = document.createElement("img");
     var btnView = document.createElement("a");

     divIconItem.setAttribute("class", "col-md-2 col-xs-4 col-sm-3 icon-item");
     spanDownloadIcon.setAttribute("class", "download-icon");
     spanDownloadIcon.setAttribute("data-id", icon.id);
     spanViewIcon.setAttribute("class", "view-icon");

     if(icon.onCart === true) {
        this.setBtnRemoveIcon(icon.id, icon.name, function(result) {
          spanDownloadIcon.appendChild(result);
        });

     } else {
        this.setBtnAddIcon(icon.id, icon.name, function(result) {
          spanDownloadIcon.appendChild(result);
        });
     }

     divImgIcon.setAttribute("class", "text-center img-icon");
     imgIcon.setAttribute("src", icon.path);
     imgIcon.setAttribute("height", "80");
     imgIcon.setAttribute("data-icon-type", "cc");
     imgIcon.setAttribute("id", icon.id);
     divImgIcon.appendChild(imgIcon);

     btnView.setAttribute("data-id", icon.id);
     btnView.setAttribute("href", "javascript:void(0)");
     btnView.setAttribute("class", "fa fa-eye fa-lg btn-view-icon");
     spanViewIcon.appendChild(btnView);

     divIconItem.appendChild(spanDownloadIcon);
     divIconItem.appendChild(spanViewIcon);
     divIconItem.appendChild(divImgIcon);

     callback(divIconItem);
     return true;
  },
  /**
   * set button action add to cart on single content icon on page
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  setBtnAddIcon: function(id, name, callback) {
    var btnAdd = document.createElement("a");
    var iconAdd = document.createElement("i");
    btnAdd.setAttribute("class", "btn-add-cart");
    btnAdd.setAttribute("data-id", id);
    btnAdd.setAttribute("data-name", name);
    btnAdd.setAttribute("href", "javascript:void(0)");
    iconAdd.setAttribute("class", "fa fa-shopping-basket");
    btnAdd.appendChild(iconAdd);

    callback(btnAdd);
    return true;
  },
  /**
   * set button action remove from cart on single content icon on page
   * @param  {[type]} id   [description]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  setBtnRemoveIcon: function(id, name, callback) {
    var btnRemove = document.createElement("a");
    var iconRemove = document.createElement("i");
    btnRemove.setAttribute("class", "btn-remove-cart");
    btnRemove.setAttribute("data-id", id);
    btnRemove.setAttribute("data-name", name);
    btnRemove.setAttribute("href", "javascript:void(0)");
    iconRemove.setAttribute("class", "fa fa-trash");
    btnRemove.appendChild(iconRemove);

    callback(btnRemove);
    return true;
  },
  /**
   * Set button loadmore, and show it to page or not
   * @param {[type]} more [description]
   * @param {[type]} page [description]
   */
  setLoadMore: function(more, page) {
    $('#content-loadmore').html('');

    if(more === true) {
      var btnLoadmore = document.createElement("a");
      var textLoadmore = document.createTextNode("LOAD MORE");
      btnLoadmore.setAttribute("class", "btn btn-primary btn-load-more");
      btnLoadmore.setAttribute("id", "btn-load-more");
      btnLoadmore.setAttribute("data-page", page);
      btnLoadmore.setAttribute("href", "javascript:void(0)");
      btnLoadmore.appendChild(textLoadmore);

      $('#content-loadmore').html(btnLoadmore);
      $('#content-loadmore').show();
    } else {
      $('#content-loadmore').hide();
    }
  },
  /**
   * Get All Icon with filter
   * @param  {[type]} by [description]
   * @return {[type]}    [description]
   */
  changefilter: function(by) {
    //first clear icon list
    this.clearList();
    //get params search
    var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search'): null;
    var search = paramSearch ? paramSearch : "";

    var page = 1;

    //call method to get icon list
    Icon.getAll(page, by, search);

    //redirect url with params
    if(search !== "") {
      window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
    } else {
      window.history.pushState("", "", BASE_URL + "?by=" +by);
    }
  },
  /**
   * Get Result All Icon from search form
   * @param  {[type]} search [description]
   * @return {[type]}        [description]
   */
  search: function(search) {
    //first clear icon list
    this.clearList();
    //set params
    var page = 1;
    var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by'): null;
    var by = paramBy ? paramBy : "newest";
    //call method to get all icon with search key
    Icon.getAll(page, by, search);
    //redirect url
    window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
  },
  /**
   * Clear Icon List from page
   * @return {[type]} [description]
   */
  clearList: function() {
    $('#icon-list').html("");
  },
  /**
   * view detail/large icon using modal element
   * @param  {[type]}   id       [description]
   * @param  {Function} callback [description]
   * @return {[type]}            [description]
   */
  view: function(id, callback) {
    $('#modal-content-large-icon').html("");
    //Ajax method to get icon detail
    $.ajax({
     type: "post",
     url: BASE_URL + "icon/get_one",
     cache: false,
     data: {id: id},
     success: function(response){
        response = JSON.parse(response);
        var data = response.data;
        var imgIcon = '';
        $('#modal-content-large-icon').append(imgIcon);
        callback(response.status);
     },
     error: function(){
      sweetAlert("Oops...", "Terjadi kesalahan pada sistem", "error");
     }
    });
  },
};<|endoftext|>


<commit_before>$(function(){

  "use strict";

  // Preloader
  $( window ).load(function() {
      $("#loading-img").fadeOut();
      $("#preloader").delay(400).fadeOut("slow");
  });

  $(document).ready(function(){

    // Create launch date for ticker
    // Date below denotes 1st October, 2015
    $(function () {
      var launchDay = new Date(2015, 10, 01);
      $('#ticker').countdown({
        until: launchDay
      });
    });

    // SVG Fallback for older browsers
    $(function() {
      if (!Modernizr.svg) {
        $(".logo img").attr('src', function(index, attr) {
          return attr.replace('svg', 'png');
        });
      }
    });

    // Placeholder initialise
    $('input, textarea').placeholder();

  });

});

<commit_msg>Update init.js<commit_after>$(function(){

  "use strict";

  // Preloader
  $( window ).load(function() {
      $("#loading-img").fadeOut();
      $("#preloader").delay(400).fadeOut("slow");
  });

  $(document).ready(function(){

    // Create launch date for ticker
    // Date below denotes 1st October, 2015
    $(function () {
      var launchDay = new Date(2015, 10, 1);
      $('#ticker').countdown({
        until: launchDay
      });
    });

    // SVG Fallback for older browsers
    $(function() {
      if (!Modernizr.svg) {
        $(".logo img").attr('src', function(index, attr) {
          return attr.replace('svg', 'png');
        });
      }
    });

    // Placeholder initialise
    $('input, textarea').placeholder();

  });

});

<|endoftext|>


<commit_before>(function($){
  $(function(){

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

    // convert rgb to hex value string
    function rgb2hex(rgb) {
      if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }

      rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
      function hex(x) {
          return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    $('.dynamic-color .col').each(function () {
      $(this).children().each(function () {
        var color = $(this).css('background-color');
        var classes = $(this).attr('class');
        $(this).html(rgb2hex(color) + " " + classes);
        if (classes.indexOf("darken") >= 0) {
          $(this).css('color', 'rgba(255,255,255,.9');
        }
      });
    });

    // Floating-Fixed table of contents
    $('.table-of-contents').each(function() {
      var origin = $(this);
      $(window).scroll(function() {
        var tabs_height = 0;
        if ($('.tabs-wrapper').length) {
          tabs_height = $('.tabs-wrapper').height();
        }
        if (origin.is(":visible")) {

          if(origin.attr('data-origpos') === undefined) {
            origin.attr('data-origpos', origin.position().top - tabs_height);
          }
          if(origin.attr('data-origmargin') === undefined) {
            origin.attr('data-origmargin', '1.5rem');
          }
          if($(window).scrollTop() >= origin.attr('data-origpos') && !origin.hasClass('fixed')) {
            origin.addClass('fixed');
            origin.css('top', tabs_height);
            origin.css('marginTop', '1.5rem');
          }
          if($(window).scrollTop() < origin.attr('data-origpos')) {
            origin.removeClass('fixed');
            origin.css('marginTop', origin.attr('data-origmargin'));
          }

        }
      });
    });

    // BuySellAds Detection
    var $bsa = $(".buysellads");
    var $timesToCheck = 3;
    function checkForChanges()
    {
        if ($bsa.find('.bsa_it').height() > 0)
        {
              $('.table-of-contents').css('marginTop', 230);
              // Floating-Fixed table of contents
              $('.table-of-contents').each(function() {
                var origin = $(this);
                var tabs_height = 0;
                if ($('.tabs-wrapper').length) {
                  tabs_height = $('.tabs-wrapper').height();
                }
                $(window).scroll(function() {

                  if (origin.is(":visible")) {
                    origin.attr('data-origpos', origin.position().top - tabs_height + 230);
                    origin.attr('data-origmargin', 230);
                  }
                });
              });
        }
        else {
          $timesToCheck -= 1;
          if ($timesToCheck >= 0) {
            setTimeout(checkForChanges, 500);
          }
        }

    }
    checkForChanges();

    // Tabs Fixed
    $(window).scroll(function() {
      var origin = $('.tabs-wrapper');
      var origin_row = origin.find('.row');
      if (origin.is(":visible")) {
        if(origin.attr('data-origpos') === undefined) {
          origin.attr('data-origpos', origin.position().top);
        }
        if($(window).scrollTop() >= origin.attr('data-origpos') && !origin.hasClass('fixed')) {
          origin_row.addClass('fixed');
        }
        if($(window).scrollTop() < origin.attr('data-origpos')) {
          origin_row.removeClass('fixed');
        }
      }
    });

    // Github Latest Commit
    if ($('.github-commit').length) { // Checks if widget div exists (Index only)
      $.ajax({
        url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
        dataType: "json",
        success: function (data) {
          var sha = data.sha;
          var date = jQuery.timeago(data.commit.author.date);
          if (window_width < 600) {
            sha = sha.substring(0,7);
          }
          $('.github-commit').find('.date').html(date);
          $('.github-commit').find('.sha').html(sha).attr('href', data.html_url);

          // console.log(returndata, returndata.commit.author.date, returndata.sha);
        }
      });
    }

    // Plugin initialization
    $('.dropdown-button').dropdown({"hover": false});
    if (window_width > 600) {
      $('ul.tabs').tabs();
    }
    else {
      $('ul.tabs').hide();
    }
    $('.tab-demo').show().tabs();
    $('.parallax').parallax();
    $('.modal-trigger').leanModal();
    $('.tooltipped').tooltip({"delay": 45});
    $('.collapsible-accordion').collapsible();
    $('.collapsible-expandable').collapsible({"accordion": false});
    $('.materialboxed').materialbox();
    $('.scrollspy').scrollSpy();
    $('.button-collapse').sideNav();
    $('.datepicker').pickadate();

  }); // end of document ready
})(jQuery); // end of jQuery name space<commit_msg>fixed table of contents placement<commit_after>(function($){
  $(function(){

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

    // convert rgb to hex value string
    function rgb2hex(rgb) {
      if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }

      rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
      function hex(x) {
          return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    $('.dynamic-color .col').each(function () {
      $(this).children().each(function () {
        var color = $(this).css('background-color');
        var classes = $(this).attr('class');
        $(this).html(rgb2hex(color) + " " + classes);
        if (classes.indexOf("darken") >= 0) {
          $(this).css('color', 'rgba(255,255,255,.9');
        }
      });
    });

    // Floating-Fixed table of contents
    $('.table-of-contents').each(function() {
      var origin = $(this);
      $(window).scroll(function() {
        var tabs_height = 0;
        if ($('.tabs-wrapper').length) {
          tabs_height = $('.tabs-wrapper').height();
        }
        if (origin.is(":visible")) {

          if(origin.attr('data-origpos') === undefined) {
            origin.attr('data-origpos', origin.position().top - tabs_height);
          }
          if(origin.attr('data-origmargin') === undefined) {
            origin.attr('data-origmargin', '1.5rem');
          }
          if($(window).scrollTop() >= origin.attr('data-origpos') && !origin.hasClass('fixed')) {
            origin.addClass('fixed');
            origin.css('top', tabs_height);
            origin.css('marginTop', '1.5rem');
          }
          if($(window).scrollTop() < origin.attr('data-origpos')) {
            origin.removeClass('fixed');
            origin.css('marginTop', origin.attr('data-origmargin'));
          }

        }
      });
    });

    // BuySellAds Detection
    var $bsa = $(".buysellads");
    var $timesToCheck = 3;
    function checkForChanges()
    {
        if ($bsa.find('.bsa_it').height() > 0)
        {
              $('.table-of-contents').css('marginTop', 270);
              // Floating-Fixed table of contents
              $('.table-of-contents').each(function() {
                var origin = $(this);
                var tabs_height = 0;
                if ($('.tabs-wrapper').length) {
                  tabs_height = $('.tabs-wrapper').height();
                }
                $(window).scroll(function() {

                  if (origin.is(":visible")) {
                    origin.attr('data-origpos', origin.position().top - tabs_height + 270);
                    origin.attr('data-origmargin', 270);
                  }
                });
              });
        }
        else {
          $timesToCheck -= 1;
          if ($timesToCheck >= 0) {
            setTimeout(checkForChanges, 500);
          }
        }

    }
    checkForChanges();

    // Tabs Fixed
    $(window).scroll(function() {
      var origin = $('.tabs-wrapper');
      var origin_row = origin.find('.row');
      if (origin.is(":visible")) {
        if(origin.attr('data-origpos') === undefined) {
          origin.attr('data-origpos', origin.position().top);
        }
        if($(window).scrollTop() >= origin.attr('data-origpos') && !origin.hasClass('fixed')) {
          origin_row.addClass('fixed');
        }
        if($(window).scrollTop() < origin.attr('data-origpos')) {
          origin_row.removeClass('fixed');
        }
      }
    });

    // Github Latest Commit
    if ($('.github-commit').length) { // Checks if widget div exists (Index only)
      $.ajax({
        url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
        dataType: "json",
        success: function (data) {
          var sha = data.sha;
          var date = jQuery.timeago(data.commit.author.date);
          if (window_width < 600) {
            sha = sha.substring(0,7);
          }
          $('.github-commit').find('.date').html(date);
          $('.github-commit').find('.sha').html(sha).attr('href', data.html_url);

          // console.log(returndata, returndata.commit.author.date, returndata.sha);
        }
      });
    }

    // Plugin initialization
    $('.dropdown-button').dropdown({"hover": false});
    if (window_width > 600) {
      $('ul.tabs').tabs();
    }
    else {
      $('ul.tabs').hide();
    }
    $('.tab-demo').show().tabs();
    $('.parallax').parallax();
    $('.modal-trigger').leanModal();
    $('.tooltipped').tooltip({"delay": 45});
    $('.collapsible-accordion').collapsible();
    $('.collapsible-expandable').collapsible({"accordion": false});
    $('.materialboxed').materialbox();
    $('.scrollspy').scrollSpy();
    $('.button-collapse').sideNav();
    $('.datepicker').pickadate();

  }); // end of document ready
})(jQuery); // end of jQuery name space<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var tipo;

function abrirModal(){
    var style = 'line-height: 1.5em; font-weight: 200; letter-spacing: 1px; font-size: 1em; padding: 0 15px;';

    swal({
        title: "¡ Importante ! ",
        text: "
 A continuación encontrará ejercicios propuestos de factorización de binomios y trinomios, \n\
            los cuales usted deberá resolver con la ayuda de papel y lápiz, para luego escribir la respuesta\n\
            obtenida en el campo correspondiente y de esta manera verificar los resultados y obtener las correcciones\n\
            necesarias
",
        imageUrl: "img/ayuda.png",
        html: true
    });
}

function mostrarNiveles(t){
    $("#tipos").hide();

    if(t === 'binomios'){
        $("#niveles").show();
    }else if (t === 'trinomios'){
        $("#niveles").show();
        $("#niveles2").show();
    }

    tipo = t;

}

function almacenarNivel(niv){
    //Almacenar en cookie
    setCookie("nivel", niv);

    if(tipo === 'binomios'){
        location.href = "binomios.html";
    }else{
        location.href = "trinomios.html";
    }

}

function setCookie(cname, cvalue) {
    document.cookie = cname + "=" + cvalue + ";";
}
<commit_msg>Incorporación de modal de bienvenida a la app<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var tipo;

function abrirModal(){
    var style = 'line-height: 1.5em; font-weight: 200; letter-spacing: 1px; font-size: 1em; padding: 0 15px;';

    /*swal({
        title: "¡ Importante ! ",
        text: "
 A continuación encontrará ejercicios propuestos de factorización de binomios y trinomios, \n\
            los cuales usted deberá resolver con la ayuda de papel y lápiz, para luego escribir la respuesta\n\
            obtenida en el campo correspondiente y de esta manera verificar los resultados y obtener las correcciones\n\
            necesarias
",
        imageUrl: "img/ayuda.png",
        html: true
    });*/
}

function mostrarNiveles(t){
    $("#tipos").hide();

    if(t === 'binomios'){
        $("#niveles").show();
    }else if (t === 'trinomios'){
        $("#niveles").show();
        $("#niveles2").show();
    }

    tipo = t;

}

function almacenarNivel(niv){
    //Almacenar en cookie
    setCookie("nivel", niv);

    if(tipo === 'binomios'){
        location.href = "binomios.html";
    }else{
        location.href = "trinomios.html";
    }

}

function setCookie(cname, cvalue) {
    document.cookie = cname + "=" + cvalue + ";";
}
<|endoftext|>


<commit_before>var backgroundScale = new chroma.scale(["#2d3940", "#fff"]).mode("lab");

document.addEventListener("scroll", function(e) {
  var scroll = window.scrollY;

  /****** STAGE 1 ******
   * HEADER SHRINK AND *
   * DOWN ICON OPACITY *
   *********************/
  var header = document.getElementsByTagName("header")[0];
  var headerTitle = document.getElementsByTagName("h1")[0];
  var laptop = document.getElementsByClassName("laptop")[0];
  var downIndicator = document.getElementsByClassName("down-indicator")[0];
  var laptopContent = laptop.getElementsByClassName("laptop-content")[0];

  var headerProgress = scroll / (window.innerHeight / 2);

  function setHeaderElementsPinned(fixed) {
    elements = [headerTitle, laptop];
    for (var i=0; i<elements.length; i++) {
      elements[i].style.position = fixed ? "fixed" : "absolute";
      elements[i].style.top = fixed ? "50vh" : window.innerHeight + "px";
    }
  }

  function updateHeaderElements(progress) {

    function tween(a, b) {
      return a + (b - a) * progress;
    }

    header.style.width = tween(
      100,
      (100 * laptopContent.offsetWidth / window.innerWidth)
    ) + "vw";
    header.style.height = tween(
      100,
      (100 * laptopContent.offsetHeight / window.innerHeight)
    ) + "vh";
    header.style.top = tween(
      window.innerHeight / 2,  // 50vh
      laptopContent.offsetTop + laptopContent.offsetHeight
    ) + "px";
    if (progress === 1) {
      header.style.top = header.offsetTop + window.innerHeight / 2 + "px";
      header.style.position = "absolute";
    } else {
      header.style.position = "fixed";
    }
    downIndicator.style.opacity = 1 - progress;
    document.body.style.backgroundColor = backgroundScale(headerProgress).hex();

    // TODO: Update canvas pixel size
  }

  switch(true) {
    case (scroll < 5):
      setHeaderElementsPinned(true);
      updateHeaderElements(0);
      break;

    case (scroll < window.innerHeight / 2):
      setHeaderElementsPinned(true);
      updateHeaderElements(headerProgress);
      break;

    default:
      setHeaderElementsPinned(false);
      updateHeaderElements(1);
  }
});
<commit_msg>(hopefully) improve performance by moving static things outside of the loop<commit_after>var backgroundScale = new chroma.scale(["#2d3940", "#fff"]).mode("lab");

var elem = {
  header: document.getElementsByTagName("header")[0],
  headerTitle: document.getElementsByTagName("h1")[0],
  laptop: document.getElementsByClassName("laptop")[0],
  downIndicator: document.getElementsByClassName("down-indicator")[0],
  laptopContent: document.getElementsByClassName("laptop-content")[0],
  body: document.body
};

function setHeaderElementsPinned(fixed) {
  var elements = [elem.headerTitle, elem.laptop];
  for (var i=0; i<elements.length; i++) {
    elements[i].style.position = fixed ? "fixed" : "absolute";
    elements[i].style.top = fixed ? "50vh" : window.innerHeight + "px";
  }
}

function updateHeaderElements(progress) {

  function tween(a, b) {
    return a + (b - a) * progress;
  }

  elem.header.style.width = tween(
    100,
    (100 * elem.laptopContent.offsetWidth / window.innerWidth)
  ) + "vw";
  elem.header.style.height = tween(
    100,
    (100 * elem.laptopContent.offsetHeight / window.innerHeight)
  ) + "vh";

  elem.header.style.top = tween(
    window.innerHeight / 2,  // 50vh
    elem.laptopContent.offsetTop + elem.laptopContent.offsetHeight
  ) + "px";

  if (progress === 1) {
    elem.header.style.top = elem.header.offsetTop + window.innerHeight / 2 + "px";
    elem.header.style.position = "absolute";
  } else {
    elem.header.style.position = "fixed";
  }
  elem.downIndicator.style.opacity = 1 - progress;
  elem.body.style.backgroundColor = backgroundScale(progress).hex();

  // TODO: Update canvas pixel size
}

document.addEventListener("scroll", function(e) {
  var scroll = window.scrollY;

  /****** STAGE 1 ******
   * HEADER SHRINK AND *
   * DOWN ICON OPACITY *
   *********************/

  var headerProgress = scroll / (window.innerHeight / 2);

  switch(true) {
    case (scroll < 5):
      setHeaderElementsPinned(true);
      updateHeaderElements(0);
      break;

    case (scroll < window.innerHeight / 2):
      setHeaderElementsPinned(true);
      updateHeaderElements(headerProgress);
      break;

    default:
      setHeaderElementsPinned(false);
      updateHeaderElements(1);
  }
});
<|endoftext|>


<commit_before>
$(function() {
  ispy.init();
  ispy.addGroups();
  ispy.initLight();
  ispy.initDetector();
  ispy.importBeampipe();
  ispy.loadWebFiles();
  ispy.run();

  console.log(ispy.event_description);
});
<commit_msg>rm display of beampipe by default<commit_after>
$(function() {
  ispy.init();
  ispy.addGroups();
  ispy.initLight();
  ispy.initDetector();
  ispy.loadWebFiles();
  ispy.run();

  console.log(ispy.event_description);
});
<|endoftext|>


<commit_before>(function(window, document, undefined) {

	// data specifically for the jobs page
	var jobsData = {
		header: "Job Postings",
		description: "Opportunities to work in sports analytics",
		navbarTitle: "Job Postings",
		jobs: [
			{
				company: "Los Angeles Angels of Anaheim",
				title: "Director, Quantitative Analysis",
				location: "Anaheim, CA",
				description: "Responsible for developing and overseeing the research and analytics initiative within Baseball Operations, reporting to the General Manager and Assistant General Manager.",
				link: "http://baseballjobs.teamworkonline.com/teamwork/r.cfm?i=88100",
				logo: "angels.gif",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 20
					}
				},
				active: true
			},
			{
				company: "TruMedia Networks",
				title: "Principal / Senior / QA Software",
				location: "Boston, MA (remote possible)",
				description: "TruMedia is looking for Principal, Senior and QA Software Engineers to help build tier one sports analytics and scouting solutions. The ideal candidates will be passionate sports fans, have a strong interest in data science and have the ability to work on the full software stack with a focus on web development and user interface design. Interfaces will be needed for web based solutions as well as mobile platforms.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-trumedia-networks-principal-senior-qa-software-engineer/",
				logo: "trumedia.jpg",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 14
					}
				},
				active: true
			},
			{
				company: "Charlotte Hornets",
				title: "Business Analytics Internship",
				location: "Charlotte, NC",
				description: "The Business Analytics and Database Marketing Intern will be interning in our offices here in Charlotte, NC. The primary responsibility of this intern will be to assist the Business Intelligence department’s needs with business analytics.",
				link: "http://nbateamjobs.teamworkonline.com/teamwork/r.cfm?i=87460",
				logo: "hornets.gif",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 5
					}
				},
				active: true
			},
			{
				company: "San Francisco 49ers",
				title: "Data Science Internship",
				location: "San Francisco, CA",
				description: "We are looking for a Data Science Intern to play a critical role in our use and understanding of data across various 49ers technology efforts and fan interaction and touch points.",
				link: "http://49ers.teamworkonline.com/teamwork/r.cfm?i=83653",
				logo: "49ers.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
					}
				},
				active: true
			},
			{
				company: "Columbus Crew SC",
				title: "Database & Analytics Internship",
				location: "Columbus, OH",
				description: "Columbus Crew SC is offering a Database and Analytics Internship designed to offer experience in reviewing and analyzing data within our Sales & Marketing Department.",
				link: "http://mls.teamworkonline.com/teamwork/r.cfm?i=87042",
				logo: "columbus-crew.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
						day: 28
					}
				},
				active: true
			},
			{
				company: "Baseball Info Solutions",
				title: "Research & Development Associate",
				location: "Allentown, PA",
				description: "Baseball Info Solutions (BIS) is looking for candidates to fill a full-time position in our R&D Department. The R&D Associate will work out of our office near Allentown, Pa., and will contribute as a member of our R&D team, supporting research for publications and future products.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-baseball-info-solutions-research-development-associate/",
				logo: "bis.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
						day: 28
					}
				},
				active: true
			},
			{
				company: "Carolina Hurricanes",
				title: "Java Developer/Database Administrator",
				location: "Raleigh, NC",
				description: "The Carolina Hurricanes and PNC Arena are seeking a Java Developer to continue development of existing systems and write new applications as needed.",
				link: "http://hockeyjobs.nhl.com/teamwork/r.cfm?i=85191",
				logo: "hurricanes.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
					}
				},
				active: false
			},
			{
				company: "Atlanta Braves",
				title: "Baseball Operations Analyst",
				location: "Atlanta, GA",
				description: "Responsibilities: Oversee the in-house technological efforts associated with the development of Braves’ new internal player evaluation application, Development and on-going adjustment of proprietary statistics and systems, etc.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-atlanta-braves-baseball-operations-analyst/",
				logo: "braves.gif",
				date: {
					posted: {
						year: 2015,
						month: 7,
						day: 23
					}
				},
				active: false
			},
			{
				company: "St. Louis Cardinals",
				title: "Analyst, Baseball Development",
				location: "St. Louis, MO",
				description: "This position is responsible for conducting quantitative research to provide timely recommendations to decision makers within Baseball Operations.",
				link: "http://www.fangraphs.com/blogs/jop-posting-cardinals-openings/",
				logo: "cardinals.gif",
				date: {
					posted: {
						year: 2015,
						month: 1,
						day: 14
					}
				},
				active: false
			},
			{
				company: "St. Louis Cardinals",
				title: "Developer, Baseball Development",
				location: "St. Louis, MO",
				description: "This position is responsible for designing, implementing and maintaining analytic and technical systems to provide timely, baseball-related information to decision makers within Baseball Operations.",
				link: "http://www.fangraphs.com/blogs/jop-posting-cardinals-openings/",
				logo: "cardinals.gif",
				date: {
					posted: {
						year: 2015,
						month: 1,
						day: 14
					}
				},
				active: false
			},
		]
	};

	Handlebars.registerHelper("job", function(job, active) {
		var result = "";
		result += '
'; // JOB POSTING

		// add job logo
		result += '
';
		result += '';
		result += '
';

		// add company name, location, title, and date posted
		result += '
';
		result += '
' + job.company + '
';
		result += '
' + job.location + '
';
		result += '
' + job.title + '
';
		result += '
Posted ' + Handlebars.helpers.textualDate(job.date.posted) + '
';
		result += '
';

		// add the description and link
		result += '
';
		result += '
' + job.description + '
';
		result += 'Link to the ' + job.title + ' job with the ' + job.company + '';
		if (!active) {
			result += '
Please note that this job is now closed.
';
		}
		result += '
';

		result += '
'; // / JOB POSTING
		return new Handlebars.SafeString(result);
	});

	Handlebars.registerHelper("job-listings", function(jobs) {
		var result = "";

		activeJobs = '
Active Jobs
';
		closedJobs = '
Closed Jobs
';

		$.each(jobs, function(index, job) {
			if (job.active) {
				activeJobs += Handlebars.helpers.job(job, true);
			} else {
				closedJobs += Handlebars.helpers.job(job, false);
			}
		});

		result += '
';
		result += activeJobs;
		result += closedJobs;
		result += '
';

		return new Handlebars.SafeString(result);
	});

	Handlebars.registerHelper('job-overview', function() {
		result = "";
		result += '
If you have found a job listing that would fit on this page, please submit the link here:
';
		result += '<form class="form-inline job-link-form">';
    	result +=     '
<input type="text" class="form-control" id="jobLinkInput" placeholder="Job Link">
';
    	result +=     '
Send
';
    	result += '</form>';
    	result += '
';

    	return new Handlebars.SafeString(result);
	});

	// Handlebars template for the jobs page
	jobsTemplate = [
		'{{job-overview}}',
		'{{job-listings pageData.jobs}}'
	].join('\n');

	// populate page with the above data
	populatePage(jobsTemplate, jobsData);

	// update the mailto link based on the contents in the
	$("#jobLinkInput").keyup(function(event) {
		var mailto = "mailto:stanfordsportsanalytics@gmail.com";
		var subject = "A New SSAC Job Posting";
		var body = "Here is a job listing that would fit well on the SSAC job postings: " + $(this).val();
		var href = mailto + "?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(body);
		$('#btn-job').attr('href', href);
	});

})(this, this.document);
<commit_msg>Fix default mailto<commit_after>(function(window, document, undefined) {

	// data specifically for the jobs page
	var jobsData = {
		header: "Job Postings",
		description: "Opportunities to work in sports analytics",
		navbarTitle: "Job Postings",
		jobs: [
			{
				company: "Los Angeles Angels of Anaheim",
				title: "Director, Quantitative Analysis",
				location: "Anaheim, CA",
				description: "Responsible for developing and overseeing the research and analytics initiative within Baseball Operations, reporting to the General Manager and Assistant General Manager.",
				link: "http://baseballjobs.teamworkonline.com/teamwork/r.cfm?i=88100",
				logo: "angels.gif",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 20
					}
				},
				active: true
			},
			{
				company: "TruMedia Networks",
				title: "Principal / Senior / QA Software",
				location: "Boston, MA (remote possible)",
				description: "TruMedia is looking for Principal, Senior and QA Software Engineers to help build tier one sports analytics and scouting solutions. The ideal candidates will be passionate sports fans, have a strong interest in data science and have the ability to work on the full software stack with a focus on web development and user interface design. Interfaces will be needed for web based solutions as well as mobile platforms.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-trumedia-networks-principal-senior-qa-software-engineer/",
				logo: "trumedia.jpg",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 14
					}
				},
				active: true
			},
			{
				company: "Charlotte Hornets",
				title: "Business Analytics Internship",
				location: "Charlotte, NC",
				description: "The Business Analytics and Database Marketing Intern will be interning in our offices here in Charlotte, NC. The primary responsibility of this intern will be to assist the Business Intelligence department’s needs with business analytics.",
				link: "http://nbateamjobs.teamworkonline.com/teamwork/r.cfm?i=87460",
				logo: "hornets.gif",
				date: {
					posted: {
						year: 2015,
						month: 10,
						day: 5
					}
				},
				active: true
			},
			{
				company: "San Francisco 49ers",
				title: "Data Science Internship",
				location: "San Francisco, CA",
				description: "We are looking for a Data Science Intern to play a critical role in our use and understanding of data across various 49ers technology efforts and fan interaction and touch points.",
				link: "http://49ers.teamworkonline.com/teamwork/r.cfm?i=83653",
				logo: "49ers.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
					}
				},
				active: true
			},
			{
				company: "Columbus Crew SC",
				title: "Database & Analytics Internship",
				location: "Columbus, OH",
				description: "Columbus Crew SC is offering a Database and Analytics Internship designed to offer experience in reviewing and analyzing data within our Sales & Marketing Department.",
				link: "http://mls.teamworkonline.com/teamwork/r.cfm?i=87042",
				logo: "columbus-crew.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
						day: 28
					}
				},
				active: true
			},
			{
				company: "Baseball Info Solutions",
				title: "Research & Development Associate",
				location: "Allentown, PA",
				description: "Baseball Info Solutions (BIS) is looking for candidates to fill a full-time position in our R&D Department. The R&D Associate will work out of our office near Allentown, Pa., and will contribute as a member of our R&D team, supporting research for publications and future products.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-baseball-info-solutions-research-development-associate/",
				logo: "bis.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
						day: 28
					}
				},
				active: true
			},
			{
				company: "Carolina Hurricanes",
				title: "Java Developer/Database Administrator",
				location: "Raleigh, NC",
				description: "The Carolina Hurricanes and PNC Arena are seeking a Java Developer to continue development of existing systems and write new applications as needed.",
				link: "http://hockeyjobs.nhl.com/teamwork/r.cfm?i=85191",
				logo: "hurricanes.gif",
				date: {
					posted: {
						year: 2015,
						month: 9,
					}
				},
				active: false
			},
			{
				company: "Atlanta Braves",
				title: "Baseball Operations Analyst",
				location: "Atlanta, GA",
				description: "Responsibilities: Oversee the in-house technological efforts associated with the development of Braves’ new internal player evaluation application, Development and on-going adjustment of proprietary statistics and systems, etc.",
				link: "http://www.fangraphs.com/blogs/instagraphs/job-posting-atlanta-braves-baseball-operations-analyst/",
				logo: "braves.gif",
				date: {
					posted: {
						year: 2015,
						month: 7,
						day: 23
					}
				},
				active: false
			},
			{
				company: "St. Louis Cardinals",
				title: "Analyst, Baseball Development",
				location: "St. Louis, MO",
				description: "This position is responsible for conducting quantitative research to provide timely recommendations to decision makers within Baseball Operations.",
				link: "http://www.fangraphs.com/blogs/jop-posting-cardinals-openings/",
				logo: "cardinals.gif",
				date: {
					posted: {
						year: 2015,
						month: 1,
						day: 14
					}
				},
				active: false
			},
			{
				company: "St. Louis Cardinals",
				title: "Developer, Baseball Development",
				location: "St. Louis, MO",
				description: "This position is responsible for designing, implementing and maintaining analytic and technical systems to provide timely, baseball-related information to decision makers within Baseball Operations.",
				link: "http://www.fangraphs.com/blogs/jop-posting-cardinals-openings/",
				logo: "cardinals.gif",
				date: {
					posted: {
						year: 2015,
						month: 1,
						day: 14
					}
				},
				active: false
			},
		]
	};

	Handlebars.registerHelper("job", function(job, active) {
		var result = "";
		result += '
'; // JOB POSTING

		// add job logo
		result += '
';
		result += '';
		result += '
';

		// add company name, location, title, and date posted
		result += '
';
		result += '
' + job.company + '
';
		result += '
' + job.location + '
';
		result += '
' + job.title + '
';
		result += '
Posted ' + Handlebars.helpers.textualDate(job.date.posted) + '
';
		result += '
';

		// add the description and link
		result += '
';
		result += '
' + job.description + '
';
		result += 'Link to the ' + job.title + ' job with the ' + job.company + '';
		if (!active) {
			result += '
Please note that this job is now closed.
';
		}
		result += '
';

		result += '
'; // / JOB POSTING
		return new Handlebars.SafeString(result);
	});

	Handlebars.registerHelper("job-listings", function(jobs) {
		var result = "";

		activeJobs = '
Active Jobs
';
		closedJobs = '
Closed Jobs
';

		$.each(jobs, function(index, job) {
			if (job.active) {
				activeJobs += Handlebars.helpers.job(job, true);
			} else {
				closedJobs += Handlebars.helpers.job(job, false);
			}
		});

		result += '
';
		result += activeJobs;
		result += closedJobs;
		result += '
';

		return new Handlebars.SafeString(result);
	});

	Handlebars.registerHelper('job-overview', function() {
		result = "";
		result += '
If you have found a job listing that would fit on this page, please submit the link here:
';
		result += '<form class="form-inline job-link-form">';
    	result +=     '
<input type="text" class="form-control" id="jobLinkInput" placeholder="Job Link">
';
    	result +=     '
Send
';
    	result += '</form>';
    	result += '
';

    	return new Handlebars.SafeString(result);
	});

	// Handlebars template for the jobs page
	jobsTemplate = [
		'{{job-overview}}',
		'{{job-listings pageData.jobs}}'
	].join('\n');

	// populate page with the above data
	populatePage(jobsTemplate, jobsData);

	// update the mailto link based on the contents in the
	$("#jobLinkInput").keyup(function(event) {
		var mailto = "mailto:stanfordsportsanalytics@gmail.com";
		var subject = "A New SSAC Job Posting";
		var body = "Here is a job listing that would fit well on the SSAC job postings: " + $(this).val();
		var href = mailto + "?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(body);
		$('#btn-job').attr('href', href);
	});

})(this, this.document);
<|endoftext|>


<commit_before>'use strict';

// ---------------------------------------------------------------------------

const acx = require ('./acx.js');
const { ExchangeError } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class kuna extends acx {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'kuna',
            'name': 'Kuna',
            'countries': [ 'UA' ],
            'rateLimit': 1000,
            'version': 'v2',
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
                'withdraw': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31697638-912824fa-b3c1-11e7-8c36-cf9606eb94ac.jpg',
                'api': 'https://kuna.io',
                'www': 'https://kuna.io',
                'doc': 'https://kuna.io/documents/api',
                'fees': 'https://kuna.io/documents/api',
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
                'funding': {
                    'withdraw': {
                        'UAH': '1%',
                        'BTC': 0.001,
                        'BCH': 0.001,
                        'ETH': 0.01,
                        'WAVES': 0.01,
                        'GOL': 0.0,
                        'GBG': 0.0,
                        // 'RMC': 0.001 BTC
                        // 'ARN': 0.01 ETH
                        // 'R': 0.01 ETH
                        // 'EVR': 0.01 ETH
                    },
                    'deposit': {
                        // 'UAH': (amount) => amount * 0.001 + 5
                    },
                },
            },
        });
    }

    async fetchMarkets () {
        let predefinedMarkets = [
            { 'id': 'btcuah', 'symbol': 'BTC/UAH', 'base': 'BTC', 'quote': 'UAH', 'baseId': 'btc', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'ethuah', 'symbol': 'ETH/UAH', 'base': 'ETH', 'quote': 'UAH', 'baseId': 'eth', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'gbguah', 'symbol': 'GBG/UAH', 'base': 'GBG', 'quote': 'UAH', 'baseId': 'gbg', 'quoteId': 'uah', 'precision': { 'amount': 3, 'price': 2 }, 'limits': { 'amount': { 'min': 0.001, 'max': undefined }, 'price': { 'min': 0.01, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}}, // Golos Gold (GBG != GOLOS)
            { 'id': 'kunbtc', 'symbol': 'KUN/BTC', 'base': 'KUN', 'quote': 'BTC', 'baseId': 'kun', 'quoteId': 'btc', 'precision': { 'amount': 6, 'price': 6 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'bchbtc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'baseId': 'bch', 'quoteId': 'btc', 'precision': { 'amount': 6, 'price': 6 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'bchuah', 'symbol': 'BCH/UAH', 'base': 'BCH', 'quote': 'UAH', 'baseId': 'bch', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'wavesuah', 'symbol': 'WAVES/UAH', 'base': 'WAVES', 'quote': 'UAH', 'baseId': 'waves', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'arnbtc', 'symbol': 'ARN/BTC', 'base': 'ARN', 'quote': 'BTC', 'baseId': 'arn', 'quoteId': 'btc' },
            { 'id': 'b2bbtc', 'symbol': 'B2B/BTC', 'base': 'B2B', 'quote': 'BTC', 'baseId': 'b2b', 'quoteId': 'btc' },
            { 'id': 'evrbtc', 'symbol': 'EVR/BTC', 'base': 'EVR', 'quote': 'BTC', 'baseId': 'evr', 'quoteId': 'btc' },
            { 'id': 'golgbg', 'symbol': 'GOL/GBG', 'base': 'GOL', 'quote': 'GBG', 'baseId': 'gol', 'quoteId': 'gbg' },
            { 'id': 'rbtc', 'symbol': 'R/BTC', 'base': 'R', 'quote': 'BTC', 'baseId': 'r', 'quoteId': 'btc' },
            { 'id': 'rmcbtc', 'symbol': 'RMC/BTC', 'base': 'RMC', 'quote': 'BTC', 'baseId': 'rmc', 'quoteId': 'btc' },
        ];
        let markets = [];
        let tickers = await this.publicGetTickers ();
        for (let i = 0; i < predefinedMarkets.length; i++) {
            let market = predefinedMarkets[i];
            if (market['id'] in tickers)
                markets.push (market);
        }
        let marketsById = this.indexBy (markets, 'id');
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            if (!(id in marketsById)) {
                let baseId = id.replace ('btc', '');
                baseId = baseId.replace ('uah', '');
                baseId = baseId.replace ('gbg', '');
                baseId = baseId.replace ('eth', '');
                if (baseId.length > 0) {
                    let baseIdLength = baseId.length - 0; // a transpiler workaround
                    let quoteId = id.slice (baseIdLength);
                    let base = baseId.toUpperCase ();
                    let quote = quoteId.toUpperCase ();
                    base = this.commonCurrencyCode (base);
                    quote = this.commonCurrencyCode (quote);
                    let symbol = base + '/' + quote;
                    markets.push ({
                        'id': id,
                        'symbol': symbol,
                        'base': base,
                        'quote': quote,
                        'baseId': baseId,
                        'quoteId': quoteId,
                    });
                }
            }
        }
        return markets;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orderBook = await this.publicGetOrderBook (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseOrderBook (orderBook, undefined, 'bids', 'asks', 'price', 'remaining_volume');
    }

    async fetchL3OrderBook (symbol, limit = undefined, params = {}) {
        return this.fetchOrderBook (symbol, limit, params);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orders = await this.privateGetOrders (this.extend ({
            'market': market['id'],
        }, params));
        // todo emulation of fetchClosedOrders, fetchOrders, fetchOrder
        // with order cache + fetchOpenOrders
        // as in BTC-e, Liqui, Yobit, DSX, Tidex, WEX
        return this.parseOrders (orders, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        let side = this.safeString (trade, 'side');
        let sideMap = {
            'ask': 'sell',
            'bid': 'buy',
        };
        side = sideMap[side];
        let cost = this.safeFloat (trade, 'funds');
        let order = this.safeString (trade, 'order_id');
        return {
            'id': trade['id'].toString (),
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': side,
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'volume'),
            'cost': cost,
            'order': order,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privateGetTradesMy ({ 'market': market['id'] });
        return this.parseTrades (response, market, since, limit);
    }
};
<commit_msg>kuna fetchTrades KeyError with "null" side in Python fix #3792<commit_after>'use strict';

// ---------------------------------------------------------------------------

const acx = require ('./acx.js');
const { ExchangeError } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class kuna extends acx {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'kuna',
            'name': 'Kuna',
            'countries': [ 'UA' ],
            'rateLimit': 1000,
            'version': 'v2',
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
                'withdraw': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31697638-912824fa-b3c1-11e7-8c36-cf9606eb94ac.jpg',
                'api': 'https://kuna.io',
                'www': 'https://kuna.io',
                'doc': 'https://kuna.io/documents/api',
                'fees': 'https://kuna.io/documents/api',
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
                'funding': {
                    'withdraw': {
                        'UAH': '1%',
                        'BTC': 0.001,
                        'BCH': 0.001,
                        'ETH': 0.01,
                        'WAVES': 0.01,
                        'GOL': 0.0,
                        'GBG': 0.0,
                        // 'RMC': 0.001 BTC
                        // 'ARN': 0.01 ETH
                        // 'R': 0.01 ETH
                        // 'EVR': 0.01 ETH
                    },
                    'deposit': {
                        // 'UAH': (amount) => amount * 0.001 + 5
                    },
                },
            },
        });
    }

    async fetchMarkets () {
        let predefinedMarkets = [
            { 'id': 'btcuah', 'symbol': 'BTC/UAH', 'base': 'BTC', 'quote': 'UAH', 'baseId': 'btc', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'ethuah', 'symbol': 'ETH/UAH', 'base': 'ETH', 'quote': 'UAH', 'baseId': 'eth', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'gbguah', 'symbol': 'GBG/UAH', 'base': 'GBG', 'quote': 'UAH', 'baseId': 'gbg', 'quoteId': 'uah', 'precision': { 'amount': 3, 'price': 2 }, 'limits': { 'amount': { 'min': 0.001, 'max': undefined }, 'price': { 'min': 0.01, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}}, // Golos Gold (GBG != GOLOS)
            { 'id': 'kunbtc', 'symbol': 'KUN/BTC', 'base': 'KUN', 'quote': 'BTC', 'baseId': 'kun', 'quoteId': 'btc', 'precision': { 'amount': 6, 'price': 6 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'bchbtc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'baseId': 'bch', 'quoteId': 'btc', 'precision': { 'amount': 6, 'price': 6 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'bchuah', 'symbol': 'BCH/UAH', 'base': 'BCH', 'quote': 'UAH', 'baseId': 'bch', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'wavesuah', 'symbol': 'WAVES/UAH', 'base': 'WAVES', 'quote': 'UAH', 'baseId': 'waves', 'quoteId': 'uah', 'precision': { 'amount': 6, 'price': 0 }, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
            { 'id': 'arnbtc', 'symbol': 'ARN/BTC', 'base': 'ARN', 'quote': 'BTC', 'baseId': 'arn', 'quoteId': 'btc' },
            { 'id': 'b2bbtc', 'symbol': 'B2B/BTC', 'base': 'B2B', 'quote': 'BTC', 'baseId': 'b2b', 'quoteId': 'btc' },
            { 'id': 'evrbtc', 'symbol': 'EVR/BTC', 'base': 'EVR', 'quote': 'BTC', 'baseId': 'evr', 'quoteId': 'btc' },
            { 'id': 'golgbg', 'symbol': 'GOL/GBG', 'base': 'GOL', 'quote': 'GBG', 'baseId': 'gol', 'quoteId': 'gbg' },
            { 'id': 'rbtc', 'symbol': 'R/BTC', 'base': 'R', 'quote': 'BTC', 'baseId': 'r', 'quoteId': 'btc' },
            { 'id': 'rmcbtc', 'symbol': 'RMC/BTC', 'base': 'RMC', 'quote': 'BTC', 'baseId': 'rmc', 'quoteId': 'btc' },
        ];
        let markets = [];
        let tickers = await this.publicGetTickers ();
        for (let i = 0; i < predefinedMarkets.length; i++) {
            let market = predefinedMarkets[i];
            if (market['id'] in tickers)
                markets.push (market);
        }
        let marketsById = this.indexBy (markets, 'id');
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            if (!(id in marketsById)) {
                let baseId = id.replace ('btc', '');
                baseId = baseId.replace ('uah', '');
                baseId = baseId.replace ('gbg', '');
                baseId = baseId.replace ('eth', '');
                if (baseId.length > 0) {
                    let baseIdLength = baseId.length - 0; // a transpiler workaround
                    let quoteId = id.slice (baseIdLength);
                    let base = baseId.toUpperCase ();
                    let quote = quoteId.toUpperCase ();
                    base = this.commonCurrencyCode (base);
                    quote = this.commonCurrencyCode (quote);
                    let symbol = base + '/' + quote;
                    markets.push ({
                        'id': id,
                        'symbol': symbol,
                        'base': base,
                        'quote': quote,
                        'baseId': baseId,
                        'quoteId': quoteId,
                    });
                }
            }
        }
        return markets;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orderBook = await this.publicGetOrderBook (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseOrderBook (orderBook, undefined, 'bids', 'asks', 'price', 'remaining_volume');
    }

    async fetchL3OrderBook (symbol, limit = undefined, params = {}) {
        return this.fetchOrderBook (symbol, limit, params);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orders = await this.privateGetOrders (this.extend ({
            'market': market['id'],
        }, params));
        // todo emulation of fetchClosedOrders, fetchOrders, fetchOrder
        // with order cache + fetchOpenOrders
        // as in BTC-e, Liqui, Yobit, DSX, Tidex, WEX
        return this.parseOrders (orders, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        let side = this.safeString (trade, 'side');
        if (typeof side !== 'undefined') {
            let sideMap = {
                'ask': 'sell',
                'bid': 'buy',
            };
            side = this.safeString (sideMap, side);
        }
        let cost = this.safeFloat (trade, 'funds');
        let order = this.safeString (trade, 'order_id');
        return {
            'id': trade['id'].toString (),
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': side,
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'volume'),
            'cost': cost,
            'order': order,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privateGetTradesMy ({ 'market': market['id'] });
        return this.parseTrades (response, market, since, limit);
    }
};
<|endoftext|>


<commit_before>	var langKey = {
		en: {
			job_title: "Product Developer",
			about: "About",
			about_sub: "Who am I?",
			about_content1: "I am a UX developer.",
			about_content2: "I write professional code using modern frameworks and awesome tooling to build rapidly and provide exceptional user experiences.",
			timeline : "Timeline",
			timeline_sub : "How did i get here?",
			timeline1: "Graduated from Wilfrid Laurier University",
			timeline1_5: "Major in Communications",
			timeline2: "Left for Korea to teach English",
			timeline3: "Came back from Korea",
			timeline3_5: "Completely fed up with teaching.",
			timeline4: "Graduated Web Development Algonquin College ",
			timeline4_5: "Course was too easy, went crazy in the evenings absorbing the net.",
			timeline5: "Front End Developer at ",
			timeline5_5: "Build, learn, repeat. Agility at its finest."	,
			timeline6: "UX Lead Developer at ",
			timeline6_5: "Working with big data and creating cool visualizations! Woah this is cool!",
			timeline7: "Product Developer at ",
			timeline7_5: "Leading teams to bring products to market!",
			timeline8: "Moving back to Korea!",
			timeline8_5: "Looking for remote work.",
			products: "Products",
			products_sub: "What have I helped build?",
			rebel_content: "With a startup mentality, I guide two teams of 4 in the product development lifecycle. We actively engage our customer during our cycles and implement process to modernise a legacy code base.",
			rebel_role: "Product Developer",
			solink_content: "As UX lead, I designed and lead development on the latest product release. I worked with customers and stakeholders to design a friendly and intuitive experience that works seemlessly on all devices.",
			solink_role: "Lead UX Developer",
			personal: "Personal",
			personal_sub: "What have I done with spare time? ... build.",
			room_content: "I wanted to build a better way for my landlord and I to communicate. So I built a web app to solve the problem.",
			room_role: "Founder",
			come_content: "A friend of mine and I co-authored an android app that allows friends to communicate real-time events.",
			come_role: "Developer",
			progression: "Developer Progression",
			progression_sub: "How far have I come?",
			prog1: "Simple & Wrong",
			prog2: "Complicated & Wrong",
			prog3: "Complicated & Right",
			prog4: "Simple & Right",
			done: "Done",
			here: "I'm here",
			tags: "Tags",
			tags_sub: "What keywords set me off?",
			accounts: "Accounts",
			accounts_sub: "A few different ways you can get a hold of me",
			tech: "Tech",
			lifestyle: "Lifestyle",
			travel: "Travel",
			food: "Food",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "Reading, Laughing, Learning, Exercise, Early mornings, Morning Coffee, Wim Hof",
			travel_tags: "Costa Rica, Casco Viejo, Soju, Boracay, Jamaica, AirBnB, Tuk-Tuk, Backpacking ",
			food_tags: "Raw Vegetables, Beer, Korean Food, Cheese & Crackers, Big Macs",
			thanks: "Thanks for taking the time to make it down here"
		},
		kr: {
			job_title: "제품 개발자",
			about: "나에 대해서",
			about_sub: "나는 누구입니까?",
			about_content1: "나는 UX 개발자입니다",
			about_content2: "나는 빠르게 구축하고 뛰어난 사용자 경험을 제공하기 위해 현대적인 프레임 워크와 멋진 도구를 사용하여 전문적인 코드를 작성합니다",
			timeline : "타임 라인",
			timeline_sub : "위대함 에 대한 경로",
			timeline1: "윌 프리드 로리에 대학 졸업",
			timeline1_5: "통신 전공",
			timeline2: "영어를 가르치는 한국 떠났다",
			timeline3: "한국 에서 돌아왔다",
			timeline3_5: "더 이상 가르 칠 싶지 않았다",
			timeline4: "졸업 웹 개발 알곤 퀸 대학",
			timeline4_5: "코스 는 너무 쉬웠다 그물을 흡수 저녁에 미친 갔다.",
			timeline5: "프런트 엔드 개발자 - ",
			timeline5_5: "학습 , 반복 을 구축 할 수 있습니다. 최상의 에서 민첩성 "	,
			timeline6: "UX 리드 개발자 - ",
			timeline6_5: "빅 데이터 로 작업 하고 멋진 시각화를 만들 ! 와우 이 멋지다!",
			timeline7: "제품 개발자 - ",
			timeline7_5: "팀을 선도 하는 것은 시장에 제품을 출시 합니다 !",
			timeline8: "한국으로 다시 이동!",
			timeline8_5: "원격 작업 을 찾고.",
			products: "제품",
			products_sub: "제품 목록 내가 도움이 빌드",
			rebel_content: "시작 의 정신 으로 , 나는 제품 개발 라이프 사이클 에 4 개의 팀을 안내합니다. 우리는 적극적으로 우리의 사이클 동안 우리의 고객 을 참여 하고 기존 코드 기반을 현대화 하는 과정을 구현한다.",
			solink_content: "UX 리드 , 나는 디자인 과 최신 제품 출시 에 리드 개발 . 나는 모든 장치 를 매끄럽게 작동하는 친절하고 직관적 인 경험을 디자인하는 고객 및 이해 관계자들과 일했다.",
			solink_role: "UX 개발자",
			personal: "개인적인",
			personal_sub: "제품 목록 내 여가 시간에 구축 ",
			room_content: "나는 나의 주인 을 위해 더 나은 방법 을 구축 하고 싶어 내가 의사 소통을 할 수 있습니다. 그래서 이 문제를 해결하기 위해 웹 응용 프로그램을 만들었습니다.",
			room_role: "설립자",
			come_content: "내 친구와 나는 친구 가 실시간 이벤트 를 전달 할 수있는 안드로이드 앱을 공동 저술 .",
			come_role: "개발자",
			progression: "개발자 진행",
			progression_sub: "나는 얼마나 멀리 왔다 ?",
			prog1: "간단하고 잘못된",
			prog2: "복잡한 및 잘못된",
			prog3: "복잡한 및 수정",
			prog4: "간단하고 및 수정",
			done: "끝난",
			here: "난 여기 있어요",
			tags: "꼬리표",
			tags_sub: "좋은 느낌 키워드",
			accounts: "계정",
			accounts_sub: "몇 가지 방법이 날 의 보류를 얻을 수 있습니다",
			tech: "테크",
			lifestyle: "라이프 스타일",
			travel: "여행",
			food: "식품",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "독서, 웃음, 배우기, 운동, 이른 아침, 모닝 커피, Wim Hof",
			travel_tags: "코스타리카, 카스코 비에 호 , 소주 , 보라카이 , 자메이카 , 에어 비앤비 , 툭 - 툭 , 배낭 여행",
			food_tags: "원시 야채, 맥주, 한국 음식, 치즈 & 크래커, 빅 맥",
			thanks: "Thanks for taking the time to make it down here"
		}
	}

	function bindLanguage(lang, elements) {
		for(var i = 0; i < elements.length; i++) {
			var thisItem = $(elements[i])
			var key = thisItem.data("lang-key");

			thisItem.text(langKey[lang][key]);

		}
	}

	var toggles = $("[data-lang-selector]");
	var translations = $("[data-lang-key]");

	bindLanguage("en", translations)

	toggles.on("click", function () {
		var $this = $(this);

		bindLanguage($this.data("lang-selector"), translations);

		$(".selected").removeClass("selected");
		$this.addClass("selected");
	})<commit_msg>update lang file<commit_after>	var langKey = {
		en: {
			job_title: "Product Developer",
			about: "About",
			about_sub: "Who am I?",
			about_content1: "I am a UX developer.",
			about_content2: "I write professional code using modern frameworks and awesome tooling to build rapidly and provide exceptional user experiences.",
			timeline : "Timeline",
			timeline_sub : "How did i get here?",
			timeline1: "Graduated from Wilfrid Laurier University",
			timeline1_5: "Major in Communications",
			timeline2: "Left for Korea to teach English",
			timeline3: "Came back from Korea",
			timeline3_5: "Teaching basic ESL curriculum, not quite my thing. Needs disruption.",
			timeline4: "Graduated Web Development Algonquin College ",
			timeline4_5: "Had fun, became addicted..",
			timeline5: "Front End Developer at ",
			timeline5_5: "Build, learn, repeat. Agility at its finest."	,
			timeline6: "UX Lead Developer at ",
			timeline6_5: "Working with big data and creating cool visualizations! Woah this is cool!",
			timeline7: "Product Developer at ",
			timeline7_5: "Leading teams to bring products to market!",
			timeline8: "Moving back to Korea!",
			timeline8_5: "Looking for remote work.",
			products: "Products",
			products_sub: "What have I helped build?",
			rebel_content: "With a startup mentality, I guide two teams of 4 in the product development lifecycle. We actively engage our customer during our cycles and implement process to modernise a legacy code base.",
			rebel_role: "Product Developer",
			solink_content: "As UX lead, I designed and lead development on the latest product release. I worked with customers and stakeholders to design a friendly and intuitive experience that works seemlessly on all devices.",
			solink_role: "Lead UX Developer",
			personal: "Personal",
			personal_sub: "What have I done with spare time? ... build.",
			room_content: "I wanted to build a better way for my landlord and I to communicate. So I built a web app to solve the problem.",
			room_role: "Founder",
			come_content: "A friend of mine and I co-authored an android app that allows friends to communicate real-time events.",
			come_role: "Developer",
			progression: "Developer Progression",
			progression_sub: "How far have I come?",
			prog1: "Simple & Wrong",
			prog2: "Complicated & Wrong",
			prog3: "Complicated & Right",
			prog4: "Simple & Right",
			done: "Done",
			here: "I'm here",
			tags: "Tags",
			tags_sub: "What keywords set me off?",
			accounts: "Accounts",
			accounts_sub: "A few different ways you can get a hold of me",
			tech: "Tech",
			lifestyle: "Life",
			travel: "Travel",
			food: "Food",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "Reading, Laughing, Learning, Exercise, Early mornings, Morning Coffee, Wim Hof",
			travel_tags: "Costa Rica, Casco Viejo, Soju, Boracay, Jamaica, AirBnB, Tuk-Tuk, Backpacking ",
			food_tags: "Raw Vegetables, Beer, Korean Food, Cheese & Crackers, Big Macs",
			thanks: "Thanks for taking the time to make it down here"
		},
		kr: {
			job_title: "제품 개발자",
			about: "나에 대해서",
			about_sub: "나는 누구입니까?",
			about_content1: "나는 UX 개발자입니다",
			about_content2: "나는 빠르게 구축하고 뛰어난 사용자 경험을 제공하기 위해 현대적인 프레임 워크와 멋진 도구를 사용하여 전문적인 코드를 작성합니다",
			timeline : "타임 라인",
			timeline_sub : "위대함 에 대한 경로",
			timeline1: "윌 프리드 로리에 대학 졸업",
			timeline1_5: "통신 전공",
			timeline2: "영어를 가르치는 한국 떠났다",
			timeline3: "한국 에서 돌아왔다",
			timeline3_5: "더 이상 가르 칠 싶지 않았다",
			timeline4: "졸업 웹 개발 알곤 퀸 대학",
			timeline4_5: "코스 는 너무 쉬웠다 그물을 흡수 저녁에 미친 갔다.",
			timeline5: "프런트 엔드 개발자 - ",
			timeline5_5: "학습 , 반복 을 구축 할 수 있습니다. 최상의 에서 민첩성 "	,
			timeline6: "UX 리드 개발자 - ",
			timeline6_5: "빅 데이터 로 작업 하고 멋진 시각화를 만들 ! 와우 이 멋지다!",
			timeline7: "제품 개발자 - ",
			timeline7_5: "팀을 선도 하는 것은 시장에 제품을 출시 합니다 !",
			timeline8: "한국으로 다시 이동!",
			timeline8_5: "원격 작업 을 찾고.",
			products: "제품",
			products_sub: "제품 목록 내가 도움이 빌드",
			rebel_content: "시작 의 정신 으로 , 나는 제품 개발 라이프 사이클 에 4 개의 팀을 안내합니다. 우리는 적극적으로 우리의 사이클 동안 우리의 고객 을 참여 하고 기존 코드 기반을 현대화 하는 과정을 구현한다.",
			solink_content: "UX 리드 , 나는 디자인 과 최신 제품 출시 에 리드 개발 . 나는 모든 장치 를 매끄럽게 작동하는 친절하고 직관적 인 경험을 디자인하는 고객 및 이해 관계자들과 일했다.",
			solink_role: "UX 개발자",
			personal: "개인적인",
			personal_sub: "제품 목록 내 여가 시간에 구축 ",
			room_content: "나는 나의 주인 을 위해 더 나은 방법 을 구축 하고 싶어 내가 의사 소통을 할 수 있습니다. 그래서 이 문제를 해결하기 위해 웹 응용 프로그램을 만들었습니다.",
			room_role: "설립자",
			come_content: "내 친구와 나는 친구 가 실시간 이벤트 를 전달 할 수있는 안드로이드 앱을 공동 저술 .",
			come_role: "개발자",
			progression: "개발자 진행",
			progression_sub: "나는 얼마나 멀리 왔다 ?",
			prog1: "간단하고 잘못된",
			prog2: "복잡한 및 잘못된",
			prog3: "복잡한 및 수정",
			prog4: "간단하고 및 수정",
			done: "끝난",
			here: "난 여기 있어요",
			tags: "꼬리표",
			tags_sub: "좋은 느낌 키워드",
			accounts: "계정",
			accounts_sub: "몇 가지 방법이 날 의 보류를 얻을 수 있습니다",
			tech: "테크",
			lifestyle: "라이프 스타일",
			travel: "여행",
			food: "식품",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "독서, 웃음, 배우기, 운동, 이른 아침, 모닝 커피, Wim Hof",
			travel_tags: "코스타리카, 카스코 비에 호 , 소주 , 보라카이 , 자메이카 , 에어 비앤비 , 툭 - 툭 , 배낭 여행",
			food_tags: "원시 야채, 맥주, 한국 음식, 치즈 & 크래커, 빅 맥",
			thanks: "Thanks for taking the time to make it down here"
		}
	}

	function bindLanguage(lang, elements) {
		for(var i = 0; i < elements.length; i++) {
			var thisItem = $(elements[i])
			var key = thisItem.data("lang-key");

			thisItem.text(langKey[lang][key]);

		}
	}

	var toggles = $("[data-lang-selector]");
	var translations = $("[data-lang-key]");

	bindLanguage("en", translations)

	toggles.on("click", function () {
		var $this = $(this);

		bindLanguage($this.data("lang-selector"), translations);

		$(".selected").removeClass("selected");
		$this.addClass("selected");
	})<|endoftext|>


<commit_before>document.write(' \
\

 \
	Main | Reference | Tutorials | Download | Contact \

 \
\

 \
	hAxe is an open source programming language for the web. \

 \
\
');<commit_msg>fixed X<commit_after>document.write(' \
\

 \
	Main | Reference | Tutorials | Download | Contact \

 \
\

 \
	haXe is an open source programming language for the web. \

 \
\
');<|endoftext|>