<commit_before>(function() {
    $(document).ready(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
                for(i = 0; i < json.length; i++) {
                    div = thumbPosterWithInfoClickable(json[i]);
                    div.style.float = 'left';
                    $('#rss_Movies').append(div);
                }
            }).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(' '));
            $('#content').tabs({
                active: 1
            }); // Jump to tab 1 > links; tabs start with 0 = first tab
        };
        /*
         * 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';
            var divTitle = document.createElement('div');
            var div = document.createElement('div');
            div.className = 'thumbPoster';
            divTitle.title = title + ' (' + year + ')';
            divTitle.className = 'thumbPosterTitle';
            //div.style.backgroundImage = 'url(' + imageUrl + ')';
            divTitle.textContent = title;
            if(imageUrl === 'http://image.tmdb.org/t/p/w500null' || (/poster_default/).test(imageUrl)) {
                div.width = '10vw';
                div.height = div.offsetWidth * 1.3;
                div.appendChild(divTitle);

            } else {
                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 res = resolutions;
            var divRes = document.createElement('div');
            divRes.className = 'resolutionBar';
            divRes.textContent = res.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() {
                    // Jump to tab 1 > links; tabs start with 0 = first tab
                    $('#content').tabs({
                        active: 1
                    });
                    $('#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('div');
            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 span = document.createElement('span');
            span.textContent = 'remove';
            span.title = 'don\'t display this movie anymore.';
            span.className = 'hyperlink';
            span.onclick = function() {
                $.getJSON('/movie/' + id + '/hide', function(data) {
                    msg.set('Movie will not be shown anymore!', 'fadeout');
                    $('#content').tabs({
                        active: 0
                    }); // Jump to tab 1 > links
                    thumbDiv.parentNode.removeChild(thumbDiv);
                });
            }
            return span;
        };

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

        /*
         * 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 server';
                cloud.onclick = (function(link) {
                    return function() {
                        console.log(link);
                        plowdown(link);
                    };
                })(link);
                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) {
                $('#rssLinks').tabs({
                    active: 1
                });
            } else $('#rssLinks').tabs({
                active: 0
            });
            // Update Tab-title counter
            for(var i in extensions) {
                $('#rssLinks ul:first li:eq(' + (Object.keys(extensions)).indexOf(i) + ') a').text(i + '(' + extensions[i] + ')');
            }
        };
    });
})();<commit_msg>fluid css<commit_after>(function() {
    $(document).ready(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
                for(i = 0; i < json.length; i++) {
                    div = thumbPosterWithInfoClickable(json[i]);
                    div.style.float = 'left';
                    $('#rss_Movies').append(div);
                }
            }).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(' '));
            $('#content').tabs({
                active: 1
            }); // Jump to tab 1 > links; tabs start with 0 = first tab
        };
        /*
         * 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';
            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' || (/poster_default/).test(imageUrl)) {
                div.width = '10vw';
                div.minHeight = '50px';
                div.appendChild(divTitle);

            } else {
                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 res = resolutions;
            var divRes = document.createElement('div');
            divRes.className = 'resolutionBar';
            divRes.textContent = res.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() {
                    // Jump to tab 1 > links; tabs start with 0 = first tab
                    $('#content').tabs({
                        active: 1
                    });
                    $('#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('div');
            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 span = document.createElement('span');
            span.textContent = 'remove';
            span.title = 'don\'t display this movie anymore.';
            span.className = 'hyperlink';
            span.onclick = function() {
                $.getJSON('/movie/' + id + '/hide', function(data) {
                    msg.set('Movie will not be shown anymore!', 'fadeout');
                    $('#content').tabs({
                        active: 0
                    }); // Jump to tab 1 > links
                    thumbDiv.parentNode.removeChild(thumbDiv);
                });
            }
            return span;
        };

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

        /*
         * 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 server';
                cloud.onclick = (function(link) {
                    return function() {
                        console.log(link);
                        plowdown(link);
                    };
                })(link);
                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) {
                $('#rssLinks').tabs({
                    active: 1
                });
            } else $('#rssLinks').tabs({
                active: 0
            });
            // Update Tab-title counter
            for(var i in extensions) {
                $('#rssLinks ul:first li:eq(' + (Object.keys(extensions)).indexOf(i) + ') a').text(i + '(' + extensions[i] + ')');
            }
        };
    });
})();<|endoftext|>


<commit_before>var numPrompts = prompts.length;
var activePromptIndex = 3;
var storyIndex = 0;
var interval = 5000;

var particles = [];
var numParticles = 50;
var promptsArray = [];
var distance = 100;

var scrollCount = 0
var bReset = false;

var width;
var height;

var rectX, rectY, lenX, lenY;

// Socket.io server
// var socket = io.connect(socketServer)
var socket = io();

function refreshData () {
  socket.emit('refresh', {})
}

socket.on('refreshData', function (data) {
  console.log("refreshing data")
  app.stories = data
});

var Particle = {
  x: 0,
  y: 0,
  vx: 1,
  vy: 1,
  radius: 0.1,
  wander: 50,
  color: '#333',
  init: function(_x, _y) {
    this.x = _x;
    this.y = _y;
    this.theta = random( TWO_PI );
    this.alive = true;
  },
  update: function() {
    if (this.radius < 0.5) {
      this.radius += 0.01;
    }
    this.x += this.vx;
    this.y += this.vy;
    this.theta += random( -0.5, 0.5 ) * this.wander;
    this.vx += sin( this.theta ) * 0.1;
    this.vy += cos( this.theta ) * 0.1;
    if (this.x < 0 || this.x > width) {
      this.alive = false;
    }
    if (this.y < 0 || this.y > height) {
      this.alive = false;
    }
  },
  draw: function(ctx) {
    ctx.beginPath();
    ctx.arc( this.x, this.y, this.radius, 0, TWO_PI );
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

var Prompt = {
  x: 0,
  y: 0,
  newY: 0,
  text: '',
  color: 'rgba(155, 77, 202, 1)',
  alpha: 1,
  animating: true,
  init: function(_text, _x, _y) {
    this.text = _text;
    this.x = _x;
    this.y = _y;
    this.newY = _y;
  },
  setActive: function() {
    this.color = '#fff'
  },
  setInactive: function () {
    this.color = 'rgba(255, 255, 255, 0.7)'
  },
  update: function() {
    var dy = this.newY - this.y;
    this.y += dy * 0.10;
    if (abs(this.newY - this.y) < 1) {
      this.y = this.newY;
    }
    if (this.newY != this.y) {
      this.animating = true;
    } else {
      this.animating = false;
    }
  },
  draw: function(ctx) {
    var words = this.text.split(' ');
    var line = '';
    var maxWidth = 290;
    var lineHeight = 25;
    var x = this.x;
    var y = this.y;
    ctx.fillStyle = this.color,
    // ctx.fillStyle = 'rgba(77, 77, 77, 0.5)'
    ctx.globalAlpha = this.alpha;
    ctx.font = "23px Fedra Sans Pro";
    for(var n = 0; n < words.length; n++) {
      var testLine = line + words[n] + ' ';
      var metrics = ctx.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        ctx.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      }
      else {
        line = testLine;
      }
    }
    ctx.fillText(line, x, y);

    ctx.globalAlpha = 1;
  }
}

var app = new Vue({
  el: '#app',
  data: {
    currentIndex: 0,
    bShowStory: false,
    stories: stories,
    prompts: prompts,
    currentStories: [],
    story: ""
  },
  components: {
    'heading': {
      props: ['story'],
      template: "<transition name='slidefade'>

{{ story }}

</transition>"
    }
  },
  created: function() {
    console.log('vue ready')
    this.setupStories(activePromptIndex)
    this.updateStory(storyIndex)
    this.showStory()
  },
  methods: {
    setupStories: function (activePromptIndex) {
      this.currentStories = []
      var promptId = this.prompts[activePromptIndex]._id
      for (var i = 0; i < this.stories.length; i++) {
        if (this.stories[i].promptId == promptId) {
          this.currentStories.push(this.stories[i].text)
        }
      }
    },
    updateStory: function (storyIndex) {
      // TODO
      this.story = this.currentStories[storyIndex]
    },
    showStory: function() {
      this.bShowStory = true
    },
    hideStory: function() {
      this.bShowStory = false
    },
    toggleStory: function() {
      this.bShowStory = !(this.bShowStory)
    },
    clearStory: function() {
      this.story = ""
    }
  }
});

Sketch.create({
  container: document.getElementById( 'container' ),
  retina: 'auto',
  setup() {
    this.r = this.g = this.b = random(100, 200)
    this.startTime = this.millis;
    this.removed = false;
    app.updateStory(storyIndex);

    width = this.width;
    height = this.height;

    //Create a particle
    for (i = 0; i < numParticles; i++) {
      x = random ( this.width )
      y = random ( this.height )
      var particle = Object.create(Particle);
      particle.init(x, y)
      particles.push(particle)
    }

    //Create prompts
    var xPos = 50;
    var y = 0;
    var yStep = Math.floor(height/6)
    for (i = 0; i < prompts.length; i++) {
      x = xPos;
      var prompt = Object.create(Prompt)
      prompt.init(prompts[i].prompt, x, y)
      if (i === 3) {
        prompt.setActive()
        rectX = 0;
        rectY = y - 50;
        lenX = width*0.33;
        lenY = 120;
      }
      else {
        prompt.setInactive()
      }
      y += yStep;
      promptsArray.push(prompt)
    }

  },
  update() {
    var animInProgress = false;
    for (i = 0; i < promptsArray.length; i++) {
      if (promptsArray[i].animating) {
        animInProgress = true;
        break;
      }
    }

    if (!animInProgress && scrollCount == 0) {
      if (this.millis - this.startTime > 5000) {
        this.startTime = this.millis;
        app.toggleStory();
        if (app.bShowStory == false) {
          // Last prompt, reset
          if (activePromptIndex == numPrompts-1) {
            // TODO: reset
            bReset = true;
            activePromptIndex = 0;
            app.setupStories(activePromptIndex);
            scrollCount += 1;
          }
          else {
            storyIndex += 1;
            if (storyIndex >= app.currentStories.length) {
              storyIndex = 0;
              app.currentStories = [];
              var startIndex = activePromptIndex;
              while (app.currentStories.length == 0) {
                activePromptIndex += 1;
                var checkIndex = (activePromptIndex) % numPrompts;
                scrollCount += 1;
                app.setupStories(checkIndex);
                if (checkIndex == startIndex) {
                  scrollCount = 0;
                  activePromptIndex = startIndex;
                  bReset = true;
                  break;
                }
              }
            }
          }
          app.updateStory(storyIndex);
        }
      }
    }

    for (i = 0; i < particles.length; i++) {
      if (!particles[i].alive) {
        particles.splice(i, 1);
        this.removed = true;
      }
    }
    if (this.removed) {
      var numToAdd = numParticles - particles.length;
      for (i=0; i < numToAdd; i++) {
        x = random ( this.width )
        y = random ( this.height )
        var particle = Object.create(Particle)
        particle.init(x, y)
        particles.push(particle)
      }
      this.removed = false;
    }
    for (i = 0; i < particles.length; i++) {
      if (particles[i].alive) {
        particles[i].update();
      }
    }
    if (scrollCount > 0) {
      promptsArray.push(promptsArray.shift());
      promptsArray[promptsArray.length-1].y = promptsArray[promptsArray.length-1].newY = promptsArray[promptsArray.length-2].y + Math.floor(height/6);
      for (i = 0; i < promptsArray.length; i++) {
        promptsArray[i].newY -= Math.floor(height/6)
        if (i === 3) {
          promptsArray[i].setActive()
        }
        else {
          promptsArray[i].setInactive()
        }
      }
      scrollCount--;
    }

    if (bReset) {
      refreshData();
      bReset = false;
    }

    for (i = 0; i < promptsArray.length; i++) {
      promptsArray[i].update()
    }

  },
  mousemove() {
    this.r = 255 * (this.mouse.x / this.width)
    this.g = 255 * (this.mouse.y / this.height)
    this.b = 255 * abs(cos(PI * this.mouse.y / this.width))
  },
  draw() {
    this.fillStyle = '#fff'
    this.fillRect(0, 0, this.width, this.height)
    for (i = 0; i < particles.length; i++) {
      particles[i].draw(this)
    }

    // Draw a left column
    this.fillStyle = 'rgba(46, 45, 77, 0.95)'
    this.fillRect(0, 0, lenX, this.height)

    this.drawActivePromptRect()
    for (i = 0; i < promptsArray.length; i++) {
      promptsArray[i].draw(this)
    }
    for (i = 0; i < particles.length; i++) {
      for (j = i+1 ; j < particles.length; j++) {
        var dist = this.distance(particles[i].x, particles[i].y, particles[j].x, particles[j].y);
        if (dist < distance) {
          this.beginPath();
          this.moveTo(particles[i].x, particles[i].y);
          this.lineTo(particles[j].x, particles[j].y);
          this.lineWidth = 0.2;
          this.strokeStyle = '#333';
          this.stroke();
        }
      }
    }
  },
  distance(x1, y1, x2, y2) {
    return sqrt( pow((x1-x2),2) + pow((y1-y2),2) );
  },
  drawActivePromptRect() {
    this.fillStyle = 'rgba(155, 77, 202, 0.9)'
    this.fillRect(rectX, rectY, lenX, lenY)
  },
});<commit_msg>size changes for grad exhibition<commit_after>var numPrompts = prompts.length;
var activePromptIndex = 3;
var storyIndex = 0;
var interval = 5000;

var particles = [];
var numParticles = 50;
var promptsArray = [];
var distance = 100;

var scrollCount = 0
var bReset = false;

var width;
var height;

var rectX, rectY, lenX, lenY;

// Socket.io server
// var socket = io.connect(socketServer)
var socket = io();

function refreshData () {
  socket.emit('refresh', {})
}

socket.on('refreshData', function (data) {
  console.log("refreshing data")
  app.stories = data
});

var Particle = {
  x: 0,
  y: 0,
  vx: 1,
  vy: 1,
  radius: 0.1,
  wander: 50,
  color: '#333',
  init: function(_x, _y) {
    this.x = _x;
    this.y = _y;
    this.theta = random( TWO_PI );
    this.alive = true;
  },
  update: function() {
    if (this.radius < 0.5) {
      this.radius += 0.01;
    }
    this.x += this.vx;
    this.y += this.vy;
    this.theta += random( -0.5, 0.5 ) * this.wander;
    this.vx += sin( this.theta ) * 0.1;
    this.vy += cos( this.theta ) * 0.1;
    if (this.x < 0 || this.x > width) {
      this.alive = false;
    }
    if (this.y < 0 || this.y > height) {
      this.alive = false;
    }
  },
  draw: function(ctx) {
    ctx.beginPath();
    ctx.arc( this.x, this.y, this.radius, 0, TWO_PI );
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

var Prompt = {
  x: 0,
  y: 0,
  newY: 0,
  text: '',
  color: 'rgba(155, 77, 202, 1)',
  alpha: 1,
  animating: true,
  init: function(_text, _x, _y) {
    this.text = _text;
    this.x = _x;
    this.y = _y;
    this.newY = _y;
  },
  setActive: function() {
    this.color = '#fff'
  },
  setInactive: function () {
    this.color = 'rgba(255, 255, 255, 0.7)'
  },
  update: function() {
    var dy = this.newY - this.y;
    this.y += dy * 0.10;
    if (abs(this.newY - this.y) < 1) {
      this.y = this.newY;
    }
    if (this.newY != this.y) {
      this.animating = true;
    } else {
      this.animating = false;
    }
  },
  draw: function(ctx) {
    var words = this.text.split(' ');
    var line = '';
    var maxWidth = 400;
    var lineHeight = 32;
    var x = this.x;
    var y = this.y;
    ctx.fillStyle = this.color,
    // ctx.fillStyle = 'rgba(77, 77, 77, 0.5)'
    ctx.globalAlpha = this.alpha;
    ctx.font = "28px Fedra Sans Pro";
    for(var n = 0; n < words.length; n++) {
      var testLine = line + words[n] + ' ';
      var metrics = ctx.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        ctx.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      }
      else {
        line = testLine;
      }
    }
    ctx.fillText(line, x, y);

    ctx.globalAlpha = 1;
  }
}

var app = new Vue({
  el: '#app',
  data: {
    currentIndex: 0,
    bShowStory: false,
    stories: stories,
    prompts: prompts,
    currentStories: [],
    story: ""
  },
  components: {
    'heading': {
      props: ['story'],
      template: "<transition name='slidefade'>

{{ story }}

</transition>"
    }
  },
  created: function() {
    console.log('vue ready')
    this.setupStories(activePromptIndex)
    this.updateStory(storyIndex)
    this.showStory()
  },
  methods: {
    setupStories: function (activePromptIndex) {
      this.currentStories = []
      var promptId = this.prompts[activePromptIndex]._id
      for (var i = 0; i < this.stories.length; i++) {
        if (this.stories[i].promptId == promptId) {
          this.currentStories.push(this.stories[i].text)
        }
      }
    },
    updateStory: function (storyIndex) {
      // TODO
      this.story = this.currentStories[storyIndex]
    },
    showStory: function() {
      this.bShowStory = true
    },
    hideStory: function() {
      this.bShowStory = false
    },
    toggleStory: function() {
      this.bShowStory = !(this.bShowStory)
    },
    clearStory: function() {
      this.story = ""
    }
  }
});

Sketch.create({
  container: document.getElementById( 'container' ),
  retina: 'auto',
  setup() {
    this.r = this.g = this.b = random(100, 200)
    this.startTime = this.millis;
    this.removed = false;
    app.updateStory(storyIndex);

    width = this.width;
    height = this.height;

    //Create a particle
    for (i = 0; i < numParticles; i++) {
      x = random ( this.width )
      y = random ( this.height )
      var particle = Object.create(Particle);
      particle.init(x, y)
      particles.push(particle)
    }

    //Create prompts
    var xPos = 50;
    var y = 0;
    var yStep = Math.floor(height/6)
    for (i = 0; i < prompts.length; i++) {
      x = xPos;
      var prompt = Object.create(Prompt)
      prompt.init(prompts[i].prompt, x, y)
      if (i === 3) {
        prompt.setActive()
        rectX = 0;
        rectY = y - 50;
        lenX = width*0.3;
        lenY = 120;
      }
      else {
        prompt.setInactive()
      }
      y += yStep;
      promptsArray.push(prompt)
    }

  },
  update() {
    var animInProgress = false;
    for (i = 0; i < promptsArray.length; i++) {
      if (promptsArray[i].animating) {
        animInProgress = true;
        break;
      }
    }

    if (!animInProgress && scrollCount == 0) {
      if (this.millis - this.startTime > 5000) {
        this.startTime = this.millis;
        app.toggleStory();
        if (app.bShowStory == false) {
          // Last prompt, reset
          if (activePromptIndex == numPrompts-1) {
            // TODO: reset
            bReset = true;
            activePromptIndex = 0;
            app.setupStories(activePromptIndex);
            scrollCount += 1;
          }
          else {
            storyIndex += 1;
            if (storyIndex >= app.currentStories.length) {
              storyIndex = 0;
              app.currentStories = [];
              var startIndex = activePromptIndex;
              while (app.currentStories.length == 0) {
                activePromptIndex += 1;
                var checkIndex = (activePromptIndex) % numPrompts;
                scrollCount += 1;
                app.setupStories(checkIndex);
                if (checkIndex == startIndex) {
                  scrollCount = 0;
                  activePromptIndex = startIndex;
                  bReset = true;
                  break;
                }
              }
            }
          }
          app.updateStory(storyIndex);
        }
      }
    }

    for (i = 0; i < particles.length; i++) {
      if (!particles[i].alive) {
        particles.splice(i, 1);
        this.removed = true;
      }
    }
    if (this.removed) {
      var numToAdd = numParticles - particles.length;
      for (i=0; i < numToAdd; i++) {
        x = random ( this.width )
        y = random ( this.height )
        var particle = Object.create(Particle)
        particle.init(x, y)
        particles.push(particle)
      }
      this.removed = false;
    }
    for (i = 0; i < particles.length; i++) {
      if (particles[i].alive) {
        particles[i].update();
      }
    }
    if (scrollCount > 0) {
      promptsArray.push(promptsArray.shift());
      promptsArray[promptsArray.length-1].y = promptsArray[promptsArray.length-1].newY = promptsArray[promptsArray.length-2].y + Math.floor(height/6);
      for (i = 0; i < promptsArray.length; i++) {
        promptsArray[i].newY -= Math.floor(height/6)
        if (i === 3) {
          promptsArray[i].setActive()
        }
        else {
          promptsArray[i].setInactive()
        }
      }
      scrollCount--;
    }

    if (bReset) {
      refreshData();
      bReset = false;
    }

    for (i = 0; i < promptsArray.length; i++) {
      promptsArray[i].update()
    }

  },
  mousemove() {
    this.r = 255 * (this.mouse.x / this.width)
    this.g = 255 * (this.mouse.y / this.height)
    this.b = 255 * abs(cos(PI * this.mouse.y / this.width))
  },
  draw() {
    this.fillStyle = '#fff'
    this.fillRect(0, 0, this.width, this.height)
    for (i = 0; i < particles.length; i++) {
      particles[i].draw(this)
    }

    // Draw a left column
    this.fillStyle = 'rgba(46, 45, 77, 0.95)'
    this.fillRect(0, 0, lenX, this.height)

    this.drawActivePromptRect()
    for (i = 0; i < promptsArray.length; i++) {
      promptsArray[i].draw(this)
    }
    for (i = 0; i < particles.length; i++) {
      for (j = i+1 ; j < particles.length; j++) {
        var dist = this.distance(particles[i].x, particles[i].y, particles[j].x, particles[j].y);
        if (dist < distance) {
          this.beginPath();
          this.moveTo(particles[i].x, particles[i].y);
          this.lineTo(particles[j].x, particles[j].y);
          this.lineWidth = 0.2;
          this.strokeStyle = '#333';
          this.stroke();
        }
      }
    }
  },
  distance(x1, y1, x2, y2) {
    return sqrt( pow((x1-x2),2) + pow((y1-y2),2) );
  },
  drawActivePromptRect() {
    this.fillStyle = 'rgba(155, 77, 202, 0.9)'
    this.fillRect(rectX, rectY, lenX, lenY)
  },
});<|endoftext|>


<commit_before>require_login = function(e){
  e.preventDefault()
  var url = null
  if($(this).is('a')){
    url = $(this).attr('href')
  } else {
    url = $('input[type=submit]').parentsUntil('form').parent().attr('action')
  }
  $('#return_to').val(url)
  $('#login_overlay').show()
  $('.another_social').hide();
  $('#login').fadeIn()
}
var return_to = null
$('#login_link,#signup_link,.login_link').live('click', function(e){
  e.preventDefault()
  $('#return_to').val(location.href)
  $('#login_overlay').show()
  $('.another_social').hide();
  $('#login').fadeIn()
})
if($('#login').length > 0){
  $('#new_project_link,#ghost_project_link').click(require_login)
}
$('#login .close').click(function(e){
  e.preventDefault()
  $('#return_to').val(null)
  $('#login').hide()
  $('#login_overlay').hide()
})
$('a.provider').click(function(e){
  e.preventDefault()
  if($(this).hasClass('disabled'))
    return
  $('a.provider').addClass('disabled')
  $('#provider').val($(this).attr('href'))
  $('#login form').submit()
})

$("#login_with_another_social").click(function(e){
  e.preventDefault();
  if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
      $('fieldset.remember_me_social').show();
    })
  } else if ($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
    })
  } else if ($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
    })
  } else {
    $('.another_social').slideDown('fast');
  }
  $('fieldset.remember_me_social').show();
});

$("#login_with_mail").click(function(e){
  e.preventDefault();
  if ($('.another_social').css('display') == 'block') {
    $('.another_social').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else if ($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else if ($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else {
    $('#login_form_with_email').slideDown('fast');
  }

  // if($('.another_social').css('display') == 'block') {
  //   $('.another_social').slideUp('fast', function(){
  //     $('#login_form_with_email').slideDown('fast');
  //   })
  // } else {
  //   $('#login_form_with_email').slideDown('fast');
  // }
  $('fieldset.remember_me_social').hide();
});

$('a.new_registration_link').click(function(e){
  e.preventDefault();
  if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('#new_email_account').slideDown('fast');
    });
  } else if($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#new_email_account').slideDown('fast');
    });
  } else { $('#new_email_account').slideDown('fast'); }
});

$('a.new_session_link').click(function(e){
  e.preventDefault();
  if($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    });
  } else if($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    });
  } else { $('#login_form_with_email').slideDown('fast'); }
});

$('a.forgot_password_link').click(function(e){
  e.preventDefault();
  if($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#forgot_password_form').slideDown('fast');
    });
  } else if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('#forgot_password_form').slideDown('fast');
    });
  } else { $('#forgot_password_form').slideDown('fast'); }
});<commit_msg>fixed bug when user click to login with another social network and calls forgot_password actions<commit_after>require_login = function(e){
  e.preventDefault()
  var url = null
  if($(this).is('a')){
    url = $(this).attr('href')
  } else {
    url = $('input[type=submit]').parentsUntil('form').parent().attr('action')
  }
  $('#return_to').val(url)
  $('#login_overlay').show()
  $('.another_social').hide();
  $('#login').fadeIn()
}
var return_to = null
$('#login_link,#signup_link,.login_link').live('click', function(e){
  e.preventDefault()
  $('#return_to').val(location.href)
  $('#login_overlay').show()
  $('.another_social').hide();
  $('#login').fadeIn()
})
if($('#login').length > 0){
  $('#new_project_link,#ghost_project_link').click(require_login)
}
$('#login .close').click(function(e){
  e.preventDefault()
  $('#return_to').val(null)
  $('#login').hide()
  $('#login_overlay').hide()
})
$('a.provider').click(function(e){
  e.preventDefault()
  if($(this).hasClass('disabled'))
    return
  $('a.provider').addClass('disabled')
  $('#provider').val($(this).attr('href'))
  $('#login #social_info form').submit()
})

$("#login_with_another_social").click(function(e){
  e.preventDefault();
  if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
      $('fieldset.remember_me_social').show();
    })
  } else if ($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
    })
  } else if ($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('.another_social').slideDown('fast');
    })
  } else {
    $('.another_social').slideDown('fast');
  }
  $('fieldset.remember_me_social').show();
});

$("#login_with_mail").click(function(e){
  e.preventDefault();
  if ($('.another_social').css('display') == 'block') {
    $('.another_social').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else if ($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else if ($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    })
  } else {
    $('#login_form_with_email').slideDown('fast');
  }

  // if($('.another_social').css('display') == 'block') {
  //   $('.another_social').slideUp('fast', function(){
  //     $('#login_form_with_email').slideDown('fast');
  //   })
  // } else {
  //   $('#login_form_with_email').slideDown('fast');
  // }
  $('fieldset.remember_me_social').hide();
});

$('a.new_registration_link').click(function(e){
  e.preventDefault();
  if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('#new_email_account').slideDown('fast');
    });
  } else if($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#new_email_account').slideDown('fast');
    });
  } else { $('#new_email_account').slideDown('fast'); }
});

$('a.new_session_link').click(function(e){
  e.preventDefault();
  if($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    });
  } else if($('#forgot_password_form').css('display') == 'block') {
    $('#forgot_password_form').slideUp('fast', function(){
      $('#login_form_with_email').slideDown('fast');
    });
  } else { $('#login_form_with_email').slideDown('fast'); }
});

$('a.forgot_password_link').click(function(e){
  e.preventDefault();
  if($('#new_email_account').css('display') == 'block') {
    $('#new_email_account').slideUp('fast', function(){
      $('#forgot_password_form').slideDown('fast');
    });
  } else if($('#login_form_with_email').css('display') == 'block') {
    $('#login_form_with_email').slideUp('fast', function(){
      $('#forgot_password_form').slideDown('fast');
    });
  } else { $('#forgot_password_form').slideDown('fast'); }
});<|endoftext|>


<commit_before>/* embed.js View

Embed reddit in external websites

//ex http://localhost:8002/embed/url=http://imgur.com/XZvyRhU&as=4&fffff=123

*/
define(['App', 'underscore', 'backbone', 'hbs!template/embed', 'hbs!template/blank', 'view/basem-view', 'collection/info'],
    function(App, _, Backbone, Tmpl, BlankTmpl, BaseView, InfoCollection) {
        return BaseView.extend({
            template: Tmpl,
            events: {
                'click .gotoSubmit': 'gotoSubmit'
            },
            ui: {
                embedStatus: '#embedStatus',
                submitBtn: '#submitBtn'
            },
            initialize: function(options) {
                _.bindAll(this);
                this.q = this.getUrlParameters()
                if (typeof this.q.url !== 'undefined') {
                    this.q.url = decodeURIComponent(this.q.url)
                }
                this.searchCollection = null
                this.urlCollection = null

                this.inputTimer = 0 //keeps track of user input and when they stop input it performs a search
                this.lastTitleInput = null //keeps track of the last input in keyboard on title field

                this.setupOptions()

            },
            onRender: function() {
                //hide the header with CSS because I am not sure if we still need it or not
                // $('#theHeader').hide()

                this.urlStatus() //find out if the link has already been submitted

                //option passed in
                if (typeof this.q.backgroundColor !== 'undefined') {
                    $('body').css('background-color', '#' + this.q.backgroundColor)
                }

            },
            onBeforeClose: function() {
                $('#theHeader').show()
            },

            setupOptions: function() {
                this.submitPostImg = this.q.submitPostImg || 'http://www.reddit.com/static/spreddit11.gif'
                this.postSortOrder = this.q.postSortOrder || 'mostUpvoted'

            },
            //backbone cant parse the complex URL we are passing it, use vanillaJS
            getUrlParameters: function(b) {
                var qsParm = []
                var query = window.location.search.substring(1);
                var parms = query.split('&');
                for (var i = 0; i < parms.length; i++) {
                    var pos = parms[i].indexOf('=');
                    if (pos > 0) {
                        var key = parms[i].substring(0, pos);
                        var val = parms[i].substring(pos + 1);
                        qsParm[key] = val;
                    }
                }
                return qsParm;
            },

            selectPostWithMostUpvoted: function(gotoPost) {
                this.urlCollection.each(function(post) {
                    //redirect the user to the post with the highest number of comments
                    if (post.get('num_comments') >= gotoPost.get('num_comments')) {
                        gotoPost = post
                    }
                })
                return gotoPost;
            },
            selectNewestPost: function(gotoPost, cb) {
                var self = this;
                var count = 0;
                this.urlCollection.each(function(tmpPost) {
                    count++;
                    // for (var i = 0; i < this.urlCollection.length; i++) {
                    // var tmpPost = this.urlCollection.models[i];
                    var newestDate = moment.unix(gotoPost.get('created_utc'))
                    var tmpDate = moment.unix(tmpPost.get('created_utc'))

                    //redirect the user to the post with the highest number of comments
                    if (tmpDate > newestDate) {
                        gotoPost = tmpPost
                    }
                    //}

                    if (count == self.urlCollection.length) {
                        cb(gotoPost)
                    }

                })
                //return gotoPost;
            },
            urlStatus: function() {
                var self = this
                self.ui.embedStatus.addClass('loadingSingle')

                if (this.validURL(this.q.url)) {

                    this.urlCollection = new InfoCollection([], {
                        linkUrl: this.q.url

                    });

                    this.urlCollection.fetch({
                        success: function(data) {
                            var gotoPost;
                            var postsLength = data.length

                            if (postsLength > 0) {

                                gotoPost = self.urlCollection.first()

                                if (self.postSortOrder === 'mostUpvoted') {
                                    return self.selectPostWithMostUpvoted(gotoPost, self.successPostFound)
                                } else if (self.postSortOrder === 'newest') {
                                    return self.selectNewestPost(gotoPost, self.successPostFound)
                                }

                            } else {
                                self.postNotFound();
                            }
                        },
                        error: function(data) {
                            console.log("ERROR inrequest details: ", data);
                            //self.ui.embedStatus.html('unable to fetch data from reddit api').removeClass('loadingSingle')
                            self.newIframeSize(0, 0)
                        }
                    })

                } else {
                    self.ui.embedStatus.html('please enter a valid url').removeClass('loadingSingle')
                }
            },

            successPostFound: function(gotoPost) {
                this.newIframeSize(null, null)

                Backbone.history.navigate(gotoPost.get('permalink'), {
                    trigger: true
                });
            },

            postNotFound: function() {
                this.showSubmitThisToReddit();
                $('#theHeader').hide()
                this.newIframeSize(80, null)
            },
            showSubmitThisToReddit: function() {

                var submitBtn = ''
                submitBtn += '
 Post not found on reddit.
 Be the first to submit

';

                this.ui.submitBtn.html(submitBtn);
                this.newIframeSize(null, null)
            },
            gotoSubmit: function() {
                //example url:  /submit/url=http://dudelol.com/now-that?asdasd=asd

                //change parent size
                this.newIframeSize(600, null)

                var url = '/submit/url=' + this.q.url
                Backbone.history.navigate(url, {
                    trigger: true
                });
            },
            // tellParentWeLoaded: function() {
            //     var postData = {
            //         loadDesiredHeight: true
            //     }
            //     parent.postMessage(postData, "*");
            // },
            // newParentHeight: function(height) {

            //     var postData = {
            //         newHeight: height
            //     }
            //     parent.postMessage(postData, "*");

            // },
            newIframeSize: function(height, width) {
                var postData = {
                    newHeight: height,
                    newWidth: width
                }
                parent.postMessage(postData, "*");
            }

        });
    });<commit_msg>added most comments options<commit_after>/* embed.js View

Embed reddit in external websites

//ex http://localhost:8002/embed/url=http://imgur.com/XZvyRhU&as=4&fffff=123

*/
define(['App', 'underscore', 'backbone', 'hbs!template/embed', 'hbs!template/blank', 'view/basem-view', 'collection/info'],
    function(App, _, Backbone, Tmpl, BlankTmpl, BaseView, InfoCollection) {
        return BaseView.extend({
            template: Tmpl,
            events: {
                'click .gotoSubmit': 'gotoSubmit'
            },
            ui: {
                embedStatus: '#embedStatus',
                submitBtn: '#submitBtn'
            },
            initialize: function(options) {
                _.bindAll(this);
                this.q = this.getUrlParameters()
                if (typeof this.q.url !== 'undefined') {
                    this.q.url = decodeURIComponent(this.q.url)
                }
                this.searchCollection = null
                this.urlCollection = null

                this.inputTimer = 0 //keeps track of user input and when they stop input it performs a search
                this.lastTitleInput = null //keeps track of the last input in keyboard on title field

                this.setupOptions()

            },
            onRender: function() {
                //hide the header with CSS because I am not sure if we still need it or not
                // $('#theHeader').hide()

                this.urlStatus() //find out if the link has already been submitted

                //option passed in
                if (typeof this.q.backgroundColor !== 'undefined') {
                    $('body').css('background-color', '#' + this.q.backgroundColor)
                }

            },
            onBeforeClose: function() {
                $('#theHeader').show()
            },

            setupOptions: function() {
                this.submitPostImg = this.q.submitPostImg || 'http://www.reddit.com/static/spreddit11.gif'
                this.postSortOrder = this.q.postSortOrder || 'mostUpvoted'

            },
            //backbone cant parse the complex URL we are passing it, use vanillaJS
            getUrlParameters: function(b) {
                var qsParm = []
                var query = window.location.search.substring(1);
                var parms = query.split('&');
                for (var i = 0; i < parms.length; i++) {
                    var pos = parms[i].indexOf('=');
                    if (pos > 0) {
                        var key = parms[i].substring(0, pos);
                        var val = parms[i].substring(pos + 1);
                        qsParm[key] = val;
                    }
                }
                return qsParm;
            },

            selectPostWithMostUpvoted: function(gotoPost, cb) {
                var self = this;
                var count = 0;
                this.urlCollection.each(function(post) {
                    count++;
                    //redirect the user to the post with the highest number of comments
                    if (post.get('score') >= gotoPost.get('score')) {
                        gotoPost = post
                    }

                    if (count == self.urlCollection.length) {
                        cb(gotoPost)
                    }

                })

            },
            selectPostWithMostComments: function(gotoPost, cb) {
                var self = this;
                var count = 0;
                this.urlCollection.each(function(post) {
                    count++;
                    //redirect the user to the post with the highest number of comments
                    if (post.get('num_comments') >= gotoPost.get('num_comments')) {
                        gotoPost = post
                    }

                    if (count == self.urlCollection.length) {
                        cb(gotoPost)
                    }

                })

            },
            selectNewestPost: function(gotoPost, cb) {
                var self = this;
                var count = 0;
                this.urlCollection.each(function(tmpPost) {
                    count++;
                    var newestDate = moment.unix(gotoPost.get('created_utc'))
                    var tmpDate = moment.unix(tmpPost.get('created_utc'))

                    //redirect the user to the newest post
                    if (tmpDate > newestDate) {
                        gotoPost = tmpPost
                    }

                    if (count == self.urlCollection.length) {
                        cb(gotoPost)
                    }

                })
            },
            urlStatus: function() {
                var self = this
                self.ui.embedStatus.addClass('loadingSingle')

                if (this.validURL(this.q.url)) {

                    this.urlCollection = new InfoCollection([], {
                        linkUrl: this.q.url

                    });

                    this.urlCollection.fetch({
                        success: function(data) {
                            var gotoPost;
                            var postsLength = data.length

                            if (postsLength > 0) {

                                gotoPost = self.urlCollection.first()

                                if (self.postSortOrder === 'mostUpvoted') {
                                    return self.selectPostWithMostUpvoted(gotoPost, self.successPostFound)
                                } else if (self.postSortOrder === 'newest') {
                                    return self.selectNewestPost(gotoPost, self.successPostFound)
                                } else if (self.postSortOrder === 'mostComments') {
                                    return self.selectPostWithMostComments(gotoPost, self.successPostFound)
                                }

                            } else {
                                self.postNotFound();
                            }
                        },
                        error: function(data) {
                            console.log("ERROR inrequest details: ", data);
                            //self.ui.embedStatus.html('unable to fetch data from reddit api').removeClass('loadingSingle')
                            self.newIframeSize(0, 0)
                        }
                    })

                } else {
                    self.ui.embedStatus.html('please enter a valid url').removeClass('loadingSingle')
                }
            },

            successPostFound: function(gotoPost) {
                this.newIframeSize(null, null)

                Backbone.history.navigate(gotoPost.get('permalink'), {
                    trigger: true
                });
            },

            postNotFound: function() {
                this.showSubmitThisToReddit();
                $('#theHeader').hide()
                this.newIframeSize(80, null)
            },
            showSubmitThisToReddit: function() {

                var submitBtn = ''
                submitBtn += '
 Post not found on reddit.
 Be the first to submit

';

                this.ui.submitBtn.html(submitBtn);
                this.newIframeSize(null, null)
            },
            gotoSubmit: function() {
                //example url:  /submit/url=http://dudelol.com/now-that?asdasd=asd

                //change parent size
                this.newIframeSize(600, null)

                var url = '/submit/url=' + this.q.url
                Backbone.history.navigate(url, {
                    trigger: true
                });
            },
            // tellParentWeLoaded: function() {
            //     var postData = {
            //         loadDesiredHeight: true
            //     }
            //     parent.postMessage(postData, "*");
            // },
            // newParentHeight: function(height) {

            //     var postData = {
            //         newHeight: height
            //     }
            //     parent.postMessage(postData, "*");

            // },
            newIframeSize: function(height, width) {
                var postData = {
                    newHeight: height,
                    newWidth: width
                }
                parent.postMessage(postData, "*");
            }

        });
    });<|endoftext|>


