<commit_before>var searchMovie = function (eventbus, movieId, lang) {
    //console.log("LANG: " + JSON.stringify(lang));
    console.log(movieId);
    eventbus.send("api_get_movie", movieId.toString(), function (error, reply) {
        var startDate = $("#watchStartDay");
        var startTime = $("#watchStartTime");
        var startNow = $("#watchStartNow");
        var startCalculate = $("#watchStartCalculate");

        var endDate = $("#watchEndDay");
        var endTime = $("#watchEndTime");
        var endNow = $("#watchEndNow");
        var endCalculate = $("#watchEndCalculate");

        var seenFirst = $("#watchSeenFirst");
        var wasCinema = $("#watchWasCinema");

        var commentFiled = $("#watchComment");

        startNow.click(function () {
            startNowPress(startDate, startTime);
        });

        endNow.click(function () {
            endNowPress(endDate, endTime);
        });

        var data = reply.body;
        var posterPath = "";
        if (data['poster_path'] === null) {
            posterPath = '/static/img/nanPosterBig.jpg'
        } else {
            posterPath = 'https://image.tmdb.org/t/p/w500/' + data['poster_path'];
        }

        document.title = lang['NAVBAR_MOVIES'] + ' - ' + data.title;
        console.log(data);

        $("#search-result").empty().hide();
        $('#movie-views-table').empty();
        $('#movie-title').text(data['original_title']).addClass('movies-heading');
        $('#navbar-background').addClass('transparent');
        $("#movie-poster-card").empty().append(
            $.parseHTML(
                ''
            )
        );

        var backgroundPath = "";
        if (data['backdrop_path'] === null) {
            backgroundPath = "";
        } else {
            backgroundPath = 'https://image.tmdb.org/t/p/w1920' + data['backdrop_path'];
        }

        getMovieViews(eventbus, movieId, lang);

        $("#body").attr("background", backgroundPath);
        $('#year').empty().append(nullCheck(data['release_date'], lang).split('-')[0]);
        $('#release').empty().append(getNormalDate(nullCheck(data['release_date'], lang), lang));
        $('#runtime').empty().append(toNormalRuntime(nullCheck(data['runtime'], lang), lang));

        $('#language').empty().append(getStringFormArray(nullCheck(data['spoken_languages'], lang), lang));
        $('#genre').empty().append(getStringFormArray(nullCheck(data['genres'], lang), lang));
        $('#budget').empty().append(toNormalRevenue(nullCheck(data['budget'], lang), lang));
        $('#revenue').empty().append(toNormalRevenue(nullCheck(data['revenue'], lang), lang));
        $('#country').empty().append(getStringFormArray(nullCheck(data['production_countries'], lang), lang));
        $('#rating').empty().append(getRating(nullCheck(data['vote_average'], lang), lang));

        $('#basic-info-box').removeClass('scale-out').addClass('scale-in');
        $('#seen-times').removeClass('scale-out').addClass('scale-in');
        $('#add-info-box').removeClass('scale-out').addClass('scale-in');
        $('#movie-poster-card').removeClass('scale-out').addClass('scale-in');
        $('#add-watch').removeClass('scale-out').addClass('scale-in');
        $('#add-wishlist').removeClass('scale-out').addClass('scale-in').off('click').off('keyup');

        inWishlist(eventbus, movieId, lang);

        $("#add-wishlist").click(function () {
            addToWishlist(eventbus, movieId, lang);
        });

        $("#add-wishlist").keyup(function (e) {
            if (e.keyCode === 13) {
                $("#add-wishlist").click();
            }
        });

        replaceUrlParameter("id", movieId);
    });
};

function addToWishlist(eventbus, movieId, lang) {
    eventbus.send("database_insert_wishlist", movieId);
    console.log(movieId + ' added to wishlist.');
    decorateInWishlist(lang);
}

function decorateInWishlist(lang) {
    $("#add-wishlist").removeClass('add-wishlist');
    $("#wishlist-text").empty().append(
        $.parseHTML(
            '' +
            lang['MOVIES_IN_WISHLIST']
        )
    ).removeClass('content-key');
}

function decorateNotInWIshlist(lang) {
    $("#add-wishlist").addClass('add-wishlist');
    $("#wishlist-text").empty().append(
        $.parseHTML(lang['MOVIES_ADD_WISHLIST'])
    ).addClass('content-key');
}

function inWishlist(eventbus, movieId, lang) {
    eventbus.send("database_get_in_wishlist", movieId, function (error, reply) {
        console.log('In wishlist: ' + reply.body['rows'].length);
        if (reply.body['rows'].length !== 0) {
            decorateInWishlist(lang);
        } else {
            decorateNotInWIshlist(lang);
        }
    });
}

var getMovieViews = function (eventbus, movieId, lang) {
    eventbus.send("database_get_movie_history", movieId.toString(), function (error, reply) {
        var data = reply.body['rows'];
        console.log(data);
        if (data.length > 0) {
            if (data.length > 1) {
                $('#seen-header').empty().append(lang['MOVIES_JS_SEEN_THIS'] + ' ' + data.length + lang['MOVIES_JS_SEEN_TIMES']);
            } else {
                $('#seen-header').empty().append(lang['MOVIES_JS_SEEN_ONCE']);
            }
            $.each(data, function (i) {
                $('#movie-views-table').append(
                    $.parseHTML(
                        '
' +
                        '' + getMonth(data[i]['Start'], lang) + '	' +
                        '	' +
                        '
'
                    )
                );
            });
        } else {
            $('#seen-header').empty().append(lang['MOVIES_JS_NOT_SEEN']);
        }
    });
};

var startNowPress = function (startDate, startTime) {
    var date = startDate.pickadate('picker').get();
    var time = startTime.pickatime().val();
    console.log('start: ' + date + ' ' + time);
};

var startCalcPress = function () {

};

