<commit_before>#!/usr/bin/env node
/**
 * Created by apizzimenti on 1/1/17.
 */

var r = require("request"),
    tools = require("../tools"),

    Error = tools.Error;

function ip (callback) {

    var msg = "Either your computer is not connected to the internet properly or the service couldn't" +
        " find your external ip address.",
        e = new Error(msg);

    r("http://api.ipify.org", function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        callback(body);
    })
}

function location (ip, callback) {

    var msg = "Either your computer isn't connected to the internet properly or the service couldn't" +
        " find your location.",
        e = new Error(msg),
        loc = {};

    r("http://freegeoip.net/json/" + ip, function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        loc = new tools.location(JSON.parse(body));
        callback(loc, callback);
    });
}

module.exports = {
    ip: ip,
    location: location
};
<commit_msg>separate current and daily weather<commit_after>#!/usr/bin/env node

/**
 * Created by apizzimenti on 1/1/17.
 */

var r = require("request"),
    tools = require("../tools"),
    p = require("../../private.json"),

    Error = tools.Error,
    Location = tools.location,
    Weather = tools.weather;

/**
 * @author Anthony Pizzimenti
 *
 * @param callback
 */

function ip (callback) {

    var msg = "Either your computer is not connected to the internet properly or the service couldn't" +
        " find your external ip address.",
        e = new Error(msg);

    r("http://api.ipify.org", function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        callback(body, current);
    });
}

function location (ip, callback) {

    var msg = "The location service couldn't find where you are by your public ip.",
        e = new Error(msg),
        loc = {};

    r("http://freegeoip.net/json/" + ip, function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        loc = new Location(JSON.parse(body));
        callback(loc, daily);
    });
}

function current (location, callback) {

    var lat = location.latitude,
        long = location.longitude,
        key = p.forecast_secret,
        cur = "https://api.darksky.net/forecast/" + key + "/" + lat + "," + long + "?exclude=minutely,hourly,daily,flags",

        msg = "The service couldn't retrieve the current weather for your location.",
        e = new Error(msg),

        w = {};

    r(cur, function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        w = new Weather(JSON.parse(body));
        callback(location);
    });
}

function daily (location, callback) {

    var lat = location.latitude,
        long = location.longitude,
        key = p.forecast_secret,
        day = "https://api.darksky.net/forecast/" + key + "/" + lat + "," + long + "?exclude=currently,minutely,hourly,flags",

        msg = "The service couldn't retrieve the daily weather for your location.",
        e = new Error(msg),

        w = {};

    r(day, function (err, res, body) {

        if (err) {
            e.throw();
            return;
        }

        w = new Weather(JSON.parse(body));
        console.log(w.daily.data.slice(0, 5));
    });
}

module.exports = {
    ip: ip,
    location: location
};
<|endoftext|>


