<commit_before>var AddProjectDialog = Backbone.View.extend({
    projectsPanel : null,
    addProjectDialog : null,
    userMultiSelect : null,
    projectMultiSelectAlreadyLoad : false,
    initialize: function(options) {
        this.container = options.container;
        this.projectsPanel = options.projectsPanel;
        this.ontologies = options.ontologies;
        _.bindAll(this, 'render');
    },
    render : function() {
        var self = this;
        require([
            "text!application/templates/project/ProjectAddDialog.tpl.html",
            "text!application/templates/project/OntologiesChoicesRadio.tpl.html",
            "text!application/templates/project/DisciplinesChoicesRadio.tpl.html",
            "text!application/templates/project/UsersChoices.tpl.html"
        ],
                function(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl, usersChoicesTpl) {
                    self.doLayout(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl,usersChoicesTpl);
                });
        return this;
    },
    doLayout : function(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl, usersChoicesTpl) {
        var self = this;
        var dialog = _.template(projectAddDialogTpl, {});
        $("#editproject").replaceWith("");
        $("#addproject").replaceWith("");
        $(self.el).append(dialog);

        self.initStepy();
        self.createProjectInfo(ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl);
        self.createUserList();
        self.createRetrievalProject();

        //Build dialog
        self.addProjectDialog = $("#addproject").modal({
            keyboard : true,
            backdrop : false
        });
        $("#saveProjectButton").click(function(){$("#login-form-add-project").submit();return false;});
        $("#closeAddProjectDialog").click(function(){$("#addproject").modal('hide');$("#addproject").remove();return false;});
        self.open();
        return this;
    },
    initStepy : function() {
        $('#login-form-add-project').stepy({next: function(index) {
             //check validate name
            var error = false;
             if(index==2) {
                 if($("#project-name").val().toUpperCase().trim()=="") {
                     window.app.view.message("User", "You must provide a valide project name!", "error");
                     error = true;
                 }
                 console.log($("#projectontology").val());
                 if($("#projectontology").val()==undefined) {
                     window.app.view.message("Ontology", "You must provide a ontology name!", "error");
                     error = true;
                 }
                 return !error;
             }
             //show save button on last step
             if(index==$("#login-form-add-project").find("fieldset").length) $("#saveProjectButton").show();
          }, back: function(index) {
            //hide save button if not on last step
            if(index!=$("#login-form-add-project").find("fieldset").length) $("#saveProjectButton").hide();
          }});
        $("fieldset").find("a.button-next").css("float","right");
        $("fieldset").find("a.button-back").css("float","left");
        $("fieldset").find("a").removeClass("button-next");
        $("fieldset").find("a").removeClass("button-back");
        $("fieldset").find("a").addClass("btn btn-primary");
    },
    createProjectInfo : function(ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl) {
        var self = this;
        $("#login-form-add-project").submit(function () {self.createProject(); return false;});
        $("#login-form-add-project").find("input").keydown(function(e){
            if (e.keyCode == 13) { //ENTER_KEY
                $("#login-form-add-project").submit();
                return false;
            }
        });

        $("#projectdiscipline").empty();
        var choice = _.template(disciplinesChoicesRadioTpl, {id:-1,name:"*** Undefined ***"});
        $("#projectdiscipline").append(choice);
        window.app.models.disciplines.each(function(discipline){
            var choice = _.template(disciplinesChoicesRadioTpl, {id:discipline.id,name:discipline.get("name")});
            $("#projectdiscipline").append(choice);
        });
        $("#projectontology").empty();
        self.ontologies.fetch({
            success : function (collection, response) {
                collection.each(function(ontology){
                    var choice = _.template(ontologiesChoicesRadioTpl, {id:ontology.id,name:ontology.get("name")});
                    $("#projectontology").append(choice);
                });
                $("#projectontology").find("option:selected").removeAttr("selected");
            }
        });

        $("#createOntologyWithProjectName").click(function(evt) {

            //create ontology
            var projectName = $("#project-name").val().toUpperCase().trim();
            var ontology = new OntologyModel({name : projectName}).save({name : projectName},{
                    success: function (model, response) {
                        window.app.view.message("Ontology", response.message, "success");
                        var id = response.ontology.id;
                        window.app.models.ontologies.add(model);

                        var choice = _.template(ontologiesChoicesRadioTpl, {id:id,name:model.get("name")});
                        $("#projectontology").prepend(choice);
                        $("#projectontology").val(id);

                    },
                    error: function (model, response) {
                        var json = $.parseJSON(response.responseText);
                        window.app.view.message("Ontology", json.errors, "error");
                    }
                }
            );

        })
    },
    createUserList : function () {
        /* Create Users List */
        $("#projectuser").empty();
        window.app.models.users.each(function(user) {

            if(user.id==window.app.status.user.id) {
                $("#projectuser").append('<option value="'+user.id+'" selected="selected">'+user.prettyName()+'</option>');
            } else $("#projectuser").append('<option value="'+user.id+'">'+user.prettyName()+'</option>');
        });

        $("#projectuser").multiselectNext({
            deselected: function(event, ui) {
                //lock current user (cannot be deselected
                if($(ui.option).val()==window.app.status.user.id)  {
                    $("#projectuser").multiselectNext('select', $(ui.option).text());
                    window.app.view.message("User", "You must be in user list of your project!", "error");
                }
            },
            selected: function(event, ui) {
                //alert($(ui.option).val() + " has been selected");
            }});

        $("div.ui-multiselect").find("ul.available").css("height","150px");
        $("div.ui-multiselect").find("ul.selected").css("height","150px");
        $("div.ui-multiselect").find("input.search").css("width","75px");

        $("div.ui-multiselect").find("div.actions").css("background-color","#DDDDDD");

        console.log("window.app.status.user.model.prettyName()="+window.app.status.user.model.prettyName());
        $("#projectuser").multiselectNext('select',window.app.status.user.model.prettyName());
    },
    createRetrievalProject : function() {
        var self = this;
        $("input#retrievalProjectSome,input#retrievalProjectAll,input#retrievalProjectNone").change(function() {
                if($("input#retrievalProjectSome").is(':checked')) {
                    if(!self.projectMultiSelectAlreadyLoad) {
                        self.createRetrievalProjectSelect();
                        self.projectMultiSelectAlreadyLoad = true
                    } else {
                        console.log("Show");
                        $("div#retrievalGroup").find(".ui-multiselect").show();
                    }
                } else {
                    console.log("Hide");
                    $("div#retrievalGroup").find(".ui-multiselect").hide();
                }
         });

        $("input#project-name").change(function() {
                console.log("change");
                if(self.projectMultiSelectAlreadyLoad) {
                    self.createRetrievalProjectSelect();
                }
         });

        $("#projectontology").change(function() {
                console.log("change");
                if(self.projectMultiSelectAlreadyLoad) {
                    self.createRetrievalProjectSelect();
                }
         });
    },
    createRetrievalProjectSelect : function () {
        /* Create Users List */
        $("#retrievalproject").empty();

        var projectName = $("input#project-name").val();
        var idOntology = $("select#projectontology").val();

        window.app.models.projects.each(function(project) {
            if(project.get('ontology')==idOntology)
                $("#retrievalproject").append('<option value="'+project.id+'">'+project.get('name')+'</option>');
        });
        $("#retrievalproject").append('<option value="-1" selected="selected">'+projectName+'</option>');

        $("#retrievalproject").multiselectNext( 'destroy' );
        $("#retrievalproject").multiselectNext({
            selected: function(event, ui) {
                //alert($(ui.option).val() + " has been selected");
            }});

        $("div.ui-multiselect").find("ul.available").css("height","150px");
        $("div.ui-multiselect").find("ul.selected").css("height","150px");
        $("div.ui-multiselect").find("input.search").css("width","75px");

        $("div.ui-multiselect").find("div.actions").css("background-color","#DDDDDD");
    },
    refresh : function() {
    },
    open: function() {
        var self = this;
        self.clearAddProjectPanel();
        $("#addproject").modal('show');
    },
    clearAddProjectPanel : function() {
        var self = this;
        $("#errormessage").empty();
        $("#projecterrorlabel").hide();
        $("#project-name").val("");

        $(self.addProjectCheckedOntologiesRadioElem).attr("checked", false);
        $(self.addProjectCheckedDisciplinesRadioElem).attr("checked", false);
        $(self.addProjectCheckedUsersCheckboxElem).attr("checked", false);
    },
    createProject : function() {

        var self = this;

        $("#errormessage").empty();
        $("#projecterrorlabel").hide();

        var name =  $("#project-name").val().toUpperCase();
        var discipline = $("#projectdiscipline").attr('value');
        if(discipline==-1) discipline=null;
        var ontology = $("#projectontology").attr('value');
        var users = $("#projectuser").multiselectNext('selectedValues');

        var retrievalDisable = $("input#retrievalProjectNone").is(':checked');
        var retrievalProjectAll = $("input#retrievalProjectAll").is(':checked');
        var retrievalProjectSome = $("input#retrievalProjectSome").is(':checked');
        var projectRetrieval = [];
        if(retrievalProjectSome)
            projectRetrieval = $("#retrievalproject").multiselectNext('selectedValues');

        //create project
        new ProjectModel({name : name, ontology : ontology, discipline:discipline,retrievalDisable:retrievalDisable,retrievalAllOntology:retrievalProjectAll,retrievalProjects:projectRetrieval}).save({name : name, ontology : ontology,discipline:discipline,retrievalDisable:retrievalDisable,retrievalAllOntology:retrievalProjectAll,retrievalProjects:projectRetrieval},{
                    success: function (model, response) {

                        window.app.view.message("Project", response.message, "success");
                        var id = response.project.id;

                        //create user-project "link"
                        var total = users.length;
                        var counter = 0;
                        if(total==0) self.addDeleteUserProjectCallback(0,0);
                        _.each(users,function(user){

                            new ProjectUserModel({project: id,user:user}).save({}, {
                                success: function (model, response) {
                                    self.addUserProjectCallback(total,++counter);
                                },error: function (model, response) {
                                    self.addUserProjectCallback(total,++counter);
                                    var json = $.parseJSON(response.responseText);
                                    window.app.view.message("User", json.errors, "error");
                                }});

                        });

                    },
                    error: function (model, response) {
                        var json = $.parseJSON(response.responseText);
                        window.app.view.message("Project", json.errors[0], "error");
                        //$("#projecterrorlabel").show();
                    }
                }
        );
    },
    addUserProjectCallback : function(total, counter) {
        if (counter < total) return;
        var self = this;
        self.projectsPanel.refresh();
        $("#addproject").modal("hide");
        $("#addproject").remove();
    }
});<commit_msg>Fix bug with project errors<commit_after>var AddProjectDialog = Backbone.View.extend({
    projectsPanel : null,
    addProjectDialog : null,
    userMultiSelect : null,
    projectMultiSelectAlreadyLoad : false,
    initialize: function(options) {
        this.container = options.container;
        this.projectsPanel = options.projectsPanel;
        this.ontologies = options.ontologies;
        _.bindAll(this, 'render');
    },
    render : function() {
        var self = this;
        require([
            "text!application/templates/project/ProjectAddDialog.tpl.html",
            "text!application/templates/project/OntologiesChoicesRadio.tpl.html",
            "text!application/templates/project/DisciplinesChoicesRadio.tpl.html",
            "text!application/templates/project/UsersChoices.tpl.html"
        ],
                function(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl, usersChoicesTpl) {
                    self.doLayout(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl,usersChoicesTpl);
                });
        return this;
    },
    doLayout : function(projectAddDialogTpl, ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl, usersChoicesTpl) {
        var self = this;
        var dialog = _.template(projectAddDialogTpl, {});
        $("#editproject").replaceWith("");
        $("#addproject").replaceWith("");
        $(self.el).append(dialog);

        self.initStepy();
        self.createProjectInfo(ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl);
        self.createUserList();
        self.createRetrievalProject();

        //Build dialog
        self.addProjectDialog = $("#addproject").modal({
            keyboard : true,
            backdrop : false
        });
        $("#saveProjectButton").click(function(){$("#login-form-add-project").submit();return false;});
        $("#closeAddProjectDialog").click(function(){$("#addproject").modal('hide');$("#addproject").remove();return false;});
        self.open();
        return this;
    },
    initStepy : function() {
        $('#login-form-add-project').stepy({next: function(index) {
             //check validate name
            var error = false;
             if(index==2) {
                 if($("#project-name").val().toUpperCase().trim()=="") {
                     window.app.view.message("User", "You must provide a valide project name!", "error");
                     error = true;
                 }
                 console.log($("#projectontology").val());
                 if($("#projectontology").val()==undefined) {
                     window.app.view.message("Ontology", "You must provide a ontology name!", "error");
                     error = true;
                 }
                 return !error;
             }
             //show save button on last step
             if(index==$("#login-form-add-project").find("fieldset").length) $("#saveProjectButton").show();
          }, back: function(index) {
            //hide save button if not on last step
            if(index!=$("#login-form-add-project").find("fieldset").length) $("#saveProjectButton").hide();
          }});
        $("fieldset").find("a.button-next").css("float","right");
        $("fieldset").find("a.button-back").css("float","left");
        $("fieldset").find("a").removeClass("button-next");
        $("fieldset").find("a").removeClass("button-back");
        $("fieldset").find("a").addClass("btn btn-primary");
    },
    createProjectInfo : function(ontologiesChoicesRadioTpl, disciplinesChoicesRadioTpl) {
        var self = this;
        $("#login-form-add-project").submit(function () {self.createProject(); return false;});
        $("#login-form-add-project").find("input").keydown(function(e){
            if (e.keyCode == 13) { //ENTER_KEY
                $("#login-form-add-project").submit();
                return false;
            }
        });

        $("#projectdiscipline").empty();
        var choice = _.template(disciplinesChoicesRadioTpl, {id:-1,name:"*** Undefined ***"});
        $("#projectdiscipline").append(choice);
        window.app.models.disciplines.each(function(discipline){
            var choice = _.template(disciplinesChoicesRadioTpl, {id:discipline.id,name:discipline.get("name")});
            $("#projectdiscipline").append(choice);
        });
        $("#projectontology").empty();
        self.ontologies.fetch({
            success : function (collection, response) {
                collection.each(function(ontology){
                    var choice = _.template(ontologiesChoicesRadioTpl, {id:ontology.id,name:ontology.get("name")});
                    $("#projectontology").append(choice);
                });
                $("#projectontology").find("option:selected").removeAttr("selected");
            }
        });

        $("#createOntologyWithProjectName").click(function(evt) {

            //create ontology
            var projectName = $("#project-name").val().toUpperCase().trim();
            var ontology = new OntologyModel({name : projectName}).save({name : projectName},{
                    success: function (model, response) {
                        window.app.view.message("Ontology", response.message, "success");
                        var id = response.ontology.id;
                        window.app.models.ontologies.add(model);

                        var choice = _.template(ontologiesChoicesRadioTpl, {id:id,name:model.get("name")});
                        $("#projectontology").prepend(choice);
                        $("#projectontology").val(id);

                    },
                    error: function (model, response) {
                        var json = $.parseJSON(response.responseText);
                        window.app.view.message("Ontology", json.errors, "error");
                    }
                }
            );

        })
    },
    createUserList : function () {
        /* Create Users List */
        $("#projectuser").empty();
        window.app.models.users.each(function(user) {

            if(user.id==window.app.status.user.id) {
                $("#projectuser").append('<option value="'+user.id+'" selected="selected">'+user.prettyName()+'</option>');
            } else $("#projectuser").append('<option value="'+user.id+'">'+user.prettyName()+'</option>');
        });

        $("#projectuser").multiselectNext({
            deselected: function(event, ui) {
                //lock current user (cannot be deselected
                if($(ui.option).val()==window.app.status.user.id)  {
                    $("#projectuser").multiselectNext('select', $(ui.option).text());
                    window.app.view.message("User", "You must be in user list of your project!", "error");
                }
            },
            selected: function(event, ui) {
                //alert($(ui.option).val() + " has been selected");
            }});

        $("div.ui-multiselect").find("ul.available").css("height","150px");
        $("div.ui-multiselect").find("ul.selected").css("height","150px");
        $("div.ui-multiselect").find("input.search").css("width","75px");

        $("div.ui-multiselect").find("div.actions").css("background-color","#DDDDDD");

        console.log("window.app.status.user.model.prettyName()="+window.app.status.user.model.prettyName());
        $("#projectuser").multiselectNext('select',window.app.status.user.model.prettyName());
    },
    createRetrievalProject : function() {
        var self = this;
        $("input#retrievalProjectSome,input#retrievalProjectAll,input#retrievalProjectNone").change(function() {
                if($("input#retrievalProjectSome").is(':checked')) {
                    if(!self.projectMultiSelectAlreadyLoad) {
                        self.createRetrievalProjectSelect();
                        self.projectMultiSelectAlreadyLoad = true
                    } else {
                        console.log("Show");
                        $("div#retrievalGroup").find(".ui-multiselect").show();
                    }
                } else {
                    console.log("Hide");
                    $("div#retrievalGroup").find(".ui-multiselect").hide();
                }
         });

        $("input#project-name").change(function() {
                console.log("change");
                if(self.projectMultiSelectAlreadyLoad) {
                    self.createRetrievalProjectSelect();
                }
         });

        $("#projectontology").change(function() {
                console.log("change");
                if(self.projectMultiSelectAlreadyLoad) {
                    self.createRetrievalProjectSelect();
                }
         });
    },
    createRetrievalProjectSelect : function () {
        /* Create Users List */
        $("#retrievalproject").empty();

        var projectName = $("input#project-name").val();
        var idOntology = $("select#projectontology").val();

        window.app.models.projects.each(function(project) {
            if(project.get('ontology')==idOntology)
                $("#retrievalproject").append('<option value="'+project.id+'">'+project.get('name')+'</option>');
        });
        $("#retrievalproject").append('<option value="-1" selected="selected">'+projectName+'</option>');

        $("#retrievalproject").multiselectNext( 'destroy' );
        $("#retrievalproject").multiselectNext({
            selected: function(event, ui) {
                //alert($(ui.option).val() + " has been selected");
            }});

        $("div.ui-multiselect").find("ul.available").css("height","150px");
        $("div.ui-multiselect").find("ul.selected").css("height","150px");
        $("div.ui-multiselect").find("input.search").css("width","75px");

        $("div.ui-multiselect").find("div.actions").css("background-color","#DDDDDD");
    },
    refresh : function() {
    },
    open: function() {
        var self = this;
        self.clearAddProjectPanel();
        $("#addproject").modal('show');
    },
    clearAddProjectPanel : function() {
        var self = this;
        $("#errormessage").empty();
        $("#projecterrorlabel").hide();
        $("#project-name").val("");

        $(self.addProjectCheckedOntologiesRadioElem).attr("checked", false);
        $(self.addProjectCheckedDisciplinesRadioElem).attr("checked", false);
        $(self.addProjectCheckedUsersCheckboxElem).attr("checked", false);
    },
    createProject : function() {

        var self = this;

        $("#errormessage").empty();
        $("#projecterrorlabel").hide();

        var name =  $("#project-name").val().toUpperCase();
        var discipline = $("#projectdiscipline").attr('value');
        if(discipline==-1) discipline=null;
        var ontology = $("#projectontology").attr('value');
        var users = $("#projectuser").multiselectNext('selectedValues');

        var retrievalDisable = $("input#retrievalProjectNone").is(':checked');
        var retrievalProjectAll = $("input#retrievalProjectAll").is(':checked');
        var retrievalProjectSome = $("input#retrievalProjectSome").is(':checked');
        var projectRetrieval = [];
        if(retrievalProjectSome)
            projectRetrieval = $("#retrievalproject").multiselectNext('selectedValues');

        //create project
        new ProjectModel({name : name, ontology : ontology, discipline:discipline,retrievalDisable:retrievalDisable,retrievalAllOntology:retrievalProjectAll,retrievalProjects:projectRetrieval}).save({name : name, ontology : ontology,discipline:discipline,retrievalDisable:retrievalDisable,retrievalAllOntology:retrievalProjectAll,retrievalProjects:projectRetrieval},{
                    success: function (model, response) {

                        window.app.view.message("Project", response.message, "success");
                        var id = response.project.id;

                        //create user-project "link"
                        var total = users.length;
                        var counter = 0;
                        if(total==0) self.addDeleteUserProjectCallback(0,0);
                        _.each(users,function(user){

                            new ProjectUserModel({project: id,user:user}).save({}, {
                                success: function (model, response) {
                                    self.addUserProjectCallback(total,++counter);
                                },error: function (model, response) {
                                    self.addUserProjectCallback(total,++counter);
                                    var json = $.parseJSON(response.responseText);
                                    window.app.view.message("User", json.errors, "error");
                                }});

                        });

                    },
                    error: function (model, response) {
                        var json = $.parseJSON(response.responseText);
                        window.app.view.message("Project", json.errors, "error");
                        $('#login-form-add-project').stepy('step', 1);
                        //$("#projecterrorlabel").show();
                    }
                }
        );
    },
    addUserProjectCallback : function(total, counter) {
        if (counter < total) return;
        var self = this;
        self.projectsPanel.refresh();
        $("#addproject").modal("hide");
        $("#addproject").remove();
    }
});<|endoftext|>


