<commit_before>module('kmlForest');

/**
 * Simply verify that the widget loads without throwing any errors (unless of course the proper options were not defined).
 */
test('initialize', function(){
    $(document.body).append('

');
    $('#treetest').kmlForest({ge: ge, gex: gex, animate: false});
    ok($('#treetest').kmlForest('length') == 0, 'No kml files loaded yet');
});

test('add', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        ok($('#treetest :contains(kmlForestTest.kmz)').length > 0, 'Proper nodes added to tree');
    }});
});

test('clear', function(){
    $('#treetest').kmlForest('clear');
    ok($('#treetest').kmlForest('length') == 0, 'All kml files removed');
    equals($('#treetest li').length, 0, 'All nodes from kmlForest removed along with them');
});

// this is here just to make sure the following tests can deal with more than
// one kml file being displayed
test('add extra kml file before continuing tests', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/example_camera_view.kml', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
    }});
});

test('getByUrl', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        var kmlObject = $('#treetest').kmlForest('getByUrl', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz');
        ok(kmlObject, 'returns value');
        equals(kmlObject.getName(), 'kmlForestTest.kmz', 'Is the correct kml file');
        $('#treetest').kmlForest('clear');
    }});
});

// this is here just to make sure the following tests can deal with more than
// one kml file being displayed
test('add extra kml file before continuing tests', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/example_camera_view.kml', {cachebust: true, callback: function(){
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        start();
    }});
});

test('remove', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 2, 'KML file successfully loaded');
        $('#treetest').kmlForest('remove', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz');
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully removed');
        equals($('#treetest :contains("kmlForestTest.kmz")').length, 0, 'kmlForestTest.kmz removed');
    }});
});

test('add with relative path', function(){
    $('#treetest').kmlForest('clear');
    // Not sure how to test this considering the location of the kml files in relation to where the tests are run
});

test('refresh', function(){
    // Not going to address this yet, since it requires remembering the on/off/open state of each element.
});

test('appropriate category header', function(){
    $('#treetest').kmlForest('clear');
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        ok($('#treetest .marinemap-tree-category').length == 1, 'Category created');
    }});
});

test('supports kml open tag', function(){
    $('#treetest').kmlForest('clear');
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("kmlForest Test File")').parent().find('> ul:visible').length, 1, "List should be visible, folder open");
        equals($('#treetest a:contains("closed folder")').parent().find('> ul:visible').length, 0, "'closed folder' should be closed");
    }});
});

test('supports visibility tag', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Visibility set to false")').length, 1, 'unchecked node exists.');
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'Node is not visible on the map.');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 0, 'Checkbox is not checked.');

        equals($('#treetest a:contains("Placemark with description")').length, 1, 'checked node exists.');
        equals($('#treetest a:contains("Placemark with description")').parent().data('kml').getVisibility(), true, 'Node is visible on the map.');
        equals($('#treetest a:contains("Placemark with description")').parent().find('input:checked').length, 1, 'Checkbox is checked.');
    }});
});

test('supports snippet tag', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("PhotoOverlay of South Coast Study Region")').length, 1, 'node with snippet exists.');
        equals($('#treetest a:contains("PhotoOverlay of South Coast Study Region")').parent().find('p.snippet').length, 1, 'Snippet is displayed.');
    }});

});

test('toggle on/off features', function(){
    // check that toggling a feature works
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "init check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "init check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });

        equals($('#treetest a:contains("Visibility set to false")').length, 1, 'invisible node exists');
        equals($('#treetest a:contains("One at a time")').length, 1, 'other invisible node exists');
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'invisible node does not show on map');
        var input = $('#treetest a:contains("Visibility set to false")').parent().find('input');
        // turn on visibility of feature
        input.click();
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), true, 'node turned on after click on map');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 1, 'node turned on after click in list');

        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "toggle-on check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "toggle-on check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });

        // turn off visibility of feature
        input.click();
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'node turned off on map');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 0, 'node turned off in list');

        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "toggle-off check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "toggle-off check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });
    }});

    // then check that it hasn't messed with any of the others
});

test('toggle on/off folders and NetworkLinks', function(){
    // same as is tested in the tree tests, just check getVisibility()
});

test('semi-toggled state for parents with some children visible', function(){
    // this will require custom icons
});

test('features with descriptions have balloon link', function(){

});

var firstLat;

test('double click feature flys to feature', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Placemark without description")').length, 1, 'Placemark exists');
        firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        $('#treetest a:contains("Placemark without description")').dblclick();
    }});
});

test('finish double click feature flys to feature', function(){
    stop();
    setTimeout(function(){
        var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        ok(firstLat != secondLat, "Viewport has changed after double-clicking the placemark");
        start();
    }, 500);
});

test('proper default icons given to folders, network links, features, etc', function(){
    // Just check the class for KmlFolder, KmlGroundOverlay, KmlPlacemark, KmlNetworkLink, etc
});

test('ListStyle support: radioFolder. All ListStyle support depends on this ticket', function(){

});

test('ListStyle support: checkOffOnly', function(){

});

test('ListStyle support: checkHideChildren', function(){

});

test('ListStyle support: ItemIcon', function(){

});

test('Contents of NetworkLinks can be displayed. Depends on this ticket, or a hack', function(){

});

// Not a very good test. If the double click event was instead causing the
// viewport to zoom to the camera like any other feature, the bug likely
// wouldn't be detected. Should really be a ge.getTourPlayer().getTour() api.
// A feature request has been submitted for that function
// http://code.google.com/p/earth-api-samples/issues/detail?id=309
test('tours are activated when double-clicked.', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Tour Example")').length, 1, 'Tour exists');
        var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        $('#treetest a:contains("Tour Example")').dblclick();
        ge.getTourPlayer().play();
        var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        ok(firstLat != secondLat, "Assuming the latitude changes after double-clicking the tour, it must be active.");
        ge.getTourPlayer().pause();
    }});
});

<commit_msg>Added tests to make sure toggling a folder toggles all it's children.<commit_after>module('kmlForest');

/**
 * Simply verify that the widget loads without throwing any errors (unless of course the proper options were not defined).
 */