<commit_before>(function($) {

	var settings = {
		"penColor": "black",
		"penWidth": 3.0,
		"clearCaption": "Clear",
		"okCaption": "OK",
		"cancelCaption": "Cancel",
		"drawPrompt": "Sign here using your mouse or touchscreen",
		"backColor" : "white",
		"borderColor": "gray"
	};

	var state = {
		x : 0,
		y : 0,
		drawing : false,
		startTime : 0
	};

	var internal = {
		getPanelHtml : function ($parentDiv){
			var r = [];

			r.push("<canvas height=\"" + ($parentDiv.height() - 40) + "px\" width=\"" + ($parentDiv.width() + 0.0) + "px\"></canvas>");
			r.push("
");
			r.push("Clear");
			r.push("
");
			return r.join("\n");
		},
		clearCanvas : function ($canvas, context) {
			var canvas = $canvas[0];

			context.save();
			context.closePath();
			context.clearRect(0, 0, canvas.width, canvas.height);
			context.restore();

		}
	};

	var methods = {
		init : function(options) {

			return this.each(function() {
				var $this, data, $canvas, context;

				$this = $(this);

				// Attach data storage to this object
				if (! $this.data("signaturePanel")) {
					$this.data("signaturePanel", {
						clickstream : []
					});
				}
				data = $this.data("signaturePanel");

				// Apply user-supplied options
				if (options) {
					$.extend(settings, options);
				}

				// Create user interface elements
				$this.empty();
				$this.append(internal.getPanelHtml($this));

				$canvas = $this.find("canvas");
				context = $canvas[0].getContext('2d');

				context.lineWidth = settings.penWidth;
				context.strokeStyle = settings.penColor;
				context.fillStyle = "none";

				// Attach event handlers

				$this.find("a.signature-panel-clear").bind("click.signaturePanel", function () {
					internal.clearCanvas($canvas, context);
				});

				$canvas.bind("mousedown.signaturePanel touchstart.signaturePanel", function (event) {
					console.log("mousedown");
					var x, y, t;

					t= (new Date).getTime - state.startTime;

					event.preventDefault();

					if (event.originalEvent.touches) {
						console.log("have touches");
						x = event.originalEvent.touches.item(0).pageX - $canvas[0].offsetLeft;
						y = event.originalEvent.touches.item(0).pageY - $canvas[0].offsetTop;
					} else {
						console.log("no touches");
						x = event.pageX - $canvas[0].offsetLeft;
						y = event.pageY - $canvas[0].offsetTop;
					}
					state.startTime = t;
					state.x = x;
					state.y = y;
					state.drawing = true;
					context.beginPath();
					context.moveTo(x, y);
					data.clickstream.push({x: state.x, y: state.y, t: 0, action: "mousedown"});
				});

				$(document).bind("mousemove.signaturePanel touchmove.signaturePanel", function (event) {
					var x, y, t;
					console.log("touchmove")

					t= (new Date).getTime - state.startTime;

					if (state.drawing) {
						event.preventDefault();
						if (event.originalEvent.touches) {
							console.log("have touches");
							x = event.originalEvent.touches.item(0).pageX - $canvas[0].offsetLeft;
							y = event.originalEvent.touches.item(0).pageY - $canvas[0].offsetTop;
						} else {
							console.log("no touches");
							x = event.pageX - $canvas[0].offsetLeft;
							y = event.pageY - $canvas[0].offsetTop;
						}
						context.lineTo(x, y);
						context.stroke();
						state.x = x;
						state.y = y;
						data.clickstream.push({x: state.x, y: state.y, t: t, action: "mousemove"});
					}
				});

				$(document).bind("mouseup.signaturePanel touchend.signaturePanel touchcancel.signaturePanel", function (event) {
					if (state.drawing) {
						event.preventDefault();
						context.closePath();
						state.drawing = false;
					}
				});

			});
		},

		destroy : function() {

			return this.each(function() {
				var $this, data, $canvas;

				$this = $(this);
				data = $this.data("signaturePanel");
				$canvas = $this.find("canvas");

				$canvas.unbind(".signaturePanel");
				$(document).unbind(".signaturePanel");

				data.signaturePanel.remove();
				$this.removeData("signaturePanel");
			})
		},

		clear : function() {
			return this.each(function() {
				var $canvas, context;

				$canvas = $this.find("canvas");
				context = $canvas[0].getContext('2d');

				internal.clearCanvas($canvas, context);

			})
		}

	};

	$.fn.signaturePanel = function(method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === "object" || ! method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error("Method " + method + " does not exist on jQuery.signaturePanel");
		}

	};

})(jQuery);
<commit_msg>Removed duplicate code for touch event handling<commit_after>(function($) {

	var settings = {
		"penColor": "black",
		"penWidth": 3.0,
		"clearCaption": "Clear",
		"okCaption": "OK",
		"cancelCaption": "Cancel",
		"drawPrompt": "Sign here using your mouse or touchscreen",
		"backColor" : "white",
		"borderColor": "gray"
	};

	var state = {
		x : 0,
		y : 0,
		drawing : false,
		startTime : 0
	};

	var internal = {
		getPanelHtml : function ($parentDiv){
			var r = [];

			r.push("<canvas height=\"" + ($parentDiv.height() - 40) + "px\" width=\"" + ($parentDiv.width() + 0.0) + "px\"></canvas>");
			r.push("
");
			r.push("Clear");
			r.push("
");
			return r.join("\n");
		},
		clearCanvas : function ($canvas, context) {
			var canvas = $canvas[0];

			context.save();
			context.closePath();
			context.clearRect(0, 0, canvas.width, canvas.height);
			context.restore();

		},
		processEventLocation : function(event, canvas) {
			var x, y;

			if (event.originalEvent.touches) {
				x = event.originalEvent.touches[0].pageX - canvas.offsetLeft;
				y = event.originalEvent.touches[0].pageY - canvas.offsetTop;
			} else {
				x = event.pageX - canvas.offsetLeft;
				y = event.pageY - canvas.offsetTop;
			}

			return {x: x, y: y};
		}
	};

	var methods = {
		init : function(options) {

			return this.each(function() {
				var $this, data, $canvas, context;

				$this = $(this);

				// Attach data storage to this object
				if (! $this.data("signaturePanel")) {
					$this.data("signaturePanel", {
						clickstream : []
					});
				}
				data = $this.data("signaturePanel");

				// Apply user-supplied options
				if (options) {
					$.extend(settings, options);
				}

				// Create user interface elements
				$this.empty();
				$this.append(internal.getPanelHtml($this));

				$canvas = $this.find("canvas");
				context = $canvas[0].getContext('2d');

				context.lineWidth = settings.penWidth;
				context.strokeStyle = settings.penColor;
				context.fillStyle = "none";

				// Attach event handlers

				$this.find("a.signature-panel-clear").bind("click.signaturePanel", function () {
					internal.clearCanvas($canvas, context);
				});

				$canvas.bind("mousedown.signaturePanel touchstart.signaturePanel", function (event) {
					var location, t;

					t= (new Date).getTime - state.startTime;
					event.preventDefault();
					location = internal.processEventLocation(event, $canvas[0]);
					state.startTime = t;
					state.x = location.x;
					state.y = location.y;
					state.drawing = true;
					context.beginPath();
					context.moveTo(location.x, location.y);
					data.clickstream.push({x: state.x, y: state.y, t: 0, action: "mousedown"});
				});

				$(document).bind("mousemove.signaturePanel touchmove.signaturePanel", function (event) {
					var location, t;

					t= (new Date).getTime - state.startTime;
					if (state.drawing) {
						event.preventDefault();
						location = internal.processEventLocation(event, $canvas[0]);
						context.lineTo(location.x, location.y);
						context.stroke();
						state.x = location.x;
						state.y = location.y;
						data.clickstream.push({x: state.x, y: state.y, t: t, action: "mousemove"});
					}
				});

				$(document).bind("mouseup.signaturePanel touchend.signaturePanel touchcancel.signaturePanel", function (event) {
					if (state.drawing) {
						event.preventDefault();
						context.closePath();
						state.drawing = false;
					}
				});

			});
		},

		destroy : function() {

			return this.each(function() {
				var $this, data, $canvas;

				$this = $(this);
				data = $this.data("signaturePanel");
				$canvas = $this.find("canvas");

				$canvas.unbind(".signaturePanel");
				$(document).unbind(".signaturePanel");

				data.signaturePanel.remove();
				$this.removeData("signaturePanel");
			})
		},

		clear : function() {
			return this.each(function() {
				var $canvas, context;

				$canvas = $this.find("canvas");
				context = $canvas[0].getContext('2d');

				internal.clearCanvas($canvas, context);

			})
		}

	};

	$.fn.signaturePanel = function(method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === "object" || ! method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error("Method " + method + " does not exist on jQuery.signaturePanel");
		}

	};

})(jQuery);
<|endoftext|>


<commit_before>//progressive enhancement (jQuery)

// $(function() {
jQuery(window).load(function() {

    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    } else {
        $('body').append('');
        jsEnhance();
    }

    function jsEnhance() {
        $('.js-enhance--show').show();
        $('.js-enhance--hide').hide();
        $('.nojs-hidden').removeClass('nojs-hidden');

        //The order of these functions being called is important...
        jsEnhanceULNavToSelectNav();
        jsEnhanceHome();
        jsEnhanceLinechart();
        jsEnhancePrint();
        jsEnhanceNumberSeparator();
        jsEnhanceMarkdownCharts();
        jsEnhanceMarkdownTables();
        jsEnhancePrintCompendium();
        jsEnhanceBoxHeight();
        jsEnhanceBoxHeightResize();
        jsEnhanceDownloadAnalytics();

        // prototypeModalButtons();

        setTimeout(function() {
            jsEnhanceIframedTables();
            jsEnhanceMobileTables();
        }, 400);

        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    }

    function jsEnhanceULNavToSelectNav() {
        $('.js-enhance--ul-to-select').each(function() {
            var labeltext = $('p:first', this).text();
            var selectoptions = $('ul:first li a', this);

            //IE9 dosent like this...
            // var label = $('', {
            //     class: 'definition-emphasis',
            //     text: labeltext
            // });
            var label = $(document.createElement('label'));
            label.attr('class', 'definition-emphasis');
            label.attr('text', labeltext);

            //$(document.createElement('select')) is faster
            // var newselect = $('<select>', {
            //     class: 'field field--spaced'
            // });
            var newselect = $(document.createElement('select'));
            newselect.attr('class', 'field field--spaced');

            newselect.append($('<option>', {
                value: '',
                text: 'Select a related time series'
            }));

            newselect.change(function() {
                var location = $(this).find('option:selected').val();
                if (location) {
                    window.location = location;
                }
            });

            $.each(selectoptions, function(i, item) {
                newselect.append($('<option>', {
                    value: $(this).attr('href'),
                    text: $(this).text()
                }));
            });

            label.append(newselect);

            $(this).html(label);

        });
    }

    function jsEnhanceHome() {

        var herostatarea = $('.stat__wrap--home');

        $(herostatarea).click(function() {
            var herostatarealink = $('a:last', this).attr('href');

            window.location = herostatarealink;
        });

        $(herostatarea).css({
            'cursor': 'pointer'
        });

        $(herostatarea).hover(function() {
            $(this).css({
                'background-color': '#f8fadc'
            })
        }, function() {
            $(this).css({
                'background-color': 'transparent'
            });
        });

    }

    function jsEnhanceLinechart() {

        var chartContainer = $("[data-chart]");
        if (!chartContainer.length) {
            return;
        }

        var location = stripTrailingSlash(window.location.pathname) + "/data";
        // console.debug("Downloading timseries data from " + location)

        $.getJSON(location, function(timeseries) {
            // console.log("Successfuly read timseries data");
            linechart = linechart(timeseries); //Global variable

        }).fail(function(d, textStatus, error) {
            // console.error("Failed reading timseries, status: " + textStatus + ", error: " + error)
        });
    }

    function stripTrailingSlash(str) {
        if(str.substr(-1) === '/') {
            return str.substr(0, str.length - 1);
        }
        return str;
    }

    function jsEnhanceMarkdownCharts() {

        var chartContainer = $(".markdown-chart-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/chart", {});
        });
    }

    function jsEnhancePrint() {
    $('#jsEnhancePrint').click(function()
        {
            window.print();
            return false;
        });
    }

    function jsEnhanceNumberSeparator() {
      // Adapted from http://stackoverflow.com/questions/14075014/jquery-function-to-to-format-number-with-commas-and-decimal
      $( ".stat__figure-enhance" ).each(function( index ) {
        //console.log( index + ": " + $( this ).text() );
        var number = $( this ).text();
        var n= number.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        // //Combines the two sections
        $( this ).text(n.join("."));
      });
    }

    function jsEnhanceMarkdownTables() {

        var chartContainer = $(".markdown-table-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/table", {});
        });
    }

    function jsEnhancePrintCompendium() {
        $('#jsEnhancePrintCompendium').click(function(e) {
            addLoadingOverlay();

            // TODO Will get function to add in div, so no empty divs on page at load
            //$("

").insertAfter('.desktop-grid-full-width');

            // TODO Remove existing page content from print
            // $(".wrapper").remove();

            $('.chapter').each(function() {
                var url = $(this).attr('href');

                var getContent = ('main');

                $('
').load(url, function() {
                    $('.print-content').append("
" + $(this).find(getContent).html() + "
");
                });

                e.preventDefault();
            });

            $(document).ajaxStop(function() {
                window.print();
                location.reload();
            });
        });
    }

    function jsEnhanceBoxHeight() {
        if ($(window).width() > 608) {
            var highestBox = 0;
            $('.equal-height').each(function(){

                if($(this).height() > highestBox) {
                   highestBox = $(this).height();
               }
            });

            $('.equal-height').height(highestBox);
        }
    }

    function jsEnhanceBoxHeightResize() {
        $( window ).resize(function() {
            $('.equal-height').height('auto');
            jsEnhanceBoxHeight();
        });
    }

    function jsEnhanceIframedTables() {
        $('iframe').each(function(i) {
            // markdown-table-container
            if($(this).contents().find('div').hasClass('markdown-table-container')) {
                // console.log('iframe with table found');
                $(this).contents().find('iframe').remove();
                $(this).contents().find('script').remove();
                $(this).contents().find('*').css('width','auto');
                $(this).contents().find('*').css('height','auto');

                // var iframedtable =  $(this).contents().find('table');

                var iframecontent = $(this).contents().find('body').html();

                // $('
' + iframecontent + '
').insertAfter($(this));
                $(iframecontent).insertAfter($(this));
                $(this).remove();
             }
        });
    }

    function jsEnhanceMobileTables() {
        //
        // $('markdown-table-container').addClass('table-holder-mobile');

        $('<button class="invisible btn btn--mobile-table-show">View table</button>').insertAfter($('.markdown-table-wrap'));
        $('<button class="invisible btn btn--mobile-table-hide">Close table</button>').insertAfter($('.markdown-table-wrap table'));

        $('.btn--mobile-table-show').click(function(e) {
            // console.log($(this).closest('.markdown-table-container').find('.markdown-table-wrap'));
            $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show();
        });

        $('.btn--mobile-table-hide').click(function(e) {
            // console.log($(this).closest('.markdown-table-container').find('.markdown-table-wrap'));
            $(this).closest('.markdown-table-wrap').hide();
        });
    }

    /*Track file downloads*/
    function jsEnhanceDownloadAnalytics() {
        $('.download-analytics').click(function(){
            var downloadType = $(this).parent().attr('action');
            var path = $('#pagePath').text();
            var downloadTitle = $('#title').text();
            var downloadFormat = $(this).attr('value');

            if(downloadType == '/file') {
                var downloadType = '/download';
                var downloadFormat = 'xls';
            }

            if(downloadType == '/chartimage') {
                downloadFormat = 'png';
            }

            ga('send', 'pageview', {
                'page': path + downloadType,
                'hitCallback': function() {
                    if(console && console.log) {
                        console.log('Analytics event triggered for ' + downloadType + ('?uri=') + path + ('/') + downloadTitle + '.' + downloadFormat);
                    }
                }
            });
        });
    }

    function prototypeModalButtons() {
        // $('.btn-modal-continue').click(function(e){
            alert('hello');
            e.preventDefault();
            var d = new Date();
            d.setTime(d.getTime() + (1*24*60*60*1000));
            var expires = "expires="+d.toUTCString();
            // document.cookie='onsBetaDisclaimer=true; ' + expires;
            $('#modal-overlay').fadeOut(300);
        // });
    }

    //

});<commit_msg>disabling iframe and table enhancements<commit_after>//progressive enhancement (jQuery)