var endNowPress = function (endDate, endTime) {
    var date = new Date();
    var time = date.getHours() + ":" + date.getMinutes();
    var day = date.getDate() + ". " + (date.getMonth() + 1) + ". " + date.getFullYear();

    /*var date = endDate.pickadate('picker').get();
    var time = endTime.pickatime().val();*/
    console.log(day);
    console.log(time);
};

var endCalcPress = function () {

};

var getNormalDate = function (date, lang) {
    if (date === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        var startArray = date.split('-');
        var dateFormat = new Date(date),
            locale = "en-us";
        var month = dateFormat.toLocaleString(locale, {month: "long"});
        return startArray[2] + lang[month.toUpperCase()] + ' ' + startArray[0];
    }
};

var nullCheck = function (data, lang) {
    console.log(data);
    if (data === 0 || data.length === 0) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else return data;
};

var getRating = function (data, lang) {
    if (data === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        return data + ' / 10.0'
    }
};

var toNormalRuntime = function (runtime, lang) {
    if (runtime === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        var hour = ~~(runtime / 60);
        var min = runtime - 60 * hour;
        return hour + ' h ' + min + ' min';
    }
};

var getStringFormArray = function (jsonArray, lang) {
    if (jsonArray === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        //console.log(jsonArray);
        if (jsonArray.length === 0) {
            return lang['MOVIES_JS_UNKNOWN'];
        }
        var result = "";

        $.each(jsonArray, function (i) {
            if (jsonArray[i].name !== '') {
                result += jsonArray[i].name + '
';
            }
        });

        return result.slice(0, -2);
    }
};

