<commit_before>/*
	drawdiv.js is able to draw as many divs as you want inside an other div.
	If you want to change the rootdiv, just call changeRootDiv(newRootDiv).
*/

//settings
var rootDivId ='annotationZone';
var rootDivDom = $('#annotationZone');
var rectPrefix = "rect-";
var divCounter = 0;
var drag = false;

var startXRel;
var startYRel;

var opacityFactor ="0.125";
var opacityFactorHighlight ="0.5";

var currentCanvasHeight=0;
var min_height_rect_rel=0.06;
var max_height_rect_rel=0.55;
var min_width_rect_rel=0.06;
var max_width_rect_rel=0.75;

var min_height_rect_abs=50;
var max_height_rect_abs=300;
var min_width_rect_abs=50;
var max_width_rect_abs=300;

var currentTagName="";
var currentTagColor="";

var bWidth ="3";
var bRadius = "4";

function absToViewTop(relToView,canvas){
	return rootDivDom.offset().top+parseInt(relToView,10);
}
function absToViewLeft(relToView,canvas){
	return rootDivDom.offset().left+parseInt(relToView,10);
}

function getCurrentTagName(){
	return currentTagName;
}

function setCurrentTagName(tTagName){
	currentTagName=tTagName;
}
function getCurrentTagColor(){
	return currentTagColor;
}
function setCurrentTagColor(tTagColor){
	currentTagColor=tTagColor;
}

function initRects() {
	rootDivDom.bind('mousedown', mouseDown);
	rootDivDom.bind('mouseup', mouseUp);
	rootDivDom.bind('mousemove', mouseMove);
	rootDivDom.bind('mouseleave', mouseLeave);
}
function appendClickEventOnRect(){
	$(".slideRect").each(function(){
		$(this).click(function(){
			var text = $(".activeTextArea").val();
			if(text.slice(-1)==" "){
				$(".activeTextArea").val( text+ $(this).attr("data-tagName"));
			}else{
				$(".activeTextArea").val( text+ " "+ $(this).attr("data-tagName"));
			}

		});
	});
}

function mouseDown(e){
	if(e.which!=3){

		if(e.pageX - rootDivDom.offset().left > (min_width_rect_abs/2)){
			if(e.pageX - rootDivDom.offset().left< parseInt(rootDivDom.width())- (min_width_rect_abs/2)){
				startXRel = e.pageX - rootDivDom.offset().left - (min_width_rect_abs/2);
			}else{
				startXRel = parseInt(rootDivDom.width())- min_width_rect_abs;

			}
		}else{
			startXRel = 0;
		}
		if(e.pageY - rootDivDom.offset().top > (min_height_rect_abs/2)){
			if(e.pageY - rootDivDom.offset().top< parseInt(rootDivDom.height())- (min_height_rect_abs/2)){
				startYRel = e.pageY - rootDivDom.offset().top - (min_height_rect_abs/2);
			}else{
				startYRel = parseInt(rootDivDom.height())- min_height_rect_abs;
			}
		}else{
			startYRel = 0;
		}

		//creating Div with default values
		element = $('<div/>', {
			id: rectPrefix+divCounter,
			position: 'absolute',
			class: 'slideRect debug',
			opacity: opacityFactorHighlight
		});
 //CHANGE LATER
		element.css({
			position: 'absolute',
			backgroundColor: getCurrentTagColor(),
			borderRadius: bWidth+"px solid #C1E0FF",
		});

		//tag
		element.attr("data-tagName","#"+getCurrentTagName());

		//setting drawed div on activeRects
		element.className = element.className+ " activeRect tagname-"+element.attr("data-tagName").slice(1);

		//transition //CHECK IF THIS LINES ARE CORRECT
		element.prop("-moz-transition", "opacity 0.1s linear");
		element.prop("-ms-transition", "opacity 0.1s linear");
		element.prop("-o-transition", "opacity 0.1s linear");
		element.prop("transition", "opacity 0.1s linear");

		element.attr("data-relstartcoord",(startXRel+";"+startYRel));

		element.offset({left: absToViewLeft(startXRel, this)});
		element.offset({top: absToViewLeft(startYRel, this)});
		element.width(min_width_rect_abs);
		element.height(min_height_rect_abs);
		element.appendTo('#annotationZone');

		appendClickEventOnRect();
		drag=true;
	}

}

function mouseUp(e){
		element.appendTo('#annotationZone');
	/*elementTag.style.opacity = 0;
	if(animation){
				var tl = new TimelineMax();
				tl.append(TweenMax.fromTo("#"+element.id,.15, {scale:1.02}, {css:{scale:1}, ease:Quad.easeIn}));
				oTransitionRect(element.id,"tagname-"+element.getAttribute("data-tagName").slice(1), opacityFactor, opacityFactorHighlight);
	}
	canvas.style.cursor = "default";*/
	divCounter=divCounter+1;
  drag = false;
}

function mouseMove(e){
	if (drag) {
  	var currentX = e.pageX - rootDivDom.offset().left;
  	var currentY = e.pageY - rootDivDom.offset().top;
   	var divWidth = currentX - startXRel;
    var divHeight = currentY - startYRel;
    var relSaveX=0;
    var relSaveY=0;

    if(currentX - startXRel < 0){
	    if((max_width_rect_abs-min_width_rect_abs)<Math.abs(currentX - startXRel)){
	    	relSaveX = startXRel-(max_width_rect_abs-min_width_rect_abs);
	    	element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft + relSaveX +tagOffsetLeft+ 'px';
	    	divWidth = max_width_rect_abs;
	    }else{
	    	relSaveX =currentX;
				element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft + relSaveX +tagOffsetLeft+ 'px';
	    	divWidth = Math.abs(currentX - startXRel)+ min_width_rect_abs;
	    }
    }else{
    	if((currentX-startXRel)<min_width_rect_abs){
    		relSaveX =startXRel;
				element.offset({left: rootDivDom.offset().left+ relSaveX});
    		//elementTag.style.left =this.offsetLeft+relSaveX +tagOffsetLeft+ 'px';
    		divWidth = min_width_rect_abs;
    	}else{
    		relSaveX=startXRel;
	    	element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft+relSaveX+tagOffsetLeft + 'px';
    		if((currentX-startXRel)>max_width_rect_abs){
    			divWidth= max_width_rect_abs;
    		}else{
    			divWidth = currentX-startXRel;
    		}
    	}

    }
    element.width (Math.abs(divWidth));

    if(currentY - startYRel < 0){
	    if((max_height_rect_abs-min_height_rect_abs)<Math.abs(currentY - startYRel)){
	    	relSaveY = startYRel-(max_height_rect_abs-min_height_rect_abs);
				element.offset({top: rootDivDom.offset().top+ relSaveY});
	    	//elementTag.style.top = this.offsetTop + relSaveY -tagOffsetTop + 'px';
	    	divHeight = max_height_rect_abs;
	    }else{
	    	relSaveY =currentY;
	    	element.offset({top: rootDivDom.offset().top+ relSaveY});
				//elementTag.style.top = this.offsetTop + relSaveY -tagOffsetTop + 'px';

	    	divHeight = Math.abs(currentY - startYRel)+ min_height_rect_abs;
	    }
    }else{
    	if((currentY-startYRel)<min_height_rect_abs){
    		relSaveY =startYRel;
				element.offset({top: startYRel+  rootDivDom.offset().top});
    		//elementTag.style.top =this.offsetTop+ relSaveY -tagOffsetTop + 'px';
    		divHeight = min_height_rect_abs;
    	}else{
    		relSaveY = startYRel;

				element.offset({top: rootDivDom.offset().top+ relSaveY});
	    	//elementTag.style.top = this.offsetTop+relSaveY-tagOffsetTop + 'px';
    		if((currentY-startYRel)>max_height_rect_abs){
    			divHeight= max_height_rect_abs;
    		}else{
    			divHeight = currentY-startYRel;
    		}
    	}

    }
    element.height(Math.abs(divHeight));

    element.attr("data-relwidthheight", Math.abs(divWidth)+";"+Math.abs(divHeight));
    element.attr("data-relstartcoord", relSaveX +";"+relSaveY);
  }

}

function mouseLeave(e){
	if(drag){mouseleftCanvas=true;}
}
//predefined variables