<commit_before>/**
 * The main AWS namespace
 */
var AWS = {};

/**
 * @!macro [new] nobrowser
 *   @note This feature is not supported in the browser environment of the SDK.
 */

module.exports = AWS;
require('./util');

AWS.util.update(AWS, {

  /**
   * @constant
   */
  VERSION: '2.0.0-rc9',

  /**
   * @api private
   */
  ServiceInterface: {},

  /**
   * @api private
   */
  Signers: {},

  /**
   * @api private
   */
  XML: {}

});

require('./service');

require('./credentials');
require('./credentials/credential_provider_chain');
require('./credentials/temporary_credentials');
require('./credentials/web_identity_credentials');
require('./credentials/saml_credentials');

require('./config');
require('./http');
require('./sequential_executor');
require('./event_listeners');
require('./request');
require('./response');
require('./signers/request_signer');
require('./param_validator');

/**
 * @readonly
 * @return [AWS.SequentialExecutor] a collection of global event listeners that
 *   are attached to every sent request.
 * @see AWS.Request AWS.Request for a list of events to listen for
 * @example Logging the time taken to send a request
 *   AWS.events.on('send', function startSend(resp) {
 *     resp.startTime = new Date().getTime();
 *   }).on('complete', function calculateTime(resp) {
 *     var time = (new Date().getTime() - resp.startTime) / 1000;
 *     console.log('Request took ' + time + ' seconds');
 *   });
 *
 *   new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
 */
