<commit_before>window.lab = (function(lab){
    /**
     * takes a state object and serialises it
     * @param {Object} state
     * @returns {string} the serialised object
     */
    lab.serialiseState = function(state) {
        return JSON.stringify(state);
    };

    /**
     * returns a deep-copied clone
     * @param {Object} obj
     * @returns {Object} clone
     */
    lab.cloneObj = function(obj){
        var clone = new obj.constructor();
        for(var p in obj){
            clone[p] = typeof obj[p] === "object" ? lab.cloneObj(obj[p]) : obj[p];
        }
        return clone;
    };

    /**
     * finds all collisions for the given entity and builds collision objects
     * @param {Object} lvl
     * @param {Object} state
     * @param {string} entity
     * @param {bool} before
     * @returns {array} collisions an array of collision objects
     */
    lab.findCollisions = function(lvl,state,entity,before){
        var collisions = []; // key: {obj1: xxx, obj2: xxx}
        // TODO - find collisions with given entity
        return collisions;
    };

    /**
     * performs the given collisions and returns updated state & anims objects
     * @param {Object} lvl
     * @param {Object} state
     * @param {Object} anims
     * @param {Object} collision
     * @returns {Object} an object containing updated state & anims
     */
    lab.performCollision = function(lvl,state,anims,collision){ // collision object contains key,obj1,obj2
        // TODO - update state & anims
        return {
            state: state,
            anims: anims
        };
    };

    /**
     * takes a state object and removes all properties not to be included when saved (like in-move data)
     * @param {Object} state
     * @returns {Object} updatedstate
     */
    lab.removeNonSaveStateProperties = function(state){
        // TODO - remove move-related properties from state
        return state;
    };

    /**
     * calculates what type a given entity is at this moment
     * @param {Object} lvl
     * @param {Object} state
     * @param {string} entitykey
     * @returns {string} type
     */
    lab.getEntityType = function(lvl, state, entitykey){
        var type;
        // TODO - calculate type
        return type;
    };

    /**
     * Calculates what dir an entity would (eventually) start to move in when a move is made
     * @param {Object} lvl
     * @param {Object} state
     * @param {int} dir
     * @param {string} entitykey
     * @returns {int} dir
     */
    lab.getEntityStartDir = function(lvl, state, dir, entitykey){
        var ret = 0, type = lab.getEntityType(lvl,state,entitykey);
        if (lvl.types[type].move === "grav"){
            ret = dir;
        }
        // TODO - add support for float and other things
        return ret;
    };

    /**
     * Takes a state and moves in a given direction
     * @param {Object} lvl
     * @param {Object} state
     * @param {int} dir The direction to move in (1-4)
     * @returns {Object} an object containing updated state & anims
     */
    lab.analyseMove = function(lvl, state, dir){
        var anims = {}, movestate = lab.cloneObj(state), sqrs = 0, before = true, movedir;
        // set all startdirs
        for(var e in lvl.entities){
            movedir = lab.getEntityStartDir(lvl,state,dir,e);
            if (movedir){
                movestate.entities[e].dir = movedir;
                movestate.entities[e].movestarted = 0;
                anim[0].slides = anim[0].slides || {};
                anims[0].slides[e] = {x: movestate.entities[e].x, y: movestate.entities[e].y};
            }
        }
        var sthmoving = false;
        do {
            for(e in lvl.entities){
                var entitydir = movestate.entities[e].dir;
                if (entitydir){
                    if (!before){
                        var fac = [[0,-1],[1,0],[0,1],[-1,0]];
                        movestate.entities[e].x += fac[entitydir][0];
                        movestate.entities[e].y += fac[entitydir][1];
                        anims[movestate.entities[e].movestarted].slides[e].x = movestate.entities[e].x;
                        anims[movestate.entities[e].movestarted].slides[e].y = movestate.entities[e].y;
                    }
                    var collisions = lab.findCollisions(lvl,movestate,e,before);
                    for(var c in collisions){
                        var collisionresult = lab.performCollision(lvl,movestate,anims,collisions[c]);
                        movestate = collisionresult.state;
                        anims = collisionresult.anims;
                    }
                    if (movestate.entities[e].dir){ // we're still on the move! :)
                        sthmoving = true;
                    }
                    // TODO: update movestate & anims for new/changed moves
                }
            }
            sqrs += before ? 0 : 1;
            before = !before;
        }
        while(sthmoving);
        return {
            state: lab.removeNonSaveStateProperties(movestate),
            anims: anims
        };
    };

    /**
     * Analyses a level, creating the full state structure with inbetween transitions
     * @param {Object} lvl
     * @returns {Object} analysis
     */
    lab.analyseLevel = function(lvl){
        return lab.analyse(lvl, lab.buildStartState(lvl), {statekeys: {nextstatekey:0},states:{}}, 1).analysis;
    };

    /**
     * Build a starting state object for a given level
     * @param {Object} lvl
     * @returns {Object} state
     */
    lab.buildStartState = function(lvl){
        var state = {};
        // TODO - build start state for lvl
        return state;
    };

    /**
     * updates an analysis for the given state. will also recursively analyse new states reached.
     * @param {Object} lvl
     * @param {Object} state
     * @param {Object} analysis
     * @param {Number} step
     * @returns {Object} object containing updated analysis and key for the analysed state
     */
    lab.analyse = function(lvl, state, analysis, step){
        var serialisedstate = serialiseState(state), key = analysis.statekeys.nextkey++;
        analysis.states[key] = {
            state: state,
            moves: {},
            steps: step
        };
        analysis.statekeys[serialisedstate] = key;
        for (var d = 1; d <= 4; d++) {
            var moveresult, targetserialised, targetkey, end;
            moveresult = lab.analyseMove(lvl, state, d);
            end = moveresult.state.end;
            if (!end) { // game did not end, so we reached another state
                targetserialised = lab.serialiseState(moveresult.state);
                targetkey = analysis.statekeys[targetserialised];
                if (!targetkey) { // reached unanalysed state
                    var stateresult = analyse(lvl, moveresult.state, analysis, step + 1);
                    analysis = stateresult.analysis;
                    targetkey = stateresult.key;
                }
                if (analysis.states[targetkey].steps > step) {
                    analysis.states[targetkey].steps = step;
                }
            }
            analysis.states[key].moves[d] = {
                target: end ? end : targetkey,
                anims: moveresult.anims
            };
        }
        return {
            analysis: analysis,
            key: key
        };
    };

})(window.lab || {});

<commit_msg>forgot to reset loop bool flag<commit_after>window.lab = (function(lab){
    /**
     * takes a state object and serialises it
     * @param {Object} state
     * @returns {string} the serialised object
     */
    lab.serialiseState = function(state) {
        return JSON.stringify(state);
    };

    /**
     * returns a deep-copied clone
     * @param {Object} obj
     * @returns {Object} clone
     */
    lab.cloneObj = function(obj){
        var clone = new obj.constructor();
        for(var p in obj){
            clone[p] = typeof obj[p] === "object" ? lab.cloneObj(obj[p]) : obj[p];
        }
        return clone;
    };

    /**
     * finds all collisions for the given entity and builds collision objects
     * @param {Object} lvl
     * @param {Object} state
     * @param {string} entity
     * @param {bool} before
     * @returns {array} collisions an array of collision objects
     */
    lab.findCollisions = function(lvl,state,entity,before){
        var collisions = []; // key: {obj1: xxx, obj2: xxx}
        // TODO - find collisions with given entity
        return collisions;
    };

    /**
     * performs the given collisions and returns updated state & anims objects
     * @param {Object} lvl
     * @param {Object} state
     * @param {Object} anims
     * @param {Object} collision
     * @returns {Object} an object containing updated state & anims
     */
    lab.performCollision = function(lvl,state,anims,collision){ // collision object contains key,obj1,obj2
        // TODO - update state & anims
        return {
            state: state,
            anims: anims
        };
    };

    /**
     * takes a state object and removes all properties not to be included when saved (like in-move data)
     * @param {Object} state
     * @returns {Object} updatedstate
     */
    lab.removeNonSaveStateProperties = function(state){
        // TODO - remove move-related properties from state
        return state;
    };

    /**
     * calculates what type a given entity is at this moment
     * @param {Object} lvl
     * @param {Object} state
     * @param {string} entitykey
     * @returns {string} type
     */
    lab.getEntityType = function(lvl, state, entitykey){
        var type;
        // TODO - calculate type
        return type;
    };

    /**
     * Calculates what dir an entity would (eventually) start to move in when a move is made
     * @param {Object} lvl
     * @param {Object} state
     * @param {int} dir
     * @param {string} entitykey
     * @returns {int} dir
     */
    lab.getEntityStartDir = function(lvl, state, dir, entitykey){
        var ret = 0, type = lab.getEntityType(lvl,state,entitykey);
        if (lvl.types[type].move === "grav"){
            ret = dir;
        }
        // TODO - add support for float and other things
        return ret;
    };

    /**
     * Takes a state and moves in a given direction
     * @param {Object} lvl
     * @param {Object} state
     * @param {int} dir The direction to move in (1-4)
     * @returns {Object} an object containing updated state & anims
     */
    lab.analyseMove = function(lvl, state, dir){
        var anims = {}, movestate = lab.cloneObj(state), sqrs = 0, before = true, movedir, sthmoving;
        // set all startdirs
        for(var e in lvl.entities){
            movedir = lab.getEntityStartDir(lvl,state,dir,e);
            if (movedir){
                movestate.entities[e].dir = movedir;
                movestate.entities[e].movestarted = 0;
                anim[0].slides = anim[0].slides || {};
                anims[0].slides[e] = {x: movestate.entities[e].x, y: movestate.entities[e].y};
            }
        }
        do {
            sthmoving = false;
            for(e in lvl.entities){
                var entitydir = movestate.entities[e].dir;
                if (entitydir){
                    if (!before){
                        var fac = [[0,-1],[1,0],[0,1],[-1,0]];
                        movestate.entities[e].x += fac[entitydir][0];
                        movestate.entities[e].y += fac[entitydir][1];
                        anims[movestate.entities[e].movestarted].slides[e].x = movestate.entities[e].x;
                        anims[movestate.entities[e].movestarted].slides[e].y = movestate.entities[e].y;
                    }
                    var collisions = lab.findCollisions(lvl,movestate,e,before);
                    for(var c in collisions){
                        var collisionresult = lab.performCollision(lvl,movestate,anims,collisions[c]);
                        movestate = collisionresult.state;
                        anims = collisionresult.anims;
                    }
                    if (movestate.entities[e].dir){ // we're still on the move! :)
                        sthmoving = true;
                    }
                    // TODO: update movestate & anims for new/changed moves
                }
            }
            sqrs += before ? 0 : 1;
            before = !before;
        }
        while(sthmoving);
        return {
            state: lab.removeNonSaveStateProperties(movestate),
            anims: anims
        };
    };

    /**
     * Analyses a level, creating the full state structure with inbetween transitions
     * @param {Object} lvl
     * @returns {Object} analysis
     */
    lab.analyseLevel = function(lvl){
        return lab.analyse(lvl, lab.buildStartState(lvl), {statekeys: {nextstatekey:0},states:{}}, 1).analysis;
    };

    /**
     * Build a starting state object for a given level
     * @param {Object} lvl
     * @returns {Object} state
     */
    lab.buildStartState = function(lvl){
        var state = {};
        // TODO - build start state for lvl
        return state;
    };

    /**
     * updates an analysis for the given state. will also recursively analyse new states reached.
     * @param {Object} lvl
     * @param {Object} state
     * @param {Object} analysis
     * @param {Number} step
     * @returns {Object} object containing updated analysis and key for the analysed state
     */
    lab.analyse = function(lvl, state, analysis, step){
        var serialisedstate = serialiseState(state), key = analysis.statekeys.nextkey++;
        analysis.states[key] = {
            state: state,
            moves: {},
            steps: step
        };
        analysis.statekeys[serialisedstate] = key;
        for (var d = 1; d <= 4; d++) {
            var moveresult, targetserialised, targetkey, end;
            moveresult = lab.analyseMove(lvl, state, d);
            end = moveresult.state.end;
            if (!end) { // game did not end, so we reached another state
                targetserialised = lab.serialiseState(moveresult.state);
                targetkey = analysis.statekeys[targetserialised];
                if (!targetkey) { // reached unanalysed state
                    var stateresult = analyse(lvl, moveresult.state, analysis, step + 1);
                    analysis = stateresult.analysis;
                    targetkey = stateresult.key;
                }
                if (analysis.states[targetkey].steps > step) {
                    analysis.states[targetkey].steps = step;
                }
            }
            analysis.states[key].moves[d] = {
                target: end ? end : targetkey,
                anims: moveresult.anims
            };
        }
        return {
            analysis: analysis,
            key: key
        };
    };

})(window.lab || {});