var toNormalRevenue = function (revenue, lang) {
    if (revenue === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else return revenue.toLocaleString() + ' $';
};

function replaceUrlParameter(param, value) {
    var url = location.href;
    var splitted = url.split('?');
    var shouldPushHistory = true;
    if (splitted.length > 1) {
        url = splitted[0];
        if (splitted[1].indexOf(value) !== -1) {
            shouldPushHistory = false;
        }
    }
    url = url + "?" + param + "=" + value;
    if (shouldPushHistory) {
        window.history.pushState('', '', url);
    }
}

fallback.ready(['jQuery', 'EventBus'], function () {
    var eventbus = new EventBus("/eventbus");
    eventbus.onopen = function () {

        var lang;
        eventbus.send("translations", getCookie("lang"), function (error, reply) {
            lang = reply.body;
            enableParameterMovieLoading(eventbus, lang);

            $("#search").keyup(function (e) {
                if (e.keyCode === 13) {
                    $("#search-button").click();
                }
            });

            $("#search-button").click(function () {
                $("#search-result").empty();
                $('#basic-info-box').removeClass('scale-in').addClass('scale-out');
                $('#seen-times').removeClass('scale-in').addClass('scale-out');
                $('#add-info-box').removeClass('scale-in').addClass('scale-out');
                $('#movie-poster-card').removeClass('scale-in').addClass('scale-out');
                $('#add-wishlist').removeClass('scale-in').addClass('scale-out');
                $('#add-watch').removeClass('scale-in').addClass('scale-out');
                setTimeout(
                    function () {
                        eventbus.send("api_get_search", $("#search").val(), function (error, reply) {
                            var data = reply.body['results'];
                            console.log(data.length);
                            if (data.length > 0) {
                                $.each(data, function (i) {
                                    var movie = data[i];
                                    var posterPath = "";
                                    if (movie['poster_path'] !== null) {
                                        posterPath = 'https://image.tmdb.org/t/p/w92/' + movie['poster_path'];
                                    } else {
                                        posterPath = '/static/img/nanPosterSmall.jpg'
                                    }
                                    var arrayOfNodes = $.parseHTML(
                                        '
' +
                                        '
' +
                                        '' +
                                        '' +
                                        movie['original_title'] +
                                        '' +
                                        '
' +
                                        '
'
                                    );
                                    arrayOfNodes[0].onclick = function () {
                                        searchMovie(eventbus, movie.id, lang);
                                    };

                                    arrayOfNodes[0].addEventListener("keyup", function (e) {
                                        if (e.keyCode === 13) {
                                            searchMovie(eventbus, movie.id, lang);
                                        }
                                    });

                                    $("#search-result").append(arrayOfNodes).show();
                                    if (i === 9) {
                                        return false;
                                    }
                                });
                            } else {
                                $("#search-result").append(
                                    $.parseHTML(
                                        '
' +
                                        '
' +
                                        '
' + lang['MOVIES_JS_NO_MOVIES'] + '
' +
                                        '
' +
                                        '
'
                                    )
                                ).show();
                            }
                            $("#movie-poster-card").empty();
                        });
                    }, 405);

            });
        });
    };

    var enableParameterMovieLoading = function (eventbus, lang) {
        var loadMovie = function (eventbus, lang) {
            var query = getUrlParam("id");
            if (query !== null && isNormalInteger(query)) {
                searchMovie(eventbus, query, lang);
            }
        };
        window.onpopstate = function() { //try to load movie on back/forward page movement
            loadMovie(eventbus, lang);
        };
        loadMovie(eventbus, lang); //load movie if url has param
    };
});<commit_msg>timepicker now valimine<commit_after>var searchMovie = function (eventbus, movieId, lang) {
    //console.log("LANG: " + JSON.stringify(lang));
    console.log(movieId);
    eventbus.send("api_get_movie", movieId.toString(), function (error, reply) {
        var startDate = $("#watchStartDay");
        var startTime = $("#watchStartTime");
        var startNow = $("#watchStartNow");
        var startCalculate = $("#watchStartCalculate");

        var endDate = $("#watchEndDay");
        var endTime = $("#watchEndTime");
        var endNow = $("#watchEndNow");
        var endCalculate = $("#watchEndCalculate");

        var seenFirst = $("#watchSeenFirst");
        var wasCinema = $("#watchWasCinema");

        var commentFiled = $("#watchComment");

        startNow.click(function () {
            startNowPress(startDate, startTime);
        });

        endNow.click(function (e) {
            endNowPress(endDate, endTime, e);
        });

        var data = reply.body;
        var posterPath = "";
        if (data['poster_path'] === null) {
            posterPath = '/static/img/nanPosterBig.jpg'
        } else {
            posterPath = 'https://image.tmdb.org/t/p/w500/' + data['poster_path'];
        }

        document.title = lang['NAVBAR_MOVIES'] + ' - ' + data.title;
        console.log(data);

        $("#search-result").empty().hide();
        $('#movie-views-table').empty();
        $('#movie-title').text(data['original_title']).addClass('movies-heading');
        $('#navbar-background').addClass('transparent');
        $("#movie-poster-card").empty().append(
            $.parseHTML(
                ''
            )
        );

        var backgroundPath = "";
        if (data['backdrop_path'] === null) {
            backgroundPath = "";
        } else {
            backgroundPath = 'https://image.tmdb.org/t/p/w1920' + data['backdrop_path'];
        }

        getMovieViews(eventbus, movieId, lang);

        $("#body").attr("background", backgroundPath);
        $('#year').empty().append(nullCheck(data['release_date'], lang).split('-')[0]);
        $('#release').empty().append(getNormalDate(nullCheck(data['release_date'], lang), lang));
        $('#runtime').empty().append(toNormalRuntime(nullCheck(data['runtime'], lang), lang));

        $('#language').empty().append(getStringFormArray(nullCheck(data['spoken_languages'], lang), lang));
        $('#genre').empty().append(getStringFormArray(nullCheck(data['genres'], lang), lang));
        $('#budget').empty().append(toNormalRevenue(nullCheck(data['budget'], lang), lang));
        $('#revenue').empty().append(toNormalRevenue(nullCheck(data['revenue'], lang), lang));
        $('#country').empty().append(getStringFormArray(nullCheck(data['production_countries'], lang), lang));
        $('#rating').empty().append(getRating(nullCheck(data['vote_average'], lang), lang));

        $('#basic-info-box').removeClass('scale-out').addClass('scale-in');
        $('#seen-times').removeClass('scale-out').addClass('scale-in');
        $('#add-info-box').removeClass('scale-out').addClass('scale-in');
        $('#movie-poster-card').removeClass('scale-out').addClass('scale-in');
        $('#add-watch').removeClass('scale-out').addClass('scale-in');
        $('#add-wishlist').removeClass('scale-out').addClass('scale-in').off('click').off('keyup');

        inWishlist(eventbus, movieId, lang);

        $("#add-wishlist").click(function () {
            addToWishlist(eventbus, movieId, lang);
        });

        $("#add-wishlist").keyup(function (e) {
            if (e.keyCode === 13) {
                $("#add-wishlist").click();
            }
        });

        replaceUrlParameter("id", movieId);
    });
};

function addToWishlist(eventbus, movieId, lang) {
    eventbus.send("database_insert_wishlist", movieId);
    console.log(movieId + ' added to wishlist.');
    decorateInWishlist(lang);
}

function decorateInWishlist(lang) {
    $("#add-wishlist").removeClass('add-wishlist');
    $("#wishlist-text").empty().append(
        $.parseHTML(
            '' +
            lang['MOVIES_IN_WISHLIST']
        )
    ).removeClass('content-key');
}

function decorateNotInWIshlist(lang) {
    $("#add-wishlist").addClass('add-wishlist');
    $("#wishlist-text").empty().append(
        $.parseHTML(lang['MOVIES_ADD_WISHLIST'])
    ).addClass('content-key');
}

function inWishlist(eventbus, movieId, lang) {
    eventbus.send("database_get_in_wishlist", movieId, function (error, reply) {
        console.log('In wishlist: ' + reply.body['rows'].length);
        if (reply.body['rows'].length !== 0) {
            decorateInWishlist(lang);
        } else {
            decorateNotInWIshlist(lang);
        }
    });
}

var getMovieViews = function (eventbus, movieId, lang) {
    eventbus.send("database_get_movie_history", movieId.toString(), function (error, reply) {
        var data = reply.body['rows'];
        console.log(data);
        if (data.length > 0) {
            if (data.length > 1) {
                $('#seen-header').empty().append(lang['MOVIES_JS_SEEN_THIS'] + ' ' + data.length + lang['MOVIES_JS_SEEN_TIMES']);
            } else {
                $('#seen-header').empty().append(lang['MOVIES_JS_SEEN_ONCE']);
            }
            $.each(data, function (i) {
                $('#movie-views-table').append(
                    $.parseHTML(
                        '
' +
                        '' + getMonth(data[i]['Start'], lang) + '	' +
                        '	' +
                        '
'
                    )
                );
            });
        } else {
            $('#seen-header').empty().append(lang['MOVIES_JS_NOT_SEEN']);
        }
    });
};

var startNowPress = function (startDate, startTime) {
    var date = startDate.pickadate('picker').get();
    var time = startTime.pickatime().val();
    console.log('start: ' + date + ' ' + time);
};

var startCalcPress = function () {

};

var endNowPress = function (endDate, endTime, e) {
    var date = new Date();
    var day = date.getDate() + ". " + (date.getMonth() + 1) + ". " + date.getFullYear();
    var time = date.getHours() + ":" + date.getMinutes();

    e.stopPropagation();
    console.log(time);

    /*endTime.pickatime({
        default: time
    });*/
    // fixme: vaja now ära fixida, et ka pärast ise aja valimist now töötaks
    endTime.pickatime('show').pickatime('done');
};

var endCalcPress = function () {

};

var getNormalDate = function (date, lang) {
    if (date === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        var startArray = date.split('-');
        var dateFormat = new Date(date),
            locale = "en-us";
        var month = dateFormat.toLocaleString(locale, {month: "long"});
        return startArray[2] + lang[month.toUpperCase()] + ' ' + startArray[0];
    }
};

var nullCheck = function (data, lang) {
    console.log(data);
    if (data === 0 || data.length === 0) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else return data;
};

var getRating = function (data, lang) {
    if (data === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        return data + ' / 10.0'
    }
};

var toNormalRuntime = function (runtime, lang) {
    if (runtime === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        var hour = ~~(runtime / 60);
        var min = runtime - 60 * hour;
        return hour + ' h ' + min + ' min';
    }
};

var getStringFormArray = function (jsonArray, lang) {
    if (jsonArray === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else {
        //console.log(jsonArray);
        if (jsonArray.length === 0) {
            return lang['MOVIES_JS_UNKNOWN'];
        }
        var result = "";

        $.each(jsonArray, function (i) {
            if (jsonArray[i].name !== '') {
                result += jsonArray[i].name + '
';
            }
        });

        return result.slice(0, -2);
    }
};

var toNormalRevenue = function (revenue, lang) {
    if (revenue === lang['MOVIES_JS_UNKNOWN']) {
        return lang['MOVIES_JS_UNKNOWN'];
    } else return revenue.toLocaleString() + ' $';
};

function replaceUrlParameter(param, value) {
    var url = location.href;
    var splitted = url.split('?');
    var shouldPushHistory = true;
    if (splitted.length > 1) {
        url = splitted[0];
        if (splitted[1].indexOf(value) !== -1) {
            shouldPushHistory = false;
        }
    }
    url = url + "?" + param + "=" + value;
    if (shouldPushHistory) {
        window.history.pushState('', '', url);
    }
}

fallback.ready(['jQuery', 'EventBus'], function () {
    var eventbus = new EventBus("/eventbus");
    eventbus.onopen = function () {

        var lang;
        eventbus.send("translations", getCookie("lang"), function (error, reply) {
            lang = reply.body;
            enableParameterMovieLoading(eventbus, lang);

            $("#search").keyup(function (e) {
                if (e.keyCode === 13) {
                    $("#search-button").click();
                }
            });

            $("#search-button").click(function () {
                $("#search-result").empty();
                $('#basic-info-box').removeClass('scale-in').addClass('scale-out');
                $('#seen-times').removeClass('scale-in').addClass('scale-out');
                $('#add-info-box').removeClass('scale-in').addClass('scale-out');
                $('#movie-poster-card').removeClass('scale-in').addClass('scale-out');
                $('#add-wishlist').removeClass('scale-in').addClass('scale-out');
                $('#add-watch').removeClass('scale-in').addClass('scale-out');
                setTimeout(
                    function () {
                        eventbus.send("api_get_search", $("#search").val(), function (error, reply) {
                            var data = reply.body['results'];
                            console.log(data.length);
                            if (data.length > 0) {
                                $.each(data, function (i) {
                                    var movie = data[i];
                                    var posterPath = "";
                                    if (movie['poster_path'] !== null) {
                                        posterPath = 'https://image.tmdb.org/t/p/w92/' + movie['poster_path'];
                                    } else {
                                        posterPath = '/static/img/nanPosterSmall.jpg'
                                    }
                                    var arrayOfNodes = $.parseHTML(
                                        '
' +
                                        '
' +
                                        '' +
                                        '' +
                                        movie['original_title'] +
                                        '' +
                                        '
' +
                                        '
'
                                    );
                                    arrayOfNodes[0].onclick = function () {
                                        searchMovie(eventbus, movie.id, lang);
                                    };

                                    arrayOfNodes[0].addEventListener("keyup", function (e) {
                                        if (e.keyCode === 13) {
                                            searchMovie(eventbus, movie.id, lang);
                                        }
                                    });

                                    $("#search-result").append(arrayOfNodes).show();
                                    if (i === 9) {
                                        return false;
                                    }
                                });
                            } else {
                                $("#search-result").append(
                                    $.parseHTML(
                                        '
' +
                                        '
' +
                                        '
' + lang['MOVIES_JS_NO_MOVIES'] + '
' +
                                        '
' +
                                        '
'
                                    )
                                ).show();
                            }
                            $("#movie-poster-card").empty();
                        });
                    }, 405);

            });
        });
    };

    var enableParameterMovieLoading = function (eventbus, lang) {
        var loadMovie = function (eventbus, lang) {
            var query = getUrlParam("id");
            if (query !== null && isNormalInteger(query)) {
                searchMovie(eventbus, query, lang);
            }
        };
        window.onpopstate = function() { //try to load movie on back/forward page movement
            loadMovie(eventbus, lang);
        };
        loadMovie(eventbus, lang); //load movie if url has param
    };
});<|endoftext|>


<commit_before>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "https://qapp.daskeyboard.com?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;
}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info',
        'You are  logged in: sample code will contain your API key so you can copy paste and experiment easily. Enjoy!');
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {

  // remove api key and email from local storage
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');

  // reload page
  window.location.reload();
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('Welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    $('#header-welcome-message').css('font-weight', 'bold');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {

      // TODO change with the root to the API Key explanation page
      const apiKeyMoreDetails = window.location.origin + '/get-started/download/';
      $(this).html($(this).html().replace(/\$API_KEY/g,
        // ""
        // + "login to retrieve your api-key"));
        "<button class='login-code-button' data-toggle='tooltip' data-html='true' title='This is a sample API key. Login to see examples "
        + "pre-filled with your keys.'>login to retrieve your api-key</button>"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

/**
 * Detects the os platform and architechture and change the download link of the Q software
 * depending on this informations
 */
function loadDownloadLinkDependingOnOsArchitechture() {
  if (navigator.platform.includes('Win32')) {
    if (navigator.userAgent.indexOf("WOW64") != -1 ||
      navigator.userAgent.indexOf("Win64") != -1) {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/Das-Keyboard-Q-x64-Setup-2.0.4.exe");
      $('#software-download-button').append(" 64 bit");
      $('#software-version-number').append(" Windows");
      return;

    } else {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/Das-Keyboard-Q-ia32-Setup-2.0.4.exe");
      $('#software-download-button').append(" 32 bit");
      $('#software-version-number').append(" Windows");
      return;

    }
  }
  if (navigator.platform.includes('MacIntel')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/DasKeyboardQ_2.0.4-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Mac");
    return;
  }

  if (navigator.platform.includes('Linux x86_64')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/das-keyboard-q_2.0.4~beta.deb");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Linux");
  }

  $('#software-version-number').append(" Windows");

}

/**
 * Detects the device pid given in param in the URL
 * and change the download fw link button depending on the pid
 */
function loadFirmwareDeviceDependingOnPidParam() {
  const pid = getParameterByName('devicePid', window.location.href);
  if (pid) {
    $('#firmware-buttons').css('display', 'flex');
    switch (pid) {
      case 'DK5QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/5Q/5Q+Flash+Upgrade.7.4.18.exe");
        $('#firmware-download-button').text("Download 5Q firmware installer");
        $('#firmware-download-version').text("Version 7.4.18");
        break;
      case 'X50QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/X50Q/DasKeyboard+X50+-+Firmware+Updater+-+57.0.0.exe");
        $('#firmware-download-button').text("Download X50Q firmware installer");
        $('#firmware-download-version').text("Version 57.0.0");
        break;
      case 'DK4QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_US_Firmware_19.22.0.exe");
        $('#firmware-download-button').text("Download DK4Q US firmware installer");
        $('#firmware-download-version').text("Version 19.22.0");
        $('#firmware-download-button-dk4-eu').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_EU_Firmware_19.22.0.exe");
        $('#firmware-download-button-dk4-eu').text("Download DK4Q EU firmware installer");
        $('#firmware-download-version-dk4-eu').text("Version 19.22.0");
        $('#firmware-download-version-dk4-eu').css('visibility', 'visible');
        $('#firmware-download-button-dk4-eu').css('visibility', 'visible');
        break;
    }
  }
}

$(document).ready(function () {
  loadFirmwareDeviceDependingOnPidParam();
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();
  loadDownloadLinkDependingOnOsArchitechture();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<commit_msg>fixed corrected the download software button description<commit_after>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "https://qapp.daskeyboard.com?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;
}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info',
        'You are  logged in: sample code will contain your API key so you can copy paste and experiment easily. Enjoy!');
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {

  // remove api key and email from local storage
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');

  // reload page
  window.location.reload();
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('Welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    $('#header-welcome-message').css('font-weight', 'bold');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {

      // TODO change with the root to the API Key explanation page
      const apiKeyMoreDetails = window.location.origin + '/get-started/download/';
      $(this).html($(this).html().replace(/\$API_KEY/g,
        // ""
        // + "login to retrieve your api-key"));
        "<button class='login-code-button' data-toggle='tooltip' data-html='true' title='This is a sample API key. Login to see examples "
        + "pre-filled with your keys.'>login to retrieve your api-key</button>"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

/**
 * Detects the os platform and architechture and change the download link of the Q software
 * depending on this informations
 */
function loadDownloadLinkDependingOnOsArchitechture() {
  if (navigator.platform.includes('Win32')) {
    if (navigator.userAgent.indexOf("WOW64") != -1 ||
      navigator.userAgent.indexOf("Win64") != -1) {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/Das-Keyboard-Q-x64-Setup-2.0.4.exe");
      $('#software-download-button').append(" 64 bit");
      $('#software-version-number').append(" Windows");
      return;

    } else {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/Das-Keyboard-Q-ia32-Setup-2.0.4.exe");
      $('#software-download-button').append(" 32 bit");
      $('#software-version-number').append(" Windows");
      return;

    }
  }
  if (navigator.platform.includes('MacIntel')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/DasKeyboardQ_2.0.4-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Mac");
    return;
  }

  if (navigator.platform.includes('Linux x86_64')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/2.0.4/das-keyboard-q_2.0.4~beta.deb");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Linux");
    return;
  }

}

/**
 * Detects the device pid given in param in the URL
 * and change the download fw link button depending on the pid
 */
function loadFirmwareDeviceDependingOnPidParam() {
  const pid = getParameterByName('devicePid', window.location.href);
  if (pid) {
    $('#firmware-buttons').css('display', 'flex');
    switch (pid) {
      case 'DK5QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/5Q/5Q+Flash+Upgrade.7.4.18.exe");
        $('#firmware-download-button').text("Download 5Q firmware installer");
        $('#firmware-download-version').text("Version 7.4.18");
        break;
      case 'X50QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/X50Q/DasKeyboard+X50+-+Firmware+Updater+-+57.0.0.exe");
        $('#firmware-download-button').text("Download X50Q firmware installer");
        $('#firmware-download-version').text("Version 57.0.0");
        break;
      case 'DK4QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_US_Firmware_19.22.0.exe");
        $('#firmware-download-button').text("Download DK4Q US firmware installer");
        $('#firmware-download-version').text("Version 19.22.0");
        $('#firmware-download-button-dk4-eu').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_EU_Firmware_19.22.0.exe");
        $('#firmware-download-button-dk4-eu').text("Download DK4Q EU firmware installer");
        $('#firmware-download-version-dk4-eu').text("Version 19.22.0");
        $('#firmware-download-version-dk4-eu').css('visibility', 'visible');
        $('#firmware-download-button-dk4-eu').css('visibility', 'visible');
        break;
    }
  }
}

$(document).ready(function () {
  loadFirmwareDeviceDependingOnPidParam();
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();
  loadDownloadLinkDependingOnOsArchitechture();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<|endoftext|>


<commit_before>Gerrit.install(function(self) {
    function print (c, r) {
        var url = "changes/" + c._number + "/revisions/" + r._number + "/ReviewAssistant~advice";
        console.log("Url is: " + url);
        var change_plugins = document.getElementById('change_plugins');
        console.log("Asking for advice...");
        Gerrit.get(
            url,
            function (r) {
                console.log("Got advice: " + r);
                change_plugins.innerHTML = "
You should spend " + r.total_review_time + " minutes reviewing this change.

Sessions: " + r.sessions +" for " + r.session_time + " minutes each.
";
            });
    }
    self.on('showchange', print);
});<commit_msg>Added divs<commit_after>Gerrit.install(function(self) {
    function print (c, r) {
        var url = "changes/" + c._number + "/revisions/" + r._number + "/ReviewAssistant~advice";
        console.log("Url is: " + url);
        var change_plugins = document.getElementById('change_plugins');
        console.log("Asking for advice...");
        Gerrit.get(
            url,
            function (r) {
                console.log("Got advice: " + r);
                var totalTime = "
You should spend " + r.total_review_time + " minutes reviewing this change.";
                var sessions = "
Sessions: " + r.sessions +" for " + r.session_time + " minutes each.";
                change_plugins.innerHTML = "
"+ totalTime +" "+ sessions + "
";
            });
    }
    self.on('showchange', print);
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         Risibot
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       Risitop
// @match        http://play.pokemonshowdown.com/*
// @require      https://raw.githubusercontent.com/Zarel/Pokemon-Showdown-Client/master/data/learnsets-g6.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/FullPokemon.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/Tools.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/PokeyI.js
// @grant        none
// ==/UserScript==
///////////////////////////////////////////////////////////////////////////////

risibotWatcher = function() {
  console.log("Watcher");
  if (window.location.href != "http://play.pokemonshowdown.com/") {
    room = getRoom();
    if (room) {
      if (room.chatHistory.lines[room.chatHistory.lines.length - 1] === "La chancla !") {
        risitas = new Risibot();
        risitas.routine(null);
        return;
      }
    }
  }
  setTimeout(risibotWatcher, 500);
};

risibotWatcher();<commit_msg>Update main.js<commit_after>// ==UserScript==
// @name         Risibot
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       Risitop
// @match        http://play.pokemonshowdown.com/*
// @require      https://raw.githubusercontent.com/Zarel/Pokemon-Showdown-Client/master/data/learnsets-g6.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/FullPokemon.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/Tools.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/PokeyI.js
// @require      https://raw.githubusercontent.com/Risitop/Risibot/master/JS/Risibot.js
// @grant        none
// ==/UserScript==
///////////////////////////////////////////////////////////////////////////////

risibotWatcher = function() {
  console.log("Watcher");
  if (window.location.href != "http://play.pokemonshowdown.com/") {
    room = getRoom();
    if (room) {
      if (room.chatHistory.lines[room.chatHistory.lines.length - 1] === "La chancla !") {
        risitas = new Risibot();
        risitas.routine(null);
        return;
      }
    }
  }
  setTimeout(risibotWatcher, 500);
};

risibotWatcher();
<|endoftext|>


<commit_before>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 600;
    var w = 700;
    var padding = 80;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.append("defs").append("clipPath")
      .attr("id", "clip")
      .append("rect")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - (2 * padding))
      .attr("height", h - padding);

    svg.selectAll("g.series")
      .data(json, function(d) { return d.target; })
      .enter().append("g")
        .attr("class", "series")
        .attr("clip-path", "url(#clip)")
        .attr("stroke", function(d, index) {
          return colors(index);
        })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .enter().append("path")
            .classed("line", true)
            .attr("d", function(d) {
              return line(d);
            });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(json[0].datapoints, x0, 1),
            d0 = json[0].datapoints[i - 1],
            d1 = json[0].datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });

    var tick = function() {
      for(var i = 0; i < json.length; i++) {
        var lastPoint = json[i].datapoints[json[i].datapoints.length - 1],
            x = lastPoint[1],
            y = yVal(lastPoint);
        json[i].datapoints.push([y, x + 10]);
      }

      xScale.domain([
        d3.min(json, function(d) { return d3.min(d.datapoints.slice(1), xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints.slice(1), xVal) })
      ]);

      /* Draw the line with the new xscale, but translated back to the right */
      svg.selectAll("g.series path")
        .attr("d", line)
        .attr("transform", "translate(" + (xScale(xVal(json[0].datapoints[2])) - padding) + ",0)");

      yScale.domain([
        d3.min(json, function(d) { return d3.min(d.datapoints.slice(1), yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints.slice(1), yVal) }),
      ]);

      xAxis.scale(xScale);
      yAxis.scale(yScale);

      var t = svg.transition()
        .duration(500)
        .ease("linear")

      t.selectAll("g.series path")
        .attr("d", line)
        .attr("transform", "translate(0,0)");
      t.select("g.x-axis").call(xAxis);
      t.select("g.y-axis").call(yAxis);

      for(var i = 0; i < json.length; i++) {
        json[i].datapoints.shift();
      }
    }

    return tick;
  }

  getGraphSources().forEach(function(source) {
    d3.json(source, function(err, json) {
      if(err && !json) {
        renderError(err, source);
      } else {
        var tick = renderGraph("body", json);
        //setTimeout(tick, 1000);
        setInterval(tick, 1000);
      }
    });
  });
})();
<commit_msg>Update the graph based on an entire dataset<commit_after>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 600;
    var w = 700;
    var padding = 80;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.append("defs").append("clipPath")
      .attr("id", "clip")
      .append("rect")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - (2 * padding))
      .attr("height", h - padding);

    svg.selectAll("g.series")
      .data(json, function(d) { return d.target; })
      .enter().append("g")
        .attr("class", "series")
        .attr("clip-path", "url(#clip)")
        .attr("stroke", function(d, index) {
          return colors(index);
        })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .enter().append("path")
            .classed("line", true)
            .attr("d", function(d) {
              return line(d);
            });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var data = d3.selectAll("g.series").datum();
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(data.datapoints, x0, 1),
            d0 = data.datapoints[i - 1],
            d1 = data.datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });

    var tick = function(newJson) {
      var data = [];
      var lastData = d3.selectAll("g.series").data();
      for(var i = 0; i < lastData.length; i++) {
        var droppedPointCount = d3.bisectLeft(
          lastData[i].datapoints.map(function(d) { return d[1]; }),
          newJson[i].datapoints[0][1]
        );
        var addedPointCount = newJson[i].datapoints.length - lastData[i].datapoints.length;
        data[i] = {
          target: newJson[i].target,
          datapoints: lastData[i].datapoints.slice(0, droppedPointCount).concat(newJson[i].datapoints)
        }
      };

      xScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), xVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), xVal) })
      ]);

      /* Draw the line with the new xscale, but translated back to the right */
      svg.selectAll("g.series")
        .data(data, function(d) { return d.target; })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .attr("d", line)
          .attr("transform", "translate(" + (xScale(xVal(data[0].datapoints[2])) - padding) + ",0)");

      yScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), yVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), yVal) }),
      ]);

      xAxis.scale(xScale);
      yAxis.scale(yScale);

      var t = svg.transition()
        .duration(300)
        .ease("linear")

      t.selectAll("g.series path")
        .attr("d", line)
        .attr("transform", "translate(0,0)");
      t.select("g.x-axis").call(xAxis);
      t.select("g.y-axis").call(yAxis);

      for(var i = 0; i < data.length; i++) {
        data[i].datapoints.shift();
      }
    }

    return tick;
  }

  function randomSeries(name, start, stop, step) {
    var rand = d3.random.normal(100, 10);
    var times = d3.range(start, stop, step);
    var series = times.map(function(time) {
      return [rand(), time];
    });

    return function(steps) {
      if(steps != 0) {
        var lastTime = series[series.length - 1][1];
        var extraTimes = d3.range(lastTime + step, lastTime + step + steps * step, step);
        series = series.slice(steps).concat(extraTimes.map(function(time) {
          return [rand(), time];
        }));
        console.log(series);
      }
      return { target: 'a', datapoints: series };
    }
  }

  getGraphSources().forEach(function(source) {
    var start = 1364523350;
    var data = randomSeries('a', start, start + 60, 10);

    var tick = renderGraph("body", [data(0)]);
    var update = function() {
      tick([data(1)]);
    };

    setInterval(update, 10000);
  })

  //getGraphSources().forEach(function(source) {
  //  d3.json(source, function(err, json) {
  //    if(err && !json) {
  //      renderError(err, source);
  //    } else {
  //      var tick = renderGraph("body", json),
  //          update = function() {
  //            d3.json(source, function(err, json) {
  //              if(err && !json) {
  //                renderError(err, source);
  //              } else {
  //                tick(json);
  //              }
  //            });
  //          };
  //      //setTimeout(tick, 1000);
  //      setInterval(update, 1000);
  //    }
  //  });
  //});
})();
<|endoftext|>


