<commit_before>/*!
 * Valiant360 panorama video player jquery plugin
 *
 * Copyright (c) 2014 Charlie Hoey <@flimshaw>
 *
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Jquery plugin pattern by @ianjmitchell (http://iainjmitchell.com/blog/?p=360)
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;define(['jquery', 'threejs', 'detector'], function ( $, THREE ) {

    //define the commands that can be used
    var commands = {
        play: play,
        stop: pause
    };

    var defaults = {
        fov: 35,
        lon: 0,
        lat: 0,
        loop: "loop",
        muted: true,
        debug: false,
        autoplay: true
    }

    var camera
      , scene
      , renderer
      , video
      , texture
      , texture_placeholder
      , self
      , lat
      , lon
      , fov;

    $.fn.Valiant360 = function() {

        if (typeof arguments[0] === 'string') {
            //execute string comand on mediaPlayer
            var property = arguments[1];
            //remove the command name from the arguments
            var args = Array.prototype.slice.call(arguments);
            args.splice(0, 1);

            commands[arguments[0]].apply(this, args);
        }
        else {
            //create mediaPlayer
            createMediaPlayer.apply(this, arguments);
        }

        return this;
    };

    function createMediaPlayer(options){

        self = this;

        this.options = $.extend( {}, defaults, options) ;

        lat = this.options.lat;
        lon = this.options.lon;
        fov = this.options.fov;

        // create ThreeJS scene
        scene = new THREE.Scene();

        // create ThreeJS camera
        camera = new THREE.PerspectiveCamera( this.options.fov, window.innerWidth / window.innerHeight, .1, 1000);

        // create ThreeJS renderer and append it to our object
        renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        this.append(renderer.domElement);

        // create off-dom video player
        video = document.createElement( 'video' );
        video.loop = this.options.loop;
        video.muted = this.options.muted;

        // create ThreeJS texture and high performance defaults
        texture = new THREE.Texture( video );
        texture.generateMipmaps = false;
        texture.minFilter = THREE.LinearFilter;
        texture.magFilter = THREE.LinearFilter;
        texture.format = THREE.RGBFormat;

        // create ThreeJS mesh sphere onto which our texture will be drawn
        mesh = new THREE.Mesh( new THREE.SphereGeometry( 500, 80, 50 ), new THREE.MeshBasicMaterial( { map: texture } ) );
        mesh.scale.x = -1; // mirror the texture, since we're looking from the inside out
        scene.add(mesh);

        // attach video player event listeners
        video.addEventListener("ended", function(e) {
            log("video loaded");
        });

        // Progress Meter
        video.addEventListener("progress", function(e) {
            var percent = null;
                if (video && video.buffered && video.buffered.length > 0 && video.buffered.end && video.duration) {
                    percent = video.buffered.end(0) / video.duration;
                }
                // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
                // to be anything other than 0. If the byte count is available we use this instead.
                // Browsers that support the else if do not seem to have the bufferedBytes value and
                // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
                else if (video && video.bytesTotal != undefined && video.bytesTotal > 0 && video.bufferedBytes != undefined) {
                    percent = video.bufferedBytes / video.bytesTotal;
                }

                var cpct = Math.round(percent * 100);
                if(cpct == 100) {

                } else {
                    // do something with this percentage info (cpct)
                }
        });

        // Video Play Listener, fires after video loads
        video.addEventListener("canplaythrough", function(e) {

            if(self.options.autoplay == true) {
                video.play();
            }

            animate();
            log("playing");
        });

        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
        document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);

        // attach mouse listeners
        function onDocumentMouseMove( event ) {
            onPointerDownPointerX = event.clientX;
            onPointerDownPointerY = -event.clientY;

            onPointerDownLon = lon;
            onPointerDownLat = lat;
            if ( 1 ) {

                lon = ( event.clientX / window.innerWidth ) * 430 - 225
                lat = ( event.clientY / window.innerHeight ) * -180 + 90

            }
        }

        function onDocumentMouseWheel( event ) {

            var wheelSpeed = -.01;

            // WebKit

            if ( event.wheelDeltaY ) {

                fov -= event.wheelDeltaY * wheelSpeed;

            // Opera / Explorer 9

            } else if ( event.wheelDelta ) {

                fov -= event.wheelDelta * wheelSpeed;

            // Firefox

            } else if ( event.detail ) {

                fov += event.detail * 1.0;

            }

            var fovMin = 3;
            var fovMax = 100;

            if(fov < fovMin) {
                fov = fovMin;
            } else if(fov > fovMax) {
                fov = fovMax;
            }

            camera.setLens(fov)
            //render();

        }

        // set the video src and begin loading
        video.src = this.attr('data-video-src');
    }

    //Exposed functions
    function play() {
      //code to play media
      video.play()
    }

    function pause() {
      //code to stop media
      video.pause();
    }

    var count = 1;
    function animate() {
        // set our animate function to fire next time a frame is ready
        requestAnimationFrame( animate );
        count++;
        if(count > 100000) {
            count = 0;
        }
        if ( video.readyState === video.HAVE_ENOUGH_DATA) {
            if(typeof(texture) != "undefined" ) {
                if(count % 2 == 0) {
                    texture.needsUpdate = true;
                }

            }
        }

        render();

    }

    function render() {

        lat = Math.max( - 85, Math.min( 85, lat ) );
        phi = ( 90 - lat ) * Math.PI / 180;
        theta = lon * Math.PI / 180;

        var cx = 500 * Math.sin( phi ) * Math.cos( theta );
        var cy = 500 * Math.cos( phi );
        var cz = 500 * Math.sin( phi ) * Math.sin( theta );

        camera.lookAt(new THREE.Vector3(cx, cy, cz));

        // distortion
        camera.position.x = - cx;
        camera.position.y = - cy;
        camera.position.z = - cz;

        renderer.render( scene, camera );
    }

    // TODO: wire up a custom log function to turn off if we have debug mode set to false
    function log(msg) {
        console.info(msg);
    }

});<commit_msg>updated texture updater to fire at 30p<commit_after>/*!
 * Valiant360 panorama video player jquery plugin
 *
 * Copyright (c) 2014 Charlie Hoey <@flimshaw>
 *
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Jquery plugin pattern by @ianjmitchell (http://iainjmitchell.com/blog/?p=360)
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;define(['jquery', 'threejs', 'detector'], function ( $, THREE ) {

    //define the commands that can be used
    var commands = {
        play: play,
        stop: pause
    };

    var defaults = {
        fov: 35,
        lon: 0,
        lat: 0,
        loop: "loop",
        muted: true,
        debug: false,
        autoplay: true
    }

    var camera
      , scene
      , renderer
      , video
      , texture
      , texture_placeholder
      , self
      , lat
      , lon
      , fov;

    $.fn.Valiant360 = function() {

        if (typeof arguments[0] === 'string') {
            //execute string comand on mediaPlayer
            var property = arguments[1];
            //remove the command name from the arguments
            var args = Array.prototype.slice.call(arguments);
            args.splice(0, 1);

            commands[arguments[0]].apply(this, args);
        }
        else {
            //create mediaPlayer
            createMediaPlayer.apply(this, arguments);
        }

        return this;
    };

    function createMediaPlayer(options){

        self = this;

        this.options = $.extend( {}, defaults, options) ;

        lat = this.options.lat;
        lon = this.options.lon;
        fov = this.options.fov;

        // create ThreeJS scene
        scene = new THREE.Scene();

        // create ThreeJS camera
        camera = new THREE.PerspectiveCamera( this.options.fov, window.innerWidth / window.innerHeight, .1, 1000);

        // create ThreeJS renderer and append it to our object
        renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        this.append(renderer.domElement);

        // create off-dom video player
        video = document.createElement( 'video' );
        video.loop = this.options.loop;
        video.muted = this.options.muted;

        // create ThreeJS texture and high performance defaults
        texture = new THREE.Texture( video );
        texture.generateMipmaps = false;
        texture.minFilter = THREE.LinearFilter;
        texture.magFilter = THREE.LinearFilter;
        texture.format = THREE.RGBFormat;

        // create ThreeJS mesh sphere onto which our texture will be drawn
        mesh = new THREE.Mesh( new THREE.SphereGeometry( 500, 80, 50 ), new THREE.MeshBasicMaterial( { map: texture } ) );
        mesh.scale.x = -1; // mirror the texture, since we're looking from the inside out
        scene.add(mesh);

        // attach video player event listeners
        video.addEventListener("ended", function(e) {
            log("video loaded");
        });

        // Progress Meter
        video.addEventListener("progress", function(e) {
            var percent = null;
                if (video && video.buffered && video.buffered.length > 0 && video.buffered.end && video.duration) {
                    percent = video.buffered.end(0) / video.duration;
                }
                // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
                // to be anything other than 0. If the byte count is available we use this instead.
                // Browsers that support the else if do not seem to have the bufferedBytes value and
                // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
                else if (video && video.bytesTotal != undefined && video.bytesTotal > 0 && video.bufferedBytes != undefined) {
                    percent = video.bufferedBytes / video.bytesTotal;
                }

                var cpct = Math.round(percent * 100);
                if(cpct == 100) {

                } else {
                    // do something with this percentage info (cpct)
                }
        });

        // Video Play Listener, fires after video loads
        video.addEventListener("canplaythrough", function(e) {

            if(self.options.autoplay == true) {
                video.play();
            }

            animate();
            log("playing");
        });

        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
        document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);

        // attach mouse listeners
        function onDocumentMouseMove( event ) {
            onPointerDownPointerX = event.clientX;
            onPointerDownPointerY = -event.clientY;

            onPointerDownLon = lon;
            onPointerDownLat = lat;
            if ( 1 ) {

                lon = ( event.clientX / window.innerWidth ) * 430 - 225
                lat = ( event.clientY / window.innerHeight ) * -180 + 90

            }
        }

        function onDocumentMouseWheel( event ) {

            var wheelSpeed = -.01;

            // WebKit

            if ( event.wheelDeltaY ) {

                fov -= event.wheelDeltaY * wheelSpeed;

            // Opera / Explorer 9

            } else if ( event.wheelDelta ) {

                fov -= event.wheelDelta * wheelSpeed;

            // Firefox

            } else if ( event.detail ) {

                fov += event.detail * 1.0;

            }

            var fovMin = 3;
            var fovMax = 100;

            if(fov < fovMin) {
                fov = fovMin;
            } else if(fov > fovMax) {
                fov = fovMax;
            }

            camera.setLens(fov)
            //render();

        }

        // set the video src and begin loading
        video.src = this.attr('data-video-src');
    }

    //Exposed functions
    function play() {
      //code to play media
      video.play()
    }

    function pause() {
      //code to stop media
      video.pause();
    }

    // store the time of the script start
    var time = new Date().getTime();

    function animate() {
        // set our animate function to fire next time a frame is ready
        requestAnimationFrame( animate );

        if ( video.readyState === video.HAVE_ENOUGH_DATA) {
            if(typeof(texture) != "undefined" ) {
                var ct = new Date().getTime();
                if(ct - time >= 33) {
                    texture.needsUpdate = true;
                    time = ct;
                }
            }
        }

        render();

    }

    function render() {

        lat = Math.max( - 85, Math.min( 85, lat ) );
        phi = ( 90 - lat ) * Math.PI / 180;
        theta = lon * Math.PI / 180;

        var cx = 500 * Math.sin( phi ) * Math.cos( theta );
        var cy = 500 * Math.cos( phi );
        var cz = 500 * Math.sin( phi ) * Math.sin( theta );

        camera.lookAt(new THREE.Vector3(cx, cy, cz));

        // distortion
        camera.position.x = - cx;
        camera.position.y = - cy;
        camera.position.z = - cz;

        renderer.render( scene, camera );
    }

    // TODO: wire up a custom log function to turn off if we have debug mode set to false
    function log(msg) {
        console.info(msg);
    }

});<|endoftext|>


<commit_before>// Create a static 'extends' method on the Object class
// This allows us to extend existing classes
// for classical object-oriented inheritance
Object.extend = function(superClass, definition) {
    var subClass = function() {};
    // Our constructor becomes the 'subclass'
    if (definition.constructor !== Object)
        subClass = definition.constructor;
    subClass.prototype = new superClass();
    for (var prop in definition) {
        if (prop != 'constructor')
            subClass.prototype[prop] = definition[prop];
    }
    return subClass;
};

var delay = (function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

var BoltExtender = Object.extend(Object, {

    selector: ".extend-bolt-container",
    messages:  {},
    paths:  {},

    constructor: function(){
        jQuery(this.selector).on("change", this, this.events.change);
        jQuery(this.selector).on("click", this, this.events.click);

        jQuery(document).ajaxStart(function() {
            // show loader on start
            active_interval = setInterval(function(){
                active_console.append(".");
            },1000);
        }).ajaxSuccess(function() {
            clearInterval(active_interval);
        });

        this.checkInstalled();
        this.liveSearch();
        this.installReset();

    },

    find: function(selector) {
        return jQuery(this.selector).find(selector);
    },

    setMessage: function(key, value) {
        this.messages[key]=value;
    },

    setPath: function(key, value) {
        this.paths[key]=value;
    },

    installReset: function() {
        var controller = this;
        jQuery('#installModal').on('hide.bs.modal', function (e) {
            controller.find(".stable-version-container .installed-version-item").html('
'+controller.messages['noStable']+'
');
            controller.find(".dev-version-container .installed-version-item").html('
'+controller.messages['noDev']+'
');
            controller.find('.extension-postinstall').hide();
            controller.find('.install-version-container').hide();
            controller.find("#installModal .loader").show();
        });
    },

    updateCheck: function() {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-list-items");
        active_console = controller.find('.update-output');
        active_console.html(controller.messages['updating']);
        jQuery.get(baseurl+'check', function(data) {
            if(data.updates.length > 0 || data.installs.length >0) {
                for(var e in data.installs) {
                    var ext = data.installs[e];
                    target.append("
"+ext+"	 Install New Package
");
                }
                for(var e in data.updates) {
                    var ext = data.updates[e];
                    target.append("
"+ext+"	 Install Package Update
");
                }
                active_console.hide();
                controller.find('.update-list').show();
            } else {
                active_console.html(controller.messages['updated']);
            }
        });
    },

    updateRun: function() {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-output" );
        active_console = target;
        active_console.html("Running update....");
        jQuery.get(baseurl+'update', function(data) {
            target.html(data);
            setTimeout(function(){
                controller.find('.update-container').hide();
            },7000);
        });
    },

    updatePackage: function(e) {
        var controller = this;
        var t = this.find('.update-output').html(controller.messages['updating']);
        var packageToUpdate = jQuery(e.target).data("package");
        t.show();
        active_console = t;
        jQuery.get(
            baseurl+'update?package='+packageToUpdate
        )
        .success(function(data) {
            controller.find('.update-output').html(data);
            controller.find('.update-list-items tr[data-package="'+packageToUpdate+'"]').remove();
            delay(function(){
                active_console.hide();
            }, 4000);
            if(controller.find('.update-list-items tbody tr').length <1) {
                controller.find('.update-container').hide();
            }
            controller.checkInstalled();
        });

        e.preventDefault();
    },

    installRun: function(e) {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-output" );
        active_console = target;
        active_console.html(controller.messages['installAll']);
        jQuery.get(baseurl+'installAll', function(data) {
            target.html(data);
            delay(function(){
                controller.find('.update-container').hide();
            },7000);
        });
        e.stopPropagation();
        e.preventDefault();
    },

    checkInstalled: function() {
        var controller = this;

        controller.find('.installed-container').each(function(){
            active_console = controller.find(".installed-container .console");
            var target = jQuery(this).find('.installed-list');
            jQuery.get(baseurl+"installed", function(data) {
                target.show();
                if(data.length > 0) {
                    active_console.html(data.length + " installed extension(s).");
                    delay(function(){
                        controller.find(".installed-container .console").hide();
                    },7000);
                    target.find('.installed-list-items').html('');
                    for(var e in data) {
                        ext = data[e];
                        var html = "
" + ext["name"] +
                            "	" + ext["version"] + "	 " + ext["type"] +
                            "	 " + ext["descrip"] + "	 ";

                        if (ext["readmelink"]) {
                            html += " Readme ";
                        }

                        if (ext["config"]) {
                            html += " Config ";
                        }

                        html += " Uninstall" + "
";
                        //console.log(ext);
                        target.find('.installed-list-items').append(html);
                    }
                } else {
                    target.find('.installed-list-items').html("
No Bolt Extensions installed.
");
                    active_console.hide();
                }
            });
        });
    },

    checkPackage: function(e) {
        var controller = this;
        var ext = this.find('input[name="check-package"]').val();
        active_console = this.find(".check-package");
        jQuery.get(baseurl+'installInfo?package='+ext, function(data) {

            var devpacks = data['dev'];
            var stablepacks = data['stable'];

            if(devpacks.length > 0) {
              controller.find('.dev-version-container .installed-version-item').html("");
            }

            if(stablepacks.length > 0) {
              controller.find('.stable-version-container .installed-version-item').html("");
            }

            for(var v in devpacks) {
                version = devpacks[v];
                var tpl = '
'+version.name+'	'+version.version+'	';
                tpl = tpl+'
'
                tpl = tpl+' Install This Version

';
                controller.find('.dev-version-container .installed-version-item').append(tpl);
            }
            for(var v in stablepacks) {
                version = stablepacks[v];
                var tpl = '
'+version.name+'	'+version.version+'	';
                tpl = tpl+'
';
                tpl = tpl+' Install This Version

';
                controller.find('.stable-version-container .installed-version-item').append(tpl);
            }

            controller.find(".install-version-container").show();
            controller.find("#installModal .loader").hide();
        });

        e.preventDefault();
    },

    install: function(e) {
        var controller = this;

        var package = jQuery(e.target).data("package");
        var version = jQuery(e.target).data("version");

        controller.find('.install-response-container').show();
        controller.find('.install-version-container').hide();
        active_console = controller.find('.install-response-container .console');
        controller.find("#installModal .loader .message").html(controller.messages['installing']);
        jQuery.get(
            baseurl+'install',
            {'package':package,'version':version}
        )
        .done(function(data) {
            active_console.html(data);
            controller.postInstall(package, version);
            setTimeout(function(){
                controller.find('.install-response-container').hide();
            }, 5000);
            controller.find(".check-package").show()
            controller.find('input[name="check-package"]').val('');
            controller.checkInstalled();
        });
        e.preventDefault();
    },

    postInstall: function(package, version) {
        var controller = this;
        jQuery.get(
            baseurl+'packageInfo',
            {'package':package,'version':version}
        )
        .done(function(data) {
            if(data['type']=='bolt-extension') {
                controller.extensionPostInstall(data);
            }
            if(data['type']=='bolt-theme') {
                controller.themePostInstall(data);
            }
        });
    },

    extensionPostInstall: function(extension) {
        var controller = this;
        controller.find('.extension-postinstall .ext-link').attr("href", extension.source);
        controller.find('.extension-postinstall').show();
    },

    themePostInstall: function(extension) {
        var controller = this;
        controller.find('.theme-postinstall').show();
        controller.find('.theme-postinstall .theme-generator').data("theme",extension['name']);
    },

    generateTheme: function(e) {
        var controller = this;
        var trigger = jQuery(e.target);
        var theme = trigger.data("theme");
        var themename  = controller.find('#theme-name').val();
        jQuery.get(
            baseurl+'generateTheme',
            {'theme':theme,'name':themename}
        )
        .done(function(data) {
            controller.find('.theme-generate-response').html("
"+data+"
").show();
            controller.find('.theme-generation-container').hide();
        });
        e.preventDefault();
    },

    packageReadme: function(e) {

        jQuery.get( jQuery(e.target).data("readme") )
        .done(function(data) {
            bootbox.dialog({
                message: data
            });
        });

        e.preventDefault();
    },

    uninstall: function(e) {
        var controller = this;
        var t = this.find('.installed-container .console').html(controller.messages['removing']);
        t.show();
        active_console = t;
        jQuery.get(
            jQuery(e.target).attr("href")
        )
        .done(function(data) {
            controller.find('.installed-container .console').html(data);
            controller.checkInstalled();
            delay(function(){
                active_console.hide();
            }, 2000);
        });

        e.preventDefault();
    },

    liveSearch: function() {
        var livesearch = this.find('input[name="check-package"]');

        livesearch.on('keyup', function(e){
            var searchVal = jQuery(this).val();
            if(searchVal.length < 3) return;
            delay(function(){
                jQuery.ajax({
                    url: site+"list.json",
                    dataType: 'jsonp',
                    data: {'name': searchVal}
                })
                .success(function(data){
                    if(data['packages'].length <1 ) return;
                    var cont = livesearch.parent().find(".auto-search");
                    cont.html("").show();
                    for(var p in data['packages']) {
                        var t = data['packages'][p];
                        cont.append(""+t.name+"");
                    }
                    livesearch.on('blur', function(){
                       cont.fadeOut();
                    });
                });
            }, 500 );
        });
    },

    prefill: function(e) {
        var target = jQuery(e.target);
        console.log(target.text());
        this.find('input[name="check-package"]').val( target.text());
        target.parent().hide();
    },

    events: {
        change: function(e, t){
            var controller = e.data;

        },

        click: function(e, t){
            var controller = e.data;
            switch(jQuery(e.target).data('action')) {
                case "update-check"     : controller.updateCheck(); break;
                case "update-run"       : controller.updateRun(); break;
                case "update-package"   : controller.updatePackage(e.originalEvent); break;
                case "check-package"    : controller.checkPackage(e.originalEvent); break;
                case "uninstall-package": controller.uninstall(e.originalEvent); break;
                case "install-package"  : controller.install(e.originalEvent); break;
                case "prefill-package"  : controller.prefill(e.originalEvent); break;
                case "install-run"      : controller.installRun(e.originalEvent); break;
                case "generate-theme"   : controller.generateTheme(e.originalEvent); break;
                case "package-readme"   : controller.packageReadme(e.originalEvent); break;
                case "package-config"   : controller.packageConfig(e.originalEvent); break;
            }
        }

    }

});<commit_msg>no need for console output when clicking browse versions<commit_after>// Create a static 'extends' method on the Object class
// This allows us to extend existing classes
// for classical object-oriented inheritance
Object.extend = function(superClass, definition) {
    var subClass = function() {};
    // Our constructor becomes the 'subclass'
    if (definition.constructor !== Object)
        subClass = definition.constructor;
    subClass.prototype = new superClass();
    for (var prop in definition) {
        if (prop != 'constructor')
            subClass.prototype[prop] = definition[prop];
    }
    return subClass;
};

var delay = (function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

var BoltExtender = Object.extend(Object, {

    selector: ".extend-bolt-container",
    messages:  {},
    paths:  {},

    constructor: function(){
        jQuery(this.selector).on("change", this, this.events.change);
        jQuery(this.selector).on("click", this, this.events.click);

        jQuery(document).ajaxStart(function() {
            // show loader on start
            active_interval = setInterval(function(){
                active_console.append(".");
            },1000);
        }).ajaxSuccess(function() {
            clearInterval(active_interval);
        });

        this.checkInstalled();
        this.liveSearch();
        this.installReset();

    },

    find: function(selector) {
        return jQuery(this.selector).find(selector);
    },

    setMessage: function(key, value) {
        this.messages[key]=value;
    },

    setPath: function(key, value) {
        this.paths[key]=value;
    },

    installReset: function() {
        var controller = this;
        jQuery('#installModal').on('hide.bs.modal', function (e) {
            controller.find(".stable-version-container .installed-version-item").html('
'+controller.messages['noStable']+'
');
            controller.find(".dev-version-container .installed-version-item").html('
'+controller.messages['noDev']+'
');
            controller.find('.extension-postinstall').hide();
            controller.find('.install-version-container').hide();
            controller.find("#installModal .loader").show();
        });
    },

    updateCheck: function() {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-list-items");
        active_console = controller.find('.update-output');
        active_console.html(controller.messages['updating']);
        jQuery.get(baseurl+'check', function(data) {
            if(data.updates.length > 0 || data.installs.length >0) {
                for(var e in data.installs) {
                    var ext = data.installs[e];
                    target.append("
"+ext+"	 Install New Package
");
                }
                for(var e in data.updates) {
                    var ext = data.updates[e];
                    target.append("
"+ext+"	 Install Package Update
");
                }
                active_console.hide();
                controller.find('.update-list').show();
            } else {
                active_console.html(controller.messages['updated']);
            }
        });
    },

    updateRun: function() {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-output" );
        active_console = target;
        active_console.html("Running update....");
        jQuery.get(baseurl+'update', function(data) {
            target.html(data);
            setTimeout(function(){
                controller.find('.update-container').hide();
            },7000);
        });
    },

    updatePackage: function(e) {
        var controller = this;
        var t = this.find('.update-output').html(controller.messages['updating']);
        var packageToUpdate = jQuery(e.target).data("package");
        t.show();
        active_console = t;
        jQuery.get(
            baseurl+'update?package='+packageToUpdate
        )
        .success(function(data) {
            controller.find('.update-output').html(data);
            controller.find('.update-list-items tr[data-package="'+packageToUpdate+'"]').remove();
            delay(function(){
                active_console.hide();
            }, 4000);
            if(controller.find('.update-list-items tbody tr').length <1) {
                controller.find('.update-container').hide();
            }
            controller.checkInstalled();
        });

        e.preventDefault();
    },

    installRun: function(e) {
        var controller = this;

        controller.find('.update-container').show();
        var target = controller.find(".update-output" );
        active_console = target;
        active_console.html(controller.messages['installAll']);
        jQuery.get(baseurl+'installAll', function(data) {
            target.html(data);
            delay(function(){
                controller.find('.update-container').hide();
            },7000);
        });
        e.stopPropagation();
        e.preventDefault();
    },

    checkInstalled: function() {
        var controller = this;

        controller.find('.installed-container').each(function(){
            active_console = controller.find(".installed-container .console");
            var target = jQuery(this).find('.installed-list');
            jQuery.get(baseurl+"installed", function(data) {
                target.show();
                if(data.length > 0) {
                    active_console.html(data.length + " installed extension(s).");
                    delay(function(){
                        controller.find(".installed-container .console").hide();
                    },7000);
                    target.find('.installed-list-items').html('');
                    for(var e in data) {
                        ext = data[e];
                        var html = "
" + ext["name"] +
                            "	" + ext["version"] + "	 " + ext["type"] +
                            "	 " + ext["descrip"] + "	 ";

                        if (ext["readmelink"]) {
                            html += " Readme ";
                        }

                        if (ext["config"]) {
                            html += " Config ";
                        }

                        html += " Uninstall" + "
";
                        //console.log(ext);
                        target.find('.installed-list-items').append(html);
                    }
                } else {
                    target.find('.installed-list-items').html("
No Bolt Extensions installed.
");
                    active_console.hide();
                }
            });
        });
    },

    checkPackage: function(e) {
        var controller = this;
        var ext = this.find('input[name="check-package"]').val();
        active_console = false;
        jQuery.get(baseurl+'installInfo?package='+ext, function(data) {

            var devpacks = data['dev'];
            var stablepacks = data['stable'];

            if(devpacks.length > 0) {
              controller.find('.dev-version-container .installed-version-item').html("");
            }

            if(stablepacks.length > 0) {
              controller.find('.stable-version-container .installed-version-item').html("");
            }

            for(var v in devpacks) {
                version = devpacks[v];
                var tpl = '
'+version.name+'	'+version.version+'	';
                tpl = tpl+'
'
                tpl = tpl+' Install This Version

';
                controller.find('.dev-version-container .installed-version-item').append(tpl);
            }
            for(var v in stablepacks) {
                version = stablepacks[v];
                var tpl = '
'+version.name+'	'+version.version+'	';
                tpl = tpl+'
';
                tpl = tpl+' Install This Version

';
                controller.find('.stable-version-container .installed-version-item').append(tpl);
            }

            controller.find(".install-version-container").show();
            controller.find("#installModal .loader").hide();
        });

        e.preventDefault();
    },

    install: function(e) {
        var controller = this;

        var package = jQuery(e.target).data("package");
        var version = jQuery(e.target).data("version");

        controller.find('.install-response-container').show();
        controller.find('.install-version-container').hide();
        active_console = controller.find('.install-response-container .console');
        controller.find("#installModal .loader .message").html(controller.messages['installing']);
        jQuery.get(
            baseurl+'install',
            {'package':package,'version':version}
        )
        .done(function(data) {
            active_console.html(data);
            controller.postInstall(package, version);
            setTimeout(function(){
                controller.find('.install-response-container').hide();
            }, 5000);
            controller.find(".check-package").show()
            controller.find('input[name="check-package"]').val('');
            controller.checkInstalled();
        });
        e.preventDefault();
    },

    postInstall: function(package, version) {
        var controller = this;
        jQuery.get(
            baseurl+'packageInfo',
            {'package':package,'version':version}
        )
        .done(function(data) {
            if(data['type']=='bolt-extension') {
                controller.extensionPostInstall(data);
            }
            if(data['type']=='bolt-theme') {
                controller.themePostInstall(data);
            }
        });
    },

    extensionPostInstall: function(extension) {
        var controller = this;
        controller.find('.extension-postinstall .ext-link').attr("href", extension.source);
        controller.find('.extension-postinstall').show();
    },

    themePostInstall: function(extension) {
        var controller = this;
        controller.find('.theme-postinstall').show();
        controller.find('.theme-postinstall .theme-generator').data("theme",extension['name']);
    },

    generateTheme: function(e) {
        var controller = this;
        var trigger = jQuery(e.target);
        var theme = trigger.data("theme");
        var themename  = controller.find('#theme-name').val();
        jQuery.get(
            baseurl+'generateTheme',
            {'theme':theme,'name':themename}
        )
        .done(function(data) {
            controller.find('.theme-generate-response').html("
"+data+"
").show();
            controller.find('.theme-generation-container').hide();
        });
        e.preventDefault();
    },

    packageReadme: function(e) {

        jQuery.get( jQuery(e.target).data("readme") )
        .done(function(data) {
            bootbox.dialog({
                message: data
            });
        });

        e.preventDefault();
    },

    uninstall: function(e) {
        var controller = this;
        var t = this.find('.installed-container .console').html(controller.messages['removing']);
        t.show();
        active_console = t;
        jQuery.get(
            jQuery(e.target).attr("href")
        )
        .done(function(data) {
            controller.find('.installed-container .console').html(data);
            controller.checkInstalled();
            delay(function(){
                active_console.hide();
            }, 2000);
        });

        e.preventDefault();
    },

    liveSearch: function() {
        var livesearch = this.find('input[name="check-package"]');

        livesearch.on('keyup', function(e){
            var searchVal = jQuery(this).val();
            if(searchVal.length < 3) return;
            delay(function(){
                jQuery.ajax({
                    url: site+"list.json",
                    dataType: 'jsonp',
                    data: {'name': searchVal}
                })
                .success(function(data){
                    if(data['packages'].length <1 ) return;
                    var cont = livesearch.parent().find(".auto-search");
                    cont.html("").show();
                    for(var p in data['packages']) {
                        var t = data['packages'][p];
                        cont.append(""+t.name+"");
                    }
                    livesearch.on('blur', function(){
                       cont.fadeOut();
                    });
                });
            }, 500 );
        });
    },

    prefill: function(e) {
        var target = jQuery(e.target);
        console.log(target.text());
        this.find('input[name="check-package"]').val( target.text());
        target.parent().hide();
    },

    events: {
        change: function(e, t){
            var controller = e.data;

        },

        click: function(e, t){
            var controller = e.data;
            switch(jQuery(e.target).data('action')) {
                case "update-check"     : controller.updateCheck(); break;
                case "update-run"       : controller.updateRun(); break;
                case "update-package"   : controller.updatePackage(e.originalEvent); break;
                case "check-package"    : controller.checkPackage(e.originalEvent); break;
                case "uninstall-package": controller.uninstall(e.originalEvent); break;
                case "install-package"  : controller.install(e.originalEvent); break;
                case "prefill-package"  : controller.prefill(e.originalEvent); break;
                case "install-run"      : controller.installRun(e.originalEvent); break;
                case "generate-theme"   : controller.generateTheme(e.originalEvent); break;
                case "package-readme"   : controller.packageReadme(e.originalEvent); break;
                case "package-config"   : controller.packageConfig(e.originalEvent); break;
            }
        }

    }

});<|endoftext|>


<commit_before>'use strict';

angular.module('IssueTracker.issues', [])
    .factory('issues', ['$http', '$q', 'BASE_URL', 'projects', function IssuesFactory($http, $q, BASE_URL, projects) {
        // Security: logged in.
        function getProjectIssues(projectId) {
            var def = $q.defer();
            projects.getProjectById(projectId).then(function (success) {
                def.resolve(seccess.issues);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        // Security logged In
        function getIssueById(id) {
            var def = $q.defer();
            $http.get(BASE_URL + '/Issues/' + id).then(function (success) {
                def.resolve(success);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        //	Security: Admin, Project lead
        function addIssue(data) {
            var def = $q.defer();
            $http.post(BASE_URL + '/Issues', data).then(function (success) {
                def.resolve(success);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        // Security: Admin, Project lead
        function editIssue(issueId, data) {
            var def = $q.defer();
            $http.put(BASE_URL + '/Issues/' + issueId, data)
                .then(function (success) {
                    def.resolve(success);
                }, function(error) {
                        def.reject(error)
                });
            return def.promise;
        }
        // Security: Login
        function getIssueComments(issueId) {
            var def = $q.defer();
            $http.get(BASE_URL + '/Issues/' + issueId + '/comments').then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        // Security: Logged in user who is either a project leader or has a assigned issue in this project
        function addIssueComment(issueId, data) {
            var def = $q.defer();
            $http.put(BASE_URL + '/Issues/' + issueId + '/comments', data).then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        function getUsersIssues(orderBy, pageSize, pageNumber) {
            var def = $q.defer();
            $http.get(BASE_URL + 'Issues/me?pageSize=' + pageSize + '&pageNumber=' + pageNumber + '&orderBy=' + orderBy)
                .then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        return {
            getProjectIssues: getProjectIssues,
            getIssueById: getIssueById,
            addIssue: addIssue,
            editIssue: editIssue,
            getIssueComments: getIssueComments,
            addIssueComment: addIssueComment
        }
    }]);<commit_msg>Added function for getting all issues of current user.<commit_after>'use strict';

angular.module('IssueTracker.issues', [])
    .factory('issues', ['$http', '$q', 'BASE_URL', 'projects', function IssuesFactory($http, $q, BASE_URL, projects) {
        // Security: logged in.
        function getProjectIssues(projectId) {
            var def = $q.defer();
            projects.getProjectById(projectId).then(function (success) {
                def.resolve(seccess.issues);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        // Security logged In
        function getIssueById(id) {
            var def = $q.defer();
            $http.get(BASE_URL + '/Issues/' + id).then(function (success) {
                def.resolve(success);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        //	Security: Admin, Project lead
        function addIssue(data) {
            var def = $q.defer();
            $http.post(BASE_URL + '/Issues', data).then(function (success) {
                def.resolve(success);
            }, function(error) {
                def.reject(error)
            });
            return def.promise;
        }
        // Security: Admin, Project lead
        function editIssue(issueId, data) {
            var def = $q.defer();
            $http.put(BASE_URL + '/Issues/' + issueId, data)
                .then(function (success) {
                    def.resolve(success);
                }, function(error) {
                        def.reject(error)
                });
            return def.promise;
        }
        // Security: Login
        function getIssueComments(issueId) {
            var def = $q.defer();
            $http.get(BASE_URL + '/Issues/' + issueId + '/comments').then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        // Security: Logged in user who is either a project leader or has a assigned issue in this project
        function addIssueComment(issueId, data) {
            var def = $q.defer();
            $http.put(BASE_URL + '/Issues/' + issueId + '/comments', data).then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        function getUsersIssues(orderBy, pageSize, pageNumber) {
            var def = $q.defer();
            $http.get(BASE_URL + 'Issues/me?pageSize=' + pageSize + '&pageNumber=' + pageNumber + '&orderBy=' + orderBy)
                .then(function (response) {
                def.resolve(response);
            }, function (error) {
                def.reject(error);
            });
            return def.promise;
        }
        return {
            getProjectIssues: getProjectIssues,
            getIssueById: getIssueById,
            addIssue: addIssue,
            editIssue: editIssue,
            getIssueComments: getIssueComments,
            addIssueComment: addIssueComment,
            getUsersIssues: getUsersIssues
        }
    }]);<|endoftext|>


<commit_before>var argscheck = require('cordova/argscheck'),
  utils = require('cordova/utils'),
  common = require('./Common'),
  event = require('./event'),
  Overlay = require('./Overlay');

/*****************************************************************************
 * StreetViewPanorama Class
 *****************************************************************************/