<|endoftext|>


<commit_before>/* показать/скрыть сайдбар */
$('#sidebar_switcher').on('mousedown', function(){
	var switch_btn = $('#sidebar_switcher');
	var sidebar_wrap = $('.sidebar_wrap');
	var content_wrap = $('.content_wrap');
	var main_wrap = $('.main_wrap');
	sidebar_wrap.toggleClass('active');
	content_wrap.toggleClass('active');
	main_wrap.toggleClass('active');
	switch_btn.toggleClass('active');
	if(switch_btn.hasClass('active')){
		switch_btn.text('Свернуть меню');
		sidebar_wrap.removeClass('noactive');
        $.cookie(COOKIE_SIDEBAR, 1, {
            path: '/'
        });
	} else {
		switch_btn.text('Показать меню');
		sidebar_wrap.addClass('noactive');
        $.cookie(COOKIE_SIDEBAR, 0, {
            path: '/'
        });
	}
	setTimeout( function(){ $(window).resize();}, 300);
});

(function selectpickerInit () {
    var locales = [ 'ru' ];

    var init;
    init = function () {
        $('select').each(function () {
            var $select = $(this);

            if ($select.children('option').length > 3) {
                $select.attr('data-live-search', 'true');
            }

            $select.selectpicker({size: 10});
        });
    };

    -1 !== locales.indexOf(LOCALE)
        ? $.getScript('/bundles/darvinadmin/scripts/bootstrap/bootstrap-select-' + LOCALE + '.js').done(init)
        : init();
})();

/* спойлер */
$('.spoiler_links').on('mousedown', function(){
	var spoiler_container = $(this).parents('.spoiler_container');
    var body = spoiler_container.find('.spoiler_body');
    if (body.css("display")=="none")
	{
		body.hide('normal');
		body.toggle('normal');
        if ('undefined' !== typeof body.data('cookie')) {
            $.cookie(body.data('cookie'), 1, {
                path: '/'
            });
        }
	} else {
        body.hide('normal');
        if ('undefined' !== typeof body.data('cookie')) {
            $.cookie(body.data('cookie'), 0, {
                path: '/'
            });
        }
    }
	spoiler_container.toggleClass('noactive');
	return false;
 });

 /* клик на пункте меню главной */
 $('.main_menu .item.parent > .name a, .main_menu .item.parent > .img a').on('click', function(){
	var item = $(this).parents('.parent');
	if(item.hasClass('active')){
		item.removeClass('active');
	} else {
		$('.main_menu .item.parent.active').removeClass('active');
		resize();
		item.addClass('active');
	}
	resize();
	setTimeout( resize(), 500);
	return false;
});

 jQuery(document).ready(function(){
	resize();

	show_menu_function();

	$('.content_wrap').css({'minHeight': $('.left_menu').height() });
 });

 function show_menu_function(){
	/*var count = $('.main_menu .item').length;
	console.log(count);
	for (i = 0; i < count; i++) {
		console.log(i);
		setTimeout( $('.main_menu .item:eq('+i+')').addClass('animate_start'), 700);
	}*/
}

 window.onresize = resize;

 function resize(){
	/* меню на главной */
	$('.main_menu .item').height('auto');
	$('.main_menu .item .description').height('auto');

	var maxHeightItem = 0;
	var maxHeightItemText = 0;
	var maxHeightDownDrop = 0;
	$('.main_menu .item').each(function(){
		if($(this).height() > maxHeightItem){ maxHeightItem = $(this).height();}
	});
	$('.main_menu .item .description').each(function(){
		if($(this).height() > maxHeightItemText){ maxHeightItemText = $(this).height();}
	});
	$('.main_menu .main_dropdown_menu').each(function(){
		if($(this).height() > maxHeightDownDrop){ maxHeightDownDrop = $(this).height();}
	});
	$('.main_menu .item').height(maxHeightItem);
	$('.main_menu .item .description').height(maxHeightItemText);
	if( $('.main_menu .item.parent.active').length > 0 ){
		$('.main_menu .item.parent.active').css({'marginBottom': maxHeightDownDrop + 5});
	} else {
		$('.main_menu .item.parent').css({'marginBottom': '10px'});
		$('.main_menu .item').height('auto');
		$('.main_menu .item .description').height('auto');
	}
	console.log('resize')
}

/* скролбар */
$(function() {
    $('.scroll-pane').each(
        function() {
            $(this).jScrollPane({
                showArrows: $(this).is('.arrow')
            });
            var api = $(this).data('jsp');
            var throttleTimeout;
            $(window).bind(
                'resize',
                function() {
                    if (!throttleTimeout) {
                        throttleTimeout = setTimeout(
                            function() {
                                api.reinitialise();
                                throttleTimeout = null;
                            },
                            50
                        );
                    }
                }
            );
        }
    )
});

/**************************************************************/<commit_msg>Update JS.<commit_after>/* показать/скрыть сайдбар */
$('#sidebar_switcher').on('mousedown', function(){
	var switch_btn = $('#sidebar_switcher');
	var sidebar_wrap = $('.sidebar_wrap');
	var content_wrap = $('.content_wrap');
	var main_wrap = $('.main_wrap');
	sidebar_wrap.toggleClass('active');
	content_wrap.toggleClass('active');
	main_wrap.toggleClass('active');
	switch_btn.toggleClass('active');
	if(switch_btn.hasClass('active')){
		switch_btn.text('Свернуть меню');
		sidebar_wrap.removeClass('noactive');
        $.cookie(COOKIE_SIDEBAR, 1, {
            path: '/'
        });
	} else {
		switch_btn.text('Показать меню');
		sidebar_wrap.addClass('noactive');
        $.cookie(COOKIE_SIDEBAR, 0, {
            path: '/'
        });
	}
	setTimeout( function(){ $(window).resize();}, 300);
});

(function selectpickerInit () {
    var locales = [ 'ru' ];

    var init;
    init = function () {
        $('select').each(function () {
            var $select = $(this);

            if ($select.children('option').length > 3) {
                $select.attr('data-live-search', 'true');
                $select.attr('data-width', 'auto');
            }

            $select.selectpicker({size: 10});
        });
    };

    -1 !== locales.indexOf(LOCALE)
        ? $.getScript('/bundles/darvinadmin/scripts/bootstrap/bootstrap-select-' + LOCALE + '.js').done(init)
        : init();
})();

