<commit_before>/**
 * Event manager class.
 */

import {array, assign, isArray, isObject, isUndefined} from './util';

export default class EventManager {

    constructor() {
        this.log = null;
        this.listeners = {};
    }

    on(event, callback, priority = 0) {

        const listeners = array(this.listeners[event]);
        const index = listeners.findIndex(listener => listener.priority < priority);

        if (~index) {
            listeners.splice(index, 0, {callback, priority});
        } else {
            listeners.push({callback, priority});
        }

        this.listeners[event] = listeners;

        return () => this.off(event, callback);
    }

    off(event, callback) {

        if (!callback) {
            delete this.listeners[event];
        }

        const listeners = this.listeners[event];

        if (listeners && callback) {

            const index = listeners.findIndex(listener => listener.callback === callback);

            if (~index) {
                listeners.splice(index, 1);
            }
        }
    }

    trigger(event, params = [], asynch = false) {

        const _event = new Event(event, params);
        const reject = result => Promise.reject(result);
        const resolve = result => !isUndefined(result) ? result : _event.result;
        const reducer = (result, {callback}) => {

            const next = result => {

                if (!isUndefined(result)) {
                    _event.result = result;
                }

                if (result === false) {
                    _event.stopPropagation();
                }

                if (_event.isPropagationStopped()) {
                    return _event.result;
                }

                return callback.apply(callback, [_event].concat(_event.params));
            };

            return asynch ? result.then(next, reject) : next(result);
        };

        const listeners = (this.listeners[_event.name] || []).concat();
        const result = listeners.reduce(reducer, asynch ? Promise.resolve() : undefined);

        if (this.log) {
            this.log.call(this, _event);
        }

        return asynch ? result.then(resolve, reject) : resolve(result);
    }

}

export class Event {

    constructor(event, params) {

        if (!isObject(event)) {
            event = {name: event};
        }

        if (!isArray(params)) {
            params = [params];
        }

        assign(this, event, {params, result: undefined});
    }

    stopPropagation() {
        this.stop = true;
    }

    isPropagationStopped() {
        return this.stop === true;
    }

}
<commit_msg>move log method call<commit_after>/**
 * Event manager class.
 */

import {array, assign, isArray, isObject, isUndefined} from './util';

export default class EventManager {

    constructor() {
        this.log = null;
        this.listeners = {};
    }

    on(event, callback, priority = 0) {

        const listeners = array(this.listeners[event]);
        const index = listeners.findIndex(listener => listener.priority < priority);

        if (~index) {
            listeners.splice(index, 0, {callback, priority});
        } else {
            listeners.push({callback, priority});
        }

        this.listeners[event] = listeners;

        return () => this.off(event, callback);
    }

    off(event, callback) {

        if (!callback) {
            delete this.listeners[event];
        }

        const listeners = this.listeners[event];

        if (listeners && callback) {

            const index = listeners.findIndex(listener => listener.callback === callback);

            if (~index) {
                listeners.splice(index, 1);
            }
        }
    }

    trigger(event, params = [], asynch = false) {

        const _event = new Event(event, params);
        const reject = result => Promise.reject(result);
        const resolve = result => !isUndefined(result) ? result : _event.result;
        const reducer = (result, {callback}) => {

            const next = result => {

                if (!isUndefined(result)) {
                    _event.result = result;
                }

                if (result === false) {
                    _event.stopPropagation();
                }

                if (_event.isPropagationStopped()) {
                    return _event.result;
                }

                return callback.apply(callback, [_event].concat(_event.params));
            };

            return asynch ? result.then(next, reject) : next(result);
        };

        if (this.log) {
            this.log.call(this, _event);
        }

        const listeners = (this.listeners[_event.name] || []).concat();
        const result = listeners.reduce(reducer, asynch ? Promise.resolve() : undefined);

        return asynch ? result.then(resolve, reject) : resolve(result);
    }

}

export class Event {

    constructor(event, params) {

        if (!isObject(event)) {
            event = {name: event};
        }

        if (!isArray(params)) {
            params = [params];
        }

        assign(this, event, {params, result: undefined});
    }

    stopPropagation() {
        this.stop = true;
    }

    isPropagationStopped() {
        return this.stop === true;
    }

}
<|endoftext|>


<commit_before>var detailsLat, detailsLon;

// Handlebars helpers

Handlebars.registerHelper('carouselimages', function(spacedata) {
    var space_id = spacedata.id;
    var elements = new Array;
    for (i=0; i < spacedata.images.length; i++) {
        image_id = spacedata.images[i].id;
        console.log(image_id);
        elements.push('

');
    }
    return new Handlebars.SafeString(elements.join('\n'));
});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

(function(w){

	var sw = document.body.clientWidth,
		breakpoint = 767,
		speed = 600,
		mobile = true;

    var deviceAgent = navigator.userAgent.toLowerCase();

    // detect ios versions
	var iphone = deviceAgent.match(/(ipad|iphone)/);
	var ios56 = navigator.userAgent.match(/OS [56](_\d)+ like Mac OS X/i);

    // detect android versions
    var android = deviceAgent.match(/(android)/);
    var gingerbread = deviceAgent.match(/android 2\.3/i);
    var gingerbreadOrNewer = deviceAgent.match(/android [2-9]/i);
    var honeycombOrNewer = deviceAgent.match(/android [3-9]/i);

    var froyoOrOlder = android && !gingerbread && !honeycombOrNewer;

	$(document).ready(function() {

    	// check if a map_canvas exists... populate it
    	if ($("#map_canvas").length == 1) {
          initialize();
        }

		checkMobile();
		setDisplay();

		if (mobile) {

    		// initialize the carousel for mobile standalone space page
            initializeCarousel();
            resizeCarouselMapContainer();

            // scroll to the top of page
            $('#top_link').click(function(e){
                  // Prevent a page reload when a link is pressed
                  e.preventDefault();
                  // Call the scroll function
                  scrollTo('top');
            });

            // scroll to top of filter list
            $('#filter_link').click(function(e){
                  // Prevent a page reload when a link is pressed
                  e.preventDefault();
                  // Call the scroll function
                  scrollTo('info_list');
            });

            // for iphones (ios5-6) - check if they have the ios detector cookie, if they don't give them one and show the popup
            // otherwise, don't do anything since they've already seen the popup
            if (iphone && ios56) {
                if (!$.cookie('showSpaceScoutiOS')){
                    console.log("no cookie... set cookie and show popup");
                    $.cookie('showSpaceScoutiOS', 'true');
                    showIosCallout();
                }
            }
		}

		// Toggle Filter display
		$('#filter_button').click(function() {

    		// calculate the filter height for mobile
    		if (mobile) {
        		$("#filter_block").height($(window).height() - $('#nav').height() - 10);

        		// handle scrolling for android gingerbread or newer
        		if (gingerbreadOrNewer) {
            		touchScroll(filter_block);
        		}
    		}

    		if ($("#filter_block").is(":hidden")) {

                $("#filter_block").slideDown('slow');

                $('#filter_button').hide();
                $('#view_results_button').show();
                $('#cancel_results_button').show();

                if (mobile) {

                    $('#main_content').hide();
                    $('#footer').hide();
                    $('.back-top').hide();
                }

            } else {

                if (mobile) {

                    $('#main_content').show();
                    $('#footer').show();
                    $('.back-top').show();
                }

                $('#filter_button').show();
                $('#view_results_button').hide();
                $('#cancel_results_button').hide();

                $("#filter_block").slideUp('slow');
            }
        });

        // Close the filter display using Cancel button
        $('#cancel_results_button').click(function() {

            if (mobile) {
                $('#main_content').show();
                $('#footer').show();
                $('.back-top').show();
            }

            $('#filter_button').show();
            $('#view_results_button').hide();
            $('#cancel_results_button').hide();

            $("#filter_block").slideUp('slow');

        });

        // handle view details click
        $('.view-details').live('click', function(e){

            // get the space id
            id =  $(this).attr('id');

            e.preventDefault();

            // clear previously selected space
            $('#info_items li').removeClass('selected');

            //highlight the selected space
            $(this).parent().addClass('selected');

            // if a space details already exists
            if ($('#space_detail_container').is(':visible')) {
                $.ajax({
                    url: '/space/'+id+'/json/',
                    success: replaceSpaceDetails
                });
            }
            else {
                $.ajax({
                    url: '/space/'+id+'/json/',
                    success: showSpaceDetails
                });
            }

        });

        $('#space_detail_container .close').live('click', function(e){
            e.preventDefault();
            hideSpaceDetails();
        });

        // fancy location select
        $("#e9").select2({
                placeholder: "Select a building",
                allowClear: true
            });

        // handle checkbox and radio button clicks
        $('.checkbox input:checkbox').click(function() {
            if(this.checked) {
                $(this).parent().addClass("selected");
            }
            else {
                $(this).parent().removeClass("selected");
            }
        });

        $('#filter_hours input:radio').change(function() {
            $(this).parent().addClass("selected");
            $(this).parent().siblings().removeClass("selected");

            if ($('#hours_list_input').is(':checked')) {
                //scrollTo('filter_hours');
                $('#hours_list_container').show();
            }
            else {
                $('#hours_list_container').hide();
            }
        });

        $('#filter_location input:radio').change(function() {
            $(this).parent().addClass("selected");
            $(this).parent().siblings().removeClass("selected");

            if ($('#building_list_input').is(':checked')) {
                //scrollTo('filter_location');
                $('#building_list_container').show();
            }
            else {
                $('#building_list_container').hide();
            }

        });

        // Toggle between carousel and map
        $('.space-image-map-buttons button').live('click', function(e){

            if ($('#carouselControl').hasClass('active')) { // show the carousel
                $('#spaceCarouselContainer').show();
                $('#spaceMap').hide();
            }
            else { //show the map
                $('#spaceCarouselContainer').hide();
                $('#spaceMap').show();
                getSpaceMap(detailsLat, detailsLon);
            }
        });

	});

	// Update dimensions on resize
	$(w).resize(function(){

	   console.log("resized");
	   sw = document.body.clientWidth;

	   checkMobile();
	   setDisplay();

	   // if the space details is already open
	   if ($('#space_detail_container').is(":visible")) {
    	   $('#space_detail_container').height($('#map_canvas').height());
    	   $('.space-detail-body').height($('.space-detail').height() - 172);
	   }

	});

	// Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
	}

	// Set the proper display settings
	function setDisplay() {
    	if (mobile) {
		  // mobile
		  mobileContent();
		} else {
		  // desktop
		  desktopContent();
		}
	}

	// Show space details (sliding transition)
	function showSpaceDetails(data) {

    	if (mobile) {
        	// change url
        	location.href = '/space/' + data.id;
    	}
    	else {

    	   // remove any open details
    	   $('#space_detail_container').remove();

        	// build the template
    	   var source = $('#space_details').html();
    	   var template = Handlebars.compile(source);
    	   $('#map_canvas').append(template(data));

    	   // set/reset initial state
    	   $('.space-detail-inner').show();
    	   $('#space_detail_container').show();

    	   $('#space_detail_container').height($('#map_canvas').height());
    	   $('.space-detail-body').height($('.space-detail').height() - 172);

    	   $('.space-detail').show("slide", { direction: "right" }, 700);

    	   initializeCarousel();
    	   resizeCarouselMapContainer();

    	   detailsLat = data.location.latitude;
    	   detailsLon = data.location.longitude;

    	}

	}

	// Replace space details (inline loading of already slid panel)
	function replaceSpaceDetails(data) {

    	if (mobile) {
        	// change url
        	location.href = '/space/' + data.id;
    	}
    	else {
        	// build the template
    	   var source = $('#space_details_replace').html();
    	   var template = Handlebars.compile(source);
    	   $('#space_detail_container').html(template(data));

    	   // set/reset initial state
    	   $('.space-detail-inner').hide();
    	   //$(".space-detail .loading").show();

    	   $('.space-detail-body').height($('.space-detail').height() - 172);

    	   $('.space-detail').show();

    	   // wait before showing the new space
    	   $(".space-detail-inner").delay(700).show(0, function() {
        	   initializeCarousel();
        	   resizeCarouselMapContainer();
           });

           detailsLat = data.location.latitude;
    	   detailsLon = data.location.longitude;
    	}

	}

	function hideSpaceDetails() {
        $('.space-detail').hide("slide", { direction: "right" }, 700, function() {
        	   $('#space_detail_container').remove();
        });

        // deselect selected space in list
        $('#info_items li').removeClass('selected');
	}

	// ScrollTo a spot on the UI
	function scrollTo(id) {
        // Scroll
        $('html,body').animate({ scrollTop: $("#"+id).offset().top},'fast');
    }

	// Desktop display defaults
	function desktopContent() {

    	var windowH = $(window).height();
        var headerH = $('#nav').height();
        var contentH = windowH - headerH;

        $('#map_canvas').height(contentH - 100);
        $('#info_list').height(contentH -80);

        // make sure loading and list height fills the list container
        $('#info_list .list-inner').css('min-height', contentH - 100);
        //$('.loading').height(contentH);
    }

    // Mobile display defaults
    function mobileContent() {

        var windowH = $(window).height();
        var headerH = $('#nav').height();
        //var contentH = windowH - headerH;
        //var mainContentH = windowH - headerH + 35;
        var mapH = windowH - headerH - 70; // enough to show the loading spinner at the bottom of the viewport

        $('#map_canvas').height(mapH);
        $('#map_canvas').css({ minHeight: mapH })
        $('#info_list').height('auto');

        //$("#filter_block").height(mapH + 60);

    }

    function initializeCarousel() {

        console.log("carousel initialized");

        $('.carousel').each(function(){
            $(this).carousel({
                interval: false
            });

            //set the first item as active
            $(this).find(".item:first-child").addClass("active");

            // hide the controls if only 1 picture exists
            if ($(this).find('.item').length == 1) {
                 $(this).find('.carousel-control').hide();
            }
        });

    }

    function resizeCarouselMapContainer() {
        // get the width
        var containerW = $('.image-container').width();

        // calcuate height based on 3:2 aspect ratio
        var containerH = containerW / 1.5;

        $('.carousel').height(containerH);
        $('.map-container').height(containerH);
    }

    // callout for ios5-6 native app
    function showIosCallout() {

        console.log("you are on an iphone");

        $('#ios_callout').show(0, function() {
            // Animation complete.
            $('.ios-inner-container').show("slide", { direction: "down" }, 700);
            // disable the iphone scroll
            document.ontouchmove = function(event){ event.preventDefault(); }
        });

        $('#continue_webapp').click(function() {
            // close the modal
            $('#ios_callout').hide();
            // enable scrolling
            document.ontouchmove = function(event){ return true; }
        });

        $('#download_native').click(function() {
            // redirect to app store
            window.location = "http://itunes.apple.com/us/app/spacescout/id551472160";
            // enable scrolling
            document.ontouchmove = function(event){ return true; }
        });
    }

    function touchScroll(id) {

		var el=document.getElementById(id);
		var scrollStartPos=0;

		document.getElementById(id).addEventListener("touchstart", function(event) {
			scrollStartPos=this.scrollTop+event.touches[0].pageY;
			event.preventDefault();
		},false);

		document.getElementById(id).addEventListener("touchmove", function(event) {
			this.scrollTop=scrollStartPos-event.touches[0].pageY;
			event.preventDefault();
		},false);

    }

})(this);
<commit_msg>fixes android scroll logic for filters<commit_after>var detailsLat, detailsLon;