<commit_before>$(function() {

	$.getJSON('get-tweets.php',function(feeds) {
	    var date = parseTwitterDate(feeds[0].created_at);
	    var entry = "@nickjvm: " + feeds[0].text + " — " + moment(date).fromNow();

	    $("#twitter .tweet").html(entry.parseURL().parseUsername().parseHashtag());
	    $("#twitter").fadeIn();
	});

	$('.email').magnificPopup({
		type: 'inline',
		preloader: false,
		focus: '#name',

		// When elemened is focused, some mobile browsers in some cases zoom in
		// It looks not nice, so we disable it:
		callbacks: {
			beforeOpen: function() {
			  if($(window).width() < 700) {
			    this.st.focus = false;
			  } else {
			    this.st.focus = '#name';
			  }
			},
			beforeClose:function() {
				clearForm("#contact");
				$("#contact").removeClass("thinking");
				validator.resetForm();
			}
		}
	});

	var validator = $("#contact").validate({
		errorPlacement:function() {}
	});

	$("#contact .cancel").on("click",function(e) {
		e.preventDefault();
		validator.resetForm();
		$.magnificPopup.close()
	});

	$("#contact").on("submit",function(e) {
		if(!validator.valid()) {
			return false;
		}
		var $self = $(this);
		//do some cleanup
		e.preventDefault();
		validator.resetForm();
		$self.addClass("thinking");
		var data = $(this).serialize();

		var request = $.ajax({
			type: "POST",
			url: "contact.php",
			data: data
		})

		request.done(function(response,success) {
			$self.removeClass("thinking");
			response = $.parseJSON(response);
			if(response.status) {
				//passed validation - got a good response!
				clearForm("#contact");
				$.magnificPopup.close();
				$("#success").css({
					top:0
				})
				setTimeout(function() {
					$("#success").css({
						top:-40
					})
				},2500);

			} else {
				if(response.code == 1) {
					//something went wrong!
					$.each(response.errors,function() {
						$("#contact [name='"+this+"']").addClass("error");
					});
			 	} else if (response.code == 2) {
			 		$("#contact .alert-error").text("Something went wrong. Please try again later");
			 	}
			}
		});

	});
});
var clearForm = function(selector) {
	$(selector).find(":input").val("").prop("checked",false);
}