AWS.events = new AWS.SequentialExecutor();

if (typeof window !== 'undefined') window.AWS = AWS;
<commit_msg>Add hack to parse nobrowser macro<commit_after>/**
 * The main AWS namespace
 */
var AWS = {};

/**
 * @!macro [new] nobrowser
 *   @note This feature is not supported in the browser environment of the SDK.
 */
var _hidden = {}; _hidden = {}; // hack to parse macro

module.exports = AWS;
require('./util');

AWS.util.update(AWS, {

  /**
   * @constant
   */
  VERSION: '2.0.0-rc9',

  /**
   * @api private
   */
  ServiceInterface: {},

  /**
   * @api private
   */
  Signers: {},

  /**
   * @api private
   */
  XML: {}

});

require('./service');

require('./credentials');
require('./credentials/credential_provider_chain');
require('./credentials/temporary_credentials');
require('./credentials/web_identity_credentials');
require('./credentials/saml_credentials');

require('./config');
require('./http');
require('./sequential_executor');
require('./event_listeners');
require('./request');
require('./response');
require('./signers/request_signer');
require('./param_validator');

/**
 * @readonly
 * @return [AWS.SequentialExecutor] a collection of global event listeners that
 *   are attached to every sent request.
 * @see AWS.Request AWS.Request for a list of events to listen for
 * @example Logging the time taken to send a request
 *   AWS.events.on('send', function startSend(resp) {
 *     resp.startTime = new Date().getTime();
 *   }).on('complete', function calculateTime(resp) {
 *     var time = (new Date().getTime() - resp.startTime) / 1000;
 *     console.log('Request took ' + time + ' seconds');
 *   });
 *
 *   new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
 */
AWS.events = new AWS.SequentialExecutor();

if (typeof window !== 'undefined') window.AWS = AWS;
<|endoftext|>


<commit_before>'use strict';

var
  testHelper = require('./testHelper'),
  docuWriter = require('../../lib/scenarioDocuWriter.js'),
  expect = require('expect.js'),
  _ = require('lodash'),
  Q = require('q'),
  fs = require('fs');

before(function () {

  // define our mock jasmine object
  global.jasmine = {
    getEnv: function () {
      return {
        currentSpec: {
          suite: {
            description: 'SuiteDescription'
          },
          description: 'specDescription'
        }
      };
    }
  };

  global.browser = {
    getCurrentUrl: function () {
      var deferred = Q.defer();
      deferred.resolve('http://example.url.com/#/somepage');
      return deferred.promise;
    },
    takeScreenshot: function () {
      var deferred = Q.defer();
      deferred.resolve('dummyImageDate');
      return deferred.promise;
    }
  };

  global.by = {
    css: function () {
    }
  };

  global.element = function () {
    return {
      getOuterHtml: function () {
        var outerHtmlDeferred = Q.defer();
        outerHtmlDeferred.resolve('');
        return outerHtmlDeferred.promise;
      }
    };
  };

});

describe('scenarioDocuWriter', function () {

  /** let's set up some dummy objects **/
  var targetDir = './test/out/docu';

  var dummyBranch = {
    name: 'my unsafe branch name, will',
    description: 'my safe description'
  };

  var dummyBuild = {
    name: 'some build name_',
    revision: '1234'
  };

  var dummyUseCase = {
    name: 'use case name, toll!',
    description: 'some description with special chars ;) %&'
  };

  var dummyScenario = {
    useCaseName: dummyUseCase.name,
    scenarioName: ' some cool scenario name',
    scenarioDescription: 'scenario description',
    stepCounter: 0
  };

  function getTimeStamp() {
    return Math.round((new Date()).getTime() / 1000);
  }

  function getTimeStampedBuildObject(timeStamp) {
    var build = _.cloneDeep(dummyBuild);
    build.name = build.name + timeStamp;
    return build;
  }

  function assertFileExists(filePath, done) {
    fs.exists(filePath, function (result) {
      if (result === false) {
        // file not found, list files in our test-out dir
        testHelper
          .logDirectoryTree(targetDir)
          .then(function () {
            done(new Error('File ' + filePath + ' does not exist!'));
          });

      } else {
        done();
      }
    });
  }

  it('should write branch on start()', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir)
      .then(function () {
        var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/branch.xml';
        assertFileExists(expectedFilePath, done);
      });
  });

  it('should save usecase', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveUseCase(dummyUseCase)
      .then(function () {
        var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/some+build+name_' + timeStamp + '/use+case+name%2C+toll!/usecase.xml';
        assertFileExists(expectedFilePath, done);
      });
  });

  it('should save scenario', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveUseCase(dummyUseCase)
      .then(function () {
        docuWriter.saveScenario(dummyScenario)
          .then(function () {
            var expectedFilePath = targetDir + '//my+unsafe+branch+name%2C+will//some+build+name_' + timeStamp + '/use+case+name%2C+toll!/+some+cool+scenario+name/scenario.xml';
            assertFileExists(expectedFilePath, done);
          });
      });
  });

  it('should save a step', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveStep('my step').then(function () {
      var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/some+build+name_' + timeStamp + '/suitedescription/specdescription/steps/000.xml';
      assertFileExists(expectedFilePath, done);
    }, done);
  });

  it('should save a step with default pagename', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveStep('my step')
      .then(function (stepData) {
        expect(stepData[0].page.name).to.be('#_somepage');
        done();
      }, done)
      .catch(done);
  });

  it('should save a step with custom pagename function', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.registerPageNameFunction(function (url) {
      var pos = url.href.indexOf('#');
      if (pos > -1) {
        return url.href.substring(pos + 1);
      } else {
        return url.href;
      }
    });
    docuWriter.saveStep('my step').then(function (stepData) {
      expect(stepData[0].page.name).to.be('_somepage');
      done();
    }, done);
  });

  it('should save a step with additional misc data ("details")', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = {
      first: {
        arbitrary: 1,
        additional: 'data',
        that: 'should be stored'
      },
      second: {
        arbitrary: 2,
        additional: 'data2',
        that: 'should be stored2'
      }
    };

    docuWriter.saveStep('my step', dummyDetailData).then(function (savedStepData) {
      var stepDescriptionDetails = savedStepData[0].metadata.details;
      expect(stepDescriptionDetails).not.to.be(undefined);
      expect(stepDescriptionDetails.entry[0].key).to.be('first');
      expect(stepDescriptionDetails.entry[0].value).to.eql({
        arbitrary: 1,
        additional: 'data',
        that: 'should be stored'
      });
      expect(stepDescriptionDetails.entry[1].key).to.be('second');
      expect(stepDescriptionDetails.entry[1].value).to.eql({
        arbitrary: 2,
        additional: 'data2',
        that: 'should be stored2'
      });

      done();
    }, done);
  });

  /**
   * At the moment, this does not work as expected.
   * //TODO: Discuss this with the scenarioo core team.
   */
  it('should save a step with additional misc data ("details") including arrays', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = {
      complexCustomInfo: [
        'this is a more complex example of metadata',
        'We expect this to end up in valid "entry/key/value" xml'
      ],
      moreComplexCustomInfo: [
        {
          attributeOne: 'valueOne',
          attributeTwo: 'valueTwo'
        },
        {
          attributeOne: 'valueOneOne',
          attributeTwo: 'valueTwoTwo'
        }
      ]
    };

    docuWriter.saveStep('my step', dummyDetailData).then(function (savedStepData) {
      var stepDescriptionDetails = savedStepData[0].metadata.details;

      expect(stepDescriptionDetails).not.to.be(undefined);

      done();
    }, done);
  });

  it('should fail if step metadata details is not an object', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = [];

    docuWriter.saveStep('my step', dummyDetailData)
      .then(function () {
        done('should not be successful!');
      }, function (err) {
        expect(err.message).to.contain('Step metadata details must be an object');
        done();
      });
  });

});
<commit_msg>#7 #1 this should fix test on travis. problem was case sensitivity in folder names<commit_after>'use strict';

