<commit_before>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 *        Jonatan Lundin (jonatan.lundin a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
    var wym = this;

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    jQuery(this._element).trigger('wymeditor:iframe_loaded');

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor click events
    jQuery(this._doc).bind("click", this.click);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", function () {
        // Fix scope
        wym.enableDesignMode.call(wym);
    });

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) {
      //do nothing
    }

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/em>/gi, "");
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
  return false;
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1 || ancestor.tagName.toLowerCase() == WYMeditor.OL || ancestor.tagName.toLowerCase() == WYMeditor.UL) {
              this._doc.execCommand(cmd,'',null);
            }
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    break;
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    return(true);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }

  return true;
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  if(evt.keyCode != 8 && evt.keyCode != 17 && evt.keyCode != 46 && evt.keyCode != 224 && !evt.metaKey && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

//click handler
WYMeditor.WymClassMozilla.prototype.click = function(evt) {

	var wym = WYMeditor.INSTANCES[this.title];
	var container = wym.selected();

	if(container && container.tagName.toLowerCase() == WYMeditor.TR) {
		jQuery(WYMeditor.TD, wym._doc.body).append('
');
	} else if (container && container.tagName.toLowerCase() == WYMeditor.BODY) {
		wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
	}
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this._doc.body.contentEditable != "true") {
      try {
        this._doc.body.contentEditable = "true";
        this._doc.execCommand("styleWithCSS", '', false);
        this._doc.execCommand("enableObjectResizing", false, false);
        this._doc.execCommand("enableInlineTableEditing", false, false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
    attributes = this.validator.getValidTagAttributes(tag, attributes);

    // Handle Mozilla styled spans
    if (tag == 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';
        }
    }

    this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<commit_msg>Mozilla: prevent the up arrow from creating new Ps.<commit_after>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 *        Jonatan Lundin (jonatan.lundin a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
    var wym = this;

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    jQuery(this._element).trigger('wymeditor:iframe_loaded');

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor click events
    jQuery(this._doc).bind("click", this.click);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", function () {
        // Fix scope
        wym.enableDesignMode.call(wym);
    });

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) {
      //do nothing
    }

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/em>/gi, "");
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
  return false;
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1 || ancestor.tagName.toLowerCase() == WYMeditor.OL || ancestor.tagName.toLowerCase() == WYMeditor.UL) {
              this._doc.execCommand(cmd,'',null);
            }
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    break;
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    return(true);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }

  return true;
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  if(evt.keyCode != 8 && evt.keyCode != 17 && evt.keyCode != 46 && evt.keyCode != 224 && !evt.metaKey && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ) name = container.parentNode.tagName.toLowerCase();

    // prevent the up arrow on the first node from creating a new P
    if(evt.keyCode == 38 && name == WYMeditor.BODY ) { //UP arrow
      var $first_p = jQuery(wym._doc.body).find('p:first');
      if($first_p.length) {
        var sel = wym._iframe.contentWindow.getSelection();
        var p_range = wym._iframe.contentWindow.document.createRange();
        p_range.setStart($first_p[0], 0);
        p_range.setEnd($first_p[0], 0);
        sel.removeAllRanges();
        sel.addRange(p_range);
        return;
      }
    }

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