console.log("test: "+rootDivDom.height());
initRects();
<commit_msg>rectangles now rescaling on window resizing<commit_after>/*
	drawdiv.js is able to draw as many divs as you want inside an other div.
	If you want to change the rootdiv, just call changeRootDiv(newRootDiv).
*/

//settings
var rootDivId ='annotationZone';
var rootDivDom = $('#annotationZone');
var rectPrefix = "rect-";
var divCounter = 0;
var drag = false;

var startXRel;
var startYRel;

var opacityFactor ="0.125";
var opacityFactorHighlight ="0.5";

//Random Values
var tagFontSize = 1;
var tagIffsetTop =4;

var currentCanvasHeight=0;
var min_height_rect_rel=0.06;
var max_height_rect_rel=0.55;
var min_width_rect_rel=0.06;
var max_width_rect_rel=0.75;

var min_height_rect_abs=50;
var max_height_rect_abs=300;
var min_width_rect_abs=50;
var max_width_rect_abs=300;

var currentTagName="";
var currentTagColor="";

var bWidth ="3";
var bRadius = "4";

function absToViewTop(relToView,canvas){
	console.log(rootDivDom.offset().top);
	return rootDivDom.offset().top+parseInt(relToView,10);
}
function absToViewLeft(relToView,canvas){
	return rootDivDom.offset().left+parseInt(relToView,10);
}

function getCurrentTagName(){
	return currentTagName;
}

function setCurrentTagName(tTagName){
	currentTagName=tTagName;
}
function getCurrentTagColor(){
	return currentTagColor;
}
function setCurrentTagColor(tTagColor){
	currentTagColor=tTagColor;
}

function initRects() {
	rootDivDom.bind('mousedown', mouseDown);
	rootDivDom.bind('mouseup', mouseUp);
	rootDivDom.bind('mousemove', mouseMove);
	rootDivDom.bind('mouseleave', mouseLeave);
}
function appendClickEventOnRect(){
	$(".slideRect").each(function(){
		$(this).click(function(){
			var text = $(".activeTextArea").val();
			if(text.slice(-1)==" "){
				$(".activeTextArea").val( text+ $(this).attr("data-tagName"));
			}else{
				$(".activeTextArea").val( text+ " "+ $(this).attr("data-tagName"));
			}

		});
	});
}

function mouseDown(e){
	if(e.which!=3){

		if(e.pageX - rootDivDom.offset().left > (min_width_rect_abs/2)){
			if(e.pageX - rootDivDom.offset().left< parseInt(rootDivDom.width())- (min_width_rect_abs/2)){
				startXRel = e.pageX - rootDivDom.offset().left - (min_width_rect_abs/2);
			}else{
				startXRel = parseInt(rootDivDom.width())- min_width_rect_abs;

			}
		}else{
			startXRel = 0;
		}
		if(e.pageY - rootDivDom.offset().top > (min_height_rect_abs/2)){
			if(e.pageY - rootDivDom.offset().top< parseInt(rootDivDom.height())- (min_height_rect_abs/2)){
				startYRel = e.pageY - rootDivDom.offset().top - (min_height_rect_abs/2);
			}else{
				startYRel = parseInt(rootDivDom.height())- min_height_rect_abs;
			}
		}else{
			startYRel = 0;
		}

		//creating Div with default values
		element = $('<div/>', {
			id: rectPrefix+divCounter,
			position: 'absolute',
			class: 'slideRect debug',
			opacity: opacityFactorHighlight
		});
 //CHANGE LATER
		element.css({
			position: 'absolute',
			backgroundColor: getCurrentTagColor(),
			borderRadius: bWidth+"px solid #C1E0FF",
		});

		//tag
		element.attr("data-tagName","#"+getCurrentTagName());

		//setting drawed div on activeRects
		element.className = element.className+ " activeRect tagname-"+element.attr("data-tagName").slice(1);

		//transition //CHECK IF THIS LINES ARE CORRECT
		element.prop("-moz-transition", "opacity 0.1s linear");
		element.prop("-ms-transition", "opacity 0.1s linear");
		element.prop("-o-transition", "opacity 0.1s linear");
		element.prop("transition", "opacity 0.1s linear");

		element.attr("data-relstartcoord",(startXRel+";"+startYRel));

		element.offset({left: absToViewLeft(startXRel, this)});
		element.offset({top: absToViewLeft(startYRel, this)});
		element.width(min_width_rect_abs);
		element.height(min_height_rect_abs);
		element.appendTo('#annotationZone');

		appendClickEventOnRect();
		drag=true;
	}

}

function mouseUp(e){
		element.appendTo('#annotationZone');
	/*elementTag.style.opacity = 0;
	if(animation){
				var tl = new TimelineMax();
				tl.append(TweenMax.fromTo("#"+element.id,.15, {scale:1.02}, {css:{scale:1}, ease:Quad.easeIn}));
				oTransitionRect(element.id,"tagname-"+element.getAttribute("data-tagName").slice(1), opacityFactor, opacityFactorHighlight);
	}
	canvas.style.cursor = "default";*/
	divCounter=divCounter+1;
  drag = false;
}

function mouseMove(e){
	if (drag) {
  	var currentX = e.pageX - rootDivDom.offset().left;
  	var currentY = e.pageY - rootDivDom.offset().top;
   	var divWidth = currentX - startXRel;
    var divHeight = currentY - startYRel;
    var relSaveX=0;
    var relSaveY=0;

    if(currentX - startXRel < 0){
	    if((max_width_rect_abs-min_width_rect_abs)<Math.abs(currentX - startXRel)){
	    	relSaveX = startXRel-(max_width_rect_abs-min_width_rect_abs);
	    	element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft + relSaveX +tagOffsetLeft+ 'px';
	    	divWidth = max_width_rect_abs;
	    }else{
	    	relSaveX =currentX;
				element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft + relSaveX +tagOffsetLeft+ 'px';
	    	divWidth = Math.abs(currentX - startXRel)+ min_width_rect_abs;
	    }
    }else{
    	if((currentX-startXRel)<min_width_rect_abs){
    		relSaveX =startXRel;
				element.offset({left: rootDivDom.offset().left+ relSaveX});
    		//elementTag.style.left =this.offsetLeft+relSaveX +tagOffsetLeft+ 'px';
    		divWidth = min_width_rect_abs;
    	}else{
    		relSaveX=startXRel;
	    	element.offset({left: rootDivDom.offset().left+ relSaveX});
	    	//elementTag.style.left = this.offsetLeft+relSaveX+tagOffsetLeft + 'px';
    		if((currentX-startXRel)>max_width_rect_abs){
    			divWidth= max_width_rect_abs;
    		}else{
    			divWidth = currentX-startXRel;
    		}
    	}

    }
    element.width (Math.abs(divWidth));

    if(currentY - startYRel < 0){
	    if((max_height_rect_abs-min_height_rect_abs)<Math.abs(currentY - startYRel)){
	    	relSaveY = startYRel-(max_height_rect_abs-min_height_rect_abs);
				element.offset({top: rootDivDom.offset().top+ relSaveY});
	    	//elementTag.style.top = this.offsetTop + relSaveY -tagOffsetTop + 'px';
	    	divHeight = max_height_rect_abs;
	    }else{
	    	relSaveY =currentY;
	    	element.offset({top: rootDivDom.offset().top+ relSaveY});
				//elementTag.style.top = this.offsetTop + relSaveY -tagOffsetTop + 'px';

	    	divHeight = Math.abs(currentY - startYRel)+ min_height_rect_abs;
	    }
    }else{
    	if((currentY-startYRel)<min_height_rect_abs){
    		relSaveY =startYRel;
				element.offset({top: startYRel+  rootDivDom.offset().top});
    		//elementTag.style.top =this.offsetTop+ relSaveY -tagOffsetTop + 'px';
    		divHeight = min_height_rect_abs;
    	}else{
    		relSaveY = startYRel;

				element.offset({top: rootDivDom.offset().top+ relSaveY});
	    	//elementTag.style.top = this.offsetTop+relSaveY-tagOffsetTop + 'px';
    		if((currentY-startYRel)>max_height_rect_abs){
    			divHeight= max_height_rect_abs;
    		}else{
    			divHeight = currentY-startYRel;
    		}
    	}

    }
    element.height(Math.abs(divHeight));

    element.attr("data-relwidthheight", Math.abs(divWidth)+";"+Math.abs(divHeight));
    element.attr("data-relstartcoord", relSaveX +";"+relSaveY);
  }

}