var exec;
var StreetViewPanorama = function(streetViewId, _exec) {
  exec = _exec;
  Overlay.call(this, this, {}, 'StreetViewPanorama', _exec, {
    id: streetViewId
  });

  var self = this;
  self.set("visible", true);
  self.set("gesture_panning", true);
  self.set("gesture_zoom", true);
  self.set("control_navigation", true);
  self.set("control_streetNames", true);

  //-----------------------------------------------
  // Sets event listeners
  //-----------------------------------------------
  self.on("gesture_panning_changed", function() {
      var booleanValue = self.get("gesture_panning");
      exec.call(self, null, self.errorHandler, self.id, 'setPanningGesturesEnabled', [booleanValue]);
  });
  self.on("gesture_zoom_changed", function() {
      var booleanValue = self.get("gesture_zoom");
      exec.call(self, null, self.errorHandler, self.id, 'setZoomGesturesEnabled', [booleanValue]);
  });
  self.on("control_navigation_changed", function() {
      var booleanValue = self.get("control_navigation");
      exec.call(self, null, self.errorHandler, self.id, 'setNavigationEnabled', [booleanValue]);
  });
  self.on("control_streetNames_changed", function() {
      var booleanValue = self.get("control_streetNames");
      exec.call(self, null, self.errorHandler, self.id, 'setStreetNamesEnabled', [booleanValue]);
  });
  self.on("visible_changed", function() {
      var booleanValue = self.get("visible");
      exec.call(self, null, self.errorHandler, self.id, 'setVisible', [booleanValue]);
  });
};