/* спойлер */
$('.spoiler_links').on('mousedown', function(){
	var spoiler_container = $(this).parents('.spoiler_container');
    var body = spoiler_container.find('.spoiler_body');
    if (body.css("display")=="none")
	{
		body.hide('normal');
		body.toggle('normal');
        if ('undefined' !== typeof body.data('cookie')) {
            $.cookie(body.data('cookie'), 1, {
                path: '/'
            });
        }
	} else {
        body.hide('normal');
        if ('undefined' !== typeof body.data('cookie')) {
            $.cookie(body.data('cookie'), 0, {
                path: '/'
            });
        }
    }
	spoiler_container.toggleClass('noactive');
	return false;
 });

 /* клик на пункте меню главной */
 $('.main_menu .item.parent > .name a, .main_menu .item.parent > .img a').on('click', function(){
	var item = $(this).parents('.parent');
	if(item.hasClass('active')){
		item.removeClass('active');
	} else {
		$('.main_menu .item.parent.active').removeClass('active');
		resize();
		item.addClass('active');
	}
	resize();
	setTimeout( resize(), 500);
	return false;
});

 jQuery(document).ready(function(){
	resize();

	show_menu_function();

	$('.content_wrap').css({'minHeight': $('.left_menu').height() });
 });

 function show_menu_function(){
	/*var count = $('.main_menu .item').length;
	console.log(count);
	for (i = 0; i < count; i++) {
		console.log(i);
		setTimeout( $('.main_menu .item:eq('+i+')').addClass('animate_start'), 700);
	}*/
}

 window.onresize = resize;

 function resize(){
	/* меню на главной */
	$('.main_menu .item').height('auto');
	$('.main_menu .item .description').height('auto');

	var maxHeightItem = 0;
	var maxHeightItemText = 0;
	var maxHeightDownDrop = 0;
	$('.main_menu .item').each(function(){
		if($(this).height() > maxHeightItem){ maxHeightItem = $(this).height();}
	});
	$('.main_menu .item .description').each(function(){
		if($(this).height() > maxHeightItemText){ maxHeightItemText = $(this).height();}
	});
	$('.main_menu .main_dropdown_menu').each(function(){
		if($(this).height() > maxHeightDownDrop){ maxHeightDownDrop = $(this).height();}
	});
	$('.main_menu .item').height(maxHeightItem);
	$('.main_menu .item .description').height(maxHeightItemText);
	if( $('.main_menu .item.parent.active').length > 0 ){
		$('.main_menu .item.parent.active').css({'marginBottom': maxHeightDownDrop + 5});
	} else {
		$('.main_menu .item.parent').css({'marginBottom': '10px'});
		$('.main_menu .item').height('auto');
		$('.main_menu .item .description').height('auto');
	}
	console.log('resize')
}

/* скролбар */
$(function() {
    $('.scroll-pane').each(
        function() {
            $(this).jScrollPane({
                showArrows: $(this).is('.arrow')
            });
            var api = $(this).data('jsp');
            var throttleTimeout;
            $(window).bind(
                'resize',
                function() {
                    if (!throttleTimeout) {
                        throttleTimeout = setTimeout(
                            function() {
                                api.reinitialise();
                                throttleTimeout = null;
                            },
                            50
                        );
                    }
                }
            );
        }
    )
});

/**************************************************************/<|endoftext|>


<commit_before>//
// CineView class
//

var self = this;

// constructor

function CineView(_args) {
	// get the _args
	self._args = _args;
	self.movies = _args.movies;
}

// public methods

CineView.prototype.buildView = function () {

	var movies = self._args.movies;
	// create a var to track the active row
	var currentRow = null;
	var currentRowIndex = null;

	self.win = self._args.win;
	self.tab = movies.ui.tabs.currentTab;

	// creo el mapa
	self.mapview = Titanium.Map.createView({
				mapType: Titanium.Map.STANDARD_TYPE,
				animate:true,
				regionFit:true,
				userLocation:true,
				top: 1
			});

	self.mapIsAdded = false;

	// defino la region del mapa
	latitude = movies.latitude;
	longitude = movies.longitude;
	if (latitude == null || longitude == null ) {
		latitude = -34.569281;
		longitude = -58.468939;
	}
	self.mapview.region = {latitude: latitude, longitude: longitude, latitudeDelta:0.04, longitudeDelta:0.04};

	// creo el menú para android y el tab nav para ios
	createCineMenuUI(self.tab,self.win);

	// Cine model
	var Cine = require('model/Cine').Cine;
	// instance
	var cine = new Cine();
	// get cines
	var row = null;

	//movies.ui.activityIndicator.message = 'Cargando Cines ...';
	// en ios necesita estar attachado a una ventana
	//if (movies.osname != 'android')
	//	self.win.add(movies.ui.activityIndicator);

	var cines = cine.getCines({
		host: movies.WSHOST,
		success: buildRows,
		latitude: latitude,
		longitude: longitude
	});

	return self.mapview;

}; // end function

CineView.prototype.reload = function() {
		var cines = cine.getCines({
			host: self._args.movies.WSHOST,
			success: buildRows
		});
};

////////////// private methods ////////////////

var buildRows = function(cns) {
	// globals
	var movies = self._args.movies;
	var data = [];

	for (var c=0; c<cns.length; c++) {

		var cine = cns[c];
		var cine_id = cine.cine_id;
		var nombre = cine.nombre;
		var imagen = cine.imagen;
		var distancia = cine.distancia;
		var lat = cine.lat;
		var lon = cine.lon;
		var cineAnnotations = [];

		if (cine_id != 0 ) {

			var mapParams = {
					latitude: lat,
					longitude: lon,
					title: nombre,
					subtitle: nombre,
					animate:true,
					cineId: cine_id
				};

			if (self.movies.osname != 'android') {
				mapParams.pincolor = Titanium.Map.ANNOTATION_PURPLE;
				mapParams.rightButton = Titanium.UI.iPhone.SystemButton.DISCLOSURE;
			} else {
				mapParams.image = "../images/pin.png";
			}

			var annotation = Titanium.Map.createAnnotation(mapParams);
			self.mapview.addAnnotation(annotation);
		}

	} // end for

	// el mapa tiene que ser global si no no funciona (??) y solo puede haber 1 por view (al menos en android)
	if (!self.mapIsAdded) {
		self.win.add(self.mapview);
		self.mapIsAdded = true;
	}

	//movies.ui.activityIndicator.hide();
	self.mapview.addEventListener('click', clickAnnotation);

} // end function

var clickAnnotation = function(e) {
	var movies = self.movies;
	// abro la descripcion del cine
	if (!e) return;
	if (e.annotation && (e.clicksource === 'title' || e.clicksource == 'rightButton' || e.clicksource == 'subtitle') ) {

		// creo la windows de la descripcion
		var winDescripcion = Titanium.UI.createWindow({ backgroundColor:'#fff', title:e.rowData.titulo})

		// Pelicula view
		var CineDetailView = require('/ui/CineDetailView');
		winDescripcion = new PeliculaDetailView({titulo: e.rowData.titulo, movieId: e.rowData.cineId, win: winDescripcion, movies: movies});

		if (movies.osname=="android" ) {
			self.tab.add(winDescripcion);
			winDescripcion.open({animated: true});
			self._args.win.addEventListener('android:back',function(e){
				winDescripcion.close();
				return false;
			});

		}

		if (movies.osname=="iphone" || movies.osname == "ipad" ) {
			self.tab.open(winDescripcion,{animated:true});
		}

	}
}

var cinesClickHandlers = function(e) {

	e.button1['tab'] = self.tab;
	e.button2['mapview'] = self.mapview;
	e.button2['loadData'] = self.loadData;

};

var onCreateCineMenu = function(e) {
	var menu = e.menu;
	lstCines = menu.add({title : 'Listado'});
	var path = Titanium.Filesystem.resourcesDirectory;
	lstCines.setIcon('list.png');
	refreshCines = menu.add({title : 'Actualizar', mapview: mapview});
	refreshCines.setIcon('refresh.png');
	//refreshCines['mapview'] = self.mapview;
	refreshCines['loadData'] = self.loadData
	//cinesClickHandlers({button1: lstCines, button2: refreshCines});

	lstCines.addEventListener('click', createCineListadoUI );

	refreshCines.addEventListener('click', function(e) {
		self.mapview.removeAllAnnotations();
		self.mapview.removeEventListener('click', clickAnnotation);
		e.source.loadData();
	});

};

var createCineListadoUI = function () {
	var movies = self._args.movies;
	// Cine list view
	var CineListadoView = require('/ui/CineListadoView');
	var winDescripcion = Ti.UI.createWindow();
	var listadoView = new CineListadoView({titulo: 'Cines', win: winDescripcion, movies: movies});
	winDescripcion.add(listadoView.buildView());

	if (movies.osname=="android" ) {
		self.tab.add(winDescripcion);
		winDescripcion.open({animated: true});
		self._args.win.addEventListener('android:back',function(e){
			winDescripcion.close();
			return false;
		});

	}

	if (movies.osname=="iphone" || movies.osname == "ipad" ) {
		self.tab.open(winDescripcion,{animated:true});
	}
}

function createCineMenuUI(tab, win) {
	if (self.movies.osname == 'iphone' || self.movies.osname=='ipad') {
		// ios nav button
		var listadoButton = Titanium.UI.createButtonBar({
			labels:['Listado'],
			backgroundColor:'#336699'
		});

		self.win.setRightNavButton(listadoButton);

		listadoButton.addEventListener('click', createCineListadoUI );

	}
	if (self.movies.osname=='android') {
		// creo menu contextual
		var activity = self.win.activity;
		activity.onCreateOptionsMenu = onCreateCineMenu;
	}
}

// public interface

module.exports = CineView;
<commit_msg>Código obsoleto<commit_after>//
// CineView class
//

var self = this;

// constructor

