<commit_before>/*
 Copyright (C) 2015-2017 GEM Foundation

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/agpl.html>.
 */

(function($, Backbone, _) {
    var calculation_table;

    var progressHandlingFunction = function(progress) {
        var percent = progress.loaded / progress.total * 100;
        $('.bar').css('width', percent + '%');
        if (percent == 100) {
            dialog.hide();
        }
    };

    var htmlEscape = function (record) {
        // record[3] is the log message
        record[3] = record[3].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
        return record
    };

    var dialog = (function ()
                  {
                      var pleaseWaitDiv = $('

Processing...

');
                      return {
                          show: function(msg, progress) {
                              $('h1', pleaseWaitDiv).text(msg);
                              if (progress) {
                                  progressHandlingFunction({loaded: 0, total: 1});
                              } else {
                                  progressHandlingFunction({loaded: 1, total: 1});
                              }
                              pleaseWaitDiv.modal('show');
                          },
                          hide: function () {
                              pleaseWaitDiv.modal('hide');
                          }
                      };
                  })();

    var diaerror = (function ()
                  {
                      var errorDiv = $('
\

\

\

\

Calculation not accepted: traceback
\

\

\

\

\
                      <input type="checkbox" id="diaerror_scroll_enabled" checked>\
                      Auto Scroll   \
                      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\

\

\

\

');
                      errorDiv.bind('hide', function() { calculation_table.hide_log(); });
                      return {
                          getdiv: function() {
                              return errorDiv;
                          },

                          show: function(is_large, title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              if (msg != null) {
                                  $('.modal-body-pre', errorDiv).html(msg);
                              }
                              if (is_large) {
                                  errorDiv.addClass("errorDialogLarge");
                              }
                              else {
                                  errorDiv.removeClass("errorDialogLarge");
                              }
                              errorDiv.modal('show');
                          },

                          append: function(title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              $( msg ).appendTo( $('.modal-body-pre', errorDiv) );
                          },

                          scroll_to_bottom: function(ctx) {
                              ctx.scrollTop(ctx[0].scrollHeight);
                          },

                          hide: function () {
                              errorDiv.modal('hide');
                          }
                      };
                  })();

    var CalculationTable = Backbone.View.extend(
        {
            /* the html element where the table is rendered */
            el: $('#my-calculations'),

            logXhr: null,
            logId: -1,
            logIsNew: false,
            logLinesAll: 0,
            logLines: 0,
            logTimeout: null,

            initialize: function(options) {

                /* whatever happens to any calculation, re-render the table */
                _.bindAll(this, 'render');
                this.calculations = options.calculations;
                this.calculations.bind('reset', this.render);
                this.calculations.bind('add', this.render);
                this.calculations.bind('remove', this.render);

                /* if false, it prevents the table to be refreshed */
                this.can_be_rendered = true;

                this.render();
            },

            events: {
                "click .btn-show-remove": "remove_calculation",
                "click .btn-danger": "show_modal_confirm_remove_calculation",
                "click .btn-hide-remove": "hide_modal_confirm_remove_calculation",
                "click .btn-traceback": "show_traceback",
                "click .btn-log": "show_log",
                "click .btn-file": "on_run_risk_clicked",
                "change .btn-file input": "on_run_risk_queued"
            },

            /* When an input dialog is opened, it is very important to not re-render the table */
            on_run_risk_clicked: function(e) {
                /* if a file input dialog has been opened do not refresh the calc table */
                this.can_be_rendered = false;
            },

            on_run_risk_queued: function(e) {
                this.can_be_rendered = true;
            },

            show_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var show_or_back = (function(e) {
                    this.conf_show = $('#confirmDialog' + calc_id).show();
                    this.back_conf_show = $('.back_confirmDialog' + calc_id).show();
                    closeTimer();
                })();
            },

            hide_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();
            },

            remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var calc_desc = $(e.target).attr('data-calc-desc');
                var view = this;
                diaerror.show(false, "Removing calculation " + calc_id, "...");
                $.post(gem_oq_server_url + "/v1/calc/" + calc_id + "/remove"
                     ).success(
                         function(data, textStatus, jqXHR)
                         {
                             diaerror.show(false, "Calculation removed", "Calculation:
(" + calc_id + ") " + calc_desc + " removed.");
                             view.calculations.remove([view.calculations.get(calc_id)]);
                         }
                     ).error(
                         function(jqXHR, textStatus, errorThrown)
                         {
                             if (jqXHR.status == 404) {
                                 diaerror.show(false, "Removing calculation", "Failed calculation:
(" + calc_id + ") " + calc_desc + " not found.");
                             }
                             else {
                                 diaerror.show(false, "Removing calculation " + calc_id, "Failed: " + textStatus);
                             }
                         }
                     );
                 setTimer();
            },

            show_traceback: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/traceback",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 404) {
                                            diaerror.show(false, "Calculation " + calc_id + " not found.");
                                        }
                                        else {
                                            diaerror.show(false, "Error retrieving traceback for calculation " + calc_id, textStatus);
                                        }
                                        // alert("Error: " + textStatus);
                                    },
                                    success: function (data, textStatus, jqXHR) {
                                        if (data.length == 0) {
                                            diaerror.show(true, "Traceback not found for calculation " + calc_id, []);
                                        }
                                        else {
                                            var out = "";
                                            var ct = 0;
                                            for (s in data) {
                                                if (data[s] == "")
                                                    continue;
                                                out += '
' + data[s] + '
';
                                                ct++;
                                            }
                                            diaerror.show(true, "Traceback of calculation " + calc_id, out);
                                        }
                                        // alert("Success: " + textStatus);
                                    }});
            },

            _show_log_priv: function(is_new, calc_id, is_running, from) {
                var was_running = is_running;

                // TO CHECK hide_log method enable console.log and take a look
                // console.log("_show_log_priv: begin");
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                if (is_new) {
                    if (this.logTimeout != null) {
                        window.clearTimeout(this.logTimeout);
                        this.logTimeout = null;
                    }
                }
                var obj = this;

                this.logXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/log/" + from + ":",
                                      error: function (jqXHR, textStatus, errorThrown) {
                                          if (jqXHR.status == 404) {
                                              diaerror.show(true, "Log of calculation " + calc_id + " not found.");
                                          }
                                          else {
                                              diaerror.show(true, "Error retrieving log for calculation " + calc_id, textStatus);
                                          }
                                          obj.logIsNew = false;
                                      },
                                      success: function (data, textStatus, jqXHR) {
                                          var delay = 250;

                                          if (is_new) {
                                              obj.logLines = 0;
                                              obj.logLinesAll = 0;
                                          }
                                          else {
                                              // if data is empty check if job is still running
                                              if (is_running) {
                                                  if (data.length == 0) {
                                                      var ajax, status;

                                                      delay = 1000;

                                                      ajax = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/status",
                                                                     async: false}).done(function (data) { status = data.is_running; });
                                                      if (status !== true) {
                                                          is_running = false;
                                                      }
                                                  }
                                              }
                                          }
                                          var out = "";

                                          for (s in data) {
                                              if (data[s] == "") {
                                                  obj.logLinesAll++;
                                                  continue;
                                              }
                                              out += '
' + htmlEscape(data[s]) + '
';
                                              obj.logLines++;
                                              obj.logLinesAll++;
                                          }

                                          var title;
                                          if (is_running) {
                                              var dt;
                                              dt = new Date();
                                              title = "Log of calculation " + calc_id + " - " + dt.toString();
                                          }
                                          else if (was_running != is_running) {
                                              title = "Log of calculation " + calc_id + " - finished";
                                          }
                                          else {
                                              title = "Log of calculation " + calc_id;
                                          }

                                          if (obj.logIsNew) {
                                              diaerror.show(true, title, out);
                                          }
                                          else {
                                              diaerror.append(title, out);
                                          }
                                          if ($("#diaerror_scroll_enabled").prop( "checked" ) || was_running == false) {
                                              diaerror.scroll_to_bottom($('.modal-body', diaerror.getdiv()));
                                          }

                                          if (is_running) {
                                              function log_update(obj)
                                              {
                                                  obj._show_log_priv(false, obj.logId, true, obj.logLinesAll);
                                              }

                                              obj.logTimeout = window.setTimeout(log_update, delay, obj);
                                          }
                                          else {
                                              $('#diaerror_scroll_enabled_box').hide();
                                          }

                                          obj.logIsNew = false;
                                      }});
            },

            show_log: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var is_running = ($(e.target).attr('is-running') == "true");

                this.logId = calc_id;
                this.logIsNew = true;

                if (is_running)
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).show();
                else
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).hide();

                this._show_log_priv(true, calc_id, is_running, "0");
            },

            hide_log: function(e) {
                if (this.logTimeout != null) {
                    window.clearTimeout(this.logTimeout);
                    this.logTimeout = null;
                }
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                $('#diaerror_scroll_enabled_box').hide();
            },

            render: function() {
                if (!this.can_be_rendered) {
                    return;
                };
                this.$el.html(_.template($('#calculation-table-template').html(),
                                         { calculations: this.calculations.models }));
            }
        });

    var Calculation = Backbone.Model.extend({
        defaults: {
            map: null,
            layers: []
        }
    });

    var Calculations = Backbone.Collection.extend(
        {
            model: Calculation,
            url: gem_oq_server_url + "/v1/calc/list?relevant=true"
        });
    var calculations = new Calculations();

    var refresh_calcs;

    function setTimer() {
        refresh_calcs = setInterval(function() { calculations.fetch({reset: true}) }, 3000);
    }

    function closeTimer() {
        refresh_calcs = clearInterval(refresh_calcs);
    }

    /* classic event management */
    $(document).ready(
        function() {
            calculation_table = new CalculationTable({ calculations: calculations });
            calculations.fetch({reset: true});
            setTimer();

            /* XXX. Reset the input file value to ensure the change event
               will be always triggered */
            $(document).on("click", 'input[name=archive]',
                           function(e) { this.value = null; });
            $(document).on("change", 'input[name=archive]',
                           function(e) {
                               dialog.show('Uploading calculation', true);
                               var input = $(e.target);
                               var form = input.parents('form')[0];

                               $(form).ajaxSubmit(
                                   {
                                    xhr: function() {  // custom xhr to add progress bar management
                                        var myXhr = $.ajaxSettings.xhr();
                                        if(myXhr.upload){ // if upload property exists
                                            myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                                        }
                                        return myXhr;
                                    },
                                    success: function(data) {
                                        calculations.add(new Calculation(data), {at: 0});
                                    },
                                    error: function(xhr) {
                                        dialog.hide();
                                        var s, out, data = $.parseJSON(xhr.responseText);
                                        var out = "";
                                        var ct = 0;
                                        for (s in data) {
                                            if (data[s] == "")
                                                continue;
                                            out += '
' + data[s] + '
';
                                            ct++;
                                        }
                                        diaerror.show(false, "Calculation not accepted: traceback", out);
                                    }});
                           });

            $(document).on('hidden.bs.modal', 'div[id^=traceback-]',
                           function(e) {
                               setTimer();
                           });

        });
})($, Backbone, _, gem_oq_server_url);
<commit_msg>Changed text for failed removal command<commit_after>/*
 Copyright (C) 2015-2017 GEM Foundation

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/agpl.html>.
 */