utils.extend(StreetViewPanorama, Overlay);

StreetViewPanorama.prototype.getPluginName = function() {
  return this.map.getId() + "-streetview";
};

StreetViewPanorama.prototype.getHashCode = function() {
  return this.hashCode;
};

StreetViewPanorama.prototype.getId = function() {
  return this.id;
};
StreetViewPanorama.prototype.getPanorama = function(meta, div, options) {
  var self = this,
    args = [meta];
  options = options || {};

  //self.set("clickable", options.clickable === false ? false : true);
  self.set("visible", options.visible === false ? false : true, true);
  args.push(options);

  // Initial camera options
  if ("camera" in options) {
    self.set("camera", options.camera, true);
    if ("zoom" in options.camera) {
      self.set("camera_zoom", options.camera.zoom, true);
    }
    if ("bearing" in options.camera) {
      self.set("camera_bearing", options.camera.bearing, true);
    }
    if ("tilt" in options.camera) {
      self.set("camera_tilt", options.camera.tilt, true);
    }
    if ("target" in options.camera) {
      self.set("position", options.camera.target, true);
    }
  }

  // Gesture options
  options.gestures = options.gestures || {};
  options.gestures.panning = common.defaultTrueOption(options.gestures.panning);
  options.gestures.zoom = common.defaultTrueOption(options.gestures.zoom);
  self.set("gesture_panning", options.gestures.panning, true);
  self.set("gesture_zoom", options.gestures.zoom, true);

  // Controls options
  options.controls = options.controls || {};
  options.controls.panning = common.defaultTrueOption(options.controls.navigation);
  options.controls.zoom = common.defaultTrueOption(options.controls.streetNames);
  self.set("control_navigation", options.controls.navigation, true);
  self.set("control_streetNames", options.controls.streetNames, true);

  // Gets the map div size.
  // The plugin needs to consider the viewport zoom ratio
  // for the case window.innerHTML > body.offsetWidth.
  self.set("div", div);
  var elemId = common.getPluginDomId(div);
  args.push(elemId);

  exec.call({
    _isReady: true
  }, function() {

    //------------------------------------------------------------------------
    // Clear background colors of map div parents after the map is created
    //------------------------------------------------------------------------

    var positionCSS;
    for (var i = 0; i < div.children.length; i++) {
      positionCSS = common.getStyle(div.children[i], "position");
      if (positionCSS === "static") {
        div.children[i].style.position = "relative";
      }
    }
    //div.insertBefore(self._layers.info, div.firstChild);

    while (div.parentNode) {
      div.style.backgroundColor = 'rgba(0,0,0,0) !important';

      // prevent multiple readding the class
      if (div.classList && !div.classList.contains('_gmaps_cdv_')) {
        div.classList.add('_gmaps_cdv_');
      } else if (div.className && div.className.indexOf('_gmaps_cdv_') === -1) {
        div.className = div.className + ' _gmaps_cdv_';
      }

      div = div.parentNode;
    }
    cordova.fireDocumentEvent("plugin_touch", {
      force: true
    });
    self._privateInitialize();
    delete self._privateInitialize;

    self.trigger(event.PANORAMA_READY, self);
  }, self.errorHandler, 'CordovaGoogleMaps', 'getPanorama', args, {
    sync: true
  });
};

