<commit_before>// Generated by CoffeeScript 1.6.3
jQuery(function() {
  return $.each($("[data-time]"), function(index, ele) {
    return $(ele).html(prettyDate(new Date($(this).data("time"))));
  });
});

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.masthead').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
		/*adjustFlyBar();*/
    }
}, 250);
/*
function adjustFlyBar(){
	var flybarHeight = document.querySelector(".masthead").offsetHeight;
	var scrollOffSet = window.pageYOffset;
	document.querySelector(".masthead").style.marginTop = flybarHeight - scrollOffSet;
}*/

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('.masthead').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
		if(!document.querySelector('#sidebar-checkbox').checked){
			if(st + $(window).height() < $(document).height()) {
				$('.masthead').removeClass('nav-up').addClass('nav-down');
			}
		}
    }

    lastScrollTop = st;
}<commit_msg>9/2301/0_020906<commit_after>// Generated by CoffeeScript 1.6.3
jQuery(function() {
  return $.each($("[data-time]"), function(index, ele) {
    return $(ele).html(prettyDate(new Date($(this).data("time"))));
  });
});

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.masthead').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
		/*adjustFlyBar();*/
    }
}, 250);
/*
function adjustFlyBar(){
	var flybarHeight = document.querySelector(".masthead").offsetHeight;
	var scrollOffSet = window.pageYOffset;
	document.querySelector(".masthead").style.marginTop = flybarHeight - scrollOffSet;
}*/

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
		if(!document.querySelector('#sidebar-checkbox').checked){
			$('.masthead').removeClass('nav-down').addClass('nav-up');
		}
    } else {
        // Scroll Up
		if(st + $(window).height() < $(document).height()) {
			$('.masthead').removeClass('nav-up').addClass('nav-down');
		}
    }

    lastScrollTop = st;
}<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
  // Image Upload Option
  jQuery('.struts-image-upload').click(function() {
    formfield = jQuery(this).attr('data-field-id');
    tb_show('', 'media-upload.php?type=image&TB_iframe=true');
    return false;
  });

  window.original_send_to_editor = window.send_to_editor;
  window.send_to_editor = function(html) {
    if(formfield) {
      source = jQuery(html).find('img').attr('src');
      jQuery('#'+formfield).val(source);
      tb_remove();
    }else{
      window.original_send_to_editor(html);
    }
  }

  // Color Chooser Option
  jQuery('.struts-color-chooser').each(function() {
    jQuery(this).farbtastic('#' + jQuery(this).attr('data-field-id'));
  });

  // hides as soon as the DOM is ready
  jQuery( 'div.struts-section-body' ).hide();
  // shows on clicking the noted link
  jQuery( 'div.struts-section h3' ).click(function() {
    jQuery(this).toggleClass("open");
    jQuery(this).next("div").toggle();
    return false;
  });

  jQuery('.struts-color-chooser').hide();
  jQuery( '.struts-color-chooser-toggle' ).click(function() {
    var colorchooser = jQuery(this).parent().next();

    colorchooser.toggle();

    if (colorchooser.is(':visible')) {
      jQuery(this).text('hide color picker');
    } else {
      jQuery(this).text('show color picker');
    }
    return false;
  });

  /**
   * Option Section Display
   *
   * Display an options section if the section param
   * is passed via a query string in the url.
   *
   * Example: <php get_admin_url() . 'themes.php?page=yourtheme_options&section=logo_section'
   */
	var section_id = getParameterByName('section');

	if( section_id ) {
		var section_id = '#' + section_id;
		jQuery('h3', section_id).addClass('open');
		jQuery('.struts-section-body', section_id).css('display','block');
	}

	function getParameterByName(name) {
	  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	  var regexS = "[\\?&]" + name + "=([^&#]*)";
	  var regex = new RegExp(regexS);
	  var results = regex.exec(window.location.search);
	  if(results == null)
	    return "";
	  else
	    return decodeURIComponent(results[1].replace(/\+/g, " "));
	}

});<commit_msg>Adding comment for confusing bit of JS.<commit_after>jQuery(document).ready(function($) {
  // Image Upload Option
  jQuery('.struts-image-upload').click(function() {
    formfield = jQuery(this).attr('data-field-id');
    tb_show('', 'media-upload.php?type=image&TB_iframe=true');
    return false;
  });

  // Handles sending the image from the media uploader screen to the input field (for images)
  window.original_send_to_editor = window.send_to_editor;
  window.send_to_editor = function(html) {
    if(formfield) {
      source = jQuery(html).find('img').attr('src');
      jQuery('#'+formfield).val(source);
      tb_remove();
    }else{
      window.original_send_to_editor(html);
    }
  }

  // Color Chooser Option
  jQuery('.struts-color-chooser').each(function() {
    jQuery(this).farbtastic('#' + jQuery(this).attr('data-field-id'));
  });

  // hides as soon as the DOM is ready
  jQuery( 'div.struts-section-body' ).hide();
  // shows on clicking the noted link
  jQuery( 'div.struts-section h3' ).click(function() {
    jQuery(this).toggleClass("open");
    jQuery(this).next("div").toggle();
    return false;
  });

  jQuery('.struts-color-chooser').hide();
  jQuery( '.struts-color-chooser-toggle' ).click(function() {
    var colorchooser = jQuery(this).parent().next();

    colorchooser.toggle();

    if (colorchooser.is(':visible')) {
      jQuery(this).text('hide color picker');
    } else {
      jQuery(this).text('show color picker');
    }
    return false;
  });

  /**
   * Option Section Display
   *
   * Display an options section if the section param
   * is passed via a query string in the url.
   *
   * Example: <php get_admin_url() . 'themes.php?page=yourtheme_options&section=logo_section'
   */
	var section_id = getParameterByName('section');

	if( section_id ) {
		var section_id = '#' + section_id;
		jQuery('h3', section_id).addClass('open');
		jQuery('.struts-section-body', section_id).css('display','block');
	}

	function getParameterByName(name) {
	  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	  var regexS = "[\\?&]" + name + "=([^&#]*)";
	  var regex = new RegExp(regexS);
	  var results = regex.exec(window.location.search);
	  if(results == null)
	    return "";
	  else
	    return decodeURIComponent(results[1].replace(/\+/g, " "));
	}

});<|endoftext|>


<commit_before>// jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

//Spinneri plugin jQueryyn
$.fn.spin = function(opts) {
    this.each(function() {
        var $this = $(this),
        data = $this.data();

        if (data.spinner) {
            data.spinner.stop();
            delete data.spinner;
            return; //Muokattu funktiota jotta spinnerin saa pois päältä
        }
        if (opts !== false) {
            data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
        }
    });
    return this;
};

//Spinner options
var opts = {
    lines: 12, // The number of lines to draw
    length: 7, // The length of each line
    width: 4, // The line thickness
    radius: 10, // The radius of the inner circle
    color: '#000', // #rgb or #rrggbb
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false // Whether to render a shadow
};

// rakentaa linkin josta lukkari löytyy
function haeJakso(x){
    alkupvm = jaksot[x][0].replace(/\./gi, "");
    loppupvm = jaksot[x][1].replace(/\./gi, "");
    var linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
    //var linkki = "jakso2.html";
    //yritä ladata lukkari sivulle
    try {
        $("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
            korvaa();
        });
        $("#lukkarikoodit").load(linkki + " .lukkari_table2");
    }
    catch(err){
        alert ("Lukkarin latauksessa tapahtui virhe " + err);
    }
}

// korvaa talukosta koodit nimillä
function korvaa() {
    $("#lukkarinimet td").each(function(){
        var text = $(this).html();
        for(i in koodit){
            text = text.replace(i, koodit[i]);
        }
        $(this).html(text);
    });
}

//muuta ruokalistan asemointia jos ikkuna liian pieni
function ikkunankoko(){
    if($(window).width() < 1260)
        {
            $("#ruokalista").css("position", "relative");
            $("#ruokalista").css("right", "auto");
            $("#ruokalista").css("left", "1.5%");
            $("#sivu").css("min-height", "1900px");
            $("#ruokalista").remove().insertBefore($("#napit"));
        }
        else
            {
                $("#ruokalista").css("position", "absolute");
                $("#ruokalista").css("right", "12%");
                $("#ruokalista").css("left", "auto");
                $("#sivu").css("min-height", "1310px");
                $("#ruokalista").remove().insertAfter($("#napit"));
            }
}

//Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso()
{
    var nyt = Date.today();
    //var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

    for (var i = 1; i <= 6; i++) {
        loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
        alkupvm = Date.parse(jaksot[i][0]);
        loppupvm = Date.parse(jaksot[i][1]);

        //tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
        if(nyt >= alkupvm && nyt <= loppupvm)
            return i;
        //tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
        //ja palautaa uuden jakson
        else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
            return i+1;

    }
    //palauttaa viimeisen jakson jos koulu loppunut
    if(nyt > jaksot[6][1])
        return 6;
}

$(window).resize(function(){
    ikkunankoko();
});

$(document).ready(function(){

    $("#loading").ajaxStart(function(){
        $(this).spin(opts);
    });
    $("#loading").ajaxStop(function(){
        $(this).spin();
    });

    ikkunankoko();

    //hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
    haeJakso(nykyinenJakso());
    $("#jakso").val(nykyinenJakso());

    $("#ruokalista").load("ruokalistaa.php");

    //hakee valitun jakson nappia painettaessa
    $("#ok").click(function(){
        var jakso = $("#jakso").val();
        haeJakso(jakso);
    });

    //vaihtaa nimet koodeiksi ja toisinpäin
    $("#toggle").click(function(){
        $(".lukkari").toggle();
    });
});
<commit_msg>Fixed moving of the menu when resizing the window and also made code formatting more consistent<commit_after>// jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

//Spinneri plugin jQueryyn
$.fn.spin = function(opts){
    this.each(function() {
        var $this = $(this),
        data = $this.data();

        if (data.spinner){
            data.spinner.stop();
            delete data.spinner;
            return; //Muokattu funktiota jotta spinnerin saa pois päältä
        }
        if (opts !== false){
            data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
        }
    });
    return this;
};

//Spinner options
var opts = {
    lines: 12, // The number of lines to draw
    length: 7, // The length of each line
    width: 4, // The line thickness
    radius: 10, // The radius of the inner circle
    color: '#000', // #rgb or #rrggbb
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false // Whether to render a shadow
};