//click handler
WYMeditor.WymClassMozilla.prototype.click = function(evt) {

	var wym = WYMeditor.INSTANCES[this.title];
	var container = wym.selected();

	if(container && container.tagName.toLowerCase() == WYMeditor.TR) {
		jQuery(WYMeditor.TD, wym._doc.body).append('
');
	} else if (container && container.tagName.toLowerCase() == WYMeditor.BODY) {
		wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
	}
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this._doc.body.contentEditable != "true") {
      try {
        this._doc.body.contentEditable = "true";
        this._doc.execCommand("styleWithCSS", '', false);
        this._doc.execCommand("enableObjectResizing", false, false);
        this._doc.execCommand("enableInlineTableEditing", false, false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
    attributes = this.validator.getValidTagAttributes(tag, attributes);

    // Handle Mozilla styled spans
    if (tag == 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';
        }
    }

    this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<|endoftext|>


<commit_before>$(document).ready(function(){

                auto_complete()

            })

var auto_complete = function(){
                AutoComplete({
                    //_Render: function(response, ){
                    //    console.log(response)
                    //    response = JSON.parse(response)
                    //    this._Render(response.params)
                    //},
                    post: do_post,
                    select: do_select,
                    //_RenderResponseItems: do_renderresponse,
                    //_Select: do_select,
                    //autoFocus: true,

                    })
//upon select choose what to do with it.
                function do_select(input, item){
                    alert("do_select")

                    //console.log(input)
                    //console.log(item)
                    input.value = attr(item, "data-autocomplete-value", item.innerHTML);
                    console.log(input.value); // PO: antheridium jacket layer - is the element chosen in the input form
                    attr(input, {"data-autocomplete-old-value": input.value});
                    alert("you selected "+ input.value);
                }

                //connect the selection to a local mySQL database:
                //https://www.sitepoint.com/using-node-mysql-javascript-client/

                function do_post(result, response, custParams) {
                    console.log(result)
                    response = JSON.parse(response);
                    console.log("num_found " + response.response.numFound)
                    var properties = Object.getOwnPropertyNames(response);
                    //Try parse like JSON data

                    var empty,
                        length = response.length,
                        li = domCreate("li"),
                        ul = domCreate("ul"); // HTML id

                 // var ulhtml_id = '
';
                       //

                    /*    // create the HTML id for the ul

One

Two

Three

                       */

                    //Reverse result if limit parameter is custom
                    if (custParams.limit < 0) {
                        properties.reverse();
                    }

                    for (var item in response.response.docs) {

                        doc = response.response.docs[item]

                        try {
                            //
                            console.log(response.highlighting[doc.id])
                            console.log(doc)
                            var s
                            s = response.highlighting[doc.id].label
                            if (s == undefined) {
                                s = response.highlighting[doc.id].synonym
                            }
                            var desc
                            if (doc.ontology_prefix == undefined) {
                                desc = "Origin Unknown"
                            }
                            else {
                                desc = doc.ontology_prefix
                            }
                            li.innerHTML = '' + doc.ontology_prefix + ':' + doc.label + ' ' + '' + ' - ' + '' + doc.obo_id + '';

                            $(li).attr('data-id', doc.id)
                            var styles = {
                                margin : "2px",
                                marginTop: '4px',
                                fontSize: "large",

                            };
                            $(li).css(styles)
                            $(li).attr('data-term_accession', doc.iri)
                            $(li).attr('data-annotation_value', doc.label)
                            var s = doc.obo_id
                            s = s.split(':')[0]

                            $(li).attr('data-term_source', s)
                            //$(li).attr("data-autocomplete-value", response.highlighting[item].label_autosuggest[0].replace('', '').replace('', '') + ' - ' + item);

                            console.log($(li).data('label'))

                            ul.appendChild(li);
                            li = domCreate("li");
                        }
                        catch (err) {
                            console.log(err)
                            li = domCreate("li");
                        }
                    }
                    if (result.hasChildNodes()) {
                        result.childNodes[0].remove();
                    }

                    result.appendChild(ul);

                    $(document).keydown(function(e){ // 38-up, 40-down
    if (e.keyCode == 40) {
        console.log("length "+$('ul li').length)
        if(chosen === "") {
            chosen = 0;
        } else if((chosen+1) < $(result + 'ul li').length) {
            chosen++;
        }
        $('ul li').removeClass('selected');
        $('ul li:eq('+chosen+')').addClass('selected');
        var result = $('ul li:eq('+chosen+')').text();
        $('.autosuggest1').val(result);
        return false;
    }
    /**
    if (e.keyCode == 38) {
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            chosen--;
        }

        $('li').removeClass('selected');
        $('li:eq('+chosen+')').addClass('selected');
        var result = $('li:eq('+chosen+')').text();
        $('.autosuggest1').val(result);
        return false;
    }
     if (e.keyCode == "ENTER") {
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            do select
        }

    }**/
});

                    }

                function do_render(response){
                    response = JSON.parse(response);
                    Autocomplete._Render(response)

                }}<commit_msg>i think i created an html id for the ul still works<commit_after>$(document).ready(function(){

                auto_complete()

            })

var auto_complete = function(){
                AutoComplete({
                    //_Render: function(response, ){
                    //    console.log(response)
                    //    response = JSON.parse(response)
                    //    this._Render(response.params)
                    //},
                    post: do_post,
                    select: do_select,
                    //_RenderResponseItems: do_renderresponse,
                    //_Select: do_select,
                    //autoFocus: true,

                    })
//upon select choose what to do with it.
                function do_select(input, item){
                    alert("do_select")

                    //console.log(input)
                    //console.log(item)
                    input.value = attr(item, "data-autocomplete-value", item.innerHTML);
                    console.log(input.value); // PO: antheridium jacket layer - is the element chosen in the input form
                    attr(input, {"data-autocomplete-old-value": input.value});
                    alert("you selected "+ input.value);
                }

                //connect the selection to a local mySQL database:
                //https://www.sitepoint.com/using-node-mysql-javascript-client/

                function do_post(result, response, custParams) {
                    console.log(result)
                    response = JSON.parse(response);
                    console.log("num_found " + response.response.numFound)
                    var properties = Object.getOwnPropertyNames(response);
                    //Try parse like JSON data

                    var empty,
                        length = response.length,
                        li = domCreate("li"),
                        ul = domCreate("ul"); // HTML id

                    var ulhtml_id = '
';
                       //

                    /*    // create the HTML id for the ul

One

Two

Three

                       */

                    //Reverse result if limit parameter is custom
                    if (custParams.limit < 0) {
                        properties.reverse();
                    }

                    for (var item in response.response.docs) {

                        doc = response.response.docs[item]

                        try {
                            //
                            console.log(response.highlighting[doc.id])
                            console.log(doc)
                            var s
                            s = response.highlighting[doc.id].label
                            if (s == undefined) {
                                s = response.highlighting[doc.id].synonym
                            }
                            var desc
                            if (doc.ontology_prefix == undefined) {
                                desc = "Origin Unknown"
                            }
                            else {
                                desc = doc.ontology_prefix
                            }
                            li.innerHTML = '' + doc.ontology_prefix + ':' + doc.label + ' ' + '' + ' - ' + '' + doc.obo_id + '';

                            $(li).attr('data-id', doc.id)
                            var styles = {
                                margin : "2px",
                                marginTop: '4px',
                                fontSize: "large",

                            };
                            $(li).css(styles)
                            $(li).attr('data-term_accession', doc.iri)
                            $(li).attr('data-annotation_value', doc.label)
                            var s = doc.obo_id
                            s = s.split(':')[0]

                            $(li).attr('data-term_source', s)
                            //$(li).attr("data-autocomplete-value", response.highlighting[item].label_autosuggest[0].replace('', '').replace('', '') + ' - ' + item);

                            console.log($(li).data('label'))

                            ul.appendChild(li);
                            li = domCreate("li");
                        }
                        catch (err) {
                            console.log(err)
                            li = domCreate("li");
                        }
                    }
                    if (result.hasChildNodes()) {
                        result.childNodes[0].remove();
                    }

                    result.appendChild(ul);

                    $(document).keydown(function(e){ // 38-up, 40-down
    if (e.keyCode == 40) {
        console.log("length "+$('ulhtml_id li').length)
        if(chosen === "") {
            chosen = 0;
        } else if((chosen+1) < $(result + 'ulhtml_id li').length) {
            chosen++;
        }
        $('ulhtml_id li').removeClass('selected');
        $('ulhtml_id li:eq('+chosen+')').addClass('selected');
        var result = $('ulhtml_id li:eq('+chosen+')').text();
        $('.autosuggest1').val(result);
        return false;
    }
    /**
    if (e.keyCode == 38) {
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            chosen--;
        }

        $('li').removeClass('selected');
        $('li:eq('+chosen+')').addClass('selected');
        var result = $('li:eq('+chosen+')').text();
        $('.autosuggest1').val(result);
        return false;
    }
     if (e.keyCode == "ENTER") {
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            do select
        }

    }**/
});

                    }

                function do_render(response){
                    response = JSON.parse(response);
                    Autocomplete._Render(response)

                }}<|endoftext|>


<commit_before>var MutantMap = require('./map')
var MutantArray = require('./array')

module.exports = MutantMappedArray

function MutantMappedArray (defaultItems, lambda, opts) {
  opts = opts || {}

  var list = MutantArray(defaultItems, {
    comparer: opts.comparer,
    fixedIndexing: true
  })

  var obs = MutantMap(list, lambda, opts)
  obs.set = list.set

  obs.push = function (item) {
    list.push(item)
    return obs.get(obs.getLength() - 1)
  }

  obs.insert = function (item, at) {
    list.insert(item, at)
    return obs.get(at)
  }

  obs.remove = function (mappedItem) {
    var index = obs.indexOf(mappedItem)
    if (~index) {
      list.deleteAt(index)
      return true
    }
  }

  obs.move = function (mappedItem, targetIndex) {
    var currentIndex = obs.indexOf(mappedItem)
    if (~currentIndex) {
      var item = list.get(currentIndex)
      if (currentIndex < targetIndex) {
        list.insert(item, targetIndex + 1)
        list.deleteAt(currentIndex)
      } else {
        list.insert(item, targetIndex)
        list.deleteAt(currentIndex)
      }
    }
  }

  return obs
}
<commit_msg>mapped-array: fix move<commit_after>var MutantMap = require('./map')
var MutantArray = require('./array')

module.exports = MutantMappedArray

function MutantMappedArray (defaultItems, lambda, opts) {
  opts = opts || {}

  var list = MutantArray(defaultItems, {
    comparer: opts.comparer,
    fixedIndexing: true
  })

  var obs = MutantMap(list, lambda, opts)
  obs.set = list.set

  obs.push = function (item) {
    list.push(item)
    return obs.get(obs.getLength() - 1)
  }

  obs.insert = function (item, at) {
    list.insert(item, at)
    return obs.get(at)
  }

  obs.remove = function (mappedItem) {
    var index = obs.indexOf(mappedItem)
    if (~index) {
      list.deleteAt(index)
      return true
    }
  }

  obs.move = function (mappedItem, targetIndex) {
    var currentIndex = obs.indexOf(mappedItem)
    if (~currentIndex) {
      var item = list.get(currentIndex)
      if (currentIndex < targetIndex) {
        list.transaction(function () {
          list.insert(item, targetIndex + 1)
          list.deleteAt(currentIndex)
        })
      } else if (currentIndex > targetIndex) {
        list.transaction(function () {
          list.insert(item, targetIndex)
          list.deleteAt(currentIndex + 1)
        })
      }
    }
  }

  return obs
}
<|endoftext|>


<commit_before>var successGauge, failuresGauge, noopsGauge, skipsGauge, totalGauge;
var numNodes, numResources, resourceDupes, resourcesPerNode;

window.onload = function(){
  numNodes = new JustGage({
    id: "numNodes",
    value: 0,
    min: 0,
    max: 1000,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Nodes",
    label: "#"
  });
  numResources = new JustGage({
    id: "numResources",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Resources",
    label: "#/k"
  });
  resourceDupes = new JustGage({
    id: "resourceDupes",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#FF0000','#FFFF00','#00FF00'],
    title: "Duplicate Resources",
    label: "%"
  });
  resourcesPerNode = new JustGage({
    id: "resourcesPerNode",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Resources Per Node",
    label: "Avg"
  });
  successGauge = new JustGage({
    id: "successGauge",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#FF0000','#FFFF00','#00FF00'],
    title: "Succeeded",
    label: "%"
  });
  failuresGauge = new JustGage({
    id: "failuresGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "Failed",
    label: "%"
  });
  noopsGauge = new JustGage({
    id: "noopsGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "NoOps",
    label: "%"
  });
  skipsGauge = new JustGage({
    id: "skipsGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "Skipped",
    label: "%"
  });
/*  totalGauge = new JustGage({
    id: "totalGauge",
    value: 0,
    min: 0,
    max: 1000,
    title: "Total",
    label: "Hosts"
  });*/
  refreshGauges();
  setInterval(function() {
    refreshGauges();
  }, 60 * 2 * 1000);
};

var refreshGauges = function()
{
  $.getJSON('/api/v1/puppet/metrics/population', function (data) {
    console.log(data);
    $.each(data, function(key, val) {
      switch (key.toLowerCase()) {
        case 'numnodes':
          numNodes.refresh(Math.round(val));
          break;
        case 'numresources':
          numResources.refresh(Math.round(val/1000));
          break;
        case 'resourcedupes':
          resourceDupes.refresh(Math.round(val)*100);
          break;
        case 'resourcespernode':
          resourcesPerNode.refresh(Math.round(val));
          break;
      }
    });
  });
  $.getJSON('/api/v1/puppet/aggregate_event_counts/hours/24', function (data) {
    console.log(data);
    $.each(data, function(key, val) {
      switch (key.toLowerCase()) {
        case 'successes':
          successGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'failures':
          failuresGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'noops':
          noopsGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'skips':
          skipsGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'total':
          //totalGauge.refresh(Math.round(val));
          break;
      }
    });
  });
}<commit_msg>adjusted graphs<commit_after>var successGauge, failuresGauge, noopsGauge, skipsGauge, totalGauge;
var numNodes, numResources, resourceDupes, resourcesPerNode;

window.onload = function(){
  numNodes = new JustGage({
    id: "numNodes",
    value: 0,
    min: 0,
    max: 1000,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Nodes",
    label: "#"
  });
  numResources = new JustGage({
    id: "numResources",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Resources",
    label: "#/k"
  });
  resourceDupes = new JustGage({
    id: "resourceDupes",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#FF0000','#FFFF00','#00FF00'],
    title: "Duplicate Resources",
    label: "%"
  });
  resourcesPerNode = new JustGage({
    id: "resourcesPerNode",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#00FF00','#00FF00','#00FF00'],
    title: "Resources Per Node",
    label: "Avg"
  });
  successGauge = new JustGage({
    id: "successGauge",
    value: 0,
    min: 0,
    max: 100,
    levelColors: ['#FF0000','#FFFF00','#00FF00'],
    title: "Succeeded",
    label: "%"
  });
  failuresGauge = new JustGage({
    id: "failuresGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "Failed",
    label: "%"
  });
  noopsGauge = new JustGage({
    id: "noopsGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "NoOps",
    label: "%"
  });
  skipsGauge = new JustGage({
    id: "skipsGauge",
    value: 0,
    min: 0,
    max: 100,
    title: "Skipped",
    label: "%"
  });
/*  totalGauge = new JustGage({
    id: "totalGauge",
    value: 0,
    min: 0,
    max: 1000,
    title: "Total",
    label: "Hosts"
  });*/
  refreshGauges();
  setInterval(function() {
    refreshGauges();
  }, 60 * 2 * 1000);
};

var refreshGauges = function()
{
  $.getJSON('/api/v1/puppet/metrics/population', function (data) {
    console.log(data);
    $.each(data, function(key, val) {
      switch (key.toLowerCase()) {
        case 'numnodes':
          numNodes.refresh(Math.round(val));
          break;
        case 'numresources':
          numResources.refresh(Math.round(val/1000));
          break;
        case 'resourcedupes':
          resourceDupes.refresh(Math.round(val*100));
          break;
        case 'resourcespernode':
          resourcesPerNode.refresh(Math.round(val));
          break;
      }
    });
  });
  $.getJSON('/api/v1/puppet/aggregate_event_counts/hours/24', function (data) {
    console.log(data);
    $.each(data, function(key, val) {
      switch (key.toLowerCase()) {
        case 'successes':
          successGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'failures':
          failuresGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'noops':
          noopsGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'skips':
          skipsGauge.refresh(Math.round((val/data.total)*100));
          break;
        case 'total':
          //totalGauge.refresh(Math.round(val));
          break;
      }
    });
  });
}<|endoftext|>


<commit_before>$(document).ready(function(){

// Initialize content
initContent();
function initContent(){
    $('html, body').css('cursor','none');
    $("#messages li:odd").addClass("dim");
    setTimeout(rotateTabs, 12500);
};

// Evaluate Messages //
var messageTimer;
var timer;
var c = 0;
paginateMessages();

function fadeMessage(){
    $('#messages li').each(function(){
        //document.getElementById("mainview_footer").getBoundingClientRect().top;
        var mvbody = document.getElementById("mainview_body").getBoundingClientRect();
        var mvhead = document.getElementById("mainview_header").getBoundingClientRect();
        var mvbody_height = mvbody.bottom - mvbody.top;
        var mvhead_height = mvhead.bottom - mvhead.top;

        var element = $(this).position().top + $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
        //var footer = $("#mainview_body").height() + $("#mainview_header").height();
        var footer = mvbody_height + mvhead_height;

        console.log(element + " > " + footer);
        if (Math.floor(element > footer)){
            $(this).fadeTo(0,0);
        } else {
            $(this).fadeTo(500,1);
        }
    });
};

function paginateMessages(){
    fadeMessage();

    clearTimeout(timer);

    var listAmount = $('#mainview_body ul li').size();
    var listHeight = Math.ceil($('#mainview_body ul').height());
    var itemHeight = $('#mainview_body ul li:nth-child(1)').height();
    var height = itemHeight + 43;

    if(c == 0){
        timer = setTimeout(paginateMessages, 10000);
    }else if(c <= listAmount){
        $('#mainview_body ul').animate({
            marginTop: -height
          }, {
            duration: 1000,
            specialEasing: {
                marginTop: 'easeInOutBack'
            },
            complete: function() {
                clearTimeout(timer);
                $('#mainview_body ul li:nth-child(1)').clone().appendTo('#mainview_body ul');
                $('#mainview_body ul li:nth-child(1)').remove();
                $('#mainview_body ul').css('margin-top', 0);
                timer = setTimeout(paginateMessages, 10000);
                fadeMessage();
            }
         });
    }else if(c > listAmount){
        clearTimeout(timer);
        timer = setTimeout(paginateMessages, 10000);
        console.log('refreshed');
        c = 0;
    }
    c++;
}

function rotateTabs() {
    allTabs = $("[data-group|='sidebar_body_containers']");
    current = $("[data-group|='sidebar_body_containers'].bounceInLeft");
    if (allTabs.last()[0] == current[0]) {
        next = allTabs.first();
    } else {
        next = current.next();
    }
    $("[data-group|='sidebar_body_containers']").removeClass("bounceOutLeft bounceInLeft").addClass("animated bounceOutLeft");
    next.removeClass().addClass("animated bounceInLeft");
    setTimeout(rotateTabs, 12500);
}

/*
$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: 15000,
    //gap in pixels between the tickers
    gap: 200,
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});
*/

});
<commit_msg>remove unnecessary console.logging<commit_after>$(document).ready(function(){

// Initialize content
initContent();
function initContent(){
    $('html, body').css('cursor','none');
    $("#messages li:odd").addClass("dim");
    setTimeout(rotateTabs, 12500);
};

// Evaluate Messages //
var messageTimer;
var timer;
var c = 0;
paginateMessages();

function fadeMessage(){
    $('#messages li').each(function(){
        //document.getElementById("mainview_footer").getBoundingClientRect().top;
        var mvbody = document.getElementById("mainview_body").getBoundingClientRect();
        var mvhead = document.getElementById("mainview_header").getBoundingClientRect();
        var mvbody_height = mvbody.bottom - mvbody.top;
        var mvhead_height = mvhead.bottom - mvhead.top;

        var element = $(this).position().top + $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
        //var footer = $("#mainview_body").height() + $("#mainview_header").height();
        var footer = mvbody_height + mvhead_height;

        //console.log(element + " > " + footer);
        if (Math.floor(element > footer)){
            $(this).fadeTo(0,0);
        } else {
            $(this).fadeTo(500,1);
        }
    });
};

function paginateMessages(){
    fadeMessage();

    clearTimeout(timer);

    var listAmount = $('#mainview_body ul li').size();
    var listHeight = Math.ceil($('#mainview_body ul').height());
    var itemHeight = $('#mainview_body ul li:nth-child(1)').height();
    var height = itemHeight + 43;

    if(c == 0){
        timer = setTimeout(paginateMessages, 10000);
    }else if(c <= listAmount){
        $('#mainview_body ul').animate({
            marginTop: -height
          }, {
            duration: 1000,
            specialEasing: {
                marginTop: 'easeInOutBack'
            },
            complete: function() {
                clearTimeout(timer);
                $('#mainview_body ul li:nth-child(1)').clone().appendTo('#mainview_body ul');
                $('#mainview_body ul li:nth-child(1)').remove();
                $('#mainview_body ul').css('margin-top', 0);
                timer = setTimeout(paginateMessages, 10000);
                fadeMessage();
            }
         });
    }else if(c > listAmount){
        clearTimeout(timer);
        timer = setTimeout(paginateMessages, 10000);
        console.log('refreshed');
        c = 0;
    }
    c++;
}

function rotateTabs() {
    allTabs = $("[data-group|='sidebar_body_containers']");
    current = $("[data-group|='sidebar_body_containers'].bounceInLeft");
    if (allTabs.last()[0] == current[0]) {
        next = allTabs.first();
    } else {
        next = current.next();
    }
    $("[data-group|='sidebar_body_containers']").removeClass("bounceOutLeft bounceInLeft").addClass("animated bounceOutLeft");
    next.removeClass().addClass("animated bounceInLeft");
    setTimeout(rotateTabs, 12500);
}

/*
$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: 15000,
    //gap in pixels between the tickers
    gap: 200,
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});
*/

});
<|endoftext|>


<commit_before>
window.app = angular.module('config', [], function ($interpolateProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');
});

app.controller('Config', ['$scope', '$element', function ($scope, $element, $attributes) {
  // this is the parent controller.
  $scope.message = null;
  $scope.repo = JSON.parse($element.attr('data-repo-config') || '{}');
  $scope.panelData = JSON.parse($element.attr('data-panel-data') || '{}');
  $scope.gravatar = function (email) {
    if (!email) return '';
    var hash = md5(email.toLowerCase());
    return 'https://secure.gravatar.com/avatar/' + hash + '?d=identicon';
  }
  $scope.error = function (text) {
    $scope.message = {
      text: text,
      type: 'error',
      showing: true
    };
  };
  $scope.info = function (text) {
    $scope.message = {
      text: text,
      type: 'info',
      showing: true
    };
  };
  var waitTime = null;
  $scope.success = function (text, sticky) {
    if (waitTime) {
      clearTimeout(waitTime);
      waitTime = null;
    }
    if (clearTime) {
      clearTimeout(clearTime);
      clearTime = null;
    }
    $scope.message = {
      text: 'Done. ' + text,
      type: 'success',
      showing: true
    };
    if (!sticky) {
      waitTime = setTimeout(function () {
        $scope.clearMessage();
        $scope.$digest();
      }, 5000);
    }
  };
  var clearTime = null;
  $scope.clearMessage = function () {
    if (clearTime) {
      clearTimeout(clearTime);
    }
    $scope.message.showing = false;
    clearTime = setTimeout(function () {
      clearTime = null;
      $scope.message = null;
      $scope.$digest();
    }, 1000);
  };
}]);

<commit_msg>isolating scope<commit_after>
;(function () {

  window.app = angular.module('config', [], function ($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  });

  function post(url, data, done) {
    $.ajax({
      url: url,
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function (data, ts, xhr) {
        done(null);
      },
      error: function (xhr, ts, e) {
        if (xhr && xhr.responseText) {
          var data = $.parseJSON(xhr.responseText);
          e = data.errors[0];
        }
        done(e);
      }
    });
  }

  app.controller('Config', ['$scope', '$element', function ($scope, $element, $attributes) {
    // this is the parent controller.
    $scope.message = null;
    $scope.repo = JSON.parse($element.attr('data-repo-config') || '{}');
    $scope.panelData = JSON.parse($element.attr('data-panel-data') || '{}');
    $scope.gravatar = function (email) {
      if (!email) return '';
      var hash = md5(email.toLowerCase());
      return 'https://secure.gravatar.com/avatar/' + hash + '?d=identicon';
    }
    $scope.error = function (text) {
      $scope.message = {
        text: text,
        type: 'error',
        showing: true
      };
    };
    $scope.info = function (text) {
      $scope.message = {
        text: text,
        type: 'info',
        showing: true
      };
    };
    var waitTime = null;
    $scope.success = function (text, sticky) {
      if (waitTime) {
        clearTimeout(waitTime);
        waitTime = null;
      }
      if (clearTime) {
        clearTimeout(clearTime);
        clearTime = null;
      }
      $scope.message = {
        text: 'Done. ' + text,
        type: 'success',
        showing: true
      };
      if (!sticky) {
        waitTime = setTimeout(function () {
          $scope.clearMessage();
          $scope.$digest();
        }, 5000);
      }
    };
    var clearTime = null;
    $scope.clearMessage = function () {
      if (clearTime) {
        clearTimeout(clearTime);
      }
      $scope.message.showing = false;
      clearTime = setTimeout(function () {
        clearTime = null;
        $scope.message = null;
        $scope.$digest();
      }, 1000);
    };

    $scope.post = post;
  }]);

})();
<|endoftext|>


<commit_before>// AJAX CALLS:
// create splash and prepend to the front of the list. (PortfolioJS, SimplyScroll jquery plugin or MouseWheel Plugin)
// inserts comment to bottom of comments and removes comment box on submission of comment form
// set timeout function to refresh the feed of splashes

// MODALS
// http://i-like-robots.github.io/jQuery-Modal/
// http://leanmodal.finelysliced.com.au/#

// SLIDEDOWN MENU FOR COMMENTS
// slideDown when user wants to create a comment
// http://www.alessioatzeni.com/blog/signin-dropdown-box-like-twitter-with-jquery/
// http://alexsblog.org/2014/08/21/custom-html-dropdown-with-jquery/

var controller = (function(){

  function createSplash(){
    $('#create_splash').on('click', function(evt){
      evt.preventDefault();
      var data = $('#create_splash').serialize();
      $.ajax({
        url: '/splash',
        type: 'POST',
        data: data
      }).done(function(data){
        console.log(data);
        view.addNewSplash(data);
      });
    });
  }

  function createComment(){
    $('#create_comment').on('submit', function(evt){
    evt.preventDefault();
      $.ajax({
        url: '/splashes/:id/comment',
        type: 'POST',
        data: data
      }).done(function(data){
        view.addNewComment(data);
      });
    });
  }

  (function poll() {
      setTimeout(function () {
          $.ajax({
              type: 'POST',
              dataType: 'json',
              url: '',                          //add a URL
              success: function (data) {
                  MyNamespace.myFunction(data); //DO ANY PROCESS HERE
              },
              complete: poll
          });
      }, 30000);                                //this is 30 seconds
  })();

  return{
    createSplash: createSplash,
    createComment: createComment,
    poll: poll
  };
})();
<commit_msg>update controller AJAX calls<commit_after>// AJAX CALLS:
// create splash and prepend to the front of the list. (PortfolioJS, SimplyScroll jquery plugin or MouseWheel Plugin)
// inserts comment to bottom of comments and removes comment box on submission of comment form
// set timeout function to refresh the feed of splashes

// SLIDEDOWN MENU FOR COMMENTS
// slideDown when user wants to create a comment
// http://www.alessioatzeni.com/blog/signin-dropdown-box-like-twitter-with-jquery/
// http://alexsblog.org/2014/08/21/custom-html-dropdown-with-jquery/

var controller = (function(){

  function createSplash(){
    $('#create_splash').on('click', function(evt){
      evt.preventDefault();
      var data = $('#create_splash').serialize();
      $.ajax({
        url: '/splash',
        type: 'POST',
        data: data,
        success: function(returned_splash) {
          view.addNewSplash(data);
        }
      });
    });
  };

  function createComment(){
    $('#create_comment').on('submit', function(evt){
    evt.preventDefault();
    var data = $('#create_comment').serialize();
      $.ajax({
        url: '/splashes/:id/comment',
        type: 'POST',
        data: data,
        success: function(returned_comment) {
          view.addNewComment(data);
        }
      });
    });
  };

  (function poll() {
      setTimeout(function () {
          $.ajax({
              type: 'GET',
              dataType: 'json',
              url: '/splashes',
              success: function(data) {
                  MyNamespace.myFunction(data); //DO ANY PROCESS HERE
              },
              complete: poll
          });
      }, 5000);                                //this is 5 seconds
  })();

  return{
    createSplash: createSplash,
    createComment: createComment,
    poll: poll
  };
})();
<|endoftext|>


<commit_before>(function(){

  "use strict";

  angular
    .module('galleryApp')
      .controller('crudCtrl', ['$scope', 'RestService', function ($scope, RestService) {

      $scope.tagline = 'This is crud controler !';

      var RestServ = new RestService();

      RestServ.getAllData().then(function(data){
        $scope.listImg = data.data;
      }).catch(function(err) {
        errorHandler(err);
      });

      function errorHandler(err){

        console.error(
          'name : ', err.name, '\n',
          'message : ', err.message,
          'message : ', err.stack
        );

      }
    }]);

})();<commit_msg>fixed code styles error<commit_after>(function(){

  "use strict";

  angular
    .module('galleryApp')
      .controller('crudCtrl', ['$scope', 'RestService', function ($scope, RestService) {

      $scope.tagline = 'This is crud controler !';

      var RestServ = new RestService();

      RestServ.getAllData().then(function(data){
        $scope.listImg = data.data;
      }).catch(function(err) {
        errorHandler(err);
      });

      function errorHandler(err){

        console.error(
          'name : ', err.name, '\n',
          'message : ', err.message, '\n',
          'message : ', err.stack
        );

      }
    }]);

})();<|endoftext|>


<commit_before>angular.module('cmsController', [])

    .controller('dashboardCtl', ['$scope', '$http', 'topology', '$interval', function ($scope, $http, topology, $interval) {

        $scope.title = "CMS Cloud Dashboard Console";
        $scope.formData = {
            server: "16.165.219.18:9091",
            view: "HPE SH DataCenter",
            container: "Container_RunningSoftware",
            interval: 2,
            lenLineChart: 100,
            pageSize: 5,
            animation: "easeOutBounce",
            ciType: 'event',
            random: 'true'
        };

        $scope.statistics;
        $scope.time;
        $scope.currentPage = 0;
        $scope.raw;
        $scope.cis = [];
        $scope.chartAnimation = chartAnimation;

        // get UCMDB TQL data
        $scope.getREST = function () {
            $scope.getContainer();
            $scope.getTopology();
        };

        $scope.getContainer = function () {
            topology.getContainer($scope.formData).success(function (data) {

                var RSNumber = {};

                data.cis.map(function (obj) {
                    if (obj.type in RSNumber)
                        RSNumber[obj.type]++;
                    else
                        RSNumber[obj.type] = 1;
                });

                $scope.updateDoughnutChart($scope.doughnut, RSNumber);

            });
        };

        $scope.getTopology = function () {
            topology.get($scope.formData).success(function (data) {
                var d = new Date();
                $scope.time = d.toLocaleString();

                if (data.cis instanceof Array) {

                    $scope.raw = data.cis; // save raw data

                    var ciNumber = {};
                    var ISNumber = {};
                    data.cis.map(function (obj) {

                        // count all CI type
                        if (obj.type in ciNumber)
                            ciNumber[obj.type]++;
                        else
                            ciNumber[obj.type] = 1;

                        // create time
                        if ('create_time' in obj.properties) {
                            obj.properties['timestamp'] = Date.parse(obj.properties['create_time']);
                        }
                        ;

                        // count install software name
                        if (obj.type == 'installed_software') {
                            if (obj.properties['display_label'] in ISNumber)
                                ISNumber[obj.properties['display_label']]++;
                            else
                                ISNumber[obj.properties['display_label']] = 1;
                        }
                    });

                    $scope.updateLineChart($scope.lineChart, ciNumber);
                    $scope.updateBarChart($scope.barChart, ISNumber);

                    $scope.statistics = ciNumber;	// caculate statistics

                    $scope.queryCis($scope.formData.ciType); // query specified Cis by ciType

                }

            });
        };

        // build records
        $scope.queryCis = function (ciType) {

            $scope.formData.ciType = ciType;
            $scope.disp_ciType = ciType;

            // save web storage
            if (localStorage)
                localStorage.ciType = $scope.formData.ciType;

            $scope.cis = [];
            for (i in $scope.raw) {
                if ($scope.raw[i].type == ciType && $scope.raw[i].properties)
                    $scope.cis.push($scope.raw[i].properties);
            }
            ;

        };

        // capitalize each word, replace _ to " "
        $scope.t2t = function (type) {
            return type.replace(/_/g, " ").capitalize();
        };

        // form behavior ==========================================
        $scope.submit = function () {
            for (form in $scope.formData) {
                $scope.formData[form] = $scope["disp_" + form];

                // save web storage
                if (localStorage)
                    localStorage[form] = $scope.formData[form];
            }

            $scope.getREST();
            $scope.setInterval();
            $scope.initCharts();

        };

        $scope.reset = function () {

            for (form in $scope.formData) {
                // load web storage
                if (localStorage)
                    $scope.formData[form] = localStorage[form] ? localStorage[form] : $scope.formData[form];

                $scope["disp_" + form] = $scope.formData[form]
            }

        };

        $scope.setInterval = function () {
            $interval.cancel(interval);
            interval = $interval(function () {
                $scope.getTopology()
            }, $scope.formData.interval * 1000);
        };

        $scope.disp = function () {
            var display = false;
            for (form in $scope.formData) {
                display = display || ($scope.formData[form] != $scope["disp_" + form]);
            }
            return display;
        };

        // list order by and pagination =============================
        $scope.predicate = 'timestamp';
        $scope.reverse = true;
        $scope.order = function (predicate) {
            console.log("order: " + predicate);
            $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
            $scope.predicate = predicate;
        };

        $scope.jump = function (i) {
            var pos = i;
            $scope.currentPage = pos;
        };

        // chart ==================================================
        $scope.updateLineChart = function (chart, ciNumber) {
            while (chart.labels.length < $scope.formData.lenLineChart) {
                chart.labels.push("");
                chart.data[0].push(0);
            }
            if ($scope.statistics) {

                chart.labels.push("");
                // chart.series = ['Event'];
                if ($scope.formData.random == 'true')
                    chart.data[0].push(Math.round(Math.random() * 10));
                else
                    chart.data[0].push(ciNumber['event'] - $scope.statistics['event']);

                // keep length
                while (chart.labels.length > $scope.formData.lenLineChart) {
                    chart.labels.shift();
                    chart.data[0].shift();
                }

            }
        };

        $scope.updateBarChart = function (chart, ISNumber) {
            chart.data = [];
            chart.labels = [];

            for (is in ISNumber) {

                if (chart.series.indexOf(is) < 0) {
                    chart.data.push([ISNumber[is]]);
                    chart.series.push(is);
                } else {
                    if ($scope.formData.random == 'true')
                        chart.data[chart.series.indexOf(is)] = [ISNumber[is] + Math.round(Math.random() * 10)];
                    else
                        chart.data[chart.series.indexOf(is)] = [ISNumber[is]];
                }
            }
            for (s in chart.series) {
                if (!(chart.series[s] in ISNumber)) {
                    chart.series.splice(s, 1);
                    chart.data.splice(s, 1);
                }

            }
        };

        $scope.updateDoughnutChart = function (chart, RSNumber) {
            chart.data = [];
            chart.labels = [];
            for (rs in RSNumber) {
                if ($scope.formData.random == 'true')
                    chart.data.push(RSNumber[rs] + Math.round(Math.random() * 10));
                else
                    chart.data.push(RSNumber[rs]);
                chart.labels.push($scope.t2t(rs));
            }
        };

        $scope.initCharts = function () {
            $scope.chart_data = [];
            $scope.lineChart = {
                data: [$scope.chart_data],
                labels: [],
                series: ['Event'],
                options: chart_line
            };

            $scope.barChart = {
                data: [],
                labels: [],
                series: [],
                options: chart_bar
            };

            $scope.doughnut = {
                labels: [],
                data: [],
                options: chart_circle
            }

            // $scope.lineChart.options = Object.assign(chart_global, chart_line);
            if ($scope.formData.animation == "<None>")
                Chart.defaults.global.animation = false;
            else
                Chart.defaults.global.animation = true;

            Chart.defaults.global.animationEasing = $scope.formData.animation;

        };

        // initial ======================================================
        $scope.reset();	// inital run for set disp value
        $scope.initCharts();
        $scope.getREST(); // inital get, then interval
        var interval = $interval(function () {
            $scope.getREST()
        }, $scope.formData.interval * 1000);

    }]);
<commit_msg>fix a random defect, and animation logic<commit_after>angular.module('cmsController', [])

    .controller('dashboardCtl', ['$scope', '$http', 'topology', '$interval', function ($scope, $http, topology, $interval) {

        $scope.title = "CMS Cloud Dashboard Console";
        $scope.formData = {
            server: "16.165.219.18:9091",
            view: "HPE SH DataCenter",
            container: "Container_RunningSoftware",
            interval: 2,
            lenLineChart: 100,
            pageSize: 5,
            animation: "easeOutBounce",
            ciType: 'event',
            random: 'true'
        };

        $scope.statistics = {};
        $scope.time = "";
        $scope.currentPage = 0;
        $scope.raw = [];
        $scope.cis = [];
        $scope.chartAnimation = chartAnimation;

        // get UCMDB TQL data
        $scope.getREST = function () {
            $scope.getContainer();
            $scope.getTopology();
        };

        $scope.getContainer = function () {
            topology.getContainer($scope.formData).success(function (data) {

                var RSNumber = {};

                data.cis.map(function (obj) {
                    if (obj.type in RSNumber)
                        RSNumber[obj.type]++;
                    else
                        RSNumber[obj.type] = 1;
                });

                $scope.updateDoughnutChart($scope.doughnut, RSNumber);

            });
        };

        $scope.getTopology = function () {
            topology.get($scope.formData).success(function (data) {
                var d = new Date();
                $scope.time = d.toLocaleString();

                if (data.cis instanceof Array) {

                    $scope.raw = data.cis; // save raw data

                    var ciNumber = {};
                    var ISNumber = {};
                    data.cis.map(function (obj) {

                        // count all CI type
                        if (obj.type in ciNumber)
                            ciNumber[obj.type]++;
                        else
                            ciNumber[obj.type] = 1;

                        // create time
                        if ('create_time' in obj.properties) {
                            obj.properties['timestamp'] = Date.parse(obj.properties['create_time']);
                        }

                        // count install software name
                        if (obj.type == 'installed_software') {
                            if (obj.properties['display_label'] in ISNumber)
                                ISNumber[obj.properties['display_label']]++;
                            else
                                ISNumber[obj.properties['display_label']] = 1;
                        }
                    });

                    $scope.updateLineChart($scope.lineChart, ciNumber);
                    $scope.updateBarChart($scope.barChart, ISNumber);

                    $scope.statistics = ciNumber;	// caculate statistics

                    $scope.queryCis($scope.formData.ciType); // query specified Cis by ciType

                }

            });
        };

        // build records
        $scope.queryCis = function (ciType) {

            $scope.formData.ciType = ciType;
            $scope.disp_ciType = ciType;

            // save web storage
            if (localStorage)
                localStorage.ciType = $scope.formData.ciType;

            $scope.cis = [];
            for (i in $scope.raw) {
                if ($scope.raw[i].type == ciType && $scope.raw[i].properties)
                    $scope.cis.push($scope.raw[i].properties);
            }

        };

        // capitalize each word, replace _ to " "
        $scope.t2t = function (type) {
            return type.replace(/_/g, " ").capitalize();
        };

        // form behavior ==========================================
        $scope.submit = function () {
            for (form in $scope.formData) {
                $scope.formData[form] = $scope["disp_" + form];

                // save web storage
                if (localStorage)
                    localStorage[form] = $scope.formData[form];
            }

            $scope.getREST();
            $scope.setInterval();
            $scope.initCharts();

        };

        $scope.reset = function () {

            for (form in $scope.formData) {
                // load web storage
                if (localStorage)
                    $scope.formData[form] = localStorage[form] ? localStorage[form] : $scope.formData[form];

                $scope["disp_" + form] = $scope.formData[form]
            }

        };

        $scope.setInterval = function () {
            $interval.cancel(interval);
            interval = $interval(function () {
                $scope.REST();
            }, $scope.formData.interval * 1000);
        };

        $scope.disp = function () {
            var display = false;
            for (form in $scope.formData) {
                display = display || ($scope.formData[form] != $scope["disp_" + form]);
            }
            return display;
        };

        // list order by and pagination =============================
        $scope.predicate = 'timestamp';
        $scope.reverse = true;
        $scope.order = function (predicate) {
            console.log("order: " + predicate);
            $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
            $scope.predicate = predicate;
        };

        $scope.jump = function (i) {
            var pos = i;
            $scope.currentPage = pos;
        };

        // chart ==================================================
        $scope.updateLineChart = function (chart, ciNumber) {
            while (chart.labels.length < $scope.formData.lenLineChart) {
                chart.labels.push("");
                chart.data[0].push(0);
            }
            if ($scope.statistics) {

                chart.labels.push("");
                // chart.series = ['Event'];
                if ($scope.formData.random == 'true')
                    chart.data[0].push(Math.round(Math.random() * 10));
                else
                    chart.data[0].push(ciNumber['event'] - $scope.statistics['event']);

                // keep length
                while (chart.labels.length > $scope.formData.lenLineChart) {
                    chart.labels.shift();
                    chart.data[0].shift();
                }

            }
        };

        $scope.updateBarChart = function (chart, ISNumber) {
            chart.data = [];
            chart.labels = [];

            for (is in ISNumber) {

                if (chart.series.indexOf(is) < 0) {
                    chart.data.push([ISNumber[is]]);
                    chart.series.push(is);
                } else {
                    if ($scope.formData.random == 'true')
                        chart.data[chart.series.indexOf(is)] = [ISNumber[is] + Math.round(Math.random() * 10)];
                    else
                        chart.data[chart.series.indexOf(is)] = [ISNumber[is]];
                }
            }
            for (s in chart.series) {
                if (!(chart.series[s] in ISNumber)) {
                    chart.series.splice(s, 1);
                    chart.data.splice(s, 1);
                }

            }
        };

        $scope.updateDoughnutChart = function (chart, RSNumber) {
            chart.data = [];
            chart.labels = [];
            for (rs in RSNumber) {
                if ($scope.formData.random == 'true')
                    chart.data.push(RSNumber[rs] + Math.round(Math.random() * 10));
                else
                    chart.data.push(RSNumber[rs]);
                chart.labels.push($scope.t2t(rs));
            }
        };

        $scope.initCharts = function () {
            $scope.chart_data = [];
            $scope.lineChart = {
                data: [$scope.chart_data],
                labels: [],
                series: ['Event'],
                options: chart_line
            };

            $scope.barChart = {
                data: [],
                labels: [],
                series: [],
                options: chart_bar
            };

            $scope.doughnut = {
                labels: [],
                data: [],
                options: chart_circle
            };

            // $scope.lineChart.options = Object.assign(chart_global, chart_line);
            Chart.defaults.global.animation = !($scope.formData.animation == "<None>");
            Chart.defaults.global.animationEasing = $scope.formData.animation;

        };

        // initial ======================================================
        $scope.reset();	// inital run for set disp value
        $scope.initCharts();
        $scope.getREST(); // inital get, then interval
        var interval = $interval(function () {
            $scope.getREST()
        }, $scope.formData.interval * 1000);

    }]);
<|endoftext|>


<commit_before>(function () {
	'use strict';

	mare.routers.SuccessStory = Backbone.Router.extend({

		routes: {
			'.*' : 'loadSuccessStory'
		},

		loadSuccessStory: function loadSuccessStory() {
			// Load the view for the success story
			mare.views.successStory = mare.views.successStory || new mare.views.SuccessStory();
		}

	});

}());<commit_msg>#41 | update function names in Backbone success story router<commit_after>(function () {
	'use strict';

	mare.routers.SuccessStory = Backbone.Router.extend({

		routes: {
			'.*' : 'showDetails'
		},

		showDetails: function showDetails() {
			// Load the view for the success story
			mare.views.successStory = mare.views.successStory || new mare.views.SuccessStory();
		}

	});

}());<|endoftext|>


<commit_before>define(function(require, exports, module) {
	var MButton = require('MButton');
	var Modal = Backbone.View.extend({
		tagName: 'div',
		className: 'modal',
		template: '

',
		headerTemplate: '

',
		initialize: function(options) {
			var self = this;
			options = options || {};
			var defaults = {
				title: 'Dialog',
				message: '',
				buttons: [], //{label: '', cssClass: '', action: function}
				dismissible: true,
				opacity: .5,
				in_duration: 300,
				out_duration: 200,
				autodestroy: true,
				withHeader: true,
				withFixedFooter: true
				//onOpen: function() {},
				//onClosed: function() {}
			};
			var config = {
				dismissible: options.dismissible==undefined ? defaults.dismissible : options.dismissible,
				opacity: options.opacity || defaults.opacity,
				in_duration: options.in_duration || defaults.in_duration,
				out_duration: options.out_duration || defaults.out_duration,
				ready: _.isFunction(options.onOpen) ? options.onOpen : defaults.onOpen,
				complete: _.isFunction(options.onClosed) ? options.onClosed : defaults.onClosed
			}
			this.autodestroy = options.autodestroy==undefined ? defaults.autodestroy : options.autodestroy;
			var el = $(this.el);
			var isFixedFooter = typeof options.withFixedFooter==='undefined' ? defaults.withFixedFooter : options.withFixedFooter;
			if(isFixedFooter) el.addClass('modal-fixed-footer');
			el.html(this.template);
			var hasHeader = typeof options.withHeader==='undefined' ? defaults.withHeader : options.withHeader;
			if(hasHeader) {
				el.find('.modal-content').prepend(this.headerTemplate);
				el.find('.modal-header').html(options.title || defaults.title);
			}
			el.find('.modal-body').html(options.message || defaults.message);
			if(options.buttons && options.buttons.length > 0) {
				for(var i in options.buttons) {
					var btn = new MButton({
						modal: self,
						label: options.buttons[i].label,
						action: options.buttons[i].action,
						cssClass: options.buttons[i].cssClass
					});
					el.find('.modal-footer').append(btn.render().el);
				}
			}
			$('body').append(this.el);
			$(this.el).openModal(config);
		},
		close: function() {
			$(this.el).closeModal();
			if(this.autodestroy) this.remove();
		}
	});

	module.exports = {
		alert: function(message, title, label) {
			var modal = new Modal({
				title: title,
				message: message,
				dismissible: false,
				buttons: [{
					label: label,
					action: function(modal) {
						modal.close();
					}
				}]
			});
		},
		confirm: function(options) {
			options = options || {};
			var modal = new Modal({
				title: options.title || 'Confirm',
				message: options.message || '?',
				buttons: [{
					label: options.btnCancelLabel || 'Cancel',
					action: function(modal) {
						if(options.callback && _.isFunction(options.callback)) {
							options.callback(false);
						}
						modal.close();
					}
				}, {
					label: options.btnOKLabel || 'OK',
					cssClass: options.btnOKClass || 'teal lighten-2',
					action: function(modal) {
						if(options.callback && _.isFunction(options.callback)) {
							options.callback(true);
						}
						modal.close();
					}
				}]
			});
		},
		show: function(options) {
			return (new Modal(options));
		}
	};

});<commit_msg>添加modal大小参数<commit_after>define(function(require, exports, module) {
	var MButton = require('MButton');
	var Modal = Backbone.View.extend({
		tagName: 'div',
		className: 'modal',
		template: '

',
		headerTemplate: '

',
		initialize: function(options) {
			var self = this;
			options = options || {};
			var defaults = {
				title: 'Dialog',
				message: '',
				buttons: [], //{label: '', cssClass: '', action: function}
				dismissible: true,
				opacity: .5,
				in_duration: 300,
				out_duration: 200,
				autodestroy: true,
				withHeader: true,
				withFixedFooter: true
				//onOpen: function() {},
				//onClosed: function() {}
			};
			var config = {
				dismissible: options.dismissible==undefined ? defaults.dismissible : options.dismissible,
				opacity: options.opacity || defaults.opacity,
				in_duration: options.in_duration || defaults.in_duration,
				out_duration: options.out_duration || defaults.out_duration,
				ready: _.isFunction(options.onOpen) ? options.onOpen : defaults.onOpen,
				complete: _.isFunction(options.onClosed) ? options.onClosed : defaults.onClosed
			}
			this.autodestroy = options.autodestroy==undefined ? defaults.autodestroy : options.autodestroy;
			var el = $(this.el);
			var isFixedFooter = typeof options.withFixedFooter==='undefined' ? defaults.withFixedFooter : options.withFixedFooter;
			if(isFixedFooter) el.addClass('modal-fixed-footer');
			el.html(this.template);
			var hasHeader = typeof options.withHeader==='undefined' ? defaults.withHeader : options.withHeader;
			if(hasHeader) {
				el.find('.modal-content').prepend(this.headerTemplate);
				el.find('.modal-header').html(options.title || defaults.title);
			}
			el.find('.modal-body').html(options.message || defaults.message);
			if(options.buttons && options.buttons.length > 0) {
				for(var i in options.buttons) {
					var btn = new MButton({
						modal: self,
						label: options.buttons[i].label,
						action: options.buttons[i].action,
						cssClass: options.buttons[i].cssClass
					});
					el.find('.modal-footer').append(btn.render().el);
				}
			}
			if(options.height) $(this.el).css({'height': options.height});
			if(options.width) $(this.el).css({'width': options.width});
			$('body').append(this.el);
			$(this.el).openModal(config);
		},
		close: function() {
			$(this.el).closeModal();
			if(this.autodestroy) this.remove();
		}
	});

	module.exports = {
		alert: function(message, title, label, size) {
			size = size || {};
			var modal = new Modal({
				title: title,
				message: message,
				dismissible: false,
				height: size.height || '210px',
				width: size.width || '400px',
				buttons: [{
					label: label,
					action: function(modal) {
						modal.close();
					}
				}]
			});
		},
		confirm: function(options) {
			options = options || {};
			var modal = new Modal({
				title: options.title || 'Confirm',
				message: options.message || '?',
				height: options.height || '230px',
				width: options.width || '420px',
				buttons: [{
					label: options.btnCancelLabel || 'Cancel',
					cssClass: options.btnCancelClass || 'btn-flat',
					action: function(modal) {
						if(options.callback && _.isFunction(options.callback)) {
							options.callback(false);
						}
						modal.close();
					}
				}, {
					label: options.btnOKLabel || 'OK',
					cssClass: options.btnOKClass || 'teal lighten-2',
					action: function(modal) {
						if(options.callback && _.isFunction(options.callback)) {
							options.callback(true);
						}
						modal.close();
					}
				}]
			});
		},
		show: function(options) {
			return (new Modal(options));
		}
	};

});<|endoftext|>


<commit_before>// JavaScript Document
//==========================================
//         ZHAOSTEPHEN ANIMATIONS
//==========================================

// GLOBAL VARIABLES
var bHomeMenuVis = false,
	bHomeMenuCircleIsFadingIn = false,
	bHomeMenuCircleIsFadingOut = false,
	bMouseHoverMenuCircle = false,
	bClickedMenuCircle = false;

// Animation Options Def
var ANOPT_EASEOUT_800 = {duration: 800, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEOUT_1000 = {duration: 1000, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEOUT_1500 = {duration: 1500, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEIN_1500 = {duration: 1500, easing: 'easeInExpo', queue: false};

var ANOPT_DEF = ANOPT_EASEOUT_800;

//ANIMATION FUNCTIONS DEF
var homeTransitionPanelPeek = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	switch (direction) {
		case 'top':
			$('#bg-img').animate({'top': '10%'},ANOPT_DEF);
			$('#bg-img').animate({'height': '90%'},ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '10%'},ANOPT_DEF);
			break;

		case 'bottom':
			$('#bg-img').animate({'bottom': '10%'},ANOPT_DEF);
			$('#bg-img').animate({'height': '90%'},ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '10%'},ANOPT_DEF);
			break;

		case 'left':
			$('#bg-img').animate({'left': '20%'},ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '80%'},ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '20%'},ANOPT_EASEOUT_1000);
			break;

		case 'right':
			$('#bg-img').animate({'right': '20%'},ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '80%'},ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '20%'},ANOPT_EASEOUT_1000);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().fadeIn(300);
}