var
  testHelper = require('./testHelper'),
  docuWriter = require('../../lib/scenarioDocuWriter.js'),
  expect = require('expect.js'),
  _ = require('lodash'),
  Q = require('q'),
  fs = require('fs');

before(function () {

  // define our mock jasmine object
  global.jasmine = {
    getEnv: function () {
      return {
        currentSpec: {
          suite: {
            description: 'SuiteDescription'
          },
          description: 'specDescription'
        }
      };
    }
  };

  global.browser = {
    getCurrentUrl: function () {
      var deferred = Q.defer();
      deferred.resolve('http://example.url.com/#/somepage');
      return deferred.promise;
    },
    takeScreenshot: function () {
      var deferred = Q.defer();
      deferred.resolve('dummyImageDate');
      return deferred.promise;
    }
  };

  global.by = {
    css: function () {
    }
  };

  global.element = function () {
    return {
      getOuterHtml: function () {
        var outerHtmlDeferred = Q.defer();
        outerHtmlDeferred.resolve('');
        return outerHtmlDeferred.promise;
      }
    };
  };

});

describe('scenarioDocuWriter', function () {

  /** let's set up some dummy objects **/
  var targetDir = './test/out/docu';

  var dummyBranch = {
    name: 'my unsafe branch name, will',
    description: 'my safe description'
  };

  var dummyBuild = {
    name: 'some build name_',
    revision: '1234'
  };

  var dummyUseCase = {
    name: 'use case name, toll!',
    description: 'some description with special chars ;) %&'
  };

  var dummyScenario = {
    useCaseName: dummyUseCase.name,
    scenarioName: ' some cool scenario name',
    scenarioDescription: 'scenario description',
    stepCounter: 0
  };

  function getTimeStamp() {
    return Math.round((new Date()).getTime() / 1000);
  }

  function getTimeStampedBuildObject(timeStamp) {
    var build = _.cloneDeep(dummyBuild);
    build.name = build.name + timeStamp;
    return build;
  }

  function assertFileExists(filePath, done) {
    fs.exists(filePath, function (result) {
      if (result === false) {
        // file not found, list files in our test-out dir
        testHelper
          .logDirectoryTree(targetDir)
          .then(function () {
            done(new Error('File ' + filePath + ' does not exist!'));
          });

      } else {
        done();
      }
    });
  }

  it('should write branch on start()', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir)
      .then(function () {
        var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/branch.xml';
        assertFileExists(expectedFilePath, done);
      });
  });

  it('should save usecase', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveUseCase(dummyUseCase)
      .then(function () {
        var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/some+build+name_' + timeStamp + '/use+case+name%2C+toll!/usecase.xml';
        assertFileExists(expectedFilePath, done);
      });
  });

  it('should save scenario', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveUseCase(dummyUseCase)
      .then(function () {
        docuWriter.saveScenario(dummyScenario)
          .then(function () {
            var expectedFilePath = targetDir + '//my+unsafe+branch+name%2C+will//some+build+name_' + timeStamp + '/use+case+name%2C+toll!/+some+cool+scenario+name/scenario.xml';
            assertFileExists(expectedFilePath, done);
          });
      });
  });

  it('should save a step', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveStep('my step').then(function () {
      var expectedFilePath = targetDir + '/my+unsafe+branch+name%2C+will/some+build+name_' + timeStamp + '/SuiteDescription/specDescription/steps/000.xml';
      assertFileExists(expectedFilePath, done);
    }, done);
  });

  it('should save a step with default pagename', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.saveStep('my step')
      .then(function (stepData) {
        expect(stepData[0].page.name).to.be('#_somepage');
        done();
      }, done)
      .catch(done);
  });

  it('should save a step with custom pagename function', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    docuWriter.registerPageNameFunction(function (url) {
      var pos = url.href.indexOf('#');
      if (pos > -1) {
        return url.href.substring(pos + 1);
      } else {
        return url.href;
      }
    });
    docuWriter.saveStep('my step').then(function (stepData) {
      expect(stepData[0].page.name).to.be('_somepage');
      done();
    }, done);
  });

  it('should save a step with additional misc data ("details")', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = {
      first: {
        arbitrary: 1,
        additional: 'data',
        that: 'should be stored'
      },
      second: {
        arbitrary: 2,
        additional: 'data2',
        that: 'should be stored2'
      }
    };

    docuWriter.saveStep('my step', dummyDetailData).then(function (savedStepData) {
      var stepDescriptionDetails = savedStepData[0].metadata.details;
      expect(stepDescriptionDetails).not.to.be(undefined);
      expect(stepDescriptionDetails.entry[0].key).to.be('first');
      expect(stepDescriptionDetails.entry[0].value).to.eql({
        arbitrary: 1,
        additional: 'data',
        that: 'should be stored'
      });
      expect(stepDescriptionDetails.entry[1].key).to.be('second');
      expect(stepDescriptionDetails.entry[1].value).to.eql({
        arbitrary: 2,
        additional: 'data2',
        that: 'should be stored2'
      });

      done();
    }, done);
  });

  /**
   * At the moment, this does not work as expected.
   * //TODO: Discuss this with the scenarioo core team.
   */
  it('should save a step with additional misc data ("details") including arrays', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = {
      complexCustomInfo: [
        'this is a more complex example of metadata',
        'We expect this to end up in valid "entry/key/value" xml'
      ],
      moreComplexCustomInfo: [
        {
          attributeOne: 'valueOne',
          attributeTwo: 'valueTwo'
        },
        {
          attributeOne: 'valueOneOne',
          attributeTwo: 'valueTwoTwo'
        }
      ]
    };

    docuWriter.saveStep('my step', dummyDetailData).then(function (savedStepData) {
      var stepDescriptionDetails = savedStepData[0].metadata.details;

      expect(stepDescriptionDetails).not.to.be(undefined);

      done();
    }, done);
  });

  it('should fail if step metadata details is not an object', function (done) {
    var timeStamp = getTimeStamp();
    docuWriter.start(dummyBranch, getTimeStampedBuildObject(timeStamp), targetDir);
    var dummyDetailData = [];

    docuWriter.saveStep('my step', dummyDetailData)
      .then(function () {
        done('should not be successful!');
      }, function (err) {
        expect(err.message).to.contain('Step metadata details must be an object');
        done();
      });
  });

});
<|endoftext|>


<commit_before>import Application from 'appkit/app';
import Router from 'appkit/router';

function startApp(attrs) {
  var App;

  var attributes = Ember.merge({
    // useful Test defaults
    rootElement: '#ember-testing',
    LOG_ACTIVE_GENERATION:false,
    LOG_VIEW_LOOKUPS: false
  }, attrs); // but you can override;

  Router.reopen({
    location: 'none'
  });

  Ember.run(function(){
    App = Application.create(attributes);
    App.setupForTesting();
    App.injectTestHelpers();
  });

  App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL"

  return App;
}

export default startApp;
<commit_msg>Remove unnecessary router reopening<commit_after>import Application from 'appkit/app';

function startApp(attrs) {
  var App;

  var attributes = Ember.merge({
    // useful Test defaults
    rootElement: '#ember-testing',
    LOG_ACTIVE_GENERATION:false,
    LOG_VIEW_LOOKUPS: false
  }, attrs); // but you can override;

  Ember.run(function(){
    App = Application.create(attributes);
    App.setupForTesting();
    App.injectTestHelpers();
  });

  App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL"

  return App;
}

export default startApp;
<|endoftext|>


<commit_before>const fillMon = require('../../lib/utils/fillMongo.js');
const schematize = require('../../lib/utils/schematize');
const genUsers = require('../../lib/utils/genUsers');

const Country = require('../../lib/models/Country');

const {assert} = require('chai');
const mongoose = require('mongoose');
mongoose.Promise = Promise;

const testUri = 'mongodb://localhost:27017/country-love-test';
mongoose.connect(testUri, {useMongoClient: true});

/**************************************
 * Purpose:
 *  - pull the files from the cloned factbook.json folder
 *          (in same folder as repo root; not in repo itself)
 *  - translate them to mongoose Country schema
 *
 *  - use by unskipping 'RUN' describe function and running npm test ONCE
 *  - add skip again when db is populated
 */

describe.skip('POPULATE COUNTRIES', () => {

    describe('fillMongo', () => {
        it('fills the db with factbook data', () => {
            assert.ok(fillMon());

        });
    });

    describe('schematize:     THIS SHOULD FAIL WITH TIMEOUT ERROR', () => {
        before(() => {
            if(Country.collection.findOne({})) Country.collection.drop();
        });

        it('pulls the database info and puts it into a schema', done => {
            assert.ok(schematize(done));
        });
    });
});

describe.skip('POPULATE USERS', () => {

    it('testing genusers: delete later', () => {
        genUsers(100).then((users) => {
            console.log(`created ${users.length} users`); // eslint-disable-line
        });
    });
});

<commit_msg>write red test for genExps<commit_after>const fillMon = require('../../lib/utils/fillMongo.js');
const schematize = require('../../lib/utils/schematize');
const genUsers = require('../../lib/utils/genUsers');

const Country = require('../../lib/models/Country');

const {assert} = require('chai');
const mongoose = require('mongoose');
mongoose.Promise = Promise;

const testUri = 'mongodb://localhost:27017/country-love-test';
mongoose.connect(testUri, {useMongoClient: true});

/**************************************
 * Purpose:
 *  - pull the files from the cloned factbook.json folder
 *          (in same folder as repo root; not in repo itself)
 *  - translate them to mongoose Country schema
 *
 *  - use by unskipping 'RUN' describe function and running npm test ONCE
 *  - add skip again when db is populated
 */