function CineView(_args) {
	// get the _args
	self._args = _args;
	self.movies = _args.movies;
}

// public methods

CineView.prototype.buildView = function () {

	var movies = self._args.movies;
	// create a var to track the active row
	var currentRow = null;
	var currentRowIndex = null;

	self.win = self._args.win;
	self.tab = movies.ui.tabs.currentTab;

	// creo el mapa
	self.mapview = Titanium.Map.createView({
				mapType: Titanium.Map.STANDARD_TYPE,
				animate:true,
				regionFit:true,
				userLocation:true,
				top: 1
			});

	self.mapIsAdded = false;

	// defino la region del mapa
	latitude = movies.latitude;
	longitude = movies.longitude;
	if (latitude == null || longitude == null ) {
		latitude = -34.569281;
		longitude = -58.468939;
	}
	self.mapview.region = {latitude: latitude, longitude: longitude, latitudeDelta:0.04, longitudeDelta:0.04};

	// creo el menú para android y el tab nav para ios
	createCineMenuUI(self.tab,self.win);

	// Cine model
	var Cine = require('model/Cine').Cine;
	// instance
	var cine = new Cine();
	// get cines
	var row = null;

	//movies.ui.activityIndicator.message = 'Cargando Cines ...';
	// en ios necesita estar attachado a una ventana
	//if (movies.osname != 'android')
	//	self.win.add(movies.ui.activityIndicator);

	var cines = cine.getCines({
		host: movies.WSHOST,
		success: buildRows,
		latitude: latitude,
		longitude: longitude
	});

	return self.mapview;

}; // end function

CineView.prototype.reload = function() {
		var cines = cine.getCines({
			host: self._args.movies.WSHOST,
			success: buildRows
		});
};

////////////// private methods ////////////////

var buildRows = function(cns) {
	// globals
	var movies = self._args.movies;
	var data = [];

	for (var c=0; c<cns.length; c++) {

		var cine = cns[c];
		var cine_id = cine.cine_id;
		var nombre = cine.nombre;
		var imagen = cine.imagen;
		var distancia = cine.distancia;
		var lat = cine.lat;
		var lon = cine.lon;
		var cineAnnotations = [];

		if (cine_id != 0 ) {

			var mapParams = {
					latitude: lat,
					longitude: lon,
					title: nombre,
					subtitle: nombre,
					animate:true,
					cineId: cine_id
				};

			if (self.movies.osname != 'android') {
				mapParams.pincolor = Titanium.Map.ANNOTATION_PURPLE;
				mapParams.rightButton = Titanium.UI.iPhone.SystemButton.DISCLOSURE;
			} else {
				mapParams.image = "../images/pin.png";
			}

			var annotation = Titanium.Map.createAnnotation(mapParams);
			self.mapview.addAnnotation(annotation);
		}

	} // end for

	// el mapa tiene que ser global si no no funciona (??) y solo puede haber 1 por view (al menos en android)
	if (!self.mapIsAdded) {
		self.win.add(self.mapview);
		self.mapIsAdded = true;
	}

	//movies.ui.activityIndicator.hide();
	self.mapview.addEventListener('click', clickAnnotation);

} // end function

var clickAnnotation = function(e) {
	var movies = self.movies;
	// abro la descripcion del cine
	if (!e) return;
	if (e.annotation && (e.clicksource === 'title' || e.clicksource == 'rightButton' || e.clicksource == 'subtitle') ) {

		// creo la windows de la descripcion
		var winDescripcion = Titanium.UI.createWindow({ backgroundColor:'#fff', title:e.rowData.titulo})

		// Pelicula view
		var CineDetailView = require('/ui/CineDetailView');
		winDescripcion = new PeliculaDetailView({titulo: e.rowData.titulo, movieId: e.rowData.cineId, win: winDescripcion, movies: movies});

		if (movies.osname=="android" ) {
			self.tab.add(winDescripcion);
			winDescripcion.open({animated: true});
			self._args.win.addEventListener('android:back',function(e){
				winDescripcion.close();
				return false;
			});

		}

		if (movies.osname=="iphone" || movies.osname == "ipad" ) {
			self.tab.open(winDescripcion,{animated:true});
		}

	}
}

var onCreateCineMenu = function(e) {
	var menu = e.menu;
	lstCines = menu.add({title : 'Listado'});
	var path = Titanium.Filesystem.resourcesDirectory;
	//lstCines.setIcon('list.png');
	refreshCines = menu.add({title : 'Actualizar', mapview: mapview});
	//refreshCines.setIcon('refresh.png');
	refreshCines['loadData'] = self.loadData

	lstCines.addEventListener('click', createCineListadoUI );

	refreshCines.addEventListener('click', function(e) {
		self.mapview.removeAllAnnotations();
		self.mapview.removeEventListener('click', clickAnnotation);
		e.source.loadData();
	});

};

var createCineListadoUI = function () {
	var movies = self._args.movies;
	// Cine list view
	var CineListadoView = require('/ui/CineListadoView');
	var winDescripcion = Ti.UI.createWindow();
	var listadoView = new CineListadoView({titulo: 'Cines', win: winDescripcion, movies: movies});
	winDescripcion.add(listadoView.buildView());

	if (movies.osname=="android" ) {
		self.tab.add(winDescripcion);
		winDescripcion.open({animated: true});
		self._args.win.addEventListener('android:back',function(e){
			winDescripcion.close();
			return false;
		});

	}

	if (movies.osname=="iphone" || movies.osname == "ipad" ) {
		self.tab.open(winDescripcion,{animated:true});
	}
}

function createCineMenuUI(tab, win) {
	if (self.movies.osname == 'iphone' || self.movies.osname=='ipad') {
		// ios nav button
		var listadoButton = Titanium.UI.createButtonBar({
			labels:['Listado'],
			backgroundColor:'#336699'
		});

		self.win.setRightNavButton(listadoButton);

		listadoButton.addEventListener('click', createCineListadoUI );

	}
	if (self.movies.osname=='android') {
		// creo menu contextual
		var activity = self.win.activity;
		activity.onCreateOptionsMenu = onCreateCineMenu;
	}
}

// public interface

module.exports = CineView;
<|endoftext|>


<commit_before>ace.define("ace/mode/sh_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var reservedKeywords = exports.reservedKeywords = (
        '!|{|}|case|do|done|elif|else|'+
        'esac|fi|for|if|in|then|until|while|'+
        '&|;|export|local|read|typeset|unset|'+
        'elif|select|set|function|declare|readonly'
    );

var languageConstructs = exports.languageConstructs = (
    '[|]|alias|bg|bind|break|builtin|'+
     'cd|command|compgen|complete|continue|'+
     'dirs|disown|echo|enable|eval|exec|'+
     'exit|fc|fg|getopts|hash|help|history|'+
     'jobs|kill|let|logout|popd|printf|pushd|'+
     'pwd|return|set|shift|shopt|source|'+
     'suspend|test|times|trap|type|ulimit|'+
     'umask|unalias|wait'
);