// $(function() {
jQuery(window).load(function() {

    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    } else {
        $('body').append('');
        jsEnhance();
    }

    function jsEnhance() {
        $('.js-enhance--show').show();
        $('.js-enhance--hide').hide();
        $('.nojs-hidden').removeClass('nojs-hidden');

        //The order of these functions being called is important...
        jsEnhanceULNavToSelectNav();
        jsEnhanceHome();
        jsEnhanceLinechart();
        jsEnhancePrint();
        jsEnhanceNumberSeparator();
        jsEnhanceMarkdownCharts();
        jsEnhanceMarkdownTables();
        jsEnhancePrintCompendium();
        jsEnhanceBoxHeight();
        jsEnhanceBoxHeightResize();
        jsEnhanceDownloadAnalytics();

        // jsEnhanceMobileTables();

        // prototypeModalButtons();

        // setTimeout(function() {
        //     jsEnhanceIframedTables();
        //     jsEnhanceMobileTables();
        // }, 400);

        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    }

    function jsEnhanceULNavToSelectNav() {
        $('.js-enhance--ul-to-select').each(function() {
            var labeltext = $('p:first', this).text();
            var selectoptions = $('ul:first li a', this);

            //IE9 dosent like this...
            // var label = $('', {
            //     class: 'definition-emphasis',
            //     text: labeltext
            // });
            var label = $(document.createElement('label'));
            label.attr('class', 'definition-emphasis');
            label.attr('text', labeltext);

            //$(document.createElement('select')) is faster
            // var newselect = $('<select>', {
            //     class: 'field field--spaced'
            // });
            var newselect = $(document.createElement('select'));
            newselect.attr('class', 'field field--spaced');

            newselect.append($('<option>', {
                value: '',
                text: 'Select a related time series'
            }));

            newselect.change(function() {
                var location = $(this).find('option:selected').val();
                if (location) {
                    window.location = location;
                }
            });

            $.each(selectoptions, function(i, item) {
                newselect.append($('<option>', {
                    value: $(this).attr('href'),
                    text: $(this).text()
                }));
            });

            label.append(newselect);

            $(this).html(label);

        });
    }

    function jsEnhanceHome() {

        var herostatarea = $('.stat__wrap--home');

        $(herostatarea).click(function() {
            var herostatarealink = $('a:last', this).attr('href');

            window.location = herostatarealink;
        });

        $(herostatarea).css({
            'cursor': 'pointer'
        });

        $(herostatarea).hover(function() {
            $(this).css({
                'background-color': '#f8fadc'
            })
        }, function() {
            $(this).css({
                'background-color': 'transparent'
            });
        });

    }

    function jsEnhanceLinechart() {

        var chartContainer = $("[data-chart]");
        if (!chartContainer.length) {
            return;
        }

        var location = stripTrailingSlash(window.location.pathname) + "/data";
        // console.debug("Downloading timseries data from " + location)

        $.getJSON(location, function(timeseries) {
            // console.log("Successfuly read timseries data");
            linechart = linechart(timeseries); //Global variable

        }).fail(function(d, textStatus, error) {
            // console.error("Failed reading timseries, status: " + textStatus + ", error: " + error)
        });
    }

    function stripTrailingSlash(str) {
        if(str.substr(-1) === '/') {
            return str.substr(0, str.length - 1);
        }
        return str;
    }

    function jsEnhanceMarkdownCharts() {

        var chartContainer = $(".markdown-chart-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/chart", {});
        });
    }

    function jsEnhancePrint() {
    $('#jsEnhancePrint').click(function()
        {
            window.print();
            return false;
        });
    }

    function jsEnhanceNumberSeparator() {
      // Adapted from http://stackoverflow.com/questions/14075014/jquery-function-to-to-format-number-with-commas-and-decimal
      $( ".stat__figure-enhance" ).each(function( index ) {
        //console.log( index + ": " + $( this ).text() );
        var number = $( this ).text();
        var n= number.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        // //Combines the two sections
        $( this ).text(n.join("."));
      });
    }

    function jsEnhanceMarkdownTables() {

        var chartContainer = $(".markdown-table-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/table", {});
        });
    }

    function jsEnhancePrintCompendium() {
        $('#jsEnhancePrintCompendium').click(function(e) {
            addLoadingOverlay();

            // TODO Will get function to add in div, so no empty divs on page at load
            //$("

").insertAfter('.desktop-grid-full-width');

            // TODO Remove existing page content from print
            // $(".wrapper").remove();

            $('.chapter').each(function() {
                var url = $(this).attr('href');

                var getContent = ('main');

                $('
').load(url, function() {
                    $('.print-content').append("
" + $(this).find(getContent).html() + "
");
                });

                e.preventDefault();
            });

            $(document).ajaxStop(function() {
                window.print();
                location.reload();
            });
        });
    }

    function jsEnhanceBoxHeight() {
        if ($(window).width() > 608) {
            var highestBox = 0;
            $('.equal-height').each(function(){

                if($(this).height() > highestBox) {
                   highestBox = $(this).height();
               }
            });

            $('.equal-height').height(highestBox);
        }
    }

    function jsEnhanceBoxHeightResize() {
        $( window ).resize(function() {
            $('.equal-height').height('auto');
            jsEnhanceBoxHeight();
        });
    }

    function jsEnhanceIframedTables() {
        $('iframe').each(function(i) {
            // markdown-table-container
            if($(this).contents().find('div').hasClass('markdown-table-container')) {
                // console.log('iframe with table found');
                $(this).contents().find('iframe').remove();
                $(this).contents().find('script').remove();
                $(this).contents().find('*').css('width','auto');
                $(this).contents().find('*').css('height','auto');

                // var iframedtable =  $(this).contents().find('table');

                var iframecontent = $(this).contents().find('body').html();

                // $('
' + iframecontent + '
').insertAfter($(this));
                $(iframecontent).insertAfter($(this));
                $(this).remove();
             }
        });
    }

    function jsEnhanceMobileTables() {
        //
        // $('markdown-table-container').addClass('table-holder-mobile');

        $('<button class="invisible btn btn--mobile-table-show">View table</button>').insertAfter($('.markdown-table-wrap'));
        $('<button class="invisible btn btn--mobile-table-hide">Close table</button>').insertAfter($('.markdown-table-wrap table'));

        $('.btn--mobile-table-show').click(function(e) {
            // console.log($(this).closest('.markdown-table-container').find('.markdown-table-wrap'));
            $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show();
        });

        $('.btn--mobile-table-hide').click(function(e) {
            // console.log($(this).closest('.markdown-table-container').find('.markdown-table-wrap'));
            $(this).closest('.markdown-table-wrap').hide();
        });
    }

    /*Track file downloads*/
    function jsEnhanceDownloadAnalytics() {
        $('.download-analytics').click(function(){
            var downloadType = $(this).parent().attr('action');
            var path = $('#pagePath').text();
            var downloadTitle = $('#title').text();
            var downloadFormat = $(this).attr('value');

            if(downloadType == '/file') {
                var downloadType = '/download';
                var downloadFormat = 'xls';
            }

            if(downloadType == '/chartimage') {
                downloadFormat = 'png';
            }

            ga('send', 'pageview', {
                'page': path + downloadType,
                'hitCallback': function() {
                    if(console && console.log) {
                        console.log('Analytics event triggered for ' + downloadType + ('?uri=') + path + ('/') + downloadTitle + '.' + downloadFormat);
                    }
                }
            });
        });
    }

    function prototypeModalButtons() {
        // $('.btn-modal-continue').click(function(e){
            alert('hello');
            e.preventDefault();
            var d = new Date();
            d.setTime(d.getTime() + (1*24*60*60*1000));
            var expires = "expires="+d.toUTCString();
            // document.cookie='onsBetaDisclaimer=true; ' + expires;
            $('#modal-overlay').fadeOut(300);
        // });
    }

    //

});<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { render } from 'react-dom'
import store from './lib/standup-store'
import PledgeTally from './components/pledge-tally'

/*
 * Available store methods

  store.get.for(district) ->
    returns a promise that resolves with an array of videos
    at the moment, it will not resolve if the district is invalid
    TODO: error on bad district

  store.get.recent() ->
    returns a promise that resolves with an array of videos sorted by recency

  store.create(data)
    returns a promise that resolves with the created video

 */

class Standup extends Component {
  state = {
    videos: []
  }

  componentDidMount() {
    store.videos
      .recent()
      .then(videos => this.setState({ videos }))
      .catch(console.error)
  }

  render() {
    const { videos } = this.state

    return (

        Hello, world!
        {videos.map(({ district, first_name, email, rep, link }) =>

            {`${first_name} in ${district} wants ${rep} to support medicare for all!`}

            Watch their endorsement  here

        )}

        <PledgeTally />

    )
  }
}

const el = document.getElementById('standup-app')
render(<Standup />, el)
<commit_msg>fixed merge conflict<commit_after>import React, { Component } from 'react'
import { render } from 'react-dom'
import store from './lib/standup-store'
import PledgeTally from './components/pledge-tally'

/*
 * Available store methods

  store.get.for(district) ->
    returns a promise that resolves with an array of videos
    at the moment, it will not resolve if the district is invalid
    TODO: error on bad district

  store.get.recent() ->
    returns a promise that resolves with an array of videos sorted by recency

  store.create(data)
    returns a promise that resolves with the created video

 */

class Standup extends Component {
  styles = {}
  state = {
    videos: []
  }

  componentDidMount() {
    store.videos
      .recent()
      .then(videos => this.setState({ videos }))
      .catch(console.error)
  }