(function($, Backbone, _) {
    var calculation_table;

    var progressHandlingFunction = function(progress) {
        var percent = progress.loaded / progress.total * 100;
        $('.bar').css('width', percent + '%');
        if (percent == 100) {
            dialog.hide();
        }
    };

    var htmlEscape = function (record) {
        // record[3] is the log message
        record[3] = record[3].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
        return record
    };

    var dialog = (function ()
                  {
                      var pleaseWaitDiv = $('

Processing...

');
                      return {
                          show: function(msg, progress) {
                              $('h1', pleaseWaitDiv).text(msg);
                              if (progress) {
                                  progressHandlingFunction({loaded: 0, total: 1});
                              } else {
                                  progressHandlingFunction({loaded: 1, total: 1});
                              }
                              pleaseWaitDiv.modal('show');
                          },
                          hide: function () {
                              pleaseWaitDiv.modal('hide');
                          }
                      };
                  })();

    var diaerror = (function ()
                  {
                      var errorDiv = $('
\

\

\

\

Calculation not accepted: traceback
\

\

\

\

\
                      <input type="checkbox" id="diaerror_scroll_enabled" checked>\
                      Auto Scroll   \
                      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\

\

\

\

');
                      errorDiv.bind('hide', function() { calculation_table.hide_log(); });
                      return {
                          getdiv: function() {
                              return errorDiv;
                          },

                          show: function(is_large, title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              if (msg != null) {
                                  $('.modal-body-pre', errorDiv).html(msg);
                              }
                              if (is_large) {
                                  errorDiv.addClass("errorDialogLarge");
                              }
                              else {
                                  errorDiv.removeClass("errorDialogLarge");
                              }
                              errorDiv.modal('show');
                          },

                          append: function(title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              $( msg ).appendTo( $('.modal-body-pre', errorDiv) );
                          },

                          scroll_to_bottom: function(ctx) {
                              ctx.scrollTop(ctx[0].scrollHeight);
                          },

                          hide: function () {
                              errorDiv.modal('hide');
                          }
                      };
                  })();

    var CalculationTable = Backbone.View.extend(
        {
            /* the html element where the table is rendered */
            el: $('#my-calculations'),

            logXhr: null,
            logId: -1,
            logIsNew: false,
            logLinesAll: 0,
            logLines: 0,
            logTimeout: null,

            initialize: function(options) {

                /* whatever happens to any calculation, re-render the table */
                _.bindAll(this, 'render');
                this.calculations = options.calculations;
                this.calculations.bind('reset', this.render);
                this.calculations.bind('add', this.render);
                this.calculations.bind('remove', this.render);

                /* if false, it prevents the table to be refreshed */
                this.can_be_rendered = true;

                this.render();
            },

            events: {
                "click .btn-show-remove": "remove_calculation",
                "click .btn-danger": "show_modal_confirm_remove_calculation",
                "click .btn-hide-remove": "hide_modal_confirm_remove_calculation",
                "click .btn-traceback": "show_traceback",
                "click .btn-log": "show_log",
                "click .btn-file": "on_run_risk_clicked",
                "change .btn-file input": "on_run_risk_queued"
            },

            /* When an input dialog is opened, it is very important to not re-render the table */
            on_run_risk_clicked: function(e) {
                /* if a file input dialog has been opened do not refresh the calc table */
                this.can_be_rendered = false;
            },

            on_run_risk_queued: function(e) {
                this.can_be_rendered = true;
            },

            show_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var show_or_back = (function(e) {
                    this.conf_show = $('#confirmDialog' + calc_id).show();
                    this.back_conf_show = $('.back_confirmDialog' + calc_id).show();
                    closeTimer();
                })();
            },

            hide_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();
            },

            remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var calc_desc = $(e.target).attr('data-calc-desc');
                var view = this;
                diaerror.show(false, "Removing calculation " + calc_id, "...");
                $.post(gem_oq_server_url + "/v1/calc/" + calc_id + "/remove"
                     ).success(
                         function(data, textStatus, jqXHR)
                         {
                             diaerror.show(false, "Calculation removed", "Calculation:
(" + calc_id + ") " + calc_desc + " removed.");
                             view.calculations.remove([view.calculations.get(calc_id)]);
                         }
                     ).error(
                         function(jqXHR, textStatus, errorThrown)
                         {
                             if (jqXHR.status == 404) {
                                 diaerror.show(false, "Removing calculation", "The removal command for:
(" + calc_id + ") " + calc_desc + " is failed.");
                             }
                             else {
                                 diaerror.show(false, "Removing calculation " + calc_id, "Failed: " + textStatus);
                             }
                         }
                     );
                 setTimer();
            },

            show_traceback: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/traceback",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 404) {
                                            diaerror.show(false, "Calculation " + calc_id + " not found.");
                                        }
                                        else {
                                            diaerror.show(false, "Error retrieving traceback for calculation " + calc_id, textStatus);
                                        }
                                        // alert("Error: " + textStatus);
                                    },
                                    success: function (data, textStatus, jqXHR) {
                                        if (data.length == 0) {
                                            diaerror.show(true, "Traceback not found for calculation " + calc_id, []);
                                        }
                                        else {
                                            var out = "";
                                            var ct = 0;
                                            for (s in data) {
                                                if (data[s] == "")
                                                    continue;
                                                out += '
' + data[s] + '
';
                                                ct++;
                                            }
                                            diaerror.show(true, "Traceback of calculation " + calc_id, out);
                                        }
                                        // alert("Success: " + textStatus);
                                    }});
            },

            _show_log_priv: function(is_new, calc_id, is_running, from) {
                var was_running = is_running;

                // TO CHECK hide_log method enable console.log and take a look
                // console.log("_show_log_priv: begin");
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                if (is_new) {
                    if (this.logTimeout != null) {
                        window.clearTimeout(this.logTimeout);
                        this.logTimeout = null;
                    }
                }
                var obj = this;

                this.logXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/log/" + from + ":",
                                      error: function (jqXHR, textStatus, errorThrown) {
                                          if (jqXHR.status == 404) {
                                              diaerror.show(true, "Log of calculation " + calc_id + " not found.");
                                          }
                                          else {
                                              diaerror.show(true, "Error retrieving log for calculation " + calc_id, textStatus);
                                          }
                                          obj.logIsNew = false;
                                      },
                                      success: function (data, textStatus, jqXHR) {
                                          var delay = 250;

                                          if (is_new) {
                                              obj.logLines = 0;
                                              obj.logLinesAll = 0;
                                          }
                                          else {
                                              // if data is empty check if job is still running
                                              if (is_running) {
                                                  if (data.length == 0) {
                                                      var ajax, status;

                                                      delay = 1000;

                                                      ajax = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/status",
                                                                     async: false}).done(function (data) { status = data.is_running; });
                                                      if (status !== true) {
                                                          is_running = false;
                                                      }
                                                  }
                                              }
                                          }
                                          var out = "";

                                          for (s in data) {
                                              if (data[s] == "") {
                                                  obj.logLinesAll++;
                                                  continue;
                                              }
                                              out += '
' + htmlEscape(data[s]) + '
';
                                              obj.logLines++;
                                              obj.logLinesAll++;
                                          }

                                          var title;
                                          if (is_running) {
                                              var dt;
                                              dt = new Date();
                                              title = "Log of calculation " + calc_id + " - " + dt.toString();
                                          }
                                          else if (was_running != is_running) {
                                              title = "Log of calculation " + calc_id + " - finished";
                                          }
                                          else {
                                              title = "Log of calculation " + calc_id;
                                          }

                                          if (obj.logIsNew) {
                                              diaerror.show(true, title, out);
                                          }
                                          else {
                                              diaerror.append(title, out);
                                          }
                                          if ($("#diaerror_scroll_enabled").prop( "checked" ) || was_running == false) {
                                              diaerror.scroll_to_bottom($('.modal-body', diaerror.getdiv()));
                                          }

                                          if (is_running) {
                                              function log_update(obj)
                                              {
                                                  obj._show_log_priv(false, obj.logId, true, obj.logLinesAll);
                                              }

                                              obj.logTimeout = window.setTimeout(log_update, delay, obj);
                                          }
                                          else {
                                              $('#diaerror_scroll_enabled_box').hide();
                                          }

                                          obj.logIsNew = false;
                                      }});
            },

            show_log: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var is_running = ($(e.target).attr('is-running') == "true");

                this.logId = calc_id;
                this.logIsNew = true;

                if (is_running)
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).show();
                else
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).hide();

                this._show_log_priv(true, calc_id, is_running, "0");
            },

            hide_log: function(e) {
                if (this.logTimeout != null) {
                    window.clearTimeout(this.logTimeout);
                    this.logTimeout = null;
                }
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                $('#diaerror_scroll_enabled_box').hide();
            },

            render: function() {
                if (!this.can_be_rendered) {
                    return;
                };
                this.$el.html(_.template($('#calculation-table-template').html(),
                                         { calculations: this.calculations.models }));
            }
        });

    var Calculation = Backbone.Model.extend({
        defaults: {
            map: null,
            layers: []
        }
    });

    var Calculations = Backbone.Collection.extend(
        {
            model: Calculation,
            url: gem_oq_server_url + "/v1/calc/list?relevant=true"
        });
    var calculations = new Calculations();

    var refresh_calcs;

    function setTimer() {
        refresh_calcs = setInterval(function() { calculations.fetch({reset: true}) }, 3000);
    }

    function closeTimer() {
        refresh_calcs = clearInterval(refresh_calcs);
    }

    /* classic event management */
    $(document).ready(
        function() {
            calculation_table = new CalculationTable({ calculations: calculations });
            calculations.fetch({reset: true});
            setTimer();

            /* XXX. Reset the input file value to ensure the change event
               will be always triggered */
            $(document).on("click", 'input[name=archive]',
                           function(e) { this.value = null; });
            $(document).on("change", 'input[name=archive]',
                           function(e) {
                               dialog.show('Uploading calculation', true);
                               var input = $(e.target);
                               var form = input.parents('form')[0];

                               $(form).ajaxSubmit(
                                   {
                                    xhr: function() {  // custom xhr to add progress bar management
                                        var myXhr = $.ajaxSettings.xhr();
                                        if(myXhr.upload){ // if upload property exists
                                            myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                                        }
                                        return myXhr;
                                    },
                                    success: function(data) {
                                        calculations.add(new Calculation(data), {at: 0});
                                    },
                                    error: function(xhr) {
                                        dialog.hide();
                                        var s, out, data = $.parseJSON(xhr.responseText);
                                        var out = "";
                                        var ct = 0;
                                        for (s in data) {
                                            if (data[s] == "")
                                                continue;
                                            out += '
' + data[s] + '
';
                                            ct++;
                                        }
                                        diaerror.show(false, "Calculation not accepted: traceback", out);
                                    }});
                           });

            $(document).on('hidden.bs.modal', 'div[id^=traceback-]',
                           function(e) {
                               setTimer();
                           });

        });
})($, Backbone, _, gem_oq_server_url);
<|endoftext|>