describe.skip('POPULATE COUNTRIES', () => {

    describe('fillMongo', () => {
        it('fills the db with factbook data', () => {
            assert.ok(fillMon());

        });
    });

    describe('schematize:     THIS SHOULD FAIL WITH TIMEOUT ERROR', () => {
        before(() => {
            if(Country.collection.findOne({})) Country.collection.drop();
        });

        it('pulls the database info and puts it into a schema', done => {
            assert.ok(schematize(done));
        });
    });
});

describe.skip('POPULATE USERS', () => {
    it('fills user collection', () => {
        genUsers(100).then((users) => {
            console.log(`created ${users.length} users`); // eslint-disable-line
        });
    });
});

describe.only('POPULATE EXPERIENCES', () => {
    it('fills experiences collection', () => {
        genExps(1000).then((expIds) => {
            assert.ok(expIds);
        });
    });
});

<|endoftext|>


<commit_before>{
	"Get a Smoke Alarm": "Get a Smoke Alarm",
	"Javascript is disabled in your browser. In order to use the site correctly, please enable javascript.": "Javascript is disabled in your browser. In order to use the site correctly, please enable javascript.",
	"Smoke alarms save lives.  Installing a smoke alarm is the first step to keeping your family safe.": "Smoke alarms save lives.  Installing a smoke alarm is the first step to keeping your family safe.",
	"Thank you for your interest in having FREE smoke alarms installed in your home.": "Thank you for your interest in having FREE smoke alarms installed in your home.",
	"To request a FREE installation, please complete all fields in the form below and click “Submit.”": "To request a FREE installation, please complete all fields in the form below and click “Submit.”",
	"After submitting your request, you will be contacted by an American Red Cross representative with information on installation availability in your area.": "After submitting your request, you will be contacted by an American Red Cross representative with information on installation availability in your area.",
	"Your Name": "Your Name",
	"Street Address & Unit (e.g., 123 Main St., Unit Q)": "Street Address & Unit (e.g., 123 Main St., Unit Q)",
	"Address & Unit": "Address & Unit",
	"City": "City",
	"State": "State",
	"Zip Code": "Zip Code",
	"Phone Number": "Phone Number",
	"Phone #": "Phone #",
	"Email Address": "Email Address",
	"Email": "Email",
	"Submit": "Submit",
	"The American Red Cross and its partners have launched the Home Fire Campaign to reduce deaths and injuries caused by home fires by 25 percent over five years.": "The American Red Cross and its partners have launched the Home Fire Campaign to reduce deaths and injuries caused by home fires by 25 percent over five years.",
	"The Red Cross asks every household in America to take two simple steps to help save lives: check or install smoke alarms and practice fire drills at home.": "The Red Cross asks every household in America to take two simple steps to help save lives: check or install smoke alarms and practice fire drills at home.",
	"This form can accept requests from the following States and Counties: IA (except Harrison, Mills and Pottawattamie Counties), ID, IL, MN, MO, MT, ND, SD, WA (except Clark, Cowlitz, Klickitat, Pacific, Skamania and Wahkiakum Counties), WI and Atchison, Doniphan, Johnson, Leavenworth and Wyandotte Counties in KS, Dakota County, NE and Malheur County, OR.": "This form can accept requests from the following States and Counties: IA (except Harrison, Mills and Pottawattamie Counties), ID, IL, MN, MO, MT, ND, SD, WA (except Clark, Cowlitz, Klickitat, Pacific, Skamania and Wahkiakum Counties), WI and Atchison, Doniphan, Johnson, Leavenworth and Wyandotte Counties in KS, Dakota County, NE and Malheur County, OR.",
	"  If your location is not listed, please call 800-RED-CROSS to be connected to ": "  If your location is not listed, please call 800-RED-CROSS to be connected to ",
	"your": "your",
	" local Red Cross Chapter.": " local Red Cross Chapter.",
	"For more information about the importance of smoke alarms, see ": "For more information about the importance of smoke alarms, see ",
	"the Smoke Signals project": "the Smoke Signals project",
	"This web site is open source ": "This web site is open source ",
	" volunteers welcome ": " volunteers welcome ",
	" at GitHub": " at GitHub",
	"This field is required": "This field is required",
	"Please provide either a 10-digit phone number or an email address": "Please provide either a 10-digit phone number or an email address",
	"The phone number is invalid": "The phone number is invalid",
	"A valid US zip code is required": "A valid US zip code is required",
	"Please provide either a phone number or an email address": "Please provide either a phone number or an email address",
	"The email address is invalid": "The email address is invalid",
	"American Red Cross": "American Red Cross",
	"Thank you for your smoke alarm installation request.": "Thank you for your smoke alarm installation request.",
	"If you need to contact the Red Cross about this request, use ID number %s.": "If you need to contact the Red Cross about this request, use ID number %s.",
	"Your information has been sent to the Red Cross representative for %s.": "Your information has been sent to the Red Cross representative for %s.",
	"A representative will contact you with information on installation availability in your area.  Please allow two to four weeks for a response.": "A representative will contact you with information on installation availability in your area.  Please allow two to four weeks for a response.",
	"Visit the Red Cross": "Visit the Red Cross",
	" to learn how to prepare for and prevent home fires.": " to learn how to prepare for and prevent home fires.",
	"Sorry, the Red Cross Region serving %s County, %s does not utilize this website to accept smoke alarm installation requests.": "Sorry, the Red Cross Region serving %s County, %s does not utilize this website to accept smoke alarm installation requests.",
	"Please call 800-REDCROSS (800-733-2767) to be connected to your servicing Region.": "Please call 800-REDCROSS (800-733-2767) to be connected to your servicing Region.",
	"Thank you for contacting the Red Cross.": "Thank you for contacting the Red Cross.",
	"Sorry, we don't recognize any U.S. location for Zip Code \"%s\".  Are you sure you entered an accurate Zip Code?": "Sorry, we don't recognize any U.S. location for Zip Code \"%s\".  Are you sure you entered an accurate Zip Code?"
}<commit_msg>Keep locales file(s) up to date.<commit_after>{
	"Get a Smoke Alarm": "Get a Smoke Alarm",
	"Javascript is disabled in your browser. In order to use the site correctly, please enable javascript.": "Javascript is disabled in your browser. In order to use the site correctly, please enable javascript.",
	"Smoke alarms save lives.  Installing a smoke alarm is the first step to keeping your family safe.": "Smoke alarms save lives.  Installing a smoke alarm is the first step to keeping your family safe.",
	"Thank you for your interest in having FREE smoke alarms installed in your home.": "Thank you for your interest in having FREE smoke alarms installed in your home.",
	"To request a FREE installation, please complete all fields in the form below and click “Submit.”": "To request a FREE installation, please complete all fields in the form below and click “Submit.”",
	"After submitting your request, you will be contacted by an American Red Cross representative with information on installation availability in your area.": "After submitting your request, you will be contacted by an American Red Cross representative with information on installation availability in your area.",
	"Your Name": "Your Name",
	"Street Address & Unit (e.g., 123 Main St., Unit Q)": "Street Address & Unit (e.g., 123 Main St., Unit Q)",
	"Address & Unit": "Address & Unit",
	"City": "City",
	"State": "State",
	"Zip Code": "Zip Code",
	"Phone Number": "Phone Number",
	"Phone #": "Phone #",
	"Email Address": "Email Address",
	"Email": "Email",
	"Submit": "Submit",
	"The American Red Cross and its partners have launched the Home Fire Campaign to reduce deaths and injuries caused by home fires by 25 percent over five years.": "The American Red Cross and its partners have launched the Home Fire Campaign to reduce deaths and injuries caused by home fires by 25 percent over five years.",
	"The Red Cross asks every household in America to take two simple steps to help save lives: check or install smoke alarms and practice fire drills at home.": "The Red Cross asks every household in America to take two simple steps to help save lives: check or install smoke alarms and practice fire drills at home.",
	"This form can accept requests from the following States and Counties: IA (except Harrison, Mills and Pottawattamie Counties), ID, IL, MN, MO, MT, ND, SD, WA (except Clark, Cowlitz, Klickitat, Pacific, Skamania and Wahkiakum Counties), WI and Atchison, Doniphan, Johnson, Leavenworth and Wyandotte Counties in KS, Dakota County, NE and Malheur County, OR.": "This form can accept requests from the following States and Counties: IA (except Harrison, Mills and Pottawattamie Counties), ID, IL, MN, MO, MT, ND, SD, WA (except Clark, Cowlitz, Klickitat, Pacific, Skamania and Wahkiakum Counties), WI and Atchison, Doniphan, Johnson, Leavenworth and Wyandotte Counties in KS, Dakota County, NE and Malheur County, OR.",
	"  If your location is not listed, please call 800-RED-CROSS to be connected to ": "  If your location is not listed, please call 800-RED-CROSS to be connected to ",
	"your": "your",
	" local Red Cross Chapter.": " local Red Cross Chapter.",
	"For more information about the importance of smoke alarms, see ": "For more information about the importance of smoke alarms, see ",
	"the Smoke Signals project": "the Smoke Signals project",
	"This web site is open source ": "This web site is open source ",
	" volunteers welcome ": " volunteers welcome ",
	" at GitHub": " at GitHub",
	"This field is required": "This field is required",
	"Please provide either a 10-digit phone number or an email address": "Please provide either a 10-digit phone number or an email address",
	"The phone number is invalid": "The phone number is invalid",
	"A valid US zip code is required": "A valid US zip code is required",
	"Please provide either a phone number or an email address": "Please provide either a phone number or an email address",
	"The email address is invalid": "The email address is invalid",
	"American Red Cross": "American Red Cross",
	"Thank you for your smoke alarm installation request.": "Thank you for your smoke alarm installation request.",
	"If you need to contact the Red Cross about this request, use ID number %s.": "If you need to contact the Red Cross about this request, use ID number %s.",
	"Your information has been sent to the Red Cross representative for %s.": "Your information has been sent to the Red Cross representative for %s.",
	"A representative will contact you with information on installation availability in your area.  Please allow two to four weeks for a response.": "A representative will contact you with information on installation availability in your area.  Please allow two to four weeks for a response.",
	"Visit the Red Cross": "Visit the Red Cross",
	" to learn how to prepare for and prevent home fires.": " to learn how to prepare for and prevent home fires.",
	"Sorry, the Red Cross Region serving %s County, %s does not utilize this website to accept smoke alarm installation requests.": "Sorry, the Red Cross Region serving %s County, %s does not utilize this website to accept smoke alarm installation requests.",
	"Please call 800-REDCROSS (800-733-2767) to be connected to your servicing Region.": "Please call 800-REDCROSS (800-733-2767) to be connected to your servicing Region.",
	"Thank you for contacting the Red Cross.": "Thank you for contacting the Red Cross.",
	"Sorry, we don't recognize any U.S. location for Zip Code \"%s\".  Are you sure you entered an accurate Zip Code?": "Sorry, we don't recognize any U.S. location for Zip Code \"%s\".  Are you sure you entered an accurate Zip Code?",
	"What is your address, including the unit number, city, state, and zipcode?": "What is your address, including the unit number, city, state, and zipcode?",
	"Sorry, we couldn't process your zipcode. Please text us your 5-digit zipcode.": "Sorry, we couldn't process your zipcode. Please text us your 5-digit zipcode.",
	"Is the number you're texting from the best way to get in touch with you?": "Is the number you're texting from the best way to get in touch with you?",
	"If so, text YES. Otherwise, please text a phone number where we can reach you.": "If so, text YES. Otherwise, please text a phone number where we can reach you.",
	"One last question: is there an email address we can use to contact you?": "One last question: is there an email address we can use to contact you?",
	"If not, text NONE. If yes, please text us the email address.": "If not, text NONE. If yes, please text us the email address.",
	"This is the smoke alarm request system from the Red Cross.  For more information, call 1-800-RED-CROSS or visit getasmokealarm.org.": "This is the smoke alarm request system from the Red Cross.  For more information, call 1-800-RED-CROSS or visit getasmokealarm.org.",
	"Welcome to the smoke alarm request system (para continuar en espanol, mande el texto \"ES\"). We need to ask four questions to process your request. Please text back the answer to each and wait for the next question. First, what is your name?": "Welcome to the smoke alarm request system (para continuar en espanol, mande el texto \"ES\"). We need to ask four questions to process your request. Please text back the answer to each and wait for the next question. First, what is your name?"
}<|endoftext|>


