<commit_before>// Define outerHtml method for jQuery since we need to give openlayers plain html
// http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html
// Elements outerHtml property only works on IE and chrome
jQuery.fn.outerHTML = function (arg) {
    var ret;

    // If no items in the collection, return
    if (!this.length)
        return typeof val == "undefined" ? this : null;
    // Getter overload (no argument passed)
    if (!arg) {
        return this[0].outerHTML ||
            (ret = this.wrap('
').parent().html(), this.unwrap(), ret);
    }
    // Setter overload
    jQuery.each(this, function (i, el) {
        var fnRet,
            pass = el,
            inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";

        if (!el.outerHTML)
            el = jQuery(el).wrap('
').parent()[0];

        if (jQuery.isFunction(arg)) {
            if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
                el[inOrOut] = fnRet;
        }
        else
            el[inOrOut] = arg;

        if (!el.outerHTML)
            jQuery(el).children().unwrap();
    });

    return this;
};

/**
 * @class Oskari.harava.bundle.infobox.plugin.mapmodule.OpenlayersPopupPlugin
 *
 * Provides a customized popup functionality for Openlayers map.
 */
Oskari.clazz.define('Oskari.harava.bundle.haravaInfobox.plugin.mapmodule.OpenlayersPopupPlugin',

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this.mapModule = null;
    this.pluginName = null;
    this._sandbox = null;
    this._map = null;
    this._popups ={};
}, {
	/**
	 * @static
	 * @property __name
	 */
    __name : 'HaravaOpenLayersPopupPlugin',

	/**
	 * @method getName
	 * @return {String} the name for the component
	 */
    getName : function() {
        return this.pluginName;
    },
    /**
     * @method getMapModule
     * @return {Oskari.mapframework.ui.module.common.MapModule} reference to map
     * module
     */
    getMapModule : function() {
        return this.mapModule;
    },
    /**
     * @method setMapModule
     * @param {Oskari.mapframework.ui.module.common.MapModule} reference to map
     * module
     */
    setMapModule : function(mapModule) {
        this.mapModule = mapModule;
        this._map = mapModule.getMap();
        this.pluginName = mapModule.getName() + this.__name;
    },
	/**
	 * @method init
	 * implements Module protocol init method - declares popup templates
	 */
    init : function() {
        var me = this;

		// templates
		this._arrow =  jQuery('

');
    	this._header = jQuery('

');
    	this._headerWrapper = jQuery('

');
    	this._headerCloseButton = jQuery('

');
    	this._contentDiv = jQuery('

');
    	this._contentWrapper = jQuery('

');
    	this._actionLink = jQuery('');
        this._actionButton = jQuery('<input type="button" />');
    	this._contentSeparator = jQuery('
separator
');
    },

    /**
     * @method popup
     * @param {String} id
     * 		id for popup so we can use additional requests to control it
     * @param {String} title
     * 		popup title
     * @param {Object[]} contentData
     * 		JSON presentation for the popup data
     * @param {OpenLayers.LonLat} lonlat
     * 		coordinates where to show the popup
     * @param {Boolean} hidePrevious
     * 		hide previous popups
     * @param {Integer} width
     * 		popup width
     * @param {Integer} height
     * 		popup height
     * @param {Boolean} centerMap
     * 		if true, centers map to selected coordinates
     *
     * Displays a popup with given title and data in the given coordinates.
     *
     * contentData format example:
     * [{
	 * 	html: "",
     *  useButtons: true,
     *  primaryButton: "<button label>",
	 *  actions : {
	 * 	   "Tallenna" : callbackFunction,
	 * 	   "Sulje" : callbackFunction
	 * }
	 * }]
     */
    popup : function(id, title, contentData, lonlat, hidePrevious, width, height, centerMap) {
    	var me = this;

    	var arrow = this._arrow.clone();
    	var header = this._header.clone();
    	var headerWrapper = this._headerWrapper.clone();
    	var contentDiv = this._contentDiv.clone();
    	var closeButton = this._headerCloseButton.clone();

    	var size = this._map.getCurrentSize();
        var mapWidth = size.w;
        var mapHeight = size.h;

        // Check if map is over than 900 x 400 pixels bigger then we can change also info to bigger
        if(mapWidth>900 && mapHeight>400){
        	if(width<400){
        		width = 400;
        	}
        	if(height<250){
        		height = 250;
        	}
        }

    	header.append(title);
    	headerWrapper.append(header);
    	headerWrapper.append(closeButton);

    	for(var i =0;i < contentData.length;i++) {
    		if(i != 0) {
		  		contentDiv.append(this._contentSeparator.clone());
    		}
		    var html = contentData[i].html;
		  	var contentWrapper = this._contentWrapper.clone();
		  	contentWrapper.append(html);
		  	var action = contentData[i].actions;
            var useButtons = (contentData[i].useButtons == true);
            var primaryButton = contentData[i].primaryButton;
		  	for(var key in action){
	            var attrName = key;
	            var attrValue = action[key];
	            var actionLink = null;
	            if(useButtons) {
	               actionLink = this._actionButton.clone();
                   var btn = actionLink.find('input');
                   btn.attr('contentdata', i);
                   btn.attr('value', attrName);
                   if(attrName == primaryButton) {
                       btn.addClass('primary');
                   }
	            }
	            else {
                   actionLink = this._actionLink.clone();
                   var link = actionLink.find('a');
                   link.attr('contentdata', i);
                   link.append(attrName);
	            }
	            contentWrapper.append(actionLink);
        	}
		  	contentDiv.append(contentWrapper);
		}

    	var openlayersMap = this.getMapModule().getMap();

    	if(openlayersMap.popups!=null && openlayersMap.popups.length>0 && hidePrevious){
    		for(var i=0;i<openlayersMap.popups.length;i++){
    			var pop = openlayersMap.popups[i];
    			openlayersMap.removePopup(pop);
    		}
    	}
    	var popup = new OpenLayers.Popup(
                id,
                new OpenLayers.LonLat(lonlat.lon,lonlat.lat),
                new OpenLayers.Size(width,height),
                arrow.outerHTML() +
                headerWrapper.outerHTML()+
                contentDiv.outerHTML(),
                false
            );

        popup.moveTo = function(px) {
        	if ((px != null) && (this.div != null)) {
            	this.div.style.left = px.x + "px";
            	var topy = px.y-20;
            	this.div.style.top = topy + "px";
        	}
    	};

		popup.setBackgroundColor('transparent');
		this._popups[id] = {
		    title : title,
		    contentData : contentData,
		    lonlat : lonlat,
		    popup : popup
		}
		jQuery(popup.div).css('overflow','visible');
		jQuery(popup.groupDiv).css('overflow','visible');
		// override
		popup.events.un({
			"click": popup.onclick,
			scope: popup
		});

		popup.events.on({
			"click": function(evt) {
				var link = jQuery(evt.target||evt.srcElement);
				if (link.hasClass('olPopupCloseBox')) { // Close button
					me.close(id);
				} else { // Action links
					var i = link.attr('contentdata');
                    //var text = link.html();
					var text = link.attr('value');
					if(!text) {
					    text = link.html();
					}
					if(contentData[i] && contentData[i].actions && contentData[i].actions[text]) {
						contentData[i].actions[text]();
					}
				}
			},
			scope: popup
		});

		openlayersMap.addPopup(popup);

		// set popup styles
		var arrowWidth =parseInt($('div.popupHeaderArrow').css('borderRightWidth'),10);
		var titleHeight = jQuery('div.popupHeader').height();
		jQuery('div.popupHeader').width(width-arrowWidth);
		jQuery('div.popupContent').height(height-titleHeight);

		if(centerMap){
			this._centerMapToSelectedCoordinate(lonlat,width,height);
		} else {
			this._panMapToShowPopup(lonlat,width,height);
		}

    },
    /**
     * @method _centerMapToSelectedCoordinate
     * @private
     * Centers map to popup position
     * @param {OpenLayers.LonLat} lonlat where to show the popup
     * @param {Integer} popupWidthPx,  popup width in pixels
     * @param {Integer} popupHeightPx, popup height in pixels
     */
    _centerMapToSelectedCoordinate: function(lonlat,popupWidthPx,popupHeightPx){
    	var popupPixels = this._map.getPixelFromLonLat(lonlat);
    	var mapCenterPixels = this._map.getPixelFromLonLat(this._map.getCenter());

    	var offset = 10;
    	var infoboxWidth = popupWidthPx + offset;
        var infoboxHeight = popupHeightPx + offset;
        var size = this._map.getCurrentSize();
        var width = size.w;
        var height = size.h;

        var point = {
        		x: popupPixels.x,
        		y: popupPixels.y
        };
        var popupLonLat =this._map.getLonLatFromPixel(point);
        this._map.setCenter(popupLonLat);
        this.getMapModule()._updateDomain();
    },
    /**
     * @method _panMapToShowPopup
     * @private
     * Pans map to show popup
     * @param {OpenLayers.LonLat} lonlat where to show the popup
     * @param {Integer} popupWidthPx,  popup width in pixels
     * @param {Integer} popupHeightPx, popup height in pixels
     */
    _panMapToShowPopup : function(lonlat, popupWidthPx, popupHeightPx) {
        var pixels = this._map.getViewPortPxFromLonLat(lonlat);
        var size = this._map.getCurrentSize();
        var width = size.w;
        var height = size.h;
        // if infobox would be out of screen
        // -> move map to make infobox visible on screen
        var panx = 0;
        var pany = 0;
        var popupMarginWidthPx = 15;
        var popupMarginHeightPx = 10;
        var infoboxWidth = popupWidthPx+popupMarginWidthPx;
        var infoboxHeight = popupHeightPx+popupMarginHeightPx;
        if( pixels.x + infoboxWidth > width) {
            panx = width - (pixels.x + infoboxWidth);
        }
        if( pixels.y + infoboxHeight > height) {
            pany = height - (pixels.y + infoboxHeight);
        }
        // check that we are not "over the top"
        else if(pixels.y < 25) {
            pany = 25;
        }
        if(panx != 0 || pany != 0) {
            this.getMapModule().panMapByPixels(-panx, -pany);
        }

    },
    /**
     * @method close
     * @param {String} id
     * 		id for popup that we want to close (optional - if not given, closes all popups)
     */
    close : function(id) {
    	// destroys all if id not given
    	// deletes reference to the same id will work next time also
        if(!id) {
            for(var pid in this._popups) {
    			this._popups[pid].popup.destroy();
    			delete this._popups[pid];
            }
            return;
        }
        // id specified, delete only single popup
        if(this._popups[id]) {
            if(this._popups[id].popup) {
                this._popups[id].popup.destroy();
            }
            delete this._popups[id];
        }
        // else notify popup not found?
    },
    /**
     * @method getPopups
     * Returns references to popups that are currently open
     * @return {Object}
     */
    getPopups : function() {
        return this._popups;
    },

    /**
     * @method register
     * mapmodule.Plugin protocol method - does nothing atm
     */
    register : function() {

    },
    /**
     * @method unregister
     * mapmodule.Plugin protocol method - does nothing atm
     */
    unregister : function() {
    },
    /**
     * @method startPlugin
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * mapmodule.Plugin protocol method.
     * Sets sandbox and registers self to sandbox
     */
    startPlugin : function(sandbox) {
        this._sandbox = sandbox;
        sandbox.register(this);

    },
    /**
     * @method stopPlugin
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * mapmodule.Plugin protocol method.
     * Unregisters self from sandbox
     */
    stopPlugin : function(sandbox) {

        sandbox.unregister(this);

        this._map = null;
        this._sandbox = null;
    },
    /**
     * @method start
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * Module protocol method - does nothing atm
     */
    start : function(sandbox) {
    },
    /**
     * @method stop
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * Module protocol method - does nothing atm
     */
    stop : function(sandbox) {
    }
}, {
	/**
	 * @property {String[]} protocol
	 * @static
	 */
    'protocol' : ["Oskari.mapframework.module.Module", "Oskari.mapframework.ui.module.common.mapmodule.Plugin"]
});
<commit_msg>Korjattu IE8 sopivuutta popuppiin<commit_after>// Define outerHtml method for jQuery since we need to give openlayers plain html
// http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html
// Elements outerHtml property only works on IE and chrome
jQuery.fn.outerHTML = function (arg) {
    var ret;

    // If no items in the collection, return
    if (!this.length)
        return typeof val == "undefined" ? this : null;
    // Getter overload (no argument passed)
    if (!arg) {
        return this[0].outerHTML ||
            (ret = this.wrap('
').parent().html(), this.unwrap(), ret);
    }
    // Setter overload
    jQuery.each(this, function (i, el) {
        var fnRet,
            pass = el,
            inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";

        if (!el.outerHTML)
            el = jQuery(el).wrap('
').parent()[0];

        if (jQuery.isFunction(arg)) {
            if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
                el[inOrOut] = fnRet;
        }
        else
            el[inOrOut] = arg;

        if (!el.outerHTML)
            jQuery(el).children().unwrap();
    });

    return this;
};

/**
 * @class Oskari.harava.bundle.infobox.plugin.mapmodule.OpenlayersPopupPlugin
 *
 * Provides a customized popup functionality for Openlayers map.
 */
Oskari.clazz.define('Oskari.harava.bundle.haravaInfobox.plugin.mapmodule.OpenlayersPopupPlugin',

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this.mapModule = null;
    this.pluginName = null;
    this._sandbox = null;
    this._map = null;
    this._popups ={};
}, {
	/**
	 * @static
	 * @property __name
	 */
    __name : 'HaravaOpenLayersPopupPlugin',

	/**
	 * @method getName
	 * @return {String} the name for the component
	 */
    getName : function() {
        return this.pluginName;
    },
    /**
     * @method getMapModule
     * @return {Oskari.mapframework.ui.module.common.MapModule} reference to map
     * module
     */
    getMapModule : function() {
        return this.mapModule;
    },
    /**
     * @method setMapModule
     * @param {Oskari.mapframework.ui.module.common.MapModule} reference to map
     * module
     */
    setMapModule : function(mapModule) {
        this.mapModule = mapModule;
        this._map = mapModule.getMap();
        this.pluginName = mapModule.getName() + this.__name;
    },
	/**
	 * @method init
	 * implements Module protocol init method - declares popup templates
	 */
    init : function() {
        var me = this;

		// templates
		this._arrow =  jQuery('

');
    	this._header = jQuery('

');
    	this._headerWrapper = jQuery('

');
    	this._headerCloseButton = jQuery('

');
    	this._contentDiv = jQuery('

');
    	this._contentWrapper = jQuery('

');
    	this._actionLink = jQuery('');
        this._actionButton = jQuery('<input type="button" />');
    	this._contentSeparator = jQuery('
separator
');
    },

    /**
     * @method popup
     * @param {String} id
     * 		id for popup so we can use additional requests to control it
     * @param {String} title
     * 		popup title
     * @param {Object[]} contentData
     * 		JSON presentation for the popup data
     * @param {OpenLayers.LonLat} lonlat
     * 		coordinates where to show the popup
     * @param {Boolean} hidePrevious
     * 		hide previous popups
     * @param {Integer} width
     * 		popup width
     * @param {Integer} height
     * 		popup height
     * @param {Boolean} centerMap
     * 		if true, centers map to selected coordinates
     *
     * Displays a popup with given title and data in the given coordinates.
     *
     * contentData format example:
     * [{
	 * 	html: "",
     *  useButtons: true,
     *  primaryButton: "<button label>",
	 *  actions : {
	 * 	   "Tallenna" : callbackFunction,
	 * 	   "Sulje" : callbackFunction
	 * }
	 * }]
     */
    popup : function(id, title, contentData, lonlat, hidePrevious, width, height, centerMap) {
    	var me = this;

    	var arrow = this._arrow.clone();
    	var header = this._header.clone();
    	var headerWrapper = this._headerWrapper.clone();
    	var contentDiv = this._contentDiv.clone();
    	var closeButton = this._headerCloseButton.clone();

    	var size = this._map.getCurrentSize();
        var mapWidth = size.w;
        var mapHeight = size.h;

        // Check if map is over than 900 x 400 pixels bigger then we can change also info to bigger
        if(mapWidth>900 && mapHeight>400){
        	if(width<400){
        		width = 400;
        	}
        	if(height<250){
        		height = 250;
        	}
        }

    	header.append(title);
    	headerWrapper.append(header);
    	headerWrapper.append(closeButton);

    	for(var i =0;i < contentData.length;i++) {
    		if(i != 0) {
		  		contentDiv.append(this._contentSeparator.clone());
    		}
		    var html = contentData[i].html;
		  	var contentWrapper = this._contentWrapper.clone();
		  	contentWrapper.append(html);
		  	var action = contentData[i].actions;
            var useButtons = (contentData[i].useButtons == true);
            var primaryButton = contentData[i].primaryButton;
		  	for(var key in action){
	            var attrName = key;
	            var attrValue = action[key];
	            var actionLink = null;
	            if(useButtons) {
	               actionLink = this._actionButton.clone();
                   var btn = actionLink.find('input');
                   btn.attr('contentdata', i);
                   btn.attr('value', attrName);
                   if(attrName == primaryButton) {
                       btn.addClass('primary');
                   }
	            }
	            else {
                   actionLink = this._actionLink.clone();
                   var link = actionLink.find('a');
                   link.attr('contentdata', i);
                   link.append(attrName);
	            }
	            contentWrapper.append(actionLink);
        	}
		  	contentDiv.append(contentWrapper);
		}

    	var openlayersMap = this.getMapModule().getMap();

    	if(openlayersMap.popups!=null && openlayersMap.popups.length>0 && hidePrevious){
    		for(var i=0;i<openlayersMap.popups.length;i++){
    			var pop = openlayersMap.popups[i];
    			openlayersMap.removePopup(pop);
    		}
    	}
    	var popup = new OpenLayers.Popup(
                id,
                new OpenLayers.LonLat(lonlat.lon,lonlat.lat),
                new OpenLayers.Size(width,height),
                arrow.outerHTML() +
                headerWrapper.outerHTML()+
                contentDiv.outerHTML(),
                false
            );

        popup.moveTo = function(px) {
        	if ((px != null) && (this.div != null)) {
            	this.div.style.left = px.x + "px";
            	var topy = px.y-20;
            	this.div.style.top = topy + "px";
        	}
    	};

		popup.setBackgroundColor('transparent');
		this._popups[id] = {
		    title : title,
		    contentData : contentData,
		    lonlat : lonlat,
		    popup : popup
		}
		jQuery(popup.div).css('overflow','visible');
		jQuery(popup.groupDiv).css('overflow','visible');
		// override
		popup.events.un({
			"click": popup.onclick,
			scope: popup
		});

		popup.events.on({
			"click": function(evt) {
				var link = jQuery(evt.target||evt.srcElement);
				if (link.hasClass('olPopupCloseBox')) { // Close button
					me.close(id);
				} else { // Action links
					var i = link.attr('contentdata');
                    //var text = link.html();
					var text = link.attr('value');
					if(!text) {
					    text = link.html();
					}
					if(contentData[i] && contentData[i].actions && contentData[i].actions[text]) {
						contentData[i].actions[text]();
					}
				}
			},
			scope: popup
		});

		openlayersMap.addPopup(popup);

		// set popup styles
		var arrowWidth =parseInt($('div.popupHeaderArrow').css('borderRightWidth'),10);
		var titleHeight = jQuery('div.popupHeader').height();
		jQuery('div.popupHeader').width(width-arrowWidth);
		jQuery('div.popupContent').height(height-titleHeight-12);

		if(centerMap){
			this._centerMapToSelectedCoordinate(lonlat,width,height);
		} else {
			this._panMapToShowPopup(lonlat,width,height);
		}

    },
    /**
     * @method _centerMapToSelectedCoordinate
     * @private
     * Centers map to popup position
     * @param {OpenLayers.LonLat} lonlat where to show the popup
     * @param {Integer} popupWidthPx,  popup width in pixels
     * @param {Integer} popupHeightPx, popup height in pixels
     */
    _centerMapToSelectedCoordinate: function(lonlat,popupWidthPx,popupHeightPx){
    	var popupPixels = this._map.getPixelFromLonLat(lonlat);
    	var mapCenterPixels = this._map.getPixelFromLonLat(this._map.getCenter());

    	var offset = 10;
    	var infoboxWidth = popupWidthPx + offset;
        var infoboxHeight = popupHeightPx + offset;
        var size = this._map.getCurrentSize();
        var width = size.w;
        var height = size.h;

        var point = {
        		x: popupPixels.x,
        		y: popupPixels.y
        };
        var popupLonLat =this._map.getLonLatFromPixel(point);
        this._map.setCenter(popupLonLat);
        this.getMapModule()._updateDomain();
    },
    /**
     * @method _panMapToShowPopup
     * @private
     * Pans map to show popup
     * @param {OpenLayers.LonLat} lonlat where to show the popup
     * @param {Integer} popupWidthPx,  popup width in pixels
     * @param {Integer} popupHeightPx, popup height in pixels
     */
    _panMapToShowPopup : function(lonlat, popupWidthPx, popupHeightPx) {
        var pixels = this._map.getViewPortPxFromLonLat(lonlat);
        var size = this._map.getCurrentSize();
        var width = size.w;
        var height = size.h;
        // if infobox would be out of screen
        // -> move map to make infobox visible on screen
        var panx = 0;
        var pany = 0;
        var popupMarginWidthPx = 15;
        var popupMarginHeightPx = 10;
        var infoboxWidth = popupWidthPx+popupMarginWidthPx;
        var infoboxHeight = popupHeightPx+popupMarginHeightPx;
        if( pixels.x + infoboxWidth > width) {
            panx = width - (pixels.x + infoboxWidth);
        }
        if( pixels.y + infoboxHeight > height) {
            pany = height - (pixels.y + infoboxHeight);
        }
        // check that we are not "over the top"
        else if(pixels.y < 25) {
            pany = 25;
        }
        if(panx != 0 || pany != 0) {
            this.getMapModule().panMapByPixels(-panx, -pany);
        }

    },
    /**
     * @method close
     * @param {String} id
     * 		id for popup that we want to close (optional - if not given, closes all popups)
     */
    close : function(id) {
    	// destroys all if id not given
    	// deletes reference to the same id will work next time also
        if(!id) {
            for(var pid in this._popups) {
    			this._popups[pid].popup.destroy();
    			delete this._popups[pid];
            }
            return;
        }
        // id specified, delete only single popup
        if(this._popups[id]) {
            if(this._popups[id].popup) {
                this._popups[id].popup.destroy();
            }
            delete this._popups[id];
        }
        // else notify popup not found?
    },
    /**
     * @method getPopups
     * Returns references to popups that are currently open
     * @return {Object}
     */
    getPopups : function() {
        return this._popups;
    },

    /**
     * @method register
     * mapmodule.Plugin protocol method - does nothing atm
     */
    register : function() {

    },
    /**
     * @method unregister
     * mapmodule.Plugin protocol method - does nothing atm
     */
    unregister : function() {
    },
    /**
     * @method startPlugin
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * mapmodule.Plugin protocol method.
     * Sets sandbox and registers self to sandbox
     */
    startPlugin : function(sandbox) {
        this._sandbox = sandbox;
        sandbox.register(this);

    },
    /**
     * @method stopPlugin
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * mapmodule.Plugin protocol method.
     * Unregisters self from sandbox
     */
    stopPlugin : function(sandbox) {

        sandbox.unregister(this);

        this._map = null;
        this._sandbox = null;
    },
    /**
     * @method start
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * Module protocol method - does nothing atm
     */
    start : function(sandbox) {
    },
    /**
     * @method stop
	 * @param {Oskari.mapframework.sandbox.Sandbox} sandbox
     * Module protocol method - does nothing atm
     */
    stop : function(sandbox) {
    }
}, {
	/**
	 * @property {String[]} protocol
	 * @static
	 */
    'protocol' : ["Oskari.mapframework.module.Module", "Oskari.mapframework.ui.module.common.mapmodule.Plugin"]
});
<|endoftext|>


<commit_before>
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('format-author', 'helper:format-author', {
  integration: true
});

test('it renders one author', function(assert) {
  this.set('authors', {
    "type": "Person",
    "id": "https://orcid.org/0000-0002-2822-4968",
    "name": "Mitesh Patel",
    "given-name": "Mitesh",
    "family-name": "Patel"
  });

  this.render(hbs`{{format-author authors}}`);

  assert.equal(this.$().text().trim(), 'Mitesh Patel');
});

test('it renders three authors', function(assert) {
  this.set('authors', [
    {
      "type": "Person",
      "name": "Empbh R. Goh",
      "given-name": "Empbh R.",
      "family-name": "Goh"
    }, {
      "type": "Person",
      "name": "M. Barrgow",
      "given-name": "M.",
      "family-name": "Barrgow"
    }, {
      "type": "Person",
      "name": "M. Barrgoe",
      "given-name": "M.",
      "family-name": "Barrgoe"
    }
  ]);

  this.render(hbs`{{format-author authors}}`);

  assert.equal(this.$().text().trim(), 'Empbh R. Goh, M. Barrgow & M. Barrgoe');
});
<commit_msg>update test<commit_after>
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('format-author', 'helper:format-author', {
  integration: true
});

test('it renders one author', function(assert) {
  this.set('authors', {
    "type": "Person",
    "id": "https://orcid.org/0000-0002-2822-4968",
    "name": "Mitesh Patel",
    "given-name": "Mitesh",
    "family-name": "Patel"
  });

  this.render(hbs`{{format-author authors}}`);

  assert.equal(this.$().text().trim(), 'Mitesh Patel');
});

test('it renders three authors', function(assert) {
  this.set('authors', [
    {
      "type": "Person",
      "name": "Empbh R. Goh",
      "given-name": "Empbh R.",
      "family-name": "Goh"
    }, {
      "type": "Person",
      "name": "M. Barrgow",
      "given-name": "M.",
      "family-name": "Barrgow"
    }, {
      "type": "Person",
      "name": "M. Barrgoe",
      "given-name": "M.",
      "family-name": "Barrgoe"
    }
  ]);

  this.render(hbs`{{format-author authors}}`);

  assert.equal(this.$().text().trim(), 'Empbh R. Goh, M. Barrgow & M. Barrgoe');
});
<|endoftext|>


<commit_before>const SEARCH_API = 'https://api.reddit.com/search.json?sort=top&t=all&limit=100&q=url:';
const INFO_API = 'https://reddit.com/api/info.json?url=';

function findOnReddit(url, useCache = true, exact = true) {
	let query = encodeURIComponent(url);
	let results = search(query, useCache, exact);
	results.then(res => cachePosts(query, res, exact)).catch(ignoreRejection);
	return results;
}

function search(query, useCache = true, exact = true) {
	let requestUrl = `${exact ? INFO_API : SEARCH_API}${query}`;
	if (!useCache) {
		return makeApiRequest(requestUrl).then(res => res.data.children);
	}
	return searchCache(query).then(cache => {
		let data = cache[query] || {};
		let key = exact ? 'exact' : 'nonExact';
		let otherResults = data[exact ? 'nonExact' : 'exact'];
		return checkCacheValidity(data, key).then(isValid => {
			if (isValid) {
				posts = data[key].posts;
				if (otherResults) {
					posts.other = otherResults.posts.length;
				}
				return posts;
			} else {
				let res = makeApiRequest(requestUrl).then(res => res.data.children);
				if (otherResults) {
					res.then(posts => {
						posts.other = otherResults.posts.length;
						return posts;
					});
				}
				return res;
			}
		});
	});
}

function makeApiRequest(url) {
	console.log('cache miss');
	return new Promise((resolve, reject) => {
		$.get(url).done(resolve).fail(reject);
	});
}

function cachePosts(query, posts, exact) {
	let key = exact ? 'exact' : 'nonExact';
	searchCache(query).then(c => {
		let objectToStore = {};
		let data = c[query] || {};
		data[key] = {
			posts: posts,
			time: Date.now()
		};
		objectToStore[query] = data;
		return cache(objectToStore);
	});
}

function checkCacheValidity(cache, key) {
	if (!cache.hasOwnProperty(key)) {
		return Promise.resolve(false);
	}
	let data = cache[key];
	if (!(data.time && data.posts)) {
		return Promise.resolve(false);
	}
	let diff = Date.now() - data.time;
	let query = { cache: { period: DEFAULT_CACHE_PERIOD_MINS } };
	return getOptions(query).then(opts => diff < +(opts.cache.period) * 60e3);
}
<commit_msg>ignore protocol when doing a non-exact search<commit_after>const SEARCH_API = 'https://api.reddit.com/search.json?sort=top&t=all&limit=100&q=url:';
const INFO_API = 'https://reddit.com/api/info.json?url=';

function findOnReddit(url, useCache = true, exact = true) {
	if (!exact) {
		url = url.replace(/^https?\:\/\//i, "")
	}
	let query = encodeURIComponent(url);
	let results = search(query, useCache, exact);
	results.then(res => cachePosts(query, res, exact)).catch(ignoreRejection);
	return results;
}

function search(query, useCache = true, exact = true) {
	let requestUrl = `${exact ? INFO_API : SEARCH_API}${query}`;
	if (!useCache) {
		return makeApiRequest(requestUrl).then(res => res.data.children);
	}
	return searchCache(query).then(cache => {
		let data = cache[query] || {};
		let key = exact ? 'exact' : 'nonExact';
		let otherResults = data[exact ? 'nonExact' : 'exact'];
		return checkCacheValidity(data, key).then(isValid => {
			if (isValid) {
				posts = data[key].posts;
				if (otherResults) {
					posts.other = otherResults.posts.length;
				}
				return posts;
			} else {
				let res = makeApiRequest(requestUrl).then(res => res.data.children);
				if (otherResults) {
					res.then(posts => {
						posts.other = otherResults.posts.length;
						return posts;
					});
				}
				return res;
			}
		});
	});
}

function makeApiRequest(url) {
	console.log('cache miss');
	return new Promise((resolve, reject) => {
		$.get(url).done(resolve).fail(reject);
	});
}

function cachePosts(query, posts, exact) {
	let key = exact ? 'exact' : 'nonExact';
	searchCache(query).then(c => {
		let objectToStore = {};
		let data = c[query] || {};
		data[key] = {
			posts: posts,
			time: Date.now()
		};
		objectToStore[query] = data;
		return cache(objectToStore);
	});
}

function checkCacheValidity(cache, key) {
	if (!cache.hasOwnProperty(key)) {
		return Promise.resolve(false);
	}
	let data = cache[key];
	if (!(data.time && data.posts)) {
		return Promise.resolve(false);
	}
	let diff = Date.now() - data.time;
	let query = { cache: { period: DEFAULT_CACHE_PERIOD_MINS } };
	return getOptions(query).then(opts => diff < +(opts.cache.period) * 60e3);
}
<|endoftext|>


<commit_before>function preview(e){
  e.preventDefault();
  e.stopPropagation();
  if($(".ace_editor").is(":visible")){
    $(".ace_editor").hide();
    $("#readme article").show();
    $("#gist-preview span").html("Edit");
  } else {
    $("#readme article").hide();
    $(".ace_editor").show();
    $("#gist-preview span").html("Preview");
  }
  $("#readme article").html($.markdown($(".input > textarea").val()));
  return false;
}

function appendHtml(e){
  ele = e.currentTarget;
  selected_item = $(ele).html().replace(/<(?:.|\n)*?>/gm, '');
  var isMarkdown = false;
  if($("input.gist-language").val() == "Markdown"){
    isMarkdown = true;
  }
  if(e.type == "change"){
    selected_item = $(ele).val();
    $.each([".md",".markdown"],function(k,v){
      if(selected_item.indexOf(v, selected_item.length - v.length) !== -1){
        isMarkdown = true;
      }
    });
  }
  if(!isMarkdown){
    $("#readme").remove();
    $("#gist-preview span").parent().remove();
    $(".ace_editor").show();
    return;
  }

  preview_area = $('

');
  $(".ace_editor").parent().append(preview_area);
  $(".form-actions").append("<button type='button' class='classy' id='gist-preview'>Preview</button>");
}

jQuery(function($){
  $("#gist-preview").live("click",preview);
  $(".gist-name-textbox").live("change", appendHtml);
});
<commit_msg>Update for latest Github changes.<commit_after>function preview(e){
  e.preventDefault();
  e.stopPropagation();
  if($(".commit-create").is(":visible")){
    $(".commit-create").hide();
    $("#readme article").show();
    $("#gist-preview span").html("Edit");
  } else {
    $("#readme article").hide();
    $(".commit-create").show();
    $("#gist-preview span").html("Preview");
  }
  $("#readme article").html($.markdown($(".commit-create > textarea").val()));
  return false;
}

function appendHtml(e){
  ele = e.currentTarget;
  selected_item = $(ele).html().replace(/<(?:.|\n)*?>/gm, '');
  var isMarkdown = false;
  if($("input.gist-language").val() == "Markdown"){
    isMarkdown = true;
  }
  if(e.type == "change"){
    selected_item = $(ele).val();
    $.each([".md",".markdown"],function(k,v){
      if(selected_item.indexOf(v, selected_item.length - v.length) !== -1){
        isMarkdown = true;
      }
    });
  }
  if(!isMarkdown){
    $("#readme").remove();
    $("#gist-preview span").parent().remove();
    $(".commit-create").show();
    return;
  }

  preview_area = $('

');
  $(".commit-create").parent().append(preview_area);
  $(".form-actions").append("<button type='button' class='btn' id='gist-preview'>Preview</button>");
}

jQuery(function($){
  $("#gist-preview").live("click",preview);
  $(".js-gist-filename").live("change", appendHtml);
});
<|endoftext|>


<commit_before>'use strict';

var gonawingApp = angular.module('gonawingApp', [
  'ngSanitize',
  'ngRoute',
  'ngResource',
  'ngCookies',
  'directive.googleplussignin',
  'directive.twittersignin',
  'directive.googlesignin',
  'directive.facebooksignin',
  'directive.formValidation',
  'directive.formFocus',
  'directive.joinButton',
  'directive.addButton',
  'directive.activities',
  '$strap.directives',
  'filter.fromNow',
  'filter.reverse',

  'rootControllers',
  'navigationControllers',
  'dashboardControllers',
  'activitiesControllers',
  'userControllers',
  'teamControllers',
  'tournamentControllers',
  'inviteControllers',
  'searchControllers',

  'dataServices',
  'authServices'
]);

gonawingApp.factory('notFoundInterceptor', ['$q', '$location', function($q, $location){
  return {
    response: function(response) {
      return response || $q.when(response);
    },

    responseError: function(response) {
      if (response && response.status === 404) {
        $location.path('/404');
      }
      return $q.reject(response);
    }
  };
}]);

gonawingApp.config(['$routeProvider', '$httpProvider',
  function($routeProvider, $httpProvider) {
    $routeProvider.
      when('/welcome', { templateUrl: 'templates/welcome.html', requireLogin: false }).
      when('/getting-started', { templateUrl: 'templates/getting-started.html', requireLogin: false }).
      when('/', { templateUrl:  'templates/home.html', controller: 'RootCtrl', requireLogin: true }).
      when('/signin', { templateUrl: 'templates/signin.html', requireLogin: false }).
      when('/about', { templateUrl: 'templates/about.html', requireLogin: false }).
      when('/search', { templateUrl: 'templates/search.html', controller: 'SearchCtrl', requireLogin: true }).

      when('/users/', { templateUrl: 'templates/users/index.html', controller: 'UserListCtrl', requireLogin: true }).
      when('/users/:id', { templateUrl: 'templates/users/show.html', controller: 'UserShowCtrl', requireLogin: true }).

      when('/teams', { templateUrl: 'templates/teams/index.html', controller: 'TeamListCtrl', requireLogin: true }).
      when('/teams/new', { templateUrl: 'templates/teams/new.html', controller: 'TeamNewCtrl', requireLogin: true }).
      when('/teams/:id', { templateUrl: 'templates/teams/show.html', controller: 'TeamShowCtrl', requireLogin: true }).
      when('/teams/edit/:id', { templateUrl: 'templates/teams/edit.html', controller: 'TeamEditCtrl', requireLogin: true }).
      when('/teams/invite/:id', { templateUrl: 'templates/teams/invite.html', controller: 'TeamInviteCtrl', requireLogin: true }).

      when('/tournaments', { templateUrl: 'templates/tournaments/index.html', controller: 'TournamentListCtrl', requireLogin: true }).
      when('/tournaments/new', { templateUrl: 'templates/tournaments/new.html', controller: 'TournamentNewCtrl', requireLogin: true }).
      when('/tournaments/:id', { templateUrl: 'templates/tournaments/show.html', controller: 'TournamentShowCtrl', requireLogin: true, reloadOnSearch: false }).
      when('/tournaments/edit/:id', { templateUrl: 'templates/tournaments/edit.html', controller: 'TournamentEditCtrl', requireLogin: true }).

      when('/settings/edit-profile', { templateUrl: 'templates/users/edit.html', controller: 'UserEditCtrl', requireLogin: true }).
      when('/settings/networks', { templateUrl: 'templates/settings/networks.html', requireLogin: true }).
      when('/settings/email', { templateUrl: 'templates/settings/email.html', requireLogin: true }).
      when('/invite', { templateUrl: 'templates/invite.html', controller: 'InviteCtrl', requireLogin: true }).
      when('/404', { templateUrl: 'static/templates/404.html' }).
      otherwise( {redirectTo: '/'});

    $httpProvider.interceptors.push('notFoundInterceptor');
}]);

gonawingApp.run(['$rootScope', '$location', '$window', '$cookieStore', 'sAuth', 'Session', 'User', function($rootScope, $location, $window, $cookieStore, sAuth, Session, User) {
    $rootScope.title = 'gonawin';

    $rootScope.currentUser = undefined;
    $rootScope.isLoggedIn = false;
    $rootScope.serviceIds = Session.serviceIds();

    $window.fbAsyncInit = function() {
      // Executed when the SDK is loaded
      $rootScope.serviceIds.$promise.then(function(response){
          FB.init({
        appId: response.FacebookAppId,
        channelUrl: 'static/templates/channel.html',
        status: true, /*Set if you want to check the authentication status at the start up of the app */
        cookie: true,
        xfbml: true
          });

          sAuth.watchLoginChange();
      });
    };

  (function(d){
    // load the Facebook javascript SDK
    var js,
    id = 'facebook-jssdk',
    ref = d.getElementsByTagName('script')[0];

    if (d.getElementById(id)) {
      return;
    }

    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";

    ref.parentNode.insertBefore(js, ref);

  }(document));

  $rootScope.$on("$routeChangeStart", function(event, next, current) {
    console.log('routeChangeStart, requireLogin = ', next.requireLogin);
    console.log('routeChangeStart, current user = ', $rootScope.currentUser);
    console.log('routeChangeStart, isLoggedIn = ', $rootScope.isLoggedIn);

    setPageTite();

    $rootScope.originalPath = $location.$$url;

    $rootScope.isLoggedIn = sAuth.isLoggedIn();
    $rootScope.isLoginRequired = next.requireLogin;

    if($location.$$path === '/auth/twitter/callback') {
      sAuth.signinWithTwitter(($location.search()).oauth_token, ($location.search()).oauth_verifier);
    } else if($location.$$path === '/auth/google/callback') {
      sAuth.signinWithGoogle(($location.search()).auth_token);
    } else {
      // Everytime the route in our app changes check authentication status.
      // Get current user only if we are logged in.
      if( $rootScope.isLoggedIn && (undefined == $rootScope.currentUser) ) {
        $rootScope.currentUser = User.get({ id:sAuth.getUserID(), including: "Teams TeamRequests Invitations" });
        console.log('routeChangeStart, current user = ', $rootScope.currentUser);
      }
      // Redirect user to root if he tries to go on welcome page or signin page and he is logged in.
      if( ($location.path() === '/welcome' || $location.path() === '/signin') && $rootScope.isLoggedIn ) {
        console.log('routeChangeStart, redirect to root');
        $location.path('/');
      }
      // Redidrect to welcome if route requires to be logged in and user is not logged in.
      if ( next.requireLogin && ((undefined == $rootScope.currentUser) || !$rootScope.isLoggedIn) ) {
        console.log('routeChangeStart, redirect to welcome');
        $location.path('/welcome');
      }
    }
    console.log('end of routeChangeStart');
  });

  $rootScope.$on('event:google-plus-signin-success', function (event, authResult) {
    // User successfully authorized the G+ App!
    console.log('event:google-plus-signin-success');
    Session.fetchUserInfo({ access_token: authResult.access_token }).$promise.then(function(userInfo) {
      $rootScope.currentUser = Session.fetchUser({
        access_token: authResult.access_token,
        provider: 'google',
        id:userInfo.id,
        name:userInfo.displayName,
        email:userInfo.emails[0].value } );
      $rootScope.currentUser.$promise.then(function(currentUser){
        console.log('event:google-plus-signin-success: current user = ', currentUser);
        sAuth.storeCookies(authResult.access_token, currentUser.User.Auth, currentUser.User.Id);
        $cookieStore.put('provider', 'google_plus');
        $rootScope.isLoggedIn = true;
        $location.path('/');
      });
    });
  });
  $rootScope.$on('event:google-plus-signin-failure', function (event, authResult) {
    // User has not authorized the G+ App!
  });

  // search function:
  function setPageTite(){
    if( $location.$$url == '/welcome') {
      $rootScope.title = 'gonawin';
    } else if($location.$$url == '/signin'){
      $rootScope.title = 'gonawin - Sign In';
    } else if($location.$$url == '/about'){
      $rootScope.title = 'gonawin - About';
    } else if($location.$$url == '/getting-started') {
      $rootScope.title = 'gonawin - Getting Started';
    }
  };
}]);
<commit_msg>Display issue on logout when URL paramters exist<commit_after>'use strict';

var gonawingApp = angular.module('gonawingApp', [
  'ngSanitize',
  'ngRoute',
  'ngResource',
  'ngCookies',
  'directive.googleplussignin',
  'directive.twittersignin',
  'directive.googlesignin',
  'directive.facebooksignin',
  'directive.formValidation',
  'directive.formFocus',
  'directive.joinButton',
  'directive.addButton',
  'directive.activities',
  '$strap.directives',
  'filter.fromNow',
  'filter.reverse',

  'rootControllers',
  'navigationControllers',
  'dashboardControllers',
  'activitiesControllers',
  'userControllers',
  'teamControllers',
  'tournamentControllers',
  'inviteControllers',
  'searchControllers',

  'dataServices',
  'authServices'
]);

gonawingApp.factory('notFoundInterceptor', ['$q', '$location', function($q, $location){
  return {
    response: function(response) {
      return response || $q.when(response);
    },

    responseError: function(response) {
      if (response && response.status === 404) {
        $location.path('/404');
      }
      return $q.reject(response);
    }
  };
}]);

gonawingApp.config(['$routeProvider', '$httpProvider',
  function($routeProvider, $httpProvider) {
    $routeProvider.
      when('/welcome', { templateUrl: 'templates/welcome.html', requireLogin: false }).
      when('/getting-started', { templateUrl: 'templates/getting-started.html', requireLogin: false }).
      when('/', { templateUrl:  'templates/home.html', controller: 'RootCtrl', requireLogin: true }).
      when('/signin', { templateUrl: 'templates/signin.html', requireLogin: false }).
      when('/about', { templateUrl: 'templates/about.html', requireLogin: false }).
      when('/search', { templateUrl: 'templates/search.html', controller: 'SearchCtrl', requireLogin: true }).

      when('/users/', { templateUrl: 'templates/users/index.html', controller: 'UserListCtrl', requireLogin: true }).
      when('/users/:id', { templateUrl: 'templates/users/show.html', controller: 'UserShowCtrl', requireLogin: true }).

      when('/teams', { templateUrl: 'templates/teams/index.html', controller: 'TeamListCtrl', requireLogin: true }).
      when('/teams/new', { templateUrl: 'templates/teams/new.html', controller: 'TeamNewCtrl', requireLogin: true }).
      when('/teams/:id', { templateUrl: 'templates/teams/show.html', controller: 'TeamShowCtrl', requireLogin: true }).
      when('/teams/edit/:id', { templateUrl: 'templates/teams/edit.html', controller: 'TeamEditCtrl', requireLogin: true }).
      when('/teams/invite/:id', { templateUrl: 'templates/teams/invite.html', controller: 'TeamInviteCtrl', requireLogin: true }).

      when('/tournaments', { templateUrl: 'templates/tournaments/index.html', controller: 'TournamentListCtrl', requireLogin: true }).
      when('/tournaments/new', { templateUrl: 'templates/tournaments/new.html', controller: 'TournamentNewCtrl', requireLogin: true }).
      when('/tournaments/:id', { templateUrl: 'templates/tournaments/show.html', controller: 'TournamentShowCtrl', requireLogin: true, reloadOnSearch: false }).
      when('/tournaments/edit/:id', { templateUrl: 'templates/tournaments/edit.html', controller: 'TournamentEditCtrl', requireLogin: true }).

      when('/settings/edit-profile', { templateUrl: 'templates/users/edit.html', controller: 'UserEditCtrl', requireLogin: true }).
      when('/settings/networks', { templateUrl: 'templates/settings/networks.html', requireLogin: true }).
      when('/settings/email', { templateUrl: 'templates/settings/email.html', requireLogin: true }).
      when('/invite', { templateUrl: 'templates/invite.html', controller: 'InviteCtrl', requireLogin: true }).
      when('/404', { templateUrl: 'static/templates/404.html' }).
      otherwise( {redirectTo: '/'});

    $httpProvider.interceptors.push('notFoundInterceptor');
}]);

gonawingApp.run(['$rootScope', '$location', '$window', '$cookieStore', 'sAuth', 'Session', 'User', function($rootScope, $location, $window, $cookieStore, sAuth, Session, User) {
    $rootScope.title = 'gonawin';

    $rootScope.currentUser = undefined;
    $rootScope.isLoggedIn = false;
    $rootScope.serviceIds = Session.serviceIds();

    $window.fbAsyncInit = function() {
      // Executed when the SDK is loaded
      $rootScope.serviceIds.$promise.then(function(response){
          FB.init({
        appId: response.FacebookAppId,
        channelUrl: 'static/templates/channel.html',
        status: true, /*Set if you want to check the authentication status at the start up of the app */
        cookie: true,
        xfbml: true
          });

          sAuth.watchLoginChange();
      });
    };

  (function(d){
    // load the Facebook javascript SDK
    var js,
    id = 'facebook-jssdk',
    ref = d.getElementsByTagName('script')[0];

    if (d.getElementById(id)) {
      return;
    }

    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";

    ref.parentNode.insertBefore(js, ref);

  }(document));

  $rootScope.$on("$routeChangeStart", function(event, next, current) {
    console.log('routeChangeStart, requireLogin = ', next.requireLogin);
    console.log('routeChangeStart, current user = ', $rootScope.currentUser);
    console.log('routeChangeStart, isLoggedIn = ', $rootScope.isLoggedIn);

    setPageTite();
    $rootScope.originalPath = $location.$$path;

    $rootScope.isLoggedIn = sAuth.isLoggedIn();
    $rootScope.isLoginRequired = next.requireLogin;

    if($location.$$path === '/auth/twitter/callback') {
      sAuth.signinWithTwitter(($location.search()).oauth_token, ($location.search()).oauth_verifier);
    } else if($location.$$path === '/auth/google/callback') {
      sAuth.signinWithGoogle(($location.search()).auth_token);
    } else {
      // Everytime the route in our app changes check authentication status.
      // Get current user only if we are logged in.
      if( $rootScope.isLoggedIn && (undefined == $rootScope.currentUser) ) {
        $rootScope.currentUser = User.get({ id:sAuth.getUserID(), including: "Teams TeamRequests Invitations" });
        console.log('routeChangeStart, current user = ', $rootScope.currentUser);
      }
      // Redirect user to root if he tries to go on welcome page or signin page and he is logged in.
      if( ($location.path() === '/welcome' || $location.path() === '/signin') && $rootScope.isLoggedIn ) {
        console.log('routeChangeStart, redirect to root');
        $location.path('/');
      }
      // Redidrect to welcome if route requires to be logged in and user is not logged in.
      if ( next.requireLogin && ((undefined == $rootScope.currentUser) || !$rootScope.isLoggedIn) ) {
        console.log('routeChangeStart, redirect to welcome');
        $location.path('/welcome');
      }
    }
    console.log('end of routeChangeStart');
  });

  $rootScope.$on('event:google-plus-signin-success', function (event, authResult) {
    // User successfully authorized the G+ App!
    console.log('event:google-plus-signin-success');
    Session.fetchUserInfo({ access_token: authResult.access_token }).$promise.then(function(userInfo) {
      $rootScope.currentUser = Session.fetchUser({
        access_token: authResult.access_token,
        provider: 'google',
        id:userInfo.id,
        name:userInfo.displayName,
        email:userInfo.emails[0].value } );
      $rootScope.currentUser.$promise.then(function(currentUser){
        console.log('event:google-plus-signin-success: current user = ', currentUser);
        sAuth.storeCookies(authResult.access_token, currentUser.User.Auth, currentUser.User.Id);
        $cookieStore.put('provider', 'google_plus');
        $rootScope.isLoggedIn = true;
        $location.path('/');
      });
    });
  });
  $rootScope.$on('event:google-plus-signin-failure', function (event, authResult) {
    // User has not authorized the G+ App!
  });

  // search function:
  function setPageTite(){
    if( $location.$$url == '/welcome') {
      $rootScope.title = 'gonawin';
    } else if($location.$$url == '/signin'){
      $rootScope.title = 'gonawin - Sign In';
    } else if($location.$$url == '/about'){
      $rootScope.title = 'gonawin - About';
    } else if($location.$$url == '/getting-started') {
      $rootScope.title = 'gonawin - Getting Started';
    }
  };
}]);
<|endoftext|>


<commit_before>const assert = require('assert');

const BROWSER_OPTIONS = {
    ignoreHTTPSErrors: true,
    headless: process.env.CI === "true",
    devtools: true,
    defaultViewport: null,
    slowMo: process.env.CI === "true" ? 0 : 10,
    args: ['--start-maximized']
};

exports.browserOptions = () => BROWSER_OPTIONS;
exports.browserOptions = (opt) => {
    return {
        ...BROWSER_OPTIONS,
        ...opt
    };
};

exports.click = async (page, button) => {
    await page.evaluate((button) => {
        document.querySelector(button).click();
    }, button);
}

exports.clickLast = async (page, button) => {
    await page.evaluate((button) => {
        let buttons = document.querySelectorAll(button);
        buttons[buttons.length - 1].click();
    }, button);
}

exports.innerText = async (page, selector) => {
    let text = await page.$eval(selector, el => el.innerText.trim());
    console.log(`Text for selector [${selector}] is: [${text}]`);
    return text;
}

exports.textContent = async(page, selector) => {
    let element = await page.$(selector);
    let text = await page.evaluate(element => element.textContent.trim(), element);
    console.log(`Text content for selector [${selector}] is: [${text}]`);
    return text;
}

exports.inputValue = async(page, selector) => {
    let element = await page.$(selector);
    let text = await page.evaluate(element => element.value, element);
    console.log(`Input value for selector [${selector}] is: [${text}]`);
    return text;
}

exports.loginWith = async(page, user, password) => {
    console.log(`Logging in with ${user} and ${password}`);
    await this.type(page, '#username', user);
    await this.type(page, '#password', password);
    await page.keyboard.press('Enter');
    await page.waitForNavigation();
}

exports.assertVisibility = async(page, selector) => {
    let element = await page.$(selector);
    console.log(`Checking visibility for ${selector}`);
    assert(await element != null && element.boundingBox() != null);
}

exports.assertInvisibility = async(page, selector) => {
    let element = await page.$(selector);
    console.log(`Checking invisibility for ${selector}`);
    assert(element == null || await element.boundingBox() == null);
}

exports.submitForm = async(page, selector) => {
    await page.$eval(selector, form => form.submit());
    await page.waitForTimeout(2500)
}

exports.type = async(page, selector, value) => {
    await page.$eval(selector, el => el.value = '');
    await page.type(selector, value);
}
<commit_msg>refactor puppeteer to use common type method; reset previous text<commit_after>const assert = require('assert');

const BROWSER_OPTIONS = {
    ignoreHTTPSErrors: true,
    headless: process.env.CI === "true",
    devtools: true,
    defaultViewport: null,
    slowMo: process.env.CI === "true" ? 0 : 10,
    args: ['--start-maximized']
};

exports.browserOptions = () => BROWSER_OPTIONS;
exports.browserOptions = (opt) => {
    return {
        ...BROWSER_OPTIONS,
        ...opt
    };
};

exports.click = async (page, button) => {
    await page.evaluate((button) => {
        document.querySelector(button).click();
    }, button);
}

exports.clickLast = async (page, button) => {
    await page.evaluate((button) => {
        let buttons = document.querySelectorAll(button);
        buttons[buttons.length - 1].click();
    }, button);
}

exports.innerText = async (page, selector) => {
    let text = await page.$eval(selector, el => el.innerText.trim());
    console.log(`Text for selector [${selector}] is: [${text}]`);
    return text;
}

exports.textContent = async(page, selector) => {
    let element = await page.$(selector);
    let text = await page.evaluate(element => element.textContent.trim(), element);
    console.log(`Text content for selector [${selector}] is: [${text}]`);
    return text;
}

exports.inputValue = async(page, selector) => {
    let element = await page.$(selector);
    let text = await page.evaluate(element => element.value, element);
    console.log(`Input value for selector [${selector}] is: [${text}]`);
    return text;
}

exports.loginWith = async(page, user, password) => {
    console.log(`Logging in with ${user} and ${password}`);
    await this.type(page, '#username', user);
    await this.type(page, '#password', password);
    await page.keyboard.press('Enter');
    await page.waitForNavigation();
}

exports.assertVisibility = async(page, selector) => {
    let element = await page.$(selector);
    console.log(`Checking visibility for ${selector}`);
    assert(element != null && await element.boundingBox() != null);
}

exports.assertInvisibility = async(page, selector) => {
    let element = await page.$(selector);
    console.log(`Checking invisibility for ${selector}`);
    assert(element == null || await element.boundingBox() == null);
}

exports.submitForm = async(page, selector) => {
    await page.$eval(selector, form => form.submit());
    await page.waitForTimeout(2500)
}

exports.type = async(page, selector, value) => {
    await page.$eval(selector, el => el.value = '');
    await page.type(selector, value);
}
<|endoftext|>


<commit_before>var CmsLess = ( function($) {
  var config = {
    contentPath: 'cms-less-content',
    destinationSelector: '#cms-less-destination',
    anchorDelimiter: '-',
    notFoundPageName: '404',
    eagerLoadPages: [],
    redirects: {}
  }

  /* Public Members */
  function Init(options) {
    config = $.extend(config, options);
    // if the path is the PHP back-end path, upgrade it to the corresponding hash path
    var hashPath = hashPathFromStandardPath(window.location.pathname);
    if(hashPath !== false) {
      window.history.replaceState(hashPath, document.title, hashPath);
    }

    // if the site is accessed from a non-upgraded path, the content will be preloaded
    var preloadedPageName = $(config.destinationSelector).data("cms-less-preloaded");
    if(preloadedPageName) {
      afterPageLoad(preloadedPageName);
      preloadedPageName = preloadedPageName == 'index' ? '' : preloadedPageName;
      window.location.hash = "#" + preloadedPageName;
    } else {
      loadContentFromHash();
    }
    $(window).bind('hashchange', loadContentFromHash);

    UpgradeLinks();

    Cache.EagerLoad(config.eagerLoadPages);
  }

  function UpgradeLinks() {
    // upgrade all standard (PHP back-end) links to the corresponding hash path
    $("a.cms-less-link").each(function() {
      var link = $(this);
      var pageName = link.attr("href");
      var hashPath = hashPathFromStandardPath(pageName);
      if(hashPath !== false) {
        link.attr("href", hashPath);
      }
    });
  }

  /* Nested Classes */
  var Cache = (function () {
    var pageNotFoundPromise;

    var cache = {};

    function Get (pageName, handlePageContent) {
      ensureLoaded(pageName);
      cache[pageName].retrieve(handlePageContent);
    }

    function EagerLoad (pagesToLoad) {
      $.each(pagesToLoad, function (_, pageName) {
        ensureLoaded(pageName);
      });
    }

    function getPageNotFoundResult () {
      if(!pageNotFoundPromise) {
        pageNotFoundPromise = $.get(expandedContentPath(config.notFoundPageName)).then(
          function (page) {
            return new Result(page, 404);
          }, function () {
            // Can't show the 404 page, show something mildly helpful
            var error = $("
Sorry, something wen't wrong when trying to load this page
");
            return new Result(error, 500);
          }
        );
      }

      return pageNotFoundPromise;
    }

    function ensureLoaded (pageName) {
      if(!(pageName in cache)) {
        cache[pageName] = new CacheEntry(pageName);
      }
    }

    var Result = function (page, statusCode) {
      this.page = page;
      this.code = statusCode;
    };

    var CacheEntry = function (pageName) {
      this.promise = $.get(expandedContentPath(pageName)).then(
        function (page) {
          return new Result(page, 200);
        }, function () {
          return getPageNotFoundResult();
        }
      )

      this.retrieve = function (handlePageContent) {
        this.promise.always(handlePageContent);
      }
    }

    return {
      EagerLoad: EagerLoad,
      Get: Get
    }
  }());

  /* Private Members */
  function loadContent(pageName) {
    beforePageLoad(pageName);
    Cache.Get(pageName, function (result) {
      $(config.destinationSelector).html(result.page);
      if(result.code == 200) {
        markPageAsIndexable(true);
        afterPageLoad(pageName);
      } else {
        markPageAsIndexable(false);
        afterPageLoad(config.notFoundPageName, pageName);
      }
    });
  }

  function markPageAsIndexable(indexable) {
    if(indexable) {
      $("head meta[name='robots']").remove();
    } else {
      $("head").append($("<meta name='robots' content='noindex' />"));
    }
  }

  function beforePageLoad(newPageName) {
    // scroll to the top
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  function afterPageLoad(newPageName, missingPageName) {
    // dispatch an event
    pageChangeEvent = new CustomEvent('cms-less-page-change', { 'detail': { 'pageName': newPageName, 'missingPageName': missingPageName }});
    document.dispatchEvent(pageChangeEvent);
  }

  function expandedContentPath(pageName) {
    return config.contentPath + "/" + pageName + ".html";
  }

  function loadContentFromHash() {
    var pageName = extractPageNameFromHash() || 'index';

    if(pageName in config.redirects) {
      window.location.href = "/#" + config.redirects[pageName];
    } else {
      loadContent(pageName);
    }
  }

  function extractPageNameFromHash(hash) {
    hash = hash || window.location.hash
    delimiterIndex = hash.lastIndexOf(config.anchorDelimiter);
    if(delimiterIndex > 0) {
      return hash.slice(1, delimiterIndex);
    } else {
      return hash.slice(1);
    }
  }

  function hashPathFromStandardPath(path) {
    if(path == "/") {
      return '/-#';
    } else if(path.match(/\/[^\/-][^\/]*/)) {
      return '/-#' + path.match(/\/([^\/-][^\/]*)$/)[1];
    } else {
      return false;
    }
  }

  return {
    Init : Init,
    PageName : extractPageNameFromHash,
    UpgradeLinks: UpgradeLinks
  };

} )( jQuery );
<commit_msg>eager load pages sequentially, not as a batch<commit_after>var CmsLess = ( function($) {
  var config = {
    contentPath: 'cms-less-content',
    destinationSelector: '#cms-less-destination',
    anchorDelimiter: '-',
    notFoundPageName: '404',
    eagerLoadPages: [],
    redirects: {}
  }

  /* Public Members */
  function Init(options) {
    config = $.extend(config, options);
    // if the path is the PHP back-end path, upgrade it to the corresponding hash path
    var hashPath = hashPathFromStandardPath(window.location.pathname);
    if(hashPath !== false) {
      window.history.replaceState(hashPath, document.title, hashPath);
    }

    // if the site is accessed from a non-upgraded path, the content will be preloaded
    var preloadedPageName = $(config.destinationSelector).data("cms-less-preloaded");
    if(preloadedPageName) {
      afterPageLoad(preloadedPageName);
      preloadedPageName = preloadedPageName == 'index' ? '' : preloadedPageName;
      window.location.hash = "#" + preloadedPageName;
    } else {
      loadContentFromHash();
    }
    $(window).on('hashchange', loadContentFromHash);

    UpgradeLinks();

    Cache.EagerLoad(config.eagerLoadPages);
  }

  function UpgradeLinks() {
    // upgrade all standard (PHP back-end) links to the corresponding hash path
    $("a.cms-less-link").each(function() {
      var link = $(this);
      var pageName = link.attr("href");
      var hashPath = hashPathFromStandardPath(pageName);
      if(hashPath !== false) {
        link.attr("href", hashPath);
      }
    });
  }

  /* Nested Classes */
  var Cache = (function () {
    var cache = {};

    var pageNotFoundPromise;

    var pagesToLoad = [];

    function Get (pageName, handlePageContent) {
      ensureLoaded(pageName).then(handlePageContent);
    }

    function EagerLoad (_pagesToLoad) {
      pagesToLoad = _pagesToLoad || [];
      eagerLoadNextPage();
    }

    function getPageNotFoundResult () {
      if(!pageNotFoundPromise) {
        pageNotFoundPromise = $.get(expandedContentPath(config.notFoundPageName)).then(
          function (page) {
            return new Result(page, 404);
          }, function () {
            // Can't show the 404 page, show something mildly helpful
            var error = $("
Sorry, something wen't wrong when trying to load this page
");
            return new Result(error, 500);
          }
        );
      }

      return pageNotFoundPromise;
    }

    function eagerLoadNextPage () {
      page = pagesToLoad.pop();
      if(page) {
        ensureLoaded(page).then(eagerLoadNextPage);
      }
    }

    function ensureLoaded (pageName) {
      if(!(pageName in cache)) {
        cache[pageName] = new CacheEntry(pageName);
      }

      return cache[pageName];
    }

    var Result = function (page, statusCode) {
      this.page = page;
      this.code = statusCode;
    };

    var CacheEntry = function (pageName) {
      this.promise = $.get(expandedContentPath(pageName)).then(
        function (page) {
          return new Result(page, 200);
        }, function () {
          return getPageNotFoundResult();
        }
      )

      this.then= function (handlePageContent) {
        this.promise.always(handlePageContent);
      }
    }

    return {
      EagerLoad: EagerLoad,
      Get: Get
    }
  }());

  /* Private Members */
  function loadContent(pageName) {
    beforePageLoad(pageName);
    Cache.Get(pageName, function (result) {
      $(config.destinationSelector).html(result.page);
      if(result.code == 200) {
        markPageAsIndexable(true);
        afterPageLoad(pageName);
      } else {
        markPageAsIndexable(false);
        afterPageLoad(config.notFoundPageName, pageName);
      }
    });
  }

  function markPageAsIndexable(indexable) {
    if(indexable) {
      $("head meta[name='robots']").remove();
    } else {
      $("head").append($("<meta name='robots' content='noindex' />"));
    }
  }

  function beforePageLoad(newPageName) {
    // scroll to the top
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  function afterPageLoad(newPageName, missingPageName) {
    // dispatch an event
    pageChangeEvent = new CustomEvent('cms-less-page-change', { 'detail': { 'pageName': newPageName, 'missingPageName': missingPageName }});
    document.dispatchEvent(pageChangeEvent);
  }

  function expandedContentPath(pageName) {
    return config.contentPath + "/" + pageName + ".html";
  }

  function loadContentFromHash() {
    var pageName = extractPageNameFromHash() || 'index';

    if(pageName in config.redirects) {
      window.location.href = "/#" + config.redirects[pageName];
    } else {
      loadContent(pageName);
    }
  }

  function extractPageNameFromHash(hash) {
    hash = hash || window.location.hash
    delimiterIndex = hash.lastIndexOf(config.anchorDelimiter);
    if(delimiterIndex > 0) {
      return hash.slice(1, delimiterIndex);
    } else {
      return hash.slice(1);
    }
  }

  function hashPathFromStandardPath(path) {
    if(path == "/") {
      return '/-#';
    } else if(path.match(/\/[^\/-][^\/]*/)) {
      return '/-#' + path.match(/\/([^\/-][^\/]*)$/)[1];
    } else {
      return false;
    }
  }

  return {
    Init : Init,
    PageName : extractPageNameFromHash,
    UpgradeLinks: UpgradeLinks
  };

} )( jQuery );
<|endoftext|>


<commit_before>beforeEach(function () {
  jasmine.addMatchers({
    toBeEqualAsJSON: function (util, customEqualityTesters) {
      return {
        compare: function (actual, expected) {
          var actualAsJSON = JSON.stringify(actual);
          var expectedAsJSON = JSON.stringify(expected);

          var result = {};

          result.pass = actualAsJSON === expectedAsJSON;

          if (result.pass)
            result.message = "Expected " + actualAsJSON + " not to be equal to " + expectedAsJSON + " once converted to JSON";
          else
            result.message = "Expected " + actualAsJSON + " to be equal to " + expectedAsJSON + " once converted to JSON";

          return result;
        }
      }
    }
  });
});
<commit_msg>Fix tests in phantom.<commit_after>beforeEach(function () {
  jasmine.addMatchers({
    toBeEqualAsJSON: function (util, customEqualityTesters) {
      return {
        compare: function (actual, expected) {
          var actualAsJSON = JSON.stringify(actual);
          var expectedAsJSON = JSON.stringify(expected);

          var result = {};

          result.pass = actualAsJSON === expectedAsJSON;

          if (result.pass)
            result.message = "Expected " + actualAsJSON + " not to be equal to " + expectedAsJSON + " once converted to JSON";
          else
            result.message = "Expected " + actualAsJSON + " to be equal to " + expectedAsJSON + " once converted to JSON";

          return result;
        }
      }
    }
  });
});

// When using phantomJS JSON.parse seems bugged, returning a string instead of a built object.
// I'm unsure as to why, since when testing this behaviour directly in phantom it behaves
// as expected. This monkey patches the issue, but It'd be good to find out what's going on here.
var _JSON_parse = JSON.parse;
JSON.parse = function(json_string) {
  var result = _JSON_parse(json_string);
  if (typeof result == "string") {
    result = eval(result);
  }
  return result;
}
<|endoftext|>


<commit_before>/* globals describe, it, expect */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.publishBehavior()', function () {
  it('should return a ConnectableObservable', function () {
    var source = Observable.of(1).publishBehavior(1);
    expect(source instanceof Rx.ConnectableObservable).toBe(true);
  });

  it('should mirror a simple source Observable', function () {
    var source = cold('--1-2---3-4--5-|');
    var sourceSubs =  '^              !';
    var published = source.publishBehavior('0');
    var expected =    '0-1-2---3-4--5-|';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should only emit default value if connect is not called, despite subscriptions', function () {
    var source = cold('--1-2---3-4--5-|');
    var sourceSubs = [];
    var published = source.publishBehavior('0');
    var expected =    '0';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);
  });

  it('should multicast the same values to multiple observers', function () {
    var source =     cold('-1-2-3----4-|');
    var sourceSubs =      '^           !';
    var published = source.publishBehavior('0');
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----4-|';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----4-|';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-4-|';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast an error from the source to multiple observers', function () {
    var source =     cold('-1-2-3----4-#');
    var sourceSubs =      '^           !';
    var published = source.publishBehavior('0');
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----4-#';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----4-#';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-4-#';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast the same values to multiple observers, ' +
  'but is unsubscribed explicitly and early', function () {
    var source =     cold('-1-2-3----4-|');
    var sourceSubs =      '^        !   ';
    var published = source.publishBehavior('0');
    var unsub =           '         u   ';
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----   ';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----   ';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-   ';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    // Set up unsubscription action
    var connection;
    expectObservable(hot(unsub).do(function () {
      connection.unsubscribe();
    })).toBe(unsub);

    connection = published.connect();
  });

  describe('with refCount()', function () {
    it('should connect when first subscriber subscribes', function() {
      var source = cold(       '-1-2-3----4-|');
      var sourceSubs =      '   ^           !';
      var replayed = source.publishBehavior('0').refCount();
      var subscriber1 = hot('   a|           ').mergeMapTo(replayed);
      var expected1 =       '   01-2-3----4-|';
      var subscriber2 = hot('       b|       ').mergeMapTo(replayed);
      var expected2 =       '       23----4-|';
      var subscriber3 = hot('           c|   ').mergeMapTo(replayed);
      var expected3 =       '           3-4-|';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should disconnect when last subscriber unsubscribes', function () {
      var source =     cold(   '-1-2-3----4-|');
      var sourceSubs =      '   ^        !   ';
      var replayed = source.publishBehavior('0').refCount();
      var subscriber1 = hot('   a|           ').mergeMapTo(replayed);
      var unsub1 =          '          !     ';
      var expected1   =     '   01-2-3--     ';
      var subscriber2 = hot('       b|       ').mergeMapTo(replayed);
      var unsub2 =          '            !   ';
      var expected2   =     '       23----   ';

      expectObservable(subscriber1, unsub1).toBe(expected1);
      expectObservable(subscriber2, unsub2).toBe(expected2);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should NOT be retryable', function () {
      var source =     cold('-1-2-3----4-#');
      var sourceSubs =     ['^           !',
                            '            (^!)',
                            '            (^!)',
                            '            (^!)'];
      var published = source.publishBehavior('0').refCount().retry(3);
      var subscriber1 = hot('a|           ').mergeMapTo(published);
      var expected1   =     '01-2-3----4-#';
      var subscriber2 = hot('    b|       ').mergeMapTo(published);
      var expected2   =     '    23----4-#';
      var subscriber3 = hot('        c|   ').mergeMapTo(published);
      var expected3   =     '        3-4-#';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should NOT be repeatable', function () {
      var source =     cold('-1-2-3----4-|');
      var sourceSubs =     ['^           !',
                            '            (^!)',
                            '            (^!)'];
      var published = source.publishBehavior('0').refCount().repeat(3);
      var subscriber1 = hot('a|           ').mergeMapTo(published);
      var expected1   =     '01-2-3----4-|';
      var subscriber2 = hot('    b|       ').mergeMapTo(published);
      var expected2   =     '    23----4-|';
      var subscriber3 = hot('        c|   ').mergeMapTo(published);
      var expected3   =     '        3-4-|';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });
  });

  it('should emit completed when subscribed after completed', function (done) {
    var results1 = [];
    var results2 = [];
    var subscriptions = 0;

    var source = new Observable(function (observer) {
      subscriptions++;
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
      observer.complete();
    });

    var connectable = source.publishBehavior(0);

    connectable.subscribe(function (x) {
      results1.push(x);
    });

    expect(results1).toEqual([0]);
    expect(results2).toEqual([]);

    connectable.connect();

    expect(results1).toEqual([0, 1, 2, 3, 4]);
    expect(results2).toEqual([]);
    expect(subscriptions).toBe(1);

    connectable.subscribe(function (x) {
      results2.push(x);
    }, done.fail, function () {
      expect(results2).toEqual([]);
      done();
    });
  });

  it('should multicast an empty source', function () {
    var source = cold('|');
    var sourceSubs =  '(^!)';
    var published = source.publishBehavior('0');
    var expected =    '(0|)';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast a never source', function () {
    var source = cold('-');
    var sourceSubs =  '^';
    var published = source.publishBehavior('0');
    var expected =    '0';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast a throw source', function () {
    var source = cold('#');
    var sourceSubs =  '(^!)';
    var published = source.publishBehavior('0');
    var expected =    '(0#)';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast one observable to multiple observers', function (done) {
    var results1 = [];
    var results2 = [];
    var subscriptions = 0;

    var source = new Observable(function (observer) {
      subscriptions++;
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
    });

    var connectable = source.publishBehavior(0);

    connectable.subscribe(function (x) {
      results1.push(x);
    });

    expect(results1).toEqual([0]);

    connectable.connect();

    expect(results2).toEqual([]);

    connectable.subscribe(function (x) {
      results2.push(x);
    });

    expect(results1).toEqual([0, 1, 2, 3, 4]);
    expect(results2).toEqual([4]);
    expect(subscriptions).toBe(1);
    done();
  });

  it('should follow the RxJS 4 behavior and emit nothing to observer after completed', function (done) {
    var results = [];

    var source = new Observable(function (observer) {
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
      observer.complete();
    });

    var connectable = source.publishBehavior(0);

    connectable.connect();

    connectable.subscribe(function (x) {
      results.push(x);
    });

    expect(results).toEqual([]);
    done();
  });

  it('should follow the RxJS 4 behavior and NOT allow you to reconnect by subscribing again', function (done) {
    var expected = [0, 1, 2, 3, 4];
    var i = 0;

    var source = Observable.of(1, 2, 3, 4).publishBehavior(0);

    source.subscribe(
      function (x) {
        expect(x).toBe(expected[i++]);
      },
      null,
      function () {
        source.subscribe(function (x) {
          throw 'should not be called';
        }, null, done);

        source.connect();
      });

    source.connect();
  });
});<commit_msg>style(publishBehavior-spec): fix lint<commit_after>/* globals describe, it, expect */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.publishBehavior()', function () {
  it('should return a ConnectableObservable', function () {
    var source = Observable.of(1).publishBehavior(1);
    expect(source instanceof Rx.ConnectableObservable).toBe(true);
  });

  it('should mirror a simple source Observable', function () {
    var source = cold('--1-2---3-4--5-|');
    var sourceSubs =  '^              !';
    var published = source.publishBehavior('0');
    var expected =    '0-1-2---3-4--5-|';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should only emit default value if connect is not called, despite subscriptions', function () {
    var source = cold('--1-2---3-4--5-|');
    var sourceSubs = [];
    var published = source.publishBehavior('0');
    var expected =    '0';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);
  });

  it('should multicast the same values to multiple observers', function () {
    var source =     cold('-1-2-3----4-|');
    var sourceSubs =      '^           !';
    var published = source.publishBehavior('0');
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----4-|';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----4-|';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-4-|';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast an error from the source to multiple observers', function () {
    var source =     cold('-1-2-3----4-#');
    var sourceSubs =      '^           !';
    var published = source.publishBehavior('0');
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----4-#';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----4-#';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-4-#';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast the same values to multiple observers, ' +
  'but is unsubscribed explicitly and early', function () {
    var source =     cold('-1-2-3----4-|');
    var sourceSubs =      '^        !   ';
    var published = source.publishBehavior('0');
    var unsub =           '         u   ';
    var subscriber1 = hot('a|           ').mergeMapTo(published);
    var expected1   =     '01-2-3----   ';
    var subscriber2 = hot('    b|       ').mergeMapTo(published);
    var expected2   =     '    23----   ';
    var subscriber3 = hot('        c|   ').mergeMapTo(published);
    var expected3   =     '        3-   ';

    expectObservable(subscriber1).toBe(expected1);
    expectObservable(subscriber2).toBe(expected2);
    expectObservable(subscriber3).toBe(expected3);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    // Set up unsubscription action
    var connection;
    expectObservable(hot(unsub).do(function () {
      connection.unsubscribe();
    })).toBe(unsub);

    connection = published.connect();
  });

  describe('with refCount()', function () {
    it('should connect when first subscriber subscribes', function () {
      var source = cold(       '-1-2-3----4-|');
      var sourceSubs =      '   ^           !';
      var replayed = source.publishBehavior('0').refCount();
      var subscriber1 = hot('   a|           ').mergeMapTo(replayed);
      var expected1 =       '   01-2-3----4-|';
      var subscriber2 = hot('       b|       ').mergeMapTo(replayed);
      var expected2 =       '       23----4-|';
      var subscriber3 = hot('           c|   ').mergeMapTo(replayed);
      var expected3 =       '           3-4-|';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should disconnect when last subscriber unsubscribes', function () {
      var source =     cold(   '-1-2-3----4-|');
      var sourceSubs =      '   ^        !   ';
      var replayed = source.publishBehavior('0').refCount();
      var subscriber1 = hot('   a|           ').mergeMapTo(replayed);
      var unsub1 =          '          !     ';
      var expected1   =     '   01-2-3--     ';
      var subscriber2 = hot('       b|       ').mergeMapTo(replayed);
      var unsub2 =          '            !   ';
      var expected2   =     '       23----   ';

      expectObservable(subscriber1, unsub1).toBe(expected1);
      expectObservable(subscriber2, unsub2).toBe(expected2);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should NOT be retryable', function () {
      var source =     cold('-1-2-3----4-#');
      var sourceSubs =     ['^           !',
                            '            (^!)',
                            '            (^!)',
                            '            (^!)'];
      var published = source.publishBehavior('0').refCount().retry(3);
      var subscriber1 = hot('a|           ').mergeMapTo(published);
      var expected1   =     '01-2-3----4-#';
      var subscriber2 = hot('    b|       ').mergeMapTo(published);
      var expected2   =     '    23----4-#';
      var subscriber3 = hot('        c|   ').mergeMapTo(published);
      var expected3   =     '        3-4-#';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });

    it('should NOT be repeatable', function () {
      var source =     cold('-1-2-3----4-|');
      var sourceSubs =     ['^           !',
                            '            (^!)',
                            '            (^!)'];
      var published = source.publishBehavior('0').refCount().repeat(3);
      var subscriber1 = hot('a|           ').mergeMapTo(published);
      var expected1   =     '01-2-3----4-|';
      var subscriber2 = hot('    b|       ').mergeMapTo(published);
      var expected2   =     '    23----4-|';
      var subscriber3 = hot('        c|   ').mergeMapTo(published);
      var expected3   =     '        3-4-|';

      expectObservable(subscriber1).toBe(expected1);
      expectObservable(subscriber2).toBe(expected2);
      expectObservable(subscriber3).toBe(expected3);
      expectSubscriptions(source.subscriptions).toBe(sourceSubs);
    });
  });

  it('should emit completed when subscribed after completed', function (done) {
    var results1 = [];
    var results2 = [];
    var subscriptions = 0;

    var source = new Observable(function (observer) {
      subscriptions++;
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
      observer.complete();
    });

    var connectable = source.publishBehavior(0);

    connectable.subscribe(function (x) {
      results1.push(x);
    });

    expect(results1).toEqual([0]);
    expect(results2).toEqual([]);

    connectable.connect();

    expect(results1).toEqual([0, 1, 2, 3, 4]);
    expect(results2).toEqual([]);
    expect(subscriptions).toBe(1);

    connectable.subscribe(function (x) {
      results2.push(x);
    }, done.fail, function () {
      expect(results2).toEqual([]);
      done();
    });
  });

  it('should multicast an empty source', function () {
    var source = cold('|');
    var sourceSubs =  '(^!)';
    var published = source.publishBehavior('0');
    var expected =    '(0|)';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast a never source', function () {
    var source = cold('-');
    var sourceSubs =  '^';
    var published = source.publishBehavior('0');
    var expected =    '0';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast a throw source', function () {
    var source = cold('#');
    var sourceSubs =  '(^!)';
    var published = source.publishBehavior('0');
    var expected =    '(0#)';

    expectObservable(published).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(sourceSubs);

    published.connect();
  });

  it('should multicast one observable to multiple observers', function (done) {
    var results1 = [];
    var results2 = [];
    var subscriptions = 0;

    var source = new Observable(function (observer) {
      subscriptions++;
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
    });

    var connectable = source.publishBehavior(0);

    connectable.subscribe(function (x) {
      results1.push(x);
    });

    expect(results1).toEqual([0]);

    connectable.connect();

    expect(results2).toEqual([]);

    connectable.subscribe(function (x) {
      results2.push(x);
    });

    expect(results1).toEqual([0, 1, 2, 3, 4]);
    expect(results2).toEqual([4]);
    expect(subscriptions).toBe(1);
    done();
  });

  it('should follow the RxJS 4 behavior and emit nothing to observer after completed', function (done) {
    var results = [];

    var source = new Observable(function (observer) {
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.next(4);
      observer.complete();
    });

    var connectable = source.publishBehavior(0);

    connectable.connect();

    connectable.subscribe(function (x) {
      results.push(x);
    });

    expect(results).toEqual([]);
    done();
  });

  it('should follow the RxJS 4 behavior and NOT allow you to reconnect by subscribing again', function (done) {
    var expected = [0, 1, 2, 3, 4];
    var i = 0;

    var source = Observable.of(1, 2, 3, 4).publishBehavior(0);

    source.subscribe(
      function (x) {
        expect(x).toBe(expected[i++]);
      },
      null,
      function () {
        source.subscribe(function (x) {
          throw 'should not be called';
        }, null, done);

        source.connect();
      });

    source.connect();
  });
});<|endoftext|>


<commit_before>var http = require('http'),
    _ = require('underscore');

var ourTeamId = 1;

var extractHandFromGame = function (game_state) {
    var hand = [],
        me = game_state.players.filter(function (player) {
            if (player.id == ourTeamId) return player;
        }),
        publicCards = game_state.community_cards;
    _.forEach(me[0].hole_cards, function (card) {
        hand.push(card);
    });
    _.forEach(publicCards, function (card) {
        hand.push(card);
    });

    return hand;
};

var playGame = function (game_state, bet) {
    var myHand = extractHandFromGame(game_state);
    var request = http.get("http://rainman.leanpoker.org/rank?cards=" + JSON.stringify(myHand), function (response) {
        var body = '';
        response.on('data', function (d) {
            body += d;
        });
        response.on('end', function () {
            var data = JSON.parse(body);
            console.log(body);
            placeBet(data.rank, game_state, bet);
        });
    });
    request.on('error', function (err) {
        console.log("an error occured ");
        bet(0);
    });

};

var placeBet = function (handRank, game_state, bet) {
    if (handRank == 0 ) {
        bet(0);
    } else if (handRank >= 1 && handRank <= 5) {
        call(game_state, bet);
    } else {
        raise(game_state, bet);
    }
};

var call = function (game_state, bet) {
    return bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet);
};

var raise = function raise(game_state, bet) {
    return bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet + game_state.minimum_raise + 200);
};

module.exports = {
    VERSION: "V1",

    bet_request: function (game_state, bet) {
        if (game_state)
            console.log(JSON.stringify(game_state));

        playGame(game_state, bet);
    },

    showdown: function (game_state) {

    }
};

<commit_msg> rank cards only after flop<commit_after>var http = require('http'),
    _ = require('underscore');

var ourTeamId = 1;

var extractHandFromGame = function (game_state) {
    var hand = [],
        me = game_state.players.filter(function (player) {
            if (player.id == ourTeamId) return player;
        }),
        publicCards = game_state.community_cards;
    _.forEach(me[0].hole_cards, function (card) {
        hand.push(card);
    });
    _.forEach(publicCards, function (card) {
        hand.push(card);
    });

    return hand;
};

var playGame = function (game_state, bet) {
    var myHand = extractHandFromGame(game_state);
    if(myHand.length >= 5) {
        var request = http.get("http://rainman.leanpoker.org/rank?cards=" + JSON.stringify(myHand), function (response) {
            var body = '';
            response.on('data', function (d) {
                body += d;
            });
            response.on('end', function () {
                var data = JSON.parse(body);
                console.log(body);
                placeBet(data.rank, game_state, bet);
            });
        });
        request.on('error', function (err) {
            console.log("an error occured ");
            bet(0);
        });
    } else {
        placeBet(1, game_state, bet);
    }

};

var placeBet = function (handRank, game_state, bet) {
    if (handRank == 0 ) {
        bet(0);
    } else if (handRank >= 1 && handRank <= 5) {
        call(game_state, bet);
    } else {
        raise(game_state, bet);
    }
};

var call = function (game_state, bet) {
    return bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet);
};

var raise = function raise(game_state, bet) {
    return bet(game_state.current_buy_in - game_state.players[game_state.in_action].bet + game_state.minimum_raise + 200);
};

module.exports = {
    VERSION: "V1",

    bet_request: function (game_state, bet) {
        if (game_state)
            console.log(JSON.stringify(game_state));

        playGame(game_state, bet);
    },

    showdown: function (game_state) {

    }
};

<|endoftext|>