<commit_before>var routeControl = null;
var showControl = false;

var line = null;

function convertirKM(distancia)
{
    var distanciaConvertida = '';
    if (distancia >= 1000)
    {
        distancia = distancia/1000;
        distanciaConvertida = distancia.toString() + ' km';
    }
    else
        distanciaConvertida = distancia.toString() + ' m';

    return distanciaConvertida;
}

function borrar()
{
    if (marker1 !== null)
    {
        mapa.removeLayer(marker1);
        marker1 = null;
    }

    if (marker2 !== null)
    {
        mapa.removeLayer(marker2);
        marker2 = null;
    }

    waypoints.length = 0;
    coords.length = 0;

    if (line !== null)
        mapa.removeLayer(line);

}

function borrarRuta()
{
    routeControl.getPlan().setWaypoints([]);
}

function esconderMostrar()
{
    if (showControl)  // control despleagdo
        {
            routeControl.hide();
            showControl = false;
            /*$(".btnBorrar").css({
                       'right': '11px', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       });    */
        }
        else
        {
            routeControl.show();
            showControl = true;
            /*$(".btnBorrar").css({
                      'right': '27%', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       }); */
        }
}

function displayRoutingControl()
{

    if (routeControl == null)
    {

        crearControlRouting();

         /*$(".btnBorrar").css({
                       'display': 'inline',
                       'right': '37%', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       });        */
        showControl = true;
    }

}