function mouseLeave(e){
	if(drag){mouseleftCanvas=true;}
}

function rescalingRects(rectClassName,tagClassName){
	var allElements = $("."+rectClassName);
	var scalingFactor = parseInt(rootDivDom.height())/currentCanvasHeight;
	//console.log("height "+ rootDivDom.height() + " currentCanvasHeight"+ currentCanvasHeight)
	/*var allElementsTag = $("."+tagClassName);
	tagFontSize = parseInt(rootDivDom.height())*tagFontSizeFactor;*/
	tagOffsetTop = tagFontSize+4;
	//console.log("Scaling factor: "+scalingFactor);

	if(currentCanvasHeight!=0){
		for (var i = 0, len = allElements.length; i < len; i++) {
			var coordAttr=$(allElements[i]).attr("data-relstartcoord").split(";");
			var startXAttr = coordAttr[0]*scalingFactor;
			var startYAttr = coordAttr[1]*scalingFactor;
	  	$(allElements[i]).attr("data-relstartcoord",startXAttr+";"+startYAttr);
			$(allElements[i]).css('left',  Math.round(startXAttr));
			$(allElements[i]).css('top',  Math.round(startYAttr));
	  	$(allElements[i]).css('height',  Math.round(parseInt($(allElements[i]).css('height'))*scalingFactor));
			$(allElements[i]).css('width',   Math.round(parseInt($(allElements[i]).css('width'))*scalingFactor));
		}
	}

	currentCanvasHeight=parseInt(rootDivDom.height());
}

function alwaysRescaleRects(){
	rescalingRects("slideRect", "slideRectTag");
	currentCanvasHeight=parseInt(rootDivDom.height());

	//tagFontSize = currentCanvasHeight*tagFontSizeFactor;
	//tagOffsetTop = tagFontSize+4;

	min_height_rect_abs=currentCanvasHeight*min_height_rect_rel;
	max_height_rect_abs=currentCanvasHeight*max_height_rect_rel;
	min_width_rect_abs=currentCanvasHeight*min_width_rect_rel;
	max_width_rect_abs=currentCanvasHeight*max_width_rect_rel;

}
console.log("test: "+rootDivDom.height());
initRects();

window.onresize = function(){
  		alwaysRescaleRects();
}
<|endoftext|>


<commit_before>app.controller('mapController', function($scope, $stateParams, communityDataService, directionsDataService) {

    //Obtain lat and lng for searched city
    var lat = parseFloat($stateParams.lat),
        lng = parseFloat($stateParams.lng);

    //Hard code bound for Chicago
    var NW = {lat: 41.9786, lng: -87.9047},
        SE = {lat: 41.6600, lng: -87.5500};

    var defaultBounds = new google.maps.LatLngBounds(NW, SE);
    var defaultCenter = defaultBounds.getCenter();

    angular.element(document).ready(function () {
        $scope.map = new google.maps.Map(document.getElementById('map'), {
            disableDefaultUI: true,
            center: {lat: defaultCenter.lat(), lng: defaultCenter.lng()},
            zoom: 8,
            scaleControl: false
        });

        $scope.map.fitBounds(defaultBounds);
        google.maps.event.addListenerOnce(map, 'idle', function() {
            google.maps.event.trigger(map, 'resize');
        });
        setPreferences();

        $scope.directionsService = new google.maps.DirectionsService();
        $scope.directionsDisplay = new google.maps.DirectionsRenderer();
        $scope.directionsDisplay.setMap($scope.map);
    });

    $scope.categories = {
        violentCrimePctOfAvg    :   'Violent Crime',
        nonViolentCrimePctOfAvg :   'Nonviolent Crime',
        nightlifePctOfAvg       :   'Nightlife',
        pricePctOfAvg           :   'Price',
        crowdedPctOfAvg         :   'Crowded'
    };

    $scope.preferences = [];
    $scope.showDetail = false;

    //Update communities when time limit changes
    $scope.$on('timeChange', function(ev){
        filterData();
    });

    //Retrieve commute time for the communities
    var coordinatesInfo = directionsDataService.getCommunityTime();
    $scope.communityTimes = coordinatesInfo.communityTimes;
    $scope.timeLimit = coordinatesInfo.maxTime;

    //Populate map with preferences from database
    function setPreferences() {
        communityDataService.preferences()
            .done(function (result) {
                $scope.communityData = result;
                $scope.safeApply();
                filterData();
                mapPreferences();
            })
            .fail(function () {
                console.log("Unable to retrieve preferences");
            });

    };

    //Filter data based on time limit
    function filterData(){
        $scope.preferences = [];
        var count = 0,
            index = 0;
        while (count < 10 && index < $scope.communityData.length){
            if ($scope.communityTimes[index] !== null && $scope.timeLimit >= $scope.communityTimes[index]){
                $scope.preferences.push($scope.communityData[index]);
                count++;
            }
            index++;
        }
        $scope.safeApply();
    };

    //Map the preferred neighborhoods
    function mapPreferences() {
        $scope.neighborhoods = [];

        for (var i = 0; i < $scope.preferences.length; i++) {

            var preference = $scope.preferences[i];
            var bounds = new google.maps.LatLngBounds();

            for (var j =0; j < preference.outline.length; j++) {
                var xy = preference.outline[j];
                var point = new google.maps.LatLng({lat:xy.lat,lng:xy.lng});
                bounds.extend(point);
            }

            var neighborhood = new google.maps.Polygon({
                map             : $scope.map,
                paths           : preference.outline,
                fillColor       : '#2e618d',
                strokeOpacity   : 1,
                fillOpacity     : 0.9 - (0.05 * i),
                name            : preference.name,
                bounds          : bounds,
                prefIndex       : i
            });

            $scope.neighborhoods.push(neighborhood);

            google.maps.event.addListener(neighborhood, 'click', function (event) {
                $scope.selectedPreference = $scope.preferences[this.prefIndex];
                $scope.showDetail = true;

                //calcRoute($scope.preferences[this.prefIndex].bounds.getCenter());

                $scope.map.fitBounds(this.bounds);
                google.maps.event.addListenerOnce(map, 'idle', function() {
                    google.maps.event.trigger(map, 'resize');
                });
                $scope.safeApply();
            });

        }
    };

    $scope.choose = function (index) {
        google.maps.event.trigger($scope.neighborhoods[index], 'click', function (event) {
        });
    };

    $scope.$on('return', function () {
        returnToMainPanel();
    });

    function returnToMainPanel() {
        $scope.showDetail = false;
        $scope.map.fitBounds(defaultBounds);
        google.maps.event.addListenerOnce(map, 'idle', function() {
            google.maps.event.trigger(map, 'resize');
        });
    }

    $scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };

    $scope.getStars = function(n) {
        return new Array(n);
    };

    function calcRoute(end) {
        var request = {
            origin:defaultCenter,
            destination:end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        $scope.directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                $scope.directionsDisplay.setDirections(result);
            }
        });
    }
});<commit_msg>dynamically redraw neighborhoods when changing slidebar<commit_after>app.controller('mapController', function($scope, $stateParams, communityDataService, directionsDataService) {

    //Obtain lat and lng for searched city
    var lat = parseFloat($stateParams.lat),
        lng = parseFloat($stateParams.lng);

    //Hard code bound for Chicago
    var NW = {lat: 41.9786, lng: -87.9047},
        SE = {lat: 41.6600, lng: -87.5500};

    var defaultBounds = new google.maps.LatLngBounds(NW, SE);
    var defaultCenter = defaultBounds.getCenter();

    angular.element(document).ready(function () {
        $scope.map = new google.maps.Map(document.getElementById('map'), {
            disableDefaultUI: true,
            center: {lat: defaultCenter.lat(), lng: defaultCenter.lng()},
            zoom: 8,
            scaleControl: false
        });

        $scope.map.fitBounds(defaultBounds);
        google.maps.event.addListenerOnce(map, 'idle', function() {
            google.maps.event.trigger(map, 'resize');
        });
        setPreferences();

        $scope.directionsService = new google.maps.DirectionsService();
        $scope.directionsDisplay = new google.maps.DirectionsRenderer();
        $scope.directionsDisplay.setMap($scope.map);
    });

    $scope.categories = {
        violentCrimePctOfAvg    :   'Violent Crime',
        nonViolentCrimePctOfAvg :   'Nonviolent Crime',
        nightlifePctOfAvg       :   'Nightlife',
        pricePctOfAvg           :   'Price',
        crowdedPctOfAvg         :   'Crowded'
    };

    $scope.preferences = [];
    $scope.showDetail = false;

    //Update communities when time limit changes
    $scope.$on('timeChange', function(ev){
        removeNeighborhoods();
        filterData();
        mapPreferences();
    });

    //Retrieve commute time for the communities
    var coordinatesInfo = directionsDataService.getCommunityTime();
    $scope.communityTimes = coordinatesInfo.communityTimes;
    $scope.timeLimit = coordinatesInfo.maxTime;

    //Populate map with preferences from database
    function setPreferences() {
        communityDataService.preferences()
            .done(function (result) {
                $scope.communityData = result;
                $scope.safeApply();
                filterData();
                mapPreferences();
            })
            .fail(function () {
                console.log("Unable to retrieve preferences");
            });

    };

    //Filter data based on time limit
    function filterData(){
        $scope.preferences = [];
        $scope.$apply();
        var count = 0,
            index = 0;
        while (count < 10 && index < $scope.communityData.length){
            if ($scope.communityTimes[index] !== null && $scope.timeLimit >= $scope.communityTimes[index]){
                $scope.preferences.push($scope.communityData[index]);
                count++;
            }
            index++;
        }
        $scope.safeApply();
    };

    //Remove neighborhoods
    function removeNeighborhoods(){
        for (var i =0 ; i< $scope.neighborhoods.length; i++){
            $scope.neighborhoods[i].setMap(null);
        }
        $scope.$apply();
    };

    //Map the preferred neighborhoods
    function mapPreferences() {
        $scope.neighborhoods = [];
        $scope.$apply();

        for (var i = 0; i < $scope.preferences.length; i++) {

            var preference = $scope.preferences[i];
            var bounds = new google.maps.LatLngBounds();

            for (var j =0; j < preference.outline.length; j++) {
                var xy = preference.outline[j];
                var point = new google.maps.LatLng({lat:xy.lat,lng:xy.lng});
                bounds.extend(point);
            }

            var neighborhood = new google.maps.Polygon({
                map             : $scope.map,
                paths           : preference.outline,
                fillColor       : '#2e618d',
                strokeOpacity   : 1,
                fillOpacity     : 0.9 - (0.05 * i),
                name            : preference.name,
                bounds          : bounds,
                prefIndex       : i
            });

            $scope.neighborhoods.push(neighborhood);

            google.maps.event.addListener(neighborhood, 'click', function (event) {
                $scope.selectedPreference = $scope.preferences[this.prefIndex];
                $scope.showDetail = true;

                //calcRoute($scope.preferences[this.prefIndex].bounds.getCenter());

                $scope.map.fitBounds(this.bounds);
                google.maps.event.addListenerOnce(map, 'idle', function() {
                    google.maps.event.trigger(map, 'resize');
                });
                $scope.safeApply();
            });

        }
    };

    $scope.choose = function (index) {
        google.maps.event.trigger($scope.neighborhoods[index], 'click', function (event) {
        });
    };

    $scope.$on('return', function () {
        returnToMainPanel();
    });

    function returnToMainPanel() {
        $scope.showDetail = false;
        $scope.map.fitBounds(defaultBounds);
        google.maps.event.addListenerOnce(map, 'idle', function() {
            google.maps.event.trigger(map, 'resize');
        });
    }

    $scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };

    $scope.getStars = function(n) {
        return new Array(n);
    };

    function calcRoute(end) {
        var request = {
            origin:defaultCenter,
            destination:end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        $scope.directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                $scope.directionsDisplay.setDirections(result);
            }
        });
    }
});<|endoftext|>