var ShHighlightRules = function() {
    var keywordMapper = this.createKeywordMapper({
        "keyword": reservedKeywords,
        "support.function.builtin": languageConstructs,
        "invalid.deprecated": "debugger"
    }, "identifier");

    var integer = "(?:(?:[1-9]\\d*)|(?:0))";

    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";
    var fileDescriptor = "(?:&" + intPart + ")";

    var variableName = "[a-zA-Z_][a-zA-Z0-9_]*";
    var variable = "(?:" + variableName + "=)";

    var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))";

    var func = "(?:" + variableName + "\\s*\\(\\))";

    this.$rules = {
        "start" : [{
            token : "constant",
            regex : /\\./
        }, {
            token : ["text", "comment"],
            regex : /(^|\s)(#.*)$/
        }, {
            token : "string",
            regex : '"',
            push : [{
                token : "constant.language.escape",
                regex : /\\(?:[$`"\\]|$)/
            }, {
                include : "variables"
            }, {
                token : "keyword.operator",
                regex : /`/ // TODO highlight `
            }, {
                token : "string",
                regex : '"',
                next: "pop"
            }, {
                defaultToken: "string"
            }]
        }, {
            token : "string",
            regex : "\\$'",
            push : [{
                token : "constant.language.escape",
                regex : /\\(?:[abeEfnrtv\\'"]|x[a-fA-F\d]{1,2}|u[a-fA-F\d]{4}([a-fA-F\d]{4})?|c.|\d{1,3})/
            }, {
                token : "string",
                regex : "'",
                next: "pop"
            }, {
                defaultToken: "string"
            }]
        }, {
            regex : "<<<",
            token : "keyword.operator"
        }, {
            stateName: "heredoc",
            regex : "(<<-?)(\\s*)(['\"`]?)([\\w\\-]+)(['\"`]?)",
            onMatch : function(value, currentState, stack) {
                var next = value[2] == '-' ? "indentedHeredoc" : "heredoc";
                var tokens = value.split(this.splitRegex);
                stack.push(next, tokens[4]);
                return [
                    {type:"constant", value: tokens[1]},
                    {type:"text", value: tokens[2]},
                    {type:"string", value: tokens[3]},
                    {type:"support.class", value: tokens[4]},
                    {type:"string", value: tokens[5]}
                ];
            },
            rules: {
                heredoc: [{
                    onMatch:  function(value, currentState, stack) {
                        if (value === stack[1]) {
                            stack.shift();
                            stack.shift();
                            this.next = stack[0] || "start";
                            return "support.class";
                        }
                        this.next = "";
                        return "string";
                    },
                    regex: ".*$",
                    next: "start"
                }],
                indentedHeredoc: [{
                    token: "string",
                    regex: "^\t+"
                }, {
                    onMatch:  function(value, currentState, stack) {
                        if (value === stack[1]) {
                            stack.shift();
                            stack.shift();
                            this.next = stack[0] || "start";
                            return "support.class";
                        }
                        this.next = "";
                        return "string";
                    },
                    regex: ".*$",
                    next: "start"
                }]
            }
        }, {
            regex : "$",
            token : "empty",
            next : function(currentState, stack) {
                if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc")
                    return stack[0];
                return currentState;
            }
        }, {
            token : ["keyword", "text", "text", "text", "variable"],
            regex : /(declare|local|readonly)(\s+)(?:(-[fixar]+)(\s+))?([a-zA-Z_][a-zA-Z0-9_]*\b)/
        }, {
            token : "variable.language",
            regex : builtinVariable
        }, {
            token : "variable",
            regex : variable
        }, {
            include : "variables"
        }, {
            token : "support.function",
            regex : func
        }, {
            token : "support.function",
            regex : fileDescriptor
        }, {
            token : "string",           // ' string
            start : "'", end : "'"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!=|[%&|`]"
        }, {
            token : "punctuation.operator",
            regex : ";"
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]]"
        }, {
            token : "paren.rparen",
            regex : "[\\)\\}]",
            next : "pop"
        }],
        variables: [{
            token : "variable",
            regex : /(\$)(\w+)/
        }, {
            token : ["variable", "paren.lparen"],
            regex : /(\$)(\()/,
            push : "start"
        }, {
            token : ["variable", "paren.lparen", "keyword.operator", "variable", "keyword.operator"],
            regex : /(\$)(\{)([#!]?)(\w+|[*@#?\-$!0_])(:[?+\-=]?|##?|%%?|,,?\/|\^\^?)?/,
            push : "start"
        }, {
            token : "variable",
            regex : /\$[*@#?\-$!0_]/
        }, {
            token : ["variable", "paren.lparen"],
            regex : /(\$)(\{)/,
            push : "start"
        }]
    };

    this.normalizeRules();
};

oop.inherits(ShHighlightRules, TextHighlightRules);

exports.ShHighlightRules = ShHighlightRules;
});

ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
    this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
    this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
    this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (this.singleLineBlockCommentRe.test(line)) {
            if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
                return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.startRegionRe.test(line))
            return "start"; // lineCommentRegionStart

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);

        if (this.startRegionRe.test(line))
            return this.getCommentRegionBlock(session, line, row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            var range = session.getCommentFoldRange(row, i + match[0].length, 1);

            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }

            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);

            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }

        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };
    this.getCommentRegionBlock = function(session, line, row) {
        var startColumn = line.search(/\s*$/);
        var maxRow = session.getLength();
        var startRow = row;

        var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
        var depth = 1;
        while (++row < maxRow) {
            line = session.getLine(row);
            var m = re.exec(line);
            if (!m) continue;
            if (m[1]) depth--;
            else depth++;

            if (!depth) break;
        }

        var endRow = row;
        if (endRow > startRow) {
            return new Range(startRow, startColumn, endRow, line.length);
        }
    };

}).call(FoldMode.prototype);

});

ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");

var SAFE_INSERT_IN_TOKENS =
    ["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
    ["text", "paren.rparen", "punctuation.operator", "comment"];

var context;
var contextCache = {};
var initContext = function(editor) {
    var id = -1;
    if (editor.multiSelect) {
        id = editor.selection.index;
        if (contextCache.rangeCount != editor.multiSelect.rangeCount)
            contextCache = {rangeCount: editor.multiSelect.rangeCount};
    }
    if (contextCache[id])
        return context = contextCache[id];
    context = contextCache[id] = {
        autoInsertedBrackets: 0,
        autoInsertedRow: -1,
        autoInsertedLineEnd: "",
        maybeInsertedBrackets: 0,
        maybeInsertedRow: -1,
        maybeInsertedLineStart: "",
        maybeInsertedLineEnd: ""
    };
};

var getWrapped = function(selection, selected, opening, closing) {
    var rowDiff = selection.end.row - selection.start.row;
    return {
        text: opening + selected + closing,
        selection: [
                0,
                selection.start.column + 1,
                rowDiff,
                selection.end.column + (rowDiff ? 0 : 1)
            ]
    };
};

var CstyleBehaviour = function() {
    this.add("braces", "insertion", function(state, action, editor, session, text) {
        var cursor = editor.getCursorPosition();
        var line = session.doc.getLine(cursor.row);
        if (text == '{') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '{', '}');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
                    CstyleBehaviour.recordAutoInsert(editor, session, "}");
                    return {
                        text: '{}',
                        selection: [1, 1]
                    };
                } else {
                    CstyleBehaviour.recordMaybeInsert(editor, session, "{");
                    return {
                        text: '{',
                        selection: [1, 1]
                    };
                }
            }
        } else if (text == '}') {
            initContext(editor);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == '}') {
                var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        } else if (text == "\n" || text == "\r\n") {
            initContext(editor);
            var closing = "";
            if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
                closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
                CstyleBehaviour.clearMaybeInsertedClosing();
            }
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar === '}') {
                var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
                if (!openBracePos)
                     return null;
                var next_indent = this.$getIndent(session.getLine(openBracePos.row));
            } else if (closing) {
                var next_indent = this.$getIndent(line);
            } else {
                CstyleBehaviour.clearMaybeInsertedClosing();
                return;
            }
            var indent = next_indent + session.getTabString();

            return {
                text: '\n' + indent + '\n' + next_indent + closing,
                selection: [1, indent.length, 1, indent.length]
            };
        } else {
            CstyleBehaviour.clearMaybeInsertedClosing();
        }
    });

    this.add("braces", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '{') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.end.column, range.end.column + 1);
            if (rightChar == '}') {
                range.end.column++;
                return range;
            } else {
                context.maybeInsertedBrackets--;
            }
        }
    });

    this.add("parens", "insertion", function(state, action, editor, session, text) {
        if (text == '(') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '(', ')');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                CstyleBehaviour.recordAutoInsert(editor, session, ")");
                return {
                    text: '()',
                    selection: [1, 1]
                };
            }
        } else if (text == ')') {
            initContext(editor);
            var cursor = editor.getCursorPosition();
            var line = session.doc.getLine(cursor.row);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == ')') {
                var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        }
    });

    this.add("parens", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '(') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == ')') {
                range.end.column++;
                return range;
            }
        }
    });

    this.add("brackets", "insertion", function(state, action, editor, session, text) {
        if (text == '[') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '[', ']');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                CstyleBehaviour.recordAutoInsert(editor, session, "]");
                return {
                    text: '[]',
                    selection: [1, 1]
                };
            }
        } else if (text == ']') {
            initContext(editor);
            var cursor = editor.getCursorPosition();
            var line = session.doc.getLine(cursor.row);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == ']') {
                var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        }
    });

    this.add("brackets", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '[') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == ']') {
                range.end.column++;
                return range;
            }
        }
    });

    this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
        if (text == '"' || text == "'") {
            initContext(editor);
            var quote = text;
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, quote, quote);
            } else if (!selected) {
                var cursor = editor.getCursorPosition();
                var line = session.doc.getLine(cursor.row);
                var leftChar = line.substring(cursor.column-1, cursor.column);
                var rightChar = line.substring(cursor.column, cursor.column + 1);

                var token = session.getTokenAt(cursor.row, cursor.column);
                var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
                if (leftChar == "\\" && token && /escape/.test(token.type))
                    return null;

                var stringBefore = token && /string|escape/.test(token.type);
                var stringAfter = !rightToken || /string|escape/.test(rightToken.type);

                var pair;
                if (rightChar == quote) {
                    pair = stringBefore !== stringAfter;
                } else {
                    if (stringBefore && !stringAfter)
                        return null; // wrap string with different quote
                    if (stringBefore && stringAfter)
                        return null; // do not pair quotes inside strings
                    var wordRe = session.$mode.tokenRe;
                    wordRe.lastIndex = 0;
                    var isWordBefore = wordRe.test(leftChar);
                    wordRe.lastIndex = 0;
                    var isWordAfter = wordRe.test(leftChar);
                    if (isWordBefore || isWordAfter)
                        return null; // before or after alphanumeric
                    if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
                        return null; // there is rightChar and it isn't closing
                    pair = true;
                }
                return {
                    text: pair ? quote + quote : "",
                    selection: [1,1]
                };
            }
        }
    });

    this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == selected) {
                range.end.column++;
                return range;
            }
        }
    });

};

CstyleBehaviour.isSaneInsertion = function(editor, session) {
    var cursor = editor.getCursorPosition();
    var iterator = new TokenIterator(session, cursor.row, cursor.column);
    if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
        var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
        if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
            return false;
    }
    iterator.stepForward();
    return iterator.getCurrentTokenRow() !== cursor.row ||
        this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};

CstyleBehaviour.$matchTokenType = function(token, types) {
    return types.indexOf(token.type || token) > -1;
};

CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
    var cursor = editor.getCursorPosition();
    var line = session.doc.getLine(cursor.row);
    if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
        context.autoInsertedBrackets = 0;
    context.autoInsertedRow = cursor.row;
    context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
    context.autoInsertedBrackets++;
};

CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
    var cursor = editor.getCursorPosition();
    var line = session.doc.getLine(cursor.row);
    if (!this.isMaybeInsertedClosing(cursor, line))
        context.maybeInsertedBrackets = 0;
    context.maybeInsertedRow = cursor.row;
    context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
    context.maybeInsertedLineEnd = line.substr(cursor.column);
    context.maybeInsertedBrackets++;
};

CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
    return context.autoInsertedBrackets > 0 &&
        cursor.row === context.autoInsertedRow &&
        bracket === context.autoInsertedLineEnd[0] &&
        line.substr(cursor.column) === context.autoInsertedLineEnd;
};

CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
    return context.maybeInsertedBrackets > 0 &&
        cursor.row === context.maybeInsertedRow &&
        line.substr(cursor.column) === context.maybeInsertedLineEnd &&
        line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};

CstyleBehaviour.popAutoInsertedClosing = function() {
    context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
    context.autoInsertedBrackets--;
};

CstyleBehaviour.clearMaybeInsertedClosing = function() {
    if (context) {
        context.maybeInsertedBrackets = 0;
        context.maybeInsertedRow = -1;
    }
};

oop.inherits(CstyleBehaviour, Behaviour);

exports.CstyleBehaviour = CstyleBehaviour;
});

ace.define("ace/mode/sh",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sh_highlight_rules","ace/range","ace/mode/folding/cstyle","ace/mode/behaviour/cstyle"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules;
var Range = require("../range").Range;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;

var Mode = function() {
    this.HighlightRules = ShHighlightRules;
    this.foldingRules = new CStyleFoldMode();
    this.$behaviour = new CstyleBehaviour();
};
oop.inherits(Mode, TextMode);

(function() {

    this.lineCommentStart = "#";

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);

        var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
        var tokens = tokenizedLine.tokens;

        if (tokens.length && tokens[tokens.length-1].type == "comment") {
            return indent;
        }

        if (state == "start") {
            var match = line.match(/^.*[\{\(\[\:]\s*$/);
            if (match) {
                indent += tab;
            }
        }

        return indent;
    };

    var outdents = {
        "pass": 1,
        "return": 1,
        "raise": 1,
        "break": 1,
        "continue": 1
    };

    this.checkOutdent = function(state, line, input) {
        if (input !== "\r\n" && input !== "\r" && input !== "\n")
            return false;

        var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens;

        if (!tokens)
            return false;
        do {
            var last = tokens.pop();
        } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/))));

        if (!last)
            return false;

        return (last.type == "keyword" && outdents[last.value]);
    };

    this.autoOutdent = function(state, doc, row) {

        row += 1;
        var indent = this.$getIndent(doc.getLine(row));
        var tab = doc.getTabString();
        if (indent.slice(-tab.length) == tab)
            doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
    };

    this.$id = "ace/mode/sh";
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>Update public/libs/bower_components/ace-builds/src-noconflict/mode-sh.js<commit_after><|endoftext|>


<commit_before>Views.content.technology = function(win) {
	var view = Ti.UI.createView({
		backgroundImage: "images/page_bg.png"
	});

	var label = Ti.UI.createLabel({
		text: "Interventional Technology Platform",
		font:{fontFamily:'Helvetica LT CondensedBlack',fontSize:40,fontWeight:'regular'},
		color:"#023f66",
		width:'auto',
		top:40,
		height:'auto'
	});

	view.add(label);

	var label2 = Ti.UI.createLabel({
		text: "Interventional Technology Platform",
		font:{fontSize:40,fontWeight:'regular'},
		color:"#023f66",
		width:'auto',
		top:80,
		height:'auto'
	});

	view.add(label2);

	var label3 = Ti.UI.createLabel({
		text: "Interventional Technology Platform",
		font:{fontFamily:'AmericanTypewriter-Bold',fontSize:40,fontWeight:'regular'},
		color:"#023f66",
		width:'auto',
		top:120,
		height:'auto'
	});

	view.add(label3);

	var nav_view = Ti.UI.createView({
		height:430,
		width:430
	});

	var nav_circle = Ti.UI.createView({
		backgroundImage:"images/technology/large_nav/tech_nav_bg.png",
		height:400,
		width:400,
		bottom:0
	});

	nav_view.add(nav_circle);

	var nav_rf = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_rf.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_rf_pressed.png",
		height:130,
		width:130,
		top:0,
		id: 'rf_energy'
	});

	var nav_access = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_access.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_access_pressed.png",
		height:130,
		width:130,
		bottom:20,
		left:10,
		id: 'access_and_navigation'
	});

	var nav_bone = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_bone.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_bone_pressed.png",
		height:130,
		width:130,
		bottom:20,
		right:10,
		id: "bone_cement"
	});

	nav_view.add(nav_rf);
	nav_view.add(nav_access);
	nav_view.add(nav_bone);

	var getContent = function(name) {
		Views.content[name](view);
	}

	nav_rf.addEventListener('click', App.swapView(view, getContent.p("rf_energy")));
	nav_access.addEventListener('click', App.swapView(view, getContent.p("access_and_navigation")));
	nav_bone.addEventListener('click', App.swapView(view, getContent.p("bone_cement")));

	var rf_sub = Ti.UI.createLabel({
		text: "RF to modulate bone cement viscosity",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		top:300,
		left:700,
		height:'auto'
	});

	var access_sub = Ti.UI.createLabel({
		text: "Articulating osteotome enables site/size specificity",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		top:575,
		left:300,
		height:'auto'
	});

	var bone_sub = Ti.UI.createLabel({
		text: "Ultra-high viscosity cement, ideal for osteoporotic VCF applications",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		left:600,
		top:575,
		height:'auto'
	});

	var patents = Ti.UI.createLabel({
		text: "IP covering all three areas: 4 patents issued, 50 pending",
		font:{fontFamily:'Helvetica',fontSize:18,fontWeight:'regular'},
		color:"#023f66",
		width:"auto",
		bottom:50,
		height:'auto'
	});

	view.add(access_sub);
	view.add(rf_sub);
	view.add(bone_sub);
	view.add(patents);
	view.add(nav_view);

	win.add(view);
}
<commit_msg>technology update<commit_after>Views.content.technology = function(win) {
	var view = Ti.UI.createView({
		backgroundImage: "images/page_bg.png"
	});

	var label = Ti.UI.createLabel({
		text: "Interventional Technology Platform",
		font:{fontFamily:'Helvetica LT CondensedLight',fontSize:40,fontWeight:'regular'},
		color:"#023f66",
		width:'auto',
		top:40,
		height:'auto'
	});

	view.add(label);

	var nav_view = Ti.UI.createView({
		height:430,
		width:430
	});

	var nav_circle = Ti.UI.createView({
		backgroundImage:"images/technology/large_nav/tech_nav_bg.png",
		height:400,
		width:400,
		bottom:0
	});

	nav_view.add(nav_circle);

	var nav_rf = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_rf.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_rf_pressed.png",
		height:130,
		width:130,
		top:0,
		id: 'rf_energy'
	});

	var nav_access = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_access.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_access_pressed.png",
		height:130,
		width:130,
		bottom:20,
		left:10,
		id: 'access_and_navigation'
	});

	var nav_bone = Ti.UI.createButton({
		backgroundImage:"images/technology/large_nav/tech_nav_bone.png",
		backgroundSelectedImage:"images/technology/large_nav/tech_nav_bone_pressed.png",
		height:130,
		width:130,
		bottom:20,
		right:10,
		id: "bone_cement"
	});

	nav_view.add(nav_rf);
	nav_view.add(nav_access);
	nav_view.add(nav_bone);

	var getContent = function(name) {
		Views.content[name](view);
	}

	nav_rf.addEventListener('click', App.swapView(view, getContent.p("rf_energy")));
	nav_access.addEventListener('click', App.swapView(view, getContent.p("access_and_navigation")));
	nav_bone.addEventListener('click', App.swapView(view, getContent.p("bone_cement")));

	var rf_sub = Ti.UI.createLabel({
		text: "RF to modulate bone cement viscosity",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		top:300,
		left:700,
		height:'auto'
	});

	var access_sub = Ti.UI.createLabel({
		text: "Articulating osteotome enables site/size specificity",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		top:575,
		left:300,
		height:'auto'
	});

	var bone_sub = Ti.UI.createLabel({
		text: "Ultra-high viscosity cement, ideal for osteoporotic VCF applications",
		font:{fontFamily:'Helvetica',fontSize:14,fontWeight:'regular'},
		color:"#023f66",
		width:200,
		left:600,
		top:575,
		height:'auto'
	});

	var patents = Ti.UI.createLabel({
		text: "IP covering all three areas: 4 patents issued, 50 pending",
		font:{fontFamily:'Helvetica',fontSize:18,fontWeight:'regular'},
		color:"#023f66",
		width:"auto",
		bottom:50,
		height:'auto'
	});

	view.add(access_sub);
	view.add(rf_sub);
	view.add(bone_sub);
	view.add(patents);
	view.add(nav_view);

	win.add(view);
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/smart-link-to';

export default Ember.Component.extend({
  layout,
  cssClass: '',
  target: '',
  isRoute: Ember.computed('link', function () {
    // return this.get('container').has('route:' + this.get('link'));
    return Ember.getOwner(this).hasRegistration('route:' + this.get('link'));
  })
});
<commit_msg>removed comment<commit_after>import Ember from 'ember';
import layout from '../templates/components/smart-link-to';

export default Ember.Component.extend({
  layout,
  cssClass: '',
  target: '',
  isRoute: Ember.computed('link', function () {
    return Ember.getOwner(this).hasRegistration('route:' + this.get('link'));
  })
});
<|endoftext|>


<commit_before>import { assert } from '@ember/debug';
import { get } from '@ember/object';
import { assign } from '@ember/polyfills';
import removeFromDOM from '../utils/remove-from-dom';
import { compact } from '../utils/object-transforms';
import BaseAdapter from './base';

export default BaseAdapter.extend({
  toStringExtension() {
    return 'Segment';
  },

  init() {
    const config = assign({}, get(this, 'config'));
    const segmentKey = config.key;

    assert(`[ember-metrics] You must pass a valid \`key\` to the ${this.toString()} adapter`, segmentKey);

    /* eslint-disable */
    window.analytics=window.analytics||[],window.analytics.methods=["identify","group","track","page","pageview","alias","ready","on","once","off","trackLink","trackForm","trackClick","trackSubmit"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var key=window.analytics.methods[i];window.analytics[key]=window.analytics.factory(key)}window.analytics.load=function(t){if(!document.getElementById("analytics-js")){var a=document.createElement("script");a.type="text/javascript",a.id="analytics-js",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)}},window.analytics.SNIPPET_VERSION="2.0.9";
    /* eslint-enable */
    window.analytics.load(segmentKey);
  },

  alias(options = {}) {
    const compactedOptions = compact(options);
    const { alias, original } = compactedOptions;

    if (original) {
      window.analytics.alias(alias, original);
    } else {
      window.analytics.alias(alias);
    }
  },

  identify(options = {}) {
    const compactedOptions = compact(options);
    const { distinctId } = compactedOptions;
    delete compactedOptions.distinctId;

    window.analytics.identify(distinctId, compactedOptions);
  },

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const { event } = compactedOptions;
    delete compactedOptions.event;

    window.analytics.track(event, compactedOptions);
  },

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const { page } = compactedOptions;
    delete compactedOptions.page;

    window.analytics.page(page, compactedOptions);
  },

  willDestroy() {
    removeFromDOM('script[src*="segment.com"]');

    delete window.analytics;
  }
});
<commit_msg>Prettify Segment snippet<commit_after>import { assert } from '@ember/debug';
import { get } from '@ember/object';
import { assign } from '@ember/polyfills';
import removeFromDOM from '../utils/remove-from-dom';
import { compact } from '../utils/object-transforms';
import BaseAdapter from './base';

export default BaseAdapter.extend({
  toStringExtension() {
    return 'Segment';
  },

  init() {
    const config = assign({}, get(this, 'config'));
    const segmentKey = config.key;

    assert(`[ember-metrics] You must pass a valid \`key\` to the ${this.toString()} adapter`, segmentKey);

    /* eslint-disable */
    (window.analytics = window.analytics || []),
      (window.analytics.methods = [
        "identify",
        "group",
        "track",
        "page",
        "pageview",
        "alias",
        "ready",
        "on",
        "once",
        "off",
        "trackLink",
        "trackForm",
        "trackClick",
        "trackSubmit",
      ]),
      (window.analytics.factory = function (t) {
        return function () {
          var a = Array.prototype.slice.call(arguments);
          return a.unshift(t), window.analytics.push(a), window.analytics;
        };
      });
    for (var i = 0; i < window.analytics.methods.length; i++) {
      var key = window.analytics.methods[i];
      window.analytics[key] = window.analytics.factory(key);
    }
    (window.analytics.load = function (t) {
      if (!document.getElementById("analytics-js")) {
        var a = document.createElement("script");
        (a.type = "text/javascript"),
          (a.id = "analytics-js"),
          (a.async = !0),
          (a.src =
            ("https:" === document.location.protocol ? "https://" : "http://") +
            "cdn.segment.com/analytics.js/v1/" +
            t +
            "/analytics.min.js");
        var n = document.getElementsByTagName("script")[0];
        n.parentNode.insertBefore(a, n);
      }
    }),
      (window.analytics.SNIPPET_VERSION = "2.0.9");
    /* eslint-enable */
    window.analytics.load(segmentKey);
  },

  alias(options = {}) {
    const compactedOptions = compact(options);
    const { alias, original } = compactedOptions;

    if (original) {
      window.analytics.alias(alias, original);
    } else {
      window.analytics.alias(alias);
    }
  },

  identify(options = {}) {
    const compactedOptions = compact(options);
    const { distinctId } = compactedOptions;
    delete compactedOptions.distinctId;

    window.analytics.identify(distinctId, compactedOptions);
  },

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const { event } = compactedOptions;
    delete compactedOptions.event;

    window.analytics.track(event, compactedOptions);
  },

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const { page } = compactedOptions;
    delete compactedOptions.page;

    window.analytics.page(page, compactedOptions);
  },

  willDestroy() {
    removeFromDOM('script[src*="segment.com"]');

    delete window.analytics;
  },
});
<|endoftext|>