// Handlebars helpers

Handlebars.registerHelper('carouselimages', function(spacedata) {
    var space_id = spacedata.id;
    var elements = new Array;
    for (i=0; i < spacedata.images.length; i++) {
        image_id = spacedata.images[i].id;
        console.log(image_id);
        elements.push('

');
    }
    return new Handlebars.SafeString(elements.join('\n'));
});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

(function(w){

	var sw = document.body.clientWidth,
		breakpoint = 767,
		speed = 600,
		mobile = true;

    var deviceAgent = navigator.userAgent.toLowerCase();

    // detect ios versions
	var iphone = deviceAgent.match(/(ipad|iphone)/);
	var ios56 = navigator.userAgent.match(/OS [56](_\d)+ like Mac OS X/i);

    // detect android versions
    var android = deviceAgent.match(/(android)/);
    var gingerbread = deviceAgent.match(/android 2\.3/i);
    var gingerbreadOrNewer = deviceAgent.match(/android [2-9]/i);
    var honeycombOrNewer = deviceAgent.match(/android [3-9]/i);
    var froyoOrOlder = android && !gingerbread && !honeycombOrNewer;

	$(document).ready(function() {

    	// check if a map_canvas exists... populate it
    	if ($("#map_canvas").length == 1) {
          initialize();
        }

		checkMobile();
		setDisplay();

		if (mobile) {

    		// initialize the carousel for mobile standalone space page
            initializeCarousel();
            resizeCarouselMapContainer();

            // scroll to the top of page
            $('#top_link').click(function(e){
                  // Prevent a page reload when a link is pressed
                  e.preventDefault();
                  // Call the scroll function
                  scrollTo('top');
            });

            // scroll to top of filter list
            $('#filter_link').click(function(e){
                  // Prevent a page reload when a link is pressed
                  e.preventDefault();
                  // Call the scroll function
                  scrollTo('info_list');
            });

            // for iphones (ios5-6) - check if they have the ios detector cookie, if they don't give them one and show the popup
            // otherwise, don't do anything since they've already seen the popup
            if (iphone && ios56) {
                if (!$.cookie('showSpaceScoutiOS')){
                    console.log("no cookie... set cookie and show popup");
                    $.cookie('showSpaceScoutiOS', 'true');
                    showIosCallout();
                }
            }
		}

		// Toggle Filter display
		$('#filter_button').click(function() {

    		// calculate the filter height for mobile browsers
    		if (mobile) {
        		$("#filter_block").height($(window).height() - $('#nav').height() - 10);
    		}

    		if ($("#filter_block").is(":hidden")) {

                $("#filter_block").slideDown('slow');

                $('#filter_button').hide();
                $('#view_results_button').show();
                $('#cancel_results_button').show();

                if (mobile) {

                    $('#main_content').hide();
                    $('#footer').hide();
                    $('.back-top').hide();

                    // handle scrolling for android gingerbread or newer
            		if (gingerbreadOrNewer) {
                		alert("you are on gingerbread");
                		touchScroll("filter_block");
            		}
                }

            } else {

                if (mobile) {

                    $('#main_content').show();
                    $('#footer').show();
                    $('.back-top').show();
                }

                $('#filter_button').show();
                $('#view_results_button').hide();
                $('#cancel_results_button').hide();

                $("#filter_block").slideUp('slow');
            }
        });

        // Close the filter display using Cancel button
        $('#cancel_results_button').click(function() {

            if (mobile) {
                $('#main_content').show();
                $('#footer').show();
                $('.back-top').show();
            }

            $('#filter_button').show();
            $('#view_results_button').hide();
            $('#cancel_results_button').hide();

            $("#filter_block").slideUp('slow');

        });

        // handle view details click
        $('.view-details').live('click', function(e){

            // get the space id
            id =  $(this).attr('id');

            e.preventDefault();

            // clear previously selected space
            $('#info_items li').removeClass('selected');

            //highlight the selected space
            $(this).parent().addClass('selected');

            // if a space details already exists
            if ($('#space_detail_container').is(':visible')) {
                $.ajax({
                    url: '/space/'+id+'/json/',
                    success: replaceSpaceDetails
                });
            }
            else {
                $.ajax({
                    url: '/space/'+id+'/json/',
                    success: showSpaceDetails
                });
            }

        });

        $('#space_detail_container .close').live('click', function(e){
            e.preventDefault();
            hideSpaceDetails();
        });

        // fancy location select
        $("#e9").select2({
                placeholder: "Select a building",
                allowClear: true
            });

        // handle checkbox and radio button clicks
        $('.checkbox input:checkbox').click(function() {
            if(this.checked) {
                $(this).parent().addClass("selected");
            }
            else {
                $(this).parent().removeClass("selected");
            }
        });

        $('#filter_hours input:radio').change(function() {
            $(this).parent().addClass("selected");
            $(this).parent().siblings().removeClass("selected");

            if ($('#hours_list_input').is(':checked')) {
                //scrollTo('filter_hours');
                $('#hours_list_container').show();
            }
            else {
                $('#hours_list_container').hide();
            }
        });

        $('#filter_location input:radio').change(function() {
            $(this).parent().addClass("selected");
            $(this).parent().siblings().removeClass("selected");

            if ($('#building_list_input').is(':checked')) {
                //scrollTo('filter_location');
                $('#building_list_container').show();
            }
            else {
                $('#building_list_container').hide();
            }

        });

        // Toggle between carousel and map
        $('.space-image-map-buttons button').live('click', function(e){

            if ($('#carouselControl').hasClass('active')) { // show the carousel
                $('#spaceCarouselContainer').show();
                $('#spaceMap').hide();
            }
            else { //show the map
                $('#spaceCarouselContainer').hide();
                $('#spaceMap').show();
                getSpaceMap(detailsLat, detailsLon);
            }
        });

	});

	// Update dimensions on resize
	$(w).resize(function(){

	   console.log("resized");
	   sw = document.body.clientWidth;

	   checkMobile();
	   setDisplay();

	   // if the space details is already open
	   if ($('#space_detail_container').is(":visible")) {
    	   $('#space_detail_container').height($('#map_canvas').height());
    	   $('.space-detail-body').height($('.space-detail').height() - 172);
	   }

	});

	// Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
	}

	// Set the proper display settings
	function setDisplay() {
    	if (mobile) {
		  // mobile
		  mobileContent();
		} else {
		  // desktop
		  desktopContent();
		}
	}

	// Show space details (sliding transition)
	function showSpaceDetails(data) {

    	if (mobile) {
        	// change url
        	location.href = '/space/' + data.id;
    	}
    	else {

    	   // remove any open details
    	   $('#space_detail_container').remove();

        	// build the template
    	   var source = $('#space_details').html();
    	   var template = Handlebars.compile(source);
    	   $('#map_canvas').append(template(data));

    	   // set/reset initial state
    	   $('.space-detail-inner').show();
    	   $('#space_detail_container').show();

    	   $('#space_detail_container').height($('#map_canvas').height());
    	   $('.space-detail-body').height($('.space-detail').height() - 172);

    	   $('.space-detail').show("slide", { direction: "right" }, 700);

    	   initializeCarousel();
    	   resizeCarouselMapContainer();

    	   detailsLat = data.location.latitude;
    	   detailsLon = data.location.longitude;

    	}

	}

	// Replace space details (inline loading of already slid panel)
	function replaceSpaceDetails(data) {

    	if (mobile) {
        	// change url
        	location.href = '/space/' + data.id;
    	}
    	else {
        	// build the template
    	   var source = $('#space_details_replace').html();
    	   var template = Handlebars.compile(source);
    	   $('#space_detail_container').html(template(data));

    	   // set/reset initial state
    	   $('.space-detail-inner').hide();
    	   //$(".space-detail .loading").show();

    	   $('.space-detail-body').height($('.space-detail').height() - 172);

    	   $('.space-detail').show();

    	   // wait before showing the new space
    	   $(".space-detail-inner").delay(700).show(0, function() {
        	   initializeCarousel();
        	   resizeCarouselMapContainer();
           });

           detailsLat = data.location.latitude;
    	   detailsLon = data.location.longitude;
    	}

	}

	function hideSpaceDetails() {
        $('.space-detail').hide("slide", { direction: "right" }, 700, function() {
        	   $('#space_detail_container').remove();
        });

        // deselect selected space in list
        $('#info_items li').removeClass('selected');
	}

	// ScrollTo a spot on the UI
	function scrollTo(id) {
        // Scroll
        $('html,body').animate({ scrollTop: $("#"+id).offset().top},'fast');
    }

	// Desktop display defaults
	function desktopContent() {

    	var windowH = $(window).height();
        var headerH = $('#nav').height();
        var contentH = windowH - headerH;

        $('#map_canvas').height(contentH - 100);
        $('#info_list').height(contentH -80);

        // make sure loading and list height fills the list container
        $('#info_list .list-inner').css('min-height', contentH - 100);
        //$('.loading').height(contentH);
    }

    // Mobile display defaults
    function mobileContent() {

        var windowH = $(window).height();
        var headerH = $('#nav').height();
        //var contentH = windowH - headerH;
        //var mainContentH = windowH - headerH + 35;
        var mapH = windowH - headerH - 70; // enough to show the loading spinner at the bottom of the viewport

        $('#map_canvas').height(mapH);
        $('#map_canvas').css({ minHeight: mapH })
        $('#info_list').height('auto');

        //$("#filter_block").height(mapH + 60);

    }

    function initializeCarousel() {

        console.log("carousel initialized");

        $('.carousel').each(function(){
            $(this).carousel({
                interval: false
            });

            //set the first item as active
            $(this).find(".item:first-child").addClass("active");

            // hide the controls if only 1 picture exists
            if ($(this).find('.item').length == 1) {
                 $(this).find('.carousel-control').hide();
            }
        });

    }

    function resizeCarouselMapContainer() {
        // get the width
        var containerW = $('.image-container').width();

        // calcuate height based on 3:2 aspect ratio
        var containerH = containerW / 1.5;

        $('.carousel').height(containerH);
        $('.map-container').height(containerH);
    }

    // callout for ios5-6 native app
    function showIosCallout() {

        console.log("you are on an iphone");

        $('#ios_callout').show(0, function() {
            // Animation complete.
            $('.ios-inner-container').show("slide", { direction: "down" }, 700);
            // disable the iphone scroll
            document.ontouchmove = function(event){ event.preventDefault(); }
        });

        $('#continue_webapp').click(function() {
            // close the modal
            $('#ios_callout').hide();
            // enable scrolling
            document.ontouchmove = function(event){ return true; }
        });

        $('#download_native').click(function() {
            // redirect to app store
            window.location = "http://itunes.apple.com/us/app/spacescout/id551472160";
            // enable scrolling
            document.ontouchmove = function(event){ return true; }
        });
    }

    function touchScroll(id) {

		var el=document.getElementById(id);
		var scrollStartPos=0;

		document.getElementById(id).addEventListener("touchstart", function(event) {
			scrollStartPos=this.scrollTop+event.touches[0].pageY;
			event.preventDefault();
		},false);

		document.getElementById(id).addEventListener("touchmove", function(event) {
			this.scrollTop=scrollStartPos-event.touches[0].pageY;
			event.preventDefault();
		},false);

    }

})(this);
<|endoftext|>