<commit_before>/* global module, asyncTest, $, ok, equal, notEqual, start, test, Util, testLog */

(function() {

    module("strings", {
        setup: function () {
            testLog.reset();
        }
    });

    test("getSubString", function() {
        equal(OpenSeadragon.getString("Errors.Dzi"),
            "Hmm, this doesn't appear to be a valid Deep Zoom Image.",
            "Read sub-string");
    });

    test("getStringWithPlaceholders", function() {
        equal(OpenSeadragon.getString("Errors.OpenFailed", "foo", "bar"),
              "Unable to open foo: bar",
              "String placeholder replacement");
    });

    test("getInvalidString", function() {
        equal(OpenSeadragon.getString("Greeting"), "", "Handled unset string key");
        ok(testLog.debug.contains('["Untranslated source string:","Greeting"]'),
                                  'Invalid string keys are logged');

        equal(OpenSeadragon.getString("Errors"), "", "Handled requesting parent key");
        ok(testLog.debug.contains('["Untranslated source string:","Errors"]'),
                                  'Invalid string parent keys are logged');
    });

    test("setString", function() {
        OpenSeadragon.setString("Greeting", "Hello world");
        equal(OpenSeadragon.getString("Greeting"), "Hello world",
            "Set a string");
    });

    test("setSubString", function() {
       OpenSeadragon.setString("CustomGreeting.Hello", "Hello world");
       equal(OpenSeadragon.getString("CustomGreeting.Hello"), "Hello world",
           "Set a sub-string");
    });

})();
<commit_msg>updated test for console.log instead of console.debug<commit_after>/* global module, asyncTest, $, ok, equal, notEqual, start, test, Util, testLog */

(function() {

    module("strings", {
        setup: function () {
            testLog.reset();
        }
    });

    test("getSubString", function() {
        equal(OpenSeadragon.getString("Errors.Dzi"),
            "Hmm, this doesn't appear to be a valid Deep Zoom Image.",
            "Read sub-string");
    });

    test("getStringWithPlaceholders", function() {
        equal(OpenSeadragon.getString("Errors.OpenFailed", "foo", "bar"),
              "Unable to open foo: bar",
              "String placeholder replacement");
    });

    test("getInvalidString", function() {
        equal(OpenSeadragon.getString("Greeting"), "", "Handled unset string key");
        ok(testLog.log.contains('["Untranslated source string:","Greeting"]'),
                                  'Invalid string keys are logged');

        equal(OpenSeadragon.getString("Errors"), "", "Handled requesting parent key");
        ok(testLog.log.contains('["Untranslated source string:","Errors"]'),
                                  'Invalid string parent keys are logged');
    });

    test("setString", function() {
        OpenSeadragon.setString("Greeting", "Hello world");
        equal(OpenSeadragon.getString("Greeting"), "Hello world",
            "Set a string");
    });

    test("setSubString", function() {
       OpenSeadragon.setString("CustomGreeting.Hello", "Hello world");
       equal(OpenSeadragon.getString("CustomGreeting.Hello"), "Hello world",
           "Set a sub-string");
    });

})();
<|endoftext|>


<commit_before>/* jslint browser: true */

define([
	'backbone',
	'controller/AppRouter'
], function (Backbone, AppRouter) {
	"use strict";

	var router = new AppRouter();
	Backbone.history.start({
		root: 'manager'
	});

	return router;
});
<commit_msg>Added a trailing slash to the root url for the backbone history<commit_after>/* jslint browser: true */

define([
	'backbone',
	'controller/AppRouter'
], function (Backbone, AppRouter) {
	"use strict";

	var router = new AppRouter();
	Backbone.history.start({
		root: 'manager/'
	});

	return router;
});
<|endoftext|>


<commit_before>'use strict';