function removeRouting()
{
    if (routeControl != null)
    {
        mapa.removeControl(routeControl);  //remueve el camino tb
        routeControl = null;
        /*$(".btnBorrar").css({
                       'display': 'none',
                       'right': '-44px', //antes 37% 6
                       'left': 'auto',
                      'top': '70px' //antes 13%*  5
                       });     */
    }
}

// function crearControlRouting() {
//
//       routeControl = L.Routing.control({
//
//
//         router: L.Routing.mapzen('mapzen-3indRB', {
//             costing: 'bicycle',
//             directions_options: {
//               language: 'es'
//             }
//         }),
//
//         plan: L.Routing.plan([], {
//                 geocoder: L.Control.Geocoder.nominatim({
//                 geocodingQueryParams: { countrycodes: 'uy'}
//               }),
//               reverseWaypoints: true,
//               city:'Montevideo',
//               language: 'sp'
//             }),
//         lineOptions: {
//             styles:
//                 [
//                     {color: 'black', opacity: 0.15, weight: 9}, //sombra
//                     {color: 'white', opacity: 0.8, weight: 6}, // Contorno
//                     {color: 'red', opacity: 1, weight: 4}] // Centro
//        },
//        summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance}
',
//        language: 'sp',
//         //city: 'Montevideo',   //si no va plan, debe agregarse si se desea afinar búsquedas.
//         routeWhileDragging: true,
//         waypointMode:  'snap',
//         collapsible: true  //nuevo
//     }).addTo(mapa);
//
// }