<commit_before>/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

 (function($, undefined){
	"use strict";

	$.widget("ui.rangeSliderHandle", $.ui.rangeSliderDraggable, {
		currentMove: null,
		margin: 0,
		parentElement: null,

		options: {
			isLeft: true,
			bounds: {min:0, max:100},
			range: false,
			value: 0,
			step: false
		},

		_value: 0,
		_left: 0,

		_create: function(){
			$.ui.rangeSliderDraggable.prototype._create.apply(this);

			this.element
				.css("position", "absolute")
				.css("top", 0)
				.addClass("ui-rangeSlider-handle")
				.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
				.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

			this._value = this.options.value;
		},

		_setOption: function(key, value){
			if (key === "isLeft" && (value === true || value === false) && value != this.options.isLeft){
				this.options.isLeft = value;

				this.element
					.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
					.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

				this._position(this._value);

				this.element.trigger("switch", this.options.isLeft);
			} else if (key === "step" && this._checkStep(value)){
				this.options.step = value;
				this.update();
			} else if (key === "bounds"){
				this.options.bounds = value;
				this.update();
			}else if (key === "range" && this._checkRange(value)){
				this.options.range = value;
				this.update();
			}

			$.ui.rangeSliderDraggable.prototype._setOption.apply(this, [key, value]);
		},

		_checkRange: function(range){
			return range === false ||
				((typeof range.min === "undefined" || range.min === false || parseFloat(range.min) === range.min)
					&& (typeof range.max === "undefined" || range.max === false || parseFloat(range.max) === range.max));
		},

		_checkStep: function(step){
			return (step === false || parseFloat(step) == step);
		},

		_initElement: function(){
			$.ui.rangeSliderDraggable.prototype._initElement.apply(this);

			if (this.cache.parent.width === 0 || this.cache.parent.width === null){
				setTimeout($.proxy(this._initElement, this), 500);
			}else{
				this._position(this.options.value);
				this._triggerMouseEvent("initialize");
			}
		},

		_bounds: function(){
			return this.options.bounds;
		},

		/*
		 * From draggable
		 */

		_cache: function(){
			$.ui.rangeSliderDraggable.prototype._cache.apply(this);

			this._cacheParent();
		},

		_cacheParent: function(){
			var parent = this.element.parent();

			this.cache.parent = {
				element: parent,
				offset: parent.offset(),
				padding: {
					left: this._parsePixels(parent, "paddingLeft")
				},
				width: parent.width()
			}
		},

		_position: function(value){
			var left = this._getPositionForValue(value);

			this._applyPosition(left);
		},

		_constraintPosition: function(position){
			var value = this._getValueForPosition(position);

			return this._getPositionForValue(value);
		},

		_applyPosition: function(left){
			$.ui.rangeSliderDraggable.prototype._applyPosition.apply(this, [left]);

			this._left = left;
			this._setValue(this._getValueForPosition(left));
			this._triggerMouseEvent("moving");
		},

		_prepareEventData: function(){
			var data = $.ui.rangeSliderDraggable.prototype._prepareEventData.apply(this);

			data.value = this._value;

			return data;
		},

		/*
		 * Value
		 */
		_setValue: function(value){
			if (value != this._value){
				this._value = value;
			}
		},

		_constraintValue: function(value){
			value = Math.min(value, this._bounds().max);
			value = Math.max(value, this._bounds().min);

			value = this._round(value);

			if (this.options.range !== false){
				var min = this.options.range.min || false,
					max = this.options.range.max || false;

				if (min !== false){
					value = Math.max(value, this._round(min));
				}

				if (max !== false){
					value = Math.min(value, this._round(max));
				}
			}

			return value;
		},

		_round: function(value){
			if (this.options.step !== false && this.options.step > 0){
				return Math.round(value / this.options.step) * this.options.step;
			}

			return value;
		},

		_getPositionForValue: function(value){
			if (this.cache.parent.offset == null){
				return 0;
			}

			value = this._constraintValue(value);

			var ratio = (value - this.options.bounds.min) / (this.options.bounds.max - this.options.bounds.min),
				position = this.cache.parent.offset.left;

			if (!this.options.isLeft){
				position -= this.cache.width.outer;
			}

			return position + ratio * this.cache.parent.width;
		},

		_getValueForPosition: function(position){
			if (!this.options.isLeft){
				position += this.cache.width.outer;
			}

			var ratio = (position - this.cache.parent.offset.left) / this.cache.parent.width,
				raw = ratio * (this.options.bounds.max - this.options.bounds.min) + this.options.bounds.min;

			return this._constraintValue(raw);
		},

		/*
		 * Public
		 */

		value: function(value){
			if (typeof value != "undefined"){
				this._cache();

				value = this._constraintValue(value);

				this._position(value);
			}

			return this._value;
		},

		update: function(){
			this._cache();
			var value = this._constraintValue(this._value),
				position = this._getPositionForValue(value);

			if (value != this._value){
				this._position(value);
				this._triggerMouseEvent("update");
			}else if (position != this.cache.offset.left){
				this._position(value);
				this._triggerMouseEvent("update");
			}
		},

		position: function(position){
			if (typeof position != "undefined"){
				this._cache();

				position = this._constraintPosition(position);
				this._applyPosition(position);
			}

			return this._left;
		},

		add: function(value, step){
			return value + step;
		},

		substract: function(value, step){
			return value - step;
		},

		stepsBetween: function(val1, val2){
			if (this.options.step === false){
				return val2 - val1;
			}

			return (val2 - val1) / this.options.step;
		},

		multiplyStep: function(step, factor){
			return step * factor;
		},

		moveRight: function(quantity){
			var previous;

			if (this.options.step == false){
				previous = this._left;
				this.position(this._left + quantity);

				return this._left - previous;
			}

			previous = this._value;
			this.value(this.add(previous, this.multiplyStep(this.options.step, quantity)));

			return this.stepsBetween(previous, this._value);
		},

		moveLeft: function(quantity){
			return -this.moveRight(-quantity);
		},

		stepRatio: function(){
			if (this.options.step == false){
				return 1;
			}else{
				var steps = (this.options.bounds.max - this.options.bounds.min) / this.options.step;
				return this.cache.parent.width / steps;
			}
		}
	});
 })(jQuery);<commit_msg>#46 Labels swap when values are very close<commit_after>/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

 (function($, undefined){
	"use strict";

	$.widget("ui.rangeSliderHandle", $.ui.rangeSliderDraggable, {
		currentMove: null,
		margin: 0,
		parentElement: null,

		options: {
			isLeft: true,
			bounds: {min:0, max:100},
			range: false,
			value: 0,
			step: false
		},

		_value: 0,
		_left: 0,

		_create: function(){
			$.ui.rangeSliderDraggable.prototype._create.apply(this);

			this.element
				.css("position", "absolute")
				.css("top", 0)
				.addClass("ui-rangeSlider-handle")
				.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
				.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

			this._value = this.options.value;
		},

		_setOption: function(key, value){
			if (key === "isLeft" && (value === true || value === false) && value != this.options.isLeft){
				this.options.isLeft = value;

				this.element
					.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
					.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

				this._position(this._value);

				this.element.trigger("switch", this.options.isLeft);
			} else if (key === "step" && this._checkStep(value)){
				this.options.step = value;
				this.update();
			} else if (key === "bounds"){
				this.options.bounds = value;
				this.update();
			}else if (key === "range" && this._checkRange(value)){
				this.options.range = value;
				this.update();
			}

			$.ui.rangeSliderDraggable.prototype._setOption.apply(this, [key, value]);
		},

		_checkRange: function(range){
			return range === false ||
				((typeof range.min === "undefined" || range.min === false || parseFloat(range.min) === range.min)
					&& (typeof range.max === "undefined" || range.max === false || parseFloat(range.max) === range.max));
		},

		_checkStep: function(step){
			return (step === false || parseFloat(step) == step);
		},

		_initElement: function(){
			$.ui.rangeSliderDraggable.prototype._initElement.apply(this);

			if (this.cache.parent.width === 0 || this.cache.parent.width === null){
				setTimeout($.proxy(this._initElement, this), 500);
			}else{
				this._position(this.options.value);
				this._triggerMouseEvent("initialize");
			}
		},

		_bounds: function(){
			return this.options.bounds;
		},

		/*
		 * From draggable
		 */

		_cache: function(){
			$.ui.rangeSliderDraggable.prototype._cache.apply(this);

			this._cacheParent();
		},

		_cacheParent: function(){
			var parent = this.element.parent();

			this.cache.parent = {
				element: parent,
				offset: parent.offset(),
				padding: {
					left: this._parsePixels(parent, "paddingLeft")
				},
				width: parent.width()
			}
		},

		_position: function(value){
			var left = this._getPositionForValue(value);

			this._applyPosition(left);
		},

		_constraintPosition: function(position){
			var value = this._getValueForPosition(position);

			return this._getPositionForValue(value);
		},

		_applyPosition: function(left){
			$.ui.rangeSliderDraggable.prototype._applyPosition.apply(this, [left]);

			this._left = left;
			this._setValue(this._getValueForPosition(left));
			this._triggerMouseEvent("moving");
		},

		_prepareEventData: function(){
			var data = $.ui.rangeSliderDraggable.prototype._prepareEventData.apply(this);

			data.value = this._value;

			return data;
		},

		/*
		 * Value
		 */
		_setValue: function(value){
			if (value != this._value){
				this._value = value;
			}
		},

		_constraintValue: function(value){
			value = Math.min(value, this._bounds().max);
			value = Math.max(value, this._bounds().min);

			value = this._round(value);

			if (this.options.range !== false){
				var min = this.options.range.min || false,
					max = this.options.range.max || false;

				if (min !== false){
					value = Math.max(value, this._round(min));
				}

				if (max !== false){
					value = Math.min(value, this._round(max));
				}
			}

			return value;
		},

		_round: function(value){
			if (this.options.step !== false && this.options.step > 0){
				return Math.round(value / this.options.step) * this.options.step;
			}

			return value;
		},

		_getPositionForValue: function(value){
			if (this.cache.parent.offset == null){
				return 0;
			}

			value = this._constraintValue(value);

			var ratio = (value - this.options.bounds.min) / (this.options.bounds.max - this.options.bounds.min),
				leftShift = Math.round(this.cache.width.outer / 2),
				position = this.cache.parent.offset.left + leftShift,
				rightShift = this.cache.width.outer - leftShift;

			if (this.options.isLeft){
				position -= leftShift;
			}else{
				position -= rightShift;
			}

			return position + ratio * (this.cache.parent.width - this.cache.width.outer);
		},

		_getValueForPosition: function(position){
			var leftShift = Math.round(this.cache.width.outer / 2),
				rightShift = this.cache.width.outer - leftShift;

			if (this.options.isLeft){
				position += leftShift;
			}else{
				position += rightShift;
			}

			position -= leftShift;

			var ratio = (position - this.cache.parent.offset.left) / (this.cache.parent.width - this.cache.width.outer),
				raw = ratio * (this.options.bounds.max - this.options.bounds.min) + this.options.bounds.min;

			return this._constraintValue(raw);
		},

		/*
		 * Public
		 */

		value: function(value){
			if (typeof value != "undefined"){
				this._cache();

				value = this._constraintValue(value);

				this._position(value);
			}

			return this._value;
		},

		update: function(){
			this._cache();
			var value = this._constraintValue(this._value),
				position = this._getPositionForValue(value);

			if (value != this._value){
				this._position(value);
				this._triggerMouseEvent("update");
			}else if (position != this.cache.offset.left){
				this._position(value);
				this._triggerMouseEvent("update");
			}
		},

		position: function(position){
			if (typeof position != "undefined"){
				this._cache();

				position = this._constraintPosition(position);
				this._applyPosition(position);
			}

			return this._left;
		},

		add: function(value, step){
			return value + step;
		},

		substract: function(value, step){
			return value - step;
		},

		stepsBetween: function(val1, val2){
			if (this.options.step === false){
				return val2 - val1;
			}

			return (val2 - val1) / this.options.step;
		},

		multiplyStep: function(step, factor){
			return step * factor;
		},

		moveRight: function(quantity){
			var previous;

			if (this.options.step == false){
				previous = this._left;
				this.position(this._left + quantity);

				return this._left - previous;
			}

			previous = this._value;
			this.value(this.add(previous, this.multiplyStep(this.options.step, quantity)));

			return this.stepsBetween(previous, this._value);
		},

		moveLeft: function(quantity){
			return -this.moveRight(-quantity);
		},

		stepRatio: function(){
			if (this.options.step == false){
				return 1;
			}else{
				var steps = (this.options.bounds.max - this.options.bounds.min) / this.options.step;
				return this.cache.parent.width / steps;
			}
		}
	});
 })(jQuery);<|endoftext|>