  render() {
    const { videos } = this.state
    return (

[COSMIC DATA]Video

Button for people

Logo

Button for people running

          [COSMIC DATA]Because of your pressure, 43 members of Congress decided
          to co-sponsor Conyers' house bill for Medicare for All. But as the
          health care debate rages, many of these same co-sponsors have publicly
          been advocating for half-measures like increasing subsidies for
          insurance companies or simply playing defense against Medicaid cuts.
          These congresspeople are silently backing Medicare for All just as a
          weak political move to cover their bases. We believe it's time for
          them to grow a spine and stand up for Medicare for All. We're calling
          on sitting members of Congress and anyone running for Congress to go
          on video pledging to stand up for Medicare for All in any public
          appearances and statements addressing our country's healthcare crisis.

        {videos.map(({ district, first_name, email, rep, link }) =>

            {`${first_name} in ${district} wants ${rep} to support medicare for all!`}

            Watch their endorsement  here

        )}

[COSMIC DATA - LIST OF VIDEOS]

[TWEET STREAM]

[COSMIC DATA - STATS]

          <PledgeTally />

    )
  }
}

const el = document.getElementById('standup-app')
render(<Standup />, el)
<|endoftext|>


<commit_before>/* This is a simple plugin to render action dropdown menus from html.
 * John Barlow - SugarCRM
 * add secondary popup implementation by Justin Park - SugarCRM
 *
 * The html structure it expects is as follows:
 *
 *
                                     - Menu root
 *
                                - First element in menu (visible)
 *
		            - Popout menu (should start hidden)
 *

                       - \
 *          ...                             -  Elements in popout menu
 *

                       - /
 *

 *              <input></input>  - element contains submenu
 *
     - sub-popout menu (shown when mouseover on the above element)
 *

               - \
 *                  ...                     -  Elements in sub-popout menu
 *

               - /
 *

 *

 *

 *

 *

 *
 * By adding a class of "fancymenu" to the menu root, the plugin adds an additional "ab" class to the
 * dropdown handle, allowing you to make the menu "fancy" with additional css if you would like :)
 *
 * Functions:
 *
 * 		init: initializes things (called by default)... currently no options are passed
 *
 * 		Adds item to the menu at position index
 * 		addItem: (item, index)
 * 			item - created dom element or string that represents one
 * 			index(optional) - the position you want your new menuitem. If you leave this off,
 * 				the item is appended to the end of the list.
 *      	returns: nothing
 *
 *      Finds an item in the menu (including the root node "outside" the ul structure).
 * 		findItem: (item)
 * 			item - string of the menu item you are looking for.
 * 			returns: index of element, or -1 if not found.
 */
(function ($) {
  var methods = {
    init: function (options) {

      var menuNode = this;
      if (!this.hasClass("SugarActionMenu")) {
        //tag this element as a sugarmenu
        this.addClass("SugarActionMenu");

        //Fix custom code buttons programatically to prevent metadata edits
        this.find("input[type='submit'], input[type='button']").each(function (idx, node) {
          var jNode = $(node);
          var parent = jNode.parent();
          var _subnav = menuNode.find("ul.subnav");
          var _timer_for_subnav = null;
          var disabled = $(this).prop('disabled');
          var newItem = $(document.createElement("li"));
          var newItemA = $(document.createElement("a"));
          var accesskey = jNode.attr("accesskey");
          var accesskey_el = $("");

          newItemA.html(jNode.val());
          if (!disabled) {
            newItemA.click(function (event) {
              if ($(this).hasClass("void") === false) {
                jNode.click();
              }
            });
          }
          else {
            newItemA.addClass("disabled");
          }
          newItemA.attr("id", jNode.attr("id"));
          accesskey_el.attr("id", jNode.attr("id") + "_accesskey");
          jNode.attr("id", jNode.attr("id") + "_old");

          if (accesskey !== undefined) {
            if ($('#' + accesskey_el.attr('id')).length === 0) {
              accesskey_el.attr("accesskey", accesskey).click(function () {
                jNode.click();
              }).appendTo("#content");
            }
            jNode.attr("accesskey", '');
          }

          //make sure the node we found isn't the main item of the list -- we don't want
          //to show it then.
          if (menuNode.sugarActionMenu("findItem", newItemA.html()) == -1) {
            parent.prepend(newItemA);
          }

          //make sub sliding menu
          jNode.siblings(".subnav-sub").each(function (idx, node) {
            var _menu = $(node);
            var _hide_menu = function () {
              if (_menu.hasClass("hover") === false)
                _menu.hide();
            };
            var _hide_timer = null;
            var _delay = 300;
            _menu.mouseover(function (evt) {
              if ($(this).hasClass("hover") === false)
                $(this).addClass("hover");
            }).mouseout(function (evt) {
              if ($(this).hasClass("hover"))
                $(this).removeClass("hover");
              if (_hide_timer)
                clearTimeout(_hide_timer);
              _hide_timer = setTimeout(_hide_menu, _delay);
            });

            newItemA.mouseover(function (evt) {
              $("ul.SugarActionMenu ul.subnav-sub").each(function (index, node) {
                $(node).removeClass("hover");
                $(node).hide();
              });
              var _left = parent.offset().left + parent.width() - newItemA.css("paddingRight").replace("px", "");
              var _top = parent.offset().top - _menu.css("paddingTop").replace("px", "");
              _menu.css({
                left: _left,
                top: _top
              });
              if (_menu.hasClass("hover") === false)
                _menu.addClass("hover");
              if (_subnav.hasClass("subnav-sub-handler") === false)
                _subnav.addClass("subnav-sub-handler");
              _menu.show();
            }).mouseout(function (evt) {
              _menu.removeClass("hover");
              _subnav.removeClass("subnav-sub-handler")
              if (_hide_timer)
                clearTimeout(_hide_timer);
              _hide_timer = setTimeout(_hide_menu, _delay);
            }).click(function (evt) {
              if (_timer_for_subnav)
                clearTimeout(_timer_for_subnav);
            }).addClass("void");
            menuNode.append(_menu);
          });
          jNode.css("display", "none");
        });

        //look for all subnavs and set them up
        this.find("ul.subnav").each(function (index, node) {
          var jNode = $(node);
          var parent = jNode.parent();
          var fancymenu = "";
          var slideUpSpeed = 1;
          var slideDownSpeed = 1;
          var dropDownHandle;

          //if the dropdown handle doesn't exist, lets create it and
          //add it to the dom
          if (parent.find("span").length == 0) {

            //create dropdown handle
            dropDownHandle = $(document.createElement("span"));
            dropDownHandle.addClass('suitepicon suitepicon-action-caret');
            parent.append(dropDownHandle);

          } else if (parent.find("span").length == 1) {
            dropDownHandle = $(parent.find("span"));
          } else {
            dropDownHandle = $(parent.find("span").first());
          }

          var toggleDropDown = function () {
            //close all other open menus
            //restore the dom elements back by handling iefix
            $("ul.SugarActionMenu > li").each(function () {
              $(this).sugarActionMenu('IEfix');
            });
            $("ul.SugarActionMenu ul.subnav").each(function (subIndex, node) {
              var subjNode = $(node);
              if (!(subjNode[0] === jNode[0])) {
                subjNode.slideUp(slideUpSpeed);
                subjNode.removeClass("ddopen");
              }
            });
            if (jNode.hasClass("ddopen")) {
              parent.sugarActionMenu('IEfix');
              //Bug#50983: Popup the dropdown list above the arrow if the bottom part is cut off .
              var _animation = {
                'height': 0
              };
              if (jNode.hasClass("upper")) {
                _animation['top'] = (dropDownHandle.height() * -1);
              }
              jNode.animate(_animation, slideUpSpeed, function () {
                $(this).css({
                  'height': '',
                  'top': ''
                }).hide().removeClass("upper ddopen");
              });
            }
            else {
              //To support IE fixed size rendering,
              //parse out dom elements out of the fixed element
              parent.sugarActionMenu('IEfix', jNode);
              var _dropdown_height = jNode.height(),
                _animation = {'height': _dropdown_height},
                _dropdown_bottom = dropDownHandle.offset().top + dropDownHandle.height() - $(document).scrollTop() + jNode.outerHeight(),
                _win_height = $(window).height();
              if (dropDownHandle.offset().top > jNode.height() && _dropdown_bottom > $(window).height()) {
                jNode.css('top', (dropDownHandle.height() * -1)).addClass("upper");
                _animation['top'] = (jNode.height() + dropDownHandle.height()) * -1;
              }

              jNode.height(0).show().animate(_animation, slideDownSpeed, function () {
                $(this).css('height', '');
                setTimeout(function () {
                  // $('.subnav.ddopen').each(function (i, e) {
                  //   if (!$(e).hasClass('upper')) {
                  //     $(e).css('top', parseInt($(e).css('top')) + 10 + 'px');
                  //   }
                  // })
                }, 2);
              });
              jNode.addClass("ddopen");
            }
          };

          //add click handler to handle
          dropDownHandle.click(function (event) {
            toggleDropDown();
            event.stopPropagation();
          });

          var parentDropDownHandler = parent.find('a').first().hasClass('parent-dropdown-handler');
          if (parentDropDownHandler) {
            parent.click(function (event) {
              dropDownHandle.click();
              event.stopPropagation();
            });
          }

          //add submenu click off to body
          var jBody = $("body");
          var _hide_subnav_delay = 30;
          var _hide_subnav = function (subnav) {
            if (subnav.hasClass("subnav-sub-handler") === false) {
              subnav.slideUp(slideUpSpeed);
              subnav.removeClass("ddopen");
            }
          }
          if (jBody.data("sugarActionMenu") != true) {
            jBody.data("sugarActionMenu", true);
            jBody.bind("click", function () {
              //retore the dom elements back by handling iefix
              $("ul.SugarActionMenu > li").each(function () {
                $(this).sugarActionMenu('IEfix');
              });

              $("ul.SugarActionMenu ul.subnav").each(function (subIndex, node) {
                //prevent hiding the submenu when user click the submenu which contains one more depth submenu
                var _hide = function () {
                  _hide_subnav($(node));
                }
                setTimeout(_hide, _hide_subnav_delay);
              });
              //Hide second depth submenu
              $("ul.SugarActionMenu ul.subnav-sub").each(function (subIndex, node) {
                var _hide = function () {
                  $(this).removeClass("hover");
                  $(this).hide();
                }
                _timer_for_subnav = setTimeout(_hide, _hide_subnav_delay);
              });

            });
          }

          //add hover handler to handle
          dropDownHandle.hover(function () {
            dropDownHandle.addClass("subhover");
          }, function () {
            dropDownHandle.removeClass("subhover");
          });

          //bind click event to submenu items to hide the menu on click
          jNode.find("li").each(function (index, subnode) {
            //prevent hiding the submenu when user click the submenu which contains one more depth submenu
            $(subnode).bind("click", function (evt) {
              var _hide = function () {
                _hide_subnav(jNode);
              }
              setTimeout(_hide, _hide_subnav_delay);
            });
          });

          //fix up text of  tags so they span correctly
          jNode.find("a").each(function (index, subnode) {
            $(subnode).html(function (index, oldhtml) {
              return oldhtml.replace(" ", " ");
            });
          });
        });

        //Bug#51579: delete li tags which contains empty due to access role
        this.find(".subnav > li").each(function (index, subnode) {
          if ($(subnode).html().replace(/ /g, '') == '') {
            $(subnode).remove();
          }
        });
        //Bug#51579: If the first item is empty due to the access role,
        //           replace the first button from the first of the sub-list items.
        this.find("li.sugar_action_button:first").each(function (index, node) {
          var _this = $(node);
          var _first_item = $(node).find("a:first").not($(node).find(".subnav > li a"));
          if (_first_item.length == 0) {
            var sub_items = $(node).find(".subnav > li:first").children();
            if (sub_items.length == 0)
              menuNode.hide();
            else
              _this.prepend(sub_items);
          }
        });

      }
      return this;
    },
    addItem: function (args) {
      if (args.index == null) {
        this.find("ul.subnav").each(function (index, node) {
          $(node).append(args.item);
        })
      }
      else {
        this.find("ul.subnav").find("li").each(function (index, node) {
          if (args.index == index + 1) {
            $(node).before(args.item);
          }
        });
      }
      return this;
    },
    findItem: function (item) {
      var index = -1;
      this.find("a").each(function (idx, node) {
        var jNode = $(node);
        if ($.trim(jNode.html()) == $.trim(item)) {
          index = idx;
        }
      });
      return index;
    },
    /**
     * To support IE fixed size rendering,
     * parse out dom elements out of the fixed element
     *
     * Prepare ===
     *

     *     ...
     *

     *

     *             ...
     *

     *

     *

     *
     * Application ===
     *

     *

     *     ...
     *

     *

     *
     *

     *     ...
     *

     * @param this - element container which is inside the fixed box model
     * @param $ul - dropdown box model which needs to render out of the fixed box range
     *              if $ul is not given, it will restore back to the original structure
     */
    IEfix: function ($ul) {
      if ($ul) {
        if ($ul.hasClass('iefixed') === false)
          return;
        this.each(function () {
          SUGAR.themes.counter = SUGAR.themes.counter ? SUGAR.themes.counter++ : 1;
          var $$ = $(this),
            _id = $$.attr("ul-child-id") ? $$.attr("ul-child-id") : ($$.parent('.SugarActionMenu').attr("id")) ? $$.parent('.SugarActionMenu').attr("id") + 'Subnav' : 'sugaractionmenu' + SUGAR.themes.counter,
            _top = $$.position().top + $$.outerHeight(),
            _width = 'auto', //to obtain a certain size, apply min-width in css
            _css = {
              top: _top,
              width: _width,
              position: 'fixed'
            },
            _right = $('body').width() - $$.offset().left - $$.width(),
            _left = $$.offset().left;
          //fixed positioning depends on the css property
          if ($ul.css('right') != 'auto') {
            _css['right'] = _right;
          } else {
            _css['left'] = _left;
          }
          $('body').append($ul.attr("id", _id).addClass("SugarActionMenuIESub").css(_css));
          $$.attr("ul-child-id", _id);
        });

      } else {
        this.each(function () {
          var _id = $(this).attr("ul-child-id");
          $(this).append($("body>#" + _id).removeClass("SugarActionMenuIESub"));
        });
      }
    }
  }

  $.fn.sugarActionMenu = function (method) {

    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(
        arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.tooltip');
    }
  }
})(jQuery);
<commit_msg>Make jquery selector not match opt in span<commit_after>/* This is a simple plugin to render action dropdown menus from html.
 * John Barlow - SugarCRM
 * add secondary popup implementation by Justin Park - SugarCRM
 *
 * The html structure it expects is as follows:
 *
 *
                                     - Menu root
 *
                                - First element in menu (visible)
 *
		            - Popout menu (should start hidden)
 *

                       - \
 *          ...                             -  Elements in popout menu
 *

                       - /
 *

 *              <input></input>  - element contains submenu
 *
     - sub-popout menu (shown when mouseover on the above element)
 *

               - \
 *                  ...                     -  Elements in sub-popout menu
 *

               - /
 *

 *

 *

 *

 *

 *
 * By adding a class of "fancymenu" to the menu root, the plugin adds an additional "ab" class to the
 * dropdown handle, allowing you to make the menu "fancy" with additional css if you would like :)
 *
 * Functions:
 *
 * 		init: initializes things (called by default)... currently no options are passed
 *
 * 		Adds item to the menu at position index
 * 		addItem: (item, index)
 * 			item - created dom element or string that represents one
 * 			index(optional) - the position you want your new menuitem. If you leave this off,
 * 				the item is appended to the end of the list.
 *      	returns: nothing
 *
 *      Finds an item in the menu (including the root node "outside" the ul structure).
 * 		findItem: (item)
 * 			item - string of the menu item you are looking for.
 * 			returns: index of element, or -1 if not found.
 */