function crearControlRouting() {
    routeControl = L.Routing.control({
    routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
  //  waypoints: routingData.waypoints,
  // You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)

  plan: L.Routing.plan([], {
                   geocoder: L.Control.Geocoder.nominatim({
                   geocodingQueryParams: { countrycodes: 'uy'}
                 }),
                 reverseWaypoints: true,
                 city:'Montevideo',
                 language: 'sp'
               }),
    lineOptions: {
            styles:
                [
                  {color: 'black', opacity: 0.15, weight: 9}, //sombra
                  {color: 'white', opacity: 0.8, weight: 6}, // Contorno
                  {color: 'red', opacity: 1, weight: 4}] // Centro
       },

    router: L.Routing.mapzen('mapzen-3indRB', {
                 costing: 'bicycle',
                directions_options: {
                    language: 'es'
                  }
    }),

    collapsible: true,
    formatter: new L.Routing.mapzenFormatter(),
    //summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance} info {costing}
',
    summaryTemplate:'
{name}

{distance}
'
    //summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance}
',
}).addTo(mapa);

}

function calcRoute()  // esto para cuando no se usa el control
{
    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((marker1 !== null)  && (marker2 !== null))
    {
        waypoints.push({latLng: marker1.getLatLng()});
        waypoints.push({latLng: marker2.getLatLng()});
        router.route(waypoints, function(err, routes) {
         if (line) {
             map.removeLayer(line);
         }

         if (err) {
             alert(err);
         } else {
             coords = routes[0].coordinates;
             waysp = routes[0].waypoints;
             alert(routes[0].summary.totalTime);
             alert(routes[0].summary.totalDistance);
             line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: 'red', opacity: 1, weight: 4}]}).addTo(map);

         }
     });

    }
    else
        alert("Se necesita el par Origen-Destino para calcular la ruta");
}