var contentTop = $(window).width() < 480 ? 150 : 360;
window.onscroll = function() {
	if(!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
		var n = Math.ceil($(window).scrollTop() / 2.5);
		$("#hero").css({
			"-webkit-transform":"translateY(-" + n + "px)",
			"-moz-transform":"translateY(-" + n + "px)",
			"-ms-transform":"translateY(-" + n + "px)",
			"transform":"translateY(-" + n + "px)"
		});
	}
	if($(window).scrollTop() > contentTop) {
		$("header").addClass("shrink");
	} else {
		$("header").removeClass("shrink");
	}
}

function parseTwitterDate(text) {
	return new Date(Date.parse(text.replace(/( +)/, ' UTC$1')));
}

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
		return url.link(url);
	});
};
    String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		return u.link("http://twitter.com/"+username);
	});
};
    String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};
<commit_msg>Updating parseTwitterDate function<commit_after>$(function() {

	$.getJSON('get-tweets.php',function(feeds) {
	    var date = parseTwitterDate(feeds[0].created_at);
	    var entry = "@nickjvm: " + feeds[0].text + " — " + moment(date).fromNow();

	    $("#twitter .tweet").html(entry.parseURL().parseUsername().parseHashtag());
	    $("#twitter").fadeIn();
	});

	$('.email').magnificPopup({
		type: 'inline',
		preloader: false,
		focus: '#name',

		// When elemened is focused, some mobile browsers in some cases zoom in
		// It looks not nice, so we disable it:
		callbacks: {
			beforeOpen: function() {
			  if($(window).width() < 700) {
			    this.st.focus = false;
			  } else {
			    this.st.focus = '#name';
			  }
			},
			beforeClose:function() {
				clearForm("#contact");
				$("#contact").removeClass("thinking");
				validator.resetForm();
			}
		}
	});

	var validator = $("#contact").validate({
		errorPlacement:function() {}
	});

	$("#contact .cancel").on("click",function(e) {
		e.preventDefault();
		validator.resetForm();
		$.magnificPopup.close()
	});

	$("#contact").on("submit",function(e) {
		if(!validator.valid()) {
			return false;
		}
		var $self = $(this);
		//do some cleanup
		e.preventDefault();
		validator.resetForm();
		$self.addClass("thinking");
		var data = $(this).serialize();

		var request = $.ajax({
			type: "POST",
			url: "contact.php",
			data: data
		})

		request.done(function(response,success) {
			$self.removeClass("thinking");
			response = $.parseJSON(response);
			if(response.status) {
				//passed validation - got a good response!
				clearForm("#contact");
				$.magnificPopup.close();
				$("#success").css({
					top:0
				})
				setTimeout(function() {
					$("#success").css({
						top:-40
					})
				},2500);

			} else {
				if(response.code == 1) {
					//something went wrong!
					$.each(response.errors,function() {
						$("#contact [name='"+this+"']").addClass("error");
					});
			 	} else if (response.code == 2) {
			 		$("#contact .alert-error").text("Something went wrong. Please try again later");
			 	}
			}
		});

	});
});
var clearForm = function(selector) {
	$(selector).find(":input").val("").prop("checked",false);
}