test('initialize', function(){
    $(document.body).append('

');
    $('#treetest').kmlForest({ge: ge, gex: gex, animate: false});
    ok($('#treetest').kmlForest('length') == 0, 'No kml files loaded yet');
});

test('add', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        ok($('#treetest :contains(kmlForestTest.kmz)').length > 0, 'Proper nodes added to tree');
    }});
});

test('clear', function(){
    $('#treetest').kmlForest('clear');
    ok($('#treetest').kmlForest('length') == 0, 'All kml files removed');
    equals($('#treetest li').length, 0, 'All nodes from kmlForest removed along with them');
});

// this is here just to make sure the following tests can deal with more than
// one kml file being displayed
test('add extra kml file before continuing tests', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/example_camera_view.kml', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
    }});
});

test('getByUrl', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        var kmlObject = $('#treetest').kmlForest('getByUrl', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz');
        ok(kmlObject, 'returns value');
        equals(kmlObject.getName(), 'kmlForestTest.kmz', 'Is the correct kml file');
        $('#treetest').kmlForest('clear');
    }});
});

// this is here just to make sure the following tests can deal with more than
// one kml file being displayed
test('add extra kml file before continuing tests', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/example_camera_view.kml', {cachebust: true, callback: function(){
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        start();
    }});
});

test('remove', function(){
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 2, 'KML file successfully loaded');
        $('#treetest').kmlForest('remove', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz');
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully removed');
        equals($('#treetest :contains("kmlForestTest.kmz")').length, 0, 'kmlForestTest.kmz removed');
    }});
});

test('add with relative path', function(){
    $('#treetest').kmlForest('clear');
    // Not sure how to test this considering the location of the kml files in relation to where the tests are run
});

test('refresh', function(){
    // Not going to address this yet, since it requires remembering the on/off/open state of each element.
});

test('appropriate category header', function(){
    $('#treetest').kmlForest('clear');
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        ok($('#treetest .marinemap-tree-category').length == 1, 'Category created');
    }});
});

test('supports kml open tag', function(){
    $('#treetest').kmlForest('clear');
    stop();
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("kmlForest Test File")').parent().find('> ul:visible').length, 1, "List should be visible, folder open");
        equals($('#treetest a:contains("closed folder")').parent().find('> ul:visible').length, 0, "'closed folder' should be closed");
    }});
});

test('supports visibility tag', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Visibility set to false")').length, 1, 'unchecked node exists.');
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'Node is not visible on the map.');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 0, 'Checkbox is not checked.');

        equals($('#treetest a:contains("Placemark with description")').length, 1, 'checked node exists.');
        equals($('#treetest a:contains("Placemark with description")').parent().data('kml').getVisibility(), true, 'Node is visible on the map.');
        equals($('#treetest a:contains("Placemark with description")').parent().find('input:checked').length, 1, 'Checkbox is checked.');
    }});
});

test('supports snippet tag', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("PhotoOverlay of South Coast Study Region")').length, 1, 'node with snippet exists.');
        equals($('#treetest a:contains("PhotoOverlay of South Coast Study Region")').parent().find('p.snippet').length, 1, 'Snippet is displayed.');
    }});

});

test('toggle on/off features', function(){
    // check that toggling a feature works
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "init check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "init check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });

        equals($('#treetest a:contains("Visibility set to false")').length, 1, 'invisible node exists');
        equals($('#treetest a:contains("One at a time")').length, 1, 'other invisible node exists');
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'invisible node does not show on map');
        var input = $('#treetest a:contains("Visibility set to false")').parent().find('input');
        // turn on visibility of feature
        input.click();
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), true, 'node turned on after click on map');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 1, 'node turned on after click in list');

        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "toggle-on check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "toggle-on check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });

        // turn off visibility of feature
        input.click();
        equals($('#treetest a:contains("Visibility set to false")').parent().data('kml').getVisibility(), false, 'node turned off on map');
        equals($('#treetest a:contains("Visibility set to false")').parent().find('input:checked').length, 0, 'node turned off in list');

        // Make sure all other visibilities match up
        $('#treetest li').each(function(){
            var kml = $(this).data('kml');
            if(!$(this).hasClass('toggle')){
                ok(kml.getVisibility(), "toggle-off check: "+kml.getName() + ' node: KML is not toggle-able, so should have visibility set at true');
            }else{
                var text = "toggle-off check: "+'"' + kml.getName() + '" node ';
                var checked = $(this).find('> input:checked').length == 1;
                if(checked){
                    text += 'is checked so should be visible.'
                }else{
                    text += "is not checked so shouldn't be visible."
                }
                ok(checked == kml.getVisibility(), text)
            }
        });
    }});

    // then check that it hasn't messed with any of the others
});

test('toggle on/off folders toggles children', function(){
    // same as is tested in the tree tests, just check getVisibility()
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        var folder = $('#treetest a:contains("Both visible")').parent();
        var input = folder.find('>input');
        // toggle off
        input.click();
        var kml = folder.data('kml');
        ok(!kml.getVisibility(), 'Folder is now visible');
        ok(!kml.getFeatures().getLastChild().getVisibility(), 'Children are now visible');
        // toggle on now
        input.click();
        equals(kml.getVisibility(), true, 'Folder is now invisible');
        equals(kml.getFeatures().getLastChild().getVisibility(), true, 'Children are now visible');
    }});
});

test('semi-toggled state for parents with some children visible', function(){
    // this will require custom icons
});

test('features with descriptions have balloon link', function(){

});

var firstLat;

test('double click feature flys to feature', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Placemark without description")').length, 1, 'Placemark exists');
        firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        $('#treetest a:contains("Placemark without description")').dblclick();
    }});
});

test('finish double click feature flys to feature', function(){
    stop();
    setTimeout(function(){
        var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        ok(firstLat != secondLat, "Viewport has changed after double-clicking the placemark");
        start();
    }, 500);
});

test('proper default icons given to folders, network links, features, etc', function(){
    // Just check the class for KmlFolder, KmlGroundOverlay, KmlPlacemark, KmlNetworkLink, etc
});

test('ListStyle support: radioFolder. All ListStyle support depends on this ticket', function(){

});

test('ListStyle support: checkOffOnly', function(){

});

test('ListStyle support: checkHideChildren', function(){

});

test('ListStyle support: ItemIcon', function(){

});

test('Contents of NetworkLinks can be displayed. Depends on this ticket, or a hack', function(){

});

