<commit_before>/* AJAX SETUP FOR CSRF */
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/* END AJAX SETUP */

$(document).ready(function() {
    $('#image-name').hide();

    $('.img-polaroid').imagesLoaded().always( function() {
        var imageWidth = $('.img-polaroid').outerWidth() - 24;
        if(imageWidth < 150) imageWidth = 150;
        $('.image-choice-button').width(imageWidth);
    });

    //Ajax request to remove profile image
    $('#confirm-delete').click(function() {
        confirmRemoveImage();
    });

    function confirmRemoveImage() {
        $.ajax({
            method: 'DELETE',
            url: 'removeprofileimage/',
            success: function(res) {
                res = JSON.parse(res);
                $('img#profile-image').attr('src', res['url']);
                $('#remove-image-modal').modal("hide");
                var utils = new Utils();
                utils.setStatusMessage(res['message'], 'alert-success');
            },
            error: function(res) {
                res = JSON.parse(res['responseText']);
                $('#remove-image-modal').modal("hide");
                var utils = new Utils();
                utils.setStatusMessage(res['message'], 'alert-danger');
            },
            crossDomain: false
        });
    }

    $('#userprofile-tabs > li > a').click(function(e) {
        e.preventDefault();
        updateActiveTab(this.getAttribute('href').substr(1));
        $(this).tab('show');
    })

    function updateActiveTab(activetab) {
        var data = JSON.stringify({active_tab : activetab});
        $.ajax({
            method: 'POST',
            data: data,
            url: 'updateactivetab/',
            crossDomain: false
        });
    }

    $('.privacybox').click(
        function() {
            var checkbox = $(this).find('input');
            var checked = checkbox.is(':checked');
            checkbox.prop('checked', !checked)

            animatePrivacyBox(this, checked);
        }
    )

    function animatePrivacyBox(checkbox, state) {
        if(state) {
            $(checkbox).stop().animate(
                {  opacity: 0.30  }, 100
            );
            $(checkbox).removeClass("on");
            $(checkbox).addClass("off");
        }
        else {
            $(checkbox).removeClass("off");
            $(checkbox).addClass("on");
            $(checkbox).stop().animate(
                {  opacity: 1.0 }, 100
            );
        }
    }

    // Popover for privacy
    $('#privacy-help').popover({placement: 'bottom'});

    /* Image cropping and uploading */
    var api;
    var formData = false;
    var x, y, x2, y2, w, h;

    if(window.FormData) {
        formData = new FormData();
    }

    $('input[type=file]').change(function() {
        readURL(this);
    });

    function readURL(input) {

        if (input.files && input.files[0]) {
            var file = input.files[0];

            if (!file.type.match(/image.*/)) {
                return;
            }

            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onloadend = function(e) {
                var api;
                $('.jcrop-holder').remove();
                api = $.Jcrop('#image-resize', {
                    // start off with jcrop-light class
                    bgOpacity: 0.5,
                    bgColor: 'white',
                    addClass: 'jcrop-light',
                    boxHeight: 300,
                    aspectRatio: 3/4,
                    onChange: updateCoords,
                    onSelect: updateCoords,
                    keySupport: false,
                    allowSelect: false
                });
                api.setImage(e.target.result, function () {
                    api.setSelect([0,0,500,500]);
                });
                api.setOptions({ bgFade: true });
                api.ui.selection.addClass('jcrop-selection');
                api.allowResize = true;
                if(formData) {
                    formData.append("image", file);
                }

                $('#upload-button').show();
            }
        }
    }

    function updateCoords(c) {
        x = c.x;
        y = c.y;
        x2 = c.x2;
        y2 = c.y2;
        w = c.w;
        h = c.h;
        $('#inputx').val(c.x);
        $('#inputy').val(c.y);
        $('#inputx2').val(c.x2);
        $('#inputy2').val(c.y2);
        $('#inputw').val(c.w);
        $('#inputh').val(c.h);
    }

    var setStatus = function(statusMsg) {
        $('#status').html(statusMsg);
    }

    $('#upload-image-form').submit(function(e) {
        if (formData) {
            e.preventDefault();

            if(!imageChosen()) return;

            setStatus("Laster opp bildet...")

            //JCrop select coordinates
            formData.append("x", x);
            formData.append("y", y);
            formData.append("x2", x2);
            formData.append("y2", y2);
            formData.append("w", w);
            formData.append("h", h);

            $.ajax({
                url: "uploadimage/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                crossDomain: false,
                success: function (res) {
                    res = JSON.parse(res);
                    $('#profile-image').attr("src", res['image-url']);
                    $('#upload-image-modal').modal('hide');
                    var utils = new Utils();
                    utils.setStatusMessage(res['message'], 'alert-success');
                },
                error: function(res) {
                    res = JSON.parse(res);
                    var utils = new Utils();
                    $('#upload-image-modal').modal('hide');
                    utils.setStatusMessage(res['message'], 'alert-success');
                }
            });
        }
        else {
            if(!imageChosen()) {
                e.preventDefault();
            }
        }
    });

    function imageChosen() {
        var fileInput = $('input[type=file]')[0];
            if(!fileInput || fileInput.files.length < 1) {
                setStatus("Ingen fil valgt.");
                return false;
            }
        return true;
    }

    /* End image cropping and uploading*/

/*
 JS for marks pane
*/

    $(".marks").click(function() {
        var markscheckbox = $("#marks-checkbox");
        var checked = markscheckbox.is(':checked');
        markscheckbox.prop('checked', !checked)

        if(!checked) {
            $(".marks").removeClass("off").addClass("on");
            updateMarkRules(true);
        }
        else {
            $(".marks").removeClass("on").addClass("off");
            updateMarkRules(false);
        }
    });

    var updateMarkRules = function(accepted) {

        var utils = new Utils();

        $.ajax({
            method: 'POST',
            url: 'update_mark_rules/',
            data: { 'rules_accepted': accepted },
            success: function(res) {
                res = jQuery.parseJSON(res);
                utils.setStatusMessage(res['message'], 'alert-success');
            },
            error: function() {
                utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
            },
            crossDomain: false
        });
    }

/*
 JS for email management.
*/

    $('button.addnewemail').click(function() {
        $('tr.addnewemail').show();
        $(this).hide();
    });
    $('.emptyonclick').focus(function() {
        $(this).val('');
    });

    $('tr').each(function(i, row) {
// Ajax request to delete an email
        $(row).find('button.delete').click(function() {
            email = $(row).find('span.email').text();
            deleteEmail(email, row);
        });
// Ajax request to set email as primary
        $(row).find('button.primary').click(function() {
            email = $(row).find('span.email').text();
            setPrimaryEmail(email, row);
        });
// Ajax request to send verification mail
        $(row).find('button.verify').click(function() {
            email = $(row).find('span.email').text();
            verifyEmail(email, row);
        });
    });

    var deleteEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'delete_email/',
            data: {'email':email, },
            success: function() {
                // TODO Make animation
                $(row).hide();
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

    var setPrimaryEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'set_primary/',
            data: {'email':email, },
            success: function() {
                $('button.active').removeClass('active').removeClass('btn-success').addClass('btn-default')
                    .prop('disabled', false).text('Sett primær');
                $(row).find('button.primary').addClass('active').removeClass('btn-default').addClass('btn-success')
                    .prop('disabled', true).text('Primær');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

    var verifyEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'verify_email/',
            data: {'email':email, },
            success: function() {
                var utils = new Utils();
                utils.setStatusMessage('En ny verifikasjonsepost har blitt sendt til ' + email + '.', 'alert-success');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

/*
  JS for membership
*/

    $(".hasDatePicker").datepicker({
        yearRange: "2004:" + new Date().getFullYear(),
        changeYear: true,
        dateFormat: "yy-mm-dd"
    });

    $("#membership-details").submit(function(event) {
        event.preventDefault();
        $.ajax({
            method: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() {
                var utils = new Utils();
                utils.setStatusMessage('Detaljer for ditt medlemskap har blitt lagret.', 'alert-success');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    });
});

<commit_msg>Fixed bug where pressing checkbox would do nothing<commit_after>/* AJAX SETUP FOR CSRF */
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/* END AJAX SETUP */

$(document).ready(function() {
    $('#image-name').hide();

    $('.img-polaroid').imagesLoaded().always( function() {
        var imageWidth = $('.img-polaroid').outerWidth() - 24;
        if(imageWidth < 150) imageWidth = 150;
        $('.image-choice-button').width(imageWidth);
    });

    //Ajax request to remove profile image
    $('#confirm-delete').click(function() {
        confirmRemoveImage();
    });

    function confirmRemoveImage() {
        $.ajax({
            method: 'DELETE',
            url: 'removeprofileimage/',
            success: function(res) {
                res = JSON.parse(res);
                $('img#profile-image').attr('src', res['url']);
                $('#remove-image-modal').modal("hide");
                var utils = new Utils();
                utils.setStatusMessage(res['message'], 'alert-success');
            },
            error: function(res) {
                res = JSON.parse(res['responseText']);
                $('#remove-image-modal').modal("hide");
                var utils = new Utils();
                utils.setStatusMessage(res['message'], 'alert-danger');
            },
            crossDomain: false
        });
    }

    $('#userprofile-tabs > li > a').click(function(e) {
        e.preventDefault();
        updateActiveTab(this.getAttribute('href').substr(1));
        $(this).tab('show');
    })

    function updateActiveTab(activetab) {
        var data = JSON.stringify({active_tab : activetab});
        $.ajax({
            method: 'POST',
            data: data,
            url: 'updateactivetab/',
            crossDomain: false
        });
    }

    $('.privacybox').click(
        function() {
            var checkbox = $(this).find('input');
            var checked = checkbox.is(':checked');
            checkbox.prop('checked', !checked)

            animatePrivacyBox(this, checked);
        }
    )

    function animatePrivacyBox(checkbox, state) {
        if(state) {
            $(checkbox).stop().animate(
                {  opacity: 0.30  }, 100
            );
            $(checkbox).removeClass("on");
            $(checkbox).addClass("off");
        }
        else {
            $(checkbox).removeClass("off");
            $(checkbox).addClass("on");
            $(checkbox).stop().animate(
                {  opacity: 1.0 }, 100
            );
        }
    }

    // Popover for privacy
    $('#privacy-help').popover({placement: 'bottom'});

    /* Image cropping and uploading */
    var api;
    var formData = false;
    var x, y, x2, y2, w, h;

    if(window.FormData) {
        formData = new FormData();
    }

    $('input[type=file]').change(function() {
        readURL(this);
    });

    function readURL(input) {

        if (input.files && input.files[0]) {
            var file = input.files[0];

            if (!file.type.match(/image.*/)) {
                return;
            }

            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onloadend = function(e) {
                var api;
                $('.jcrop-holder').remove();
                api = $.Jcrop('#image-resize', {
                    // start off with jcrop-light class
                    bgOpacity: 0.5,
                    bgColor: 'white',
                    addClass: 'jcrop-light',
                    boxHeight: 300,
                    aspectRatio: 3/4,
                    onChange: updateCoords,
                    onSelect: updateCoords,
                    keySupport: false,
                    allowSelect: false
                });
                api.setImage(e.target.result, function () {
                    api.setSelect([0,0,500,500]);
                });
                api.setOptions({ bgFade: true });
                api.ui.selection.addClass('jcrop-selection');
                api.allowResize = true;
                if(formData) {
                    formData.append("image", file);
                }

                $('#upload-button').show();
            }
        }
    }

    function updateCoords(c) {
        x = c.x;
        y = c.y;
        x2 = c.x2;
        y2 = c.y2;
        w = c.w;
        h = c.h;
        $('#inputx').val(c.x);
        $('#inputy').val(c.y);
        $('#inputx2').val(c.x2);
        $('#inputy2').val(c.y2);
        $('#inputw').val(c.w);
        $('#inputh').val(c.h);
    }

    var setStatus = function(statusMsg) {
        $('#status').html(statusMsg);
    }

    $('#upload-image-form').submit(function(e) {
        if (formData) {
            e.preventDefault();

            if(!imageChosen()) return;

            setStatus("Laster opp bildet...")

            //JCrop select coordinates
            formData.append("x", x);
            formData.append("y", y);
            formData.append("x2", x2);
            formData.append("y2", y2);
            formData.append("w", w);
            formData.append("h", h);

            $.ajax({
                url: "uploadimage/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                crossDomain: false,
                success: function (res) {
                    res = JSON.parse(res);
                    $('#profile-image').attr("src", res['image-url']);
                    $('#upload-image-modal').modal('hide');
                    var utils = new Utils();
                    utils.setStatusMessage(res['message'], 'alert-success');
                },
                error: function(res) {
                    res = JSON.parse(res);
                    var utils = new Utils();
                    $('#upload-image-modal').modal('hide');
                    utils.setStatusMessage(res['message'], 'alert-success');
                }
            });
        }
        else {
            if(!imageChosen()) {
                e.preventDefault();
            }
        }
    });

    function imageChosen() {
        var fileInput = $('input[type=file]')[0];
            if(!fileInput || fileInput.files.length < 1) {
                setStatus("Ingen fil valgt.");
                return false;
            }
        return true;
    }

    /* End image cropping and uploading*/

/*
 JS for marks pane
*/

    function performMarkRulesClick() {
        var markscheckbox = $("#marks-checkbox");
        var checked = markscheckbox.is(':checked');
        markscheckbox.prop('checked', !checked);

        if(!checked) {
            $(".marks").removeClass("off").addClass("on");
            updateMarkRules(true);
        }
        else {
            $(".marks").removeClass("on").addClass("off");
            updateMarkRules(false);
        }
    }

    $(".marks").mouseup(function(e) {
        performMarkRulesClick();
    });

    $("#marks-checkbox").click(function(e){
        e.stopPropagation();
        e.preventDefault();
    });

    var updateMarkRules = function(accepted) {
        var utils = new Utils();

        $.ajax({
            method: 'POST',
            url: 'update_mark_rules/',
            data: { 'rules_accepted': accepted },
            success: function(res) {
                res = jQuery.parseJSON(res);
                utils.setStatusMessage(res['message'], 'alert-success');
            },
            error: function() {
                utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
            },
            crossDomain: false
        });
    }

/*
 JS for email management.
*/

    $('button.addnewemail').click(function() {
        $('tr.addnewemail').show();
        $(this).hide();
    });
    $('.emptyonclick').focus(function() {
        $(this).val('');
    });

    $('tr').each(function(i, row) {
// Ajax request to delete an email
        $(row).find('button.delete').click(function() {
            email = $(row).find('span.email').text();
            deleteEmail(email, row);
        });
// Ajax request to set email as primary
        $(row).find('button.primary').click(function() {
            email = $(row).find('span.email').text();
            setPrimaryEmail(email, row);
        });
// Ajax request to send verification mail
        $(row).find('button.verify').click(function() {
            email = $(row).find('span.email').text();
            verifyEmail(email, row);
        });
    });

    var deleteEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'delete_email/',
            data: {'email':email, },
            success: function() {
                // TODO Make animation
                $(row).hide();
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

    var setPrimaryEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'set_primary/',
            data: {'email':email, },
            success: function() {
                $('button.active').removeClass('active').removeClass('btn-success').addClass('btn-default')
                    .prop('disabled', false).text('Sett primær');
                $(row).find('button.primary').addClass('active').removeClass('btn-default').addClass('btn-success')
                    .prop('disabled', true).text('Primær');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

    var verifyEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'verify_email/',
            data: {'email':email, },
            success: function() {
                var utils = new Utils();
                utils.setStatusMessage('En ny verifikasjonsepost har blitt sendt til ' + email + '.', 'alert-success');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    }

/*
  JS for membership
*/

    $(".hasDatePicker").datepicker({
        yearRange: "2004:" + new Date().getFullYear(),
        changeYear: true,
        dateFormat: "yy-mm-dd"
    });

    $("#membership-details").submit(function(event) {
        event.preventDefault();
        $.ajax({
            method: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() {
                var utils = new Utils();
                utils.setStatusMessage('Detaljer for ditt medlemskap har blitt lagret.', 'alert-success');
            },
            error: function(res) {
                var utils = new Utils();
                if (res['status'] === 412) {
                    res = JSON.parse(res['responseText']);
                    utils.setStatusMessage(res['message'], 'alert-danger');
                }
                else {
                    utils.setStatusMessage('En uventet error ble oppdaget. Kontakt dotkom@online.ntnu.no for assistanse.', 'alert-danger');
                }
            },
            crossDomain: false
        });
    });
});

<|endoftext|>


<commit_before>import Ember from 'ember';
import Resize from '../motions/resize';
import { task } from '../ember-scheduler';
import Sprite from '../sprite';
import { emptyBounds } from '../bounds';

export default Ember.Component.extend({
  classNames: ['animated-container'],
  motionService: Ember.inject.service('-ea-motion'),
  onInitialRender: false,

  init() {
    this._super();
    this._signals = null;
    this._signalPromise = null;
    this._signalResolve= null;
    this._inserted = false;
    this.get('motionService').register(this);
  },

  didInsertElement() {
    this._inserted = true;
  },

  willDestroyElement() {
    this.get('motionService').unregister(this);
  },

  isAnimating: Ember.computed.alias('animate.isRunning'),

  animationStarting(message) {
    let { duration, task } = message;
    this.get('animate').perform(duration, task);
  },

  beginStaticMeasurement() {
    if (this.sprite) {
      this.sprite.unlock();
    }
  },

  endStaticMeasurement() {
    if (this.sprite) {
      this.sprite.lock();
    }
  },

  animate: task(function * (duration, animationTask) {
    let service = this.get('motionService');
    let sprite;
    let useMotion;

    if (this._inserted){
      sprite = Sprite.sizedStartingAt(this.element);
      this.sprite = sprite;
      sprite.lock();
      useMotion = true;
    } else {
      useMotion = this.get('onInitialRender');
    }

    yield * service.staticMeasurement(() => {
      if (!sprite) {
        sprite = Sprite.sizedEndingAt(this.element);
        this.sprite = sprite;
        sprite.initialBounds = emptyBounds;
      } else {
        sprite.measureFinalBounds();
      }
    });

    if (useMotion) {
      yield* new (this.motion || Resize)(this.sprite, { duration })._run();
    }

    yield animationTask;

    this.sprite.unlock();
    this.sprite = null;
  }).restartable()
});
<commit_msg>match timing between container and each<commit_after>import Ember from 'ember';
import Resize from '../motions/resize';
import { task } from '../ember-scheduler';
import Sprite from '../sprite';
import { emptyBounds } from '../bounds';
import { afterRender } from '../concurrency-helpers';

export default Ember.Component.extend({
  classNames: ['animated-container'],
  motionService: Ember.inject.service('-ea-motion'),
  onInitialRender: false,

  init() {
    this._super();
    this._signals = null;
    this._signalPromise = null;
    this._signalResolve= null;
    this._inserted = false;
    this.get('motionService').register(this);
  },

  didInsertElement() {
    this._inserted = true;
  },

  willDestroyElement() {
    this.get('motionService').unregister(this);
  },

  isAnimating: Ember.computed.alias('animate.isRunning'),

  animationStarting(message) {
    let { duration, task } = message;
    this.get('animate').perform(duration, task);
  },

  beginStaticMeasurement() {
    if (this.sprite) {
      this.sprite.unlock();
    }
  },

  endStaticMeasurement() {
    if (this.sprite) {
      this.sprite.lock();
    }
  },

  animate: task(function * (duration, animationTask) {
    let service = this.get('motionService');
    let sprite;
    let useMotion;

    if (this._inserted){
      sprite = Sprite.sizedStartingAt(this.element);
      this.sprite = sprite;
      sprite.lock();
      useMotion = true;
    } else {
      useMotion = this.get('onInitialRender');
    }

    yield afterRender();

    yield * service.staticMeasurement(() => {
      if (!sprite) {
        sprite = Sprite.sizedEndingAt(this.element);
        this.sprite = sprite;
        sprite.initialBounds = emptyBounds;
      } else {
        sprite.measureFinalBounds();
      }
    });

    if (useMotion) {
      yield* new (this.motion || Resize)(this.sprite, { duration })._run();
    }

    yield animationTask;

    this.sprite.unlock();
    this.sprite = null;
  }).restartable()
});
<|endoftext|>


<commit_before>/**
 * Breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <missallsunday@simplemachines.org>
 * @copyright Copyright (c) 2013 Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

/* The status stuff goes right here... */
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				/* Disable the button to prevent multiple clicks -_- */
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				/* Shhh! */
				else
					if(test== 'about:breeze')
					{
						alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

						/* Enable the button again... */
						jQuery('.status_button').removeAttr('disabled');
					}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

/* Handle the comments */
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = jQuery('#status_id'+Id).val();
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						dataType: 'json',
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: breeze_error_message,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();
									jQuery('#comment_loadplace_'+Id).append(html.data);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow');
							noty({
								text: breeze_error_message,
								timeout: 3500, type: 'error',
							});
						},
					});
				}
				return false;
			});
		});
	});

	/* Delete a comment */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'comment';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								dataType: 'json',
								success: function(html){
									if(html.type == 'error'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#comment_id_'+I).fadeOut('slow');
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	/* Delete a status */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'status';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								dataType: 'json',
								success: function(html){
									if(html.type == 'error'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#status_id_'+I).fadeOut('slow');
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

/* Facebox */
	jQuery(document).ready(function()
	{
		jQuery('a[rel*=facebox]').livequery(function()
		{
			jQuery(this).facebox(
			{
				loadingImage : smf_images_url + '/breeze/loading.gif',
				closeImage   : smf_images_url + '/breeze/error_close.png'
			});
		});
	});

/* infinitescroll  */
if (typeof breeze_infinite_scroll == "string")
{
	jQuery(document).ready(function(){
		jQuery.noConflict();
		jQuery('#breeze_display_status').infinitescroll({
			loading: {
				finished: undefined,
				msg: null,
				msgText  : breeze_page_loading,
				img   : smf_images_url + "/breeze/loading.gif",
				finishedMsg     : breeze_page_loading_end,
				selector: null,
				speed: 'slow',
				start: undefined
			},
			navSelector  : "#breeze_pagination",
			nextSelector : "#breeze_next_link",
			itemSelector : "li.windowbg",
			animate      : true,
		});
	});
}

/* Mark as read */
jQuery(document).ready(function(){
	jQuery('.Breeze_markRead').click(function(){

		var element = jQuery(this);
		var noti_id_delete = element.attr('id').replace(/[^0-9]/gi, '');
		noti_id_delete = parseInt(noti_id_delete, 10);
		var user = breeze_current_user;

		jQuery.ajax(
		{
			type: 'POST',
			url: smf_scripturl + '?action=breezeajax;sa=notimarkasread',
			data: ({content : noti_id_delete, user : user}),
			cache: false,
			dataType: 'json',
			success: function(html)
			{
				if(html.type == 'error')
				{
					noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				}

				else if(html.type == 'ok')
				{
					noty({text: breeze_noti_delete_after, timeout: 3500, type: 'success'});
				}
			},
			error: function (html)
			{
				noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			},
		});
	});
});

/* Delete a notification */
jQuery(document).ready(function(){
	jQuery('.Breeze_delete').click(function(){

		var element = jQuery(this);
		var noti_id = element.attr('id').replace(/[^0-9]/gi, '');
		noti_id = parseInt(noti_id, 10);
		var user = breeze_current_user;

		jQuery.ajax(
		{
			type: 'POST',
			url: smf_scripturl + '?action=breezeajax;sa=notidelete',
			data: ({content : noti_id, user : user}),
			cache: false,
			dataType: 'json',
			success: function(html)
			{
				if(html.type == 'error')
				{
					noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				}

				else if(html.type == 'ok')
				{
					noty({text: breeze_noti_markasread_after, timeout: 3500, type: 'success'});
				}
			},
			error: function (html)
			{
				noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			},
		});
	});
});<commit_msg>minor stuff<commit_after>/**
 * Breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <missallsunday@simplemachines.org>
 * @copyright Copyright (c) 2013 Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

/* The status stuff goes right here... */
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				/* Disable the button to prevent multiple clicks -_- */
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				/* Shhh! */
				else
					if(test== 'about:breeze')
					{
						alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

						/* Enable the button again... */
						jQuery('.status_button').removeAttr('disabled');
					}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html)
						{
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

/* Handle the comments */
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = jQuery('#status_id'+Id).val();
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						dataType: 'json',
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: breeze_error_message,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();
									jQuery('#comment_loadplace_'+Id).append(html.data);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow');
							noty({
								text: breeze_error_message,
								timeout: 3500, type: 'error',
							});
						},
					});
				}
				return false;
			});
		});
	});

	/* Delete a comment */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'comment';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								dataType: 'json',
								success: function(html){
									if(html.type == 'error'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#comment_id_'+I).fadeOut('slow');
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	/* Delete a status */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'status';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								dataType: 'json',
								success: function(html){
									if(html.type == 'error'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#status_id_'+I).fadeOut('slow');
										$noty.close();
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

/* Facebox */
	jQuery(document).ready(function()
	{
		jQuery('a[rel*=facebox]').livequery(function()
		{
			jQuery(this).facebox(
			{
				loadingImage : smf_images_url + '/breeze/loading.gif',
				closeImage   : smf_images_url + '/breeze/error_close.png'
			});
		});
	});

/* infinitescroll  */
if (typeof breeze_infinite_scroll == "string")
{
	jQuery(document).ready(function(){
		jQuery.noConflict();
		jQuery('#breeze_display_status').infinitescroll({
			loading: {
				finished: undefined,
				msg: null,
				msgText  : breeze_page_loading,
				img   : smf_images_url + "/breeze/loading.gif",
				finishedMsg     : breeze_page_loading_end,
				selector: null,
				speed: 'slow',
				start: undefined
			},
			navSelector  : "#breeze_pagination",
			nextSelector : "#breeze_next_link",
			itemSelector : "li.windowbg",
			animate      : true,
		});
	});
}

/* Mark as read */
jQuery(document).ready(function(){
	jQuery('.Breeze_markRead').click(function(){

		var element = jQuery(this);
		var noti_id_delete = element.attr('id').replace(/[^0-9]/gi, '');
		noti_id_delete = parseInt(noti_id_delete, 10);
		var user = breeze_current_user;

		jQuery.ajax({
			type: 'POST',
			url: smf_scripturl + '?action=breezeajax;sa=notimarkasread',
			data: ({content : noti_id_delete, user : user}),
			cache: false,
			dataType: 'json',
			success: function(html)
			{
				if(html.type == 'error')
				{
					noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				}

				else if(html.type == 'ok')
				{
					noty({text: breeze_noti_delete_after, timeout: 3500, type: 'success'});
				}
			},
			error: function (html)
			{
				noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			},
		});
	});
});

/* Delete a notification */
jQuery(document).ready(function(){
	jQuery('.Breeze_delete').click(function(){

		var element = jQuery(this);
		var noti_id = element.attr('id').replace(/[^0-9]/gi, '');
		noti_id = parseInt(noti_id, 10);
		var user = breeze_current_user;

		jQuery.ajax(
		{
			type: 'POST',
			url: smf_scripturl + '?action=breezeajax;sa=notidelete',
			data: ({content : noti_id, user : user}),
			cache: false,
			dataType: 'json',
			success: function(html)
			{
				if(html.type == 'error')
				{
					noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				}

				else if(html.type == 'ok')
				{
					noty({text: breeze_noti_markasread_after, timeout: 3500, type: 'success'});
				}
			},
			error: function (html)
			{
				noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			},
		});
	});
});<|endoftext|>


<commit_before>var toggle = false;
$("#isJsonFormatted").click(function () {
    $("#isJsonFormatted").attr("checked", !toggle);
    toggle = !toggle;
    formatJson(toggle);
});

function formatJson(isFormatted) {
    $.each($(".json-data"), function () {
            var payload = $(this).html();
            if (isFormatted) {
                try {
                    var result = JSON.parse(payload);
                } catch (e) {

                }
                $(this).attr("text", payload);
                var node = new PrettyJSON.view.Node({
                    el: $(this),
                    data: result
                });
                node.expandAll();
            }
            else {
                var unformattedJSON = $(this).attr("text");
                $(this).html(unformattedJSON);
            }
        }
    );
}<commit_msg>check if JSON is already formatted<commit_after>var toggle = false;
$("#isJsonFormatted").click(function () {
    $("#isJsonFormatted").attr("checked", !toggle);
    toggle = !toggle;
    formatJson(toggle);
});

function formatJson(isFormatted) {
    $.each($(".json-data"), function () {
            var payload = $(this).html();
            if (isFormatted) {
                if($(this).attr("text")) {
                    // json already formatted
                    return;
                }
                try {
                    var result = JSON.parse(payload);
                } catch (e) {

                }
                $(this).attr("text", payload);
                var node = new PrettyJSON.view.Node({
                    el: $(this),
                    data: result
                });
                node.expandAll();
            }
            else {
                var unformattedJSON = $(this).attr("text");
                $(this).html(unformattedJSON);
            }
        }
    );
}<|endoftext|>


<commit_before>import {savecopy} from "../../exporter/copy"
import {NativeExporter, uploadNative} from "../../exporter/native"
import {LatexExporter} from "../../exporter/latex"
import {HTMLExporter} from "../../exporter/html"
import {EpubExporter} from "../../exporter/epub"
import {WordExporter} from "../../exporter/word"

export class ModMenusActions {
    constructor(mod) {
        mod.actions = this
        this.mod = mod
    }

    saveRevision() {
        let that = this
        that.mod.editor.save(function() {
            uploadNative(that.mod.editor)
        })
    }

    saveCopy() {
        let that = this
        that.mod.editor.save(function() {
            if (that.mod.editor.doc.owner.id === that.mod.editor.user.id) {
                // We are copying from and to the same user. We don't need different databases for this.
                savecopy(that.mod.editor.doc, that.mod.editor.bibDB.db, that.mod.editor.imageDB.db,
                    that.mod.editor.bibDB.db, that.mod.editor.imageDB.db, that.mod.editor.user,
                    function(doc, docInfo, newBibEntries){
                        window.location.href = `/document/${doc.id}/`
                })
            } else {
                // We copy from one user to another. So we first load one set of databases, and then the other
                let oldBibDB = that.mod.editor.bibDB.db
                let oldImageDB = that.mod.editor.imageDB.db
                that.mod.editor.removeBibDB()
                that.mod.editor.removeImageDB()
                that.mod.editor.getBibDB(that.mod.editor.user.id, function(){
                    that.mod.editor.getImageDB(that.mod.editor.user.id, function(){
                        savecopy(that.mod.editor.doc, oldBibDB, oldImageDB, that.mod.editor.bibDB.db,
                                that.mod.editor.imageDB.db, that.mod.editor.user,
                                function(doc, docInfo, newBibEntries){
                            window.location.href = `/document/${doc.id}/`
                        })
                    })
                })
            }
        })
    }

    download() {
        let that = this
        that.mod.editor.save(function (){
            new NativeExporter(that.mod.editor.doc, that.mod.editor.bibDB, that.mod.editor.imageDB.db)
        })
    }

    downloadWord() {
        let that = this
        that.mod.editor.save(function() {
            new WordExporter(that.mod.editor.doc, that.mod.editor.bibDB.bibDB)
        })
    }

    downloadLatex() {
        let that = this
        that.mod.editor.save(function() {
            new LatexExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    downloadEpub() {
        let that = this
        that.mod.editor.save(function () {
            new EpubExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    downloadHtml() {
        let that = this
        that.mod.editor.save(function() {
            new HTMLExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    close() {
        let that = this
        that.mod.editor.save(function () {
            window.location.href = '/'
        })
    }

    showKeyBindings() {
        this.mod.editor.mod.tools.showKeyBindings.show()
    }

    print() {
        this.mod.editor.mod.tools.print.print()
    }

    wordCounter() {
        this.mod.editor.mod.tools.wordCount.wordCountDialog()
    }

}
<commit_msg>adjust to changes in 3.1 branch, part 2<commit_after>import {savecopy} from "../../exporter/copy"
import {NativeExporter, uploadNative} from "../../exporter/native"
import {LatexExporter} from "../../exporter/latex"
import {HTMLExporter} from "../../exporter/html"
import {EpubExporter} from "../../exporter/epub"
import {WordExporter} from "../../exporter/word"

export class ModMenusActions {
    constructor(mod) {
        mod.actions = this
        this.mod = mod
    }

    saveRevision() {
        let that = this
        that.mod.editor.save(function() {
            uploadNative(that.mod.editor)
        })
    }

    saveCopy() {
        let that = this
        that.mod.editor.save(function() {
            if (that.mod.editor.doc.owner.id === that.mod.editor.user.id) {
                // We are copying from and to the same user. We don't need different databases for this.
                savecopy(that.mod.editor.doc, that.mod.editor.bibDB.db, that.mod.editor.imageDB.db,
                    that.mod.editor.bibDB.db, that.mod.editor.imageDB.db, that.mod.editor.user,
                    function(doc, docInfo, newBibEntries){
                        window.location.href = `/document/${doc.id}/`
                })
            } else {
                // We copy from one user to another. So we first load one set of databases, and then the other
                let oldBibDB = that.mod.editor.bibDB.db
                let oldImageDB = that.mod.editor.imageDB.db
                that.mod.editor.removeBibDB()
                that.mod.editor.removeImageDB()
                that.mod.editor.getBibDB(that.mod.editor.user.id, function(){
                    that.mod.editor.getImageDB(that.mod.editor.user.id, function(){
                        savecopy(that.mod.editor.doc, oldBibDB, oldImageDB, that.mod.editor.bibDB.db,
                                that.mod.editor.imageDB.db, that.mod.editor.user,
                                function(doc, docInfo, newBibEntries){
                            window.location.href = `/document/${doc.id}/`
                        })
                    })
                })
            }
        })
    }

    download() {
        let that = this
        that.mod.editor.save(function (){
            new NativeExporter(that.mod.editor.doc, that.mod.editor.bibDB, that.mod.editor.imageDB.db)
        })
    }

    downloadWord() {
        let that = this
        that.mod.editor.save(function() {
            new WordExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    downloadLatex() {
        let that = this
        that.mod.editor.save(function() {
            new LatexExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    downloadEpub() {
        let that = this
        that.mod.editor.save(function () {
            new EpubExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    downloadHtml() {
        let that = this
        that.mod.editor.save(function() {
            new HTMLExporter(that.mod.editor.doc, that.mod.editor.bibDB)
        })
    }

    close() {
        let that = this
        that.mod.editor.save(function () {
            window.location.href = '/'
        })
    }

    showKeyBindings() {
        this.mod.editor.mod.tools.showKeyBindings.show()
    }

    print() {
        this.mod.editor.mod.tools.print.print()
    }

    wordCounter() {
        this.mod.editor.mod.tools.wordCount.wordCountDialog()
    }

}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
define(['log', 'jquery', 'lodash', 'backbone', 'console'], function (log, $, _, Backbone, Console) {

    var ConsoleList = Backbone.View.extend(
        /** @lends ConsoleList.prototype */
        {
            initialize: function (options) {
                var errMsg;
                // check whether a custom Console type is set
                if (_.has(options, 'consoleModel')) {
                    this.ConsoleModel = _.get(options, 'consoleModel');
                    // check whether the custom type is of type Console
                    if (!this.ConsoleModel instanceof Console) {
                        errMsg = 'custom console model is not a sub type of Console: ' + Console;
                        log.error(errMsg);
                        throw errMsg;
                    }
                } else {
                    this.ConsoleModel = Console;
                }
                this._consoles = [];

                if (!_.has(options, 'container')) {
                    errMsg = 'unable to find configuration for container';
                    log.error(errMsg);
                    throw errMsg;
                }
                var container = $(_.get(options, 'container'));
                //container.on('click', '.closeConsole', _.bindKey(this, 'hide'));
                // check whether container element exists in dom
                if (!container.length > 0) {
                    errMsg = 'unable to find container for console list with selector: ' + _.get(options, 'container');
                    log.error(errMsg);
                    throw errMsg;
                }
                this._$parent_el = container;
                if (!_.has(options, 'consoles.container')) {
                    errMsg = 'unable to find configuration for container';
                    log.error(errMsg);
                    throw errMsg;
                }
                var consoleContainer = this._$parent_el.find(_.get(options, 'consoles.container'));
                // check whether container element exists in dom
                if (!consoleContainer.length > 0) {
                    errMsg = 'unable to find container for console list with selector: ' + _.get(options, 'consoles.container');
                    log.error(errMsg);
                    throw errMsg;
                }
                this._$console_container = consoleContainer;
                this.options = options;
            },

            render: function () {
                var consoleHeaderContainer = this._$parent_el.children(_.get(this.options, 'headers.container'));
                var consoleList = $('

');
                consoleHeaderContainer.append(consoleList);

                var consoleListClass = _.get(this.options, 'headers.cssClass.list');
                consoleList.addClass(consoleListClass);
                this._$consoleList = consoleList;
                this.el = consoleList.get();
            },

            hideConsoleComponents: function () {
                var consoleHeaderContainer = this._$parent_el;
                consoleHeaderContainer.addClass('hide');
                $('#service-tabs-wrapper').css('height', '100%');
            },

            showConsoleComponents: function () {
                var self = this;
                var consoleHeaderContainer = self._$parent_el;
                var serviceWrapper =  $('#service-tabs-wrapper');
                serviceWrapper.css('height', '65%');
                consoleHeaderContainer.removeClass('hide');
                $("#service-tabs-wrapper").resizable({
                    handleSelector: ".splitter-horizontal",
                    handles: "s",
                    resize: function( event, ui ) {
                    }
                });
                var activeTab = self.options.application.tabController.activeTab;
                if (activeTab.getTitle() != "welcome-page") {
                    activeTab.getSiddhiFileEditor().getSourceView().editorResize();
                }
            },

            showActiveDebugConsole: function () {

            },

            createHeaderForConsole: function (console) {
                var consoleHeader = $('

');
                this._$consoleList.append(consoleHeader);

                var consoleHeaderClass = _.get(this.options, 'headers.cssClass.item');
                consoleHeader.addClass(consoleHeaderClass);

                var consoleHeaderLink = $('');
                consoleHeader.append(consoleHeaderLink);
                consoleHeader.link = consoleHeaderLink;
                consoleHeader.attr('href', '#' + console.cid);
                consoleHeaderLink.text(console.getTitle());

                consoleHeader.setText = function (text) {
                    consoleHeaderLink.text(text);
                };

                var self = this;
                consoleHeaderLink.click(function (e) {
                    consoleHeaderLink.tab('show');
                    self.setActiveConsole(console);
                    e.preventDefault();
                    e.stopPropagation();
                });

//                var consoleCloseBtn = $('<button type="button" >×</button>');
//                consoleHeader.append(consoleCloseBtn);
//                consoleCloseBtn.addClass( _.get(this.options, 'consoles.console.cssClass.console_close_btn'));
//                consoleCloseBtn.click(function(e){
//                    self.removeConsole(console);
//                    e.preventDefault();
//                    e.stopPropagation();
//                });

                console.on('title-changed', function (title) {
                    consoleHeaderLink.text(title);
                });
                console.setHeader(consoleHeader);
            },

            getConsoleContainer: function () {
                return this._$console_container;
            },
            /**
             * add a console to the console list.
             *
             * @param {Console} console an object of console
             * @fires ConsoleList#console-added
             */
            addConsole: function (console) {
                console.setParent(this);
                this.createHeaderForConsole(console);
                this._consoles.push(console);
                this.showConsoleComponents();
                /**
                 * console added event.
                 * @event ConsoleList#console-added
                 * @type {Console}
                 */
                this.trigger("console-added", console);
            },
            /**
             * gets Console
             * @param {string} console id
             * @returns {*}
             */
            getConsole: function (consoleId) {
                return _.find(this._consoles, ['id', consoleId]);
            },
            /**
             * removes a console
             * @param {Console} console the console instance
             * @fires ConsoleList#console-removed
             */
            removeConsole: function (console) {
                if (!_.includes(this._consoles, console)) {
                    var errMsg = 'console : ' + console.id + 'is not part of this console list.';
                    log.error(errMsg);
                    throw errMsg;
                }
                var consoleIndex = _.findIndex(this._consoles, console);

                _.remove(this._consoles, console);
                console.getHeader().remove();
                console.remove();
                /**
                 * console removed event.
                 * @event ConsoleList#console-removed
                 * @type {Console}
                 */
                this.trigger("console-removed", console);

                //switch to console at last or next index
                //make sure there are remaining consoles
                if (this._consoles.length > 0 && !_.isEqual(consoleIndex, -1)) {
                    // if removing console is 0th tab, next console is also the 0th
                    var nextConsoleIndex = 0;
                    if (!_.isEqual(consoleIndex, 0)) {
                        nextConsoleIndex = consoleIndex - 1;
                    }
                    var nextConsole = this._consoles[nextConsoleIndex];
                    this.setActiveConsole(nextConsole);
                } else {
                    this.hideConsoleComponents();
                }
            },
            /**
             * set selected console
             * @param {Console} tab the console instance
             * @fires ConsoleList#active-console-changed
             */
            setActiveConsole: function (console) {

                //set the corresponding active console for Tab
                if (console._type == "CONSOLE") {
                    $(".consoleToolbar").removeClass("hidden");
                    this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";
                } else {
                    $(".consoleToolbar").addClass("hidden");
                    this.options.application.tabController.getActiveTab()._lastActiveConsole = "DEBUG";
                }

                if (!_.isEqual(this.activeConsole, console)) {
                    if (!_.includes(this._consoles, console)) {
                        var errMsg = 'console : ' + console.cid + 'is not part of this console list.';
                        log.error(errMsg);
                        throw errMsg;
                    }
                    var lastActiveConsole = this.activeConsole;
                    this.activeConsole = console;
                    var activeConsoleHeaderClass = _.get(this.options, 'headers.cssClass.active');

                    if (!_.isUndefined(lastActiveConsole)) {
                        lastActiveConsole.getHeader().removeClass(activeConsoleHeaderClass);
                        lastActiveConsole.setActive(false);
                    }
                    this.activeConsole.getHeader().addClass(activeConsoleHeaderClass);
                    this.activeConsole.setActive(true);
                    /**
                     * Active console changed event.
                     * @event ConsoleList#active-tab-changed
                     * @type {object}
                     * @property {Console} lastActiveConsole - last active console.
                     * @property {Console} newActiveConsole - new active console.
                     */
                    var evt = {lastActiveConsole: lastActiveConsole, newActiveConsole: console};
                    this.trigger("active-console-changed", evt);
                }
            },
            /**
             * active console
             * @returns {Console}
             */
            getActiveConsole: function () {
                return this.activeConsole;
            },
            getConsoleList: function () {
                return this._consoles;
            },
            getGlobalConsole: function () {
                return _.find(this._consoles, function (console) {
                    return console._type == "CONSOLE"
                });
            },
            showActiveConsole: function (activeConsole) {
                activeConsole.show(true);
                _.each(this._consoles, function (console) {
                    if (console._type != "CONSOLE" && console._uniqueId != activeConsole._uniqueId) {
                        console.hide();
                    }
                });
            },
            hideConsoles: function () {
                _.each(this._consoles, function (console) {
                    console.hide();
                });
            },
            enableConsoleByTitle: function (title,type) {
                var globalConsole;
                var exist = false;
                var self = this;
                var globalConsole = this._consoles[_.findIndex(this._consoles, function(o) { return o._type ==
                    'CONSOLE'; })]
                _.each(this._consoles, function (console) {
                    if(console._type == type){
                        if (console._appName == title) {
                            console.show(true);
                            self.setActiveConsole(console);
                            globalConsole._isActive = false;
                        } else{
                            console.hide();
                            if(console._isActive){
                                self.setActiveConsole(globalConsole);
                            }
                        }
                    }
                });
            },
            /**
             * Creates a new console.
             * @param opts
             *          switchToNewConsole: indicate whether to switch to new console of type after creation
             *          consoleOptions: constructor args for the console
             * @returns {Console} created console instance
             * @event ConsoleList#console-added
             * @fires ConsoleList#active-console-changed
             */
            newConsole: function (opts) {
                var consoleOptions = _.get(opts, 'consoleOptions') || {};
                _.set(consoleOptions, 'application', this.options.application);
                _.assign(consoleOptions, _.get(this.options, 'consoles.console'));
                _.set(consoleOptions, 'consoles_container', _.get(this.options, 'consoles.container'));
                _.set(consoleOptions, 'parent', this);
                var consoleType = _.get(consoleOptions, '_type');
                var uniqueTabId = _.get(consoleOptions, 'uniqueTabId');
                var message = _.get(consoleOptions, 'message');
                var newConsole = this.getConsoleForType(consoleType, uniqueTabId);
                var currentFocusedFile = _.get(opts, 'consoleOptions.currentFocusedFile');
                var statusForCurrentFocusedFile = _.get(opts, 'consoleOptions.statusForCurrentFocusedFile');

                if (newConsole == undefined) {
                    newConsole = new this.ConsoleModel(consoleOptions);
                    if (consoleType == "CONSOLE") {
                        _.set(newConsole, '_title', _.get(consoleOptions, 'title'));
                        this.addConsole(newConsole);
                        _.set(newConsole, '_runStatus', true);
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";

                        if (statusForCurrentFocusedFile == "SUCCESS") {
                            newConsole.showInitialStartingMessage(currentFocusedFile + ".siddhi " + message);
                        } else if(statusForCurrentFocusedFile != "LOGGER"){
                            var message = {
                                "type": "ERROR",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                            newConsole.println(message);
                        }
                    } else {
                        _.set(newConsole, '_debugStatus', true);
                        _.set(newConsole, '_title', _.get(consoleOptions, 'title') + " - " + _.get(consoleOptions, 'appName'));
                        this.addConsole(newConsole);
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "DEBUG";
                    }
                } else if (newConsole !== undefined) {
                    if (consoleType == "CONSOLE") {
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";
                        var consoleMessage;
                        if (statusForCurrentFocusedFile == "SUCCESS") {
                            consoleMessage = {
                                "type": "INFO",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                        } else if (statusForCurrentFocusedFile != "LOGGER") {
                            consoleMessage = {
                                "type": "ERROR",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                        }
                        newConsole.println(consoleMessage);
                    }
                }

                // check whether switch to new console set to false
                if (_.has(opts, 'switchToNewConsole')) {
                    if (_.isBoolean(_.get(opts, 'switchToNewConsole')) && _.get(opts, 'switchToNewConsole')) {
                        this.setActiveConsole(newConsole);
                    }
                } else {
                    // activate by default
                    this.setActiveConsole(newConsole);
                }
                this.showActiveConsole(newConsole);
                this.showConsoleComponents();
                this.getConsoleActivateBtn().parent('li').addClass('active');
                return newConsole;
            }
        });

    return ConsoleList;
});
<commit_msg>Fixing resize issue on page load<commit_after>/**
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
define(['log', 'jquery', 'lodash', 'backbone', 'console'], function (log, $, _, Backbone, Console) {

    var ConsoleList = Backbone.View.extend(
        /** @lends ConsoleList.prototype */
        {
            initialize: function (options) {
                var errMsg;
                // check whether a custom Console type is set
                if (_.has(options, 'consoleModel')) {
                    this.ConsoleModel = _.get(options, 'consoleModel');
                    // check whether the custom type is of type Console
                    if (!this.ConsoleModel instanceof Console) {
                        errMsg = 'custom console model is not a sub type of Console: ' + Console;
                        log.error(errMsg);
                        throw errMsg;
                    }
                } else {
                    this.ConsoleModel = Console;
                }
                this._consoles = [];

                if (!_.has(options, 'container')) {
                    errMsg = 'unable to find configuration for container';
                    log.error(errMsg);
                    throw errMsg;
                }
                var container = $(_.get(options, 'container'));
                //container.on('click', '.closeConsole', _.bindKey(this, 'hide'));
                // check whether container element exists in dom
                if (!container.length > 0) {
                    errMsg = 'unable to find container for console list with selector: ' + _.get(options, 'container');
                    log.error(errMsg);
                    throw errMsg;
                }
                this._$parent_el = container;
                if (!_.has(options, 'consoles.container')) {
                    errMsg = 'unable to find configuration for container';
                    log.error(errMsg);
                    throw errMsg;
                }
                var consoleContainer = this._$parent_el.find(_.get(options, 'consoles.container'));
                // check whether container element exists in dom
                if (!consoleContainer.length > 0) {
                    errMsg = 'unable to find container for console list with selector: ' + _.get(options, 'consoles.container');
                    log.error(errMsg);
                    throw errMsg;
                }
                this._$console_container = consoleContainer;
                this.options = options;
            },

            render: function () {
                var consoleHeaderContainer = this._$parent_el.children(_.get(this.options, 'headers.container'));
                var consoleList = $('

');
                consoleHeaderContainer.append(consoleList);

                var consoleListClass = _.get(this.options, 'headers.cssClass.list');
                consoleList.addClass(consoleListClass);
                this._$consoleList = consoleList;
                this.el = consoleList.get();
            },

            hideConsoleComponents: function () {
                var consoleHeaderContainer = this._$parent_el
                var serviceWrapper =  $('#service-tabs-wrapper');
                consoleHeaderContainer.addClass('hide');
                serviceWrapper.css('height', '100%');
                if (serviceWrapper.is('.ui-resizable')){
                    serviceWrapper.resizable( "destroy" );
                }
            },

            showConsoleComponents: function () {
                var self = this;
                var consoleHeaderContainer = self._$parent_el;
                var serviceWrapper =  $('#service-tabs-wrapper');
                serviceWrapper.css('height', '65%');
                consoleHeaderContainer.removeClass('hide');
                serviceWrapper.resizable({
                    handleSelector: ".splitter-horizontal",
                    handles: "s",
                    resize: function( event, ui ) {
                    }
                });
                var activeTab = self.options.application.tabController.activeTab;
                if (activeTab.getTitle() != "welcome-page") {
                    activeTab.getSiddhiFileEditor().getSourceView().editorResize();
                }
            },

            showActiveDebugConsole: function () {

            },

            createHeaderForConsole: function (console) {
                var consoleHeader = $('

');
                this._$consoleList.append(consoleHeader);

                var consoleHeaderClass = _.get(this.options, 'headers.cssClass.item');
                consoleHeader.addClass(consoleHeaderClass);

                var consoleHeaderLink = $('');
                consoleHeader.append(consoleHeaderLink);
                consoleHeader.link = consoleHeaderLink;
                consoleHeader.attr('href', '#' + console.cid);
                consoleHeaderLink.text(console.getTitle());

                consoleHeader.setText = function (text) {
                    consoleHeaderLink.text(text);
                };

                var self = this;
                consoleHeaderLink.click(function (e) {
                    consoleHeaderLink.tab('show');
                    self.setActiveConsole(console);
                    e.preventDefault();
                    e.stopPropagation();
                });

//                var consoleCloseBtn = $('<button type="button" >×</button>');
//                consoleHeader.append(consoleCloseBtn);
//                consoleCloseBtn.addClass( _.get(this.options, 'consoles.console.cssClass.console_close_btn'));
//                consoleCloseBtn.click(function(e){
//                    self.removeConsole(console);
//                    e.preventDefault();
//                    e.stopPropagation();
//                });

                console.on('title-changed', function (title) {
                    consoleHeaderLink.text(title);
                });
                console.setHeader(consoleHeader);
            },

            getConsoleContainer: function () {
                return this._$console_container;
            },
            /**
             * add a console to the console list.
             *
             * @param {Console} console an object of console
             * @fires ConsoleList#console-added
             */
            addConsole: function (console) {
                console.setParent(this);
                this.createHeaderForConsole(console);
                this._consoles.push(console);
                this.showConsoleComponents();
                /**
                 * console added event.
                 * @event ConsoleList#console-added
                 * @type {Console}
                 */
                this.trigger("console-added", console);
            },
            /**
             * gets Console
             * @param {string} console id
             * @returns {*}
             */
            getConsole: function (consoleId) {
                return _.find(this._consoles, ['id', consoleId]);
            },
            /**
             * removes a console
             * @param {Console} console the console instance
             * @fires ConsoleList#console-removed
             */
            removeConsole: function (console) {
                if (!_.includes(this._consoles, console)) {
                    var errMsg = 'console : ' + console.id + 'is not part of this console list.';
                    log.error(errMsg);
                    throw errMsg;
                }
                var consoleIndex = _.findIndex(this._consoles, console);

                _.remove(this._consoles, console);
                console.getHeader().remove();
                console.remove();
                /**
                 * console removed event.
                 * @event ConsoleList#console-removed
                 * @type {Console}
                 */
                this.trigger("console-removed", console);

                //switch to console at last or next index
                //make sure there are remaining consoles
                if (this._consoles.length > 0 && !_.isEqual(consoleIndex, -1)) {
                    // if removing console is 0th tab, next console is also the 0th
                    var nextConsoleIndex = 0;
                    if (!_.isEqual(consoleIndex, 0)) {
                        nextConsoleIndex = consoleIndex - 1;
                    }
                    var nextConsole = this._consoles[nextConsoleIndex];
                    this.setActiveConsole(nextConsole);
                } else {
                    this.hideConsoleComponents();
                }
            },
            /**
             * set selected console
             * @param {Console} tab the console instance
             * @fires ConsoleList#active-console-changed
             */
            setActiveConsole: function (console) {

                //set the corresponding active console for Tab
                if (console._type == "CONSOLE") {
                    $(".consoleToolbar").removeClass("hidden");
                    this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";
                } else {
                    $(".consoleToolbar").addClass("hidden");
                    this.options.application.tabController.getActiveTab()._lastActiveConsole = "DEBUG";
                }

                if (!_.isEqual(this.activeConsole, console)) {
                    if (!_.includes(this._consoles, console)) {
                        var errMsg = 'console : ' + console.cid + 'is not part of this console list.';
                        log.error(errMsg);
                        throw errMsg;
                    }
                    var lastActiveConsole = this.activeConsole;
                    this.activeConsole = console;
                    var activeConsoleHeaderClass = _.get(this.options, 'headers.cssClass.active');

                    if (!_.isUndefined(lastActiveConsole)) {
                        lastActiveConsole.getHeader().removeClass(activeConsoleHeaderClass);
                        lastActiveConsole.setActive(false);
                    }
                    this.activeConsole.getHeader().addClass(activeConsoleHeaderClass);
                    this.activeConsole.setActive(true);
                    /**
                     * Active console changed event.
                     * @event ConsoleList#active-tab-changed
                     * @type {object}
                     * @property {Console} lastActiveConsole - last active console.
                     * @property {Console} newActiveConsole - new active console.
                     */
                    var evt = {lastActiveConsole: lastActiveConsole, newActiveConsole: console};
                    this.trigger("active-console-changed", evt);
                }
            },
            /**
             * active console
             * @returns {Console}
             */
            getActiveConsole: function () {
                return this.activeConsole;
            },
            getConsoleList: function () {
                return this._consoles;
            },
            getGlobalConsole: function () {
                return _.find(this._consoles, function (console) {
                    return console._type == "CONSOLE"
                });
            },
            showActiveConsole: function (activeConsole) {
                activeConsole.show(true);
                _.each(this._consoles, function (console) {
                    if (console._type != "CONSOLE" && console._uniqueId != activeConsole._uniqueId) {
                        console.hide();
                    }
                });
            },
            hideConsoles: function () {
                _.each(this._consoles, function (console) {
                    console.hide();
                });
            },
            enableConsoleByTitle: function (title,type) {
                var globalConsole;
                var exist = false;
                var self = this;
                var globalConsole = this._consoles[_.findIndex(this._consoles, function(o) { return o._type ==
                    'CONSOLE'; })]
                _.each(this._consoles, function (console) {
                    if(console._type == type){
                        if (console._appName == title) {
                            console.show(true);
                            self.setActiveConsole(console);
                            globalConsole._isActive = false;
                        } else{
                            console.hide();
                            if(console._isActive){
                                self.setActiveConsole(globalConsole);
                            }
                        }
                    }
                });
            },
            /**
             * Creates a new console.
             * @param opts
             *          switchToNewConsole: indicate whether to switch to new console of type after creation
             *          consoleOptions: constructor args for the console
             * @returns {Console} created console instance
             * @event ConsoleList#console-added
             * @fires ConsoleList#active-console-changed
             */
            newConsole: function (opts) {
                var consoleOptions = _.get(opts, 'consoleOptions') || {};
                _.set(consoleOptions, 'application', this.options.application);
                _.assign(consoleOptions, _.get(this.options, 'consoles.console'));
                _.set(consoleOptions, 'consoles_container', _.get(this.options, 'consoles.container'));
                _.set(consoleOptions, 'parent', this);
                var consoleType = _.get(consoleOptions, '_type');
                var uniqueTabId = _.get(consoleOptions, 'uniqueTabId');
                var message = _.get(consoleOptions, 'message');
                var newConsole = this.getConsoleForType(consoleType, uniqueTabId);
                var currentFocusedFile = _.get(opts, 'consoleOptions.currentFocusedFile');
                var statusForCurrentFocusedFile = _.get(opts, 'consoleOptions.statusForCurrentFocusedFile');

                if (newConsole == undefined) {
                    newConsole = new this.ConsoleModel(consoleOptions);
                    if (consoleType == "CONSOLE") {
                        _.set(newConsole, '_title', _.get(consoleOptions, 'title'));
                        this.addConsole(newConsole);
                        _.set(newConsole, '_runStatus', true);
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";

                        if (statusForCurrentFocusedFile == "SUCCESS") {
                            newConsole.showInitialStartingMessage(currentFocusedFile + ".siddhi " + message);
                        } else if(statusForCurrentFocusedFile != "LOGGER"){
                            var message = {
                                "type": "ERROR",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                            newConsole.println(message);
                        }
                    } else {
                        _.set(newConsole, '_debugStatus', true);
                        _.set(newConsole, '_title', _.get(consoleOptions, 'title') + " - " + _.get(consoleOptions, 'appName'));
                        this.addConsole(newConsole);
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "DEBUG";
                    }
                } else if (newConsole !== undefined) {
                    if (consoleType == "CONSOLE") {
                        this.options.application.tabController.getActiveTab()._lastActiveConsole = "CONSOLE";
                        var consoleMessage;
                        if (statusForCurrentFocusedFile == "SUCCESS") {
                            consoleMessage = {
                                "type": "INFO",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                        } else if (statusForCurrentFocusedFile != "LOGGER") {
                            consoleMessage = {
                                "type": "ERROR",
                                "message": "" + currentFocusedFile + ".siddhi - " + message + ""
                            };
                        }
                        newConsole.println(consoleMessage);
                    }
                }

                // check whether switch to new console set to false
                if (_.has(opts, 'switchToNewConsole')) {
                    if (_.isBoolean(_.get(opts, 'switchToNewConsole')) && _.get(opts, 'switchToNewConsole')) {
                        this.setActiveConsole(newConsole);
                    }
                } else {
                    // activate by default
                    this.setActiveConsole(newConsole);
                }
                this.showActiveConsole(newConsole);
                this.showConsoleComponents();
                this.getConsoleActivateBtn().parent('li').addClass('active');
                return newConsole;
            }
        });

    return ConsoleList;
});
<|endoftext|>