var contentTop = $(window).width() < 480 ? 150 : 360;
window.onscroll = function() {
	if(!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
		var n = Math.ceil($(window).scrollTop() / 2.5);
		$("#hero").css({
			"-webkit-transform":"translateY(-" + n + "px)",
			"-moz-transform":"translateY(-" + n + "px)",
			"-ms-transform":"translateY(-" + n + "px)",
			"transform":"translateY(-" + n + "px)"
		});
	}
	if($(window).scrollTop() > contentTop) {
		$("header").addClass("shrink");
	} else {
		$("header").removeClass("shrink");
	}
}

function parseTwitterDate(text) {
	//IE doesn't like twitter's created_at date format, need to move a few things around
	var date = text.split(" ");
	return new Date(date[0] + " " + date[1] + " " + date[2] + " " + date[5] + " " + date[3] + " " + date[4]);
}

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
		return url.link(url);
	});
};
    String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		return u.link("http://twitter.com/"+username);
	});
};
    String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};
<|endoftext|>


<commit_before>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = '#'
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	if(Object.keys(Logo.queryObj).length < 1 || Logo.queryObj.random) {
		// ERMAGOD RANDOM LOGO
		Logo.backColor = Logo.randomColor();
		Logo.fontColor = Logo.randomColor();
		Logo.fontStroke = Logo.backColor;
		Logo.stripeColor = Logo.randomColor();
		Logo.letters = new Array();
		var letterLength = 1 + Math.floor(Math.random() * 2);
		for(var i = 0; i < letterLength; i++) {
			Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
		}
		Logo.backStyle = Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.offsetX = Math.floor(Math.random() * 50);
		Logo.fontFamily = Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];
		console.log(Logo.fontFamily);
	} else {
		Logo.backColor = '#' + Logo.queryObj.backColor ? Logo.queryObj.backColor : '333';
		Logo.fontColor = '#' + Logo.queryObj.fontColor ? Logo.queryObj.fontColor : '999';
		Logo.fontStroke = '#' + (Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor);
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : 'blank';
		Logo.stripeColor = '#' + (Logo.queryObj.foreColor ? Logo.queryObj.foreColor : Logo.backColor);
		Logo.letters = Logo.queryObj.logoLetter.split("|");
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : 0;
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : "Calibri";
	}

	Logo.url = 'http://' + window.location.hostname + '/?backColor=' + Logo.backColor+ '&fontColor=' + Logo.fontColor + '&fontStroke=' + Logo.fontStroke + '&backStyle=' + Logo.backStyle + '&stripeColor=' + Logo.stripeColor + '&logoLetter=' + Logo.letters.join('|');

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
		},
		fill: "cecece",
		opacity: .25
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

})();<commit_msg>-logging<commit_after>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = '#'
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	if(Object.keys(Logo.queryObj).length < 1 || Logo.queryObj.random) {
		// ERMAGOD RANDOM LOGO
		Logo.backColor = Logo.randomColor();
		Logo.fontColor = Logo.randomColor();
		Logo.fontStroke = Logo.backColor;
		Logo.stripeColor = Logo.randomColor();
		Logo.letters = new Array();
		var letterLength = 1 + Math.floor(Math.random() * 2);
		for(var i = 0; i < letterLength; i++) {
			Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
		}
		Logo.backStyle = Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.offsetX = Math.floor(Math.random() * 50);
		Logo.fontFamily = Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];
	} else {
		Logo.backColor = '#' + Logo.queryObj.backColor ? Logo.queryObj.backColor : '333';
		Logo.fontColor = '#' + Logo.queryObj.fontColor ? Logo.queryObj.fontColor : '999';
		Logo.fontStroke = '#' + (Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor);
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : 'blank';
		Logo.stripeColor = '#' + (Logo.queryObj.foreColor ? Logo.queryObj.foreColor : Logo.backColor);
		Logo.letters = Logo.queryObj.logoLetter.split("|");
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : 0;
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : "Calibri";
	}

	Logo.url = 'http://' + window.location.hostname + '/?backColor=' + Logo.backColor+ '&fontColor=' + Logo.fontColor + '&fontStroke=' + Logo.fontStroke + '&backStyle=' + Logo.backStyle + '&stripeColor=' + Logo.stripeColor + '&logoLetter=' + Logo.letters.join('|');

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
		},
		fill: "cecece",
		opacity: .25
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

})();<|endoftext|>