<commit_before>'use strict';

const path = require('path'),
      os = require('os'),
      webpack = require('webpack'),
      utils = require('steamer-webpack-utils'),
      steamerConfig = require('./steamer.config'),
      __basename = path.dirname(__dirname),
      __env = process.env.NODE_ENV,
      isProduction = __env === 'production';

var srcPath = path.resolve(__basename, "src"),
    devPath = path.resolve(__basename, "dev"),
    distPath = path.resolve(__basename, "dist"),
    spritePath = path.resolve(__basename, "src/img/sprites");

var hash = "[hash:6]",
    chunkhash = "[chunkhash:6]",
    contenthash = "[contenthash:6]";

var HtmlResWebpackPlugin = require('html-res-webpack-plugin'),
    ExtractTextPlugin = require("extract-text-webpack-plugin"),
    HappyPack = require('happypack');

// ========================= webpack快捷配置 =========================
// 基本情况下，你只需要关注这里的配置
var config = {
    // ========================= webpack环境配置 =========================
    env: __env,

    webpack: {

        // ========================= webpack路径与url =========================
        // 项目路径
        path: {
            src: srcPath,
            dev: devPath,
            dist: distPath,
            sprite: spritePath,
        },

        // ========================= webpack服务器及路由配置 =========================
        // 开发服务器配置
        webserver: steamerConfig.webserver,
        cdn: steamerConfig.cdn,
        port: steamerConfig.port,    // port for local server
        route: steamerConfig.route, // http://host/news/

        // ========================= webpack自定义配置 =========================
        // 是否清理生成文件夹
        clean: true,
        // sourcemap
        sourceMap: {
            development: "inline-source-map",
            production: false,
        },

        // 样式
        style: [
            "css", "less", "stylus"
        ],
        // 生产环境是否提取css
        extractCss: true,
        // 是否启用css模块化
        cssModule: false,

        // 合图，mobile = 2倍图，pc = 1倍图
        spriteMode: "mobile",
        // less, stylus
        spriteStyle: "less",

        // html模板
        template: [
            "html", "pug", "handlebars"
        ],

        // 资源是否压缩
        compress: true,

        // 不经webpack打包的资源
        static: [
            {
                src: "libs/",
                hash: true,
            }
        ],

        // 文件名与哈希, hash, chunkhash, contenthash 与webpack的哈希配置对应
        hash: hash,
        chunkhash: chunkhash,
        contenthash: contenthash,
        hashName: isProduction ? ("[name]-" + hash) : "[name]",
        chunkhashName: isProduction ? ("[name]-" + chunkhash) : "[name]",
        contenthashName: isProduction ? ("[name]-" + contenthash) : "[name]",

        // ========================= webpack entry配置 =========================
        // 根据约定，自动扫描js entry，约定是src/page/xxx/main.js 或 src/page/xxx/main.jsx
        /**
            当前获取结果
            {
                'js/index': [path.join(configWebpack.path.src, "/page/index/main.js")],
                'js/spa': [path.join(configWebpack.path.src, "/page/spa/main.js")],
                'js/pindex': [path.join(configWebpack.path.src, "/page/pindex/main.jsx")],
            }
         */
        entry: utils.getJsEntry({
            srcPath: path.join(srcPath, "page"),
            fileName: "main",
            extensions: ["js", "jsx"],
            keyPrefix: "js/",
            level: 1
        }),

        // 自动扫描html，配合html-res-webpack-plugin
        html: utils.getHtmlEntry({
            srcPath: path.join(srcPath, "page"),
            level: 1
        }),

        // 自动扫描合图，配合webpack-spritesmith插件
        sprites: utils.getSpriteEntry({
            srcPath: spritePath
        }),

    },
};