function SClass(_clazz, numberOfFields) {
    SObject.call(this, _clazz, numberOfFields);

    var invokablesTable    = {},
        superclass         = null,
        name               = null,
        instanceInvokables = new Array(),
        instanceFields     = new Array(),
        _this              = this;

    this.getSuperClass = function () {
        return superclass;
    };

    this.setSuperClass = function (value) {
        superclass = value;
    };

    this.hasSuperClass = function () {
        return superclass != null;
    };

    this.getName = function () {
        return name;
    };

    this.setName = function (value) {
        name = value;
    };

    this.getInstanceFields = function () {
        return instanceFields;
    };

    this.setInstanceFields = function (fieldsArray) {
        instanceFields = fieldsArray;
    };

    this.getInstanceInvokables = function () {
        return instanceInvokables;
    };

    this.setInstanceInvokables = function (arr) {
        instanceInvokables = arr;

        // Make sure this class is the holder of all invokables in the array
        var num = getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            instanceInvokables[i].setHolder(this);
        }
    };

    this.getNumberOfInstanceInvokables = function () {
        // Return the number of instance invokables in this class
        return instanceInvokables.length;
    };

    this.getInstanceInvokable = function (index) {
        return instanceInvokables[index];
    };

    this.setInstanceInvokable = function (index, value) {
        // Set this class as the holder of the given invokable
        value.setHolder(this);

        instanceInvokables[index] = value;

        if (invokablesTable.containsKey(value.getSignature())) {
            invokablesTable.put(value.getSignature(), value);
        }
    };

    this.lookupInvokable = function (selector) {
        // Lookup invokable and return if found
        var invokable = invokablesTable.get(selector);
        if (invokable != null) { return invokable; }

        // Lookup invokable with given signature in array of instance invokables
        var num = getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            // Get the next invokable in the instance invokable array
            invokable = getInstanceInvokable(i);

            // Return the invokable if the signature matches
            if (invokable.getSignature() == selector) {
                invokablesTable.put(selector, invokable);
                return invokable;
            }
        }

        // Traverse the super class chain by calling lookup on the super class
        if (hasSuperClass()) {
            invokable = getSuperClass().lookupInvokable(selector);
            if (invokable != null) {
                invokablesTable.put(selector, invokable);
                return invokable;
            }
        }

        // Invokable not found
        return null;
    };

    this.lookupFieldIndex = function (fieldName) {
        // Lookup field with given name in array of instance fields
        var num = getNumberOfInstanceFields();
        for (var i = num - 1; i >= 0; i--) {
            // Return the current index if the name matches
            if (fieldName == getInstanceFieldName(i)) { return i; }
        }
        return -1;  // Field not found
    };

    function addInstanceInvokable(value) {
        // Add the given invokable to the array of instance invokables
        var num = getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            // Get the next invokable in the instance invokable array
            var invokable = getInstanceInvokable(i);

            // Replace the invokable with the given one if the signature matches
            if (invokable.getSignature() == value.getSignature()) {
                setInstanceInvokable(i, value);
                return false;
            }
        }

        // Append the given method to the array of instance methods
        var numInvokables = instanceInvokables.length;
        instanceInvokables = Arrays.copyOf(instanceInvokables, numInvokables + 1);
        instanceInvokables[numInvokables] = value;
        return true;
    }

    this.addInstancePrimitive = function (value) {
        if (addInstanceInvokable(value)) {
            universe.print("Warning: Primitive " + value.getSignature().getString());
            universe.println(" is not in class definition for class "
                + getName().getString());
        }
    };

    this.getInstanceFieldName = function (index) {
        return instanceFields[index];
    };

    this.getNumberOfInstanceFields = function () {
        return instanceFields.length;
    };

    function includesPrimitives(clazz) {
        // Lookup invokable with given signature in array of instance invokables
        for (var i = 0; i < clazz.getNumberOfInstanceInvokables(); i++) {
            // Get the next invokable in the instance invokable array
            if (clazz.getInstanceInvokable(i).isPrimitive()) {
                return true;
            }
        }
        return false;
    }

    this.hasPrimitives = function () {
        return includesPrimitives(this) || includesPrimitives(_this.getClass());
    };

    this.loadPrimitives = function (displayWarning) {
        // Compute the class name of the Java(TM) class containing the
        // primitives
        if (som.primitives[name.getString()] !== undefined) {
            som.primitives[name.getString()].installPrimitivesIn(this);
        } else {
            if (displayWarning) {
                universe.println("Primitives class " + name.getString() + " not found");
            }
        }
    };

    this.toString = function () {
        return "Class(" + name.getString() + ")";
    };
}

SClass.prototype = Object.create(SObject.prototype);
<commit_msg>Fix cross-language-porting bugs<commit_after>'use strict';

function SClass(_clazz, numberOfFields) {
    SObject.call(this, _clazz, numberOfFields);

    var invokablesTable    = {},
        superclass         = null,
        name               = null,
        instanceInvokables = new Array(),
        instanceFields     = new Array(),
        _this              = this;

    this.getSuperClass = function () {
        return superclass;
    };

    this.setSuperClass = function (value) {
        superclass = value;
    };

    this.hasSuperClass = function () {
        return superclass != null;
    };

    this.getName = function () {
        return name;
    };

    this.setName = function (value) {
        name = value;
    };

    this.getInstanceFields = function () {
        return instanceFields;
    };

    this.setInstanceFields = function (fieldsArray) {
        instanceFields = fieldsArray;
    };

    this.getInstanceInvokables = function () {
        return instanceInvokables;
    };

    this.setInstanceInvokables = function (arr) {
        instanceInvokables = arr;

        // Make sure this class is the holder of all invokables in the array
        var num = getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            instanceInvokables[i].setHolder(this);
        }
    };

    this.getNumberOfInstanceInvokables = function () {
        // Return the number of instance invokables in this class
        return instanceInvokables.length;
    };

    this.getInstanceInvokable = function (index) {
        return instanceInvokables[index];
    };

    this.setInstanceInvokable = function (index, value) {
        // Set this class as the holder of the given invokable
        value.setHolder(this);

        instanceInvokables[index] = value;

        if (invokablesTable[value.getSignature()] == undefined) {
            invokablesTable[value.getSignature()] = value;
        }
    };

    this.lookupInvokable = function (selector) {
        // Lookup invokable and return if found
        var invokable = invokablesTable[selector];
        if (invokable != null) { return invokable; }

        // Lookup invokable with given signature in array of instance invokables
        var num = _this.getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            // Get the next invokable in the instance invokable array
            invokable = _this.getInstanceInvokable(i);

            // Return the invokable if the signature matches
            if (invokable.getSignature() == selector) {
                invokablesTable.put(selector, invokable);
                return invokable;
            }
        }

        // Traverse the super class chain by calling lookup on the super class
        if (_this.hasSuperClass()) {
            invokable = _this.getSuperClass().lookupInvokable(selector);
            if (invokable != null) {
                invokablesTable[selector] = invokable;
                return invokable;
            }
        }

        // Invokable not found
        return null;
    };

    this.lookupFieldIndex = function (fieldName) {
        // Lookup field with given name in array of instance fields
        var num = _this.getNumberOfInstanceFields();
        for (var i = num - 1; i >= 0; i--) {
            // Return the current index if the name matches
            if (fieldName == _this.getInstanceFieldName(i)) { return i; }
        }
        return -1;  // Field not found
    };

    function addInstanceInvokable(value) {
        // Add the given invokable to the array of instance invokables
        var num = _this.getNumberOfInstanceInvokables();
        for (var i = 0; i < num; i++) {
            // Get the next invokable in the instance invokable array
            var invokable = _this.getInstanceInvokable(i);

            // Replace the invokable with the given one if the signature matches
            if (invokable.getSignature() == value.getSignature()) {
                _this.setInstanceInvokable(i, value);
                return false;
            }
        }

        instanceInvokables.push(value);
        return true;
    }

    this.addInstancePrimitive = function (value) {
        if (addInstanceInvokable(value)) {
            universe.print("Warning: Primitive " + value.getSignature().getString());
            universe.println(" is not in class definition for class "
                + _this.getName().getString());
        }
    };

    this.getInstanceFieldName = function (index) {
        return instanceFields[index];
    };

    this.getNumberOfInstanceFields = function () {
        return instanceFields.length;
    };

    function includesPrimitives(clazz) {
        // Lookup invokable with given signature in array of instance invokables
        for (var i = 0; i < clazz.getNumberOfInstanceInvokables(); i++) {
            // Get the next invokable in the instance invokable array
            if (clazz.getInstanceInvokable(i).isPrimitive()) {
                return true;
            }
        }
        return false;
    }

    this.hasPrimitives = function () {
        return includesPrimitives(this) || includesPrimitives(_this.getClass());
    };

    this.loadPrimitives = function (displayWarning) {
        // Compute the class name of the Java(TM) class containing the
        // primitives
        if (som.primitives[name.getString()] !== undefined) {
            som.primitives[name.getString()].installPrimitivesIn(this);
        } else {
            if (displayWarning) {
                universe.println("Primitives class " + name.getString() + " not found");
            }
        }
    };

    this.toString = function () {
        return "Class(" + name.getString() + ")";
    };
}
SClass.prototype = Object.create(SObject.prototype);
<|endoftext|>


<commit_before>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