var homeTransitionPanelShow = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children('.transitionPanel-bg').stop().fadeIn(300);
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().animate({
		'color': '#1B1B1B',
		'font-size': '6.4rem'},100);
	$('#bg-img').animate(JSON.parse('{"'+direction+'" : "100%"}'),ANOPT_EASEOUT_1500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate({'height': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'height': '100%'}, ANOPT_EASEOUT_1500);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate({'width': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'width': '100%'}, ANOPT_EASEOUT_1500);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
}

var homeTransitionPanelCont = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children('.transitionPanel-bg').stop().fadeIn(300);
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().animate({
		'color': '#1B1B1B',
		'font-size': '6.4rem'},100);
	$('#bg-img').animate(JSON.parse('{"'+direction+'" : "100%"}'),ANOPT_EASEOUT_1500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate({'height': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'height': '100%'}, ANOPT_EASEOUT_1500);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate({'width': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'width': '100%'}, ANOPT_EASEOUT_1500);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
}

var homeTransitionPanelRevert = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children().stop().fadeOut(500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate(JSON.parse('{"'+direction+'" : "0"}'),ANOPT_DEF);
			$('#bg-img').animate({'height': '100%'}, ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '0'}, ANOPT_DEF);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate(JSON.parse('{"'+direction+'" : "0"}'),ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '100%'}, ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '0'}, ANOPT_EASEOUT_1000);
			break;

		default:
			console.error('Animation err: Unknown direction');
	}
}