// Not a very good test. If the double click event was instead causing the
// viewport to zoom to the camera like any other feature, the bug likely
// wouldn't be detected. Should really be a ge.getTourPlayer().getTour() api.
// A feature request has been submitted for that function
// http://code.google.com/p/earth-api-samples/issues/detail?id=309
test('tours are activated when double-clicked.', function(){
    stop();
    $('#treetest').kmlForest('clear');
    $('#treetest').kmlForest('add', 'http://marinemap.googlecode.com/svn/trunk/media/common/fixtures/kmlForestTest.kmz', {cachebust: true, callback: function(){
        start();
        ok($('#treetest').kmlForest('length') == 1, 'KML file successfully loaded');
        equals($('#treetest a:contains("Tour Example")').length, 1, 'Tour exists');
        var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        $('#treetest a:contains("Tour Example")').dblclick();
        ge.getTourPlayer().play();
        var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude();
        ok(firstLat != secondLat, "Assuming the latitude changes after double-clicking the tour, it must be active.");
        ge.getTourPlayer().pause();
    }});
});

<|endoftext|>


<commit_before>dojo.provide("sketchSpaceDesigner.designer.ui");

dojo.require("sketchSpaceDesigner.designer.editor");
dojo.require("sketchSpaceDesigner.designer.widgets");
dojo.require("dojo.parser");
dojo.require("dojox.layout.TableContainer");
dojo.require("dijit.layout.ContentPane");

dojo.declare("sketchSpaceDesigner.designer.DesignerUI", [dijit._Widget, dijit._Templated], {
  widgetsInTemplate: true,
  templateString: '
' +
		  '
' +
		  '
' +
		  '
' +
		  '

' +
		  '

      ' +
		  '
' +
		  '
' +
		  '

' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '' +
		  '	      	' +
		  '

' +
		  '
' +
		  '
' +
		  '

' +
		  '

' +
		  '
' +
		  '
' +
		  '
' +
		  '
' +
		  '
' +
                  '

' +
                  '
' +
                  '
Value
' +
                  '
' +
                  '
',
  startup: function () {
    this.inherited(arguments);

    if (typeof("AjaxUpload") != "undefined") {
      var info = {
	action: '/ep/fileUpload/',
	name: 'uploadfile',
	onSubmit: function(file, ext){
	//console.log('Starting...');
	},
	onComplete: function(file, response){
	  var path = eval(response)[0].split("/");
	  sketchSpace.editorUi.addImg(path[path.length-1]);
	}
      }
      new AjaxUpload($(this.addImgButton), info);
    }

    this.editor = new sketchSpaceDesigner.designer.editor.Editor(this.editorArea, this.attr("userId"), this);
    this.selectToolIcon("select");
  },

  selectToolIcon: function(name) {
    $(this.toolbar).find(".tool").css({background: "#ffffff"});
    $(this.toolbar).find(".tool." + name).css({background: "#cccccc"});
  },

  _onAddEllipse: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddEllipse());
    this.selectToolIcon("addEllipse");
  },

  _onAddPath: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddPath());
    this.selectToolIcon("addPath");
  },

  _onAddRect: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddRect());
    this.selectToolIcon("addRect");
  },

  addImg: function(imageName) {
    var shape = this.editor.createImage(this.surface_transform, imageName);
    this.editor.registerObjectShape(shape);
    this.editor.saveShapeToStr(shape);
  },

  _onSelect: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.Select());
    this.selectToolIcon("select");
  },
});
<commit_msg>Bugfix for timeslider<commit_after>dojo.provide("sketchSpaceDesigner.designer.ui");

dojo.require("sketchSpaceDesigner.designer.editor");
dojo.require("sketchSpaceDesigner.designer.widgets");
dojo.require("dojo.parser");
dojo.require("dojox.layout.TableContainer");
dojo.require("dijit.layout.ContentPane");

dojo.declare("sketchSpaceDesigner.designer.DesignerUI", [dijit._Widget, dijit._Templated], {
  widgetsInTemplate: true,
  templateString: '
' +
		  '
' +
		  '
' +
		  '
' +
		  '

' +
		  '

      ' +
		  '
' +
		  '
' +
		  '

' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '	     	' +
		  '' +
		  '	      	' +
		  '

' +
		  '
' +
		  '
' +
		  '

' +
		  '

' +
		  '
' +
		  '
' +
		  '
' +
		  '
' +
		  '
' +
                  '

' +
                  '
' +
                  '
Value
' +
                  '
' +
                  '
',
  startup: function () {
    this.inherited(arguments);

    if (typeof(AjaxUpload) != "undefined") {
      var info = {
	action: '/ep/fileUpload/',
	name: 'uploadfile',
	onSubmit: function(file, ext){
	//console.log('Starting...');
	},
	onComplete: function(file, response){
	  var path = eval(response)[0].split("/");
	  sketchSpace.editorUi.addImg(path[path.length-1]);
	}
      };
      new AjaxUpload($(this.addImgButton), info);
    }

    this.editor = new sketchSpaceDesigner.designer.editor.Editor(this.editorArea, this.attr("userId"), this);
    this.selectToolIcon("select");
  },

  selectToolIcon: function(name) {
    $(this.toolbar).find(".tool").css({background: "#ffffff"});
    $(this.toolbar).find(".tool." + name).css({background: "#cccccc"});
  },

  _onAddEllipse: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddEllipse());
    this.selectToolIcon("addEllipse");
  },

  _onAddPath: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddPath());
    this.selectToolIcon("addPath");
  },

  _onAddRect: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.AddRect());
    this.selectToolIcon("addRect");
  },

  addImg: function(imageName) {
    var shape = this.editor.createImage(this.surface_transform, imageName);
    this.editor.registerObjectShape(shape);
    this.editor.saveShapeToStr(shape);
  },

  _onSelect: function() {
    this.editor.setMode(new sketchSpaceDesigner.designer.modes.Select());
    this.selectToolIcon("select");
  },
});
<|endoftext|>


<commit_before>function toggleDisp(){
    var txt = document.getElementById('asText');
    var box = document.getElementById('asBoxed');
    if (txt.style.display == 'none') {
        box.style.display = 'none';
        txt.style.display = 'block';
    }
    else {
        txt.style.display = 'none';
        box.style.display = 'block';
    }
}