/**
 * @class easyXDM.stack.FlashTransport
 * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} config The transports configuration.
 * @cfg {String} remote The remote domain to communicate with.
 * @cfg {String} secret the pre-shared secret used to secure the communication.
 * @cfg {String} swf The path to the swf file
 */
easyXDM.stack.FlashTransport = function(config){
    // #ifdef debug
    var trace = debug.getTracer("easyXDM.stack.FlashTransport");
    trace("constructor");
    if (!config.swf) {
        throw new Error("Path to easyxdm.swf is missing");
    }
    // #endif
    var pub, // the public interface
 frame, send, targetOrigin, swf, swfContainer, ns = (namespace ? namespace + "." : "");

    function onMessage(message){
        setTimeout(function(){
            // #ifdef debug
            trace("received message");
            // #endif
            pub.up.incoming(message, targetOrigin);
        }, 0);
    }

    /**
     * This method adds the SWF to the DOM and prepares the initialization of the channel
     */
    function addSwf(callback){
        var url = config.swf;
        var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
        var init = ns + "easyXDM.Fn.get(\"flash_" + id + "_init\")";

        // prepare the init function that will fire once the swf is ready
        easyXDM.Fn.set("flash_" + id + "_init", function(){
            easyXDM.stack.FlashTransport.__swf = swf = swfContainer.firstChild;
            callback();
        });

        // create the container that will hold the swf
        swfContainer = document.createElement('div');
        apply(swfContainer.style, {
            height: "1px",
            width: "1px",
            postition: "abosolute",
            left: 0,
            top: 0
        });
        document.body.appendChild(swfContainer);

        // create the object/embed
        swfContainer.innerHTML = "<object height='1' width='1' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
        "<param name='allowScriptAccess' value='always'></param>" +
        "<param name='wmode' value='transparent'>" +
        "<param name='movie' value='" +
        url +
        "'></param>" +
        "<param name='flashvars' value='init=" +
        init +
        "'></param>" +
        "<embed type='application/x-shockwave-flash' allowScriptAccess='always' wmode='transparent' src='" +
        url +
        "' height='1' width='1'></embed>" +
        "</object>";
    }

    return (pub = {
        outgoing: function(message, domain, fn){
            swf.postMessage(config.channel, message);
            if (fn) {
                fn();
            }
        },
        destroy: function(){
            // #ifdef debug
            trace("destroy");
            // #endif
            swf.destroyChannel(config.channel);
            swf = null;
            if (frame) {
                frame.parentNode.removeChild(frame);
                frame = null;
            }
        },
        onDOMReady: function(){
            // #ifdef debug
            trace("init");
            // #endif

            targetOrigin = getLocation(config.remote);
            swf = easyXDM.stack.FlashTransport.__swf;

            /**
             * Prepare the code that will be run after the swf has been intialized
             */
            var fn = function(){
                // set up the omMessage handler
                if (config.isHost) {
                    easyXDM.Fn.set("flash_" + config.channel + "_onMessage", function(message){
                        if (message == config.channel + "-ready") {
                            easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
                            setTimeout(function(){
                                // #ifdef debug
                                trace("firing onReady");
                                // #endif
                                pub.up.callback(true);
                            }, 0);
                        }
                    });
                }
                else {
                    easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
                }

                // create the channel
                swf.createChannel(config.channel, config.remote, config.isHost, ns + "easyXDM.Fn.get(\"flash_" + config.channel + "_onMessage\")", config.secret);

                if (config.isHost) {
                    // set up the iframe
                    apply(config.props, {
                        src: appendQueryParameters(config.remote, {
                            xdm_e: getLocation(location.href),
                            xdm_c: config.channel,
                            xdm_s: config.secret,
                            xdm_p: 6 // 6 = FlashTransport
                        }),
                        name: IFRAME_PREFIX + config.channel + "_provider"
                    });
                    frame = createFrame(config);
                }
                else {
                    // signal to the remote end that we are ready, and fire the callback
                    swf.postMessage(config.channel, config.channel + "-ready");
                    setTimeout(function(){
                        // #ifdef debug
                        trace("firing onReady");
                        // #endif
                        pub.up.callback(true);
                    }, 0);
                }
            };

            if (swf) {
                // if the swf is in place and we are the consumer
                fn();
            }
            else {
                // if the swf does not yet exist
                addSwf(fn);
            }
        },
        init: function(){
            whenReady(pub.onDOMReady, pub);
        }
    });
};
<commit_msg>Improved the destroy method for the FlashTransport<commit_after>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

/**
 * @class easyXDM.stack.FlashTransport
 * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} config The transports configuration.
 * @cfg {String} remote The remote domain to communicate with.
 * @cfg {String} secret the pre-shared secret used to secure the communication.
 * @cfg {String} swf The path to the swf file
 */
easyXDM.stack.FlashTransport = function(config){
    // #ifdef debug
    var trace = debug.getTracer("easyXDM.stack.FlashTransport");
    trace("constructor");
    if (!config.swf) {
        throw new Error("Path to easyxdm.swf is missing");
    }
    // #endif
    var pub, // the public interface
 frame, send, targetOrigin, swf, swfContainer, ns = (namespace ? namespace + "." : "");

    function onMessage(message){
        setTimeout(function(){
            // #ifdef debug
            trace("received message");
            // #endif
            pub.up.incoming(message, targetOrigin);
        }, 0);
    }

    /**
     * This method adds the SWF to the DOM and prepares the initialization of the channel
     */
    function addSwf(callback){
        var url = config.swf;
        var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
        var init = ns + "easyXDM.Fn.get(\"flash_" + id + "_init\")";

        // prepare the init function that will fire once the swf is ready
        easyXDM.Fn.set("flash_" + id + "_init", function(){
            easyXDM.stack.FlashTransport.__swf = swf = swfContainer.firstChild;
            callback();
        });

        // create the container that will hold the swf
        swfContainer = document.createElement('div');
        apply(swfContainer.style, {
            height: "1px",
            width: "1px",
            postition: "abosolute",
            left: 0,
            top: 0
        });
        document.body.appendChild(swfContainer);

        // create the object/embed
        swfContainer.innerHTML = "<object height='1' width='1' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
        "<param name='allowScriptAccess' value='always'></param>" +
        "<param name='wmode' value='transparent'>" +
        "<param name='movie' value='" +
        url +
        "'></param>" +
        "<param name='flashvars' value='init=" +
        init +
        "'></param>" +
        "<embed type='application/x-shockwave-flash' allowScriptAccess='always' wmode='transparent' src='" +
        url +
        "' height='1' width='1'></embed>" +
        "</object>";
    }

    return (pub = {
        outgoing: function(message, domain, fn){
            swf.postMessage(config.channel, message);
            if (fn) {
                fn();
            }
        },
        destroy: function(){
            // #ifdef debug
            trace("destroy");
            // #endif
            try {
                swf.destroyChannel(config.channel);
            }
            catch (e) {
            }
            swf = null;
            if (frame) {
                frame.parentNode.removeChild(frame);
                frame = null;
            }
        },
        onDOMReady: function(){
            // #ifdef debug
            trace("init");
            // #endif

            targetOrigin = getLocation(config.remote);
            swf = easyXDM.stack.FlashTransport.__swf;

            /**
             * Prepare the code that will be run after the swf has been intialized
             */
            var fn = function(){
                // set up the omMessage handler
                if (config.isHost) {
                    easyXDM.Fn.set("flash_" + config.channel + "_onMessage", function(message){
                        if (message == config.channel + "-ready") {
                            easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
                            setTimeout(function(){
                                // #ifdef debug
                                trace("firing onReady");
                                // #endif
                                pub.up.callback(true);
                            }, 0);
                        }
                    });
                }
                else {
                    easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
                }

                // create the channel
                swf.createChannel(config.channel, config.remote, config.isHost, ns + "easyXDM.Fn.get(\"flash_" + config.channel + "_onMessage\")", config.secret);

                if (config.isHost) {
                    // set up the iframe
                    apply(config.props, {
                        src: appendQueryParameters(config.remote, {
                            xdm_e: getLocation(location.href),
                            xdm_c: config.channel,
                            xdm_s: config.secret,
                            xdm_p: 6 // 6 = FlashTransport
                        }),
                        name: IFRAME_PREFIX + config.channel + "_provider"
                    });
                    frame = createFrame(config);
                }
                else {
                    // signal to the remote end that we are ready, and fire the callback
                    swf.postMessage(config.channel, config.channel + "-ready");
                    setTimeout(function(){
                        // #ifdef debug
                        trace("firing onReady");
                        // #endif
                        pub.up.callback(true);
                    }, 0);
                }
            };

            if (swf) {
                // if the swf is in place and we are the consumer
                fn();
            }
            else {
                // if the swf does not yet exist
                addSwf(fn);
            }
        },
        init: function(){
            whenReady(pub.onDOMReady, pub);
        }
    });
};
<|endoftext|>