<commit_before>import _curry2 from './internal/_curry2';

/**
 * Returns the second argument if it is not `null`, `undefined` or `NaN`;
 * otherwise the first argument is returned.
 *
 * @func
 * @memberOf R
 * @since v0.10.0
 * @category Logic
 * @sig a -> b -> a | b
 * @param {a} default The default value.
 * @param {b} val `val` will be returned instead of `default` unless `val` is `null`, `undefined` or `NaN`.
 * @return {*} The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value
 * @example
 *
 *      var defaultTo42 = R.defaultTo(42);
 *
 *      defaultTo42(null);  //=> 42
 *      defaultTo42(undefined);  //=> 42
 *      defaultTo42('Ramda');  //=> 'Ramda'
 *      // parseInt('string') results in NaN
 *      defaultTo42(parseInt('string')); //=> 42
 */
var defaultTo = _curry2(function defaultTo(d, v) {
  return v == null || v !== v ? d : v;
});
export default defaultTo;
<commit_msg>add example to defaultTo<commit_after>import _curry2 from './internal/_curry2';

/**
 * Returns the second argument if it is not `null`, `undefined` or `NaN`;
 * otherwise the first argument is returned.
 *
 * @func
 * @memberOf R
 * @since v0.10.0
 * @category Logic
 * @sig a -> b -> a | b
 * @param {a} default The default value.
 * @param {b} val `val` will be returned instead of `default` unless `val` is `null`, `undefined` or `NaN`.
 * @return {*} The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value
 * @example
 *
 *      var defaultTo42 = R.defaultTo(42);
 *
 *      defaultTo42(null);  //=> 42
 *      defaultTo42(undefined);  //=> 42
  *      defaultTo42(false);  //=> false
 *      defaultTo42('Ramda');  //=> 'Ramda'
 *      // parseInt('string') results in NaN
 *      defaultTo42(parseInt('string')); //=> 42
 */
var defaultTo = _curry2(function defaultTo(d, v) {
  return v == null || v !== v ? d : v;
});
export default defaultTo;
<|endoftext|>


<commit_before>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed 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.
 */
/**
 * @fileoverview Definitions for all the extensions over the
 *  W3C's event specification by IE in JScript. This file depends on
 *  w3c_event.js. The whole file has NOT been fully type annotated.
 *
 * @externs
 */

Event.prototype.Abstract;
Event.prototype.altKey;
Event.prototype.altLeft;
Event.prototype.Banner;
Event.prototype.button;
Event.prototype.cancelBubble;
Event.prototype.clientX;
Event.prototype.clientY;
/**
 * @see http://msdn.microsoft.com/en-us/library/ms535220(VS.85).aspx
 * @type {ClipboardData|undefined}
 */
Event.prototype.clipboardData;
Event.prototype.contentOverflow;
Event.prototype.ctrlKey;
Event.prototype.ctrlLeft;
Event.prototype.data;
Event.prototype.dataFld;
Event.prototype.domain;
Event.prototype.fromElement;
Event.prototype.keyCode;
Event.prototype.MoreInfo;
Event.prototype.nextPage;
Event.prototype.offsetX;
Event.prototype.offsetY;
Event.prototype.propertyName;
Event.prototype.qualifier;
Event.prototype.reason;
Event.prototype.recordset;
Event.prototype.repeat;
/**
 * @type {boolean|string|undefined}
 */
Event.prototype.returnValue;
Event.prototype.saveType;
Event.prototype.scheme;
Event.prototype.screenX;
Event.prototype.screenY;
Event.prototype.shiftKey;
Event.prototype.shiftLeft;
Event.prototype.source;
Event.prototype.srcElement;
Event.prototype.srcFilter;
Event.prototype.srcUrn;
Event.prototype.toElement;
Event.prototype.type;
Event.prototype.userName;
Event.prototype.wheelDelta;
Event.prototype.x;
Event.prototype.y;
<commit_msg>Add type information to ie_event.js externs<commit_after>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed 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.
 */