function rutaAB(latA, latB)  // esto para cuando no se usa el control
{
    var waypoints = [];
    var coords = [];
    var waysp = [];

    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((latA != null) && (latB != null))
    //if ((marker1 !== null)  && (marker2 !== null))
    {

        //var router = L.Routing.osrm();

        var latlngA = L.Routing.waypoint(latA);
        var latlngB = L.Routing.waypoint(latB);
        // waypoints.push({latLng: latA});
        // waypoints.push({latLng: latB});
        waypoints.push(latlngA);
        waypoints.push(latlngB);

        var routes = null;

        //routes: L.Routing.mapzen('mapzen-3indRB', {costing: 'bicycle'});

        routes = L.Routing.osrmv1({addWaypoints: false});
        //routes: L.Routing.mapzen('mapzen-3indRB', {
            // addWaypoints: false,
          //  costing: 'bicycle'
        //})

        routes.route(waypoints, function(err, routes) {
             if (line) {
                 mapa.removeLayer(line);
             }

             if (err) {
                 console.log(err);
             }
             else {

                 coords = routes[0].coordinates;
                 waysp = routes[0].waypoints;
                 line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);

                 var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
                 popup = L.popup({offset: L.point(0, -30)})
                        .setLatLng(latB)
                        .setContent('
Distancia: ' + distanciaCerc + '
')
                        .openOn(mapa);

             }
       });

    }
    else
    {
        alert("Se necesita el par Origen-Destino para calcular la ruta");

    }

}
<commit_msg>agregando opciones de ruteo<commit_after>var routeControl = null;
var showControl = false;