var homeMenuPeek = function(){
	$('div.home-bannerNameContainer').animate({
		'height':'70rem',
		'width':'70rem',
		'background-color':'rgba(0,0,0,0.1)',
		'-webkit-border-radius':'35rem',
		'border-radius':'35rem'
		}, ANOPT_DEF);

	if($('.home-menucircle').is(':animated')) {
		$('.home-menucircle').animate({'opacity':'100%', 'display':''}, ANOPT_DEF);
    }
	else {
		$('.home-menucircle').fadeIn(ANOPT_DEF);
	}
}
var homeMenuRevert = function(){
	$('div.home-bannerNameContainer').animate({
		'height':'30rem',
		'width':'56rem',
		'background-color':'rgba(0,0,0,0)',
		'-webkit-border-radius':'0rem',
		'border-radius':'0rem'
		}, ANOPT_DEF);

	$('.home-menucircle').fadeOut(ANOPT_DEF);
}

// DOCUMENT READY FUNCTION
$(function() {
	// ON PAGE LOAD EVENTS
	$('.home-menucircle').hide();
	$('.transitionPanel').children().hide();

	// ON HOVER TRIGGERED EVENTS

	// home-bannerNameContainer mouseenter and mouseleave events
	$('div.home-bannerNameContainer').contents().add('div.home-bannerNameContainer').mouseenter(function() {
        homeMenuPeek();
	});
	$('div.home-bannerNameContainer').mouseleave(function() {
		homeMenuRevert();
    });

	// home-menucircle hover events
	$('#home-circle-1').hover(function() {
		homeTransitionPanelPeek('top');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('top');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-2').hover(function() {
		homeTransitionPanelPeek('left');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('left');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-3').hover(function() {
		homeTransitionPanelPeek('right');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('right');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-4').hover(function() {
		homeTransitionPanelPeek('bottom');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('bottom');
		}
		bMouseHoverMenuCircle = false;
	});

	//"transitionPanel" (mouseable regions) mouseenter events
//	$('#home-topMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('top');
//		});
//	$('#home-leftMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('left');
//		});
//	$('#home-rightMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('right');
//		});
//	$('#home-bottomMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('bottom');
//		});

	//transitionPanel mouseleave events
//	$('#transitionPanel-top').mouseleave(function(){homeTransitionPanelRevert('top');});
//	$('#transitionPanel-left').mouseleave(function(){homeTransitionPanelRevert('left');});
//	$('#transitionPanel-right').mouseleave(function(){homeTransitionPanelRevert('right');});
//	$('#transitionPanel-bottom').mouseleave(function(){homeTransitionPanelRevert('bottom');});

	//MOUSE POSITION TRIGGERED EVENTS
//	$(document).mousemove(function(e){
//		if ((e.pageY > ($(document).height())*0.05
//				|| e.pageY < 0)
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('top');
//		}
//		if ((e.pageX > ($(document).width())*0.05
//				|| e.pageX < 0)
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('left');
//		}
//		if ((e.pageX < ($(document).width())*0.95
//				|| e.pageX > ($(document).width()))
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('right');
//		}
//		if ((e.pageY < ($(document).height())*0.95
//				|| e.pageY > ($(document).height()))
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('bottom');
//		}
//	});

	// home-menucircle onclick event
	$('a.home-menucircle').on('click', function(e) {
		bClickedMenuCircle = true;
        var href = $(this).attr('href');
		e.preventDefault();

		switch ($(this).attr('id')) {
			case 'home-circle-1-a':
				homeTransitionPanelShow('top');
	//			$("#transitionPanel-top").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-2-a':
				homeTransitionPanelShow('left');
	//			$("#transitionPanel-left").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-3-a':
				homeTransitionPanelShow('right');
	//			$("#transitionPanel-right").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-4-a':
				homeTransitionPanelShow('bottom');
	//			$("#transitionPanel-bottom").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
				break;

			default:
				console.error('Animation error: Unknown element');
		}
		setTimeout(function() {window.open(href,"_self");},1500);
    });

});
<commit_msg>Try with alternate test<commit_after>// JavaScript Document
//==========================================
//         ZHAOSTEPHEN ANIMATIONS
//==========================================