<commit_before>/* More on programming models: https://webtask.io/docs/models */

module.exports =
    function (context, req, res) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(require('ejs').render(view.stringify(), {
            name: context.data.name || 'Anonymous'
        }));
    }

function view() {/*

      <title>Welcome to Webtasks</title>

Hello, <%= name %>

*/}<commit_msg>Fix broken link<commit_after>/* More on programming models: https://webtask.io/docs/model */

module.exports =
    function (context, req, res) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(require('ejs').render(view.stringify(), {
            name: context.data.name || 'Anonymous'
        }));
    }

function view() {/*

      <title>Welcome to Webtasks</title>

Hello, <%= name %>

*/}
<|endoftext|>


<commit_before>var shakaGetMessage = function(code) {
	for (var k in shaka.util.Error.Code) {
		if (shaka.util.Error.Code[k] == code)
			return k
	}
}

var shakaSignalError = function(ui, err) {
	if (!err.message)
		err.message = shakaGetMessage(err.code)
	ui.error(err)
}

var Player = function(ui) {
	var player = ui._context.createElement('video')

	this._player = player

	if (!shaka.Player.isBrowserSupported()) {
		throw new Error("browser is not supported, backend should not have been registered")
	}

	var shakaPlayer = new shaka.Player(player.dom);
	this.shakaPlayer = shakaPlayer;

	this.element = player
	this.ui = ui
	this.setEventListeners()
	this.setAutoPlay(ui.autoPlay)

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)
}

Player.prototype = Object.create(_globals.video.html5.backend.Player.prototype)

Player.prototype.setupDrm = function(type, options, callback, error) {
	var laServer = {}
	if (type === "widevine")
		laServer["com.widevine.alpha"] = options.laServer
	else if (type === "playready")
		laServer["com.microsoft.playready"] = options.laServer
	else
		error ? error(new Error("Unknown or not supported DRM type " + type)) : log("Unknown or not supported DRM type " + type)

	var config = { drm: { servers: laServer }, manifest: { dash: { defaultPresentationDelay: 30 } } }
	log("SetupDRM", config)
	this.shakaPlayer.configure(config);
	if (callback)
		callback()
}

Player.prototype.stop = function() {
	log("stop player")
	var self = this
	if (this._loaded) {
		this.shakaPlayer.unload()
			.then(function(e) { log("Unloaded"); self.shakaPlayer.destroy(); self.shakaPlayer = new shaka.Player(self._player.dom); })
			.catch(function(e) { log("Unload failed", e); self.shakaPlayer.destroy(); self.shakaPlayer = new shaka.Player(self._player.dom); })
	} else {
		this.pause()
	}
}

Player.prototype.setSource = function(url) {
	var ui = this.ui
	if (url) {
		var urlLower = url.toLowerCase()
		var querryIndex = url.indexOf("?")
		if (querryIndex >= 0)
			urlLower = urlLower.substring(0, querryIndex)
		var extIndex = urlLower.lastIndexOf(".")
		var extension = urlLower.substring(extIndex, urlLower.length)
		var player = this._player
		if (extension === ".mpd") {
			this._loaded = true
			this.shakaPlayer.load(url)
				.then(function() { console.log('The video has now been loaded!'); })
				.catch(ui._context.wrapNativeCallback(function(err) { log("Failed to load manifest", err); shakaSignalError(ui, err) }));
		} else {
			this._loaded = false
			this._player.dom.src = url
		}
	}
}

Player.prototype.getVideoTracks = function() {
	var video = []
	var tracks = this.shakaPlayer.getVariantTracks()

	for (var i = 0; i < tracks.length; ++i) {
		var track = tracks[i]
		video.push({
			id: track.id,
			width: track.width,
			framerate: track.frameRate,
			bandwidth: track.videoBandwidth,
			height: track.height
		})
	}
	return video
}

Player.prototype.getAudioTracks = function() {
	var tracks = this.shakaPlayer.getVariantTracks()
	var audioTracks = {}
	for (var i = 0; i < tracks.length; ++i) {
		var track = tracks[i]
		if (audioTracks[track.audioId])
			continue

		audioTracks[track.audioId] = {
			id: track.audioId,
			language: track.language,
			codec: track.audioCodec
		}
	}

	var audio = []
	for (var i in audioTracks) {
		audio.push(audioTracks[i])
	}
	log("Available audio tracks", audio)

	return audio
}

Player.prototype.setAudioTrack = function(trackId) {
	var tracks = this.shakaPlayer.getVariantTracks()

	var found = tracks.filter(function(element) {
		return element.audioId === trackId
	})

	log("Try to set audio track", found)
	if (found && found.length) {
		this.shakaPlayer.configure({
			abr: {
				enabled: false,
				switchInterval: 0
			}
		});
		this.shakaPlayer.selectVariantTrack(found[0])
	}
}

Player.prototype.setVideoTrack = function(trackId) {
	var tracks = this.shakaPlayer.getVariantTracks()

	var found = tracks.filter(function(element) {
		return element.id === trackId
	})

	log("Try to set video track", found)
	if (found && found.length) {
		this.shakaPlayer.configure({
			abr: {
				enabled: false,
				switchInterval: 0
			}
		});
		this.shakaPlayer.selectVariantTrack(found[0])
	}
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 150
}

exports.Player = Player
<commit_msg>Call 'play' when mpd was loaded if 'autoPlay' is true<commit_after>var shakaGetMessage = function(code) {
	for (var k in shaka.util.Error.Code) {
		if (shaka.util.Error.Code[k] == code)
			return k
	}
}

var shakaSignalError = function(ui, err) {
	if (!err.message)
		err.message = shakaGetMessage(err.code)
	ui.error(err)
}

var Player = function(ui) {
	var player = ui._context.createElement('video')

	this._player = player

	if (!shaka.Player.isBrowserSupported()) {
		throw new Error("browser is not supported, backend should not have been registered")
	}

	var shakaPlayer = new shaka.Player(player.dom);
	this.shakaPlayer = shakaPlayer;

	this.element = player
	this.ui = ui
	this.setEventListeners()
	this.setAutoPlay(ui.autoPlay)

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)
}

Player.prototype = Object.create(_globals.video.html5.backend.Player.prototype)

Player.prototype.setupDrm = function(type, options, callback, error) {
	var laServer = {}
	if (type === "widevine")
		laServer["com.widevine.alpha"] = options.laServer
	else if (type === "playready")
		laServer["com.microsoft.playready"] = options.laServer
	else
		error ? error(new Error("Unknown or not supported DRM type " + type)) : log("Unknown or not supported DRM type " + type)

	var config = { drm: { servers: laServer }, manifest: { dash: { defaultPresentationDelay: 30 } } }
	log("SetupDRM", config)
	this.shakaPlayer.configure(config);
	if (callback)
		callback()
}

Player.prototype.stop = function() {
	log("stop player")
	var self = this
	if (this._loaded) {
		this.shakaPlayer.unload()
			.then(function(e) { log("Unloaded"); self.shakaPlayer.destroy(); self.shakaPlayer = new shaka.Player(self._player.dom); })
			.catch(function(e) { log("Unload failed", e); self.shakaPlayer.destroy(); self.shakaPlayer = new shaka.Player(self._player.dom); })
	} else {
		this.pause()
	}
}

Player.prototype.setSource = function(url) {
	var ui = this.ui
	if (url) {
		var urlLower = url.toLowerCase()
		var querryIndex = url.indexOf("?")
		if (querryIndex >= 0)
			urlLower = urlLower.substring(0, querryIndex)
		var extIndex = urlLower.lastIndexOf(".")
		var extension = urlLower.substring(extIndex, urlLower.length)
		var player = this._player
		if (extension === ".mpd") {
			this._loaded = true
			var self = this
			this.shakaPlayer.load(url)
				.then(function() {
					console.log('The video has now been loaded!');
					if (ui.autoPlay)
						self.play()
				})
				.catch(ui._context.wrapNativeCallback(function(err) { log("Failed to load manifest", err); shakaSignalError(ui, err) }));
		} else {
			this._loaded = false
			this._player.dom.src = url
		}
	}
}