/**
 * @fileoverview Definitions for all the extensions over the
 *  W3C's event specification by IE in JScript. This file depends on
 *  w3c_event.js.
 *
 * @see http://msdn.microsoft.com/en-us/library/ms535863.aspx
 * @externs
 */

/** @type {string} */
Event.prototype.Abstract;

/** @type {boolean} */
Event.prototype.altKey;

/** @type {boolean} */
Event.prototype.altLeft;

/** @type {string} */
Event.prototype.Banner;

/** @type {number} */
Event.prototype.button;

/** @type {boolean} */
Event.prototype.cancelBubble;

/** @type {number} */
Event.prototype.clientX;

/** @type {number} */
Event.prototype.clientY;

/**
 * @see http://msdn.microsoft.com/en-us/library/ms535220.aspx
 * @type {(ClipboardData|undefined)}
 */
Event.prototype.clipboardData;

/** @type {boolean} */
Event.prototype.contentOverflow;

/** @type {boolean} */
Event.prototype.ctrlKey;

/** @type {boolean} */
Event.prototype.ctrlLeft;

/** @type {string} */
Event.prototype.data;

/** @type {string} */
Event.prototype.dataFld;

Event.prototype.domain;

/** @type {Element} */
Event.prototype.fromElement;

/** @type {number} */
Event.prototype.keyCode;

/** @type {string} */
Event.prototype.MoreInfo;

/** @type {string} */
Event.prototype.nextPage;

/** @type {number} */
Event.prototype.offsetX;

/** @type {number} */
Event.prototype.offsetY;

/** @type {string} */
Event.prototype.propertyName;

/** @type {string} */
Event.prototype.qualifier;

/** @type {number} */
Event.prototype.reason;

/** @type {Object.<*,*>} */
Event.prototype.recordset;

/** @type {boolean} */
Event.prototype.repeat;

/** @type {(boolean|string|undefined)} */
Event.prototype.returnValue;

/** @type {string} */
Event.prototype.saveType;

Event.prototype.scheme;

/** @type {number} */
Event.prototype.screenX;

/** @type {number} */
Event.prototype.screenY;

/** @type {boolean} */
Event.prototype.shiftKey;

/** @type {boolean} */
Event.prototype.shiftLeft;

/** @type {Window} */
Event.prototype.source;

/** @type {Element} */
Event.prototype.srcElement;

Event.prototype.srcFilter;

/** @type {string} */
Event.prototype.srcUrn;

/** @type {Element} */
Event.prototype.toElement;

Event.prototype.userName;

/** @type {number} */
Event.prototype.wheelDelta;

/** @type {number} */
Event.prototype.x;

/** @type {number} */
Event.prototype.y;<|endoftext|>


<commit_before>/**
 * Conversions.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Converts blob/uris/images back and forth.
 */
define("ephox/imagetools/util/Conversions", [
  "ephox/imagetools/util/Promise",
  "ephox/imagetools/util/Canvas",
  "ephox/imagetools/util/Mime",
  "ephox/imagetools/util/ImageSize"
], function(Promise, Canvas, Mime, ImageSize) {
  function loadImage(image) {
    return new Promise(function(resolve) {
      function loaded() {
        image.removeEventListener('load', loaded);
        resolve(image);
      }

      if (image.complete) {
        resolve(image);
      } else {
        image.addEventListener('load', loaded);
      }
    });
  }

  function imageToCanvas(image) {
    return loadImage(image).then(function(image) {
      var context, canvas;

      canvas = Canvas.create(ImageSize.getWidth(image), ImageSize.getHeight(image));
      context = Canvas.get2dContext(canvas);
      context.drawImage(image, 0, 0);

      return canvas;
    });
  }

  function imageToBlob(image) {
    return loadImage(image).then(function(image) {
      var src = image.src;

      if (src.indexOf('blob:') === 0) {
        return blobUriToBlob(src);
      }

      if (src.indexOf('data:') === 0) {
        return dataUriToBlob(src);
      }

      return imageToCanvas(image).then(function(canvas) {
        return dataUriToBlob(canvas.toDataURL(Mime.guessMimeType(src)));
      });
    });
  }

  function blobToImage(blob) {
    return new Promise(function(resolve) {
      var image = new Image();

      function loaded() {
        image.removeEventListener('load', loaded);
        resolve(image);
      }

      image.addEventListener('load', loaded);
      image.src = URL.createObjectURL(blob);

      if (image.complete) {
        loaded();
      }
    });
  }

  function blobUriToBlob(url) {
    return new Promise(function(resolve) {
      var xhr = new XMLHttpRequest();

      xhr.open('GET', url, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (this.status == 200) {
          resolve(this.response);
        }
      };

      xhr.send();
    });
  }

  function dataUriToBlob(uri) {
    return new Promise(function(resolve) {
      var str, arr, i, matches, type, blobBuilder;

      uri = uri.split(',');

      matches = /data:([^;]+)/.exec(uri[0]);
      if (matches) {
        type = matches[1];
      }

      str = atob(uri[1]);

      if (window.WebKitBlobBuilder) {
        /*globals WebKitBlobBuilder:false */
        blobBuilder = new WebKitBlobBuilder();

        arr = new ArrayBuffer(str.length);
        for (i = 0; i < arr.length; i++) {
          arr[i] = str.charCodeAt(i);
        }

        blobBuilder.append(arr);

        resolve(blobBuilder.getBlob(type));
        return;
      }

      arr = new Uint8Array(str.length);

      for (i = 0; i < arr.length; i++) {
        arr[i] = str.charCodeAt(i);
      }

      resolve(new Blob([arr], {type: type}));
    });
  }

  function uriToBlob(url) {
    if (url.indexOf('blob:') === 0) {
      return blobUriToBlob(url);
    }

    if (url.indexOf('data:') === 0) {
      return dataUriToBlob(url);
    }

    return null;
  }

  function canvasToBlob(canvas, type) {
    return dataUriToBlob(canvas.toDataURL(type));
  }

  function blobToDataUri(blob) {
    return new Promise(function(resolve) {
      var reader = new FileReader();

      reader.onloadend = function() {
        resolve(reader.result);
      };

      reader.readAsDataURL(blob);
    });
  }

  function blobToBase64(blob) {
    return blobToDataUri(blob).then(function(dataUri) {
      return dataUri.split(',')[1];
    });
  }

  function revokeImageUrl(image) {
    URL.revokeObjectURL(image.src);
  }

  return {
    // used outside
    blobToImage: blobToImage,
    // used outside
    imageToBlob: imageToBlob,
    // used outside
    blobToDataUri: blobToDataUri,
    // used outside
    blobToBase64: blobToBase64,

    // helper method
    imageToCanvas: imageToCanvas,

    // helper method
    canvasToBlob: canvasToBlob,

    // helper method
    revokeImageUrl: revokeImageUrl,

     // helper method
    uriToBlob: uriToBlob

  };
});<commit_msg>Conversions: Add methods that will convert blob and dataUri to a combined ImageResult.<commit_after>/**
 * Conversions.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Converts blob/uris/images back and forth.
 */
define("ephox/imagetools/util/Conversions", [
  "ephox/imagetools/util/Promise",
  "ephox/imagetools/util/Canvas",
  "ephox/imagetools/util/Mime",
  "ephox/imagetools/util/ImageSize",
  "ephox/imagetools/util/ImageResult"
], function(Promise, Canvas, Mime, ImageSize, ImageResult) {
  function loadImage(image) {
    return new Promise(function(resolve) {
      function loaded() {
        image.removeEventListener('load', loaded);
        resolve(image);
      }

      if (image.complete) {
        resolve(image);
      } else {
        image.addEventListener('load', loaded);
      }
    });
  }

  function imageToCanvas(image) {
    return loadImage(image).then(function(image) {
      var context, canvas;

      canvas = Canvas.create(ImageSize.getWidth(image), ImageSize.getHeight(image));
      context = Canvas.get2dContext(canvas);
      context.drawImage(image, 0, 0);

      return canvas;
    });
  }

  function imageToBlob(image) {
    return loadImage(image).then(function(image) {
      var src = image.src;

      if (src.indexOf('blob:') === 0) {
        return blobUriToBlob(src);
      }

      if (src.indexOf('data:') === 0) {
        return dataUriToBlob(src);
      }

      return imageToCanvas(image).then(function(canvas) {
        return dataUriToBlob(canvas.toDataURL(Mime.guessMimeType(src)));
      });
    });
  }

  function blobToImage(blob) {
    return new Promise(function(resolve) {
      var image = new Image();

      function loaded() {
        image.removeEventListener('load', loaded);
        resolve(image);
      }

      image.addEventListener('load', loaded);
      image.src = URL.createObjectURL(blob);

      if (image.complete) {
        loaded();
      }
    });
  }

  function blobUriToBlob(url) {
    return new Promise(function(resolve) {
      var xhr = new XMLHttpRequest();

      xhr.open('GET', url, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (this.status == 200) {
          resolve(this.response);
        }
      };

      xhr.send();
    });
  }

  function dataUriToBlob(uri) {
    return new Promise(function(resolve) {
      var str, arr, i, matches, type, blobBuilder;

      uri = uri.split(',');

      matches = /data:([^;]+)/.exec(uri[0]);
      if (matches) {
        type = matches[1];
      }

      str = atob(uri[1]);

      if (window.WebKitBlobBuilder) {
        /*globals WebKitBlobBuilder:false */
        blobBuilder = new WebKitBlobBuilder();

        arr = new ArrayBuffer(str.length);
        for (i = 0; i < arr.length; i++) {
          arr[i] = str.charCodeAt(i);
        }

        blobBuilder.append(arr);

        resolve(blobBuilder.getBlob(type));
        return;
      }

      arr = new Uint8Array(str.length);

      for (i = 0; i < arr.length; i++) {
        arr[i] = str.charCodeAt(i);
      }

      resolve(new Blob([arr], {type: type}));
    });
  }

  function uriToBlob(url) {
    if (url.indexOf('blob:') === 0) {
      return blobUriToBlob(url);
    }

    if (url.indexOf('data:') === 0) {
      return dataUriToBlob(url);
    }

    return null;
  }

  function canvasToBlob(canvas, type) {
    return dataUriToBlob(canvas.toDataURL(type));
  }

  function blobToDataUri(blob) {
    return new Promise(function(resolve) {
      var reader = new FileReader();

      reader.onloadend = function() {
        resolve(reader.result);
      };

      reader.readAsDataURL(blob);
    });
  }

  function blobToBase64(blob) {
    return blobToDataUri(blob).then(function(dataUri) {
      return dataUri.split(',')[1];
    });
  }

  function revokeImageUrl(image) {
    URL.revokeObjectURL(image.src);
  }

  function blobToImageResult(blob) {
    return blobToDataUri(blob).then(function(uri) {
      return new ImageResult({ blob: blob, dataUri: uri });
    });
  }

  function dataUriToImageResult(uri) {
    return uriToBlob(uri).then(function(blob) {
      return new ImageResult({ blob: blob, dataUri: uri });
    });
  }

  return {
    // used outside
    blobToImage: blobToImage,
    // used outside
    imageToBlob: imageToBlob,
    // used outside
    blobToDataUri: blobToDataUri,
    // used outside
    blobToBase64: blobToBase64,
    // used outside
    blobToImageResult: blobToImageResult,
    // used outside
    dataUriToImageResult: dataUriToImageResult,

    // helper method
    imageToCanvas: imageToCanvas,

    // helper method
    canvasToBlob: canvasToBlob,

    // helper method
    revokeImageUrl: revokeImageUrl,

     // helper method
    uriToBlob: uriToBlob

  };
});<|endoftext|>