(function ($) {
  var methods = {
    init: function (options) {

      var menuNode = this;
      if (!this.hasClass("SugarActionMenu")) {
        //tag this element as a sugarmenu
        this.addClass("SugarActionMenu");

        //Fix custom code buttons programatically to prevent metadata edits
        this.find("input[type='submit'], input[type='button']").each(function (idx, node) {
          var jNode = $(node);
          var parent = jNode.parent();
          var _subnav = menuNode.find("ul.subnav");
          var _timer_for_subnav = null;
          var disabled = $(this).prop('disabled');
          var newItem = $(document.createElement("li"));
          var newItemA = $(document.createElement("a"));
          var accesskey = jNode.attr("accesskey");
          var accesskey_el = $("");

          newItemA.html(jNode.val());
          if (!disabled) {
            newItemA.click(function (event) {
              if ($(this).hasClass("void") === false) {
                jNode.click();
              }
            });
          }
          else {
            newItemA.addClass("disabled");
          }
          newItemA.attr("id", jNode.attr("id"));
          accesskey_el.attr("id", jNode.attr("id") + "_accesskey");
          jNode.attr("id", jNode.attr("id") + "_old");

          if (accesskey !== undefined) {
            if ($('#' + accesskey_el.attr('id')).length === 0) {
              accesskey_el.attr("accesskey", accesskey).click(function () {
                jNode.click();
              }).appendTo("#content");
            }
            jNode.attr("accesskey", '');
          }

          //make sure the node we found isn't the main item of the list -- we don't want
          //to show it then.
          if (menuNode.sugarActionMenu("findItem", newItemA.html()) == -1) {
            parent.prepend(newItemA);
          }

          //make sub sliding menu
          jNode.siblings(".subnav-sub").each(function (idx, node) {
            var _menu = $(node);
            var _hide_menu = function () {
              if (_menu.hasClass("hover") === false)
                _menu.hide();
            };
            var _hide_timer = null;
            var _delay = 300;
            _menu.mouseover(function (evt) {
              if ($(this).hasClass("hover") === false)
                $(this).addClass("hover");
            }).mouseout(function (evt) {
              if ($(this).hasClass("hover"))
                $(this).removeClass("hover");
              if (_hide_timer)
                clearTimeout(_hide_timer);
              _hide_timer = setTimeout(_hide_menu, _delay);
            });

            newItemA.mouseover(function (evt) {
              $("ul.SugarActionMenu ul.subnav-sub").each(function (index, node) {
                $(node).removeClass("hover");
                $(node).hide();
              });
              var _left = parent.offset().left + parent.width() - newItemA.css("paddingRight").replace("px", "");
              var _top = parent.offset().top - _menu.css("paddingTop").replace("px", "");
              _menu.css({
                left: _left,
                top: _top
              });
              if (_menu.hasClass("hover") === false)
                _menu.addClass("hover");
              if (_subnav.hasClass("subnav-sub-handler") === false)
                _subnav.addClass("subnav-sub-handler");
              _menu.show();
            }).mouseout(function (evt) {
              _menu.removeClass("hover");
              _subnav.removeClass("subnav-sub-handler")
              if (_hide_timer)
                clearTimeout(_hide_timer);
              _hide_timer = setTimeout(_hide_menu, _delay);
            }).click(function (evt) {
              if (_timer_for_subnav)
                clearTimeout(_timer_for_subnav);
            }).addClass("void");
            menuNode.append(_menu);
          });
          jNode.css("display", "none");
        });

        //look for all subnavs and set them up
        this.find("ul.subnav").each(function (index, node) {
          var jNode = $(node);
          var parent = jNode.parent();
          var fancymenu = "";
          var slideUpSpeed = 1;
          var slideDownSpeed = 1;
          var dropDownHandle;

          //if the dropdown handle doesn't exist, lets create it and
          //add it to the dom
          var foundSpanCount = parent.find("span.suitepicon-action-caret").length;
          if (foundSpanCount === 0) {

            //create dropdown handle
            dropDownHandle = $(document.createElement("span"));
            dropDownHandle.addClass('suitepicon suitepicon-action-caret');
            parent.append(dropDownHandle);

          } else if (foundSpanCount === 1) {
            dropDownHandle = $(parent.find("span"));
          } else {
            dropDownHandle = $(parent.find("span").first());
          }

          var toggleDropDown = function () {
            //close all other open menus
            //restore the dom elements back by handling iefix
            $("ul.SugarActionMenu > li").each(function () {
              $(this).sugarActionMenu('IEfix');
            });
            $("ul.SugarActionMenu ul.subnav").each(function (subIndex, node) {
              var subjNode = $(node);
              if (!(subjNode[0] === jNode[0])) {
                subjNode.slideUp(slideUpSpeed);
                subjNode.removeClass("ddopen");
              }
            });
            if (jNode.hasClass("ddopen")) {
              parent.sugarActionMenu('IEfix');
              //Bug#50983: Popup the dropdown list above the arrow if the bottom part is cut off .
              var _animation = {
                'height': 0
              };
              if (jNode.hasClass("upper")) {
                _animation['top'] = (dropDownHandle.height() * -1);
              }
              jNode.animate(_animation, slideUpSpeed, function () {
                $(this).css({
                  'height': '',
                  'top': ''
                }).hide().removeClass("upper ddopen");
              });
            }
            else {
              //To support IE fixed size rendering,
              //parse out dom elements out of the fixed element
              parent.sugarActionMenu('IEfix', jNode);
              var _dropdown_height = jNode.height(),
                _animation = {'height': _dropdown_height},
                _dropdown_bottom = dropDownHandle.offset().top + dropDownHandle.height() - $(document).scrollTop() + jNode.outerHeight(),
                _win_height = $(window).height();
              if (dropDownHandle.offset().top > jNode.height() && _dropdown_bottom > $(window).height()) {
                jNode.css('top', (dropDownHandle.height() * -1)).addClass("upper");
                _animation['top'] = (jNode.height() + dropDownHandle.height()) * -1;
              }

              jNode.height(0).show().animate(_animation, slideDownSpeed, function () {
                $(this).css('height', '');
                setTimeout(function () {
                  // $('.subnav.ddopen').each(function (i, e) {
                  //   if (!$(e).hasClass('upper')) {
                  //     $(e).css('top', parseInt($(e).css('top')) + 10 + 'px');
                  //   }
                  // })
                }, 2);
              });
              jNode.addClass("ddopen");
            }
          };

          //add click handler to handle
          dropDownHandle.click(function (event) {
            toggleDropDown();
            event.stopPropagation();
          });

          var parentDropDownHandler = parent.find('a').first().hasClass('parent-dropdown-handler');
          if (parentDropDownHandler) {
            parent.click(function (event) {
              dropDownHandle.click();
              event.stopPropagation();
            });
          }

          //add submenu click off to body
          var jBody = $("body");
          var _hide_subnav_delay = 30;
          var _hide_subnav = function (subnav) {
            if (subnav.hasClass("subnav-sub-handler") === false) {
              subnav.slideUp(slideUpSpeed);
              subnav.removeClass("ddopen");
            }
          }
          if (jBody.data("sugarActionMenu") != true) {
            jBody.data("sugarActionMenu", true);
            jBody.bind("click", function () {
              //retore the dom elements back by handling iefix
              $("ul.SugarActionMenu > li").each(function () {
                $(this).sugarActionMenu('IEfix');
              });

              $("ul.SugarActionMenu ul.subnav").each(function (subIndex, node) {
                //prevent hiding the submenu when user click the submenu which contains one more depth submenu
                var _hide = function () {
                  _hide_subnav($(node));
                }
                setTimeout(_hide, _hide_subnav_delay);
              });
              //Hide second depth submenu
              $("ul.SugarActionMenu ul.subnav-sub").each(function (subIndex, node) {
                var _hide = function () {
                  $(this).removeClass("hover");
                  $(this).hide();
                }
                _timer_for_subnav = setTimeout(_hide, _hide_subnav_delay);
              });

            });
          }

          //add hover handler to handle
          dropDownHandle.hover(function () {
            dropDownHandle.addClass("subhover");
          }, function () {
            dropDownHandle.removeClass("subhover");
          });

          //bind click event to submenu items to hide the menu on click
          jNode.find("li").each(function (index, subnode) {
            //prevent hiding the submenu when user click the submenu which contains one more depth submenu
            $(subnode).bind("click", function (evt) {
              var _hide = function () {
                _hide_subnav(jNode);
              }
              setTimeout(_hide, _hide_subnav_delay);
            });
          });

          //fix up text of  tags so they span correctly
          jNode.find("a").each(function (index, subnode) {
            $(subnode).html(function (index, oldhtml) {
              return oldhtml.replace(" ", " ");
            });
          });
        });

        //Bug#51579: delete li tags which contains empty due to access role
        this.find(".subnav > li").each(function (index, subnode) {
          if ($(subnode).html().replace(/ /g, '') == '') {
            $(subnode).remove();
          }
        });
        //Bug#51579: If the first item is empty due to the access role,
        //           replace the first button from the first of the sub-list items.
        this.find("li.sugar_action_button:first").each(function (index, node) {
          var _this = $(node);
          var _first_item = $(node).find("a:first").not($(node).find(".subnav > li a"));
          if (_first_item.length == 0) {
            var sub_items = $(node).find(".subnav > li:first").children();
            if (sub_items.length == 0)
              menuNode.hide();
            else
              _this.prepend(sub_items);
          }
        });

      }
      return this;
    },
    addItem: function (args) {
      if (args.index == null) {
        this.find("ul.subnav").each(function (index, node) {
          $(node).append(args.item);
        })
      }
      else {
        this.find("ul.subnav").find("li").each(function (index, node) {
          if (args.index == index + 1) {
            $(node).before(args.item);
          }
        });
      }
      return this;
    },
    findItem: function (item) {
      var index = -1;
      this.find("a").each(function (idx, node) {
        var jNode = $(node);
        if ($.trim(jNode.html()) == $.trim(item)) {
          index = idx;
        }
      });
      return index;
    },
    /**
     * To support IE fixed size rendering,
     * parse out dom elements out of the fixed element
     *
     * Prepare ===
     *

     *     ...
     *

     *

     *             ...
     *

     *

     *

     *
     * Application ===
     *

     *

     *     ...
     *

     *

     *
     *

     *     ...
     *

     * @param this - element container which is inside the fixed box model
     * @param $ul - dropdown box model which needs to render out of the fixed box range
     *              if $ul is not given, it will restore back to the original structure
     */
    IEfix: function ($ul) {
      if ($ul) {
        if ($ul.hasClass('iefixed') === false)
          return;
        this.each(function () {
          SUGAR.themes.counter = SUGAR.themes.counter ? SUGAR.themes.counter++ : 1;
          var $$ = $(this),
            _id = $$.attr("ul-child-id") ? $$.attr("ul-child-id") : ($$.parent('.SugarActionMenu').attr("id")) ? $$.parent('.SugarActionMenu').attr("id") + 'Subnav' : 'sugaractionmenu' + SUGAR.themes.counter,
            _top = $$.position().top + $$.outerHeight(),
            _width = 'auto', //to obtain a certain size, apply min-width in css
            _css = {
              top: _top,
              width: _width,
              position: 'fixed'
            },
            _right = $('body').width() - $$.offset().left - $$.width(),
            _left = $$.offset().left;
          //fixed positioning depends on the css property
          if ($ul.css('right') != 'auto') {
            _css['right'] = _right;
          } else {
            _css['left'] = _left;
          }
          $('body').append($ul.attr("id", _id).addClass("SugarActionMenuIESub").css(_css));
          $$.attr("ul-child-id", _id);
        });

      } else {
        this.each(function () {
          var _id = $(this).attr("ul-child-id");
          $(this).append($("body>#" + _id).removeClass("SugarActionMenuIESub"));
        });
      }
    }
  }

  $.fn.sugarActionMenu = function (method) {

    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(
        arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.tooltip');
    }
  }
})(jQuery);
<|endoftext|>