<commit_before>/**
 * php tests
 *
 * @author Craig Campbell
 */
RainbowTester.startTest('php');

RainbowTester.run(
    'echo',

    'echo \'hello world\';',

    'echo \'hello world\';'
);

RainbowTester.run(
    'variable',

    '$foo = true;',

    '$foo = true;'
);

RainbowTester.run(
    'variable variable',

    '$$foo = true;',

    '$$foo = true;'
);

RainbowTester.run(
    'string concatenation',

    "$foo = 'test' . 'string' . 'concatenation';",

    '$foo = \'test\' . \'string\' . \'concatenation\';'
);

RainbowTester.run(
    'include 1',

    "include 'App.php';",

    'include \'App.php\';'
);

RainbowTester.run(
    'include 2',

    "include_once('App.php');",

    'include_once(\'App.php\');'
);

RainbowTester.run(
    'instanceof',

    "$is_array_object = $collection instanceof ArrayObject;",

    '$is_array_object = $collection instanceof ArrayObject;'
);

RainbowTester.run(
    'instanceof namespace class',

    "$is_user = $object instanceof App\\User;",

    '$is_user = $object instanceof App\\User;'
);

RainbowTester.run(
    'array stuff',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);'
);

RainbowTester.run(
    'php tag',

    '<?php echo $foo; ?>',

    '<?php echo $foo; ?>'
);

RainbowTester.run(
    'php tag 2',

    '<?php echo \'?>\'; ?>',

    '<?php echo \'?>\'; ?>'
);

RainbowTester.run(
    'namespace declaration',

    'namespace Sonic\\Database;',

    'namespace Sonic\\Database;'
);

RainbowTester.run(
    'use declaration',

    'use Sonic;',

    'use Sonic;'
);

RainbowTester.run(
    'class declaration',

    'class MyClass {}',

    'class MyClass {}'
);

RainbowTester.run(
    'trait declaration',

    'trait MyClass {}',

    'trait MyClass {}'
);

RainbowTester.run(
    'abstract class declaration',

    'abstract class MyClass {}',

    'abstract class MyClass {}'
);

RainbowTester.run(
    'final class declaration',

    'final class TestClass\n' +
    '{\n' +
    '}',

    'final class TestClass\n' +
    '{\n' +
    '}'
);

RainbowTester.run(
    'child class declaration',

    'class Collection extends ArrayObject {}',

    'class Collection extends ArrayObject {}'
);

RainbowTester.run(
    'final child class declaration',

    'final class TestClass extends \\Some\\Other\\Class {}',

    'final class TestClass extends \\Some\\Other\\Class {}'
);

RainbowTester.run(
    'test static',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();'
);

RainbowTester.run(
    'test magic function',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}'
);

RainbowTester.run(
    'test magic method',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}'
);

RainbowTester.run(
    'test new class',

    'new SomeClass();',

    'new SomeClass();'
);

RainbowTester.run(
    'test new namespace class',

    'new Sonic\\Database\\Query();',

    'new Sonic\\Database\\Query();'
);

RainbowTester.run(
    'test new class without parenthesis',

    'new Sonic\\Controller;',

    'new Sonic\\Controller;'
);

RainbowTester.run(
    'test static class call',

    '$path = Sonic\\App::getInstance()->getPath();',

    '$path = Sonic\\App::getInstance()->getPath();'
);

RainbowTester.run(
    'constant language',

    'true; TRUE;',

    'true; TRUE;'
);

RainbowTester.run(
    'constant',

    'TEST_CONSTANT',

    'TEST_CONSTANT'
);

RainbowTester.run(
    'constant 2',

    '(TEST_CONSTANT_2)',

    '(TEST_CONSTANT_2)'
);

RainbowTester.run(
    'class constant',

    '$version = Sonic\\App::VERSION',

    '$version = Sonic\\App::VERSION'
);

RainbowTester.run(
    'static variable access',

    '$foo = Sonic\\App::$static_property;',

    '$foo = Sonic\\App::$static_property;'
);

RainbowTester.run(
    'type hint',

    'public static function getForUser(User $user, Sort $sort) {}',

    'public static function getForUser(User $user, Sort $sort) {}'
);

RainbowTester.run(
    'type hint with namespace',

    'public static function getForUser(\\SomeApp\\User $user) {}',

    'public static function getForUser(\\SomeApp\\User $user) {}'
);
RainbowTester.endTest('php');
<commit_msg>added 'interface' test case.<commit_after>/**
 * php tests
 *
 * @author Craig Campbell
 */
RainbowTester.startTest('php');

RainbowTester.run(
    'echo',

    'echo \'hello world\';',

    'echo \'hello world\';'
);

RainbowTester.run(
    'variable',

    '$foo = true;',

    '$foo = true;'
);

RainbowTester.run(
    'variable variable',

    '$$foo = true;',

    '$$foo = true;'
);

RainbowTester.run(
    'string concatenation',

    "$foo = 'test' . 'string' . 'concatenation';",

    '$foo = \'test\' . \'string\' . \'concatenation\';'
);

RainbowTester.run(
    'include 1',

    "include 'App.php';",

    'include \'App.php\';'
);

RainbowTester.run(
    'include 2',

    "include_once('App.php');",

    'include_once(\'App.php\');'
);

RainbowTester.run(
    'instanceof',

    "$is_array_object = $collection instanceof ArrayObject;",

    '$is_array_object = $collection instanceof ArrayObject;'
);

RainbowTester.run(
    'instanceof namespace class',

    "$is_user = $object instanceof App\\User;",

    '$is_user = $object instanceof App\\User;'
);

RainbowTester.run(
    'array stuff',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);'
);

RainbowTester.run(
    'php tag',

    '<?php echo $foo; ?>',

    '<?php echo $foo; ?>'
);

RainbowTester.run(
    'php tag 2',

    '<?php echo \'?>\'; ?>',

    '<?php echo \'?>\'; ?>'
);

RainbowTester.run(
    'namespace declaration',

    'namespace Sonic\\Database;',

    'namespace Sonic\\Database;'
);

RainbowTester.run(
    'use declaration',

    'use Sonic;',

    'use Sonic;'
);

RainbowTester.run(
    'class declaration',

    'class MyClass {}',

    'class MyClass {}'
);

RainbowTester.run(
    'trait declaration',

    'trait MyClass {}',

    'trait MyClass {}'
);

RainbowTester.run(
    'interface declaration',

    'interface IMyClass {}',

    'interface IMyClass {}'
);

RainbowTester.run(
    'abstract class declaration',

    'abstract class MyClass {}',

    'abstract class MyClass {}'
);

RainbowTester.run(
    'final class declaration',

    'final class TestClass\n' +
    '{\n' +
    '}',

    'final class TestClass\n' +
    '{\n' +
    '}'
);

RainbowTester.run(
    'child class declaration',

    'class Collection extends ArrayObject {}',

    'class Collection extends ArrayObject {}'
);

RainbowTester.run(
    'final child class declaration',

    'final class TestClass extends \\Some\\Other\\Class {}',

    'final class TestClass extends \\Some\\Other\\Class {}'
);

RainbowTester.run(
    'test static',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();'
);

RainbowTester.run(
    'test magic function',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}'
);

RainbowTester.run(
    'test magic method',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}'
);

RainbowTester.run(
    'test new class',

    'new SomeClass();',

    'new SomeClass();'
);

RainbowTester.run(
    'test new namespace class',

    'new Sonic\\Database\\Query();',

    'new Sonic\\Database\\Query();'
);

RainbowTester.run(
    'test new class without parenthesis',

    'new Sonic\\Controller;',

    'new Sonic\\Controller;'
);

RainbowTester.run(
    'test static class call',

    '$path = Sonic\\App::getInstance()->getPath();',

    '$path = Sonic\\App::getInstance()->getPath();'
);

RainbowTester.run(
    'constant language',

    'true; TRUE;',

    'true; TRUE;'
);

RainbowTester.run(
    'constant',

    'TEST_CONSTANT',

    'TEST_CONSTANT'
);

RainbowTester.run(
    'constant 2',

    '(TEST_CONSTANT_2)',

    '(TEST_CONSTANT_2)'
);