// GLOBAL VARIABLES
var bHomeMenuVis = false,
	bHomeMenuCircleIsFadingIn = false,
	bHomeMenuCircleIsFadingOut = false,
	bMouseHoverMenuCircle = false,
	bClickedMenuCircle = false;

// Animation Options Def
var ANOPT_EASEOUT_800 = {duration: 800, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEOUT_1000 = {duration: 1000, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEOUT_1500 = {duration: 1500, easing: 'easeOutExpo', queue: false},
	ANOPT_EASEIN_1500 = {duration: 1500, easing: 'easeInExpo', queue: false};

var ANOPT_DEF = ANOPT_EASEOUT_800;

//ANIMATION FUNCTIONS DEF
var homeTransitionPanelPeek = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	switch (direction) {
		case 'top':
			$('#bg-img').animate({'top': '10%'},ANOPT_DEF);
			$('#bg-img').animate({'height': '90%'},ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '10%'},ANOPT_DEF);
			break;

		case 'bottom':
			$('#bg-img').animate({'bottom': '10%'},ANOPT_DEF);
			$('#bg-img').animate({'height': '90%'},ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '10%'},ANOPT_DEF);
			break;

		case 'left':
			$('#bg-img').animate({'left': '20%'},ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '80%'},ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '20%'},ANOPT_EASEOUT_1000);
			break;

		case 'right':
			$('#bg-img').animate({'right': '20%'},ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '80%'},ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '20%'},ANOPT_EASEOUT_1000);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().fadeIn(300);
}