// ========================= webpack深度配置 =========================
// 使用了webpack-merge与webpack.base.js进行配置合并
// 如果上面的配置仍未能满足你，你可以在此处对webpack直接进行配置，这里的配置与webpack的配置项目一一对应
config.custom = {
    // webpack output
    getOutput: function() {
        return {};
    },

    // webpack module
    getModule: function() {

        var module = {
            rules: [
                {
                    test: /\.js$/,
                    loader: 'happypack/loader?id=1',
                    exclude: /node_modules/,
                }
            ]
        };

        var styleRules = {
            css: {
                test: /\.css$/,
                // 单独抽出样式文件
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                root: config.webpack.path.src,
                                module: config.webpack.cssModule
                            }
                        },
                        { loader: 'postcss-loader' },
                    ]
                }),
                include: path.resolve(config.webpack.path.src)
            },
            less: {
                test: /\.less$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                module: config.webpack.cssModule
                            }
                        },
                        { loader: 'postcss-loader' },
                        {
                            loader:  'less-loader',
                            options: {
                                paths: [
                                    config.webpack.path.src,
                                    "node_modules"
                                ]
                            }
                        }
                    ]
                }),
            },
            stylus: {
                test: /\.styl$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                // module: true
                            }
                        },
                        { loader: 'postcss-loader' },
                        { loader:  'stylus-loader' },
                    ]
                }),
            },
        };

        var templateRules = {
            html: {
                test: /\.html$/,
                loader: 'html-loader'
            },
            pug: {
                test: /\.pug$/,
                loader: 'pug-loader'
            },
            handlebars: {
                test: /\.handlebars$/,
                loader: "handlebars-loader"
            },
        };

        config.webpack.style.forEach((style) => {
            let rule = styleRules[style] || '';
            rule && module.rules.push(rule);
        });

        config.webpack.template.forEach((tpl) => {
            let rule = templateRules[tpl] || '';
            rule && module.rules.push(rule);
        });

        return module;
    },

    // webpack resolve
    getResolve: function() {
        return {};
    },

    // webpack plugins
    getPlugins: function() {
        var plugins = [
            new ExtractTextPlugin({
                filename:  (getPath) => {
                  return getPath('css/' + config.webpack.contenthashName + '.css').replace('css/js', 'css');
                },
                allChunks: false,
                disable: (isProduction || !config.webpack.extractCss) ? false : true,
            }),
            new HappyPack({
                id: '1',
                verbose: false,
                loaders: [{
                    path: 'babel-loader',
                    options: {
                        cacheDirectory: './.webpack_cache/',
                        presets: [
                            ["es2015", {"loose": true}],
                        ]
                    },
                }],
            })
        ];

        config.webpack.html.forEach(function(page, key) {
            plugins.push(new HtmlResWebpackPlugin({
                mode: "html",
                filename: isProduction ? ("../webserver/" + page.key + ".html") : page.key + ".html",
                template: page.path,
                favicon: "src/favicon.ico",
                htmlMinify: null,
                entryLog: !key ? true : false,
                templateContent: function(tpl) {
                    return tpl;
                }
            }));
        });

        return plugins;
    },

    // webpack externals
    getExternals: function() {
        return {
            '$': "zepto",
        };
    },

    // 其它 webpack 配置
    getOtherOptions: function() {
        return {};
    }
};