// rakentaa linkin josta lukkari löytyy
function haeJakso(x){
    alkupvm = jaksot[x][0].replace(/\./gi, "");
    loppupvm = jaksot[x][1].replace(/\./gi, "");
    var linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
    //var linkki = "jakso2.html";
    //yritä ladata lukkari sivulle
    try{
        $("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
            korvaa();
        });
        $("#lukkarikoodit").load(linkki + " .lukkari_table2");
    }
    catch(err){
        alert ("Lukkarin latauksessa tapahtui virhe " + err);
    }
}

// korvaa talukosta koodit nimillä
function korvaa(){
    $("#lukkarinimet td").each(function(){
        var text = $(this).html();
        for(i in koodit){
            text = text.replace(i, koodit[i]);
        }
        $(this).html(text);
    });
}

//muuta ruokalistan asemointia jos ikkuna liian pieni
function ikkunankoko(){
    if($(window).width() < 1400){
        $("#ruokalista").css("position", "relative");
        $("#ruokalista").css("right", "auto");
        $("#ruokalista").css("left", "1.5%");
        $("#sivu").css("min-height", "1900px");
        $("#ruokalista").remove().insertBefore($("#napit"));
    }
    else{
        $("#ruokalista").css("position", "absolute");
        $("#ruokalista").css("right", "12%");
        $("#ruokalista").css("left", "auto");
        $("#sivu").css("min-height", "1310px");
        $("#ruokalista").remove().insertAfter($("#napit"));
    }
}

//Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso(){
    var nyt = Date.today();
    //var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

    for (var i = 1; i <= 6; i++){
        loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
        alkupvm = Date.parse(jaksot[i][0]);
        loppupvm = Date.parse(jaksot[i][1]);

        //tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
        if(nyt >= alkupvm && nyt <= loppupvm)
            return i;
        //tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
        //ja palautaa uuden jakson
        else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
            return i+1;
    }
    //palauttaa viimeisen jakson jos koulu loppunut
    if(nyt > jaksot[6][1])
        return 6;
}

$(window).resize(function(){
    ikkunankoko();
});

$(document).ready(function(){

    $("#loading").ajaxStart(function(){
        $(this).spin(opts);
    });
    $("#loading").ajaxStop(function(){
        $(this).spin();
    });

    ikkunankoko();

    //hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
    haeJakso(nykyinenJakso());
    $("#jakso").val(nykyinenJakso());

    $("#ruokalista").load("ruokalistaa.php");

    //hakee valitun jakson nappia painettaessa
    $("#ok").click(function(){
        var jakso = $("#jakso").val();
        haeJakso(jakso);
    });

    //vaihtaa nimet koodeiksi ja toisinpäin
    $("#toggle").click(function(){
        $(".lukkari").toggle();
    });
});
<|endoftext|>


<commit_before>/*
 * @package jsDAV
 * @subpackage DAV
 * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org>
 * @author Mike de Boer <info AT mikedeboer DOT nl>
 * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
 */
"use strict";

var Base = require("./../shared/base");
// interfaces to check for:
var jsDAV_iFile = require("./interfaces/iFile");
var jsDAV_iCollection = require("./interfaces/iCollection");
var jsDAV_iProperties = require("./interfaces/iProperties");

var Exc = require("./../shared/exceptions");
var Util  = require("./../shared/util");
var Path = require("path");

/**
 * Abstract tree object
 */
var jsDAV_Tree = module.exports = Base.extend({
    /**
     * Chunk of the path that is part of the sandbox
     *
     * @var string
     */
    sandbox: null,

    /**
     * Set the path that needs to be stripped from the real path when presented
     * to the user/ client and to check if a path from a request is within this
     * path to prevent operations to files and directories that are outside of
     * this sandbox
     *
     * @param {string} path
     * @return void
     */
    setSandbox: function(path) {
        this.sandbox = path.replace(/[\/]+$/, "");
    },

    /**
     * Strips the sandbox part from the path.
     *
     * @var {string} path
     * @return string
     */
    stripSandbox: function(path) {
        if (!this.sandbox)
            return path;
        var idx = path.indexOf(this.sandbox);
        if (idx === -1)
            return path;
        // remove the sandbox path from full path, usually at the start of the string
        return path.substr(idx + this.sandbox.length);
    },

    /**
     * Check whether the provided path is located inside the sandbox
     *
     * @param {string} path
     * @return boolean
     */
    insideSandbox: function(path) {
        if (!this.sandbox)
            return true;
        // if the relative path FROM the sandbox directory TO the requested path
        // is outside of the sandbox directory, the result of Path.relative() will
        // start with '../', which we can trap and use:
        return Path.relative(this.sandbox, path).indexOf("../") !== 0;
    },

    /**
     * This function must return an iNode object for a path
     * If a Path doesn't exist, thrown an Exc.FileNotFound
     *
     * @param {String} path
     * @throws Exception_FileNotFound
     * @return jsDAV_iNode
     */
    getNodeForPath: function(path, cbgetnodefp) {},

    /**
     * Copies a file from path to another
     *
     * @param {string} sourcePath The source location
     * @param {string} destinationPath The full destination path
     * @return void
     */
    copy: function(sourcePath, destinationPath, cbcopytree) {
        var self = this;
        if (!this.insideSandbox(destinationPath)) {
            return cbcopytree(new Exc.Forbidden("You are not allowed to copy to " +
                this.stripSandbox(destinationPath)));
        }
        this.getNodeForPath(sourcePath, function(err, sourceNode) {
            if (err)
                return cbcopytree(err);
            // grab the dirname and basename components
            var parts           = Util.splitPath(destinationPath);
            var destinationDir  = parts[0];
            var destinationName = parts[1];

            self.getNodeForPath(destinationDir, function(err, destinationParent) {
                if (err)
                    return cbcopytree(err);
                self.copyNode(sourceNode, destinationParent, destinationName, function(err) {
                    if (err)
                        return cbcopytree(err);
                    cbcopytree();
                });
            });
        });
    },

    /**
     * Moves a file from one location to another
     *
     * @param {string} sourcePath The path to the file which should be moved
     * @param {string} destinationPath The full destination path, so not just the destination parent node
     * @return int
     */
    move: function(sourcePath, destinationPath, cbmovetree) {
        var parts      = Util.splitPath(sourcePath);
        var sourceDir  = parts[0];
        var sourceName = parts[1];
        parts = Util.splitPath(destinationPath);
        if (!this.insideSandbox(destinationPath)) {
            return cbmovetree(new Exc.Forbidden("You are not allowed to move to " +
                this.stripSandbox(destinationPath)));
        }
        var destinationDir  = parts[0];
        var destinationName = parts[1];

        if (sourceDir === destinationDir) {
            this.getNodeForPath(sourcePath, function(err, renameable) {
                if (err)
                    return cbmovetree(err);
                renameable.setName(destinationName, onDone);
            });
        }
        else {
            var self = this;
            this.copy(sourcePath, destinationPath, function(err) {
                if (err)
                    return cbmovetree(err);
                self.getNodeForPath(sourcePath, function(err, sourceNode) {
                    if( err )
                        return cbmovetree(err);
                    sourceNode.delete(onDone);
                });
            });
        }

        function onDone(err) {
            if (err)
                return cbmovetree(err);
            cbmovetree();
        }
    },

    /**
     * Deletes a node from the tree
     *
     * @param {String} path
     * @return void
     */
    "delete": function(path, cbtreedelete) {
        var self = this;
        this.getNodeForPath(path, function(err, node) {
            if (err)
                return cbtreedelete(err);

            node.delete(function(err) {
                if (err)
                    return cbtreedelete(err);
                self.markDirty(Util.splitPath(path)[0]);
                cbtreedelete();
            });
        });
    },

    /**
     * Returns a list of childnodes for a given path.
     *
     * @param {String} path
     * @return array
     */
    getChildren: function(path, cbtreechildren) {
        this.getNodeForPath(path, function(err, node) {
            if (err)
                return cbtreechildren(err);
            node.getChildren(cbtreechildren);
        });
    },

    /**
     * copyNode
     *
     * @param {jsDAV_iNode} source
     * @param {jsDAV_iCollection} destination
     * @return void
     */
    copyNode: function(source, destinationParent, destinationName, cbcopytreenode) {
        if (!destinationName)
            destinationName = source.getName();

        var destination;
        var self = this;

        if (source.hasFeature(jsDAV_iFile)) {
            source.get(function(err, data) {
                if (err)
                    return cbcopytreenode(err);
                destinationParent.createFile(destinationName, data, "binary", function(err) {
                    if (err)
                        return cbcopytreenode(err);
                    destinationParent.getChild(destinationName, function(err, destination) {
                        if (err)
                            return cbcopytreenode(err);
                        afterCopy(destination);
                    });
                });
            });
        }
        else if (source.hasFeature(jsDAV_iCollection)) {
            destinationParent.createDirectory(destinationName, function(err) {
                if (err)
                    return cbcopytreenode(err);
                destinationParent.getChild(destinationName, function(err, destination) {
                    if (err)
                        return cbcopytreenode(err);
                    var child;
                    var c       = source.getChildren();
                    var i       = 0;
                    var l       = c.length;
                    var error   = null;
                    var onError = function(err) {
                        if (err)
                            error = err;
                    };
                    for (; i < l && !error; ++i) {
                        child = c[i];
                        self.copyNode(child, destination, onError);
                    }
                    if (error)
                        return cbcopytreenode(error);
                    afterCopy(destination);
                });
            });

        }

        function afterCopy(destination) {
            if (source.hasFeature(jsDAV_iProperties) && destination.hasFeature(jsDAV_iProperties))
                destination.updateProperties(source.getProperties({}), cbcopytreenode);
            else
                cbcopytreenode();
        }
    }
});
<commit_msg>Conforms whitespace rules<commit_after>/*
 * @package jsDAV
 * @subpackage DAV
 * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org>
 * @author Mike de Boer <info AT mikedeboer DOT nl>
 * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
 */
"use strict";

var Base = require("./../shared/base");
// interfaces to check for:
var jsDAV_iFile = require("./interfaces/iFile");
var jsDAV_iCollection = require("./interfaces/iCollection");
var jsDAV_iProperties = require("./interfaces/iProperties");

var Exc = require("./../shared/exceptions");
var Util  = require("./../shared/util");
var Path = require("path");

/**
 * Abstract tree object
 */