<commit_before>/*
*
* Copyright (C) 2011, The Locker Project
* All rights reserved.
*
* Please see the LICENSE file for more information.
*
*/

var fs = require('fs')
  , request = require('request')
  , auth
  , seenIDs = {}
  , lastBadges = {}
  , newBadges = []
  , badges = []
  ;

exports.sync = function(processInfo, cb) {
    auth = processInfo.auth;
    if (processInfo.config && processInfo.config.badges) {
        lastBadges = processInfo.config.badges;
    }
    exports.syncBadges(function(err) {
        var responseObj = {data : {}, config : {}};
        responseObj.data.badges = newBadges;
        responseObj.config.badges = seenIDs;
        cb(err, responseObj);
    });
};

exports.syncBadges = function (callback) {
    getBadges(auth.accessToken, function(err, resp, data) {
        if(err || !data || !JSON.parse(data).response.badges) return callback("broke" + err);
        //console.log(data.response)
        var badges_json = JSON.parse(data).response.badges;
        if (badges_json === undefined) {
            return callback('error attempting to get profile data - ' + data);
        }
        badges = JSON.stringify(badges_json);
        for (var badge in badges_json) {
            if (badges_json[badge]['unlocks'].length > 0){
                newBadges.push({obj: badges_json[badge], timestamp: Date.now()});
                seenIDs[badges_json[badge].id] = true;
            }
        }

        callback();
    });
}

function getBadges(token, callback) {
    request.get('https://api.foursquare.com/v2/users/self/badges.json?v=20111202&oauth_token=' + token, callback);
}
<commit_msg>removed stray debug<commit_after>/*
*
* Copyright (C) 2011, The Locker Project
* All rights reserved.
*
* Please see the LICENSE file for more information.
*
*/

var fs = require('fs')
  , request = require('request')
  , auth
  , seenIDs = {}
  , lastBadges = {}
  , newBadges = []
  , badges = []
  ;

exports.sync = function(processInfo, cb) {
    auth = processInfo.auth;
    if (processInfo.config && processInfo.config.badges) {
        lastBadges = processInfo.config.badges;
    }
    exports.syncBadges(function(err) {
        var responseObj = {data : {}, config : {}};
        responseObj.data.badges = newBadges;
        responseObj.config.badges = seenIDs;
        cb(err, responseObj);
    });
};

exports.syncBadges = function (callback) {
    getBadges(auth.accessToken, function(err, resp, data) {
        if(err || !data || !JSON.parse(data).response.badges) return callback("broke" + err);
        var badges_json = JSON.parse(data).response.badges;
        if (badges_json === undefined) {
            return callback('error attempting to get badge data - ' + data);
        }
        badges = JSON.stringify(badges_json);
        for (var badge in badges_json) {
            if (badges_json[badge]['unlocks'].length > 0){
                newBadges.push({obj: badges_json[badge], timestamp: Date.now()});
                seenIDs[badges_json[badge].id] = true;
            }
        }

        callback();
    });
}

function getBadges(token, callback) {
    request.get('https://api.foursquare.com/v2/users/self/badges.json?v=20111202&oauth_token=' + token, callback);
}
<|endoftext|>


<commit_before>var PN_GENERATOR =
{
	RandomNoise: function( inCanvas, inX, inY, inWidth, inHeight, inAlpha )
	{
		var g = inCanvas.getContext("2d"),
			imageData = g.getImageData( 0, 0, inCanvas.width, inCanvas.height ),
			random = Math.random,
			pixels = imageData.data;

		for( var i = 0; i < pixels.length; i += 4 )
		{
			pixels[i] = pixels[i+1] = pixels[i+2] = ( random() * 256 ) | 0;
			pixels[i+3] = 255;
		}

		g.putImageData( imageData, 0, 0 );
		return inCanvas;
	},

	PerlinNoise: function( inParameters )
	{
		/**
		 * This part is based on the snippest :
		 * https://gist.github.com/donpark/1796361
		 */

		var noise = this.RandomNoise( TERRAINGEN.CreateCanvas( inParameters.widthSegments, inParameters.heightSegments ) );
		var context = inParameters.canvas.getContext("2d");
		context.save();

		/* Scale random iterations onto the canvas to generate Perlin noise. */
		for( var size = 4; size <= noise.width; size *= inParameters.param )
		{
			var x = ( Math.random() * ( noise.width - size ) ) | 0,
				y = ( Math.random() * ( noise.height - size ) ) | 0;
			context.globalAlpha = 4 / size;
			context.drawImage( noise, x, y, size, size, 0, 0, inParameters.widthSegments, inParameters.heightSegments );
		}

		context.restore();

		return inParameters.canvas;
	},

	Get: function( inParameters )
	{
		var geometry = new THREE.Geometry();

		inParameters.param = Math.max( 1.1, inParameters.param );

		// Create the Perlin Noise
		var noise = this.PerlinNoise( inParameters );

		return noise;
	}
};<commit_msg>Fix an error on the Perlin Noise generator when width != height<commit_after>var PN_GENERATOR =
{
	RandomNoise: function( inCanvas, inX, inY, inWidth, inHeight, inAlpha )
	{
		var g = inCanvas.getContext("2d"),
			imageData = g.getImageData( 0, 0, inCanvas.width, inCanvas.height ),
			random = Math.random,
			pixels = imageData.data;

		for( var i = 0; i < pixels.length; i += 4 )
		{
			pixels[i] = pixels[i+1] = pixels[i+2] = ( random() * 256 ) | 0;
			pixels[i+3] = 255;
		}

		g.putImageData( imageData, 0, 0 );
		return inCanvas;
	},

	PerlinNoise: function( inParameters )
	{
		/**
		 * This part is based on the snippest :
		 * https://gist.github.com/donpark/1796361
		 */

		var noise = this.RandomNoise( TERRAINGEN.CreateCanvas( inParameters.widthSegments, inParameters.heightSegments ) );
		var context = inParameters.canvas.getContext("2d");
		context.save();

		var ratio = inParameters.widthSegments / inParameters.heightSegments;

		/* Scale random iterations onto the canvas to generate Perlin noise. */
		for( var size = 4; size <= noise.height; size *= inParameters.param )
		{
			var x = ( Math.random() * ( noise.width - size ) ) | 0,
				y = ( Math.random() * ( noise.height - size ) ) | 0;
			context.globalAlpha = 4 / size;
			context.drawImage( noise, x, y, size * ratio, size, 0, 0, inParameters.widthSegments, inParameters.heightSegments );
		}

		context.restore();

		return inParameters.canvas;
	},

	Get: function( inParameters )
	{
		var geometry = new THREE.Geometry();

		inParameters.param = Math.max( 1.1, inParameters.param );

		// Create the Perlin Noise
		var noise = this.PerlinNoise( inParameters );

		return noise;
	}
};<|endoftext|>