var homeTransitionPanelShow = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children('.transitionPanel-bg').stop().fadeIn(300);
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().animate({
		'color': '#1B1B1B',
		'font-size': '6.4rem'},100);
	$('#bg-img').animate(JSON.parse('{"'+direction+'" : "100%"}'),ANOPT_EASEOUT_1500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate({'height': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'height': '100%'}, ANOPT_EASEOUT_1500);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate({'width': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'width': '100%'}, ANOPT_EASEOUT_1500);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
}

var homeTransitionPanelCont = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children('.transitionPanel-bg').stop().fadeIn(300);
	$('#transitionPanel-'+direction).children('.transitionPanel-heading').stop().animate({
		'color': '#1B1B1B',
		'font-size': '6.4rem'},100);
	$('#bg-img').animate(JSON.parse('{"'+direction+'" : "100%"}'),ANOPT_EASEOUT_1500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate({'height': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'height': '100%'}, ANOPT_EASEOUT_1500);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate({'width': '0'}, ANOPT_EASEOUT_1500);
			$('#transitionPanel-'+direction).animate({'width': '100%'}, ANOPT_EASEOUT_1500);
			break;

		default:
			console.error('Animation error: Unknown direction');
	}
}

var homeTransitionPanelRevert = function(direction){
	// stop
	$('#bg-img').stop();
	$('#transitionPanel-'+direction).stop();

	$('#transitionPanel-'+direction).children().stop().fadeOut(500);

	switch (direction) {
		case 'top':
		case 'bottom':
			$('#bg-img').animate(JSON.parse('{"'+direction+'" : "0"}'),ANOPT_DEF);
			$('#bg-img').animate({'height': '100%'}, ANOPT_DEF);
			$('#transitionPanel-'+direction).animate({'height': '0'}, ANOPT_DEF);
			break;

		case 'left':
		case 'right':
			$('#bg-img').animate(JSON.parse('{"'+direction+'" : "0"}'),ANOPT_EASEOUT_1000);
			$('#bg-img').animate({'width': '100%'}, ANOPT_EASEOUT_1000);
			$('#transitionPanel-'+direction).animate({'width': '0'}, ANOPT_EASEOUT_1000);
			break;

		default:
			console.error('Animation err: Unknown direction');
	}
}