function addGraphs(){
    addPie("Code Point Ages", "ages");
    addPie("Block Names", "blocks");
    addBar("Bytes to Encode", "sizes")
}

function addPie(title, data){
    c3.generate({
        bindto: '#'+data,
        data: {
            columns: toGraph[data] ,
            type : 'donut'
        },
        donut: {
            title: title,
            label: {
                format: function (value, ratio, id) {
                    return value;
                }
            }
        }
    });
}

function addBar(title, data){
    c3.generate({
        bindto: '#'+data,
        data: {
            columns: toGraph[data],
            type: 'bar'
        },
        bar: {
            title: title
        },
        axis: {
            x: {
                show: false,
                ratio: 1
            },
            y:{
                tick: {
                    format: function(d){return d + "B"}
                }
            },
            rotated: true
        },
        tooltip: {
            grouped: false,
            format:{
                title: function () { return 'Bytes to encode'}
            }
        },
        grid: {
            x:{
                show:false
            }
        }
    });
}

addGraphs();<commit_msg>Show labels on smaller donut segments<commit_after>function toggleDisp(){
    var txt = document.getElementById('asText');
    var box = document.getElementById('asBoxed');
    if (txt.style.display == 'none') {
        box.style.display = 'none';
        txt.style.display = 'block';
    }
    else {
        txt.style.display = 'none';
        box.style.display = 'block';
    }
}

function addGraphs(){
    addPie("Code Point Ages", "ages");
    addPie("Block Names", "blocks");
    addBar("Bytes to Encode", "sizes")
}

function addPie(title, data){
    c3.generate({
        bindto: '#'+data,
        data: {
            columns: toGraph[data] ,
            type : 'donut'
        },
        donut: {
            title: title,
            label: {
                threshold:0.02,
                format: function (value, ratio, id) {
                    return value;
                }
            }
        }
    });
}

function addBar(title, data){
    c3.generate({
        bindto: '#'+data,
        data: {
            columns: toGraph[data],
            type: 'bar'
        },
        bar: {
            title: title
        },
        axis: {
            x: {
                show: false,
                ratio: 1
            },
            y:{
                tick: {
                    format: function(d){return d + "B"}
                }
            },
            rotated: true
        },
        tooltip: {
            grouped: false,
            format:{
                title: function () { return 'Bytes to encode'}
            }
        },
        grid: {
            x:{
                show:false
            }
        }
    });
}

addGraphs();<|endoftext|>