<commit_before>const Generator = require('yeoman-generator');
const chalk = require('chalk');
const config = require('../lib/config');
const { validate, find } = require('../lib/schemas');

module.exports = class EgGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this._configuration = null;
    this.eg = this.env.eg;
    this.argv = this.env.argv;
    this.admin = require('../admin')({
      baseUrl: this._getAdminClientBaseURL(),
      verbose: this._getAdminClientVerboseFlag(),
      headers: this.argv && this.argv.H ? this.processHeaders(this.argv.H) : null
    });
  }

  configureCommand (configuration) {
    const builder = configuration.builder;
    configuration.builder = yargs => {
      return this._wrapConfig(builder(yargs));
    };

    configuration.handler = argv => {
      this.env.argv = argv;

      const command = this.options.env.commandAliases[0][argv._[0]];
      const subCommand = this.options.env.commandAliases[1][command][argv._[1]];

      this.env.run(`express-gateway:${command}:${subCommand}`);
    };

    this._configuration = configuration;
  }

  stdout (...args) {
    // eslint-disable-next-line no-console
    console.log.apply(console, args);
  }

  createSubCommand (name) {
    const generatorName = `${this.constructor.namespace}:${name}`;
    return this.env.create(generatorName)._configuration;
  }

  // configuration defaults
  _wrapConfig (yargs) {
    return yargs
      .boolean(['no-color', 'q', 'v'])
      .string(['H'])
      .describe('no-color', 'Disable color in prompts')
      .alias('q', 'quiet')
      .describe('q', 'Only show major pieces of output')
      .describe('H', 'Header to send with each request to Express Gateway Admin API KEY:VALUE format')
      .alias('v', 'verbose')
      .describe('v', 'Verbose output, will show request to Admin API')
      .group(['no-color', 'q'], 'Options:')
      .help('h');
  }

  _getAdminClientBaseURL () {
    const gatewayConfig = config.gatewayConfig;
    const systemConfig = config.systemConfig;

    let baseURL = 'http://localhost:9876/'; // fallback default

    if (process.env.EG_ADMIN_URL) {
      baseURL = process.env.EG_ADMIN_URL;
    } else if (systemConfig && systemConfig.cli && systemConfig.cli.url) {
      baseURL = systemConfig.cli.url;
    } else if (gatewayConfig && gatewayConfig.admin) {
      const adminConfig = gatewayConfig.admin;
      const hostname = adminConfig.hostname || 'localhost';
      const port = adminConfig.port || 9876;

      baseURL = `http://${hostname}:${port}/`;
    }

    return baseURL;
  }

  _getAdminClientVerboseFlag () {
    let verbose = false; // default

    if (this.argv && this.argv.v) {
      verbose = this.argv.v;
    } else if (config.systemConfig && config.systemConfig.cli) {
      verbose = !!config.systemConfig.cli.verbose;
    }

    return verbose;
  }

  processHeaders (headers) {
    const ArrayHeaders = Array.isArray(headers) ? headers : [headers];

    return ArrayHeaders.reduce((prev, header) => {
      const [headerName, headerValue] = header.split(':');

      if (headerValue) {
        prev[headerName] = headerValue;
      }

      return prev;
    }, {});
  }

  _promptAndValidate (object, schema, { skipPrompt = false } = {}) {
    let questions = [];

    if (!skipPrompt) {
      let shouldPrompt = false;
      const missingProperties = [];
      const modelSchema = find(schema).schema;

      Object.keys(modelSchema.properties).forEach(prop => {
        const descriptor = modelSchema.properties[prop];
        if (!object[prop]) {
          if (!shouldPrompt && modelSchema.required && modelSchema.required.includes(prop)) {
            shouldPrompt = true;
          }

          missingProperties.push({ name: prop, descriptor });
        }
      });

      if (shouldPrompt) {
        questions = missingProperties.map(p => {
          const required = modelSchema.required.includes(p.name)
            ? ' [required]'
            : '';

          return {
            name: p.name,
            message: `Enter ${chalk.yellow(p.name)}${chalk.green(required)}:`,
            default: object[p.name] || p.descriptor.default,
            validate: input => !modelSchema.required.includes(p.name) ||
              (!!input && modelSchema.required.includes(p.name)),
            filter: input => input === '' && !modelSchema.required.includes(p.name) ? undefined : input

          };
        });
      }
    }

    const validateData = data => {
      const { isValid, error } = validate(schema, data);
      if (!isValid) {
        this.log.error(error);
        if (!skipPrompt) {
          return this.prompt(questions).then(validateData);
        }
        throw new Error(error);
      }
      return data;
    };

    return this.prompt(questions).then((answers) => {
      Object.assign(object, answers);
      return validateData(object);
    });
  }
};
<commit_msg>Remove default path from base cli URL<commit_after>const Generator = require('yeoman-generator');
const chalk = require('chalk');
const config = require('../lib/config');
const { validate, find } = require('../lib/schemas');

module.exports = class EgGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this._configuration = null;
    this.eg = this.env.eg;
    this.argv = this.env.argv;
    this.admin = require('../admin')({
      baseUrl: this._getAdminClientBaseURL(),
      verbose: this._getAdminClientVerboseFlag(),
      headers: this.argv && this.argv.H ? this.processHeaders(this.argv.H) : null
    });
  }

  configureCommand (configuration) {
    const builder = configuration.builder;
    configuration.builder = yargs => {
      return this._wrapConfig(builder(yargs));
    };

    configuration.handler = argv => {
      this.env.argv = argv;

      const command = this.options.env.commandAliases[0][argv._[0]];
      const subCommand = this.options.env.commandAliases[1][command][argv._[1]];

      this.env.run(`express-gateway:${command}:${subCommand}`);
    };

    this._configuration = configuration;
  }

  stdout (...args) {
    // eslint-disable-next-line no-console
    console.log.apply(console, args);
  }

  createSubCommand (name) {
    const generatorName = `${this.constructor.namespace}:${name}`;
    return this.env.create(generatorName)._configuration;
  }

  // configuration defaults
  _wrapConfig (yargs) {
    return yargs
      .boolean(['no-color', 'q', 'v'])
      .string(['H'])
      .describe('no-color', 'Disable color in prompts')
      .alias('q', 'quiet')
      .describe('q', 'Only show major pieces of output')
      .describe('H', 'Header to send with each request to Express Gateway Admin API KEY:VALUE format')
      .alias('v', 'verbose')
      .describe('v', 'Verbose output, will show request to Admin API')
      .group(['no-color', 'q'], 'Options:')
      .help('h');
  }

  _getAdminClientBaseURL () {
    const gatewayConfig = config.gatewayConfig;
    const systemConfig = config.systemConfig;

    let baseURL = 'http://localhost:9876'; // fallback default

    if (process.env.EG_ADMIN_URL) {
      baseURL = process.env.EG_ADMIN_URL;
    } else if (systemConfig && systemConfig.cli && systemConfig.cli.url) {
      baseURL = systemConfig.cli.url;
    } else if (gatewayConfig && gatewayConfig.admin) {
      const adminConfig = gatewayConfig.admin;
      const hostname = adminConfig.hostname || 'localhost';
      const port = adminConfig.port || 9876;

      baseURL = `http://${hostname}:${port}`;
    }

    return baseURL;
  }

  _getAdminClientVerboseFlag () {
    let verbose = false; // default

    if (this.argv && this.argv.v) {
      verbose = this.argv.v;
    } else if (config.systemConfig && config.systemConfig.cli) {
      verbose = !!config.systemConfig.cli.verbose;
    }

    return verbose;
  }

  processHeaders (headers) {
    const ArrayHeaders = Array.isArray(headers) ? headers : [headers];

    return ArrayHeaders.reduce((prev, header) => {
      const [headerName, headerValue] = header.split(':');

      if (headerValue) {
        prev[headerName] = headerValue;
      }

      return prev;
    }, {});
  }

  _promptAndValidate (object, schema, { skipPrompt = false } = {}) {
    let questions = [];

    if (!skipPrompt) {
      let shouldPrompt = false;
      const missingProperties = [];
      const modelSchema = find(schema).schema;

      Object.keys(modelSchema.properties).forEach(prop => {
        const descriptor = modelSchema.properties[prop];
        if (!object[prop]) {
          if (!shouldPrompt && modelSchema.required && modelSchema.required.includes(prop)) {
            shouldPrompt = true;
          }

          missingProperties.push({ name: prop, descriptor });
        }
      });

      if (shouldPrompt) {
        questions = missingProperties.map(p => {
          const required = modelSchema.required.includes(p.name)
            ? ' [required]'
            : '';

          return {
            name: p.name,
            message: `Enter ${chalk.yellow(p.name)}${chalk.green(required)}:`,
            default: object[p.name] || p.descriptor.default,
            validate: input => !modelSchema.required.includes(p.name) ||
              (!!input && modelSchema.required.includes(p.name)),
            filter: input => input === '' && !modelSchema.required.includes(p.name) ? undefined : input

          };
        });
      }
    }

    const validateData = data => {
      const { isValid, error } = validate(schema, data);
      if (!isValid) {
        this.log.error(error);
        if (!skipPrompt) {
          return this.prompt(questions).then(validateData);
        }
        throw new Error(error);
      }
      return data;
    };

    return this.prompt(questions).then((answers) => {
      Object.assign(object, answers);
      return validateData(object);
    });
  }
};
<|endoftext|>