module.exports = config;<commit_msg>add more comments<commit_after>'use strict';

const path = require('path'),
      os = require('os'),
      webpack = require('webpack'),
      utils = require('steamer-webpack-utils'),
      steamerConfig = require('./steamer.config'),
      __basename = path.dirname(__dirname),
      __env = process.env.NODE_ENV,
      isProduction = __env === 'production';

var srcPath = path.resolve(__basename, "src"),
    devPath = path.resolve(__basename, "dev"),
    distPath = path.resolve(__basename, "dist"),
    spritePath = path.resolve(__basename, "src/img/sprites");

var hash = "[hash:6]",
    chunkhash = "[chunkhash:6]",
    contenthash = "[contenthash:6]";

var HtmlResWebpackPlugin = require('html-res-webpack-plugin'),
    ExtractTextPlugin = require("extract-text-webpack-plugin"),
    HappyPack = require('happypack');

// ========================= webpack快捷配置 =========================
// 基本情况下，你只需要关注这里的配置
var config = {
    // ========================= webpack环境配置 =========================
    env: __env,

    webpack: {

        // ========================= webpack路径与url =========================
        // 项目路径
        path: {
            src: srcPath,
            dev: devPath,
            dist: distPath,
            sprite: spritePath,
        },

        // ========================= webpack服务器及路由配置 =========================
        // 开发服务器配置
        webserver: steamerConfig.webserver,
        cdn: steamerConfig.cdn,
        port: steamerConfig.port,    // port for local server
        route: steamerConfig.route, // http://host/news/

        // ========================= webpack自定义配置 =========================
        // 是否清理生成文件夹
        clean: true,
        // sourcemap
        sourceMap: {
            development: "inline-source-map",
            production: false,
        },

        // 样式
        style: [
            "css", "less", "stylus"
        ],
        // 生产环境是否提取css
        extractCss: true,
        // 是否启用css模块化
        cssModule: false,

        // 合图，mobile = 2倍图，pc = 1倍图
        spriteMode: "mobile",
        // less, stylus
        spriteStyle: "less",

        // html模板
        template: [
            "html", "pug", "handlebars"
        ],

        // 资源是否压缩
        compress: true,

        // 不经webpack打包的资源
        static: [
            {
                src: "libs/",
                hash: true,
            }
        ],

        // 文件名与哈希, hash, chunkhash, contenthash 与webpack的哈希配置对应
        hash: hash,
        chunkhash: chunkhash,
        contenthash: contenthash,
        hashName: isProduction ? ("[name]-" + hash) : "[name]",
        chunkhashName: isProduction ? ("[name]-" + chunkhash) : "[name]",
        contenthashName: isProduction ? ("[name]-" + contenthash) : "[name]",

        // ========================= webpack entry配置 =========================
        // 根据约定，自动扫描js entry，约定是src/page/xxx/main.js 或 src/page/xxx/main.jsx
        /**
            当前获取结果
            {
                'js/index': [path.join(configWebpack.path.src, "/page/index/main.js")],
                'js/spa': [path.join(configWebpack.path.src, "/page/spa/main.js")],
                'js/pindex': [path.join(configWebpack.path.src, "/page/pindex/main.jsx")],
            }
         */
        entry: utils.getJsEntry({
            srcPath: path.join(srcPath, "page"),
            fileName: "main",
            extensions: ["js", "jsx"],
            keyPrefix: "js/",
            level: 1
        }),

        // 自动扫描html，配合html-res-webpack-plugin
        /**
            当前获取结果
            [
                {
                    key: 'index',
                    path: 'path/src/page/index/index.html'
                },
                {
                    key: 'spa',
                    path: 'path/src/page/spa/index.html'
                },
                {
                    key: 'pindex',
                    path: 'path/src/page/pindex/index.html'
                }
            ]
         */
        html: utils.getHtmlEntry({
            srcPath: path.join(srcPath, "page"),
            level: 1
        }),

        // 自动扫描合图，配合webpack-spritesmith插件
        /**
            当前获取结果
            [
                {
                    key: 'btn',
                    path: 'path/src/img/sprites/btn'
                },
                {
                    key: 'list',
                    path: 'path/src/img/sprites/list'
                }
            ]
         */
        sprites: utils.getSpriteEntry({
            srcPath: spritePath
        }),

    },
};

// ========================= webpack深度配置 =========================
// 使用了webpack-merge与webpack.base.js进行配置合并
// 如果上面的配置仍未能满足你，你可以在此处对webpack直接进行配置，这里的配置与webpack的配置项目一一对应
config.custom = {
    // webpack output
    getOutput: function() {
        return {};
    },

    // webpack module
    getModule: function() {

        var module = {
            rules: [
                {
                    test: /\.js$/,
                    loader: 'happypack/loader?id=1',
                    exclude: /node_modules/,
                }
            ]
        };

        var styleRules = {
            css: {
                test: /\.css$/,
                // 单独抽出样式文件
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                root: config.webpack.path.src,
                                module: config.webpack.cssModule
                            }
                        },
                        { loader: 'postcss-loader' },
                    ]
                }),
                include: path.resolve(config.webpack.path.src)
            },
            less: {
                test: /\.less$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                module: config.webpack.cssModule
                            }
                        },
                        { loader: 'postcss-loader' },
                        {
                            loader:  'less-loader',
                            options: {
                                paths: [
                                    config.webpack.path.src,
                                    "node_modules"
                                ]
                            }
                        }
                    ]
                }),
            },
            stylus: {
                test: /\.styl$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                localIdentName: '[name]-[local]-[hash:base64:5]',
                                // module: true
                            }
                        },
                        { loader: 'postcss-loader' },
                        { loader:  'stylus-loader' },
                    ]
                }),
            },
        };

        var templateRules = {
            html: {
                test: /\.html$/,
                loader: 'html-loader'
            },
            pug: {
                test: /\.pug$/,
                loader: 'pug-loader'
            },
            handlebars: {
                test: /\.handlebars$/,
                loader: "handlebars-loader"
            },
        };

        config.webpack.style.forEach((style) => {
            let rule = styleRules[style] || '';
            rule && module.rules.push(rule);
        });

        config.webpack.template.forEach((tpl) => {
            let rule = templateRules[tpl] || '';
            rule && module.rules.push(rule);
        });

        return module;
    },

    // webpack resolve
    getResolve: function() {
        return {};
    },

    // webpack plugins
    getPlugins: function() {
        var plugins = [
            new ExtractTextPlugin({
                filename:  (getPath) => {
                  return getPath('css/' + config.webpack.contenthashName + '.css').replace('css/js', 'css');
                },
                allChunks: false,
                disable: (isProduction || !config.webpack.extractCss) ? false : true,
            }),
            new HappyPack({
                id: '1',
                verbose: false,
                loaders: [{
                    path: 'babel-loader',
                    options: {
                        cacheDirectory: './.webpack_cache/',
                        presets: [
                            ["es2015", {"loose": true}],
                        ]
                    },
                }],
            })
        ];

        config.webpack.html.forEach(function(page, key) {
            plugins.push(new HtmlResWebpackPlugin({
                mode: "html",
                filename: isProduction ? ("../webserver/" + page.key + ".html") : page.key + ".html",
                template: page.path,
                favicon: "src/favicon.ico",
                htmlMinify: null,
                entryLog: !key ? true : false,
                templateContent: function(tpl) {
                    return tpl;
                }
            }));
        });

        return plugins;
    },

    // webpack externals
    getExternals: function() {
        return {
            '$': "zepto",
        };
    },

    // 其它 webpack 配置
    getOtherOptions: function() {
        return {};
    }
};

module.exports = config;<|endoftext|>


<commit_before>// Collection of application secrets

module.exports = {
  twilio: {
    twilio_account_id: process.env.TWILIO_ID || 'bogus',
    twilio_auth_token: process.env.TWILIO_AUTH || 'bogus'
  }

}
<commit_msg>Added phone number setting as a secret field<commit_after>// Collection of application secrets

module.exports = {
  twilio: {
    twilio_account_id: process.env.TWILIO_ID || 'bogus',
    twilio_auth_token: process.env.TWILIO_AUTH || 'bogus',
    twilio_phone_number: process.env.TWILIO_NUMBER || '8888881994'
  }

}
<|endoftext|>