StreetViewPanorama.prototype.setVisible = function(isVisible) {
  this.set("visible", common.parseBoolean(isVisible));
  return this;
};

StreetViewPanorama.prototype.getVisible = function() {
  return this.get("visible");
};

StreetViewPanorama.prototype.getDiv = function() {
  return this.get("div");
};
StreetViewPanorama.prototype.getMap = function() {
  // stub
};

StreetViewPanorama.prototype.setPanningGesturesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('gesture_panning', boolValue);
  return this;
};
StreetViewPanorama.prototype.getPanningGesturesEnabled = function () {
  return this.get('gesture_panning');
};
StreetViewPanorama.prototype.setZoomGesturesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('gesture_zoom', boolValue);
  return this;
};
StreetViewPanorama.prototype.getZoomGesturesEnabled = function () {
  return this.get('gesture_zoom');
};
StreetViewPanorama.prototype.setNavigationEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('control_navigation', boolValue);
  return this;
};
StreetViewPanorama.prototype.getNavigationEnabled = function () {
  return this.get('control_navigation');
};
StreetViewPanorama.prototype.setStreetNamesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('control_streetNames', boolValue);
  return this;
};
StreetViewPanorama.prototype.getStreetNamesEnabled = function () {
  return this.get('control_streetNames');
};
StreetViewPanorama.prototype.getLinks = function () {
  return this.get('links');
};
StreetViewPanorama.prototype.getLocation = function () {
  return this.get('location');
};
StreetViewPanorama.prototype.getPano = function () {
  return this.get('pano');
};
StreetViewPanorama.prototype.getPosition = function () {
  return this.get('position');
};