Player.prototype.getVideoTracks = function() {
	var video = []
	var tracks = this.shakaPlayer.getVariantTracks()

	for (var i = 0; i < tracks.length; ++i) {
		var track = tracks[i]
		video.push({
			id: track.id,
			width: track.width,
			framerate: track.frameRate,
			bandwidth: track.videoBandwidth,
			height: track.height
		})
	}
	return video
}

Player.prototype.getAudioTracks = function() {
	var tracks = this.shakaPlayer.getVariantTracks()
	var audioTracks = {}
	for (var i = 0; i < tracks.length; ++i) {
		var track = tracks[i]
		if (audioTracks[track.audioId])
			continue

		audioTracks[track.audioId] = {
			id: track.audioId,
			language: track.language,
			codec: track.audioCodec
		}
	}

	var audio = []
	for (var i in audioTracks) {
		audio.push(audioTracks[i])
	}
	log("Available audio tracks", audio)

	return audio
}

Player.prototype.setAudioTrack = function(trackId) {
	var tracks = this.shakaPlayer.getVariantTracks()

	var found = tracks.filter(function(element) {
		return element.audioId === trackId
	})

	log("Try to set audio track", found)
	if (found && found.length) {
		this.shakaPlayer.configure({
			abr: {
				enabled: false,
				switchInterval: 0
			}
		});
		this.shakaPlayer.selectVariantTrack(found[0])
	}
}

Player.prototype.setVideoTrack = function(trackId) {
	var tracks = this.shakaPlayer.getVariantTracks()

	var found = tracks.filter(function(element) {
		return element.id === trackId
	})

	log("Try to set video track", found)
	if (found && found.length) {
		this.shakaPlayer.configure({
			abr: {
				enabled: false,
				switchInterval: 0
			}
		});
		this.shakaPlayer.selectVariantTrack(found[0])
	}
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 150
}

exports.Player = Player
<|endoftext|>


<commit_before>blippex.define('blippex.p2p.manager', function(oArgs){
	var _id = oArgs.id;
	var _peers = oArgs.peers;
	var _callback = oArgs.callback;

	var _this = this;

	var peer = null;

	/*
	 *	Create new peer
	 *	Remote peers should be notified automatically, also it works correctly even in case browser is closing, etc
	 */
	this.init = function(){
		blippex.browser.debug.log('p2p.manager: creating new peer ' + _id);

		peer = new Peer(_id, blippex.config.p2p);

		/* create peer */
		peer.on('open', function(__id){
			/* try to connect to known peers, keep connections internally */
			_peers.forEach(function(peer_id){
				//
				var conn = peer.connect(peer_id, {
					'reliable': true,
					'serialization': 'json'
				});

				conn.on('data', function(data){
					_this.forward(data);
				});

				conn.on('close', function(data){
					blippex.browser.debug.log('p2p.manager: remote peer closed connection');
					//TODO check how many active connections we have, recreate the manager?
				});

			});
		});

		peer.on('connection' ,function(conn, meta){
			blippex.browser.debug.log('p2p.manager: new peer connected');

			conn.on('data', function(data){
				blippex.browser.debug.log('p2p.manager: got data');
				_this.forward(data);
			});

			//TODO conn.on

		});

		peer.on('error' ,function(err){
			//TODO do something :)
		});
	}

	this.forward = function(data){
		var conn = _this.getConnection();
		if (conn && shouldForward()){
			blippex.browser.debug.log('p2p: forwarding data to peer');
		} else {
			blippex.browser.debug.log('p2p: uploading the data to api server');
			blippex.api.upload.upload(data);
		}
	}

	/*
	 *	Get random connection
	 *	Forward possible to active connection only
	 */
	this.getConnection = function(){
		var cons = [];
		for (var _peer_id in peer.connections){
			if (_peer_id !== peer.id) {//skip itself
				cons.push(_peer_id);
			}
		}
		return cons.length ? peer.connections[cons[Math.floor(Math.random() * cons.length)]].peerjs : null;
	},

	/*
	 *	Get current peer
	 */
	this.getPeer = function(){
		return peer;
	}

	/*
	 *	Destroy current peer, close all active connections
	 *	Remote peers should be notified automatically, also it works correctly even in case browser is closing, etc
	 */
	this.destroy = function(){
		blippex.browser.debug.log('p2p.manager: destroying active peer ' + peer.id);
		for (var peerId in peer.connections){
			peer.connections[peerId].peerjs.close();
		}
		//peer.disconnect();
		peer.destroy();
	}

	/*
	 *	Get forward flag
	 *	Forward the data if flag is true
	 *	@type Boolean
	 */
	var shouldForward = function(){
		return Math.round(Math.random()) == 1;
	}

	/*
	 *	Make it work()
	 */
	this.init();
});<commit_msg>Small refUcktoring<commit_after>blippex.define('blippex.p2p.manager', function(oArgs){
	var _id = oArgs.id;
	var _peers = oArgs.peers;
	var _callback = oArgs.callback;

	var _this = this;

	var peer = null;

	/*
	 *	Create new peer
	 *	Remote peers should be notified automatically, also it works correctly even in case browser is closing, etc
	 *	@author blippex
	 *	@private
	 */
	var init = function(){
		blippex.browser.debug.log('p2p.manager: creating new peer ' + _id);

		peer = new Peer(_id, blippex.config.p2p);

		/* create peer */
		peer.on('open', function(__id){
			/* try to connect to known peers, keep connections internally */
			_peers.forEach(function(peer_id){
				//
				var conn = peer.connect(peer_id, {
					'reliable': true,
					'serialization': 'json'
				});

				conn.on('data', function(data){
					_this.forward(data);
				});

				conn.on('close', function(data){
					blippex.browser.debug.log('p2p.manager: remote peer closed connection');
					//TODO check how many active connections we have, recreate the manager?
				});

			});
		});

		peer.on('connection' ,function(conn, meta){
			blippex.browser.debug.log('p2p.manager: new peer connected');

			conn.on('data', function(data){
				blippex.browser.debug.log('p2p.manager: got data');
				_this.forward(data);
			});

			//TODO conn.on

		});

		peer.on('error' ,function(err){
			//TODO do something :)
		});
	}

	/*
	 *	Forward the data
	 *	Forward data or upload
	 *	@public
	 *	@author blippex
	 */
	this.forward = function(data){
		var conn = _this.getConnection();
		if (conn && shouldForward()){
			blippex.browser.debug.log('p2p: forwarding data to peer');
		} else {
			blippex.browser.debug.log('p2p: uploading the data to api server');
			blippex.api.upload.upload(data);
		}
	}

	/*
	 *	Get random connection
	 *	Forward possible to active connection only
	 *	@type Peer
	 *	@returns {Peer} returns remote connection object, some of known peers
	 *	@author blippex
	 *	@public
	 */
	this.getConnection = function(){
		var cons = [];
		for (var _peer_id in peer.connections){
			if (_peer_id !== peer.id) {//skip itself
				cons.push(_peer_id);
			}
		}
		return cons.length ? peer.connections[cons[Math.floor(Math.random() * cons.length)]].peerjs : null;
	},

	/*
	 *	Get current peer
	 *	@type Peer
	 *	@returns {Peer} return active peer
	 *	@author blippex
	 *	@public
	 */
	this.getPeer = function(){
		return peer;
	}

	/*
	 *	Destroy current peer, close all active connections
	 *	Remote peers should be notified automatically, also it works correctly even in case browser is closing, etc
	 *	@author blippex
	 *	@public
	 */
	this.destroy = function(){
		blippex.browser.debug.log('p2p.manager: destroying active peer ' + peer.id);
		for (var peerId in peer.connections){
			peer.connections[peerId].peerjs.close();
		}
		//peer.disconnect();
		peer.destroy();
	}

	/*
	 *	Get forward flag
	 *	Forward the data if flag is true
	 *	@author blippex
	 *	@type Boolean
	 *	@private
	 *	@returns {Boolean} returns whether data should be forwarded or uploaded instead
	 */
	var shouldForward = function(){
		return Math.round(Math.random()) == 1;
	}

	/*
	 *	Make it work()
	 *	Start the manager, call the costructor
	 *	@public
	 */
	init();
});<|endoftext|>