<commit_before>var fs = require('fs');
var ga = require('../src/gitlet-api');
var testUtil = require('./test-util');

describe('branch', function() {
  beforeEach(testUtil.createEmptyRepo);
  beforeEach(testUtil.pinDate);
  afterEach(testUtil.unpinDate);

  it('should throw if not in repo', function() {
    expect(function() { ga.branch(); })
      .toThrow("fatal: Not a gitlet repository (or any of the parent directories): .gitlet");
  });

  it('should throw if master has not been created', function() {
    ga.init();
    expect(function() { ga.branch("woo"); })
      .toThrow("fatal: Not a valid object name: 'master'.");
  });

  it('should create new branch pointed at HEAD when call branch w branch name', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    ga.branch("woo");
    testUtil.expectFile(".gitlet/refs/heads/woo", "48946d55");
  });

  it('should should leave master pointed at orig hash after branching', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
    ga.branch("woo");
    testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
  });

  it('should return list of branches when called with no args', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    ga.branch("woo");
    ga.branch("boo");
    expect(ga.branch()).toEqual("  boo\n* master\n  woo\n");
  });
});
<commit_msg>Test branch throws if branch already exists<commit_after>var fs = require('fs');
var ga = require('../src/gitlet-api');
var testUtil = require('./test-util');