<commit_before>//=============================================================================
// RTK_Test.js
// The MIT License (MIT)
//=============================================================================

/*:
 * @plugindesc テスト用プラグイン
 * @author lriki
 *
 * @help このプラグインにはプラグインコマンドはありません。
 * テスト用に作成したものなので、実際に利用する場合には適当にリネームしてください
 */

(function(_global) {
    function splitExt(filename) {
        return filename.split(/\.(?=[^.]+$)/);
    }

    //-----------------------------------------------------------------------------
    // Game_Map
    //
    var _Game_Map_setup = Game_Map.prototype.setup;
    Game_Map.prototype.setup = function(mapId) {
        _Game_Map_setup.apply(this, arguments);

        /*
        console.log(this.tileset());
        if (this.tileset()) {
            var tilesetNames = this.tileset().tilesetNames;
            for (var i = 0; i < tilesetNames.length; i++) {

                tokens = tilesetNames[i].split(/\.(?=[^.]+$)/);
                path = 'img/tilesets/' + tokens[0] + '.txt';

                StorageManager.load();

                console.log(path);
                //this._tilemap.bitmaps[i] = ImageManager.loadTileset(tilesetNames[i]);
            }
        }
        */
       // StorageManager.load();
    };

    // ちなみにこれ系の "round" は マップのループ対応のための繰り返し
    Game_Map.prototype.roundXWithDirectionLong = function(x, d, len) {
        var dx = this.roundXWithDirection(x, d);
        for (var i = 0; i < len - 1; i++) {
            dx = this.roundXWithDirection(dx, d);
        }
        return dx;
    };

    Game_Map.prototype.roundYWithDirectionLong = function(y, d, len) {
        var dy = this.roundYWithDirection(y, d);
        for (var i = 0; i < len - 1; i++) {
            dy = this.roundYWithDirection(dy, d);
        }
        return dy;
    };

    // 全方位進入禁止確認
    Game_Map.prototype.checkNotPassageAll = function(x, y) {
        var flags = this.tilesetFlags();
        var tiles = this.allTiles(x, y);
        var bits = 0;
        for (var i = 0; i < tiles.length; i++) {
            var flag = flags[tiles[i]];
            bits |= flag;
        }
        return (bits & 0x0f) == 0x0f;
    };

    // 溝チェック
    Game_Map.prototype.checkGroove = function(x, y) {
        var tiles = this.allTiles(x, y);
        for (var i = 0; i < tiles.length; i++) {
            if (Tilemap.isTileA1(tiles[i])) {
                return true;
            }
        }
        return false;
    }

    //-----------------------------------------------------------------------------
    // Game_CharacterBase
    //

    var _Game_CharacterBase_moveStraight = Game_CharacterBase.prototype.moveStraight;
    Game_CharacterBase.prototype.moveStraight = function(d) {
        _Game_CharacterBase_moveStraight.apply(this, arguments);
        if (!this.isMovementSucceeded()) {
            this.setMovementSuccess(
                this.canPassJumpGroundToGround(this._x, this._y, d) ||
                this.canPassJumpGroove(this._x, this._y, d));
            if (this.isMovementSucceeded()) {
                var x1 = Math.round(this._x);
                var y1 = Math.round(this._y);
                var x2 = Math.round($gameMap.roundXWithDirectionLong(this._x, d, 2));
                var y2 = Math.round($gameMap.roundYWithDirectionLong(this._y, d, 2));
                this.jump(x2 - x1, y2 - y1);
            }
        }
    };

    Game_CharacterBase.prototype.canPassJumpGroundToGround = function(x, y, d) {

        var x1 = Math.round(x);
        var y1 = Math.round(y);
        var x2 = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var y2 = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));
        if (!$gameMap.isValid(x2, y2)) {
            // マップ外
            return false;
        }
        var d2 = this.reverseDir(d);
        if ($gameMap.isPassable(x1, y1, d) || $gameMap.isPassable(x2, y2, d2))
        {
            // 現在位置から移動できるなら崖ではない。
            // 移動先から手前に移動できるなら崖ではない。
            return false;
        }
        if ($gameMap.checkNotPassageAll(x2, y2))
        {
            // 移動先が全方位進入禁止。壁とか。
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            // 移動先にキャラクターがいる
            return false;
        }

        return true;
    }

    Game_CharacterBase.prototype.canPassJumpGroove = function(x, y, d) {
        var x1 = Math.round(x);
        var y1 = Math.round(y);
        var x2 = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var y2 = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));
        var x3 = Math.round($gameMap.roundXWithDirectionLong(x, d, 1));
        var y3 = Math.round($gameMap.roundYWithDirectionLong(y, d, 1));
        if (!$gameMap.isValid(x2, y2)) {
            // マップ外
            return false;
        }
        if (!$gameMap.isPassable(x1, y1, d))
        {
            // 現在位置から移動できない
            return false;
        }
        var d2 = this.reverseDir(d);
        if (!$gameMap.isPassable(x2, y2, d2))
        {
            // 移動先から手前に移動できない
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            // 移動先にキャラクターがいる
            return false;
        }
        if (!$gameMap.checkGroove(x3, y3)) {
            // 目の前のタイルが溝ではない
            return false;
        }
        return true;
    }

    // GS オブジェクトとしての高さ。
    // 高さを持たないのは -1。（GSObject ではない）
    Game_CharacterBase.prototype.gsObjectHeight = function() {
        return -1;
    }

    //-----------------------------------------------------------------------------
    // Game_Event
    //

    var _Game_Event_initialize = Game_Event.prototype.initialize;
    Game_Event.prototype.initialize = function(mapId, eventId) {
        _Game_Event_initialize.apply(this, arguments);

        this._gsObjectHeight = -1;
        this.parseNoteForGSObj(this.event().note);
    }

    Game_CharacterBase.prototype.gsObjectHeight = function() {
        return this._gsObjectHeight;
    }

    Game_Event.prototype.parseNoteForGSObj = function(note) {
        var index = note.indexOf("@GSObj");
        if (index >= 0)
        {
            var block = note.substring(index + 6);
            block = block.substring(
                block.indexOf("{") + 1,
                block.indexOf("}"));

            var nvps = block.split(",");
            for (var i = 0; i < nvps.length; i++) {
                var tokens = block.split(":");
                switch (tokens[0])
                {
                    case "h":
                        this._gsObjectHeight = Number(tokens[1]);
                        break;
                }
            }
        }
    }

})(this);
<commit_msg>jump between ground and object<commit_after>//=============================================================================
// RTK_Test.js
// The MIT License (MIT)
//=============================================================================

/*:
 * @plugindesc テスト用プラグイン
 * @author lriki
 *
 * @help このプラグインにはプラグインコマンドはありません。
 * テスト用に作成したものなので、実際に利用する場合には適当にリネームしてください
 */