var line = null;

function convertirKM(distancia)
{
    var distanciaConvertida = '';
    if (distancia >= 1000)
    {
        distancia = distancia/1000;
        distanciaConvertida = distancia.toString() + ' km';
    }
    else
        distanciaConvertida = distancia.toString() + ' m';

    return distanciaConvertida;
}

function borrar()
{
    if (marker1 !== null)
    {
        mapa.removeLayer(marker1);
        marker1 = null;
    }

    if (marker2 !== null)
    {
        mapa.removeLayer(marker2);
        marker2 = null;
    }

    waypoints.length = 0;
    coords.length = 0;

    if (line !== null)
        mapa.removeLayer(line);

}

function borrarRuta()
{
    routeControl.getPlan().setWaypoints([]);
}

function esconderMostrar()
{
    if (showControl)  // control despleagdo
        {
            routeControl.hide();
            showControl = false;
            /*$(".btnBorrar").css({
                       'right': '11px', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       });    */
        }
        else
        {
            routeControl.show();
            showControl = true;
            /*$(".btnBorrar").css({
                      'right': '27%', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       }); */
        }
}

function displayRoutingControl()
{

    if (routeControl == null)
    {

        crearControlRouting();

         /*$(".btnBorrar").css({
                       'display': 'inline',
                       'right': '37%', //antes 37% 6
                      'top': '70px' //antes 13%*  5
                       });        */
        showControl = true;
    }

}