describe('branch', function() {
  beforeEach(testUtil.createEmptyRepo);
  beforeEach(testUtil.pinDate);
  afterEach(testUtil.unpinDate);

  it('should throw if not in repo', function() {
    expect(function() { ga.branch(); })
      .toThrow("fatal: Not a gitlet repository (or any of the parent directories): .gitlet");
  });

  it('should throw if master has not been created', function() {
    ga.init();
    expect(function() { ga.branch("woo"); })
      .toThrow("fatal: Not a valid object name: 'master'.");
  });

  it('should create new branch pointed at HEAD when call branch w branch name', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    ga.branch("woo");
    testUtil.expectFile(".gitlet/refs/heads/woo", "48946d55");
  });

  it('should should leave master pointed at orig hash after branching', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
    ga.branch("woo");
    testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
  });

  it('should return list of branches when called with no args', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    ga.branch("woo");
    ga.branch("boo");
    expect(ga.branch()).toEqual("  boo\n* master\n  woo\n");
  });

  it('should prevent branching if branch already exists', function() {
    ga.init();
    testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
    ga.add("1/filea");
    ga.commit({ m: "first" });
    ga.branch("woo");
    expect(function() { ga.branch("woo") })
      .toThrow("fatal: A branch named 'woo' already exists.");
  });
});
<|endoftext|>


<commit_before>import chai from 'chai'
import { CharacterData, EventTarget, Node, XMLSerializer } from '../lib/dom'
import {
    CharacterDataAssembler,
    EventTargetAssembler,
    NodeAssembler,
    DocumentAssembler,
    attr, comment, doctype, element,
    fragment, instruction, text
} from '../lib'

const { assert } = chai

const serializer = new XMLSerializer

describe('Common', () => {
    describe('CharacterDataAssembler', () => {
        it('static interface', () => {
            assert.equal(CharacterDataAssembler.interface, CharacterData)
        })
    })
    describe('EventTargetAssembler', () => {
        it('static interface', () => {
            assert.equal(EventTargetAssembler.interface, EventTarget)
        })
    })
    describe('NodeAssembler', () => {
        it('static interface', () => {
            assert.equal(NodeAssembler.interface, Node)
        })
    })
    describe('DocumentAssembler', () => {
        let $attr, $doctype, $fragment, $instruction, $element, $comment, $text
        const $document = new DocumentAssembler([
            $doctype = doctype('example'),
            $fragment = fragment([
                $instruction = instruction({
                    target : 'xml-stylesheet',
                    attrset : { href : './example.css' }
                }),
                $element = element({
                    localName : 'example',
                    attributes : $attr = attr({
                        name : 'role',
                        value : 'application'
                    }),
                    childNodes : [
                        $comment = comment('Version 1.0.0'),
                        $text = text('Hello world!')
                    ]
                })
            ])
        ])
        it('serializeToString(dom)', () => {
            const sample = '<!DOCTYPE example><?xml-stylesheet href="./example.css"?><example role="application"><!--Version 1.0.0-->Hello world!</example>'
            assert.equal(serializer.serializeToString($document.node), sample)
        })
        it('index', () => {
            assert.equal($document.index, -1)
            assert.equal($document.firstChild.index, 0)
            assert.equal($document.lastChild.index, 2)
        })
        it('documentElement', () => {
            assert.equal($document.documentElement, $element)
        })
        it('doctype', () => {
            assert.equal($document.doctype, $doctype)
        })
        it('nextSibling', () => {
            assert.equal($comment.nextSibling, $text)
        })
        it('previousSibling', () => {
            assert.equal($element.previousSibling, $instruction)
        })
        it('fragment.parentNode', () => {
            assert.isNull($fragment.parentNode)
        })
        it('fragment.node.hasChildNodes()', () => {
            assert.isFalse($fragment.node.hasChildNodes())
        })
        it('attr.ownerElement', () => {
            assert.equal($attr.ownerElement, $element)
        })
    })
    describe('ChildNodeAssembler.remove()', () => {
        let $element
        const $root = element([
            text('foobar'),
            comment('example'),
            $element = element(),
            instruction('test')
        ])
        const node = $root.node
        $element.remove()
        it('node.childNodes.length', () => {
            assert.equal(node.childNodes.length, 3)
        })
        it('serializeToString(node)', () => {
            const xml = serializer.serializeToString(node)
            const sample = '<element>foobar<!--example--><?instruction test?></element>'
            assert.equal(xml, sample)
        })
    })
    describe('element(element())', () => {
        let child
        const parent = element(child = element())
        it('parent.firstElementChild', () => {
            assert.equal(parent.firstElementChild, child)
        })
        it('parent.lastElementChild', () => {
            assert.equal(parent.lastElementChild, child)
        })
        it('removeChild(child); node.hasChildNodes', () => {
            parent.removeChild(child)
            assert.isFalse(parent.node.hasChildNodes())
        })
    })
    describe('element({ textContent })', () => {
        const test = element({ textContent : 'foobar' })
        it('parent.textContent', () => {
            assert.equal(test.textContent, 'foobar')
        })
        it('serializeToString(node)', () => {
            const xml = serializer.serializeToString(test.node)
            assert.equal(xml, '<element>foobar</element>')
        })
    })
})
<commit_msg>TargetAssembler.create: add spec<commit_after>import chai from 'chai'
import { CharacterData, EventTarget, Node, XMLSerializer } from '../lib/dom'
import {
    CharacterDataAssembler,
    EventTargetAssembler,
    DocumentAssembler,
    NodeAssembler,
    TargetAssembler,
    attr, comment, doctype, element,
    fragment, instruction, text
} from '../lib'

const { assert } = chai

const serializer = new XMLSerializer

describe('Common', () => {
    describe('new TargetAssembler', () => {
        const fn = () => new TargetAssembler
        it('throws', () => {
            assert.throws(fn, Error)
        })
    })
    describe('CharacterDataAssembler', () => {
        it('static interface', () => {
            assert.equal(CharacterDataAssembler.interface, CharacterData)
        })
    })
    describe('EventTargetAssembler', () => {
        it('static interface', () => {
            assert.equal(EventTargetAssembler.interface, EventTarget)
        })
    })
    describe('NodeAssembler', () => {
        it('static interface', () => {
            assert.equal(NodeAssembler.interface, Node)
        })
    })
    describe('DocumentAssembler', () => {
        let $attr, $doctype, $fragment, $instruction, $element, $comment, $text
        const $document = new DocumentAssembler([
            $doctype = doctype('example'),
            $fragment = fragment([
                $instruction = instruction({
                    target : 'xml-stylesheet',
                    attrset : { href : './example.css' }
                }),
                $element = element({
                    localName : 'example',
                    attributes : $attr = attr({
                        name : 'role',
                        value : 'application'
                    }),
                    childNodes : [
                        $comment = comment('Version 1.0.0'),
                        $text = text('Hello world!')
                    ]
                })
            ])
        ])
        it('serializeToString(dom)', () => {
            const sample = '<!DOCTYPE example><?xml-stylesheet href="./example.css"?><example role="application"><!--Version 1.0.0-->Hello world!</example>'
            assert.equal(serializer.serializeToString($document.node), sample)
        })
        it('index', () => {
            assert.equal($document.index, -1)
            assert.equal($document.firstChild.index, 0)
            assert.equal($document.lastChild.index, 2)
        })
        it('documentElement', () => {
            assert.equal($document.documentElement, $element)
        })
        it('doctype', () => {
            assert.equal($document.doctype, $doctype)
        })
        it('nextSibling', () => {
            assert.equal($comment.nextSibling, $text)
        })
        it('previousSibling', () => {
            assert.equal($element.previousSibling, $instruction)
        })
        it('fragment.parentNode', () => {
            assert.isNull($fragment.parentNode)
        })
        it('fragment.node.hasChildNodes()', () => {
            assert.isFalse($fragment.node.hasChildNodes())
        })
        it('attr.ownerElement', () => {
            assert.equal($attr.ownerElement, $element)
        })
    })
    describe('ChildNodeAssembler.remove()', () => {
        let $element
        const $root = element([
            text('foobar'),
            comment('example'),
            $element = element(),
            instruction('test')
        ])
        const node = $root.node
        $element.remove()
        it('node.childNodes.length', () => {
            assert.equal(node.childNodes.length, 3)
        })
        it('serializeToString(node)', () => {
            const xml = serializer.serializeToString(node)
            const sample = '<element>foobar<!--example--><?instruction test?></element>'
            assert.equal(xml, sample)
        })
    })
    describe('element(element())', () => {
        let child
        const parent = element(child = element())
        it('parent.firstElementChild', () => {
            assert.equal(parent.firstElementChild, child)
        })
        it('parent.lastElementChild', () => {
            assert.equal(parent.lastElementChild, child)
        })
        it('removeChild(child); node.hasChildNodes', () => {
            parent.removeChild(child)
            assert.isFalse(parent.node.hasChildNodes())
        })
    })
    describe('element({ textContent })', () => {
        const test = element({ textContent : 'foobar' })
        it('parent.textContent', () => {
            assert.equal(test.textContent, 'foobar')
        })
        it('serializeToString(node)', () => {
            const xml = serializer.serializeToString(test.node)
            assert.equal(xml, '<element>foobar</element>')
        })
    })
})
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var cli = require("../src/create.js"),
    Q = require('q'),
    cordova_lib = require('cordova-lib'),
    plugman = cordova_lib.plugman,
    cordova = cordova_lib.cordova;