(function(_global) {
    function splitExt(filename) {
        return filename.split(/\.(?=[^.]+$)/);
    }

    //-----------------------------------------------------------------------------
    // Game_Map
    //
    var _Game_Map_setup = Game_Map.prototype.setup;
    Game_Map.prototype.setup = function(mapId) {
        _Game_Map_setup.apply(this, arguments);

        /*
        console.log(this.tileset());
        if (this.tileset()) {
            var tilesetNames = this.tileset().tilesetNames;
            for (var i = 0; i < tilesetNames.length; i++) {

                tokens = tilesetNames[i].split(/\.(?=[^.]+$)/);
                path = 'img/tilesets/' + tokens[0] + '.txt';

                StorageManager.load();

                console.log(path);
                //this._tilemap.bitmaps[i] = ImageManager.loadTileset(tilesetNames[i]);
            }
        }
        */
       // StorageManager.load();
    };

    // ちなみにこれ系の "round" は マップのループ対応のための繰り返し
    Game_Map.prototype.roundXWithDirectionLong = function(x, d, len) {
        var dx = this.roundXWithDirection(x, d);
        for (var i = 0; i < len - 1; i++) {
            dx = this.roundXWithDirection(dx, d);
        }
        return dx;
    };

    Game_Map.prototype.roundYWithDirectionLong = function(y, d, len) {
        var dy = this.roundYWithDirection(y, d);
        for (var i = 0; i < len - 1; i++) {
            dy = this.roundYWithDirection(dy, d);
        }
        return dy;
    };

    // 全方位進入禁止確認
    Game_Map.prototype.checkNotPassageAll = function(x, y) {
        var flags = this.tilesetFlags();
        var tiles = this.allTiles(x, y);
        var bits = 0;
        for (var i = 0; i < tiles.length; i++) {
            var flag = flags[tiles[i]];
            bits |= flag;
        }
        return (bits & 0x0f) == 0x0f;
    };

    // 溝チェック
    Game_Map.prototype.checkGroove = function(x, y) {
        var tiles = this.allTiles(x, y);
        for (var i = 0; i < tiles.length; i++) {
            if (Tilemap.isTileA1(tiles[i])) {
                return true;
            }
        }
        return false;
    }

    //-----------------------------------------------------------------------------
    // Game_CharacterBase
    //

    var _Game_CharacterBase_initMembers = Game_CharacterBase.prototype.initMembers;
    Game_CharacterBase.prototype.initMembers = function() {
        _Game_CharacterBase_initMembers.apply(this, arguments);
        this._ridingCharacterId = -1;
        this._ridderCharacterId = -1;
    }

    var _Game_CharacterBase_screenZ = Game_CharacterBase.prototype.screenZ;
    Game_CharacterBase.prototype.screenZ = function() {
        var base = _Game_CharacterBase_screenZ.apply(this, arguments);
        return base + (this.riddingObject() != null ? 5 : 0);
    };

    var _Game_CharacterBase_moveStraight = Game_CharacterBase.prototype.moveStraight;
    Game_CharacterBase.prototype.moveStraight = function(d) {
        if (this.ridding()) {
            // 何かのオブジェクトに乗っている。
            // オリジナルの処理を含め、元の移動処理は行わない。

            if (this.checkJumpObjectToGround(this._x, this._y, d)) {
                this.setMovementSuccess(true);
                this.getOffFromObject();
                this.jumpToDir(d, 2);
            }

            this.setDirection(d);
        }
        else {
            _Game_CharacterBase_moveStraight.apply(this, arguments);
            if (!this.isMovementSucceeded()) {
                this.setMovementSuccess(
                    this.canPassJumpGroundToGround(this._x, this._y, d) ||
                    this.canPassJumpGroove(this._x, this._y, d));

                if (this.isMovementSucceeded()) {
                    this.jumpToDir(d, 2);
                }
                else {
                    this.tryJumpGroundToObject(d);
                }
            }
        }
    };

    Game_CharacterBase.prototype.tryJumpGroundToObject = function(d) {
        var obj = this.checkJumpGroundToObject(this._x, this._y, d);
        this.setMovementSuccess(obj != null);
        if (this.isMovementSucceeded()) {
            // 乗る
            this.rideToObject(obj);
            this.jumpToDir(d, 2);
        }
    };

    // 方向と距離を指定してジャンプ開始
    Game_CharacterBase.prototype.jumpToDir = function(d, len) {
        // x1, y1 は小数点以下を調整しない。ジャンプ後に 0.5 オフセット無くなるようにしたい
        var x1 = this._x;
        var y1 = this._y;
        var x2 = Math.round($gameMap.roundXWithDirectionLong(this._x, d, len));
        var y2 = Math.round($gameMap.roundYWithDirectionLong(this._y, d, len));
        this.jump(x2 - x1, y2 - y1);
    }

    Game_CharacterBase.prototype.canPassJumpGroundToGround = function(x, y, d) {

        var x1 = Math.round(x);
        var y1 = Math.round(y);
        var x2 = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var y2 = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));
        if (!$gameMap.isValid(x2, y2)) {
            // マップ外
            return false;
        }
        var d2 = this.reverseDir(d);
        if ($gameMap.isPassable(x1, y1, d) || $gameMap.isPassable(x2, y2, d2))
        {
            // 現在位置から移動できるなら崖ではない。
            // 移動先から手前に移動できるなら崖ではない。
            return false;
        }
        if ($gameMap.checkNotPassageAll(x2, y2))
        {
            // 移動先が全方位進入禁止。壁とか。
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            // 移動先にキャラクターがいる
            return false;
        }

        return true;
    }

    Game_CharacterBase.prototype.canPassJumpGroove = function(x, y, d) {
        var x1 = Math.round(x);
        var y1 = Math.round(y);
        var x2 = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var y2 = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));
        var x3 = Math.round($gameMap.roundXWithDirectionLong(x, d, 1));
        var y3 = Math.round($gameMap.roundYWithDirectionLong(y, d, 1));
        if (!$gameMap.isValid(x2, y2)) {
            // マップ外
            return false;
        }
        if (!$gameMap.isPassable(x1, y1, d))
        {
            // 現在位置から移動できない
            return false;
        }
        var d2 = this.reverseDir(d);
        if (!$gameMap.isPassable(x2, y2, d2))
        {
            // 移動先から手前に移動できない
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            // 移動先にキャラクターがいる
            return false;
        }
        if (!$gameMap.checkGroove(x3, y3)) {
            // 目の前のタイルが溝ではない
            return false;
        }
        return true;
    }

    // GS オブジェクトとしての高さ。
    // 高さを持たないのは -1。（GSObject ではない）
    Game_CharacterBase.prototype.objectHeight = function() {
        return -1;
    };

    Game_CharacterBase.prototype.canRide = function() {
        return this.objectHeight() >= 0;
    };

    Game_CharacterBase.prototype.ridding = function() {
        return this._ridingCharacterId >= 0;
    };

    // 0:プレイヤー, 1~:イベント
    Game_CharacterBase.prototype.gsObjectId = function() {
        return -1;
    };

    // この人が乗っているオブジェクト
    Game_CharacterBase.prototype.riddingObject = function() {
        if (this._ridingCharacterId < 0) {
            return null;
        }
        else if (this._ridingCharacterId == 0) {
            return $gamePlayer;
        }
        else {
            return $gameMap.event(this._ridingCharacterId);
        }
    };

    // このオブジェクトに乗っている人
    Game_CharacterBase.prototype.rider = function() {
        if (this._ridderCharacterId < 0) {
            return null;
        }
        else if (this._ridderCharacterId == 0) {
            return $gamePlayer;
        }
        else {
            return $gameMap.event(this._ridderCharacterId);
        }
        return null;
    };

    Game_CharacterBase.prototype.checkJumpGroundToObject = function(x, y, d) {
        var x1 = Math.round(x);
        var y1 = Math.round(y);
        // ジャンプ先座標を求める
        var new_x = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var new_y = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));

        if ($gameMap.isPassable(x1, y1, d)) {
            // 現在位置から移動できるなら崖ではない
            return null;
        }

        // 乗れそうなオブジェクトを探す
        var events = $gameMap.events();
        var obj = null;
        for(var i = 0; i < events.length; i++) {
            if(events[i].checkPassRide(new_x, new_y)) {
                obj = events[i];
                break;
            };
        };
        if (obj) {
            return obj;
        }

        return null;
    }

    Game_CharacterBase.prototype.checkJumpObjectToGround = function(x, y, d) {
        // ジャンプ先座標を求める
        var new_x = Math.round($gameMap.roundXWithDirectionLong(x, d, 2));
        var new_y = Math.round($gameMap.roundYWithDirectionLong(y, d, 2));
        var d2 = this.reverseDir(d);
        if ($gameMap.isPassable(new_x, new_y, d2)) {
            // 移動先から手前に移動できるなら崖ではない
            return false;
        }
        if (this.isCollidedWithCharacters(new_x, new_y)) {
            // 移動先にキャラクターがいる
            return false;
        }
        return true;
    }

    // グローバル座標 x, yから見た時、この obj の上に乗れるか
    Game_CharacterBase.prototype.checkPassRide = function(x, y) {
        if (this.canRide() && !this.rider()) {
            var px = Math.round(this._x);
            var py = Math.round(this._y) - this.objectHeight();
            if (x == px && y == py) {
                return true;
            }
        }
        return false;
    };

    Game_CharacterBase.prototype.rideToObject = function(riddenObject) {
        this._ridingCharacterId = riddenObject.gsObjectId();
        riddenObject._ridderCharacterId = this.gsObjectId();
    };

    Game_CharacterBase.prototype.getOffFromObject = function() {
        var obj = this.riddingObject();
        if (obj != null) {
            obj._ridderCharacterId = -1;
        }
        this._ridingCharacterId = -1;
    }

    var _Game_CharacterBase_updateMove = Game_CharacterBase.prototype.updateMove;
    Game_CharacterBase.prototype.updateMove = function() {
        //var oldm = this.isMoving();
        _Game_CharacterBase_updateMove.apply(this, arguments);
        //if (!this.isMoving() && oldm != this.isMoving())
        //{
        //    console.log("stop");
       // }
    };

    //-----------------------------------------------------------------------------
    // Game_Player
    //

    Game_Player.prototype.gsObjectId = function() {
        return 0;
    };

    //-----------------------------------------------------------------------------
    // Game_Event
    //

    var _Game_Event_initialize = Game_Event.prototype.initialize;
    Game_Event.prototype.initialize = function(mapId, eventId) {
        _Game_Event_initialize.apply(this, arguments);

        this._gsObjectHeight = -1;
        this.parseNoteForGSObj(this.event().note);
    };

    Game_Event.prototype.gsObjectId = function() {
        return this.eventId();
    };

    Game_Event.prototype.objectHeight = function() {
        return this._gsObjectHeight;
    };

    Game_Event.prototype.parseNoteForGSObj = function(note) {
        var index = note.indexOf("@GSObj");
        if (index >= 0)
        {
            var block = note.substring(index + 6);
            block = block.substring(
                block.indexOf("{") + 1,
                block.indexOf("}"));

            var nvps = block.split(",");
            for (var i = 0; i < nvps.length; i++) {
                var tokens = block.split(":");
                switch (tokens[0])
                {
                    case "h":
                        this._gsObjectHeight = Number(tokens[1]);
                        break;
                }
            }
        }
    };

})(this);
<|endoftext|>