<commit_before>"use strict";
var Utils = {
  makeNullProto: function() {
    return {__proto__: null};
  },
  fetchHttpContents: function(url, success) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        success(this.responseText);
      }
    };
    req.send();
    return req;
  },
  _escapeRe: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRe, this._escapeCallback);
  },
  // "javascript" should be treated specially
  _nonUrlPrefixes: { about: 1, blob: 1, data: 1, mailto: 1, "view-source": 1 },
  _chromePrefixes: { "chrome-extension": 1, "chrome-search": 1 },
  _urlPrefix: /^[a-z]{3,}:\/\//,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  // url: only accept real tab's
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads");
    }
    return !url.startsWith(Settings.CONST.ChromeInnerNewTab) && url.startsWith('chrome');
  },
  _nonENTlds: ".\u4e2d\u56fd",
  _tlds: ["", "",
    ".ac.ad.ae.af.ag.ai.al.am.an.ao.aq.ar.as.at.au.aw.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.su.sv.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tp.tr.tt.tv.tw.tz.ua.ug.uk.um.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.yu.za.zm.zw",
    ".biz.cat.com.edu.gov.int.mil.mtn.net.org.pro.tel.top.xxx",
    ".aero.arpa.asia.club.coop.info.jobs.mobi.name.post",
    ".local",
    ".museum.travel"
  ],
  _hostRe: /^([^:]+(:[^:]+)?@)?([^:]+|\[[^\]]+\])(:\d{2,5})?$/,
  _ipRe: /^(?:\d{1,3}\.){3}\d{1,3}$/,
  spacesRe: /[\s\u3000]+/g,
  _nonENTldRe: /[^a-z]/,
  _jsNotEscapeRe: /["\[\]{}\u00ff-\uffff]|%(?![\dA-F]{2}|[\da-f]{2})/,
  filePathRe: /^['"]?((?:[A-Za-z]:[\\/]|\/(?:Users|home|root)\/)[^'"]*)['"]?$/,
  convertToUrl: function(string, keyword) {
    if (string.substring(0, 11).toLowerCase() === "javascript:") {
      if (Settings.CONST.ChromeVersion < 46 && string.indexOf('%', 11) > 0
          && !this._jsNotEscapeRe.test(string)) {
        string = this.decodeURLPart(string);
      }
      return string;
    }
    var type = -1, expected = 1, index, index2, oldString, arr;
    // NOTE: here '\u3000' is changed to ' ', which may cause a 404 (for url)
    // NOTE: here a mulit-line string is be changed to single-line,
    //       which may be better
    oldString = string.replace(this.spacesRe, ' ').trim();
    string = oldString.toLowerCase();
    if ((index = string.indexOf(' ')) > 0) {
      string = string.substring(0, index);
    }
    if ((index = string.indexOf(':')) === 0) { type = 2; }
    else if (index === -1 || string.substring(index, index + 3) !== "://") {
      if (index !== -1 && string.substring(0, index) in this._nonUrlPrefixes) {
        index2 = string.length;
        type = index2 < oldString.length || index2 <= index
          || string.charCodeAt(index + 1) === 47 ? 2 : 0;
      } else if (string.startsWith("//")) {
        string = string.substring(2);
        expected = 3; index2 = 2;
      } else {
        index2 = 0;
      }
      if (type !== -1) {}
      else if ((index = string.indexOf('/')) <= 0) {
        if (index === 0 || string.length < oldString.length - index2) { type = 2; }
      } else if (string.length >= oldString.length - index2 ||
          ((index2 = string.charCodeAt(index + 1)) > 32 && index2 !== 47)) {
        string = string.substring(0, index);
      } else {
        type = 2;
      }
    }
    else if ((index2 = string.indexOf('/', index + 3)) === -1
        ? string.length < oldString.length
        : (expected = string.charCodeAt(index2 + 1), expected <= 32 || expected === 47 )
    ) {
      type = 2;
    }
    else if (this._nonENTldRe.test(string.substring(0, index))) {
      type = (string.substring(0, index) in this._chromePrefixes)
        && (index = string.charCodeAt(index + 3)) > 32 && index !== 47 ? 0 : 2;
    }
    else if (string.startsWith("file:")) {
      if (string.charCodeAt(7) !== 47) {
        type = 2;
      } else {
        index = string.charCodeAt(8);
        type = (index > 32 && index !== 47) ? 0 : 2; // `>32`: in case of NaN
      }
    }
    else if (string.startsWith("chrome:")) {
      type = string.length < oldString.length && string.indexOf('/', 9) === -1 ? 2 : 0;
    }
    else if (string.startsWith("vimium:")) {
      type = 0;
      oldString = chrome.runtime.getURL("/") + oldString.substring(9);
    } else {
      string = string.substring(index + 3, index2 !== -1 ? index2 : undefined);
      expected = 0;
    }

    if (type !== -1) {
    } else if (!(arr = this._hostRe.exec(string))) {
      type = 2;
    } else if ((string = arr[3]).indexOf(':') !== -1 || string.endsWith("localhost")) {
      type = expected;
    } else if ((index = string.lastIndexOf('.')) <= 0) {
      type = expected !== 1 ? expected : 2;
    } else if (this._ipRe.test(string)) {
      type = expected;
    } else if (!this.isTld(string.substring(index + 1))) {
      type = 2;
    } else if (expected !== 1 || string.length < oldString.length) {
      type = expected;
    } else if (arr[2] || arr[4] || !arr[1] || string.startsWith("ftp")) {
      type = 1;
    // the below means string is like "(?<=abc@)(uvw.)*xyz.tld"
    } else if (string.startsWith("mail") || string.indexOf(".mail") > 0
        || (index2 = string.indexOf(".")) === index) {
      type = 2;
    } else if (string.indexOf(".", ++index2) !== index) {
      type = 1;
    } else {
      type = this.isTld(string.substring(index2, index)) ? 2 : 1;
    }
    // window.type = type;
    return type === 0 ? oldString : type === 1
      ? ("http://" + oldString) : type === 3 ? ("http:" + oldString)
      : this.createSearchUrl(oldString.split(' '), keyword || "~");
  },
  isTld: function(tld) {
    if (this._nonENTldRe.test(tld)) {
      return this._nonENTlds.indexOf(tld) !== -1;
    } else if (tld.length < this._tlds.length) {
      return this._tlds[tld.length].indexOf(tld) > 0;
    }
    return false;
  },
  searchWordRe: /%[sS]/g,
  createSearchUrl: function(query, keyword) {
    query = this.createSearch(query, Settings.get("searchEnginesMap")[keyword]).url;
    if (keyword != "~") {
      query = this.convertToUrl(query);
    }
    return query;
  },
  createSearch: function(query, pattern, $S) {
    var queryStr;
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      queryStr = query.map(encodeURIComponent).join('+');
    }
    return {
      url: pattern.url.replace(this.searchWordRe, function(s) {
        return (s === "%s") ? queryStr : $S;
      }),
      $s: queryStr,
      $S: $S
    };
  },
  decodeURLPart: function(url) {
    try {
      url = decodeURIComponent(url);
    } catch (e) {}
    return url;
  },
  parseSearchEngines: function(searchEnginesText, map) {
    var a, pairs, key, val, name, obj, _i, _len, ind, func, //
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g;
    a = searchEnginesText.replace(/\\\n/g, '').split('\n');
    func = function(key) {
      return (key = key.trim()) && (map[key] = obj);
    };
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      ind = 0;
      do {
        ind = val.indexOf(":", ind + 1);
      } while (val.charCodeAt(ind - 1)  === 92);
      if (ind <= 0 || !(key = val.substring(0, ind).trimRight())) continue;
      val = val.substring(ind + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      ind = val.search(rSpace);
      if (ind > 0) {
        name = val.substring(ind + 1).trimLeft();
        val = val.substring(0, ind);
      } else {
        name = "";
      }
      val = val.replace(rEscapeS, " ");
      obj = {
        $S: val.indexOf("%S") + 1,
        $s: val.indexOf("%s") + 1,
        name: null,
        url: val
      };
      pairs = key.replace(rColon, ":").split('|').filter(func);
      if (pairs.length === 0) continue;
      key = pairs[0];
      obj.name = name ? this.decodeURLPart(name) : pairs[pairs.length - 1];
      if (pairs = this.reparseSearchUrl(obj)) {
        pairs.push(key);
        map[""].push(pairs);
      }
    }
  },
  reparseSearchUrl: function (pattern) {
    var url, ind = pattern.$s || pattern.$S, prefix;
    if (!ind) { return; }
    url = pattern.url.toLowerCase();
    if (!(this.hasOrdinaryUrlPrefix(url) || url.startsWith("chrome-"))) { return; }
    url = url.substring(0, ind - 1);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      prefix = url.substring(0, ind - 1);
      url = url.substring(ind);
      if (ind = url.lastIndexOf("&") + 1) {
        url = url.substring(ind);
      }
      if (url && url !== "=" && !url.endsWith("/")) {
        return this.makeReparser(prefix, "[?#&]", url, "([^&#]*)")
      }
      url = pattern.url.substring(0, (pattern.$s || pattern.$S) - 1);
    }
    prefix = url;
    url = pattern.url.substring(url.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    return this.makeReparser(prefix, "^([^?#]*)", url, "");
  },
  escapeAllRe: /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
  makeReparser: function(head, prefix, url, suffix) {
    url = url.toLowerCase().replace(this.escapeAllRe, "\\$&");
    if (head.startsWith("https://")) {
      head = "http" + head.substring(5);
    } else if (head.toLowerCase().startsWith("vimium://")) {
      head = chrome.runtime.getURL("/") + head.substring(9);
    }
    return [head, new RegExp(prefix + url + suffix, "i")];
  },
  Decoder: null,
  upperRe: /[A-Z]/
};

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s) {
  return this.length >= s.length && this.lastIndexOf(s, 0) === 0;
};
String.prototype.endsWith || (String.prototype.endsWith = function(s) {
  var i = this.length - s.length;
  return i >= 0 && this.indexOf(s, i) === i;
});
}
<commit_msg>noop: rename a variable<commit_after>"use strict";
var Utils = {
  makeNullProto: function() {
    return {__proto__: null};
  },
  fetchHttpContents: function(url, success) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        success(this.responseText);
      }
    };
    req.send();
    return req;
  },
  _escapeRe: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRe, this._escapeCallback);
  },
  // "javascript" should be treated specially
  _nonUrlPrefixes: { about: 1, blob: 1, data: 1, mailto: 1, "view-source": 1 },
  _chromePrefixes: { "chrome-extension": 1, "chrome-search": 1 },
  _urlPrefix: /^[a-z]{3,}:\/\//,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  // url: only accept real tab's
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads");
    }
    return !url.startsWith(Settings.CONST.ChromeInnerNewTab) && url.startsWith('chrome');
  },
  _nonENTlds: ".\u4e2d\u56fd",
  _tlds: ["", "",
    ".ac.ad.ae.af.ag.ai.al.am.an.ao.aq.ar.as.at.au.aw.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.su.sv.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tp.tr.tt.tv.tw.tz.ua.ug.uk.um.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.yu.za.zm.zw",
    ".biz.cat.com.edu.gov.int.mil.mtn.net.org.pro.tel.top.xxx",
    ".aero.arpa.asia.club.coop.info.jobs.mobi.name.post",
    ".local",
    ".museum.travel"
  ],
  _hostRe: /^([^:]+(:[^:]+)?@)?([^:]+|\[[^\]]+\])(:\d{2,5})?$/,
  _ipRe: /^(?:\d{1,3}\.){3}\d{1,3}$/,
  spacesRe: /[\s\u3000]+/g,
  _nonENTldRe: /[^a-z]/,
  _jsNotEscapeRe: /["\[\]{}\u00ff-\uffff]|%(?![\dA-F]{2}|[\da-f]{2})/,
  filePathRe: /^['"]?((?:[A-Za-z]:[\\/]|\/(?:Users|home|root)\/)[^'"]*)['"]?$/,
  convertToUrl: function(string, keyword) {
    if (string.substring(0, 11).toLowerCase() === "javascript:") {
      if (Settings.CONST.ChromeVersion < 46 && string.indexOf('%', 11) > 0
          && !this._jsNotEscapeRe.test(string)) {
        string = this.decodeURLPart(string);
      }
      return string;
    }
    var type = -1, expected = 1, index, index2, oldString, arr;
    // NOTE: here '\u3000' is changed to ' ', which may cause a 404 (for url)
    // NOTE: here a mulit-line string is be changed to single-line,
    //       which may be better
    oldString = string.replace(this.spacesRe, ' ').trim();
    string = oldString.toLowerCase();
    if ((index = string.indexOf(' ')) > 0) {
      string = string.substring(0, index);
    }
    if ((index = string.indexOf(':')) === 0) { type = 2; }
    else if (index === -1 || string.substring(index, index + 3) !== "://") {
      if (index !== -1 && string.substring(0, index) in this._nonUrlPrefixes) {
        index2 = string.length;
        type = index2 < oldString.length || index2 <= index
          || string.charCodeAt(index + 1) === 47 ? 2 : 0;
      } else if (string.startsWith("//")) {
        string = string.substring(2);
        expected = 3; index2 = 2;
      } else {
        index2 = 0;
      }
      if (type !== -1) {}
      else if ((index = string.indexOf('/')) <= 0) {
        if (index === 0 || string.length < oldString.length - index2) { type = 2; }
      } else if (string.length >= oldString.length - index2 ||
          ((index2 = string.charCodeAt(index + 1)) > 32 && index2 !== 47)) {
        string = string.substring(0, index);
      } else {
        type = 2;
      }
    }
    else if ((index2 = string.indexOf('/', index + 3)) === -1
        ? string.length < oldString.length
        : (expected = string.charCodeAt(index2 + 1), expected <= 32 || expected === 47 )
    ) {
      type = 2;
    }
    else if (this._nonENTldRe.test(string.substring(0, index))) {
      type = (string.substring(0, index) in this._chromePrefixes)
        && (index = string.charCodeAt(index + 3)) > 32 && index !== 47 ? 0 : 2;
    }
    else if (string.startsWith("file:")) {
      if (string.charCodeAt(7) !== 47) {
        type = 2;
      } else {
        index = string.charCodeAt(8);
        type = (index > 32 && index !== 47) ? 0 : 2; // `>32`: in case of NaN
      }
    }
    else if (string.startsWith("chrome:")) {
      type = string.length < oldString.length && string.indexOf('/', 9) === -1 ? 2 : 0;
    }
    else if (string.startsWith("vimium:")) {
      type = 0;
      oldString = chrome.runtime.getURL("/") + oldString.substring(9);
    } else {
      string = string.substring(index + 3, index2 !== -1 ? index2 : undefined);
      expected = 0;
    }

    if (type !== -1) {
    } else if (!(arr = this._hostRe.exec(string))) {
      type = 2;
    } else if ((string = arr[3]).indexOf(':') !== -1 || string.endsWith("localhost")) {
      type = expected;
    } else if ((index = string.lastIndexOf('.')) <= 0) {
      type = expected !== 1 ? expected : 2;
    } else if (this._ipRe.test(string)) {
      type = expected;
    } else if (!this.isTld(string.substring(index + 1))) {
      type = 2;
    } else if (expected !== 1 || string.length < oldString.length) {
      type = expected;
    } else if (arr[2] || arr[4] || !arr[1] || string.startsWith("ftp")) {
      type = 1;
    // the below means string is like "(?<=abc@)(uvw.)*xyz.tld"
    } else if (string.startsWith("mail") || string.indexOf(".mail") > 0
        || (index2 = string.indexOf(".")) === index) {
      type = 2;
    } else if (string.indexOf(".", ++index2) !== index) {
      type = 1;
    } else {
      type = this.isTld(string.substring(index2, index)) ? 2 : 1;
    }
    // window.type = type;
    return type === 0 ? oldString : type === 1
      ? ("http://" + oldString) : type === 3 ? ("http:" + oldString)
      : this.createSearchUrl(oldString.split(' '), keyword || "~");
  },
  isTld: function(tld) {
    if (this._nonENTldRe.test(tld)) {
      return this._nonENTlds.indexOf(tld) !== -1;
    } else if (tld.length < this._tlds.length) {
      return this._tlds[tld.length].indexOf(tld) > 0;
    }
    return false;
  },
  searchWordRe: /%[sS]/g,
  createSearchUrl: function(query, keyword) {
    query = this.createSearch(query, Settings.get("searchEnginesMap")[keyword]).url;
    if (keyword != "~") {
      query = this.convertToUrl(query);
    }
    return query;
  },
  createSearch: function(query, pattern, $S) {
    var queryStr;
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      queryStr = query.map(encodeURIComponent).join('+');
    }
    return {
      url: pattern.url.replace(this.searchWordRe, function(s) {
        return (s === "%s") ? queryStr : $S;
      }),
      $s: queryStr,
      $S: $S
    };
  },
  decodeURLPart: function(url) {
    try {
      url = decodeURIComponent(url);
    } catch (e) {}
    return url;
  },
  parseSearchEngines: function(searchEnginesText, map) {
    var a, pairs, key, val, str, obj, _i, _len, ind, func, //
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g;
    a = searchEnginesText.replace(/\\\n/g, '').split('\n');
    func = function(key) {
      return (key = key.trim()) && (map[key] = obj);
    };
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      ind = 0;
      do {
        ind = val.indexOf(":", ind + 1);
      } while (val.charCodeAt(ind - 1)  === 92);
      if (ind <= 0 || !(key = val.substring(0, ind).trimRight())) continue;
      val = val.substring(ind + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      ind = val.search(rSpace);
      if (ind > 0) {
        str = val.substring(ind + 1).trimLeft();
        val = val.substring(0, ind);
      } else {
        str = "";
      }
      val = val.replace(rEscapeS, " ");
      obj = {
        $S: val.indexOf("%S") + 1,
        $s: val.indexOf("%s") + 1,
        name: null,
        url: val
      };
      pairs = key.replace(rColon, ":").split('|').filter(func);
      if (pairs.length === 0) continue;
      key = pairs[0];
      obj.name = str ? this.decodeURLPart(str) : pairs[pairs.length - 1];
      if (pairs = this.reparseSearchUrl(obj)) {
        pairs.push(key);
        map[""].push(pairs);
      }
    }
  },
  reparseSearchUrl: function (pattern) {
    var url, ind = pattern.$s || pattern.$S, prefix;
    if (!ind) { return; }
    url = pattern.url.toLowerCase();
    if (!(this.hasOrdinaryUrlPrefix(url) || url.startsWith("chrome-"))) { return; }
    url = url.substring(0, ind - 1);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      prefix = url.substring(0, ind - 1);
      url = url.substring(ind);
      if (ind = url.lastIndexOf("&") + 1) {
        url = url.substring(ind);
      }
      if (url && url !== "=" && !url.endsWith("/")) {
        return this.makeReparser(prefix, "[?#&]", url, "([^&#]*)")
      }
      url = pattern.url.substring(0, (pattern.$s || pattern.$S) - 1);
    }
    prefix = url;
    url = pattern.url.substring(url.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    return this.makeReparser(prefix, "^([^?#]*)", url, "");
  },
  escapeAllRe: /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
  makeReparser: function(head, prefix, url, suffix) {
    url = url.toLowerCase().replace(this.escapeAllRe, "\\$&");
    if (head.startsWith("https://")) {
      head = "http" + head.substring(5);
    } else if (head.toLowerCase().startsWith("vimium://")) {
      head = chrome.runtime.getURL("/") + head.substring(9);
    }
    return [head, new RegExp(prefix + url + suffix, "i")];
  },
  Decoder: null,
  upperRe: /[A-Z]/
};

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s) {
  return this.length >= s.length && this.lastIndexOf(s, 0) === 0;
};
String.prototype.endsWith || (String.prototype.endsWith = function(s) {
  var i = this.length - s.length;
  return i >= 0 && this.indexOf(s, i) === i;
});
}
<|endoftext|>