<commit_before>(function() {
    $(document).ready(function() {
        /*
         * Loads the list of Downloaded files that are on the server
         */
        var loadFiles = function() {
            $.ajax({
                url: '/files',
                type: 'get',
                cache: false,
                dataType: 'json'
            }).done(function(data){
                $('#rss_files tbody').empty();
                // Sort files by Filename
                data.sort(function(a, b) {
                    a = a.filename.toLowerCase();
                    b = b.filename.toLowerCase();
                    return a > b ? 1 : a < b ? -1 : 0;
                });
                var tr, td = [], a, icon, del, s, i;
                for(i in data) {
                    $('#rss_files tbody').append(fileRow(data[i]));
                }
            }).fail(function(){

            });
        };
        /*
         * Loads List of TV-Shows direct from monitored RSS
         *
         */
        var loadRssTV = function(type) {
            var div, rssTV = document.getElementById('rss_TV');
            $.ajax({
                url: '/tv',
                type: 'get',
                dataType: 'json',
                cache: false
            }).done(function(data) {
                for(var i in data) {
                    rssTV.appendChild(siteRow(data[i]));
                }
            }).fail(function(data) {
                msg.set('Error loading TV-Shows');
            });
        };
        /*
         * Loads list of Movies as Thumbnails from db
         *
         */
        var loadRssMovies = function() {
            $.ajax({
                url: '/movies',
                type: 'get',
                dataType: 'json',
                cache: false,
            }).done(function(json) {
                var div, i;
                json.sort(function(a, b) {
                    a = new Date(a.lastUpdate);
                    b = new Date(b.lastUpdate);
                    return a > b ? -1 : a < b ? 1 : 0;
                });
                // Start creating Movie-Thumbs
                var li;
                for(i = 0; i < json.length; i++) {
                    div = thumbPosterWithInfoClickable(json[i]);
                    li = document.createElement('li');
                    li.className = 'col-lg-1 col-md-2 col-sm-3 col-xs-4';
                    li.appendChild(div);
                    //div.style.float = 'left';
                    $('#rss_Movies').append(li);
                }
            }).fail(function(data) {
                msg.set('Error while loading movies');
            });
        };
        loadRssTV();
        loadRssMovies();
        loadFiles();
        /*
         * Creates a siteRow which can be parsed
         *
         * @param site  {object} {title, pubdate, link, description}
         *
         *
         */
        var siteRow = function(sites) {
            var div = document.createElement('div');
            div.className = 'hyperlinkParse';
            if(sites.title !== undefined) {
                var domain = sites.link.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
                var date = new Date(sites.pubdate);
                div.innerHTML = sites.title + ' (' + date.easy() + ' @' + domain[1] + ')';
                sites = [sites];
            } else {
                div.textContent = '>- rip All Sites -<';
            }
            div.onclick = (function(sites) {
                return function() {
                    msg.set('parsing site...');
                    $.ajax({
                        url: '/site/links',
                        type: 'POST',
                        data: {
                            sites: sites
                        },
                        cache: false,
                        dataType: 'json'
                    }).done(function(onlineLinks){processLinks(onlineLinks)}).fail(function() {
                        msg.set('Error when checking links!');
                    });
                };
            })(sites);
            return div;
        };
        /*
         * Process returned online links
         */
        var processLinks = function(data) {
            /* structure of data; example
                [
                  {
                    "status": "0",
                    "filename": "Sm.2013.720p-iFT",
                    "extension": "mkv",
                    "size": "4920000000",
                    "link": "http://ul.to/08otd5be"
                  }
                  { etc. }
                ]
            */
            msg.set('found ' + data.length + ' links.')
            makeTableChecked(data);
            // Add links to textarea for exporting
            $('#paste').html(data.map(function(elem) {
                return elem.link;
            }).join(' '));
            $('.nav-tabs a[href="#tabLinks"]').tab('show');
        };

        /*
         * One Row of FileExplorer
         */
        var fileRow = function(file) {
            var tr = document.createElement('tr');
            var td = [];
            for(s = 0; s < 4; s++) {
                td.push(document.createElement('td'));
            }
            var a = null,
                icon = null,
                del = null,
                s = 0,
                i = 0;
            // Filename Link
            a = document.createElement('a');
            a.href = 'files/' + file.link;
            a.textContent = file.filename;
            td[0].appendChild(a);
            td[1].textContent = bytesToSize(file.size);
            // Filetype Icon
            icon = document.createElement('div');
            icon.className = 'icon icon' + file.extension;
            icon.title = file.extension;
            td[2].appendChild(icon);
            // DELETE Link
            del = document.createElement('div');
            del.className = 'a';
            del.onclick = function() {
                $.ajax({
                    url: 'files/' + file.link + '/delete',
                    type: 'DELETE',
                    dataType: 'json'
                }).done(function(err) {
                    err === null && msg.set('File Deleted', 'fadeout');
                    loadFiles(); // reload files-table
                }).fail(function() {
                    msg.set('Problem with connection; try again.', 'fadeout');
                });
            };
            del.textContent = 'delete';
            td[3].appendChild(del);
            for(s = 0; s < 4; s++) {
                tr.appendChild(td[s]);
            }
            return tr;
        };

        /**
         * Creates a HTML Movie-Thumb from the Movie-Poster
         *
         * @param {string} imageUrl The Url of the Movie-Poster-Image
         * @param {string} title Title of the Movie as title-tag
         *
         * @returns {Object} the DOM-Object of the div
         */
        var thumbPoster = function(imageUrl, title, year) {
            var img = document.createElement('img');
            img.src = imageUrl;
            img.className = 'thumbPosterImg thumb thumbnail';
            img.style.height = '150px';
            img.title = title + ' (' + year + ')';
            var divTitle = document.createElement('div');
            var div = document.createElement('div');
            div.className = 'thumbPoster';
            divTitle.title = title + ' (' + year + ')';
            divTitle.className = 'thumbPosterTitle';
            divTitle.textContent = title;
            if(imageUrl === 'http://image.tmdb.org/t/p/w500null' || imageUrl === '' || (/poster_default/).test(imageUrl)) {
                img.src = '/images/default.jpg';
                //div.appendChild(divTitle);

            }
            div.appendChild(img);
            return div;
        };
        /**
         * Adds info to the movie-Thumb (Resolution, etc.)
         */
        var thumbPosterWithInfo = function(imageUrl, title, year, resolutions) {
            var thumb = thumbPoster(imageUrl, title, year);
            var divRes = document.createElement('div');
            divRes.className = 'resolutionBar';
            divRes.textContent = resolutions.join(', ');
            //thumb.appendChild(divRes);
            return thumb;
        };
        var thumbPosterWithInfoClickable = function(mData) {
            imgUrl = mData.info.posters !== undefined ? mData.info.posters.thumbnail : '';
            var div = thumbPosterWithInfo(imgUrl, mData.title, mData.info.year, mData.resolutions);
            div.style.cursor = 'pointer';
            div.onclick = (function(_id, title, info, image, sites, div) {
                return function() {
                    $('.nav-tabs a[href="#tabLinks"]').tab('show');
                    $('#linksDetails').empty();
                    $('#linksDetails').append(divMovieInfo(_id, title, image, info.runtime ? info.runtime : '?', info.year, 'imdb-Rating', info.synopsis === '' ? 'no synopsis' : info.synopsis, 'actors', div));
                    // Site-Links for ripping links
                    var linkList = document.getElementById('linksDetails');
                    // Link to Rip all links at the same time
                    linkList.appendChild(siteRow(sites));
                    // Single Links that can be parsed
                    for(var key in sites) {
                        linkList.appendChild(siteRow(sites[key]));
                    }
                };
            })(mData._id, mData.title, mData.info, imgUrl, mData.sites, div);
            return div;
        };
        /**
         * Creates the Movie-Info-Card
         */
        var divMovieInfo = function(_id, title, posterUrl, runtime, year, imdb, synopsis, actors, thumbDiv) {
            var div = document.createElement('div');
            div.className = 'movieDigest';
            var divOuter = document.createElement('div');
            divOuter.className = 'movieInfo';
            var divTitle = document.createElement('h2');
            divTitle.className = 'movieInfoTitle';
            divTitle.textContent = title;
            var divDetails = document.createElement('div');
            divDetails.className = 'movieInfoLine';
            divDetails.textContent = 'Length: ' + runtime + 'min, Year: ' + year + ', ';
            var spanRemove = createElementSpanRemove(_id, thumbDiv);
            divDetails.appendChild(spanRemove);
            divDetails.appendChild(createElementSpanSpace());
            var spanUpdate = createElementSpanUpdate(_id);
            divDetails.appendChild(spanUpdate);
            var divSynopsis = document.createElement('div');
            divSynopsis.className = 'movieInfoLine';
            divSynopsis.textContent = synopsis;
            divSynopsis.style.fontStyle = 'italic';
            var poster = thumbPoster(posterUrl, title, year);
            poster.style.float = 'left';
            divOuter.appendChild(divTitle);
            divOuter.appendChild(divDetails);
            divOuter.appendChild(divSynopsis);
            div.appendChild(poster);
            div.appendChild(divOuter);
            return div;
        };
        /**
         * creates a space-span of len white spaces
         */
        var createElementSpanSpace = function(len) {
            if(len === undefined) len = 1;
            var span = document.createElement('span');
            var space = '';
            for(var i = 0; i < len; i++) {
                space += ' ';
            }
            span.textContent = space;
            return span;
        };
        /**
         * Creates a link which removes a movie from future display
         */
        var createElementSpanRemove = function(id, thumbDiv) {
            var button = document.createElement('div');
            button.className = 'btn btn-default btn-sm';
            var span = document.createElement('span');
            span.textContent = 'remove';
            span.title = 'don\'t display this movie anymore.';
            span.className = 'glyphicon glyphicon-trash';
            button.onclick = function() {
                $.getJSON('/movie/' + id + '/hide', function(data) {
                    msg.set('Movie will not be shown anymore!', 'fadeout');
                    $('.nav-tabs a[href="#tabHome"]').tab('show');
                    thumbDiv.parentNode.removeChild(thumbDiv);
                });
            };
            button.appendChild(span)
            return button;
        };

        /*
         * Creates a link which updates a movie-info
         */
        var createElementSpanUpdate = function(id) {
            var button = document.createElement('div');
            button.className = 'btn btn-default btn-sm';
            var span = document.createElement('span');
            span.textContent = 'update';
            span.title = 'update info to this movie';
            span.className = 'glyphicon glyphicon-refresh';
            button.onclick = function() {
                $.getJSON('/movie/' + id + '/update', function(data) {
                    msg.set('Movie-Info Updated', 'fadeout');
                });
            };
            button.appendChild(span)
            return button;
        };

        /*
         * Create a Link that can be parsed (for one or multiple Links)
         */
        var parseLink = function(text, sites, clickEvent) {
            var div = document.createElement('div');
            div.className = 'hyperlinkParse';
            div.textContent = text;
            div.onclick = function() {
                clickEvent(sites);
            };
            return div;
        };

        /*
         * Table with ul.to links that have been checked for availability
         *
         * @param {array} files an Array containing all checked ul.to links
         */
        var makeTableChecked = function(files) {
            // one tab for every extension; integer is filecount per extension
            var extensions = {
                mp4: 0,
                mkv: 0,
                avi: 0,
                rar: 0,
                default: 0
            };
            var rowcols = ['link', 'size', 'extension', 'jd', 'cloud'];
            var target = '#tabs-links-';
            // empty all tabs
            for(var i in extensions) $(target + i + ' tbody').empty();
            var cols = function() {
                var tds = [];
                for(var i in rowcols) tds.push(document.createElement('td'));
                return tds;
            };
            // sort files by extension
            files.sort(function(a, b) {
                return a.extension  b.extension ? -1 : 0;
            });
            var makeRow = function(filename, href, extension, size) {
                // create new DOM-table-row
                var tr = document.createElement('tr');
                // create cells
                var tds = [];
                for(var i in rowcols) tds.push(document.createElement('td'));
                // Link/Name Col
                var link = document.createElement('a');
                link.href = href;
                link.textContent = filename;
                tds[0].appendChild(link);
                // Size Col
                tds[1].textContent = bytesToSize(size);
                // Extension Col
                var extension = document.createElement('div');
                extension.className = 'icon icon' + extension;
                extension.title = extension;
                tds[2].appendChild(extension);
                // J-Downloader Col
                tds[3].appendChild(jDLink(link));
                // Download to Server Col
                var cloud = document.createElement('div');
                cloud.className = 'icon iconcloud';
                cloud.title = 'download to diskstation';
                cloud.onclick = (function(link) {
                    return function() {
                        DownloadStation(link);
                    };
                })(href);
                tds[4].appendChild(cloud);
                for(var key in tds) tr.appendChild(tds[key]);
                return tr;
            };
            // Loop through all files
            for(i in files) {
                var t = (extensions[files[i].extension] !== undefined) ? files[i].extension : 'default';
                extensions[t]++;
                var tr = makeRow(files[i].filename, files[i].link, files[i].extension, files[i].size);
                $(target + t + ' tbody').append(tr);
            }
            // update files per extension
            if(extensions.mp4 === 0) {
                $('.nav-tabs a[href="#tabLinks"]').tab('show');
            } else {
                $('.nav-tabs a[href="#tabs-links-mkv"]').tab('show');
            }
            // Update Tab-title counter
            for(var i in extensions) {
                $('#rssLinks ul:first li:eq(' + (Object.keys(extensions)).indexOf(i) + ') a').text(i + '(' + extensions[i] + ')');
            }
        };

        (function(){
            var bParse = document.getElementById('go');
            bParse.onclick = function(){
                var data = document.getElementById('data').value;
                if (validateURL(data)) {
                    msg.set('parsing site...');
                    $.ajax({
                        url: '/site/links',
                        type: 'POST',
                        data: {
                            sites: [data]
                        },
                        cache: false,
                        dataType: 'json'
                    }).done(function(onlineLinks){processLinks(onlineLinks)}).fail(function() {
                        msg.set('Error when checking links!');
                    });
                }
            };
        })();

    });
})();<commit_msg>manual parsing of links<commit_after>(function() {
    $(document).ready(function() {
        /*
         * Loads the list of Downloaded files that are on the server
         */
        var loadFiles = function() {
            $.ajax({
                url: '/files',
                type: 'get',
                cache: false,
                dataType: 'json'
            }).done(function(data){
                $('#rss_files tbody').empty();
                // Sort files by Filename
                data.sort(function(a, b) {
                    a = a.filename.toLowerCase();
                    b = b.filename.toLowerCase();
                    return a > b ? 1 : a < b ? -1 : 0;
                });
                var tr, td = [], a, icon, del, s, i;
                for(i in data) {
                    $('#rss_files tbody').append(fileRow(data[i]));
                }
            }).fail(function(){

            });
        };
        /*
         * Loads List of TV-Shows direct from monitored RSS
         *
         */
        var loadRssTV = function(type) {
            var div, rssTV = document.getElementById('rss_TV');
            $.ajax({
                url: '/tv',
                type: 'get',
                dataType: 'json',
                cache: false
            }).done(function(data) {
                for(var i in data) {
                    rssTV.appendChild(siteRow(data[i]));
                }
            }).fail(function(data) {
                msg.set('Error loading TV-Shows');
            });
        };
        /*
         * Loads list of Movies as Thumbnails from db
         *
         */
        var loadRssMovies = function() {
            $.ajax({
                url: '/movies',
                type: 'get',
                dataType: 'json',
                cache: false,
            }).done(function(json) {
                var div, i;
                json.sort(function(a, b) {
                    a = new Date(a.lastUpdate);
                    b = new Date(b.lastUpdate);
                    return a > b ? -1 : a < b ? 1 : 0;
                });
                // Start creating Movie-Thumbs
                var li;
                for(i = 0; i < json.length; i++) {
                    div = thumbPosterWithInfoClickable(json[i]);
                    li = document.createElement('li');
                    li.className = 'col-lg-1 col-md-2 col-sm-3 col-xs-4';
                    li.appendChild(div);
                    //div.style.float = 'left';
                    $('#rss_Movies').append(li);
                }
            }).fail(function(data) {
                msg.set('Error while loading movies');
            });
        };
        loadRssTV();
        loadRssMovies();
        loadFiles();
        /*
         * Creates a siteRow which can be parsed
         *
         * @param site  {object} {title, pubdate, link, description}
         *
         *
         */
        var siteRow = function(sites) {
            var div = document.createElement('div');
            div.className = 'hyperlinkParse';
            if(sites.title !== undefined) {
                var domain = sites.link.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
                var date = new Date(sites.pubdate);
                div.innerHTML = sites.title + ' (' + date.easy() + ' @' + domain[1] + ')';
                sites = [sites];
            } else {
                div.textContent = '>- rip All Sites -<';
            }
            div.onclick = (function(sites) {
                return function() {
                    msg.set('parsing site...');
                    $.ajax({
                        url: '/site/links',
                        type: 'POST',
                        data: {
                            sites: sites
                        },
                        cache: false,
                        dataType: 'json'
                    }).done(function(onlineLinks){processLinks(onlineLinks)}).fail(function() {
                        msg.set('Error when checking links!');
                    });
                };
            })(sites);
            return div;
        };
        /*
         * Process returned online links
         */
        var processLinks = function(data) {
            /* structure of data; example
                [
                  {
                    "status": "0",
                    "filename": "Sm.2013.720p-iFT",
                    "extension": "mkv",
                    "size": "4920000000",
                    "link": "http://ul.to/08otd5be"
                  }
                  { etc. }
                ]
            */
            msg.set('found ' + data.length + ' links.')
            makeTableChecked(data);
            // Add links to textarea for exporting
            $('#paste').html(data.map(function(elem) {
                return elem.link;
            }).join(' '));
            $('.nav-tabs a[href="#tabLinks"]').tab('show');
        };

        /*
         * One Row of FileExplorer
         */
        var fileRow = function(file) {
            var tr = document.createElement('tr');
            var td = [];
            for(s = 0; s < 4; s++) {
                td.push(document.createElement('td'));
            }
            var a = null,
                icon = null,
                del = null,
                s = 0,
                i = 0;
            // Filename Link
            a = document.createElement('a');
            a.href = 'files/' + file.link;
            a.textContent = file.filename;
            td[0].appendChild(a);
            td[1].textContent = bytesToSize(file.size);
            // Filetype Icon
            icon = document.createElement('div');
            icon.className = 'icon icon' + file.extension;
            icon.title = file.extension;
            td[2].appendChild(icon);
            // DELETE Link
            del = document.createElement('div');
            del.className = 'a';
            del.onclick = function() {
                $.ajax({
                    url: 'files/' + file.link + '/delete',
                    type: 'DELETE',
                    dataType: 'json'
                }).done(function(err) {
                    err === null && msg.set('File Deleted', 'fadeout');
                    loadFiles(); // reload files-table
                }).fail(function() {
                    msg.set('Problem with connection; try again.', 'fadeout');
                });
            };
            del.textContent = 'delete';
            td[3].appendChild(del);
            for(s = 0; s < 4; s++) {
                tr.appendChild(td[s]);
            }
            return tr;
        };

        /**
         * Creates a HTML Movie-Thumb from the Movie-Poster
         *
         * @param {string} imageUrl The Url of the Movie-Poster-Image
         * @param {string} title Title of the Movie as title-tag
         *
         * @returns {Object} the DOM-Object of the div
         */
        var thumbPoster = function(imageUrl, title, year) {
            var img = document.createElement('img');
            img.src = imageUrl;
            img.className = 'thumbPosterImg thumb thumbnail';
            img.style.height = '150px';
            img.title = title + ' (' + year + ')';
            var divTitle = document.createElement('div');
            var div = document.createElement('div');
            div.className = 'thumbPoster';
            divTitle.title = title + ' (' + year + ')';
            divTitle.className = 'thumbPosterTitle';
            divTitle.textContent = title;
            if(imageUrl === 'http://image.tmdb.org/t/p/w500null' || imageUrl === '' || (/poster_default/).test(imageUrl)) {
                img.src = '/images/default.jpg';
                //div.appendChild(divTitle);

            }
            div.appendChild(img);
            return div;
        };
        /**
         * Adds info to the movie-Thumb (Resolution, etc.)
         */
        var thumbPosterWithInfo = function(imageUrl, title, year, resolutions) {
            var thumb = thumbPoster(imageUrl, title, year);
            var divRes = document.createElement('div');
            divRes.className = 'resolutionBar';
            divRes.textContent = resolutions.join(', ');
            //thumb.appendChild(divRes);
            return thumb;
        };
        var thumbPosterWithInfoClickable = function(mData) {
            imgUrl = mData.info.posters !== undefined ? mData.info.posters.thumbnail : '';
            var div = thumbPosterWithInfo(imgUrl, mData.title, mData.info.year, mData.resolutions);
            div.style.cursor = 'pointer';
            div.onclick = (function(_id, title, info, image, sites, div) {
                return function() {
                    $('.nav-tabs a[href="#tabLinks"]').tab('show');
                    $('#linksDetails').empty();
                    $('#linksDetails').append(divMovieInfo(_id, title, image, info.runtime ? info.runtime : '?', info.year, 'imdb-Rating', info.synopsis === '' ? 'no synopsis' : info.synopsis, 'actors', div));
                    // Site-Links for ripping links
                    var linkList = document.getElementById('linksDetails');
                    // Link to Rip all links at the same time
                    linkList.appendChild(siteRow(sites));
                    // Single Links that can be parsed
                    for(var key in sites) {
                        linkList.appendChild(siteRow(sites[key]));
                    }
                };
            })(mData._id, mData.title, mData.info, imgUrl, mData.sites, div);
            return div;
        };
        /**
         * Creates the Movie-Info-Card
         */
        var divMovieInfo = function(_id, title, posterUrl, runtime, year, imdb, synopsis, actors, thumbDiv) {
            var div = document.createElement('div');
            div.className = 'movieDigest';
            var divOuter = document.createElement('div');
            divOuter.className = 'movieInfo';
            var divTitle = document.createElement('h2');
            divTitle.className = 'movieInfoTitle';
            divTitle.textContent = title;
            var divDetails = document.createElement('div');
            divDetails.className = 'movieInfoLine';
            divDetails.textContent = 'Length: ' + runtime + 'min, Year: ' + year + ', ';
            var spanRemove = createElementSpanRemove(_id, thumbDiv);
            divDetails.appendChild(spanRemove);
            divDetails.appendChild(createElementSpanSpace());
            var spanUpdate = createElementSpanUpdate(_id);
            divDetails.appendChild(spanUpdate);
            var divSynopsis = document.createElement('div');
            divSynopsis.className = 'movieInfoLine';
            divSynopsis.textContent = synopsis;
            divSynopsis.style.fontStyle = 'italic';
            var poster = thumbPoster(posterUrl, title, year);
            poster.style.float = 'left';
            divOuter.appendChild(divTitle);
            divOuter.appendChild(divDetails);
            divOuter.appendChild(divSynopsis);
            div.appendChild(poster);
            div.appendChild(divOuter);
            return div;
        };
        /**
         * creates a space-span of len white spaces
         */
        var createElementSpanSpace = function(len) {
            if(len === undefined) len = 1;
            var span = document.createElement('span');
            var space = '';
            for(var i = 0; i < len; i++) {
                space += ' ';
            }
            span.textContent = space;
            return span;
        };
        /**
         * Creates a link which removes a movie from future display
         */
        var createElementSpanRemove = function(id, thumbDiv) {
            var button = document.createElement('div');
            button.className = 'btn btn-default btn-sm';
            var span = document.createElement('span');
            span.textContent = 'remove';
            span.title = 'don\'t display this movie anymore.';
            span.className = 'glyphicon glyphicon-trash';
            button.onclick = function() {
                $.getJSON('/movie/' + id + '/hide', function(data) {
                    msg.set('Movie will not be shown anymore!', 'fadeout');
                    $('.nav-tabs a[href="#tabHome"]').tab('show');
                    thumbDiv.parentNode.removeChild(thumbDiv);
                });
            };
            button.appendChild(span)
            return button;
        };

        /*
         * Creates a link which updates a movie-info
         */
        var createElementSpanUpdate = function(id) {
            var button = document.createElement('div');
            button.className = 'btn btn-default btn-sm';
            var span = document.createElement('span');
            span.textContent = 'update';
            span.title = 'update info to this movie';
            span.className = 'glyphicon glyphicon-refresh';
            button.onclick = function() {
                $.getJSON('/movie/' + id + '/update', function(data) {
                    msg.set('Movie-Info Updated', 'fadeout');
                });
            };
            button.appendChild(span)
            return button;
        };

        /*
         * Create a Link that can be parsed (for one or multiple Links)
         */
        var parseLink = function(text, sites, clickEvent) {
            var div = document.createElement('div');
            div.className = 'hyperlinkParse';
            div.textContent = text;
            div.onclick = function() {
                clickEvent(sites);
            };
            return div;
        };

        /*
         * Table with ul.to links that have been checked for availability
         *
         * @param {array} files an Array containing all checked ul.to links
         */
        var makeTableChecked = function(files) {
            // one tab for every extension; integer is filecount per extension
            var extensions = {
                mp4: 0,
                mkv: 0,
                avi: 0,
                rar: 0,
                default: 0
            };
            var rowcols = ['link', 'size', 'extension', 'jd', 'cloud'];
            var target = '#tabs-links-';
            // empty all tabs
            for(var i in extensions) $(target + i + ' tbody').empty();
            var cols = function() {
                var tds = [];
                for(var i in rowcols) tds.push(document.createElement('td'));
                return tds;
            };
            // sort files by extension
            files.sort(function(a, b) {
                return a.extension  b.extension ? -1 : 0;
            });
            var makeRow = function(filename, href, extension, size) {
                // create new DOM-table-row
                var tr = document.createElement('tr');
                // create cells
                var tds = [];
                for(var i in rowcols) tds.push(document.createElement('td'));
                // Link/Name Col
                var link = document.createElement('a');
                link.href = href;
                link.textContent = filename;
                tds[0].appendChild(link);
                // Size Col
                tds[1].textContent = bytesToSize(size);
                // Extension Col
                var extension = document.createElement('div');
                extension.className = 'icon icon' + extension;
                extension.title = extension;
                tds[2].appendChild(extension);
                // J-Downloader Col
                tds[3].appendChild(jDLink(link));
                // Download to Server Col
                var cloud = document.createElement('div');
                cloud.className = 'icon iconcloud';
                cloud.title = 'download to diskstation';
                cloud.onclick = (function(link) {
                    return function() {
                        DownloadStation(link);
                    };
                })(href);
                tds[4].appendChild(cloud);
                for(var key in tds) tr.appendChild(tds[key]);
                return tr;
            };
            // Loop through all files
            for(i in files) {
                var t = (extensions[files[i].extension] !== undefined) ? files[i].extension : 'default';
                extensions[t]++;
                var tr = makeRow(files[i].filename, files[i].link, files[i].extension, files[i].size);
                $(target + t + ' tbody').append(tr);
            }
            // update files per extension
            if(extensions.mp4 === 0) {
                $('.nav-tabs a[href="#tabLinks"]').tab('show');
            } else {
                $('.nav-tabs a[href="#tabs-links-mkv"]').tab('show');
            }
            // Update Tab-title counter
            for(var i in extensions) {
                $('#rssLinks ul:first li:eq(' + (Object.keys(extensions)).indexOf(i) + ') a').text(i + '(' + extensions[i] + ')');
            }
        };

        (function(){
            var bParse = document.getElementById('go');
            bParse.onclick = function(){
                var data = document.getElementById('data').value;
                if (validateURL(data)) {
                    msg.set('parsing site...');
                    $.ajax({
                        url: '/site/links',
                        type: 'POST',
                        data: {
                            sites: [{link:data}]
                        },
                        cache: false,
                        dataType: 'json'
                    }).done(function(onlineLinks){processLinks(onlineLinks)}).fail(function() {
                        msg.set('Error when checking links!');
                    });
                }
            };
        })();

    });
})();<|endoftext|>