StreetViewPanorama.prototype.moveCamera = function(cameraPosition, callback) {
  var self = this;
  cameraPosition = cameraPosition || {};
  cameraPosition.duration = 0;
  self.animateCamera.call(self, cameraPosition, callback);
  return this;
};

StreetViewPanorama.prototype.animateCamera = function(cameraPosition, callback) {
  var self = this;
  cameraPosition = cameraPosition || {};
  if (typeof cameraPosition.target === "object") {
    self.set("position", cameraPosition.target);
  }
  if ("zoom" in cameraPosition) {
    self.set("camera_zoom", cameraPosition.zoom);
  }
  if ("bearing" in cameraPosition) {
    self.set("camera_bearing", cameraPosition.bearing);
  }
  if ("tilt" in cameraPosition) {
    self.set("camera_tilt", cameraPosition.tilt);
  }
  self.exec.call(self, function() {
    if (typeof callback === "function") {
      callback.call(self);
    }
  }, self.errorHandler, self.id, 'moveCamera', [cameraPosition], {
    sync: true
  });
  return this;
};

StreetViewPanorama.prototype.remove = function(callback) {
  var self = this;
  self.exec.call(this, function() {
    if (typeof callback === "function") {
      callback.call(self);
    }
  }, self.errorHandler, 'CordovaGoogleMaps', 'removeMap', [self.id], {
    sync: true,
    remove: true
  });
  self.trigger("remove");
};
StreetViewPanorama.prototype._onPanoramaCameraChange = function(eventName, cameraPosition) {
  var self = this;
  self.set('camera', Object.assign(self.get("camera") || {}, cameraPosition));
  self.set('camera_zoom', cameraPosition.zoom);
  self.set('camera_bearing', cameraPosition.bearing);
  self.set('camera_tilt', cameraPosition.viewAngle || cameraPosition.tilt);
  self.set('links', cameraPosition.links || []);
  if (self._isReady) {
    self._onPanoramaEvent(eventName, cameraPosition);
  }
};

StreetViewPanorama.prototype._onPanoramaLocationChange = function(eventName, panoramaLocation) {
  var self = this;
  self.set('location', panoramaLocation);
  self.set('pano', panoramaLocation.panoId);
  self.set('position', panoramaLocation.latLng);
  if (self._isReady) {
    self._onPanoramaEvent(eventName, panoramaLocation);
  }
};
StreetViewPanorama.prototype._onPanoramaEvent = function(eventName) {
  var self = this;
  if (self._isReady) {
    var args = Array.prototype.slice.call(arguments, 0);
    args.push(self);
    self.trigger.apply(self, args);
  }
};

module.exports = StreetViewPanorama;
<commit_msg>Fix: typo<commit_after>var argscheck = require('cordova/argscheck'),
  utils = require('cordova/utils'),
  common = require('./Common'),
  event = require('./event'),
  Overlay = require('./Overlay');

/*****************************************************************************
 * StreetViewPanorama Class
 *****************************************************************************/
var exec;
var StreetViewPanorama = function(streetViewId, _exec) {
  exec = _exec;
  Overlay.call(this, this, {}, 'StreetViewPanorama', _exec, {
    id: streetViewId
  });

  var self = this;
  self.set("visible", true);
  self.set("gesture_panning", true);
  self.set("gesture_zoom", true);
  self.set("control_navigation", true);
  self.set("control_streetNames", true);

  //-----------------------------------------------
  // Sets event listeners
  //-----------------------------------------------
  self.on("gesture_panning_changed", function() {
      var booleanValue = self.get("gesture_panning");
      exec.call(self, null, self.errorHandler, self.id, 'setPanningGesturesEnabled', [booleanValue]);
  });
  self.on("gesture_zoom_changed", function() {
      var booleanValue = self.get("gesture_zoom");
      exec.call(self, null, self.errorHandler, self.id, 'setZoomGesturesEnabled', [booleanValue]);
  });
  self.on("control_navigation_changed", function() {
      var booleanValue = self.get("control_navigation");
      exec.call(self, null, self.errorHandler, self.id, 'setNavigationEnabled', [booleanValue]);
  });
  self.on("control_streetNames_changed", function() {
      var booleanValue = self.get("control_streetNames");
      exec.call(self, null, self.errorHandler, self.id, 'setStreetNamesEnabled', [booleanValue]);
  });
  self.on("visible_changed", function() {
      var booleanValue = self.get("visible");
      exec.call(self, null, self.errorHandler, self.id, 'setVisible', [booleanValue]);
  });
};

utils.extend(StreetViewPanorama, Overlay);

StreetViewPanorama.prototype.getPluginName = function() {
  return this.map.getId() + "-streetview";
};

StreetViewPanorama.prototype.getHashCode = function() {
  return this.hashCode;
};