var jsDAV_Tree = module.exports = Base.extend({
    /**
     * Chunk of the path that is part of the sandbox
     *
     * @var string
     */
    sandbox: null,

    /**
     * Set the path that needs to be stripped from the real path when presented
     * to the user/ client and to check if a path from a request is within this
     * path to prevent operations to files and directories that are outside of
     * this sandbox
     *
     * @param {string} path
     * @return void
     */
    setSandbox: function(path) {
        this.sandbox = path.replace(/[\/]+$/, "");
    },

    /**
     * Strips the sandbox part from the path.
     *
     * @var {string} path
     * @return string
     */
    stripSandbox: function(path) {
        if (!this.sandbox)
            return path;
        var idx = path.indexOf(this.sandbox);
        if (idx === -1)
            return path;
        // remove the sandbox path from full path, usually at the start of the string
        return path.substr(idx + this.sandbox.length);
    },

    /**
     * Check whether the provided path is located inside the sandbox
     *
     * @param {string} path
     * @return boolean
     */
    insideSandbox: function(path) {
        if (!this.sandbox)
            return true;
        // if the relative path FROM the sandbox directory TO the requested path
        // is outside of the sandbox directory, the result of Path.relative() will
        // start with '../', which we can trap and use:
        return Path.relative(this.sandbox, path).indexOf("../") !== 0;
    },

    /**
     * This function must return an iNode object for a path
     * If a Path doesn't exist, thrown an Exc.FileNotFound
     *
     * @param {String} path
     * @throws Exception_FileNotFound
     * @return jsDAV_iNode
     */
    getNodeForPath: function(path, cbgetnodefp) {},

    /**
     * Copies a file from path to another
     *
     * @param {string} sourcePath The source location
     * @param {string} destinationPath The full destination path
     * @return void
     */
    copy: function(sourcePath, destinationPath, cbcopytree) {
        var self = this;
        if (!this.insideSandbox(destinationPath)) {
            return cbcopytree(new Exc.Forbidden("You are not allowed to copy to " +
                this.stripSandbox(destinationPath)));
        }
        this.getNodeForPath(sourcePath, function(err, sourceNode) {
            if (err)
                return cbcopytree(err);
            // grab the dirname and basename components
            var parts           = Util.splitPath(destinationPath);
            var destinationDir  = parts[0];
            var destinationName = parts[1];

            self.getNodeForPath(destinationDir, function(err, destinationParent) {
                if (err)
                    return cbcopytree(err);
                self.copyNode(sourceNode, destinationParent, destinationName, function(err) {
                    if (err)
                        return cbcopytree(err);
                    cbcopytree();
                });
            });
        });
    },

    /**
     * Moves a file from one location to another
     *
     * @param {string} sourcePath The path to the file which should be moved
     * @param {string} destinationPath The full destination path, so not just the destination parent node
     * @return int
     */
    move: function(sourcePath, destinationPath, cbmovetree) {
        var parts      = Util.splitPath(sourcePath);
        var sourceDir  = parts[0];
        var sourceName = parts[1];
        parts = Util.splitPath(destinationPath);
        if (!this.insideSandbox(destinationPath)) {
            return cbmovetree(new Exc.Forbidden("You are not allowed to move to " +
                this.stripSandbox(destinationPath)));
        }
        var destinationDir  = parts[0];
        var destinationName = parts[1];

        if (sourceDir === destinationDir) {
            this.getNodeForPath(sourcePath, function(err, renameable) {
                if (err)
                    return cbmovetree(err);
                renameable.setName(destinationName, onDone);
            });
        }
        else {
            var self = this;
            this.copy(sourcePath, destinationPath, function(err) {
                if (err)
                    return cbmovetree(err);
                self.getNodeForPath(sourcePath, function(err, sourceNode) {
                    if(err)
                        return cbmovetree(err);
                    sourceNode.delete(onDone);
                });
            });
        }

        function onDone(err) {
            if (err)
                return cbmovetree(err);
            cbmovetree();
        }
    },

    /**
     * Deletes a node from the tree
     *
     * @param {String} path
     * @return void
     */
    "delete": function(path, cbtreedelete) {
        var self = this;
        this.getNodeForPath(path, function(err, node) {
            if (err)
                return cbtreedelete(err);

            node.delete(function(err) {
                if (err)
                    return cbtreedelete(err);
                self.markDirty(Util.splitPath(path)[0]);
                cbtreedelete();
            });
        });
    },

    /**
     * Returns a list of childnodes for a given path.
     *
     * @param {String} path
     * @return array
     */
    getChildren: function(path, cbtreechildren) {
        this.getNodeForPath(path, function(err, node) {
            if (err)
                return cbtreechildren(err);
            node.getChildren(cbtreechildren);
        });
    },

    /**
     * copyNode
     *
     * @param {jsDAV_iNode} source
     * @param {jsDAV_iCollection} destination
     * @return void
     */
    copyNode: function(source, destinationParent, destinationName, cbcopytreenode) {
        if (!destinationName)
            destinationName = source.getName();

        var destination;
        var self = this;

        if (source.hasFeature(jsDAV_iFile)) {
            source.get(function(err, data) {
                if (err)
                    return cbcopytreenode(err);
                destinationParent.createFile(destinationName, data, "binary", function(err) {
                    if (err)
                        return cbcopytreenode(err);
                    destinationParent.getChild(destinationName, function(err, destination) {
                        if (err)
                            return cbcopytreenode(err);
                        afterCopy(destination);
                    });
                });
            });
        }
        else if (source.hasFeature(jsDAV_iCollection)) {
            destinationParent.createDirectory(destinationName, function(err) {
                if (err)
                    return cbcopytreenode(err);
                destinationParent.getChild(destinationName, function(err, destination) {
                    if (err)
                        return cbcopytreenode(err);
                    var child;
                    var c       = source.getChildren();
                    var i       = 0;
                    var l       = c.length;
                    var error   = null;
                    var onError = function(err) {
                        if (err)
                            error = err;
                    };
                    for (; i < l && !error; ++i) {
                        child = c[i];
                        self.copyNode(child, destination, onError);
                    }
                    if (error)
                        return cbcopytreenode(error);
                    afterCopy(destination);
                });
            });

        }

        function afterCopy(destination) {
            if (source.hasFeature(jsDAV_iProperties) && destination.hasFeature(jsDAV_iProperties))
                destination.updateProperties(source.getProperties({}), cbcopytreenode);
            else
                cbcopytreenode();
        }
    }
});
<|endoftext|>


<commit_before>module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    roots: ['<rootDir>/server'],
    globals: {
        'ts-jest': {
            tsConfig: '<rootDir>/server/tsconfig.json'
        }
    }
};
<commit_msg>Update jest config to avoid deprecated settings.<commit_after>module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    roots: ['<rootDir>/server'],
    globals: {
        'ts-jest': {
            tsconfig: '<rootDir>/server/tsconfig.json'
        }
    }
};
<|endoftext|>


<commit_before>var demand = require('must');

exports.initList = function (List) {
	List.add({
		text: String,
		nested: {
			text: String,
		},
	});
};