<commit_before>// Copyright 2014-2015, University of Colorado Boulder

/**
 * General dialog type
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Shape = require( 'KITE/Shape' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Panel = require( 'SUN/Panel' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var joist = require( 'JOIST/joist' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Node} content - The content to display inside the dialog (not including the title)
   * @param {Object} [options]
   * @constructor
   */
  function Dialog( content, options ) {

    var self = this;
    options = _.extend( {

      // Dialog-specific options
      modal: false, // {boolean} modal dialogs prevent interaction with the rest of the sim while open
      title: null, // {Node} title to be displayed at top
      titleAlign: 'center', // horizontal alignment of the title: {string} left, right or center
      titleSpacing: 20, // {number} how far the title is placed above the content
      hasCloseButton: true, // whether to put a close 'X' button is upper-right corner

      // {function} which sets the dialog's position in global coordinates. called as
      // layoutStrategy( dialog, simBounds, screenBounds, scale )
      layoutStrategy: Dialog.DEFAULT_LAYOUT_STRATEGY,

      // pass through to Panel options
      cornerRadius: 10, // {number} radius of the dialog's corners
      resize: true, // {boolean} whether to resize if content's size changes
      fill: 'white', // {string|Color}
      stroke: 'black', // {string|Color}
      backgroundPickable: true,
      xMargin: 20,
      yMargin: 20,
      closeButtonBaseColor: '#d00',
      closeButtonMargin: 5, // {number} how far away should the close button be from the panel border
      tandem: Tandem.tandemRequired(),

      // a11y options
      tagName: 'div',
      ariaRole: 'dialog'
    }, options );

    // @private (read-only)
    this.isModal = options.modal;

    // see https://github.com/phetsims/joist/issues/293
    assert && assert( this.isModal, 'Non-modal dialogs not currently supported' );

    // @private - whether the dialog is showing
    this.isShowing = false;

    var dialogContent = new Node( {
      children: [ content ]
    } );

    if ( options.title ) {

      var titleNode = options.title;
      dialogContent.addChild( titleNode );

      var updateTitlePosition = function() {
        switch( options.titleAlign ) {
          case 'center':
            titleNode.centerX = content.centerX;
            break;
          case 'left':
            titleNode.left = content.left;
            break;
          case 'right':
            titleNode.right = content.right;
            break;
          default:
            throw new Error( 'unknown titleAlign for Dialog: ' + options.titleAlign );
        }
        titleNode.bottom = content.top - options.titleSpacing;
      };

      if ( options.resize ) {
        content.on( 'bounds', updateTitlePosition );
        titleNode.on( 'localBounds', updateTitlePosition );
      }
      updateTitlePosition();
    }

    Panel.call( this, dialogContent, options );

    if ( options.hasCloseButton ) {

      var crossSize = 10;
      var crossNode = new Path( new Shape().moveTo( 0, 0 ).lineTo( crossSize, crossSize ).moveTo( 0, crossSize ).lineTo( crossSize, 0 ), {
        stroke: '#fff',
        lineWidth: 3
      } );

      var closeButton = new RectangularPushButton( {
        content: crossNode,
        baseColor: options.closeButtonBaseColor,
        xMargin: 5,
        yMargin: 5,
        listener: function() {
          self.hide();
        },
        tandem: options.tandem && options.tandem.createTandem( 'closeButton' )
      } );
      this.addChild( closeButton );

      var updateClosePosition = function() {
        closeButton.right = dialogContent.right + options.xMargin - options.closeButtonMargin;
        closeButton.top = dialogContent.top - options.xMargin + options.closeButtonMargin;
      };

      //TODO memory leak, see https://github.com/phetsims/joist/issues/357
      if ( options.resize ) {
        dialogContent.on( 'bounds', updateClosePosition );
        if ( options.title ) {
          options.title.on( 'bounds', updateClosePosition );
        }
      }
      updateClosePosition();
    }

    var sim = window.phet.joist.sim;

    // @private
    this.updateLayout = function() {
      options.layoutStrategy( self, sim.boundsProperty.value, sim.screenBoundsProperty.value, sim.scaleProperty.value );
    };

    this.updateLayout();

    // @private
    this.sim = sim;

    // a11y - set the order of content for accessibility, title before content
    this.accessibleOrder = [ titleNode, dialogContent ];

    // a11y - set the aria labelledby and describedby relations so that whenever focus enters the dialog, the title
    // and description content are read in full
    content.domElement && this.setAriaDescribedByElement( content.domElement );
    if ( options.title ) {
      options.title.domElement && this.setAriaLabelledByElement( options.title.domElement );
    }
  }

  joist.register( 'Dialog', Dialog );

  // @private
  Dialog.DEFAULT_LAYOUT_STRATEGY = function( dialog, simBounds, screenBounds, scale ) {

    // The size is set in the Sim.topLayer, but we need to update the location here
    dialog.center = simBounds.center.times( 1.0 / scale );
  };

  return inherit( Panel, Dialog, {

    // @public
    show: function() {
      if ( !this.isShowing ) {
        window.phet.joist.sim.showPopup( this, this.isModal );
        this.isShowing = true;
        this.sim.resizedEmitter.addListener( this.updateLayout );

        // a11y - hide all ScreenView content from assistive technology when the dialog is shown
        this.setAccessibleViewsHidden( true );

        // In case the window size has changed since the dialog was hidden, we should try layout out again.
        // See https://github.com/phetsims/joist/issues/362
        this.updateLayout();
      }
    },

    // @public
    hide: function() {
      if ( this.isShowing ) {
        window.phet.joist.sim.hidePopup( this, this.isModal );
        this.isShowing = false;
        this.sim.resizedEmitter.removeListener( this.updateLayout );

        // a11y - when the dialog is hidden, unhide all ScreenView content from assistive technology
        this.setAccessibleViewsHidden( false );
      }
    },

    /**
     * Hide or show all accessible content related to the sim ScreenViews.
     *
     * @param  {boolean} hidden
     */
    setAccessibleViewsHidden: function( hidden ) {
      for ( var i = 0; i < this.sim.screens.length; i++ ) {
        this.sim.screens[ i ].view.accessibleHidden = hidden;
      }
    }
  } );
} );<commit_msg>restore focus to active element when dialog closes, see phetsims/john-travoltage#127<commit_after>// Copyright 2014-2015, University of Colorado Boulder