function removeRouting()
{
    if (routeControl != null)
    {
        mapa.removeControl(routeControl);  //remueve el camino tb
        routeControl = null;
        /*$(".btnBorrar").css({
                       'display': 'none',
                       'right': '-44px', //antes 37% 6
                       'left': 'auto',
                      'top': '70px' //antes 13%*  5
                       });     */
    }
}

// function crearControlRouting() {
//
//       routeControl = L.Routing.control({
//
//
//         router: L.Routing.mapzen('mapzen-3indRB', {
//             costing: 'bicycle',
//             directions_options: {
//               language: 'es'
//             }
//         }),
//
//         plan: L.Routing.plan([], {
//                 geocoder: L.Control.Geocoder.nominatim({
//                 geocodingQueryParams: { countrycodes: 'uy'}
//               }),
//               reverseWaypoints: true,
//               city:'Montevideo',
//               language: 'sp'
//             }),
//         lineOptions: {
//             styles:
//                 [
//                     {color: 'black', opacity: 0.15, weight: 9}, //sombra
//                     {color: 'white', opacity: 0.8, weight: 6}, // Contorno
//                     {color: 'red', opacity: 1, weight: 4}] // Centro
//        },
//        summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance}
',
//        language: 'sp',
//         //city: 'Montevideo',   //si no va plan, debe agregarse si se desea afinar búsquedas.
//         routeWhileDragging: true,
//         waypointMode:  'snap',
//         collapsible: true  //nuevo
//     }).addTo(mapa);
//
// }