StreetViewPanorama.prototype.getId = function() {
  return this.id;
};
StreetViewPanorama.prototype.getPanorama = function(meta, div, options) {
  var self = this,
    args = [meta];
  options = options || {};

  //self.set("clickable", options.clickable === false ? false : true);
  self.set("visible", options.visible === false ? false : true, true);
  args.push(options);

  // Initial camera options
  if ("camera" in options) {
    self.set("camera", options.camera, true);
    if ("zoom" in options.camera) {
      self.set("camera_zoom", options.camera.zoom, true);
    }
    if ("bearing" in options.camera) {
      self.set("camera_bearing", options.camera.bearing, true);
    }
    if ("tilt" in options.camera) {
      self.set("camera_tilt", options.camera.tilt, true);
    }
    if ("target" in options.camera) {
      self.set("position", options.camera.target, true);
    }
  }

  // Gesture options
  options.gestures = options.gestures || {};
  options.gestures.panning = common.defaultTrueOption(options.gestures.panning);
  options.gestures.zoom = common.defaultTrueOption(options.gestures.zoom);
  self.set("gesture_panning", options.gestures.panning, true);
  self.set("gesture_zoom", options.gestures.zoom, true);

  // Controls options
  options.controls = options.controls || {};
  options.controls.navigation = common.defaultTrueOption(options.controls.navigation);
  options.controls.streetNames = common.defaultTrueOption(options.controls.streetNames);
  self.set("control_navigation", options.controls.navigation, true);
  self.set("control_streetNames", options.controls.streetNames, true);

  // Gets the map div size.
  // The plugin needs to consider the viewport zoom ratio
  // for the case window.innerHTML > body.offsetWidth.
  self.set("div", div);
  var elemId = common.getPluginDomId(div);
  args.push(elemId);

  exec.call({
    _isReady: true
  }, function() {

    //------------------------------------------------------------------------
    // Clear background colors of map div parents after the map is created
    //------------------------------------------------------------------------

    var positionCSS;
    for (var i = 0; i < div.children.length; i++) {
      positionCSS = common.getStyle(div.children[i], "position");
      if (positionCSS === "static") {
        div.children[i].style.position = "relative";
      }
    }
    //div.insertBefore(self._layers.info, div.firstChild);

    while (div.parentNode) {
      div.style.backgroundColor = 'rgba(0,0,0,0) !important';

      // prevent multiple readding the class
      if (div.classList && !div.classList.contains('_gmaps_cdv_')) {
        div.classList.add('_gmaps_cdv_');
      } else if (div.className && div.className.indexOf('_gmaps_cdv_') === -1) {
        div.className = div.className + ' _gmaps_cdv_';
      }

      div = div.parentNode;
    }
    cordova.fireDocumentEvent("plugin_touch", {
      force: true
    });
    self._privateInitialize();
    delete self._privateInitialize;

    self.trigger(event.PANORAMA_READY, self);
  }, self.errorHandler, 'CordovaGoogleMaps', 'getPanorama', args, {
    sync: true
  });
};

StreetViewPanorama.prototype.setVisible = function(isVisible) {
  this.set("visible", common.parseBoolean(isVisible));
  return this;
};

StreetViewPanorama.prototype.getVisible = function() {
  return this.get("visible");
};

StreetViewPanorama.prototype.getDiv = function() {
  return this.get("div");
};
StreetViewPanorama.prototype.getMap = function() {
  // stub
};

StreetViewPanorama.prototype.setPanningGesturesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('gesture_panning', boolValue);
  return this;
};
StreetViewPanorama.prototype.getPanningGesturesEnabled = function () {
  return this.get('gesture_panning');
};
StreetViewPanorama.prototype.setZoomGesturesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('gesture_zoom', boolValue);
  return this;
};
StreetViewPanorama.prototype.getZoomGesturesEnabled = function () {
  return this.get('gesture_zoom');
};
StreetViewPanorama.prototype.setNavigationEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('control_navigation', boolValue);
  return this;
};
StreetViewPanorama.prototype.getNavigationEnabled = function () {
  return this.get('control_navigation');
};
StreetViewPanorama.prototype.setStreetNamesEnabled = function (boolValue) {
  boolValue = common.parseBoolean(boolValue);
  this.set('control_streetNames', boolValue);
  return this;
};
StreetViewPanorama.prototype.getStreetNamesEnabled = function () {
  return this.get('control_streetNames');
};
StreetViewPanorama.prototype.getLinks = function () {
  return this.get('links');
};
StreetViewPanorama.prototype.getLocation = function () {
  return this.get('location');
};
StreetViewPanorama.prototype.getPano = function () {
  return this.get('pano');
};
StreetViewPanorama.prototype.getPosition = function () {
  return this.get('position');
};

StreetViewPanorama.prototype.moveCamera = function(cameraPosition, callback) {
  var self = this;
  cameraPosition = cameraPosition || {};
  cameraPosition.duration = 0;
  self.animateCamera.call(self, cameraPosition, callback);
  return this;
};

StreetViewPanorama.prototype.animateCamera = function(cameraPosition, callback) {
  var self = this;
  cameraPosition = cameraPosition || {};
  if (typeof cameraPosition.target === "object") {
    self.set("position", cameraPosition.target);
  }
  if ("zoom" in cameraPosition) {
    self.set("camera_zoom", cameraPosition.zoom);
  }
  if ("bearing" in cameraPosition) {
    self.set("camera_bearing", cameraPosition.bearing);
  }
  if ("tilt" in cameraPosition) {
    self.set("camera_tilt", cameraPosition.tilt);
  }
  self.exec.call(self, function() {
    if (typeof callback === "function") {
      callback.call(self);
    }
  }, self.errorHandler, self.id, 'moveCamera', [cameraPosition], {
    sync: true
  });
  return this;
};

StreetViewPanorama.prototype.remove = function(callback) {
  var self = this;
  self.exec.call(this, function() {
    if (typeof callback === "function") {
      callback.call(self);
    }
  }, self.errorHandler, 'CordovaGoogleMaps', 'removeMap', [self.id], {
    sync: true,
    remove: true
  });
  self.trigger("remove");
};
StreetViewPanorama.prototype._onPanoramaCameraChange = function(eventName, cameraPosition) {
  var self = this;
  self.set('camera', Object.assign(self.get("camera") || {}, cameraPosition));
  self.set('camera_zoom', cameraPosition.zoom);
  self.set('camera_bearing', cameraPosition.bearing);
  self.set('camera_tilt', cameraPosition.viewAngle || cameraPosition.tilt);
  self.set('links', cameraPosition.links || []);
  if (self._isReady) {
    self._onPanoramaEvent(eventName, cameraPosition);
  }
};

StreetViewPanorama.prototype._onPanoramaLocationChange = function(eventName, panoramaLocation) {
  var self = this;
  self.set('location', panoramaLocation);
  self.set('pano', panoramaLocation.panoId);
  self.set('position', panoramaLocation.latLng);
  if (self._isReady) {
    self._onPanoramaEvent(eventName, panoramaLocation);
  }
};
StreetViewPanorama.prototype._onPanoramaEvent = function(eventName) {
  var self = this;
  if (self._isReady) {
    var args = Array.prototype.slice.call(arguments, 0);
    args.push(self);
    self.trigger.apply(self, args);
  }
};

module.exports = StreetViewPanorama;
<|endoftext|>


<commit_before>/**
 * Configuration
 */
angular.module('ic')

    /**
    * Config
    */
    .config(['$routeProvider', 'APIConfigProvider', function ($routeProvider, APIConfigProvider) {
        APIConfigProvider.prefix = 'http://192.168.0.15:8080';

        $routeProvider.

            // main page is the search form
            when('/search', {
                templateUrl: 'js/pages/search/search.html',
                controller: 'SearchCtrl'
            }).

            // meetup detail page
            when('/meetups/:meetupId', {
                templateUrl: 'js/pages/meetup-detail/meetup-detail.html',
                controller: 'MeetupDetailCtrl'
            }).

            // default page
            otherwise({
                redirectTo: '/search'
            });
    }]);<commit_msg>Use local backend server<commit_after>/**
 * Configuration
 */
angular.module('ic')

    /**
    * Config
    */
    .config(['$routeProvider', 'APIConfigProvider', function ($routeProvider, APIConfigProvider) {
        APIConfigProvider.prefix = 'http://localhost:5000';

        $routeProvider.

            // main page is the search form
            when('/search', {
                templateUrl: 'js/pages/search/search.html',
                controller: 'SearchCtrl'
            }).

            // meetup detail page
            when('/meetups/:meetupId', {
                templateUrl: 'js/pages/meetup-detail/meetup-detail.html',
                controller: 'MeetupDetailCtrl'
            }).

            // default page
            otherwise({
                redirectTo: '/search'
            });
    }]);<|endoftext|>


<commit_before>// Controller
wheatherApp.controller('mainController', ['$scope', 'cityService', function($scope, cityService){
    $scope.city = cityService.city;
    // Value can change
    $scope.$watch('city', function(){
        cityService.city = $scope.city;
    });
    $scope.Adress = "American University,4400 Massachusetts Ave NW,Washington, DC 20016";
    $scope.Area = {
                    Name: "Melbourne",
                    Latitude: -37.8140000,
                    Longitude: 144.9633200
                  };
    $scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 };
}]);