describe("cordova cli", function () {
    beforeEach(function () {
        // Event registration is currently process-global. Since all jasmine
        // tests in a directory run in a single process (and in parallel),
        // logging events registered as a result of the "--verbose" flag in
        // CLI testing below would cause lots of logging messages printed out by other specs.
        spyOn(cordova, "on");
        spyOn(plugman, "on");
    });

    describe("Create Module", function () {

        describe("parseConfig", function() {

            it("should be defined", function () {
                expect(cdvclicreate.parseConfig).toEqual(jasmine.any(Function));
            });

        });

        describe("create", function() {

            it("should be defined", function () {
                expect(cdvclicreate.create).toEqual(jasmine.any(Function));
            });

        });
    });
};
<commit_msg>correct object referenced in tests<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var clicreate = require("../src/create.js"),
    Q = require('q'),
    cordova_lib = require('cordova-lib'),
    plugman = cordova_lib.plugman,
    cordova = cordova_lib.cordova;

describe("cordova cli", function () {

    beforeEach(function () {
        // Event registration is currently process-global. Since all jasmine
        // tests in a directory run in a single process (and in parallel),
        // logging events registered as a result of the "--verbose" flag in
        // CLI testing below would cause lots of logging messages printed out by other specs.
        spyOn(cordova, "on");
        spyOn(plugman, "on");
    });

    describe("Create Module", function () {

        describe("parseConfig", function() {

            it("should be defined", function () {
                expect(clicreate.parseConfig).toEqual(jasmine.any(Function));
            });

        });

        describe("create", function() {

            it("should be defined", function () {
                expect(clicreate.run).toEqual(jasmine.any(Function));
            });

        });
    });
});
<|endoftext|>


<commit_before>/* global Reveal, hljs */
import Ember from 'ember';
import layout from './template';
import EmberWormhole from 'ember-wormhole/components/ember-wormhole';
import { EKMixin, keyUp } from 'ember-keyboard';

const { computed, get, set, observer, isBlank, isPresent, on } = Ember;

export default EmberWormhole.extend(EKMixin, {
  layout,
  keyboard: Ember.inject.service(),

  emberRevealJs: Ember.inject.service(),
  isSpeakerNotes: computed.alias('emberRevealJs.isSpeakerNotes'),
  isMainWindow: computed.not('isSpeakerNotes'),
  isPrintingPdf: computed.alias('emberRevealJs.printPdf'),
  presentationWidth: computed.alias('emberRevealJs.presentationWidth'),
  presentationHeight: computed.alias('emberRevealJs.presentationHeight'),
  // presentation-class - passed in

  transition: 'slide', // none|fade|slide|convex|concave|zoom
  backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
  progress: true,
  controls: computed.alias('emberRevealJs.controls'),
  center: true,
  // theme - passed in
  themePreference: computed.alias('emberRevealJs.themePreference'),
  computedTheme: computed('theme', 'themePreference', function() {
    return get(this, 'themePreference') || get(this, 'theme') || 'black';
  }),

  // Specify ember-wormhole destinationElement of body to escape the
  // application view element, as reveal.js requires 100% height and width
  destinationElement: computed(function() {
    if (typeof document !== 'undefined') {
      return document.body;
    }
  }),

  didInsertElement() {
    this._super();
    this._initializeReveal();
    this.set('keyboardActivated', true);
  },

  speakerNotesUrl() {
    let ss = 'r=true';
    let s = location.search;
    let qs = isBlank(s) ? `?${ss}` : `${s}&${ss}`;
    return ['//', location.host, location.pathname, qs].join('');
  },

  launchSpeakerNotes: on(keyUp('s'), function() {
    if (get(this, 'isSpeakerNotes')) {
      return;
    }
    window.open(this.speakerNotesUrl(), 'reveal.js - Notes', 'width=1100,height=700');
  }),

  _initializeReveal() {
    if (get(this, 'isSpeakerNotes')) {
      return;
    }
    Reveal.initialize(this._revealOptions());
    Reveal.addEventListener('slidechanged', this._revealSlideChanged);
    Reveal.addEventListener('overviewshown', this._revealOverviewShown);
    Reveal.addEventListener('overviewhidden', this._revealOverviewHidden);
    Reveal.addEventListener('paused', this._revealPaused);
    Reveal.addEventListener('resumed', this._revealResumed);
    let self = this;
    Ember.subscribe('emberRevealJs.message', {
      before: Ember.K,
      after(name, timestamp, payload) {
        self._syncRevealState(payload);
      }
    });
    this._setRevealState();
    window.RevealMarkdown.convertSlides();
    hljs.initHighlightingOnLoad();
  },

  presentationStateDidChange: observer(
    'emberRevealJs.presentationState',
    function() {
      this._setRevealState();
    }
  ),

  _revealOptions() {
    let revealOptions = {
      history: false, // Don't interfere with Ember's routing
      transition: get(this, 'transition'),
      backgroundTransition: get(this, 'backgroundTransition'),
      progress: get(this, 'progress'),
      controls: get(this, 'controls'),
      center: get(this, 'center')
    };
    if (get(this, 'presentationWidth')) {
      revealOptions.width = get(this, 'presentationWidth');
    }
    if (get(this, 'presentationHeight')) {
      revealOptions.height = get(this, 'presentationHeight');
    }
    return revealOptions;
  },

  _revealSlideChanged(event) {
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealOverviewShown(event) {
    event.overview = true;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealOverviewHidden(event) {
    event.overview = false;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealPaused(event) {
    event.paused = true;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealResumed(event) {
    event.paused = false;
    Ember.instrument('emberRevealJs.message', event);
  },

  _syncRevealState(state) {
    set(this, 'emberRevealJs.indexh', state.indexh);
    set(this, 'emberRevealJs.indexv', state.indexv);
    if (isPresent(state.paused)) {
      set(this, 'emberRevealJs.paused', !!state.paused);
    }
    if (isPresent(state.overview)) {
      set(this, 'emberRevealJs.overview', !!state.overview);
    }
  },

  _setRevealState() {
    let state = get(this, 'emberRevealJs.presentationState');
    if (state) {
      Reveal.setState(state);
    }
  }
});
<commit_msg>Remove deprecated Ember.K<commit_after>/* global Reveal, hljs */
import Ember from 'ember';
import layout from './template';
import EmberWormhole from 'ember-wormhole/components/ember-wormhole';
import { EKMixin, keyUp } from 'ember-keyboard';

const { computed, get, set, observer, isBlank, isPresent, on } = Ember;

export default EmberWormhole.extend(EKMixin, {
  layout,
  keyboard: Ember.inject.service(),

  emberRevealJs: Ember.inject.service(),
  isSpeakerNotes: computed.alias('emberRevealJs.isSpeakerNotes'),
  isMainWindow: computed.not('isSpeakerNotes'),
  isPrintingPdf: computed.alias('emberRevealJs.printPdf'),
  presentationWidth: computed.alias('emberRevealJs.presentationWidth'),
  presentationHeight: computed.alias('emberRevealJs.presentationHeight'),
  // presentation-class - passed in

  transition: 'slide', // none|fade|slide|convex|concave|zoom
  backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
  progress: true,
  controls: computed.alias('emberRevealJs.controls'),
  center: true,
  // theme - passed in
  themePreference: computed.alias('emberRevealJs.themePreference'),
  computedTheme: computed('theme', 'themePreference', function() {
    return get(this, 'themePreference') || get(this, 'theme') || 'black';
  }),

  // Specify ember-wormhole destinationElement of body to escape the
  // application view element, as reveal.js requires 100% height and width
  destinationElement: computed(function() {
    if (typeof document !== 'undefined') {
      return document.body;
    }
  }),

  didInsertElement() {
    this._super();
    this._initializeReveal();
    this.set('keyboardActivated', true);
  },

  speakerNotesUrl() {
    let ss = 'r=true';
    let s = location.search;
    let qs = isBlank(s) ? `?${ss}` : `${s}&${ss}`;
    return ['//', location.host, location.pathname, qs].join('');
  },

  launchSpeakerNotes: on(keyUp('s'), function() {
    if (get(this, 'isSpeakerNotes')) {
      return;
    }
    window.open(this.speakerNotesUrl(), 'reveal.js - Notes', 'width=1100,height=700');
  }),

  _initializeReveal() {
    if (get(this, 'isSpeakerNotes')) {
      return;
    }
    Reveal.initialize(this._revealOptions());
    Reveal.addEventListener('slidechanged', this._revealSlideChanged);
    Reveal.addEventListener('overviewshown', this._revealOverviewShown);
    Reveal.addEventListener('overviewhidden', this._revealOverviewHidden);
    Reveal.addEventListener('paused', this._revealPaused);
    Reveal.addEventListener('resumed', this._revealResumed);
    let self = this;
    Ember.subscribe('emberRevealJs.message', {
      before() {},
      after(name, timestamp, payload) {
        self._syncRevealState(payload);
      }
    });
    this._setRevealState();
    window.RevealMarkdown.convertSlides();
    hljs.initHighlightingOnLoad();
  },

  presentationStateDidChange: observer(
    'emberRevealJs.presentationState',
    function() {
      this._setRevealState();
    }
  ),

  _revealOptions() {
    let revealOptions = {
      history: false, // Don't interfere with Ember's routing
      transition: get(this, 'transition'),
      backgroundTransition: get(this, 'backgroundTransition'),
      progress: get(this, 'progress'),
      controls: get(this, 'controls'),
      center: get(this, 'center')
    };
    if (get(this, 'presentationWidth')) {
      revealOptions.width = get(this, 'presentationWidth');
    }
    if (get(this, 'presentationHeight')) {
      revealOptions.height = get(this, 'presentationHeight');
    }
    return revealOptions;
  },

  _revealSlideChanged(event) {
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealOverviewShown(event) {
    event.overview = true;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealOverviewHidden(event) {
    event.overview = false;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealPaused(event) {
    event.paused = true;
    Ember.instrument('emberRevealJs.message', event);
  },

  _revealResumed(event) {
    event.paused = false;
    Ember.instrument('emberRevealJs.message', event);
  },

  _syncRevealState(state) {
    set(this, 'emberRevealJs.indexh', state.indexh);
    set(this, 'emberRevealJs.indexv', state.indexv);
    if (isPresent(state.paused)) {
      set(this, 'emberRevealJs.paused', !!state.paused);
    }
    if (isPresent(state.overview)) {
      set(this, 'emberRevealJs.overview', !!state.overview);
    }
  },

  _setRevealState() {
    let state = get(this, 'emberRevealJs.presentationState');
    if (state) {
      Reveal.setState(state);
    }
  }
});
<|endoftext|>