exports.testFieldType = function (List) {
	describe('updateItem', function () {
		it('should update top level fields', function (done) {
			var testItem = new List.model();
			List.fields.text.updateItem(testItem, {
				text: 'value',
			}, function () {
				demand(testItem.text).be('value');
				done();
			});
		});

		it('should update nested fields', function (done) {
			var testItem = new List.model();
			List.fields['nested.text'].updateItem(testItem, {
				nested: {
					text: 'value',
				},
			}, function () {
				demand(testItem.nested.text).be('value');
				done();
			});
		});

		it('should truncate text with a length', function () {
			var testItem = new List.model({
				text: 'hello world',
			});
			demand(testItem._.text.crop(8)).be('hello wo');
		});

		it('should update nested fields with flat paths', function (done) {
			var testItem = new List.model();
			List.fields['nested.text'].updateItem(testItem, {
				'nested.text': 'value',
			}, function () {
				demand(testItem.nested.text).be('value');
				done();
			});
		});
	});

	describe('validateInput', function () {
		it('should validate string input', function (done) {
			List.fields.text.validateInput({ text: 'a' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate emtpy string input', function (done) {
			List.fields.text.validateInput({ text: '' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate undefined input', function (done) {
			List.fields.text.validateInput({}, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate null input', function (done) {
			List.fields.text.validateInput({ text: null }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate numeric input', function (done) {
			List.fields.text.validateInput({ text: 1 }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate object input', function (done) {
			List.fields.text.validateInput({ text: { things: 'stuff' } }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate array input', function (done) {
			List.fields.text.validateInput({ text: [1, 2, 3] }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate Boolean input', function (done) {
			List.fields.text.validateInput({ text: true }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate function input', function (done) {
			List.fields.text.validateInput({ text: function () {} }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate regexp input', function (done) {
			List.fields.text.validateInput({ text: /foo/ }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate date input', function (done) {
			List.fields.text.validateInput({ text: Date.now() }, function (result) {
				demand(result).be(false);
				done();
			});
		});
	});

	describe('validateRequiredInput', function () {
		it('should validate input present', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: 'a' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate undefined', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: undefined }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should validate undefined if a previous value exists', function (done) {
			var testItem = new List.model({
				text: 'a'
			});
			List.fields.text.validateRequiredInput(testItem, { text: undefined }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate input not present', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: '' }, function (result) {
				demand(result).be(false);
				done();
			});
		});
	});
};
<commit_msg>Fix linting error<commit_after>var demand = require('must');

exports.initList = function (List) {
	List.add({
		text: String,
		nested: {
			text: String,
		},
	});
};

exports.testFieldType = function (List) {
	describe('updateItem', function () {
		it('should update top level fields', function (done) {
			var testItem = new List.model();
			List.fields.text.updateItem(testItem, {
				text: 'value',
			}, function () {
				demand(testItem.text).be('value');
				done();
			});
		});

		it('should update nested fields', function (done) {
			var testItem = new List.model();
			List.fields['nested.text'].updateItem(testItem, {
				nested: {
					text: 'value',
				},
			}, function () {
				demand(testItem.nested.text).be('value');
				done();
			});
		});

		it('should truncate text with a length', function () {
			var testItem = new List.model({
				text: 'hello world',
			});
			demand(testItem._.text.crop(8)).be('hello wo');
		});

		it('should update nested fields with flat paths', function (done) {
			var testItem = new List.model();
			List.fields['nested.text'].updateItem(testItem, {
				'nested.text': 'value',
			}, function () {
				demand(testItem.nested.text).be('value');
				done();
			});
		});
	});

	describe('validateInput', function () {
		it('should validate string input', function (done) {
			List.fields.text.validateInput({ text: 'a' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate emtpy string input', function (done) {
			List.fields.text.validateInput({ text: '' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate undefined input', function (done) {
			List.fields.text.validateInput({}, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should validate null input', function (done) {
			List.fields.text.validateInput({ text: null }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate numeric input', function (done) {
			List.fields.text.validateInput({ text: 1 }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate object input', function (done) {
			List.fields.text.validateInput({ text: { things: 'stuff' } }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate array input', function (done) {
			List.fields.text.validateInput({ text: [1, 2, 3] }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate Boolean input', function (done) {
			List.fields.text.validateInput({ text: true }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate function input', function (done) {
			List.fields.text.validateInput({ text: function () {} }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate regexp input', function (done) {
			List.fields.text.validateInput({ text: /foo/ }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should invalidate date input', function (done) {
			List.fields.text.validateInput({ text: Date.now() }, function (result) {
				demand(result).be(false);
				done();
			});
		});
	});

	describe('validateRequiredInput', function () {
		it('should validate input present', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: 'a' }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate undefined', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: undefined }, function (result) {
				demand(result).be(false);
				done();
			});
		});

		it('should validate undefined if a previous value exists', function (done) {
			var testItem = new List.model({
				text: 'a',
			});
			List.fields.text.validateRequiredInput(testItem, { text: undefined }, function (result) {
				demand(result).be(true);
				done();
			});
		});

		it('should invalidate input not present', function (done) {
			var testItem = new List.model();
			List.fields.text.validateRequiredInput(testItem, { text: '' }, function (result) {
				demand(result).be(false);
				done();
			});
		});
	});
};
<|endoftext|>


<commit_before>// Next:
// DONE: output cursor: move to end, so that new commands are showing
// get rid of extra newline character so Mike doesn't get offended :(

// get text from line highlihted -> read code
// send only current line
// send on Shift Enter

// resize text area (happens automatically? in Safari) -> set textWidth to width of textarea, whenever user resizes the area (and in the beginning)
// horizontal scroll bar, so text doesn't wrap
// only send current line from text input
// keep history of input
// print output once it's back instead of hitting enter over and over, global
// event handler?
// handle post callback differently. Ajax?
//

$(document).ready(function() {

		// initialisation
		editAreaLoader.init({
			id: "M2In"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		editAreaLoader.init({
			id: "M2Out"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		// callback functions

		function test_setSelectionRange(id){
			editAreaLoader.setSelectionRange(id, 100, 150);
		}

		function test_getSelectionRange(id){
			var sel =editAreaLoader.getSelectionRange(id);
			alert("start: "+sel["start"]+"\nend: "+sel["end"]);
		}

		function test_setSelectedText(id){
			text= "[REPLACED SELECTION]";
			editAreaLoader.setSelectedText(id, text);
		}

		function test_getSelectedText(id){
			alert(editAreaLoader.getSelectedText(id));
		}

		function toogle_editable(id)
		{
			editAreaLoader.execCommand(id, 'set_editable', !editAreaLoader.execCommand(id, 'is_editable'));
		}

  // add markup to container and apply click handlers to anchors
  //$("#header a").click(function(e) {

  $('#M2In').keypress(function(e) {
    if(e.which == 13){
      submitNow();
    }
  });

  $("#button1").click(submitNow);

  $("#reset").click(function(e) {
    if (!sendToM2( ">>RESET<<", "We are resetting the current M2 session.\n")) {
      $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
    }
    $("#M2Out").val("");
  });

  //$("#M2Out").append(window.getSelected());
  //$("#M2Out").val($("#M2Out").val() + "\n");
});

// return false on error
function sendToM2( myCommand, baseString ) {
  $.post("sockets/M2Client.php", {cmd: myCommand}, function(data){
    if(data != "0") {
		editAreaLoader.setValue("M2Out", baseString + data)
    //  $("#M2Out").val(baseString + data );
		scrollDown();
      $("#M2In").val("");
    } else {
      return false;
    }
  });
  return true;
}

/* attempt to find a text selection */
function getSelected() {
  if(window.getSelection) { $('#M2Out').append("Get Selected! option1\n --" + window.getSelection() + "--"); return window.getSelection();  }

  else if(document.getSelection) { $('#M2Out').append("option2");return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { $('#M2Out').append("option3"); return selection.text; }
    $('#M2Out').append("option4");
    return false;
  }
  $('#M2Out').append("option never");
  return false;
}

function scrollDown() {
	mySize = $('#M2Out').val().length;
	//$t.animate({ scrollTop: mySize}, 1000);
	//$("#M2Out").val($("#M2Out").val() + "\nSize: " + mySize);
	$('#M2Out').scrollTop(mySize);
	//animate({scrollTop: 0},'slow');
	return false; // Return false to cancel the default link action
}

function submitNow(e) {
	var sel =editAreaLoader.getSelectionRange("M2In");
	alert("start: "+sel["start"]+"\nend: "+sel["end"]);

	//alert('position is ' + position);
  // this should be current line
  myCommand = editAreaLoader.getSelectedText("M2In");
  // call to php script
  if (!sendToM2( myCommand, "Session initialized successfully! ")) {
    $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
  }
}

/* create sniffer */
/*$(document).ready(function() {
  $('#content-area').mouseup(function() {
  var selection = getSelected();
  if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
  $.ajax({
type: 'post',
url: 'ajax-selection-copy.php',
data: 'selection=' + encodeURI(selection)
});
}
});
});*/

<commit_msg>selection or current line is now used<commit_after>// Next:
// DONE: output cursor: move to end, so that new commands are showing
// get rid of extra newline character so Mike doesn't get offended :(

// get text from line highlihted -> read code
// send only current line
// send on Shift Enter

// resize text area (happens automatically? in Safari) -> set textWidth to width of textarea, whenever user resizes the area (and in the beginning)
// horizontal scroll bar, so text doesn't wrap
// only send current line from text input
// keep history of input
// print output once it's back instead of hitting enter over and over, global
// event handler?
// handle post callback differently. Ajax?
//

$(document).ready(function() {

		// initialisation
		editAreaLoader.init({
			id: "M2In"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		editAreaLoader.init({
			id: "M2Out"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		// callback functions

		function test_setSelectionRange(id){
			editAreaLoader.setSelectionRange(id, 100, 150);
		}

		function test_getSelectionRange(id){
			var sel =editAreaLoader.getSelectionRange(id);
			alert("start: "+sel["start"]+"\nend: "+sel["end"]);
		}

		function test_setSelectedText(id){
			text= "[REPLACED SELECTION]";
			editAreaLoader.setSelectedText(id, text);
		}

		function test_getSelectedText(id){
			alert(editAreaLoader.getSelectedText(id));
		}

		function toogle_editable(id)
		{
			editAreaLoader.execCommand(id, 'set_editable', !editAreaLoader.execCommand(id, 'is_editable'));
		}

  // add markup to container and apply click handlers to anchors
  //$("#header a").click(function(e) {

  $('#M2In').keypress(function(e) {
    if(e.which == 13){
      submitNow();
    }
  });

  $("#button1").click(submitNow);

  $("#reset").click(function(e) {
    if (!sendToM2( ">>RESET<<", "We are resetting the current M2 session.\n")) {
      $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
    }
    $("#M2Out").val("");
  });

  //$("#M2Out").append(window.getSelected());
  //$("#M2Out").val($("#M2Out").val() + "\n");
});

// return false on error
function sendToM2( myCommand, baseString ) {
  $.post("sockets/M2Client.php", {cmd: myCommand}, function(data){
    if(data != "0") {
		editAreaLoader.setValue("M2Out", baseString + data)
    //  $("#M2Out").val(baseString + data );
		scrollDown();
      $("#M2In").val("");
    } else {
      return false;
    }
  });
  return true;
}

/* attempt to find a text selection */
function getSelected() {
  if(window.getSelection) { $('#M2Out').append("Get Selected! option1\n --" + window.getSelection() + "--"); return window.getSelection();  }

  else if(document.getSelection) { $('#M2Out').append("option2");return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { $('#M2Out').append("option3"); return selection.text; }
    $('#M2Out').append("option4");
    return false;
  }
  $('#M2Out').append("option never");
  return false;
}

function scrollDown() {
	mySize = $('#M2Out').val().length;
	//$t.animate({ scrollTop: mySize}, 1000);
	//$("#M2Out").val($("#M2Out").val() + "\nSize: " + mySize);
	$('#M2Out').scrollTop(mySize);
	//animate({scrollTop: 0},'slow');
	return false; // Return false to cancel the default link action
}

function submitNow(e) {
  var myCommand;
  var sel = editAreaLoader.getSelectionRange("M2In");
  var str = editAreaLoader.getValue("M2In");
  if (sel["start"] == sel["end"]) {
    // grab the current line
    sel["start"] = 1 + str.lastIndexOf("\n", sel["end"]);
  }

  alert("start: "+sel["start"]+"\nend: "+sel["end"]);
  myCommand = str.slice(sel["start"],sel["end"]) + "\n";
  alert("command: \n" + myCommand);

  //alert('position is ' + position);
  // this should be current line
  //myCommand = editAreaLoader.getSelectedText("M2In");
  // call to php script
  if (!sendToM2( myCommand, "Session initialized successfully! ")) {
    $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
  }
}

/* create sniffer */
/*$(document).ready(function() {
  $('#content-area').mouseup(function() {
  var selection = getSelected();
  if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
  $.ajax({
type: 'post',
url: 'ajax-selection-copy.php',
data: 'selection=' + encodeURI(selection)
});
}
});
});*/

<|endoftext|>


<commit_before>/**
 * jQuery UI PickList Widget
 *
 * Copyright (c) 2012 Jonathon Freeman <jonathon@awnry.com>
 * Distributed under the terms of the MIT License.
 *
 * http://code.google.com/p/jquery-ui-picklist/
 */
(function($)
{

	$.widget("awnry.pickList",
	{
		options:
		{
			// Container classes
			mainClass:                  "pickList",
			listContainerClass:         "pickList_listContainer",
			sourceListContainerClass:   "pickList_sourceListContainer",
			controlsContainerClass:     "pickList_controlsContainer",
			targetListContainerClass:   "pickList_targetListContainer",
			listClass:                  "pickList_list",
			sourceListClass:            "pickList_sourceList",
			targetListClass:            "pickList_targetList",
			clearClass:                 "pickList_clear",

			// List item classes
			listItemClass:              "pickList_listItem",
			richListItemClass:          "pickList_richListItem",
			selectedListItemClass:      "pickList_selectedListItem",

			// Control classes
			addAllClass:                "pickList_addAll",
			addClass:                   "pickList_add",
			removeAllClass:             "pickList_removeAll",
			removeClass:                "pickList_remove",

			// Control labels
			addAllLabel:                ">>",
			addLabel:                   ">",
			removeAllLabel:             "<<",
			removeLabel:                "<",

			// List labels
			listLabelClass:             "pickList_listLabel",
			sourceListLabel:            "Available",
			sourceListLabelClass:       "pickList_sourceListLabel",
			targetListLabel:            "Selected",
			targetListLabelClass:       "pickList_targetListLabel",

			// Sorting
			sortItems:                  true,
			sortAttribute:              "label",

			// Rich content items
			richItems:                  []
		},

		_create: function()
		{
			var self = this;

			self._buildPickList();
			self._refresh();
		},

		_buildPickList: function()
		{
			var self = this;

			self.pickList = $("<div/>")
					.hide()
					.addClass(self.options.mainClass)
					.insertAfter(self.element)
					.append(self._buildSourceList())
					.append(self._buildControls())
					.append(self._buildTargetList())
					.append( $("<div/>").addClass(self.options.clearClass) );

			self._populateLists();

			self.element.hide();
			self.pickList.show();
		},

		_buildSourceList: function()
		{
			var self = this;

			var container = $("<div/>")
					.addClass(self.options.listContainerClass)
					.addClass(self.options.sourceListContainerClass)
					.disableSelection();

			var label = $("<div/>")
					.text(self.options.sourceListLabel)
					.addClass(self.options.listLabelClass)
					.addClass(self.options.sourceListLabelClass);

			self.sourceList = $("<ul/>")
					.addClass(self.options.listClass)
					.addClass(self.options.sourceListClass)
					.delegate("li", "click", {pickList: self}, self._changeHandler);

			container
					.append(label)
					.append(self.sourceList);

			return container;
		},

		_buildTargetList: function()
		{
			var self = this;

			var container = $("<div/>")
					.addClass(self.options.listContainerClass)
					.addClass(self.options.targetListContainerClass)
					.disableSelection();

			var label = $("<div/>")
					.text(self.options.targetListLabel)
					.addClass(self.options.listLabelClass)
					.addClass(self.options.targetListLabelClass);

			self.targetList = $("<ul/>")
					.addClass(self.options.listClass)
					.addClass(self.options.targetListClass)
					.delegate("li", "click", {pickList: self}, self._changeHandler);

			container
					.append(label)
					.append(self.targetList);

			return container;
		},

		_buildControls: function()
		{
			var self = this;

			self.controls = $("<div/>").addClass(self.options.controlsContainerClass);

			self.addAllButton = $("<button/>").button().click({pickList: self}, self._addAllHandler).html(self.options.addAllLabel).addClass(self.options.addAllClass);
			self.addButton = $("<button/>").button().click({pickList: self}, self._addHandler).html(self.options.addLabel).addClass(self.options.addClass);
			self.removeButton = $("<button/>").button().click({pickList: self}, self._removeHandler).html(self.options.removeLabel).addClass(self.options.removeClass);
			self.removeAllButton = $("<button/>").button().click({pickList: self}, self._removeAllHandler).html(self.options.removeAllLabel).addClass(self.options.removeAllClass);

			self.controls
					.append(self.addAllButton)
					.append(self.addButton)
					.append(self.removeButton)
					.append(self.removeAllButton);

			return self.controls;
		},

		_populateLists: function()
		{
			var self = this;

			self.element.children().each(function()
			{
				var text = $(this).text();
				var copy = $("<li/>")
						.text(text)
						.val($(this).val())
						.attr("label", text)
						.addClass(self.options.listItemClass);

				if($(this).attr("selected") == "selected")
				{
					self.targetList.append( copy );
				}
				else
				{
					self.sourceList.append( copy );
				}
			});

			$(self.options.richItems).each(function()
			{
				var list = this.selected ? self.targetList : self.sourceList;
				list.append( self._createRichItem(this) );
			});
		},

		_addItem: function(value)
		{
			var self = this;

			self.sourceList.children("[value='" + value + "']").each(function()
			{
				self.targetList.append( self._removeSelection($(this)) );
			});

			self.element.children("[value='" + value + "']").each(function()
			{
				$(this).attr("selected", "selected");
			});
		},

		_removeItem: function(value)
		{
			var self = this;

			self.targetList.children("[value='" + value + "']").each(function()
			{
				self.sourceList.append( self._removeSelection($(this)) );
			});

			self.element.children("[value='" + value + "']").each(function()
			{
				$(this).removeAttr("selected");
			});
		},

		_addAllHandler: function(e)
		{
			var self = e.data.pickList;

			self.sourceList.children().each(function()
			{
				self._addItem( $(this).val() );
			});

			self._refresh();
		},

		_addHandler: function(e)
		{
			var self = e.data.pickList;

			self.sourceList.children(".ui-selected").each(function()
			{
				self._addItem( $(this).val() );
			});

			self._refresh();
		},

		_removeHandler: function(e)
		{
			var self = e.data.pickList;

			self.targetList.children(".ui-selected").each(function()
			{
				self._removeItem( $(this).val() );
			});

			self._refresh();
		},

		_removeAllHandler: function(e)
		{
			var self = e.data.pickList;

			self.targetList.children().each(function()
			{
				self._removeItem( $(this).val() );
			});

			self._refresh();
		},

		_refresh: function()
		{
			var self = this;

			// Enable/disable the Add All and Remove All buttons.
			self.addAllButton.button( (self.sourceList.children().length > 0) ? "enable" : "disable" );
			self.removeAllButton.button( (self.targetList.children().length > 0) ? "enable" : "disable" );

			// Enable/disable the Add button state.
			if(self.sourceList.children(".ui-selected").length)
			{
				self.addButton.button("enable");
			}
			else
			{
				self.addButton.button("disable");
			}

			// Enable/disable the Remove button state.
			if(self.targetList.children(".ui-selected").length)
			{
				self.removeButton.button("enable");
			}
			else
			{
				self.removeButton.button("disable");
			}

			// Refresh the buttons.
			self.controls.children().each(function()
			{
				$(this).button("refresh");
			});

			// Sort the selection lists.
			if(self.options.sortItems)
			{
				self._sortItems(self.sourceList, self.options);
				self._sortItems(self.targetList, self.options);
			}
		},

		_sortItems: function(list, options)
		{
			var items = new Array();

			list.children().each(function()
			{
				items.push( $(this) );
			});

			items.sort(function(a, b)
			{
				if(a.attr(options.sortAttribute) > b.attr(options.sortAttribute))
				{
					return 1;
				}
				else if(a.attr(options.sortAttribute) == b.attr(options.sortAttribute))
				{
					return 0;
				}
				else
				{
					return -1;
				}
			});

			list.empty();

			for(var i = 0; i < items.length; i++)
			{
				list.append(items[i]);
			}
		},

		_changeHandler: function(e)
		{
			var self = e.data.pickList;

			if(e.ctrlKey)
			{
				if(self._isSelected( $(this) ))
				{
					self._removeSelection( $(this) );
				}
				else
				{
					self.lastSelectedItem = $(this);
					self._addSelection( $(this) );
				}
			}
			else if(e.shiftKey)
			{
				var current = $(this).val();
				var last = self.lastSelectedItem.val();

				if($(this).index() < $(self.lastSelectedItem).index())
				{
					var temp = current;
					current = last;
					last = temp;
				}

				var pastStart = false;
				var beforeEnd = true;

				self._clearSelections( $(this).parent() );

				$(this).parent().children().each(function()
				{
					if($(this).val() == last)
					{
						pastStart = true;
					}

					if(pastStart && beforeEnd)
					{
						self._addSelection( $(this) );
					}

					if($(this).val() == current)
					{
						beforeEnd = false;
					}

				});
			}
			else
			{
				self.lastSelectedItem = $(this);
				self._clearSelections( $(this).parent() );
				self._addSelection( $(this) );
			}

			self._refresh();
		},

		_isSelected: function(listItem)
		{
			return listItem.hasClass("ui-selected");
		},

		_addSelection: function(listItem)
		{
			var self = this;

			return listItem
					.addClass("ui-selected")
					.addClass("ui-state-highlight")
					.addClass(self.options.selectedListItemClass);
		},

		_removeSelection: function(listItem)
		{
			var self = this;

			return listItem
					.removeClass("ui-selected")
					.removeClass("ui-state-highlight")
					.removeClass(self.options.selectedListItemClass);
		},

		_clearSelections: function(list)
		{
			var self = this;

			list.children().each(function()
			{
				self._removeSelection( $(this) );
			});
		},

		_setOption: function(key, value)
		{
			switch(key)
			{
				case "clear":
				{
					break;
				}
			}

			$.Widget.prototype._setOption.apply(this, arguments);
		},

		destroy: function()
		{
			$.Widget.prototype.destroy.call(this);
		},

		insert: function(item)
		{
			var self = this;

			var list = item.selected ? self.targetList : self.sourceList;
			list.append( self._createRichItem(item) );

			self._refresh();
		},

		_createRichItem: function(item)
		{
			var self = this;

			var selectItem = $("<option/>").val(item.value).text(item.label);

			if(item.selected)
			{
				selectItem.attr("selected", "selected");
			}

			self.element.append( selectItem );

			return $("<li/>")
					.val(item.value)
					.attr("label", item.label)
					.addClass(self.options.listItemClass)
					.addClass(self.options.richListItemClass)
					.append(item.element);
		}
	});
}(jQuery));
<commit_msg>Whitespace cleanup.<commit_after>/**
 * jQuery UI PickList Widget
 *
 * Copyright (c) 2012 Jonathon Freeman <jonathon@awnry.com>
 * Distributed under the terms of the MIT License.
 *
 * http://code.google.com/p/jquery-ui-picklist/
 */
(function($)
{
	$.widget("awnry.pickList",
	{
		options:
		{
			// Container classes
			mainClass:                  "pickList",
			listContainerClass:         "pickList_listContainer",
			sourceListContainerClass:   "pickList_sourceListContainer",
			controlsContainerClass:     "pickList_controlsContainer",
			targetListContainerClass:   "pickList_targetListContainer",
			listClass:                  "pickList_list",
			sourceListClass:            "pickList_sourceList",
			targetListClass:            "pickList_targetList",
			clearClass:                 "pickList_clear",

			// List item classes
			listItemClass:              "pickList_listItem",
			richListItemClass:          "pickList_richListItem",
			selectedListItemClass:      "pickList_selectedListItem",

			// Control classes
			addAllClass:                "pickList_addAll",
			addClass:                   "pickList_add",
			removeAllClass:             "pickList_removeAll",
			removeClass:                "pickList_remove",

			// Control labels
			addAllLabel:                ">>",
			addLabel:                   ">",
			removeAllLabel:             "<<",
			removeLabel:                "<",

			// List labels
			listLabelClass:             "pickList_listLabel",
			sourceListLabel:            "Available",
			sourceListLabelClass:       "pickList_sourceListLabel",
			targetListLabel:            "Selected",
			targetListLabelClass:       "pickList_targetListLabel",

			// Sorting
			sortItems:                  true,
			sortAttribute:              "label",

			// Rich content items
			richItems:                  []
		},

		_create: function()
		{
			var self = this;

			self._buildPickList();
			self._refresh();
		},

		_buildPickList: function()
		{
			var self = this;

			self.pickList = $("<div/>")
					.hide()
					.addClass(self.options.mainClass)
					.insertAfter(self.element)
					.append(self._buildSourceList())
					.append(self._buildControls())
					.append(self._buildTargetList())
					.append( $("<div/>").addClass(self.options.clearClass) );

			self._populateLists();

			self.element.hide();
			self.pickList.show();
		},

		_buildSourceList: function()
		{
			var self = this;

			var container = $("<div/>")
					.addClass(self.options.listContainerClass)
					.addClass(self.options.sourceListContainerClass)
					.disableSelection();

			var label = $("<div/>")
					.text(self.options.sourceListLabel)
					.addClass(self.options.listLabelClass)
					.addClass(self.options.sourceListLabelClass);

			self.sourceList = $("<ul/>")
					.addClass(self.options.listClass)
					.addClass(self.options.sourceListClass)
					.delegate("li", "click", {pickList: self}, self._changeHandler);

			container
					.append(label)
					.append(self.sourceList);

			return container;
		},

		_buildTargetList: function()
		{
			var self = this;

			var container = $("<div/>")
					.addClass(self.options.listContainerClass)
					.addClass(self.options.targetListContainerClass)
					.disableSelection();

			var label = $("<div/>")
					.text(self.options.targetListLabel)
					.addClass(self.options.listLabelClass)
					.addClass(self.options.targetListLabelClass);

			self.targetList = $("<ul/>")
					.addClass(self.options.listClass)
					.addClass(self.options.targetListClass)
					.delegate("li", "click", {pickList: self}, self._changeHandler);

			container
					.append(label)
					.append(self.targetList);

			return container;
		},

		_buildControls: function()
		{
			var self = this;

			self.controls = $("<div/>").addClass(self.options.controlsContainerClass);

			self.addAllButton = $("<button/>").button().click({pickList: self}, self._addAllHandler).html(self.options.addAllLabel).addClass(self.options.addAllClass);
			self.addButton = $("<button/>").button().click({pickList: self}, self._addHandler).html(self.options.addLabel).addClass(self.options.addClass);
			self.removeButton = $("<button/>").button().click({pickList: self}, self._removeHandler).html(self.options.removeLabel).addClass(self.options.removeClass);
			self.removeAllButton = $("<button/>").button().click({pickList: self}, self._removeAllHandler).html(self.options.removeAllLabel).addClass(self.options.removeAllClass);

			self.controls
					.append(self.addAllButton)
					.append(self.addButton)
					.append(self.removeButton)
					.append(self.removeAllButton);

			return self.controls;
		},

		_populateLists: function()
		{
			var self = this;

			self.element.children().each(function()
			{
				var text = $(this).text();
				var copy = $("<li/>")
						.text(text)
						.val($(this).val())
						.attr("label", text)
						.addClass(self.options.listItemClass);

				if($(this).attr("selected") == "selected")
				{
					self.targetList.append( copy );
				}
				else
				{
					self.sourceList.append( copy );
				}
			});

			$(self.options.richItems).each(function()
			{
				var list = this.selected ? self.targetList : self.sourceList;
				list.append( self._createRichItem(this) );
			});
		},

		_addItem: function(value)
		{
			var self = this;

			self.sourceList.children("[value='" + value + "']").each(function()
			{
				self.targetList.append( self._removeSelection($(this)) );
			});

			self.element.children("[value='" + value + "']").each(function()
			{
				$(this).attr("selected", "selected");
			});
		},

		_removeItem: function(value)
		{
			var self = this;

			self.targetList.children("[value='" + value + "']").each(function()
			{
				self.sourceList.append( self._removeSelection($(this)) );
			});

			self.element.children("[value='" + value + "']").each(function()
			{
				$(this).removeAttr("selected");
			});
		},

		_addAllHandler: function(e)
		{
			var self = e.data.pickList;

			self.sourceList.children().each(function()
			{
				self._addItem( $(this).val() );
			});

			self._refresh();
		},

		_addHandler: function(e)
		{
			var self = e.data.pickList;

			self.sourceList.children(".ui-selected").each(function()
			{
				self._addItem( $(this).val() );
			});

			self._refresh();
		},

		_removeHandler: function(e)
		{
			var self = e.data.pickList;

			self.targetList.children(".ui-selected").each(function()
			{
				self._removeItem( $(this).val() );
			});

			self._refresh();
		},

		_removeAllHandler: function(e)
		{
			var self = e.data.pickList;

			self.targetList.children().each(function()
			{
				self._removeItem( $(this).val() );
			});

			self._refresh();
		},

		_refresh: function()
		{
			var self = this;

			// Enable/disable the Add All and Remove All buttons.
			self.addAllButton.button( (self.sourceList.children().length > 0) ? "enable" : "disable" );
			self.removeAllButton.button( (self.targetList.children().length > 0) ? "enable" : "disable" );

			// Enable/disable the Add button state.
			if(self.sourceList.children(".ui-selected").length)
			{
				self.addButton.button("enable");
			}
			else
			{
				self.addButton.button("disable");
			}

			// Enable/disable the Remove button state.
			if(self.targetList.children(".ui-selected").length)
			{
				self.removeButton.button("enable");
			}
			else
			{
				self.removeButton.button("disable");
			}

			// Refresh the buttons.
			self.controls.children().each(function()
			{
				$(this).button("refresh");
			});

			// Sort the selection lists.
			if(self.options.sortItems)
			{
				self._sortItems(self.sourceList, self.options);
				self._sortItems(self.targetList, self.options);
			}
		},

		_sortItems: function(list, options)
		{
			var items = new Array();

			list.children().each(function()
			{
				items.push( $(this) );
			});

			items.sort(function(a, b)
			{
				if(a.attr(options.sortAttribute) > b.attr(options.sortAttribute))
				{
					return 1;
				}
				else if(a.attr(options.sortAttribute) == b.attr(options.sortAttribute))
				{
					return 0;
				}
				else
				{
					return -1;
				}
			});

			list.empty();

			for(var i = 0; i < items.length; i++)
			{
				list.append(items[i]);
			}
		},

		_changeHandler: function(e)
		{
			var self = e.data.pickList;

			if(e.ctrlKey)
			{
				if(self._isSelected( $(this) ))
				{
					self._removeSelection( $(this) );
				}
				else
				{
					self.lastSelectedItem = $(this);
					self._addSelection( $(this) );
				}
			}
			else if(e.shiftKey)
			{
				var current = $(this).val();
				var last = self.lastSelectedItem.val();

				if($(this).index() < $(self.lastSelectedItem).index())
				{
					var temp = current;
					current = last;
					last = temp;
				}

				var pastStart = false;
				var beforeEnd = true;

				self._clearSelections( $(this).parent() );

				$(this).parent().children().each(function()
				{
					if($(this).val() == last)
					{
						pastStart = true;
					}

					if(pastStart && beforeEnd)
					{
						self._addSelection( $(this) );
					}

					if($(this).val() == current)
					{
						beforeEnd = false;
					}

				});
			}
			else
			{
				self.lastSelectedItem = $(this);
				self._clearSelections( $(this).parent() );
				self._addSelection( $(this) );
			}

			self._refresh();
		},

		_isSelected: function(listItem)
		{
			return listItem.hasClass("ui-selected");
		},

		_addSelection: function(listItem)
		{
			var self = this;

			return listItem
					.addClass("ui-selected")
					.addClass("ui-state-highlight")
					.addClass(self.options.selectedListItemClass);
		},

		_removeSelection: function(listItem)
		{
			var self = this;

			return listItem
					.removeClass("ui-selected")
					.removeClass("ui-state-highlight")
					.removeClass(self.options.selectedListItemClass);
		},

		_clearSelections: function(list)
		{
			var self = this;

			list.children().each(function()
			{
				self._removeSelection( $(this) );
			});
		},

		_setOption: function(key, value)
		{
			switch(key)
			{
				case "clear":
				{
					break;
				}
			}

			$.Widget.prototype._setOption.apply(this, arguments);
		},

		destroy: function()
		{
			$.Widget.prototype.destroy.call(this);
		},

		insert: function(item)
		{
			var self = this;

			var list = item.selected ? self.targetList : self.sourceList;
			list.append( self._createRichItem(item) );

			self._refresh();
		},

		_createRichItem: function(item)
		{
			var self = this;

			var selectItem = $("<option/>").val(item.value).text(item.label);

			if(item.selected)
			{
				selectItem.attr("selected", "selected");
			}

			self.element.append( selectItem );

			return $("<li/>")
					.val(item.value)
					.attr("label", item.label)
					.addClass(self.options.listItemClass)
					.addClass(self.options.richListItemClass)
					.append(item.element);
		}
	});
}(jQuery));
<|endoftext|>


<commit_before>// Next:
// DONE: output cursor: move to end, so that new commands are showing
// get rid of extra newline character so Mike doesn't get offended :(

// resize text area (happens automatically? in Safari) -> set textWidth to width of textarea, whenever user resizes the area (and in the beginning)
// horizontal scroll bar, so text doesn't wrap
// only send current line from text input
// keep history of input
// print output once it's back instead of hitting enter over and over, global
// event handler?
// handle post callback differently. Ajax?
//

$(document).ready(function() {

		// initialisation
		editAreaLoader.init({
			id: "M2In"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		editAreaLoader.init({
			id: "M2Out"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		// callback functions

		function test_setSelectionRange(id){
			editAreaLoader.setSelectionRange(id, 100, 150);
		}

		function test_getSelectionRange(id){
			var sel =editAreaLoader.getSelectionRange(id);
			alert("start: "+sel["start"]+"\nend: "+sel["end"]);
		}

		function test_setSelectedText(id){
			text= "[REPLACED SELECTION]";
			editAreaLoader.setSelectedText(id, text);
		}

		function test_getSelectedText(id){
			alert(editAreaLoader.getSelectedText(id));
		}

		function toogle_editable(id)
		{
			editAreaLoader.execCommand(id, 'set_editable', !editAreaLoader.execCommand(id, 'is_editable'));
		}

  // add markup to container and apply click handlers to anchors
  //$("#header a").click(function(e) {

  $('#M2In').keypress(function(e) {
    if(e.which == 13){
      submitNow();
    }
  });

  $("#button1").click(submitNow);

  $("#reset").click(function(e) {
    if (!sendToM2( ">>RESET<<", "We are resetting the current M2 session.\n")) {
      $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
    }
    $("#M2Out").val("");
  });

  //$("#M2Out").append(window.getSelected());
  //$("#M2Out").val($("#M2Out").val() + "\n");
});

// return false on error
function sendToM2( myCommand, baseString ) {
  $.post("sockets/M2Client.php", {cmd: myCommand}, function(data){
    if(data != "0") {
		editAreaLoader.setValue("M2Out", baseString + data)
    //  $("#M2Out").val(baseString + data );
		scrollDown();
      $("#M2In").val("");
    } else {
      return false;
    }
  });
  return true;
}

/* attempt to find a text selection */
function getSelected() {
  if(window.getSelection) { $('#M2Out').append("Get Selected! option1\n --" + window.getSelection() + "--"); return window.getSelection();  }

  else if(document.getSelection) { $('#M2Out').append("option2");return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { $('#M2Out').append("option3"); return selection.text; }
    $('#M2Out').append("option4");
    return false;
  }
  $('#M2Out').append("option never");
  return false;
}

function scrollDown() {
	mySize = $('#M2Out').val().length;
	//$t.animate({ scrollTop: mySize}, 1000);
	//$("#M2Out").val($("#M2Out").val() + "\nSize: " + mySize);
	$('#M2Out').scrollTop(mySize);
	//animate({scrollTop: 0},'slow');
	return false; // Return false to cancel the default link action
}

function submitNow(e) {

  // this should be current line
  myCommand = editAreaLoader.getSelectedText("M2In");
  // call to php script
  if (!sendToM2( myCommand, "Session initialized successfully! ")) {
    $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
  }
}

/* create sniffer */
/*$(document).ready(function() {
  $('#content-area').mouseup(function() {
  var selection = getSelected();
  if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
  $.ajax({
type: 'post',
url: 'ajax-selection-copy.php',
data: 'selection=' + encodeURI(selection)
});
}
});
});*/

<commit_msg>get cursor position, good night<commit_after>// Next:
// DONE: output cursor: move to end, so that new commands are showing
// get rid of extra newline character so Mike doesn't get offended :(

// get text from line highlihted -> read code
// send only current line
// send on Shift Enter

// resize text area (happens automatically? in Safari) -> set textWidth to width of textarea, whenever user resizes the area (and in the beginning)
// horizontal scroll bar, so text doesn't wrap
// only send current line from text input
// keep history of input
// print output once it's back instead of hitting enter over and over, global
// event handler?
// handle post callback differently. Ajax?
//

$(document).ready(function() {

		// initialisation
		editAreaLoader.init({
			id: "M2In"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		editAreaLoader.init({
			id: "M2Out"	// id of the textarea to transform
			,start_highlight: true	// if start with highlight
			,allow_resize: "both"
			,allow_toggle: false
			,word_wrap: false
			,language: "en"
			,syntax: "php"
		});

		// callback functions

		function test_setSelectionRange(id){
			editAreaLoader.setSelectionRange(id, 100, 150);
		}

		function test_getSelectionRange(id){
			var sel =editAreaLoader.getSelectionRange(id);
			alert("start: "+sel["start"]+"\nend: "+sel["end"]);
		}

		function test_setSelectedText(id){
			text= "[REPLACED SELECTION]";
			editAreaLoader.setSelectedText(id, text);
		}

		function test_getSelectedText(id){
			alert(editAreaLoader.getSelectedText(id));
		}

		function toogle_editable(id)
		{
			editAreaLoader.execCommand(id, 'set_editable', !editAreaLoader.execCommand(id, 'is_editable'));
		}

  // add markup to container and apply click handlers to anchors
  //$("#header a").click(function(e) {

  $('#M2In').keypress(function(e) {
    if(e.which == 13){
      submitNow();
    }
  });

  $("#button1").click(submitNow);

  $("#reset").click(function(e) {
    if (!sendToM2( ">>RESET<<", "We are resetting the current M2 session.\n")) {
      $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
    }
    $("#M2Out").val("");
  });

  //$("#M2Out").append(window.getSelected());
  //$("#M2Out").val($("#M2Out").val() + "\n");
});

// return false on error
function sendToM2( myCommand, baseString ) {
  $.post("sockets/M2Client.php", {cmd: myCommand}, function(data){
    if(data != "0") {
		editAreaLoader.setValue("M2Out", baseString + data)
    //  $("#M2Out").val(baseString + data );
		scrollDown();
      $("#M2In").val("");
    } else {
      return false;
    }
  });
  return true;
}

/* attempt to find a text selection */
function getSelected() {
  if(window.getSelection) { $('#M2Out').append("Get Selected! option1\n --" + window.getSelection() + "--"); return window.getSelection();  }

  else if(document.getSelection) { $('#M2Out').append("option2");return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { $('#M2Out').append("option3"); return selection.text; }
    $('#M2Out').append("option4");
    return false;
  }
  $('#M2Out').append("option never");
  return false;
}

function scrollDown() {
	mySize = $('#M2Out').val().length;
	//$t.animate({ scrollTop: mySize}, 1000);
	//$("#M2Out").val($("#M2Out").val() + "\nSize: " + mySize);
	$('#M2Out').scrollTop(mySize);
	//animate({scrollTop: 0},'slow');
	return false; // Return false to cancel the default link action
}

function submitNow(e) {
	var sel =editAreaLoader.getSelectionRange("M2In");
	alert("start: "+sel["start"]+"\nend: "+sel["end"]);

	//alert('position is ' + position);
  // this should be current line
  myCommand = editAreaLoader.getSelectedText("M2In");
  // call to php script
  if (!sendToM2( myCommand, "Session initialized successfully! ")) {
    $("#M2Out").val($("#M2Out").val() + "Something Broke! HELP!");
  }
}

/* create sniffer */
/*$(document).ready(function() {
  $('#content-area').mouseup(function() {
  var selection = getSelected();
  if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
  $.ajax({
type: 'post',
url: 'ajax-selection-copy.php',
data: 'selection=' + encodeURI(selection)
});
}
});
});*/

<|endoftext|>


<commit_before>(function($) {
  var settings;

  $.fn.gratuitate = function(callerSettings) {
    settings = $.extend({
      caretColor: '#333, #111',
      contentAttr: 'title',
      tipYPosition: 'below',
      tipXPosition: 'center',
      tipOffset: 0,
      caretSize: '8'
    }, callerSettings || {});
    if (settings.caretColor.indexOf(",") != -1 ) {
      settings.caretColor1 = settings.caretColor.split(',')[0].trim();
      settings.caretColor2 = settings.caretColor.split(',')[1].trim();
    } else {
      settings.caretColor1 = settings.caretColor;
      settings.caretColor2 = settings.caretColor;
    }
    settings.caretSize = parseFloat(settings.caretSize);
    settings.tipOffset = parseFloat(settings.tipOffset);

    return this.each(function() {
      $(this).hover(
        function() {
          if ($(this).attr(settings.contentAttr) != undefined &&
            $(this).attr(settings.contentAttr) != null
            && $(this).attr(settings.contentAttr) != '' ) {
            var link;
            link = $(this);
            link.attr('data-gratuitator-title', link.attr('title'))
            link.attr('title','');
            popUp(link);
            return drawTriangle(link);
            $('a.null').live('click', function() {
              return false
            });
          }
        }, function() {
          $(this).attr('title', $(this).attr('data-gratuitator-title'));
          $('.gratuitator-tip').remove();
        });
      });
    }

  var popUp = function(link) {
    var content, height, width, xOffset, xPos, yOffset, yPos, gTip;
    if (settings.contentAttr == 'title') {
      content = link.attr('data-gratuitator-title')
    } else {
      content = link.attr(settings.contentAttr);
    }
    $('body').append("" + (content) +
      "<canvas id='gratuitator-caret' height='" + settings.caretSize +"' width='" + settings.caretSize + "'></canvas>");
    var gTip = $('.gratuitator-tip');
    width = link.outerWidth();
    xOffset = link.offset().left;
    yOffset = link.offset().top;

    if ( settings.tipXPosition == 'left' &&  settings.tipYPosition == 'above' ||
      settings.tipXPosition == 'left' && settings.tipYPosition == 'below') {
      xPos = xOffset;                                   // left
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'above' ||
      settings.tipXPosition == 'right' && settings.tipYPosition == 'below') {
      xPos = (xOffset + link.outerWidth()) - (settings.caretSize + 10);
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'inline' ) {
      xPos = xOffset + link.outerWidth() + settings.caretSize + settings.tipOffset
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'inline' ) {
      xPos =  xOffset - gTip.outerWidth() - settings.tipOffset
    } else if (settings.tipXPosition == 'center' && settings.tipYPosition == 'inline') {
      xPos = xOffset + link.outerWidth() + settings.caretSize + settings.tipOffset
    } else {
      xPos = (xOffset + (link.outerWidth()/2)) - (gTip.outerWidth()/2.25);
    }

    $('.gratuitator-tip').css({
      'left': xPos
    });

    if ( settings.tipYPosition == 'below' ) {
      yPos = yOffset + settings.tipOffset + settings.caretSize + link.outerHeight();
    } else if ( settings.tipYPosition == 'inline' ) {
      yPos = yOffset + (link.outerHeight()/2 - gTip.height());
    } else {
      height = gTip.outerHeight() + settings.caretSize + settings.tipOffset;
      yPos = link.offset().top - (gTip.outerHeight() + settings.caretSize + settings.tipOffset)
    }

    $('.gratuitator-tip').css({
      'top': yPos
    });

  };
  var drawTriangle = function(link) {
    var context, gradient, caret, leftPos, yPos, link, outerEdge, centerPoint, pointOffset;
    caret = document.getElementById('gratuitator-caret');
    outerEdge = settings.caretSize * 1.5;
    centerPoint = outerEdge / 2;
    pointOffset = 4;
    if ( settings.tipYPosition == 'below' ) {
      yPos = -(settings.caretSize)
    } else {
      yPos = "100%"
    }

    if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'above' ) {
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'below' ) {
      yPos = -($(caret).outerHeight());
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'center' && settings.tipYPosition == 'above' ) {
      yPos = "100%";
      leftPos = $('.gratuitator-tip').outerWidth()/2 - ((settings.caretSize * 1.25));
    } else if ( settings.tipXPosition == 'center' && settings.tipYPosition == 'below' ) {
      yPos = -(settings.caretSize);
      leftPos = $('.gratuitator-tip').outerWidth()/2 - ((settings.caretSize * 1.25));
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'above' ) {
      yPos = "100%";
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'below' ) {
      leftPos = pointOffset;
      yPos = -($(caret).outerHeight())
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'inline' ) {
      leftPos = -(settings.caretSize);
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'inline') {
      leftPos = "100%";
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    } else {
      leftPos = -(settings.caretSize);
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    }
    $(caret).css({
      'position': 'absolute',
      'z-index': 100,
      'top': yPos,
      'left': leftPos,
    }).attr('height', outerEdge).attr('width', outerEdge*2);
    if (caret && caret.getContext) {
      context = caret.getContext('2d');

      if ( settings.tipYPosition == 'below') {
        gradient = context.createLinearGradient(0, 0, 0, settings.caretSize);
        gradient.addColorStop(1, settings.caretColor1);
        gradient.addColorStop(0, settings.caretColor2);
      } else if ( settings.tipYPosition == 'above' ){
        gradient = context.createLinearGradient(0, 0, 0, settings.caretSize);
        gradient.addColorStop(0, settings.caretColor1);
        gradient.addColorStop(1, settings.caretColor2);
      } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'right' ||
        settings.tipYPosition == 'inline' && settings.tipXPosition == 'center' ) {
        gradient = context.createLinearGradient(0, 0, settings.caretSize, 0);
        gradient.addColorStop(0, settings.caretColor2);
        gradient.addColorStop(1, settings.caretColor1);
      } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'left' ) {
        gradient = context.createLinearGradient(0, 0, settings.caretSize, 0);
        gradient.addColorStop(0, settings.caretColor1);
        gradient.addColorStop(1, settings.caretColor2);
      }

      if (context) {
        context.fillStyle = gradient;
        context.beginPath();
        if ( settings.tipYPosition == 'below') {
          context.moveTo(centerPoint, 0);
          context.lineTo(outerEdge, settings.caretSize);
          context.lineTo(0, settings.caretSize);
          context.lineTo(centerPoint, 0);
        } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'right' ||
          settings.tipYPosition == 'inline' && settings.tipXPosition == 'center') {
          context.moveTo(0, centerPoint);
          context.lineTo(settings.caretSize, outerEdge);
          context.lineTo(settings.caretSize, 0);
          context.lineTo(0, centerPoint);
        } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'left') {
          context.moveTo(settings.caretSize, centerPoint);
          context.lineTo(0, outerEdge);
          context.lineTo(0, 0);
          context.lineTo(settings.caretSize, centerPoint);
        } else {
          context.moveTo(centerPoint, settings.caretSize);
          context.lineTo(0, 0);
          context.lineTo(outerEdge, 0);
          context.lineTo(centerPoint, settings.caretSize);
        }
        context.fill();
        return context.closePath();
      }
    }
  }
})(jQuery);<commit_msg>Defaults back to center above.<commit_after>(function($) {
  var settings;

  $.fn.gratuitate = function(callerSettings) {
    settings = $.extend({
      caretColor: '#333, #111',
      contentAttr: 'title',
      tipYPosition: 'above',
      tipXPosition: 'center',
      tipOffset: 0,
      caretSize: '8'
    }, callerSettings || {});
    if (settings.caretColor.indexOf(",") != -1 ) {
      settings.caretColor1 = settings.caretColor.split(',')[0].trim();
      settings.caretColor2 = settings.caretColor.split(',')[1].trim();
    } else {
      settings.caretColor1 = settings.caretColor;
      settings.caretColor2 = settings.caretColor;
    }
    settings.caretSize = parseFloat(settings.caretSize);
    settings.tipOffset = parseFloat(settings.tipOffset);

    return this.each(function() {
      $(this).hover(
        function() {
          if ($(this).attr(settings.contentAttr) != undefined &&
            $(this).attr(settings.contentAttr) != null
            && $(this).attr(settings.contentAttr) != '' ) {
            var link;
            link = $(this);
            link.attr('data-gratuitator-title', link.attr('title'))
            link.attr('title','');
            popUp(link);
            return drawTriangle(link);
            $('a.null').live('click', function() {
              return false
            });
          }
        }, function() {
          $(this).attr('title', $(this).attr('data-gratuitator-title'));
          $('.gratuitator-tip').remove();
        });
      });
    }

  var popUp = function(link) {
    var content, height, width, xOffset, xPos, yOffset, yPos, gTip;
    if (settings.contentAttr == 'title') {
      content = link.attr('data-gratuitator-title')
    } else {
      content = link.attr(settings.contentAttr);
    }
    $('body').append("" + (content) +
      "<canvas id='gratuitator-caret' height='" + settings.caretSize +"' width='" + settings.caretSize + "'></canvas>");
    var gTip = $('.gratuitator-tip');
    width = link.outerWidth();
    xOffset = link.offset().left;
    yOffset = link.offset().top;

    if ( settings.tipXPosition == 'left' &&  settings.tipYPosition == 'above' ||
      settings.tipXPosition == 'left' && settings.tipYPosition == 'below') {
      xPos = xOffset;                                   // left
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'above' ||
      settings.tipXPosition == 'right' && settings.tipYPosition == 'below') {
      xPos = (xOffset + link.outerWidth()) - (settings.caretSize + 10);
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'inline' ) {
      xPos = xOffset + link.outerWidth() + settings.caretSize + settings.tipOffset
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'inline' ) {
      xPos =  xOffset - gTip.outerWidth() - settings.tipOffset
    } else if (settings.tipXPosition == 'center' && settings.tipYPosition == 'inline') {
      xPos = xOffset + link.outerWidth() + settings.caretSize + settings.tipOffset
    } else {
      xPos = (xOffset + (link.outerWidth()/2)) - (gTip.outerWidth()/2.25);
    }

    $('.gratuitator-tip').css({
      'left': xPos
    });

    if ( settings.tipYPosition == 'below' ) {
      yPos = yOffset + settings.tipOffset + settings.caretSize + link.outerHeight();
    } else if ( settings.tipYPosition == 'inline' ) {
      yPos = yOffset + (link.outerHeight()/2 - gTip.height());
    } else {
      height = gTip.outerHeight() + settings.caretSize + settings.tipOffset;
      yPos = link.offset().top - (gTip.outerHeight() + settings.caretSize + settings.tipOffset)
    }

    $('.gratuitator-tip').css({
      'top': yPos
    });

  };
  var drawTriangle = function(link) {
    var context, gradient, caret, leftPos, yPos, link, outerEdge, centerPoint, pointOffset;
    caret = document.getElementById('gratuitator-caret');
    outerEdge = settings.caretSize * 1.5;
    centerPoint = outerEdge / 2;
    pointOffset = 4;
    if ( settings.tipYPosition == 'below' ) {
      yPos = -(settings.caretSize)
    } else {
      yPos = "100%"
    }

    if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'above' ) {
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'below' ) {
      yPos = -($(caret).outerHeight());
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'center' && settings.tipYPosition == 'above' ) {
      yPos = "100%";
      leftPos = $('.gratuitator-tip').outerWidth()/2 - ((settings.caretSize * 1.25));
    } else if ( settings.tipXPosition == 'center' && settings.tipYPosition == 'below' ) {
      yPos = -(settings.caretSize);
      leftPos = $('.gratuitator-tip').outerWidth()/2 - ((settings.caretSize * 1.25));
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'above' ) {
      yPos = "100%";
      leftPos = pointOffset;
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'below' ) {
      leftPos = pointOffset;
      yPos = -($(caret).outerHeight())
    } else if ( settings.tipXPosition == 'right' && settings.tipYPosition == 'inline' ) {
      leftPos = -(settings.caretSize);
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    } else if ( settings.tipXPosition == 'left' && settings.tipYPosition == 'inline') {
      leftPos = "100%";
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    } else {
      leftPos = -(settings.caretSize);
      yPos = $('.gratuitator-tip').outerHeight()/2 - (centerPoint);
    }
    $(caret).css({
      'position': 'absolute',
      'z-index': 100,
      'top': yPos,
      'left': leftPos,
    }).attr('height', outerEdge).attr('width', outerEdge*2);
    if (caret && caret.getContext) {
      context = caret.getContext('2d');

      if ( settings.tipYPosition == 'below') {
        gradient = context.createLinearGradient(0, 0, 0, settings.caretSize);
        gradient.addColorStop(1, settings.caretColor1);
        gradient.addColorStop(0, settings.caretColor2);
      } else if ( settings.tipYPosition == 'above' ){
        gradient = context.createLinearGradient(0, 0, 0, settings.caretSize);
        gradient.addColorStop(0, settings.caretColor1);
        gradient.addColorStop(1, settings.caretColor2);
      } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'right' ||
        settings.tipYPosition == 'inline' && settings.tipXPosition == 'center' ) {
        gradient = context.createLinearGradient(0, 0, settings.caretSize, 0);
        gradient.addColorStop(0, settings.caretColor2);
        gradient.addColorStop(1, settings.caretColor1);
      } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'left' ) {
        gradient = context.createLinearGradient(0, 0, settings.caretSize, 0);
        gradient.addColorStop(0, settings.caretColor1);
        gradient.addColorStop(1, settings.caretColor2);
      }

      if (context) {
        context.fillStyle = gradient;
        context.beginPath();
        if ( settings.tipYPosition == 'below') {
          context.moveTo(centerPoint, 0);
          context.lineTo(outerEdge, settings.caretSize);
          context.lineTo(0, settings.caretSize);
          context.lineTo(centerPoint, 0);
        } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'right' ||
          settings.tipYPosition == 'inline' && settings.tipXPosition == 'center') {
          context.moveTo(0, centerPoint);
          context.lineTo(settings.caretSize, outerEdge);
          context.lineTo(settings.caretSize, 0);
          context.lineTo(0, centerPoint);
        } else if ( settings.tipYPosition == 'inline' && settings.tipXPosition == 'left') {
          context.moveTo(settings.caretSize, centerPoint);
          context.lineTo(0, outerEdge);
          context.lineTo(0, 0);
          context.lineTo(settings.caretSize, centerPoint);
        } else {
          context.moveTo(centerPoint, settings.caretSize);
          context.lineTo(0, 0);
          context.lineTo(outerEdge, 0);
          context.lineTo(centerPoint, settings.caretSize);
        }
        context.fill();
        return context.closePath();
      }
    }
  }
})(jQuery);<|endoftext|>