wheatherApp.controller('forecastController', ['$scope', '$resource', '$routeParams', 'cityService', 'usSpinnerService', function($scope, $resource, $routeParams, cityService, usSpinnerService){
    $scope.city = cityService.city;
    $scope.days = $routeParams.days || '1';
    usSpinnerService.spin('spinner');

    $scope.wheatherAPI =
        $resource("//api.openweathermap.org/data/2.5/forecast/daily",
            {
                Callback: "JSON_CALLBACK"
            },
            {
                get: { method: "JSONP"}
            }
        );

    $scope.wheatherAPI.get(
        {
            q: $scope.city,
            cnt: $scope.days
        }
    ).$promise.then(function(data) {
        $scope.wheatherAPIResult = data;
        usSpinnerService.stop('spinner');
    }, function(reason) {
        console.log('Failed: ' + reason);
        usSpinnerService.stop('spinner');
    });

    $scope.convertToCelsius = function(degK){
        return Math.round(degK - 273.15) + "C";
    }

    $scope.convertToFahrenheit = function(degK){
        return Math.round((1.8 * (degK - 273)) + 32) + "F";
    }

    $scope.convertToDate = function(date){
        return new Date(date * 1000);
    }
}]);<commit_msg>fixing https issue<commit_after>// Controller
wheatherApp.controller('mainController', ['$scope', 'cityService', function($scope, cityService){
    $scope.city = cityService.city;
    // Value can change
    $scope.$watch('city', function(){
        cityService.city = $scope.city;
    });
    $scope.Adress = "American University,4400 Massachusetts Ave NW,Washington, DC 20016";
    $scope.Area = {
                    Name: "Melbourne",
                    Latitude: -37.8140000,
                    Longitude: 144.9633200
                  };
    $scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 };
}]);

wheatherApp.controller('forecastController', ['$scope', '$resource', '$routeParams', 'cityService', 'usSpinnerService', function($scope, $resource, $routeParams, cityService, usSpinnerService){
    $scope.city = cityService.city;
    $scope.days = $routeParams.days || '1';
    usSpinnerService.spin('spinner');

    $scope.wheatherAPI =
        $resource("https://api.openweathermap.org/data/2.5/forecast/daily",
            {
                Callback: "JSON_CALLBACK"
            },
            {
                get: { method: "JSONP"}
            }
        );

    $scope.wheatherAPI.get(
        {
            q: $scope.city,
            cnt: $scope.days
        }
    ).$promise.then(function(data) {
        $scope.wheatherAPIResult = data;
        usSpinnerService.stop('spinner');
    }, function(reason) {
        console.log('Failed: ' + reason);
        usSpinnerService.stop('spinner');
    });

    $scope.convertToCelsius = function(degK){
        return Math.round(degK - 273.15) + "C";
    }

    $scope.convertToFahrenheit = function(degK){
        return Math.round((1.8 * (degK - 273)) + 32) + "F";
    }

    $scope.convertToDate = function(date){
        return new Date(date * 1000);
    }
}]);<|endoftext|>


<commit_before>/*
 * Height fix for pages with .profile-info box
 */
function profileInfoHeightFix() {
  var pro_h = $('.profile-info').height()+210; //add 210 for the profile pic
  var main_h = $('#page .page-wrapper').height();

  if(pro_h > main_h){
    $('#page .page-wrapper').css({'min-height':pro_h});
  }
}

// Show a tab and hide the others. Load content from remote source if needed.
function activateSimpleTab( $heading_element ) {

  // Check that we have something to work with
  if ( ! $heading_element.size() ) return false;

  var tab_content_id = $heading_element.attr('rel');
  var $tab_content = $(tab_content_id);

  // If this tab is already open don't open it again
  if ( $tab_content.hasClass('open') )
    return true;

  // hide any currently active tabs
  $('#tab-nav ul li.active').removeClass('active');
  $('.tab.open').removeClass('open');
  $('.tab').not('.open').hide();

  // Show and activate the new tab
  $heading_element.addClass('active');
  $tab_content.addClass('open').show();

  // load content using ajax if the div has an data-tab-content-source-url
  // TODO: use a cleaner way to specify this - probably best to have a global object and tell it that certain tabs have special opening behaviour
  var content_url = $tab_content.attr('data-tab-content-source-url');
  if ( content_url ) {
      $tab_content.load(content_url);
  }
}

//generic re-usable hide or show with class states
//todo: add states to trigger elem if provided
function hideShow(elem, trig) {
  elem.toggleClass(function() {
    if ($(this).is('.open')) {
      $(this).hide().removeClass('open');
      trig.removeClass('active');
      return 'closed';
    } else {
      $(this).show().removeClass('closed');
      trig.addClass('active');
      return 'open';
    }
  });
}