/**
 * General dialog type
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Shape = require( 'KITE/Shape' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Panel = require( 'SUN/Panel' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var joist = require( 'JOIST/joist' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Node} content - The content to display inside the dialog (not including the title)
   * @param {Object} [options]
   * @constructor
   */
  function Dialog( content, options ) {

    var self = this;
    options = _.extend( {

      // Dialog-specific options
      modal: false, // {boolean} modal dialogs prevent interaction with the rest of the sim while open
      title: null, // {Node} title to be displayed at top
      titleAlign: 'center', // horizontal alignment of the title: {string} left, right or center
      titleSpacing: 20, // {number} how far the title is placed above the content
      hasCloseButton: true, // whether to put a close 'X' button is upper-right corner

      // {function} which sets the dialog's position in global coordinates. called as
      // layoutStrategy( dialog, simBounds, screenBounds, scale )
      layoutStrategy: Dialog.DEFAULT_LAYOUT_STRATEGY,

      // pass through to Panel options
      cornerRadius: 10, // {number} radius of the dialog's corners
      resize: true, // {boolean} whether to resize if content's size changes
      fill: 'white', // {string|Color}
      stroke: 'black', // {string|Color}
      backgroundPickable: true,
      xMargin: 20,
      yMargin: 20,
      closeButtonBaseColor: '#d00',
      closeButtonMargin: 5, // {number} how far away should the close button be from the panel border
      tandem: Tandem.tandemRequired(),

      // a11y options
      tagName: 'div',
      ariaRole: 'dialog'
    }, options );

    // @private (read-only)
    this.isModal = options.modal;

    // see https://github.com/phetsims/joist/issues/293
    assert && assert( this.isModal, 'Non-modal dialogs not currently supported' );

    // @private - whether the dialog is showing
    this.isShowing = false;

    var dialogContent = new Node( {
      children: [ content ]
    } );

    if ( options.title ) {

      var titleNode = options.title;
      dialogContent.addChild( titleNode );

      var updateTitlePosition = function() {
        switch( options.titleAlign ) {
          case 'center':
            titleNode.centerX = content.centerX;
            break;
          case 'left':
            titleNode.left = content.left;
            break;
          case 'right':
            titleNode.right = content.right;
            break;
          default:
            throw new Error( 'unknown titleAlign for Dialog: ' + options.titleAlign );
        }
        titleNode.bottom = content.top - options.titleSpacing;
      };

      if ( options.resize ) {
        content.on( 'bounds', updateTitlePosition );
        titleNode.on( 'localBounds', updateTitlePosition );
      }
      updateTitlePosition();
    }

    Panel.call( this, dialogContent, options );

    if ( options.hasCloseButton ) {

      var crossSize = 10;
      var crossNode = new Path( new Shape().moveTo( 0, 0 ).lineTo( crossSize, crossSize ).moveTo( 0, crossSize ).lineTo( crossSize, 0 ), {
        stroke: '#fff',
        lineWidth: 3
      } );

      var closeButton = new RectangularPushButton( {
        content: crossNode,
        baseColor: options.closeButtonBaseColor,
        xMargin: 5,
        yMargin: 5,
        listener: function() {
          self.hide();
        },
        tandem: options.tandem && options.tandem.createTandem( 'closeButton' )
      } );
      this.addChild( closeButton );

      var updateClosePosition = function() {
        closeButton.right = dialogContent.right + options.xMargin - options.closeButtonMargin;
        closeButton.top = dialogContent.top - options.xMargin + options.closeButtonMargin;
      };

      //TODO memory leak, see https://github.com/phetsims/joist/issues/357
      if ( options.resize ) {
        dialogContent.on( 'bounds', updateClosePosition );
        if ( options.title ) {
          options.title.on( 'bounds', updateClosePosition );
        }
      }
      updateClosePosition();
    }

    var sim = window.phet.joist.sim;

    // @private
    this.updateLayout = function() {
      options.layoutStrategy( self, sim.boundsProperty.value, sim.screenBoundsProperty.value, sim.scaleProperty.value );
    };

    this.updateLayout();

    // @private
    this.sim = sim;

    // a11y - set the order of content for accessibility, title before content
    this.accessibleOrder = [ titleNode, dialogContent ];

    // a11y - set the aria labelledby and describedby relations so that whenever focus enters the dialog, the title
    // and description content are read in full
    content.domElement && this.setAriaDescribedByElement( content.domElement );
    if ( options.title ) {
      options.title.domElement && this.setAriaLabelledByElement( options.title.domElement );
    }

    // @private (a11y) - the active element when the dialog is shown, tracked so that focus can be restored on hidden
    this.activeElement = null;
  }

  joist.register( 'Dialog', Dialog );

  // @private
  Dialog.DEFAULT_LAYOUT_STRATEGY = function( dialog, simBounds, screenBounds, scale ) {

    // The size is set in the Sim.topLayer, but we need to update the location here
    dialog.center = simBounds.center.times( 1.0 / scale );
  };

  return inherit( Panel, Dialog, {

    // @public
    show: function() {
      if ( !this.isShowing ) {
        window.phet.joist.sim.showPopup( this, this.isModal );
        this.isShowing = true;
        this.sim.resizedEmitter.addListener( this.updateLayout );

        // a11y - hide all ScreenView content from assistive technology when the dialog is shown
        this.setAccessibleViewsHidden( true );

        // a11y - store the currently active element
        this.activeElement = document.activeElement;

        // In case the window size has changed since the dialog was hidden, we should try layout out again.
        // See https://github.com/phetsims/joist/issues/362
        this.updateLayout();
      }
    },

    // @public
    hide: function() {
      if ( this.isShowing ) {
        window.phet.joist.sim.hidePopup( this, this.isModal );
        this.isShowing = false;
        this.sim.resizedEmitter.removeListener( this.updateLayout );

        // a11y - when the dialog is hidden, unhide all ScreenView content from assistive technology
        this.setAccessibleViewsHidden( false );

        // a11y - restore focus to the active element
        this.activeElement && this.activeElement.focus();
      }
    },

    /**
     * Hide or show all accessible content related to the sim ScreenViews and navigation bar.
     *
     * @param {boolean} hidden
     */
    setAccessibleViewsHidden: function( hidden ) {
      for ( var i = 0; i < this.sim.screens.length; i++ ) {
        this.sim.screens[ i ].view.accessibleHidden = hidden;
      }

      this.sim.navigationBar.accessibleHidden = hidden;
    }
  } );
} );<|endoftext|>


<commit_before>/**
 * Simplified Chinese translation for bootstrap-datepicker
 * Yuan Cheung <advanimal@gmail.com>
 */
;(function($){
	$.fn.datepicker.dates['zh-CN'] = {
		days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
		daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
		daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
		months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		today: "今日",
		format: "yyyy年mm月dd日",
		weekStart: 1
	};
}(jQuery));
<commit_msg>Add clear zh-CN translation<commit_after>/**
 * Simplified Chinese translation for bootstrap-datepicker
 * Yuan Cheung <advanimal@gmail.com>
 */
;(function($){
	$.fn.datepicker.dates['zh-CN'] = {
		days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
		daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
		daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
		months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		today: "今日",
		format: "yyyy年mm月dd日",
		weekStart: 1,
		clear: "清空"
	};
}(jQuery));
<|endoftext|>


<commit_before>/**
 * 手机端通用js文件
 * @param {Object} txt
 */