function crearControlRouting() {
    routeControl = L.Routing.control({
    routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
  //  waypoints: routingData.waypoints,
  // You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)

  plan: L.Routing.plan([], {
                   geocoder: L.Control.Geocoder.nominatim({
                   geocodingQueryParams: { countrycodes: 'uy'}
                 }),
                 reverseWaypoints: true,
                 city:'Montevideo',
                 language: 'sp'
               }),
    lineOptions: {
            styles:
                [
                  {color: 'black', opacity: 0.15, weight: 9}, //sombra
                  {color: 'white', opacity: 0.8, weight: 6}, // Contorno
                  {color: 'red', opacity: 1, weight: 4}] // Centro
       },

    router: L.Routing.mapzen('mapzen-3indRB', {
                 //costing: 'bicycle',
                directions_options: {
                    language: 'es'
                  }
    }),

    collapsible: true,
    formatter: new L.Routing.mapzenFormatter(),
    //summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance} info {costing}
',
    summaryTemplate:'
{name}

{distance}
'
    //summaryTemplate:  '
Trayectoria: {name}

Distancia: {distance}
',
}).addTo(mapa);

}

function calcRoute()  // esto para cuando no se usa el control
{
    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((marker1 !== null)  && (marker2 !== null))
    {
        waypoints.push({latLng: marker1.getLatLng()});
        waypoints.push({latLng: marker2.getLatLng()});
        router.route(waypoints, function(err, routes) {
         if (line) {
             map.removeLayer(line);
         }

         if (err) {
             alert(err);
         } else {
             coords = routes[0].coordinates;
             waysp = routes[0].waypoints;
             alert(routes[0].summary.totalTime);
             alert(routes[0].summary.totalDistance);
             line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: 'red', opacity: 1, weight: 4}]}).addTo(map);

         }
     });

    }
    else
        alert("Se necesita el par Origen-Destino para calcular la ruta");
}

function rutaAB(latA, latB)  // esto para cuando no se usa el control
{
    var waypoints = [];
    var coords = [];
    var waysp = [];

    waypoints.length = 0;
    coords.length = 0;
    waysp.length = 0;
    if ((latA != null) && (latB != null))
    //if ((marker1 !== null)  && (marker2 !== null))
    {

        //var router = L.Routing.osrm();

        var latlngA = L.Routing.waypoint(latA);
        var latlngB = L.Routing.waypoint(latB);
        // waypoints.push({latLng: latA});
        // waypoints.push({latLng: latB});
        waypoints.push(latlngA);
        waypoints.push(latlngB);

        var routes = null;

        //routes: L.Routing.mapzen('mapzen-3indRB', {costing: 'bicycle'});

        routes = L.Routing.osrmv1({addWaypoints: false});
        //routes: L.Routing.mapzen('mapzen-3indRB', {
            // addWaypoints: false,
          //  costing: 'bicycle'
        //})

        routes.route(waypoints, function(err, routes) {
             if (line) {
                 mapa.removeLayer(line);
             }

             if (err) {
                 console.log(err);
             }
             else {

                 coords = routes[0].coordinates;
                 waysp = routes[0].waypoints;
                 line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);

                 var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
                 popup = L.popup({offset: L.point(0, -30)})
                        .setLatLng(latB)
                        .setContent('
Distancia: ' + distanciaCerc + '
')
                        .openOn(mapa);

             }
       });

    }
    else
    {
        alert("Se necesita el par Origen-Destino para calcular la ruta");

    }

}
<|endoftext|>