$(function(){
  /*
   * auto complete
   */
    $('input.search-autocomplete-name')
    .autocomplete({
        source: "/search/autocomplete/",
        minLength: 2,
        select: function(event, ui) {
            if (ui.item) return window.location = ui.item.url;
        }
    });

    // hide/show home intro
    $('.home-read-more').on('click', function(e){
      e.preventDefault();
      hideShow($('#home-intro span.details'), $(this));
      if($('.home-read-more.active').length !== 0){
        $(this).text('less');
      }else{
        $(this).text('more');
      }
    });

    // auto-advance cycles through featured MPs; it also immediately replaces the
    // featured MP in the page (since we assume that has been frozen by caching)
    var auto_advance_enabled = false;
    var auto_advance_delay = 12000;

    function transitionDiv(height) {
      return '

loading...

';
    }

    // important to delegate this (with on()) because the contents change each auto-advance
    $('#home-featured-person').on("click", '.feature-nav > a',
        function(e, is_auto_advancing){
          e.preventDefault();
          if (! is_auto_advancing) { // user clicked
            auto_advance_enabled = false;
          }
          var m = $(this).attr('href').match(/(before|after)=([-\w]+)$/);
          if (m.length==3) { // wee sanity check: found direction [1] and slug [2]
            // fix the container height to stop content below jumping up when contents fadeOut
            $('#home-featured-person').css("height", $('#home-featured-person').height() + "px");
            $('.featured-person', '#home-featured-person').fadeOut('fast',
              function(){
                 $('#home-featured-person').html(transitionDiv())
                    .load(
                      "person/featured/" + m[1] + '/' + m[2],
                      function() {
                        $('#home-featured-person').css("height","auto");
                      }
                    );
              })
          }
        }
    );

    if (auto_advance_enabled) {
      $('#home-featured-person').html(transitionDiv()).load(
          'person/featured/' + Math.floor(Math.random()*900)
      );
      function auto_advance(){
        if (auto_advance_enabled){
          $('a.feature-next', '#home-featured-person').trigger("click", true);
          timer = window.setTimeout(auto_advance, auto_advance_delay);
        }
      }
      var timer = window.setTimeout(auto_advance, auto_advance_delay);
    }

    /*
     * enable dialog based feedback links
     */
      $('a.feedback_link')
        .on(
            'click',
            function(event) {
                // Note - we could bail out here if the window is too small, as
                // we'd be on a mobile and it might be better just to send them to
                // the feedback page. Not done as this js should only be loaded on
                // a desktop.

                // don't follow the link to the feedback page.
                event.preventDefault();

                // create a div to use in the dialog
                var dialog_div = $('
Loading...
');

                // Load the initial content for the dialog
                dialog_div.load( event.target.href + ' #ajax_dialog_subcontent' );

                // Form subission should be done using ajax, and only the ajax_dialog_subcontent should be shown.
                var handle_form_submission = function( form_submit_event ) {
                    form_submit_event.preventDefault();
                    var form = $(form_submit_event.target);
                    form.ajaxSubmit({
                        success: function( responseText ) {
                            dialog_div.html( $(responseText).find('#ajax_dialog_subcontent') );
                        }
                    });
                };

                // catch all form submissions and do them using ajax
                dialog_div.on( 'submit', 'form', handle_form_submission );

                // Show the dialog
                dialog_div.dialog({
                  modal: true,
                  minHeight: 320,
                  width: 500,
                  title: 'Leave Feedback'
                });

            }
        );

  /*
   * simple tabs
   */

  // build the nav from the relavant links dotted around
  var $tabnavs = $('h2.tab-nav');
  $tabnavs.hide();
  $('.tab-wrapper').before('

');
  $tabnavs.each(function(){
    var rel = $(this).attr('rel');
    var txt = $(this).text();
    var href = $('a', this).attr('href');
    var aClass  = $(this).hasClass('tab-static-link')? 'class="tab-static-link"':'';
    var liClass = $(this).hasClass('tab-active')? 'tab-active':'';
    var newElem = '
'+txt+'
';
    $('#tab-nav ul').append(newElem);
  }).remove();

  // store the matched element from the hash here:
  // first look to see if it's already been marked server-side (tab-active)
  var matched_element = $('li.tab-active').first();

  // If not already active, if there is a hash try to load from that
  if(! matched_element.length && window.location.hash !== '') {
    var hash = window.location.hash;
    matched_element = $('li[rel='+hash+']');
  }

  // If there was no hash, or it didn't match, use the first one
  if ( ! matched_element.length ) {
    matched_element = $('li.tab-nav-heading').first();
  }

  // activate the tab
  activateSimpleTab(matched_element);
  profileInfoHeightFix();

  //for clicks
  $("#tab-nav ul li a").not(".tab-static-link").click(function(e){
    e.preventDefault();
    window.location.hash = $(this).parent('li').attr('rel');
    activateSimpleTab($(this).parent('li'));
    profileInfoHeightFix();
  });

  // $(".tab-static-link").click(function(e){
  //   var hash = $(this).attr('rel');
  //   window.location.hash = hash;
  //   e.preventDefault();
  //   activateSimpleTab($(this));
  //   $("#tab-nav ul li[rel='"+hash+"']").addClass('active');
  // });

  /*
   * scorecard
   */
  // prep
  $('div.details').hide();

  // hide/show details
  $('ul.scorecard article.has-details').live('click', function(){
    hideShow($('div.details', $(this)), $(this));
  });

  /*
   * Comments: hover and show tools
   */
  $('.comments li').hover(function() {
    $(this).addClass('hovered');
  },
  function() {
    $(this).removeClass('hovered');
  });

  /*
   * Login box
   */
  var login_target = $('#site-user-tools .login a').attr('href');

  $('#site-user-tools').after('
Loading...
');

  $('li.login').on('click', function(event) {
    event.preventDefault();
    $('#login-box').load(login_target + ' #login');
    hideShow($('#login-box'), $(this));
  });

  /*
   * Main nav hover
   */
  $('#main-menu ul > li').on('mouseover', function(){
    if($(this).children('ul').length === 1){
      // alert('oh yeah');
      $(this).addClass('active');
    }
  }).on('mouseout', function(){
    $(this).removeClass('active');
  });

  /* carry search terms across when switching between search pages */
  $("#search-hansard-instead").click(function(e){
    e.preventDefault();
    location.href="/search/hansard?q=" + escape($('#core-search,#id_q,#loc').first().val());
  });
  $("#search-core-instead").click(function(e){
    e.preventDefault();
    location.href="/search?q=" + escape($('#id_q,#loc').first().val());
  });
});<commit_msg>tidying auto_advance featured person, small changes<commit_after>/*
 * Height fix for pages with .profile-info box
 */
function profileInfoHeightFix() {
  var pro_h = $('.profile-info').height()+210; //add 210 for the profile pic
  var main_h = $('#page .page-wrapper').height();

  if(pro_h > main_h){
    $('#page .page-wrapper').css({'min-height':pro_h});
  }
}

// Show a tab and hide the others. Load content from remote source if needed.
function activateSimpleTab( $heading_element ) {

  // Check that we have something to work with
  if ( ! $heading_element.size() ) return false;

  var tab_content_id = $heading_element.attr('rel');
  var $tab_content = $(tab_content_id);

  // If this tab is already open don't open it again
  if ( $tab_content.hasClass('open') )
    return true;

  // hide any currently active tabs
  $('#tab-nav ul li.active').removeClass('active');
  $('.tab.open').removeClass('open');
  $('.tab').not('.open').hide();

  // Show and activate the new tab
  $heading_element.addClass('active');
  $tab_content.addClass('open').show();

  // load content using ajax if the div has an data-tab-content-source-url
  // TODO: use a cleaner way to specify this - probably best to have a global object and tell it that certain tabs have special opening behaviour
  var content_url = $tab_content.attr('data-tab-content-source-url');
  if ( content_url ) {
      $tab_content.load(content_url);
  }
}

//generic re-usable hide or show with class states
//todo: add states to trigger elem if provided
function hideShow(elem, trig) {
  elem.toggleClass(function() {
    if ($(this).is('.open')) {
      $(this).hide().removeClass('open');
      trig.removeClass('active');
      return 'closed';
    } else {
      $(this).show().removeClass('closed');
      trig.addClass('active');
      return 'open';
    }
  });
}

$(function(){
  /*
   * auto complete
   */
    $('input.search-autocomplete-name')
    .autocomplete({
        source: "/search/autocomplete/",
        minLength: 2,
        select: function(event, ui) {
            if (ui.item) return window.location = ui.item.url;
        }
    });

    // hide/show home intro
    $('.home-read-more').on('click', function(e){
      e.preventDefault();
      hideShow($('#home-intro span.details'), $(this));
      if($('.home-read-more.active').length !== 0){
        $(this).text('less');
      }else{
        $(this).text('more');
      }
    });

    // auto-advance cycles through featured MPs; it also immediately replaces the
    // featured MP in the page (since we assume that has been frozen by caching)
    var auto_advance_enabled = false;
    var auto_advance_delay = 12000; // milliseconds
    var auto_advance_timeout = false;

    function transitionDiv(height) {
      return '

loading...

';
    }

    // important to delegate this (with on()) because the contents change each auto-advance
    $('#home-featured-person').on("click", '.feature-nav > a',
        function(e, is_auto_advancing){
          e.preventDefault();
          if (! is_auto_advancing) { // user clicked
            auto_advance_enabled = false;
            if (auto_advance_timeout) {
              clearTimeout(auto_advance_timeout);
            }
          }
          var m = $(this).attr('href').match(/(before|after)=([-\w]+)$/);
          if (m.length==3) { // wee sanity check: found direction [1] and slug [2]
            // fix the container height to stop content below jumping up when contents fadeOut
            $('#home-featured-person').css("height", $('#home-featured-person').height() + "px");
            $('.featured-person', '#home-featured-person').fadeOut('fast',
              function(){
                 $('#home-featured-person').html(transitionDiv())
                    .load(
                      "person/featured/" + m[1] + '/' + m[2],
                      function() {
                        $('#home-featured-person').css("height","auto");
                      }
                    );
              })
          }
        }
    );

    if (auto_advance_enabled) {
      $('#home-featured-person').html(transitionDiv()).load(
          'person/featured/' + Math.floor(Math.random()*100) // some random index of featured person
      );
      function auto_advance(){
        if (auto_advance_enabled){
          $('a.feature-next', '#home-featured-person').trigger("click", true);
          auto_advance_timeout = window.setTimeout(auto_advance, auto_advance_delay);
        }
      }
      auto_advance_timeout = window.setTimeout(auto_advance, auto_advance_delay);
    }

    /*
     * enable dialog based feedback links
     */
      $('a.feedback_link')
        .on(
            'click',
            function(event) {
                // Note - we could bail out here if the window is too small, as
                // we'd be on a mobile and it might be better just to send them to
                // the feedback page. Not done as this js should only be loaded on
                // a desktop.

                // don't follow the link to the feedback page.
                event.preventDefault();

                // create a div to use in the dialog
                var dialog_div = $('
Loading...
');

                // Load the initial content for the dialog
                dialog_div.load( event.target.href + ' #ajax_dialog_subcontent' );

                // Form subission should be done using ajax, and only the ajax_dialog_subcontent should be shown.
                var handle_form_submission = function( form_submit_event ) {
                    form_submit_event.preventDefault();
                    var form = $(form_submit_event.target);
                    form.ajaxSubmit({
                        success: function( responseText ) {
                            dialog_div.html( $(responseText).find('#ajax_dialog_subcontent') );
                        }
                    });
                };

                // catch all form submissions and do them using ajax
                dialog_div.on( 'submit', 'form', handle_form_submission );

                // Show the dialog
                dialog_div.dialog({
                  modal: true,
                  minHeight: 320,
                  width: 500,
                  title: 'Leave Feedback'
                });

            }
        );

  /*
   * simple tabs
   */

  // build the nav from the relavant links dotted around
  var $tabnavs = $('h2.tab-nav');
  $tabnavs.hide();
  $('.tab-wrapper').before('

');
  $tabnavs.each(function(){
    var rel = $(this).attr('rel');
    var txt = $(this).text();
    var href = $('a', this).attr('href');
    var aClass  = $(this).hasClass('tab-static-link')? 'class="tab-static-link"':'';
    var liClass = $(this).hasClass('tab-active')? 'tab-active':'';
    var newElem = '
'+txt+'
';
    $('#tab-nav ul').append(newElem);
  }).remove();

  // store the matched element from the hash here:
  // first look to see if it's already been marked server-side (tab-active)
  var matched_element = $('li.tab-active').first();

  // If not already active, if there is a hash try to load from that
  if(! matched_element.length && window.location.hash !== '') {
    var hash = window.location.hash;
    matched_element = $('li[rel='+hash+']');
  }

  // If there was no hash, or it didn't match, use the first one
  if ( ! matched_element.length ) {
    matched_element = $('li.tab-nav-heading').first();
  }

  // activate the tab
  activateSimpleTab(matched_element);
  profileInfoHeightFix();

  //for clicks
  $("#tab-nav ul li a").not(".tab-static-link").click(function(e){
    e.preventDefault();
    window.location.hash = $(this).parent('li').attr('rel');
    activateSimpleTab($(this).parent('li'));
    profileInfoHeightFix();
  });

  // $(".tab-static-link").click(function(e){
  //   var hash = $(this).attr('rel');
  //   window.location.hash = hash;
  //   e.preventDefault();
  //   activateSimpleTab($(this));
  //   $("#tab-nav ul li[rel='"+hash+"']").addClass('active');
  // });

  /*
   * scorecard
   */
  // prep
  $('div.details').hide();

  // hide/show details
  $('ul.scorecard article.has-details').live('click', function(){
    hideShow($('div.details', $(this)), $(this));
  });

  /*
   * Comments: hover and show tools
   */
  $('.comments li').hover(function() {
    $(this).addClass('hovered');
  },
  function() {
    $(this).removeClass('hovered');
  });

  /*
   * Login box
   */
  var login_target = $('#site-user-tools .login a').attr('href');

  $('#site-user-tools').after('
Loading...
');

  $('li.login').on('click', function(event) {
    event.preventDefault();
    $('#login-box').load(login_target + ' #login');
    hideShow($('#login-box'), $(this));
  });

  /*
   * Main nav hover
   */
  $('#main-menu ul > li').on('mouseover', function(){
    if($(this).children('ul').length === 1){
      // alert('oh yeah');
      $(this).addClass('active');
    }
  }).on('mouseout', function(){
    $(this).removeClass('active');
  });

  /* carry search terms across when switching between search pages */
  $("#search-hansard-instead").click(function(e){
    e.preventDefault();
    location.href="/search/hansard?q=" + escape($('#core-search,#id_q,#loc').first().val());
  });
  $("#search-core-instead").click(function(e){
    e.preventDefault();
    location.href="/search?q=" + escape($('#id_q,#loc').first().val());
  });
});<|endoftext|>