RainbowTester.run(
    'class constant',

    '$version = Sonic\\App::VERSION',

    '$version = Sonic\\App::VERSION'
);

RainbowTester.run(
    'static variable access',

    '$foo = Sonic\\App::$static_property;',

    '$foo = Sonic\\App::$static_property;'
);

RainbowTester.run(
    'type hint',

    'public static function getForUser(User $user, Sort $sort) {}',

    'public static function getForUser(User $user, Sort $sort) {}'
);

RainbowTester.run(
    'type hint with namespace',

    'public static function getForUser(\\SomeApp\\User $user) {}',

    'public static function getForUser(\\SomeApp\\User $user) {}'
);
RainbowTester.endTest('php');
<|endoftext|>


<commit_before>/**
 * Vosao CMS. Simple CMS for Google App Engine.
 * Copyright (C) 2009 Vosao development team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * email: vosao.dev@gmail.com
 */

/**
 * Declared in page.jsp
 *
 *   var pageId;
 *   var pageParentUrl;
 */

var page = null;
var editMode = pageId != '';
var pageRequest = null;
var currentLanguage = '';
var structureTemplates = null;

$(function(){
    $(".datepicker").datepicker({dateFormat:'dd.mm.yy'});
    Vosao.initJSONRpc(loadData);
    // hover states on the link buttons
    $('a.button').hover(
     	function() { $(this).addClass('ui-state-hover'); },
       	function() { $(this).removeClass('ui-state-hover'); }
    );
    initVersionDialog();
    $('#title').change(onTitleChange);
    $('#pageType').change(onPageTypeChange);
    $('#structure').change(onStructureChange);
    $('#pageForm').submit(function() {onPageUpdate(); return false;});
    $('#pagePreview').click(onPagePreview);
    $('#pageCancelButton').click(onPageCancel);
    $('#approveButton').click(onPageApprove);
    $('ul.ui-tabs-nav li:nth-child(1)').addClass('ui-state-active')
    		.removeClass('ui-state-default');
    $('#metadata').click(function() {
    	$('#meta').toggle();
    });
});

function loadData() {
	Vosao.jsonrpc.pageService.getPageRequest(function(r) {
		pageRequest = r;
		page = pageRequest.page;
		loadTemplates();
		loadStructures();
		loadPage();
	}, pageId, pageParentUrl);
}

function callLoadPage() {
	Vosao.jsonrpc.pageService.getPageRequest(function(r) {
		pageRequest = r;
		page = pageRequest.page;
		editMode = pageId != null;
		loadPage();
	}, pageId, pageParentUrl);
}

function loadPage() {
	if (editMode) {
		pageId = String(page.id);
		pageParentUrl = page.parentUrl;
		loadVersions();
		loadLanguages();
		loadContents();
	} else {
		pages['1'] = page;
	}
	initPageForm();
	loadPagePermission();
}

function loadTemplates() {
	var r = pageRequest.templates;
	var html = '';
    $.each(r.list, function (n,value) {
        html += '<option value="' + value.id + '">'
            + value.title + '</option>';
    });
    $('#templates').html(html);
    if (page != null) {
        $('#templates').val(page.template);
    }
    else {
        $('#templates').val($.cookie("page_template"));
    }
}

function initPageForm() {
	var urlEnd = pageParentUrl == '/' ? '' : '/';
	if (page != null) {
		$('#title').val(page.title);
		$('#titleDiv').hide();
		if (page.parentUrl == '' || page.parentUrl == null) {
			$('#friendlyUrl').hide();
			$('#friendlyUrl').val('');
			$('#parentFriendlyUrl').html('/');
		} else {
			$('#friendlyUrl').show();
			$('#friendlyUrl').val(page.pageFriendlyURL);
			$('#parentFriendlyUrl').html(page.parentFriendlyURL + urlEnd);
		}
	    if (pageRequest.children.list.length > 0) {
	     	$('#parentFriendlyUrl').hide();
	       	$('#friendlyUrl').hide();
	       	$('#friendlyUrlSpan').html(page.friendlyURL);
	    }
		$('#pageType').val(page.pageTypeString);
		$('#publishDate').val(page.publishDateString);
		$('#commentsEnabled').each(function() {
			this.checked = page.commentsEnabled;
		});
		$('#searchable').each(function() {
			this.checked = page.searchable;
		});
		$('#velocityProcessing').each(function() {
			this.checked = page.velocityProcessing;
		});
		$('#templates').val(page.template);
		$('#pageState').html(page.stateString == 'EDIT' ? 'Edit' : 'Approved');
		$('#pageCreateDate').html(page.createDateString);
		$('#pageModDate').html(page.modDateString);
		$('#pageCreateUser').html(page.createUserEmail);
		$('#pageModUser').html(page.modUserEmail);
		$('#keywords').html(page.keywords);
		$('#description').html(page.description);
		$('.contentTab').show();
		$('.childrenTab').show();
		$('.commentsTab').show();
		$('.securityTab').show();
		$('#pagePreview').show();
		$('#versions').show();
	} else {
		$('#title').val('');
		$('#titleDiv').show();
		$('#titleLocal').val('');
		$('#friendlyUrl').show();
		$('#friendlyUrl').val('');
		$('#parentFriendlyUrl').html(pageParentUrl + urlEnd);
		$('#pageType').val('SIMPLE');
		$('#publishDate').val(Vosao.formatDate(new Date()));
		$('#commentsEnabled, #searchable, #velocityProcessing').each(function() {
			this.checked = false;
		});
		$('#pageState').html('Edit');
		$('#pageCreateUser').html('');
		$('#pageCreateDate').html('');
		$('#pageModUser').html('');
		$('#pageModDate').html('');
		$('#keywords').html('');
		$('#description').html('');
		$('.contentTab').hide();
		$('.childrenTab').hide();
		$('.commentsTab').hide();
		$('.securityTab').hide();
		$('#pagePreview').hide();
		$('#versions').hide();
	}
	onPageTypeChange();
}

function onPageUpdate() {
	var pageVO = Vosao.javaMap( {
		id : pageId,
		titles : getTitles(),
		friendlyUrl : $('#parentFriendlyUrl').text() + $('#friendlyUrl').val(),
		publishDate : $('#publishDate').val(),
		commentsEnabled : String($('#commentsEnabled:checked').size() > 0),
		searchable : String($('#searchable:checked').size() > 0),
		velocityProcessing : String($('#velocityProcessing:checked').size() > 0),
		template : $('#templates option:selected').val(),
		approve : String($('#approveOnPageSave:checked, #approveOnContentSave:checked').size() > 0),
		pageType: $('#pageType').val(),
		structureId: $('#structure').val(),
		structureTemplateId: $('#structureTemplate').val(),
		keywords: $('#keywords').val(),
		description: $('#description').val()
	});
	$.cookie("page_template", pageVO.map.template, {path:'/', expires: 10});
	Vosao.jsonrpc.pageService.savePage(function(r) {
		if (r.result == 'success') {
			if (editMode) {
				location.href = '/cms/pages.jsp';
			}
			pageId = r.message;
			Vosao.info("Page was successfully saved.");
			location.href = '/cms/page/content.jsp?id=' + pageId;
		} else {
			Vosao.showServiceMessages(r);
		}
	}, pageVO);
}

function onTitleChange() {
	if (editMode) {
		return;
	}
	var url = $("#friendlyUrl").val();
	var title = $("#title").val();
	if (url == '') {
		$("#friendlyUrl").val(Vosao.urlFromTitle(title));
	}
}

function onPageTypeChange() {
	if ($('#pageType').val() == 'SIMPLE') {
		$('#structuredControls').hide();
	}
	if ($('#pageType').val() == 'STRUCTURED') {
		$('#structuredControls').show();
		$('#structure').val(page.structureId);
		onStructureChange();
	}
}

function onPagePreview() {
	var url = page.friendlyURL + '?language=' + currentLanguage
		+ '&version=' + page.version;
	window.open(url, "preview");
}

function onPageCancel() {
	location.href = '/cms/pages.jsp';
}

function onPageApprove() {
	Vosao.jsonrpc.pageService.approve(function(r) {
		Vosao.showServiceMessages(r);
		callLoadPage();
	}, pageId);
}

function loadPagePermission() {
    var r = pageRequest.pagePermission;
   	if (r.publishGranted) {
   		$('#approveButton').show();
   		$('#approveOnPageSaveDiv').show();
    	}
   	else {
   		$('#approveButton').hide();
   		$('#approveOnPageSaveDiv').hide();
   	}
   	if (r.changeGranted) {
   		$('#pageSaveButton').show();
   	}
   	else {
   		$('#pageSaveButton').hide();
   	}
   	if (r.admin && editMode) {
   		$('.securityTab').show();
   	}
   	else {
   		$('.securityTab').hide();
   	}
}

function loadStructures() {
	var h = '';
	$.each(pageRequest.structures.list, function(i, struct) {
		var sel = i == 0 ? 'selected="selected"' : '';
		h += '<option ' + sel + ' value="' + struct.id + '">' + struct.title
			+ '</option>';
	});
	$('#structure').html(h);
}

function onStructureChange() {
	var structureId = $('#structure').val();
	var h = '';
	Vosao.jsonrpc.structureTemplateService.selectByStructure(function(r) {
		var h = '';
		$.each(r.list, function(i, template) {
			var sel = i == 0 ? 'selected="selected"' : '';
			h += '<option ' + sel + ' value="' + template.id + '">' + template.title
				+ '</option>';
		});
		$('#structureTemplate').html(h);
		$('#structureTemplate').val(page.structureTemplateId);
	}, structureId)
}

function getTitles() {
	if (!editMode) {
		return 'en' + $('#title').val();
	}
}

function loadLanguages() {
	var r = pageRequest.languages;
	languages = {};
	var h = '';
	$.each(r.list, function(i, value) {
		languages[value.code] = value;
	});
}