var homeMenuPeek = function(){
	$('div.home-bannerNameContainer').animate({
		'height':'70rem',
		'width':'70rem',
		'background-color':'rgba(0,0,0,0.1)',
		'-webkit-border-radius':'35rem',
		'border-radius':'35rem'
		}, ANOPT_DEF);

	if(bHomeMenuCircleIsFadingOut) {
		$('.home-menucircle').stop().animate({'opacity':'100%'}, ANOPT_DEF);
    }
	else {
		$('.home-menucircle').fadeIn(ANOPT_DEF);
	}
}
var homeMenuRevert = function(){
	$('div.home-bannerNameContainer').animate({
		'height':'30rem',
		'width':'56rem',
		'background-color':'rgba(0,0,0,0)',
		'-webkit-border-radius':'0rem',
		'border-radius':'0rem'
		}, ANOPT_DEF);

	bHomeMenuCircleIsFadingOut = true;
	$('.home-menucircle').fadeOut(withAddedComplete(ANOPT_DEF, function(){
		bHomeMenuCircleIsFadingOut = false;
	}));
}

// DOCUMENT READY FUNCTION
$(function() {
	// ON PAGE LOAD EVENTS
	$('.home-menucircle').hide();
	$('.transitionPanel').children().hide();

	// ON HOVER TRIGGERED EVENTS

	// home-bannerNameContainer mouseenter and mouseleave events
	$('div.home-bannerNameContainer').contents().add('div.home-bannerNameContainer').mouseenter(function() {
        homeMenuPeek();
	});
	$('div.home-bannerNameContainer').mouseleave(function() {
		homeMenuRevert();
    });

	// home-menucircle hover events
	$('#home-circle-1').hover(function() {
		homeTransitionPanelPeek('top');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('top');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-2').hover(function() {
		homeTransitionPanelPeek('left');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('left');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-3').hover(function() {
		homeTransitionPanelPeek('right');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('right');
		}
		bMouseHoverMenuCircle = false;
	});
	$('#home-circle-4').hover(function() {
		homeTransitionPanelPeek('bottom');
		bMouseHoverMenuCircle = true;
	}, function() {
		if (!bClickedMenuCircle) {
			homeTransitionPanelRevert('bottom');
		}
		bMouseHoverMenuCircle = false;
	});

	//"transitionPanel" (mouseable regions) mouseenter events
//	$('#home-topMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('top');
//		});
//	$('#home-leftMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('left');
//		});
//	$('#home-rightMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('right');
//		});
//	$('#home-bottomMouseable').mouseenter(function(){
//		homeTransitionPanelPeek('bottom');
//		});

	//transitionPanel mouseleave events
//	$('#transitionPanel-top').mouseleave(function(){homeTransitionPanelRevert('top');});
//	$('#transitionPanel-left').mouseleave(function(){homeTransitionPanelRevert('left');});
//	$('#transitionPanel-right').mouseleave(function(){homeTransitionPanelRevert('right');});
//	$('#transitionPanel-bottom').mouseleave(function(){homeTransitionPanelRevert('bottom');});

	//MOUSE POSITION TRIGGERED EVENTS
//	$(document).mousemove(function(e){
//		if ((e.pageY > ($(document).height())*0.05
//				|| e.pageY < 0)
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('top');
//		}
//		if ((e.pageX > ($(document).width())*0.05
//				|| e.pageX < 0)
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('left');
//		}
//		if ((e.pageX < ($(document).width())*0.95
//				|| e.pageX > ($(document).width()))
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('right');
//		}
//		if ((e.pageY < ($(document).height())*0.95
//				|| e.pageY > ($(document).height()))
//				&& bMouseHoverMenuCircle == false) {
//			homeTransitionPanelRevert('bottom');
//		}
//	});

	// home-menucircle onclick event
	$('a.home-menucircle').on('click', function(e) {
		bClickedMenuCircle = true;
        var href = $(this).attr('href');
		e.preventDefault();

		switch ($(this).attr('id')) {
			case 'home-circle-1-a':
				homeTransitionPanelShow('top');
	//			$("#transitionPanel-top").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-2-a':
				homeTransitionPanelShow('left');
	//			$("#transitionPanel-left").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-3-a':
				homeTransitionPanelShow('right');
	//			$("#transitionPanel-right").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
	//				setTimeout(function() {window.open(href,"_self");},1000);
	//			});
				break;

			case 'home-circle-4-a':
				homeTransitionPanelShow('bottom');
	//			$("#transitionPanel-bottom").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
				break;

			default:
				console.error('Animation error: Unknown element');
		}
		setTimeout(function() {window.open(href,"_self");},1500);
    });

});
<|endoftext|>