function alertMsg(txt){
	var ele = $("#alertMsg-mobile");
	if(ele.length == 0){

		$alert = $('

');
		$("body").append($alert);
		ele = $("#alertMsg-mobile");
	}
	if(txt){
		$(".am-modal-bd",ele).html(txt);
	}else{
		return ;
//		$(".am-modal-bd",ele).text(txt);
	}

	ele.modal("open");

	setTimeout(function(){
		ele.modal("close");
	},2500);

}

function loadingMsg(txt){
	var ele = $("#loading-mobile");
	if(ele.length == 0){

		$alert = $('

');
		$("body").append($alert);
		ele = $("#loading-mobile");
	}

//	if(txt){
//		$(".am-modal-hd",ele).text(txt);
//	}else{
//		return ;
//		$(".am-modal-bd",ele).text(txt);
//	}

	ele.modal("open");
	return ele;
//	setTimeout(function(){
//	},2500);

}

/**
 *
 * @param {Object} data {content:"文字",action:"回调函数"}
 */
function confirmMsg(data){
	var ele = $("#confirm-mb");
	if(ele.length == 0){
		$confirm = $('

你，确定要进行此操作吗？

取消确定

');
		$("body").append($confirm);
		ele = $("#confirm-mb");
		ele.on('closed.modal.amui', function() {
			$(this).removeData('amui.modal');
		});

	}

	var $confirmBtn = ele.find('[data-am-modal-confirm]');
	var $cancelBtn = ele.find('[data-am-modal-cancel]');
	$confirmBtn.off('click.confirm.modal.amui').unbind('click');
	$confirmBtn.off('click.confirm.modal.amui').bind('click', function() {
			// do something
    		data.action && data.action.apply(this,[data.relatedTarget]);
	});
	if(data.content){
		$(".am-modal-bd",ele).text(data.content);
	}
//	console.log(data);

    ele.modal("open");

//	setTimeout(function(){
		//$(".am-modal-hd",ele).modal("close");
//	},2500);
}

$(window).load(function() {
	$("body").addClass("domloaded")
//	setTimeout(function(){},1300);
	if($.AMUI && $.AMUI.progress){
		$.AMUI.progress.done();
	}
});

$(function() {
		if($.AMUI && $.AMUI.progress){
			$.AMUI.progress.start();//.start();
		}
		//nprogress
		$(document).ajaxStart(function() {
			if($.AMUI && $.AMUI.progress){
				$.AMUI.progress.start();
			}
		}).ajaxStop(function() {
			if($.AMUI && $.AMUI.progress){
				$.AMUI.progress.done();
			}
		}).ajaxComplete(function() {
			if($.AMUI && $.AMUI.progress){
				$.AMUI.progress.inc();
			}
		});

		$('.ajax-get').click(function() {
//			console.log("ajax-get");
			var target, query, form;
			var that = this;
			var need_confirm = false;
			query = {};
			if ($(that).attr("href") !== undefined || $(that).attr('data-href') !== undefined) {
				target = $(that).attr('href') || $(that).attr("data-href");
			}

//			target = $(that).attr("href");
//			console.log(target,that);
			if ($(that).hasClass('confirm')) {
				confirmMsg({
					relatedTarget:that,
					content: '确认要执行该操作吗',
					action: function() {
						console.log(arguments);
						var target = $(that).attr('href') || $(that).attr("data-href");
						ajaxpost(this, target, {});
					}
				});

			} else {
				ajaxpost(that, target, query);
			}
			return false;
		}); //END ajax-get

		//依赖jquery，scojs,
		//ajax post submit请求
		$('.ajax-post').click(function() {
			console.log("ajax-post");
			var target, query, form;
			var target_form = $(this).attr('target-form');
			var that = this;
			var need_confirm = false;
			if (($(this).attr('type') == 'submit') || (target = $(this).attr('href')) || (target = $(this).attr('url'))) {
				form = $('.' + target_form);

				if ($.validator && (form.hasClass("validate-form") || form.hasClass("validateForm"))) {
					if (!form.valid()) {
						alertMsg('表单验证不通过！');
						return false;
					}
				}

				if ($(this).attr('hide-data') === 'true') {
					//以隐藏数据作为参数
					form = $('.hide-data');
					query = form.serialize();
				} else if (form.get(0) == undefined) {
					return false;
				} else if (form.get(0).nodeName == 'FORM') {
					if ($(this).attr('url') !== undefined || $(this).attr("href") !== undefined) {
						target = $(this).attr('url') || $(this).attr("href");
					} else {
						target = form.get(0).action;
					}
					query = form.serialize();

				} else {

					query = form.find('input,select,textarea').serialize();

				}

			}

			if ($(this).hasClass('confirm')) {
				console.log("confirm");
				confirmMsg({
					content: '确认要执行该操作吗',
					action: function() {
						ajaxpost(that, target, query);
					}
				});

			} else {
				ajaxpost(that, target, query);
			}
			return false;
		}); //END ajax-post

		function ajaxpost(that, target, query) {
//			$(that).button("loading");

			var ele = loadingMsg("请求中...");
			$.post(target, query).always(function() {
				ele.modal("close");
//				setTimeout(function() {
//					$(that).button("reset");
//				}, 1400);
			}).done(function(data) {
				if (data.status == 1) {
					if (data.url) {
						alertMsg(data.info + '
页面即将自动跳转~');
					} else {
						alertMsg(data.info);
					}

					setTimeout(function() {
						if (data.url) {
							location.href = data.url;
						} else if ($(that).hasClass('no-refresh')) {
							//不刷新
						} else {
							location.reload();
						}
					}, 1500);
				} else {

					alertMsg(data.info);
					setTimeout(function() {
						if (data.url) {
							location.href = data.url;
						} else {}
					}, 1500);
				}
			}).fail(function(){
				alertMsg("操作失败！");
			});
		}

		//get 请求
		//ajax get请求

		/**
		 * 绑定ajax-get 操作
		 * @param {Object} selector 标签选择器jquery支持格式
		 */
		function bindAjaxGet(selector){
			var selector = selector || ".ajax-get";
			$(selector).click(function(ev) {
				console.log("ajax-get");
				ev.preventDefault();
				ajaxgetHandler(this);
			});
			$(selector).on("tap",function(ev){
				console.log("ajax-get");
				ev.preventDefault();
				ajaxgetHandler(this);
			})
		}

		function ajaxgetHandler(that){
			var target;
			var content = $(that).attr("data-tip") || "确认要执行该操作吗";
			if ((target = $(that).attr('href')) || (target = $(that).attr('url'))) {

				if ($(that).hasClass('confirm')) {
					confirmMsg({
						content: content,
						action: function() {
							ajaxget(that, target);
						}
					});
				}else{
					ajaxget(that, target);
				}
			}
			return false;
		}

		function ajaxget(that, target) {
//				$(that).button("loading");
				var ele = loadingMsg("请求中...");
				$.get(target).always(function() {
//					;
//					setTimeout(function(){
						ele.modal("hide");
//					},1400);
				}).success(function(data) {
					if (data.status == 1) {
						if (data.url) {
							alertMsg(data.info + '
页面即将自动跳转~');
						} else {
							alertMsg(data.info);
						}
						setTimeout(function() {
							if (data.url) {
								location.href = data.url;
								} else if ($(that).hasClass('no-refresh')) {
							} else {
								location.reload();
							}
						}, 1500);
					} else {
						alertMsg(data.info);
						setTimeout(function() {
							if (data.url) {
								location.href = data.url;
							} else {

							}
						}, 1500);
					}
			});
	}//END ajaxget function
	bindAjaxGet();

	window.hbd_mobile = {
		rebindAjaxGet:bindAjaxGet //针对插入的ajax-get 标签 ，需要手动调用绑定

	};

}) //end $.ready

<commit_msg>更新mobile.JS 文件<commit_after>/**
 * 2015 12 22
 * @author 老胖子-何必都 <hebiduhebi@126.com>
 * @param txt
 */
function alertMsg(txt){
    var ele = $("#alertMsg-mobile");
    if(ele.length == 0){

        $alert = $('

');
        $("body").append($alert);
        ele = $("#alertMsg-mobile");
    }
    if(txt){
        $(".am-modal-bd",ele).html(txt);
    }else{
        return ;
//		$(".am-modal-bd",ele).text(txt);
    }

    ele.modal("open");

    setTimeout(function(){
        ele.modal("close");
    },2000);

}

function loadingMsg(txt){
    var ele = $("#loading-mobile");
    if(ele.length == 0){

        $alert = $('

');
        $("body").append($alert);
        ele = $("#loading-mobile");
    }

    ele.modal("open");
    return ele;

}

/**
 *
 * @param {Object} data {content:"文字",action:"回调函数"}
 */
function confirmMsg(data){
    var ele = $("#confirm-mb");
    if(ele.length == 0){
        $confirm = $('

你，确定要进行此操作吗？

取消确定

');
        $("body").append($confirm);
        ele = $("#confirm-mb");
        ele.on('closed.modal.amui', function() {
            $(this).removeData('amui.modal');
        });

    }

    var $confirmBtn = ele.find('[data-am-modal-confirm]');
    var $cancelBtn = ele.find('[data-am-modal-cancel]');
    $confirmBtn.off('click.confirm.modal.amui').unbind('click');
    $confirmBtn.off('click.confirm.modal.amui').bind('click', function() {
        // do something
        data.action && data.action.apply(this,[data.relatedTarget]);
    });
    if(data.content){
        $(".am-modal-bd",ele).text(data.content);
    }
//	console.log(data);

    ele.modal("open");

//	setTimeout(function(){
    //$(".am-modal-hd",ele).modal("close");
//	},2500);
}

$(window).load(function() {
    $("body").addClass("domloaded")
//	setTimeout(function(){},1300);
    $.AMUI.progress.done();
});

$(function() {
    $.AMUI.progress.start();//.start();
    //nprogress
    $(document).ajaxStart(function() {
        $.AMUI.progress.start();
    }).ajaxStop(function() {
        $.AMUI.progress.done();
    }).ajaxComplete(function() {
        $.AMUI.progress.inc();
    });

    $('.ajax-get').click(function() {
//			console.log("ajax-get");
        var target, query, form;
        var that = this;
        var need_confirm = false;
        query = {};
        if ($(that).attr("href") !== undefined || $(that).attr('data-href') !== undefined) {
            target = $(that).attr('href') || $(that).attr("data-href");
        }

//			target = $(that).attr("href");
//			console.log(target,that);
        if ($(that).hasClass('confirm')) {
            var text = $(that).data('confirm-text');
            confirmMsg({
                relatedTarget:that,
                content: (text || '确认要执行该操作吗?'),
                action: function() {
                    console.log(arguments);
                    var target = $(that).attr('href') || $(that).attr("data-href");
                    ajaxpost(this, target, {});
                }
            });

        } else {
            ajaxpost(that, target, query);
        }
        return false;
    }); //END ajax-get

    //依赖jquery，scojs,
    //ajax post submit请求
    $('.ajax-post').click(function(ev) {
        //console.log("ajax-post");
        var target, query, form;
        var target_form = $(this).attr('target-form');
        var that = this;
        var need_confirm = false;
        if (($(this).attr('type') == 'submit') || (target = $(this).attr('href')) || (target = $(this).attr('url'))) {
            form = $('.' + target_form);

            if ($.validator && (form.hasClass("validate-form") || form.hasClass("validateForm"))) {
                if (!form.valid()) {
                    alertMsg('表单验证不通过！');
                    return false;
                }
            }

            if ($(this).attr('hide-data') === 'true') {
                //以隐藏数据作为参数
                form = $('.hide-data');
                query = form.serialize();
            } else if (form.get(0) == undefined) {
                return false;
            } else if (form.get(0).nodeName == 'FORM') {
                if ($(this).attr('url') !== undefined || $(this).attr("href") !== undefined) {
                    target = $(this).attr('url') || $(this).attr("href");
                } else {
                    target = form.get(0).action;
                }
                query = form.serialize();

            } else {

                query = form.find('input,select,textarea').serialize();

            }

        }

        if ($(this).hasClass('confirm')) {
            //console.log("confirm");
            confirmMsg({
                content: '确认要执行该操作吗',
                action: function() {
                    ajaxpost(that, target, query,ev);
                }
            });

        } else {
            ajaxpost(that, target, query,ev);
        }
        return false;
    }); //END ajax-post

    function ajaxpost(that, target, query,ev) {
//			$(that).button("loading");
        console.log(that);
        //var ele = loadingMsg("请求中...");
        $(that).button('loading');
        var funcname =  $(that).data("when-done");
        $.post(target, query).always(function() {
            //ele.modal("close");
            setTimeout(function() {
                $(that).button("reset");
            }, 1400);
        }).done(function(data) {

            if (data.status == 1) {
                if(!$(that).data('no-alert')){
                    if (data.url) {
                        alertMsg(data.info + '
页面即将自动跳转~');
                    } else {
                        alertMsg(data.info);
                    }

                    setTimeout(function() {
                        if (data.url) {
                            location.href = data.url;
                        } else if ($(that).hasClass('no-refresh') || $(that).data('no-refresh')) {
                            //不刷新
                        } else {
                            location.reload();
                        }
                    }, 1500);
                }else{
                    if(funcname && funcname in window) {//判断是否是函数名
                        window[funcname](ev);
                    }
                    if (data.url) {
                        location.href = data.url;
                    }else if ($(that).data('no-refresh')) {
                        //不刷新
                    }else{
                        location.reload();
                    }
                }
            } else {

                alertMsg(data.info);
                setTimeout(function() {
                    if (data.url) {
                        location.href = data.url;
                    } else {}
                }, 1500);
            }
        }).fail(function(){
            alertMsg("操作失败！");
        });
    }

}) //end $.ready

<|endoftext|>