function loadContents() {
	if (editMode) {
		var r = pageRequest.contents;
		var allowedLangs = {};
		if (pageRequest.pagePermission.allLanguages) {
			allowedLangs = languages;
		}
		else {
			$.each(pageRequest.pagePermission.languagesList.list,
					function(i, value) {
				allowedLangs[value] = languages[value];
			});
		}
		if (allowedLangs[Vosao.ENGLISH_CODE] != undefined) {
			currentLanguage = Vosao.ENGLISH_CODE;
		}
		else {
			currentLanguage = r.list[0].languageCode;
		}
	}
}
<commit_msg>http://code.google.com/p/vosao/issues/detail?id=110<commit_after>/**
 * Vosao CMS. Simple CMS for Google App Engine.
 * Copyright (C) 2009 Vosao development team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * email: vosao.dev@gmail.com
 */

/**
 * Declared in page.jsp
 *
 *   var pageId;
 *   var pageParentUrl;
 */

var page = null;
var editMode = pageId != '';
var pageRequest = null;
var currentLanguage = '';
var structureTemplates = null;

$(function(){
    $(".datepicker").datepicker({dateFormat:'dd.mm.yy'});
    Vosao.initJSONRpc(loadData);
    // hover states on the link buttons
    $('a.button').hover(
     	function() { $(this).addClass('ui-state-hover'); },
       	function() { $(this).removeClass('ui-state-hover'); }
    );
    initVersionDialog();
    $('#title').change(onTitleChange);
    $('#pageType').change(onPageTypeChange);
    $('#structure').change(onStructureChange);
    $('#pageForm').submit(function() {onPageUpdate(); return false;});
    $('#pagePreview').click(onPagePreview);
    $('#pageCancelButton').click(onPageCancel);
    $('#approveButton').click(onPageApprove);
    $('ul.ui-tabs-nav li:nth-child(1)').addClass('ui-state-active')
    		.removeClass('ui-state-default');
    $('#metadata').click(function() {
    	$('#meta').toggle();
    });
});

function loadData() {
	Vosao.jsonrpc.pageService.getPageRequest(function(r) {
		pageRequest = r;
		page = pageRequest.page;
		loadTemplates();
		loadStructures();
		loadPage();
	}, pageId, pageParentUrl);
}

function callLoadPage() {
	Vosao.jsonrpc.pageService.getPageRequest(function(r) {
		pageRequest = r;
		page = pageRequest.page;
		editMode = pageId != null;
		loadPage();
	}, pageId, pageParentUrl);
}

function loadPage() {
	if (editMode) {
		pageId = String(page.id);
		pageParentUrl = page.parentUrl;
		loadVersions();
		loadLanguages();
		loadContents();
	} else {
		pages['1'] = page;
	}
	initPageForm();
	loadPagePermission();
}

function loadTemplates() {
	var r = pageRequest.templates;
	var html = '';
    $.each(r.list, function (n,value) {
        html += '<option value="' + value.id + '">'
            + value.title + '</option>';
    });
    $('#templates').html(html);
    if (page != null) {
        $('#templates').val(page.template);
    }
    else {
        $('#templates').val($.cookie("page_template"));
    }
}

function initPageForm() {
	var urlEnd = pageParentUrl == '/' ? '' : '/';
	if (page != null) {
		$('#title').val(page.title);
		$('#titleDiv').hide();
		if (page.parentUrl == '' || page.parentUrl == null) {
			$('#friendlyUrl').hide();
			$('#friendlyUrl').val('');
			$('#parentFriendlyUrl').html('/');
		} else {
			$('#friendlyUrl').show();
			$('#friendlyUrl').val(page.pageFriendlyURL);
			$('#parentFriendlyUrl').html(page.parentFriendlyURL + urlEnd);
		}
	    if (pageRequest.children.list.length > 0) {
	     	$('#parentFriendlyUrl').hide();
	       	$('#friendlyUrl').hide();
	       	$('#friendlyUrlSpan').html(page.friendlyURL);
	    }
		$('#pageType').val(page.pageTypeString);
		$('#publishDate').val(page.publishDateString);
		$('#commentsEnabled').each(function() {
			this.checked = page.commentsEnabled;
		});
		$('#searchable').each(function() {
			this.checked = page.searchable;
		});
		$('#velocityProcessing').each(function() {
			this.checked = page.velocityProcessing;
		});
		$('#templates').val(page.template);
		$('#pageState').html(page.stateString == 'EDIT' ? 'Edit' : 'Approved');
		$('#pageCreateDate').html(page.createDateString);
		$('#pageModDate').html(page.modDateString);
		$('#pageCreateUser').html(page.createUserEmail);
		$('#pageModUser').html(page.modUserEmail);
		$('#keywords').html(page.keywords);
		$('#description').html(page.description);
		$('.contentTab').show();
		$('.childrenTab').show();
		$('.commentsTab').show();
		$('.securityTab').show();
		$('#pagePreview').show();
		$('#versions').show();
	} else {
		$('#title').val('');
		$('#titleDiv').show();
		$('#titleLocal').val('');
		$('#friendlyUrl').show();
		$('#friendlyUrl').val('');
		$('#parentFriendlyUrl').html(pageParentUrl + urlEnd);
		$('#pageType').val('SIMPLE');
		$('#publishDate').val(Vosao.formatDate(new Date()));
		$('#commentsEnabled, #velocityProcessing').each(function() {
			this.checked = false;
		});
		$('#searchable').each(function() {
			this.checked = true;
		});
		$('#pageState').html('Edit');
		$('#pageCreateUser').html('');
		$('#pageCreateDate').html('');
		$('#pageModUser').html('');
		$('#pageModDate').html('');
		$('#keywords').html('');
		$('#description').html('');
		$('.contentTab').hide();
		$('.childrenTab').hide();
		$('.commentsTab').hide();
		$('.securityTab').hide();
		$('#pagePreview').hide();
		$('#versions').hide();
	}
	onPageTypeChange();
}

function onPageUpdate() {
	var pageVO = Vosao.javaMap( {
		id : pageId,
		titles : getTitles(),
		friendlyUrl : $('#parentFriendlyUrl').text() + $('#friendlyUrl').val(),
		publishDate : $('#publishDate').val(),
		commentsEnabled : String($('#commentsEnabled:checked').size() > 0),
		searchable : String($('#searchable:checked').size() > 0),
		velocityProcessing : String($('#velocityProcessing:checked').size() > 0),
		template : $('#templates option:selected').val(),
		approve : String($('#approveOnPageSave:checked, #approveOnContentSave:checked').size() > 0),
		pageType: $('#pageType').val(),
		structureId: $('#structure').val(),
		structureTemplateId: $('#structureTemplate').val(),
		keywords: $('#keywords').val(),
		description: $('#description').val()
	});
	$.cookie("page_template", pageVO.map.template, {path:'/', expires: 10});
	Vosao.jsonrpc.pageService.savePage(function(r) {
		if (r.result == 'success') {
			if (editMode) {
				location.href = '/cms/pages.jsp';
			}
			pageId = r.message;
			Vosao.info("Page was successfully saved.");
			location.href = '/cms/page/content.jsp?id=' + pageId;
		} else {
			Vosao.showServiceMessages(r);
		}
	}, pageVO);
}

function onTitleChange() {
	if (editMode) {
		return;
	}
	var url = $("#friendlyUrl").val();
	var title = $("#title").val();
	if (url == '') {
		$("#friendlyUrl").val(Vosao.urlFromTitle(title));
	}
}

function onPageTypeChange() {
	if ($('#pageType').val() == 'SIMPLE') {
		$('#structuredControls').hide();
	}
	if ($('#pageType').val() == 'STRUCTURED') {
		$('#structuredControls').show();
		$('#structure').val(page.structureId);
		onStructureChange();
	}
}

function onPagePreview() {
	var url = page.friendlyURL + '?language=' + currentLanguage
		+ '&version=' + page.version;
	window.open(url, "preview");
}

function onPageCancel() {
	location.href = '/cms/pages.jsp';
}

function onPageApprove() {
	Vosao.jsonrpc.pageService.approve(function(r) {
		Vosao.showServiceMessages(r);
		callLoadPage();
	}, pageId);
}

function loadPagePermission() {
    var r = pageRequest.pagePermission;
   	if (r.publishGranted) {
   		$('#approveButton').show();
   		$('#approveOnPageSaveDiv').show();
    	}
   	else {
   		$('#approveButton').hide();
   		$('#approveOnPageSaveDiv').hide();
   	}
   	if (r.changeGranted) {
   		$('#pageSaveButton').show();
   	}
   	else {
   		$('#pageSaveButton').hide();
   	}
   	if (r.admin && editMode) {
   		$('.securityTab').show();
   	}
   	else {
   		$('.securityTab').hide();
   	}
}

function loadStructures() {
	var h = '';
	$.each(pageRequest.structures.list, function(i, struct) {
		var sel = i == 0 ? 'selected="selected"' : '';
		h += '<option ' + sel + ' value="' + struct.id + '">' + struct.title
			+ '</option>';
	});
	$('#structure').html(h);
}

function onStructureChange() {
	var structureId = $('#structure').val();
	var h = '';
	Vosao.jsonrpc.structureTemplateService.selectByStructure(function(r) {
		var h = '';
		$.each(r.list, function(i, template) {
			var sel = i == 0 ? 'selected="selected"' : '';
			h += '<option ' + sel + ' value="' + template.id + '">' + template.title
				+ '</option>';
		});
		$('#structureTemplate').html(h);
		$('#structureTemplate').val(page.structureTemplateId);
	}, structureId)
}

function getTitles() {
	if (!editMode) {
		return 'en' + $('#title').val();
	}
}

function loadLanguages() {
	var r = pageRequest.languages;
	languages = {};
	var h = '';
	$.each(r.list, function(i, value) {
		languages[value.code] = value;
	});
}

function loadContents() {
	if (editMode) {
		var r = pageRequest.contents;
		var allowedLangs = {};
		if (pageRequest.pagePermission.allLanguages) {
			allowedLangs = languages;
		}
		else {
			$.each(pageRequest.pagePermission.languagesList.list,
					function(i, value) {
				allowedLangs[value] = languages[value];
			});
		}
		if (allowedLangs[Vosao.ENGLISH_CODE] != undefined) {
			currentLanguage = Vosao.ENGLISH_CODE;
		}
		else {
			currentLanguage = r.list[0].languageCode;
		}
	}
}
<|endoftext|>