<commit_before>//@flow
import React from "react";

import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../linkedin-icon";
import { OctocatIcon } from "../octocat-icon";
import { Highlight } from "../highlight";
import { Chevron } from "../chevron";
import Bubble from "../bubble";
import addActiveState from "../../global/hoc/addActiveState";

const ActiveLi = addActiveState(Li);

type props = {};

export const MainNav = (props: {}) =>
  <Nav {...props}>
    <Ul {...props}>
      <ActiveLi>
        <Highlight url="/">Projects</Highlight>
      </ActiveLi>
      <ActiveLi><Highlight url="/">About</Highlight></ActiveLi>
      <ActiveLi>
        <Chevron>Download</Chevron>
        <Bubble
          textItems={[
            { label: "Resume", target: "#" },
            { label: "Portfolio", target: "#" }
          ]}
        />
      </ActiveLi>
      <ActiveLi><Highlight url="/">Contact</Highlight></ActiveLi>
    </Ul>
    <Ul {...props}>
      <ActiveLi><LinkedInIcon /></ActiveLi>
      <ActiveLi><OctocatIcon /></ActiveLi>
    </Ul>

  </Nav>;
<commit_msg>Prettier reformat<commit_after>//@flow
import React from "react";

import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../linkedin-icon";
import { OctocatIcon } from "../octocat-icon";
import { Highlight } from "../highlight";
import { Chevron } from "../chevron";
import Bubble from "../bubble";
import addActiveState from "../../global/hoc/addActiveState";

const ActiveLi = addActiveState(Li);

type props = {};

export const MainNav = (props: {}) =>
  <Nav {...props}>
    <Ul {...props}>
      <ActiveLi>
        <Highlight url="/">Projects</Highlight>
      </ActiveLi>
      <ActiveLi>
        <Highlight url="/">About</Highlight>
      </ActiveLi>
      <ActiveLi>
        <Chevron>Download</Chevron>
        <Bubble
          textItems={[
            { label: "Resume", target: "#" },
            { label: "Portfolio", target: "#" }
          ]}
        />
      </ActiveLi>
      <ActiveLi>
        <Highlight url="/">Contact</Highlight>
      </ActiveLi>
    </Ul>
    <Ul {...props}>
      <ActiveLi>
        <LinkedInIcon />
      </ActiveLi>
      <ActiveLi>
        <OctocatIcon />
      </ActiveLi>
    </Ul>
  </Nav>;
<|endoftext|>