<commit_before> $(document).on("ready" ,function(){

              listarCarteraAnios();
              listaCarteraInversion(); //LLAMAR AL METODO LISTAR MODALIDAD DE EJECUCION
             //creacion de cartera //

                      $("#form-RegistraCarteraInv").submit(function(event)//AÑADIR NUEVA CARTERA
                       {
                            event.preventDefault();
                            var formData=new FormData($("#form-RegistraCarteraInv")[0]);
                            $.ajax({
                                type:"POST",
                                enctype: 'multipart/form-data',
                                url:base_url+"index.php/CarteraInversion/AddCartera",
                                data: formData,
                                cache: false,
                                contentType:false,
                                processData:false,
                                success:function(resp){
                                 swal("",resp, "success");
                                 $('#table-CarteraInv').dataTable()._fnAjaxUpdate();
                               }

                            });
                                   $('#form-RegistraCarteraInv')[0].reset();
                                   $("#VentanaRegistraCarteraInv").modal("hide");

                       });

            });

//-------------- MANTENIMIENTO MODALIDAD DE EJECUCION--------------------------

/*LISTAR CARTERA ACTUAL*/
         // TRAER DATOS DE LA CARTERA ACTUAL PARA SU PROGRAMACION
                /* listar y lista en tabla entidadr*/
var listaCarteraInversion=function()
{
	var table=$("#table-CarteraInv").DataTable(
	{
		"processing" : true,
		"serverSide" : false,
		"destroy" : true,
		"language" : idioma_espanol,
		"ajax" :
		{
			"url" : base_url+"index.php/CarteraInversion/GetCarteraInversion",
			"method" : "POST",
			"dataSrc" : ""
		},
		"columns" : [
		{
			"data" : "anios", "mRender" : function(data, type, full)
			{
				return '' + data + '';
			}
		},
		{ "data" : "fecha_inicio_cartera" },
		{ "data" : "fecha_cierre_cartera" },
		{
			"data" : "estado_cartera", "mRender" : function(value, type, object)
			{
				return (value==1 ? 'Activo' : 'Inactivo');
			}
		},
		{ "data" : "numero_resolucion_cartera" },
		{ "data" : "url_resolucion_cartera" },
		{ "defaultContent" : "<button type='button' class='editar btn btn-success btn-xs' data-toggle='modal' data-target='#VentanaVerCartera'></button><button type='button' class='eliminar btn btn-danger btn-xs' data-toggle='modal' data-target='#'></button>" }],
	});

	$('#table-CarteraInv tbody').on('click', 'tr', function()
	{
		var data=table.row( this ).data();

		var txt_IdfuncionM=data.id_cartera;
	});

	CambioCartera("#table-CarteraInv",table);  //obtener data de funcion para agregar  AGREGAR
}
          //FIN TRAER DATOS DE LA CARTERA ACTUAL PARA SU PROGRAMACION
/*FIN DE LISTAR MODALIDAD EJECUCION EN UN DATATABLE*/

//-------------- FIN MANTENIMIENTO MODALIDAD DE EJECUCION----------------------
var CambioCartera=function(tbody,table){
                      $(tbody).on("click","a.CambioCartera",function(){
                        var data=table.row( $(this).parents("tr")).data();
                        var AnoCartera=data.anios;
                        $("#AnioCartera").val(AnoCartera);
                        console.log(AnioCartera);

                      });
}

function listarCarteraAnios()
{
	event.preventDefault();

	var htmlTemp='';

	var anioActualTemp=$('#Aniocartera').val();

	$.ajax(
	{
		"url" : base_url+"index.php/CarteraInversion/GetCarteraAnios",
		type : "POST",
		success : function(respuesta)
		{

			var registros=eval(respuesta);

			for(var i=0; i<registros.length;i++)
			{
				htmlTemp +="<option "+(anioActualTemp==registros[i]["anios"] ? "selected" : "")+" value="+registros[i]["anios"]+"> "+ registros[i]["anios"]+" </option>";
			}

			$("#cbCartera").html(htmlTemp);

			$('.selectpicker').selectpicker('refresh');
		}
	});
}<commit_msg>funciones para grabar cartera<commit_after> $(document).on("ready" ,function(){

              listaCarteraInversion(); //LLAMAR AL METODO LISTAR MODALIDAD DE EJECUCION
             //creacion de cartera //
 /*
                      $("#form-RegistraCarteraInv").submit(function(event)//AÑADIR NUEVA CARTERA
                       {
                            event.preventDefault();
                            var formData=new FormData($("#form-RegistraCarteraInv")[0]);
                            $.ajax({
                                type:"POST",
                                enctype: 'multipart/form-data',
                                url:base_url+"index.php/CarteraInversion/AddCartera",
                                data: formData,
                                cache: false,
                                contentType:false,
                                processData:false,
                                success:function(resp){
                                 swal("",resp, "success");
                                 $('#table-CarteraInv').dataTable()._fnAjaxUpdate();
                               }

                            });
                                   $('#form-RegistraCarteraInv')[0].reset();
                                   $("#VentanaRegistraCarteraInv").modal("hide");

                       });

*/
            });

//-------------- MANTENIMIENTO MODALIDAD DE EJECUCION--------------------------

/*LISTAR CARTERA ACTUAL*/
         // TRAER DATOS DE LA CARTERA ACTUAL PARA SU PROGRAMACION
                /* listar y lista en tabla entidadr*/
var listaCarteraInversion=function()
{
	var table=$("#table-CarteraInv").DataTable(
	{
		"processing" : true,
		"serverSide" : false,
		"destroy" : true,
		"language" : idioma_espanol,
		"ajax" :
		{
			"url" : base_url+"index.php/CarteraInversion/GetCarteraInversion",
			"method" : "POST",
			"dataSrc" : ""
		},
		"columns" : [
		{
			"data" : "anios", "mRender" : function(data, type, full)
			{
				return '' + data + '';
			}
		},
		{ "data" : "fecha_inicio_cartera" },
		{ "data" : "fecha_cierre_cartera" },
		{
			"data" : "estado_cartera", "mRender" : function(value, type, object)
			{
				return (value==1 ? 'Activo' : 'Inactivo');
			}
		},
		{ "data" : "numero_resolucion_cartera" },
		//{ "data" : "url_resolucion_cartera" },
		{"data":'url_resolucion_cartera',render: function ( data, type, row ) {
				if(row.url_resolucion_cartera=='' || row.url_resolucion_cartera==null)
					return '';
				else
					return "";

			}
		},
		/*{ "defaultContent" : "<button type='button' class='editar btn btn-success btn-xs' data-toggle='modal' data-target='#VentanaVerCartera'></button><button type='button' class='eliminar btn btn-danger btn-xs' data-toggle='modal' data-target='#'></button>" }*/
		{"data":'anios',render: function ( data, type, row ) {
			    return "<button type='button'  data-toggle='tooltip'  class='editar btn btn-primary btn-xs' data-toggle='modal' onclick=paginaAjaxDialogo('null','Modificar',{id_cartera:"+row.id_cartera+"},'"+base_url+"index.php/CarteraInversion/itemCartera','GET',null,null,false,true);></button>";
			}
		}

		],
	});

	$('#table-CarteraInv tbody').on('click', 'tr', function()
	{
		var data=table.row( this ).data();

		var txt_IdfuncionM=data.id_cartera;
	});

	CambioCartera("#table-CarteraInv",table);  //obtener data de funcion para agregar  AGREGAR
}
          //FIN TRAER DATOS DE LA CARTERA ACTUAL PARA SU PROGRAMACION
/*FIN DE LISTAR MODALIDAD EJECUCION EN UN DATATABLE*/

//-------------- FIN MANTENIMIENTO MODALIDAD DE EJECUCION----------------------
var CambioCartera=function(tbody,table){
                      $(tbody).on("click","a.CambioCartera",function(){
                        var data=table.row( $(this).parents("tr")).data();
                        var AnoCartera=data.anios;
                        $("#AnioCartera").val(AnoCartera);
                        console.log(AnioCartera);

                      });
}

function listarCarteraAnios()
{
	event.preventDefault();

	var htmlTemp='';

	var anioActualTemp=$('#Aniocartera').val();

	$.ajax(
	{
		"url" : base_url+"index.php/CarteraInversion/GetCarteraAnios",
		type : "POST",
		success : function(respuesta)
		{

			var registros=eval(respuesta);

			for(var i=0; i<registros.length;i++)
			{
				htmlTemp +="<option "+(anioActualTemp==registros[i]["anios"] ? "selected" : "")+" value="+registros[i]["anios"]+"> "+ registros[i]["anios"]+" </option>";
			}

			$("#cbCartera").html(htmlTemp);

			$('.selectpicker').selectpicker('refresh');
		}
	});
}<|endoftext|>


<commit_before>/**
 * Created by MIC on 2015/12/29.
 */

/**
 * @type {Bulletproof}
 */
var bp = null;
/**
 * @type {number}
 * @private
 */
var __timerHandle = 0;

window.document.body.onload = function () {
    initEnv();
    initList();
};

window.addEventListener("beforeunload", function (ev) {
    if (!bp) {
        return;
    }
    uninitFps();
    bp.dispose();
    bp = null;
});

function initEnv() {
    if (Bulletproof.isSupported()) {
        bp = new Bulletproof.Bulletproof();
        bp.initialize(682, 438);
        (function (selector) {
            var elem = document.querySelector(selector);
            elem.appendChild(bp.videoView);
            bp.videoView.style.position = "absolute";
            elem.appendChild(bp.view);
            bp.view.style.position = "absolute";
            bp.view.style.zIndex = "9999";
        })("#glantern-container");
    }
}

function initList() {
    var testCases = {
        "Blank": "",
        "3D ball": "3d-ball.js",
        "Green Dam Musume": "kanpai-green-dam.js",
        "Madoka and her happy tree friends": "kanpai-madoka.js"
    };

    var caseListElem = document.querySelector("#test-case-selector");
    if (Bulletproof.isSupported() && bp) {
        initListNormal();
    } else {
        initListOnFailure();
    }

    function onClick(ev) {
        /**
         * @type {HTMLAnchorElement}
         */
        var aElem = this;
        var e;
        e = document.querySelector("#test-case-selector-container");
        e.style.display = "none";
        e = document.querySelector("#test-case-desc");
        e.textContent = aElem.name || "(blank)";
        e = document.querySelector("#playground");
        e.style.display = "block";
        if (aElem.name) {
            executeCodeDanmakuContent(aElem.name);
        }
        initFps();
        bp.startAnimation();
    }

    /**
     * Execute a single script by injecting the script into the window.
     * @param fileName {String} Full JavaScript file name.
     */
    function executeCodeDanmakuContent(fileName) {
        var content;
        if (typeof global !== typeof undefined) {
            // In Node.js environments
            var fs = require("fs");
            content = fs.readFileSync(fileName, "utf-8");
        } else {
            // In common browsers
            // Note: Please view on a server. Local file access is forbidden due to safety restrictions.
            content = loadFileSync(fileName);
        }
        var codeProvider = bp.danmakuCoordinator.getDanmakuProvider(Bulletproof.danmaku.DanmakuKind.Code);
        codeProvider.addDanmaku(content);
    }

    /**
     * Load a text file content from specified path.
     * @param path {String} The file path.
     */
    function loadFileSync(path) {
        /**
         * @type {XMLHttpRequest}
         */
        var xhr = new XMLHttpRequest();
        xhr.open("GET", path, false);
        xhr.send();
        return xhr.responseText;
    }

    function initListNormal() {
        for (var caseName in testCases) {
            if (testCases.hasOwnProperty(caseName)) {
                /**
                 * @type {HTMLLIElement}
                 */
                var liElem = document.createElement("li");
                /**
                 * @type {HTMLAnchorElement}
                 */
                var aElem = document.createElement("a");
                aElem.innerHTML = caseName;
                aElem.href = "javascript:;";
                if (testCases[caseName]) {
                    aElem.name = "test-scripts/" + testCases[caseName];
                }
                aElem.onclick = onClick.bind(aElem);
                liElem.appendChild(aElem);
                caseListElem.appendChild(liElem);

                if (aElem.name) {
                    var blankElem = document.createElement("span");
                    blankElem.textContent = " #";
                    var viewSourceElem = document.createElement("a");
                    viewSourceElem.href = aElem.name;
                    viewSourceElem.textContent = "View source";
                    viewSourceElem.target = "_blank";
                    liElem.appendChild(blankElem);
                    liElem.appendChild(viewSourceElem);
                }
            }
        }
    }

    function initListOnFailure() {
        /**
         * @type {HTMLLIElement}
         */
        var liElem = document.createElement("li");
        liElem.textContent = "Oops, it seems that Bulletproof is not supported by your browser.";
        caseListElem.appendChild(liElem);
    }
}

function initFps() {
    if (!bp) {
        return;
    }
    __timerHandle = setInterval(function () {
        document.getElementById("fps-indicator").textContent = (Math.round(bp.fps * 100) / 100).toString();
    }, 1000);
}

function uninitFps() {
    if (!bp) {
        return;
    }
    if (__timerHandle !== 0) {
        clearInterval(__timerHandle);
    }
}

function addFlyingDanmaku() {
    if (!bp){
        return;
    }
    /**
     * @type {SimpleDanmakuProvider}
     */
    var provider = bp.danmakuCoordinator.getDanmakuProvider(Bulletproof.danmaku.DanmakuKind.Simple);
    /**
     * @type {HTMLInputElement}
     */
    var textBox = document.querySelector("#input-danmaku");
    provider.addDanmaku(textBox.value);
}
<commit_msg>Mild fix.<commit_after>/**
 * Created by MIC on 2015/12/29.
 */

/**
 * @type {Bulletproof}
 */
var bp = null;
/**
 * @type {number}
 * @private
 */
var __timerHandle = 0;

window.document.body.onload = function () {
    initEnv();
    initList();
};

window.addEventListener("beforeunload", function (ev) {
    if (!bp) {
        return;
    }
    uninitFps();
    bp.dispose();
    bp = null;
});

function initEnv() {
    if (Bulletproof.isSupported()) {
        bp = new Bulletproof.Bulletproof();
        bp.initialize(682, 438);
        (function (selector) {
            var elem = document.querySelector(selector);
            elem.appendChild(bp.videoView);
            bp.videoView.style.position = "absolute";
            bp.videoView.style.zIndex = "1";
            elem.appendChild(bp.view);
            bp.view.style.position = "absolute";
            bp.view.style.zIndex = "9999";
        })("#glantern-container");
    }
}

function initList() {
    var testCases = {
        "Blank": "",
        "3D ball": "3d-ball.js",
        "Green Dam Musume": "kanpai-green-dam.js",
        "Madoka and her happy tree friends": "kanpai-madoka.js"
    };

    var caseListElem = document.querySelector("#test-case-selector");
    if (Bulletproof.isSupported() && bp) {
        initListNormal();
    } else {
        initListOnFailure();
    }

    function onClick(ev) {
        /**
         * @type {HTMLAnchorElement}
         */
        var aElem = this;
        var e;
        e = document.querySelector("#test-case-selector-container");
        e.style.display = "none";
        e = document.querySelector("#test-case-desc");
        e.textContent = aElem.name || "(blank)";
        e = document.querySelector("#playground");
        e.style.display = "block";
        if (aElem.name) {
            executeCodeDanmakuContent(aElem.name);
        }
        initFps();
        bp.startAnimation();
    }

    /**
     * Execute a single script by injecting the script into the window.
     * @param fileName {String} Full JavaScript file name.
     */
    function executeCodeDanmakuContent(fileName) {
        var content;
        if (typeof global !== typeof undefined) {
            // In Node.js environments
            var fs = require("fs");
            content = fs.readFileSync(fileName, "utf-8");
        } else {
            // In common browsers
            // Note: Please view on a server. Local file access is forbidden due to safety restrictions.
            content = loadFileSync(fileName);
        }
        var codeProvider = bp.danmakuCoordinator.getDanmakuProvider(Bulletproof.danmaku.DanmakuKind.Code);
        codeProvider.addDanmaku(content);
    }

    /**
     * Load a text file content from specified path.
     * @param path {String} The file path.
     */
    function loadFileSync(path) {
        /**
         * @type {XMLHttpRequest}
         */
        var xhr = new XMLHttpRequest();
        xhr.open("GET", path, false);
        xhr.send();
        return xhr.responseText;
    }

    function initListNormal() {
        for (var caseName in testCases) {
            if (testCases.hasOwnProperty(caseName)) {
                /**
                 * @type {HTMLLIElement}
                 */
                var liElem = document.createElement("li");
                /**
                 * @type {HTMLAnchorElement}
                 */
                var aElem = document.createElement("a");
                aElem.innerHTML = caseName;
                aElem.href = "javascript:;";
                if (testCases[caseName]) {
                    aElem.name = "test-scripts/" + testCases[caseName];
                }
                aElem.onclick = onClick.bind(aElem);
                liElem.appendChild(aElem);
                caseListElem.appendChild(liElem);

                if (aElem.name) {
                    var blankElem = document.createElement("span");
                    blankElem.textContent = " #";
                    var viewSourceElem = document.createElement("a");
                    viewSourceElem.href = aElem.name;
                    viewSourceElem.textContent = "View source";
                    viewSourceElem.target = "_blank";
                    liElem.appendChild(blankElem);
                    liElem.appendChild(viewSourceElem);
                }
            }
        }
    }

    function initListOnFailure() {
        /**
         * @type {HTMLLIElement}
         */
        var liElem = document.createElement("li");
        liElem.textContent = "Oops, it seems that Bulletproof is not supported by your browser.";
        caseListElem.appendChild(liElem);
    }
}

function initFps() {
    if (!bp) {
        return;
    }
    __timerHandle = setInterval(function () {
        document.getElementById("fps-indicator").textContent = (Math.round(bp.fps * 100) / 100).toString();
    }, 1000);
}

function uninitFps() {
    if (!bp) {
        return;
    }
    if (__timerHandle !== 0) {
        clearInterval(__timerHandle);
    }
}

function addFlyingDanmaku() {
    if (!bp){
        return;
    }
    /**
     * @type {SimpleDanmakuProvider}
     */
    var provider = bp.danmakuCoordinator.getDanmakuProvider(Bulletproof.danmaku.DanmakuKind.Simple);
    /**
     * @type {HTMLInputElement}
     */
    var textBox = document.querySelector("#input-danmaku");
    provider.addDanmaku(textBox.value);
}
<|endoftext|>


<commit_before>/**
 * Main JS file for GhostScroll behaviours
 */

var $post = $('.post');
var $first = $('.post.first');
var $last = $('.post.last');
var $fnav = $('.fixed-nav');
var $postholder = $('.post-holder');
var $postafter = $('.post-after');
var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	"use strict";
	function srcTo (el) {
		$('html, body').animate({
			scrollTop: el.offset().top
		}, 1000);
	}
	$(document).ready(function(){

        // FitVids for responsive videos
        $('.post-content').fitVids();

		$postholder.each(function (e) {
			if(e % 2 != 0)
				$(this).addClass("odd");
		});

		$postafter.each(function (e) {
			var bg = $(this).parent().css('background-color')
			$(this).css('border-top-color', bg);

			if (e % 2 == 0) {
				$(this).addClass("even");
			}
		});

		$('.btn.first').click( function () {
			srcTo($first);
		});
		$('.btn.last').click( function () {
			srcTo($last);
		});
		$('#header-arrow').click(function () {
			srcTo($first);
		});
        $('#totop-arrow').click(function () {
            srcTo($sitehead);
        });

		$('.post-title').each(function () {
			var t = $(this).text();
			var index = $(this).parents('.post-holder').index();
			$fnav.append(""+t+"")
			$(this).parents('article').attr('id',t.toLowerCase().split(' ').join('-'));
			$('.fn-item').click(function () {
				var i = $(this).attr('item_index');
				var s = $(".post[item_index='"+i+"']");

				$('html, body').animate({
					scrollTop: s.offset().top
				}, 400);

			});
		});

		$('.post.last').next('.post-after').hide();
		if($sitehead.length) {
			$(window).scroll( function () {
				var w = $(window).scrollTop();
				var g = $sitehead.offset().top;
				var h = $sitehead.offset().top + $(this).height()-100;

				if(w >= g && w<=h) {
					$('.fixed-nav').fadeOut('fast');
				} else if($(window).width()>500) {
					$('.fixed-nav').fadeIn('fast');
				}

				$post.each(function () {
					var f = $(this).offset().top;
					var b = $(this).offset().top + $(this).height();
					var t = $(this).parent('.post-holder').index();
					var i = $(".fn-item[item_index='"+t+"']");
					var a = $(this).parent('.post-holder').prev('.post-holder').find('.post-after');

					$(this).attr('item_index', t);

					if(w >= f && w<=b) {
						i.addClass('active');
						a.fadeOut('slow');
					} else {
						i.removeClass('active');
						a.fadeIn('slow');
					}
				});
			});
		}

		$('ul li').before('');
		$('blockquote p').prepend('');
		$('blockquote p').append('');
	});

	$post.each(function () {
		var postText = $(this).html();
		var fa  = [];
		for(var i=0; i < icons.length; i++) {
			fa[i]       = {};
			fa[i].str   = "@"+ icons[i]+ "@";
			fa[i].icon  = icons[i];
			fa[i].int   = postText.search(fa[i].str);

			if(fa[i].int > -1 ) {
				fa[i].count = postText.match(new RegExp(fa[i].str,"g")).length;
				for(var j=0; j < fa[i].count; j++) {
					$(this).html($(this).html().replace(fa[i].str, ""))
				}
			}
		}
	});

}(jQuery));
<commit_msg>Add paralex header like all the cool kids<commit_after>/**
 * Main JS file for GhostScroll behaviours
 */

var $post = $('.post');
var $first = $('.post.first');
var $last = $('.post.last');
var $fnav = $('.fixed-nav');
var $postholder = $('.post-holder');
var $postafter = $('.post-after');
var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	"use strict";
	function srcTo (el) {
		$('html, body').animate({
			scrollTop: el.offset().top
		}, 1000);
	}
	$(document).ready(function(){

        // FitVids for responsive videos
        $('.post-content').fitVids();

		$postholder.each(function (e) {
			if(e % 2 != 0)
				$(this).addClass("odd");
		});

		$postafter.each(function (e) {
			var bg = $(this).parent().css('background-color')
			$(this).css('border-top-color', bg);

			if (e % 2 == 0) {
				$(this).addClass("even");
			}
		});

		$('.btn.first').click( function () {
			srcTo($first);
		});
		$('.btn.last').click( function () {
			srcTo($last);
		});
		$('#header-arrow').click(function () {
			srcTo($first);
		});
        $('#totop-arrow').click(function () {
            srcTo($sitehead);
        });

		$('.post-title').each(function () {
			var t = $(this).text();
			var index = $(this).parents('.post-holder').index();
			$fnav.append(""+t+"")
			$(this).parents('article').attr('id',t.toLowerCase().split(' ').join('-'));
			$('.fn-item').click(function () {
				var i = $(this).attr('item_index');
				var s = $(".post[item_index='"+i+"']");

				$('html, body').animate({
					scrollTop: s.offset().top
				}, 400);

			});
		});

		$('.post.last').next('.post-after').hide();
		if($sitehead.length) {
			$(window).scroll( function () {
				var w = $(window).scrollTop();
				var g = $sitehead.offset().top;
				var h = $sitehead.offset().top + $sitehead.height()-100;

				var paralex = 30 + w/13 + "%";
				$sitehead.css("background-position-y", paralex);

				if(w >= g && w<=h) {
					$('.fixed-nav').fadeOut('fast');
				} else if($(window).width()>500) {
					$('.fixed-nav').fadeIn('fast');
				}

				$post.each(function () {
					var f = $(this).offset().top;
					var b = $(this).offset().top + $(this).height();
					var t = $(this).parent('.post-holder').index();
					var i = $(".fn-item[item_index='"+t+"']");
					var a = $(this).parent('.post-holder').prev('.post-holder').find('.post-after');

					$(this).attr('item_index', t);

					if(w >= f && w<=b) {
						i.addClass('active');
						a.fadeOut('slow');
					} else {
						i.removeClass('active');
						a.fadeIn('slow');
					}
				});
			});
		}

		$('ul li').before('');
		$('blockquote p').prepend('');
		$('blockquote p').append('');
	});

	$post.each(function () {
		var postText = $(this).html();
		var fa  = [];
		for(var i=0; i < icons.length; i++) {
			fa[i]       = {};
			fa[i].str   = "@"+ icons[i]+ "@";
			fa[i].icon  = icons[i];
			fa[i].int   = postText.search(fa[i].str);

			if(fa[i].int > -1 ) {
				fa[i].count = postText.match(new RegExp(fa[i].str,"g")).length;
				for(var j=0; j < fa[i].count; j++) {
					$(this).html($(this).html().replace(fa[i].str, ""))
				}
			}
		}
	});

}(jQuery));
<|endoftext|>


<commit_before>'use strict';

//recursive
function calcNFibonacci(n){
  if(n === 2) return 1;
  if(n <= 1){
    return 0;
  }
  return calcNFibonacci(n-1) + calcNFibonacci(n-2);
}

console.log(calcNFibonacci(3));
console.log(calcNFibonacci(4));
console.log(calcNFibonacci(5));
console.log(calcNFibonacci(6));
console.log(calcNFibonacci(7));
console.log(calcNFibonacci(8));
console.log(calcNFibonacci(9));
console.log(calcNFibonacci(10));
console.log(calcNFibonacci(11));

function calcNFibIter(n){
  if(!n) return 'please enter a number';
  if(n === 1) return 0;
  if(n === 2) return 1;
  let first = 0;
  let second = 1;
  let count = 2;
  while(count < n){
    let current = first + second;
    first = second;
    second = current;
    count++;
  }
  return second;
}

console.log(calcNFibIter(3));
console.log(calcNFibIter(4));
console.log(calcNFibIter(5));
console.log(calcNFibIter(6));
console.log(calcNFibIter(7));
console.log(calcNFibIter(8));
console.log(calcNFibIter(9));
<commit_msg>first attempt at memoization fib still have work to do<commit_after>'use strict';

//recursive
// function calcNFibonacci(n){
//   if(n === 2) return 1;
//   if(n <= 1){
//     return 0;
//   }
//   return calcNFibonacci(n-1) + calcNFibonacci(n-2);
// }
//
// console.log(calcNFibonacci(3));
// console.log(calcNFibonacci(4));
// console.log(calcNFibonacci(5));
// console.log(calcNFibonacci(6));
// console.log(calcNFibonacci(7));
// console.log(calcNFibonacci(8));
// console.log(calcNFibonacci(9));
// console.log(calcNFibonacci(10));
// console.log(calcNFibonacci(11));

function calcNFibMemo(n){
  if(n === 1) return 0;
  if(n === 2) return 1;
  let obj = {1 : 0, 2 : 1};
  function calcRecur(n){
    if(obj[n - 1] >= 0 && obj[n - 2] >= 0) {
      obj[n] = obj[n - 1] + obj[n-2];
    } else if(obj[n-1] >= 0){
      obj[n] =  obj[n-1] + calcRecur(n-2);
    } else if(obj[n-2] >= 0){
      obj[n] = calcRecur(n-1) + obj[n-2];
    } else {
      obj[n] = calcRecur(n-1) + calcRecur(n-2);
    }
  }
  calcRecur(n);
  return obj[n]
}

console.log(calcNFibMemo(3));
console.log(calcNFibMemo(4));
console.log(calcNFibMemo(5));
console.log(calcNFibMemo(6));
console.log(calcNFibMemo(7));
console.log(calcNFibMemo(8));
console.log(calcNFibMemo(15));

// function calcNFibIter(n){
//   if(!n) return 'please enter a number';
//   if(n === 1) return 0;
//   if(n === 2) return 1;
//   let first = 0;
//   let second = 1;
//   let count = 2;
//   while(count < n){
//     let current = first + second;
//     first = second;
//     second = current;
//     count++;
//   }
//   return second;
// }
//
// console.log(calcNFibIter(3));
// console.log(calcNFibIter(4));
// console.log(calcNFibIter(5));
// console.log(calcNFibIter(6));
// console.log(calcNFibIter(7));
// console.log(calcNFibIter(8));
// console.log(calcNFibIter(9));
<|endoftext|>


<commit_before>"use strict";

/**
 * Main JS file for GhostScroll behaviours
 */

var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	$(document).ready(initialize);
	$(window).resize(onViewportChange);
	$(window).scroll(onViewportChange);

	function initialize() {
		setupJumpHandlers();
		fontAwesomeDecorators();
		fontAwesomeReplacement();

		function setupJumpHandlers() {
                    // FitVids for responsive videos
            $('.post-content').fitVids();
                    // Arrow top in fixed menu
            $('#totop-arrow').click(function () {
            smoothScroll($sitehead);
            });
			$('#header-arrow').click( function () {
				var $first = $(".post").first();
				smoothScroll($first);
			});

			$('.fn-item, .btn').click(function (evt) {
        var $this = $(this);
				var href = $this.attr("href");

        // We don't want to prevent a link from working if it is external.
        if (href.slice(0,1) === "#") {
          evt.preventDefault();
          var title = $(this).text();
          window.history.pushState(title, title, href);
          smoothScroll($(href))
        }
			});
		}

		function fontAwesomeDecorators() {
			$('ul > li').before('');
			$('blockquote p').prepend('');
			$('blockquote p').append('');
		}

		function fontAwesomeReplacement() {
			// // Matches
			// @fa-singleword@
			// @fa-dash-separated-words@
			// // Does *not* match
			// \@fa-escaped@
			// @fa-space separated@
			// @fa-Invalid-Case@
			// @fa-Invalid-(H^R@
			// @fa-will-match@@fa-will-not-match@
			//
			// Note: JS doesn't support negative lookbehinds. Thus to permit
			// escaped examples (\@fa-foo@) we capture the preceeding
			// character. This shouldn't pose a problem except in the event of
			// adjacent font-awesome characters (that are not space separated).
			// See last example above.
			var reg = /([^\\])@(fa-[-a-z]+)@/g;

			var $posts = $("#posts-wrapper")
			$posts.html($posts.html().replace(reg, "$1"));
		}
	}

	function onViewportChange() {
		conditionallyShowNav();
		highlightActiveSection();

		function conditionallyShowNav() {
      var isTooNarrow = $(window).width() < 500;
      var shouldDisplayNav = !isTooNarrow && !isElementInViewport($sitehead);
			var navOpacity = shouldDisplayNav ? 1 : 0;
			$(".fixed-nav").css("opacity", navOpacity);
		}

		function highlightActiveSection() {
			$(".post-holder").each(function () {
				var $this = $(this);
				var postId = $this.attr("id");
				var $thisNavLink = $(".fn-item[href='#" + postId + "']");
				var $previousArrow = $(this).prev('.post-holder').find('.post-after');

				if(isElementInViewport($this)) {
					$thisNavLink.addClass('active');
					$previousArrow.fadeOut('slow');
				} else {
					$thisNavLink.removeClass('active');
					$previousArrow.fadeIn('slow');
				}
			});
		}

		function isElementInViewport($element) {
			var scrollPosition = $(window).scrollTop();
			var topOfElement = $element.offset().top;
			var bottomOfElement = topOfElement + $element.height();

			var isAboveElement = topOfElement > scrollPosition;
			var isBelowElement = scrollPosition >= bottomOfElement;

			return (!isAboveElement && !isBelowElement);
		}
	}

	function smoothScroll ($element) {
		$('html, body').animate({
			scrollTop: $element.offset().top
		}, 400);
	}

}(jQuery));<commit_msg>readded scroll to first using "btn first" button<commit_after>"use strict";

/**
 * Main JS file for GhostScroll behaviours
 */

var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	$(document).ready(initialize);
	$(window).resize(onViewportChange);
	$(window).scroll(onViewportChange);

	function initialize() {
		setupJumpHandlers();
		fontAwesomeDecorators();
		fontAwesomeReplacement();

		function setupJumpHandlers() {
                    // FitVids for responsive videos
            $('.post-content').fitVids();
                    // Arrow top in fixed menu
            $('#totop-arrow').click(function () {
            smoothScroll($sitehead);
            });
			$('#header-arrow').click( function () {
				var $first = $(".post").first();
				smoothScroll($first);
			});

            $('.btn.first').click( function () {
			    var $first = $(".post").first();
				smoothScroll($first);
		    });

			$('.fn-item, .btn').click(function (evt) {
        var $this = $(this);
				var href = $this.attr("href");

        // We don't want to prevent a link from working if it is external.
        if (href.slice(0,1) === "#") {
          evt.preventDefault();
          var title = $(this).text();
          window.history.pushState(title, title, href);
          smoothScroll($(href))
        }
			});
		}

		function fontAwesomeDecorators() {
			$('ul > li').before('');
			$('blockquote p').prepend('');
			$('blockquote p').append('');
		}

		function fontAwesomeReplacement() {
			// // Matches
			// @fa-singleword@
			// @fa-dash-separated-words@
			// // Does *not* match
			// \@fa-escaped@
			// @fa-space separated@
			// @fa-Invalid-Case@
			// @fa-Invalid-(H^R@
			// @fa-will-match@@fa-will-not-match@
			//
			// Note: JS doesn't support negative lookbehinds. Thus to permit
			// escaped examples (\@fa-foo@) we capture the preceeding
			// character. This shouldn't pose a problem except in the event of
			// adjacent font-awesome characters (that are not space separated).
			// See last example above.
			var reg = /([^\\])@(fa-[-a-z]+)@/g;

			var $posts = $("#posts-wrapper")
			$posts.html($posts.html().replace(reg, "$1"));
		}
	}

	function onViewportChange() {
		conditionallyShowNav();
		highlightActiveSection();

		function conditionallyShowNav() {
      var isTooNarrow = $(window).width() < 500;
      var shouldDisplayNav = !isTooNarrow && !isElementInViewport($sitehead);
			var navOpacity = shouldDisplayNav ? 1 : 0;
			$(".fixed-nav").css("opacity", navOpacity);
		}

		function highlightActiveSection() {
			$(".post-holder").each(function () {
				var $this = $(this);
				var postId = $this.attr("id");
				var $thisNavLink = $(".fn-item[href='#" + postId + "']");
				var $previousArrow = $(this).prev('.post-holder').find('.post-after');

				if(isElementInViewport($this)) {
					$thisNavLink.addClass('active');
					$previousArrow.fadeOut('slow');
				} else {
					$thisNavLink.removeClass('active');
					$previousArrow.fadeIn('slow');
				}
			});
		}

		function isElementInViewport($element) {
			var scrollPosition = $(window).scrollTop();
			var topOfElement = $element.offset().top;
			var bottomOfElement = topOfElement + $element.height();

			var isAboveElement = topOfElement > scrollPosition;
			var isBelowElement = scrollPosition >= bottomOfElement;

			return (!isAboveElement && !isBelowElement);
		}
	}

	function smoothScroll ($element) {
		$('html, body').animate({
			scrollTop: $element.offset().top
		}, 400);
	}

}(jQuery));<|endoftext|>


<commit_before>function initMap(msg, data) {
    // Eyes wide open for this narly hack.
    // There are lots of different ways to put a D3 layer on Leaflet, and I found
    // them all to be annoying and/or weird. So, here I'm adding the topojson as a
    // regular leaflet layer so Leaflet can manage zooming/redrawing/events/etc. However,
    // I want D3 to manage symbolization et al, so I rely on the fact that Leaflet
    // adds the polys in the topojson order to add a data-id and geom class to the
    // layer so I can handle it D3-ish rather than through the Leaflet API.

    d3Layer = L.geoJson(topojson.feature(data.geom, data.geom.objects[neighborhoods]), {
        style: {
            "fillColor": "rgba(0,0,0,0)",
            "color": "none",
            "fillOpacity": 1
        }
    }).addTo(map);

    map.setMaxBounds(d3Layer.getBounds());

    d3.selectAll(".leaflet-overlay-pane svg path").attr("class", "geom metric-hover").attr("data-id", function(d, i) {
      try {
        return data.geom.objects[neighborhoods].geometries[i].id;
      } catch (e) {
        console.log("i " + i + " " + e);
      }
    });

    d3Layer.on("click", function(d) {
        var sel = d3.select(".geom[data-id='" + d.layer.feature.id + "']");
        PubSub.publish('selectGeo', {
            "id": sel.attr("data-id"),
            "value": sel.attr("data-value"),
            "d3obj": sel
        });
    });

    $(".geom").on({
        mouseenter: function(){
            addHighlight($(this));
        },
        mouseleave: function(){
            removeHighlight($(this));
        }
    });

    $(".geom").tooltip({
        html: true,
        title: function() {
            var sel = $(this),
                num = "";
            if ($.isNumeric(sel.attr("data-value"))) {
                num = dataPretty(sel.attr("data-value"), $("#metric").val());
            }
            return "
Precinct: " + precinctName(sel.attr("data-id")) + "" + num + "
";
        },
        container: '#map'
    });

    // Here's where you would load other crap in your topojson for display purposes.
    // Change the styling here as desired.
    if (typeof overlay !== 'undefined') {
        L.geoJson(topojson.feature(data.geom, data.geom.objects[overlay]), {
            style: {
                "fillColor": "rgba(0,0,0,0)",
                "color": "#4a4a4a",
                "fillOpacity": 0.5,
                "opacity": 0.5,
                "weight": 1
            }
        }).addTo(map);
        console.log('added');
    }
}

function drawMap(msg, data) {
    var theMetric = $("#metric").val();
    var theGeom = d3.selectAll(".geom");

    // clear out quantile classes
    var classlist = [];
    for (i = 0; i < colorbreaks; i++) {
        classlist.push("q" + i);
    }
    theGeom.classed(classlist.join(" "), false);

    var theData = metricData[year].map;
    theGeom.each(function() {
        var item = d3.select(this);
        var styleClass = quantize(theData.get(item.attr('data-id')));
        if (!styleClass) {
            styleClass = "";
        }
        item.classed(styleClass, true)
            .attr("data-value", theData.get(item.attr('data-id')))
            .attr("data-quantile", quantize(theData.get(item.attr('data-id'))))
            .attr("data-toggle", "tooltip");
    });

    var xScale = d3.scale.linear().domain(x_extent).range([0, $("#barChart").parent().width() - 60]);

    var y = d3.scale.linear().range([260, 0]).domain([0, 260]);
}
<commit_msg>Add padding to pan bounds<commit_after>function setPanBounds(padding) {
    // Creates pan bounds with custom padding around data extent.

    maxBounds = d3Layer.getBounds();
    southWest = maxBounds.getSouthWest();
    northEast = maxBounds.getNorthEast();
    newSouthWest = L.latLng(southWest.lat - padding, southWest.lng - padding);
    newNorthEast = L.latLng(northEast.lat + padding, northEast.lng + padding);
    return L.latLngBounds(newSouthWest, newNorthEast);

}

function initMap(msg, data) {
    // Eyes wide open for this narly hack.
    // There are lots of different ways to put a D3 layer on Leaflet, and I found
    // them all to be annoying and/or weird. So, here I'm adding the topojson as a
    // regular leaflet layer so Leaflet can manage zooming/redrawing/events/etc. However,
    // I want D3 to manage symbolization et al, so I rely on the fact that Leaflet
    // adds the polys in the topojson order to add a data-id and geom class to the
    // layer so I can handle it D3-ish rather than through the Leaflet API.

    d3Layer = L.geoJson(topojson.feature(data.geom, data.geom.objects[neighborhoods]), {
        style: {
            "fillColor": "rgba(0,0,0,0)",
            "color": "none",
            "fillOpacity": 1
        }
    }).addTo(map);

    map.setMaxBounds(setPanBounds(0.25));

    d3.selectAll(".leaflet-overlay-pane svg path").attr("class", "geom metric-hover").attr("data-id", function(d, i) {
      try {
        return data.geom.objects[neighborhoods].geometries[i].id;
      } catch (e) {
        console.log("i " + i + " " + e);
      }
    });

    d3Layer.on("click", function(d) {
        var sel = d3.select(".geom[data-id='" + d.layer.feature.id + "']");
        PubSub.publish('selectGeo', {
            "id": sel.attr("data-id"),
            "value": sel.attr("data-value"),
            "d3obj": sel
        });
    });

    $(".geom").on({
        mouseenter: function(){
            addHighlight($(this));
        },
        mouseleave: function(){
            removeHighlight($(this));
        }
    });

    $(".geom").tooltip({
        html: true,
        title: function() {
            var sel = $(this),
                num = "";
            if ($.isNumeric(sel.attr("data-value"))) {
                num = dataPretty(sel.attr("data-value"), $("#metric").val());
            }
            return "
Precinct: " + precinctName(sel.attr("data-id")) + "" + num + "
";
        },
        container: '#map'
    });

    // Here's where you would load other crap in your topojson for display purposes.
    // Change the styling here as desired.
    if (typeof overlay !== 'undefined') {
        L.geoJson(topojson.feature(data.geom, data.geom.objects[overlay]), {
            style: {
                "fillColor": "rgba(0,0,0,0)",
                "color": "#4a4a4a",
                "fillOpacity": 0.5,
                "opacity": 0.5,
                "weight": 1
            }
        }).addTo(map);
        console.log('added');
    }
}

function drawMap(msg, data) {
    var theMetric = $("#metric").val();
    var theGeom = d3.selectAll(".geom");

    // clear out quantile classes
    var classlist = [];
    for (i = 0; i < colorbreaks; i++) {
        classlist.push("q" + i);
    }
    theGeom.classed(classlist.join(" "), false);

    var theData = metricData[year].map;
    theGeom.each(function() {
        var item = d3.select(this);
        var styleClass = quantize(theData.get(item.attr('data-id')));
        if (!styleClass) {
            styleClass = "";
        }
        item.classed(styleClass, true)
            .attr("data-value", theData.get(item.attr('data-id')))
            .attr("data-quantile", quantize(theData.get(item.attr('data-id'))))
            .attr("data-toggle", "tooltip");
    });

    var xScale = d3.scale.linear().domain(x_extent).range([0, $("#barChart").parent().width() - 60]);

    var y = d3.scale.linear().range([260, 0]).domain([0, 260]);
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    console.log('Page has fully loaded')

    var values_to_load = {
      'large': [
        {
          'label': 'by Product Type',
          'id': 'product-type'
        },
        {
          'label': 'by Company',
          'id': 'company'
        },
        {
          'label': 'by Serial Number',
          'id': 'serial-number'
        }
      ],
      'statistical': [
        {
          'label': 'Read Speed',
          'id': 'read-speed'
        },
        {
          'label': 'Read Count',
          'id': 'read-count'
        },
        {
          'label': 'Write Speed',
          'id': 'write-count'
        },
        {
          'label': 'Write Count',
          'id': 'write-count'
        },
        {
          'label': 'Bandwidth',
          'id': 'bandwidth'
        },
        {
          'label': 'CPU',
          'id': 'cpu'
        }
      ]
    }

    var item;
    for(item in values_to_load.large) {
      var relevant = values_to_load.large[item];
      var s = "
"+relevant.label+"
";
      $('#large-metrics').append(s);
    }

    for(item in values_to_load.statistical) {
      var relevant = values_to_load.statistical[item];
      var s = "
"+relevant.label+"
";
      $('#statistical-metrics #statistical-sublist').append(s);
    }

    $('.overall-metric a').on("click", function() {
      console.log('Metric button clicked')
      var $actual = $(this).parent()

      if($actual.hasClass('active-metric')) {
        $actual.removeClass('active-metric')
      }
      else if($actual.hasClass('metric')) {
        console.log('Top metric selected')
        $('.overall-metric.active-metric').removeClass('active-metric')
        $actual.addClass('active-metric')
      }
      else if($actual.hasClass('performance-metric')) {
        $('.metric.active-metric').removeClass('active-metric')
        $actual.addClass('active-metric')
      }

      updateContent()
    });
});

function updateContent() {
  /*
    Logic for AJAX calls and the like to update the center
    panel of the page would go here
  */
}
<commit_msg>Update index.js<commit_after>

$(document).ready(function(){
    console.log('Page has fully loaded')

    var values_to_load = {
      'large': [
        {
          'label': 'by Product Type',
          'id': 'product-type'
        },
        {
          'label': 'by Company',
          'id': 'company'
        },
        {
          'label': 'by Serial Number',
          'id': 'serial-number'
        }
      ],
      'statistical': [
        {
          'label': 'Read Speed',
          'id': 'read-speed'
        },
        {
          'label': 'Read Count',
          'id': 'read-count'
        },
        {
          'label': 'Write Speed',
          'id': 'write-count'
        },
        {
          'label': 'Write Count',
          'id': 'write-count'
        },
        {
          'label': 'Bandwidth',
          'id': 'bandwidth'
        },
        {
          'label': 'CPU',
          'id': 'cpu'
        }
      ]
    }

    var item;
    for(item in values_to_load.large) {
      var relevant = values_to_load.large[item];
      var s = "
"+relevant.label+"
";
      $('#large-metrics').append(s);
    }

    for(item in values_to_load.statistical) {
      var relevant = values_to_load.statistical[item];
      var s = "
"+relevant.label+"
";
      $('#statistical-metrics #statistical-sublist').append(s);
    }

    $('.overall-metric a').on("click", function() {
      console.log('Metric button clicked')
      var $actual = $(this).parent()

      if($actual.hasClass('active-metric')) {
        $actual.removeClass('active-metric')
      }
      else if($actual.hasClass('metric')) {
        console.log('Top metric selected')
        $('.overall-metric.active-metric').removeClass('active-metric')
        $actual.addClass('active-metric')
      }
      else if($actual.hasClass('performance-metric')) {
        $('.metric.active-metric').removeClass('active-metric')
        $actual.addClass('active-metric')
      }

      updateContent()
    });
});

function updateContent() {
  /*
    Logic for AJAX calls and the like to update the center
    panel of the page would go here
  */
}
<|endoftext|>


<commit_before>// Third party libraries
import * as L from 'leaflet';
import $ from 'jquery';

// Local modules
import updateSummary from './summary';
import makeFilters from './filters';
import updateInfo from './tooltip';

// Globals
var autocomplete,
  selectedBucket = 'all',
  features = [],
  geojson,
  interactiveLayer,
  app,
  $infoTip = $($('.info')[0]),
  $loading = $('#loading'),
  $map = $('#map'),
  $closeButton = $('#close-button');

$map.hide(); // Map is hidden until it's done loading
toggleMobile(); // Check size of display and show precinct information accordingly

// Create Leaflet map and get tiles from Carto
var map = L.map('map');
map.setView({ lat: 33.74, lng: -84.38}, 10);

// Use panes to "sandwich" GeoJSON features between map tiles and road labels
map.createPane('labels');
map.getPane('labels').style.zIndex = 650;
map.getPane('labels').style.pointerEvents = 'none';

// Attribution
var cartodbAttribution = '© OpenStreetMap contributors, © CartoDB';

// Labels
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {pane: 'labels', attribution: cartodbAttribution}).addTo(map);

// Create base map
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {attribution: cartodbAttribution}).addTo(map);

// Get shapefiles
function getPrecincts(cb) {
  $.ajax({
    dataType: 'json',
    url: './2014_precincts_income_race.json',
    success: function(data) {
      cb(data)
    },
    failure: function() {
      console.log('failed to get precincts.');
    }
  });
};

// Append precincts from .json file to list of features so that Leaflet can render them.
function addPrecincts(precincts) {
  $(precincts).each(function(key, feature) {
    features.push(feature);
  });
  console.log(features);
  generateLayers();
  createMap();
}

/* Generate a map and a list of filter options */
function createMap() {
  // Render filters for demographic data like race and income
  makeFilters();

  // Default to display all precincts without any filtering
  $('.filter[data-filter="all"]').attr('class', 'filter-selected');

  // Add the geoJSON data to the map, hide the loading screen, and update the summary table
  geojson.addTo(map);
  updateSummary('all');
  $loading.hide();
  $map.show();
  map._onResize(); // Fixes weird bug http://stackoverflow.com/questions/24547468/leaflet-map-on-hide-div

  // Add event listeners to filter precincts by the given criteria when clicked
  $('.filter, .filter-selected').each(function() {
    $(this).on('click', function() {
      selectedBucket = this.dataset.filter; // Get the filter from the data-filter attribute

      // Loop through features in the geoJSON layer
      geojson.eachLayer(function (layer) {
        var layerParty = layer.feature.properties.party,
            layerRace = layer.feature.properties.income_rac,
            layerIncome;

        var income = layer.feature.properties.income_r_1; // Assign income to high middle or low bucket

        if (income < 50000) {
          layerIncome = 'low';
        }
        else if (income < 100000) {
          layerIncome = 'middle';
        }
        else if (income > 100000) {
          layerIncome = 'high'
        }

        // Check if each precinct meets the filter criteria, and color its fill accordingly
        if (layerRace === selectedBucket ||
        layerIncome === selectedBucket ||
        selectedBucket === 'all') {
          layer.setStyle(setColor(layerParty));
        }
        else {
          layer.setStyle({fillOpacity: 0});
        };
      });

      // Update the summary table results for the given filter
      updateSummary(selectedBucket);

      // Unset style of all filter options then style selected filter
      $('.filter-selected').attr('class', 'filter')
      $(this).attr('class', 'filter-selected')
    })
  })

  createInfo(); // Create the info box that displays precinct information
};

// Return an object with appropriate styles given the party results of a given precinct
function setColor(party) {
  var style = {fillOpacity: .3};
  switch (party) {
    case 'Republican': {
      style.fillColor = 'red';
      break;
    }
    case 'Democrat': {
      style.fillColor = 'blue';
      break;
    }
  };
  return style;
};

// generate a geoJson layer from the data, set initial styles, and add event listeners.
function generateLayers() {
  geojson = L.geoJson(features, {
      onEachFeature: onEachFeature,
      style: function(feature) {
        var style = {color: '#2E64FE', fillOpacity: .3, opacity: .5, weight: 1};
        switch (feature.properties.party) {
          case 'Republican': {
            style.fillColor = 'red';
            break;
          }
          case 'Democrat': {
            style.fillColor = 'blue';
            break;
          }
        };
        return style;
      }
  });

  // Add event handlers to precinct features to change tooltips
  function onEachFeature(feature, layer) {
    layer.on({
      click: zoomToFeature,
      mouseover: highlightFeature,
      mouseout: resetStyle
    })
  };

  /***********************
  * Begin helper functions
  ************************/
  function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
      weight: 3,
      opacity: 1,
      color: 'black'
    });

    updateInfo(layer.feature.properties);
    $infoTip.show();
  };

  function zoomToFeature(e) {
    highlightFeature(e);
    map.fitBounds(e.target.getBounds());
  };

  function resetStyle(e) {
    if ($(window).width() > 1200) {
      $infoTip.hide();
    }

    e.target.setStyle({
      opacity: .5,
      weight: 1,
      color: '#2E64FE'
    })
  }
  /**********************
  * End helper functions
  ***********************/
};

// Add an info box to the main map
function createInfo() {
  // Event handler to change position of tooltip depending on mouse position (on desktop only)
  $('#map').bind('mousemove', function(e) {
    if ($(window).width() > 1200) { // info box shouldn't hide on mobile unless the user clicks the close button
      $infoTip.css({left: e.pageX - 100, top: e.pageY + 20})
    }
  })

  // Event handler to change display of tooltip for mobile or desktop
  $(window).resize(function() {
    $infoTip.hide();
    toggleMobile();
  });

  // Only display the close button on mobile
  $closeButton.on('click', function() {
    $infoTip.hide();
  })

  $infoTip.hide(); // Don't display info tip until user mouses over or clicks on map
};

/* Depending on the size of the display, have tooltip follow the mouse or stick to the
bottom of the screen. */
function toggleMobile() {
  if ($(window).width() < 1200) {
    $closeButton.show();
    $infoTip.css({left: '', top: ''}); // Remove css styles added by mousemove event handler
    $infoTip.toggleClass('fixed-bottom', true);
    $infoTip.toggleClass('follow', false);
    $infoTip.show();
  }
  else {
    $closeButton.hide();
    $infoTip.toggleClass('fixed-bottom', false);
    $infoTip.toggleClass('follow', true);
  }
}

/* Add event listeners to autocomplete input field and query Google
 * Places API */
function initInput() {
  var input = document.getElementById('address-input');
  var options = {types: ['address']}
  autocomplete = new google.maps.places.Autocomplete(input, options);

  autocomplete.addListener('place_changed', onPlaceChanged)
}

// Pan map to the address selected by the user
function onPlaceChanged() {
  var lat = autocomplete.getPlace().geometry.location.lat();
  var lng = autocomplete.getPlace().geometry.location.lng();
  map.setView(new L.LatLng(lat, lng), 15);
}

// Finally, run main function to generate the map
initInput();
getPrecincts(addPrecincts);

<commit_msg>fixed color settings<commit_after>// Third party libraries
import * as L from 'leaflet';
import $ from 'jquery';

// Local modules
import updateSummary from './summary';
import makeFilters from './filters';
import updateInfo from './tooltip';

// Globals
var autocomplete,
  selectedBucket = 'all',
  features = [],
  geojson,
  interactiveLayer,
  app,
  $infoTip = $($('.info')[0]),
  $loading = $('#loading'),
  $map = $('#map'),
  $closeButton = $('#close-button');

$map.hide(); // Map is hidden until it's done loading
toggleMobile(); // Check size of display and show precinct information accordingly

// Create Leaflet map and get tiles from Carto
var map = L.map('map');
map.setView({ lat: 33.74, lng: -84.38}, 10);

// Use panes to "sandwich" GeoJSON features between map tiles and road labels
map.createPane('labels');
map.getPane('labels').style.zIndex = 650;
map.getPane('labels').style.pointerEvents = 'none';

// Attribution
var cartodbAttribution = '© OpenStreetMap contributors, © CartoDB';

// Labels
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {pane: 'labels', attribution: cartodbAttribution}).addTo(map);

// Create base map
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {attribution: cartodbAttribution}).addTo(map);

// Get shapefiles
function getPrecincts(cb) {
  $.ajax({
    dataType: 'json',
    url: './2014_precincts_income_race.json',
    success: function(data) {
      cb(data)
    },
    failure: function() {
      console.log('failed to get precincts.');
    }
  });
};

// Append precincts from .json file to list of features so that Leaflet can render them.
function addPrecincts(precincts) {
  $(precincts).each(function(key, feature) {
    features.push(feature);
  });
  console.log(features);
  generateLayers();
  createMap();
}

/* Generate a map and a list of filter options */
function createMap() {
  // Render filters for demographic data like race and income
  makeFilters();

  // Default to display all precincts without any filtering
  $('.filter[data-filter="all"]').attr('class', 'filter-selected');

  // Add the geoJSON data to the map, hide the loading screen, and update the summary table
  geojson.addTo(map);
  updateSummary('all');
  $loading.hide();
  $map.show();
  map._onResize(); // Fixes weird bug http://stackoverflow.com/questions/24547468/leaflet-map-on-hide-div

  // Add event listeners to filter precincts by the given criteria when clicked
  $('.filter, .filter-selected').each(function() {
    $(this).on('click', function() {
      selectedBucket = this.dataset.filter; // Get the filter from the data-filter attribute

      // Loop through features in the geoJSON layer
      geojson.eachLayer(function (layer) {
          var layerRace = layer.feature.properties.income_rac,
            layerIncome;

        var income = layer.feature.properties.income_r_1; // Assign income to high middle or low bucket

        if (income < 50000) {
          layerIncome = 'low';
        }
        else if (income < 100000) {
          layerIncome = 'middle';
        }
        else if (income > 100000) {
          layerIncome = 'high'
        }

        // Check if each precinct meets the filter criteria, and color its fill accordingly
        if (layerRace === selectedBucket ||
        layerIncome === selectedBucket ||
        selectedBucket === 'all') {
          layer.setStyle(setColor(layer.feature));
        }
        else {
          layer.setStyle({fillOpacity: 0});
        };
      });

      // Update the summary table results for the given filter
      updateSummary(selectedBucket);

      // Unset style of all filter options then style selected filter
      $('.filter-selected').attr('class', 'filter')
      $(this).attr('class', 'filter-selected')
    })
  })

  createInfo(); // Create the info box that displays precinct information
};

// Return an object with appropriate styles given the party results of a given precinct
function setColor(feature) {
  var style = {color: '#2E64FE', fillOpacity: .3, opacity: .5, weight: 1};

  var party = feature.properties.rep_v > feature.properties.dem_v ? 'Republican' : 'Democrat';

  switch (party) {
    case 'Republican': {
      style.fillColor = 'red';
      break;
    }
    case 'Democrat': {
      style.fillColor = 'blue';
      break;
    }
  };
  return style;
};

// generate a geoJson layer from the data, set initial styles, and add event listeners.
function generateLayers() {
  geojson = L.geoJson(features, {
      onEachFeature: onEachFeature,
      style: function(feature) {
        return setColor(feature)
      }
  });

  // Add event handlers to precinct features to change tooltips
  function onEachFeature(feature, layer) {
    layer.on({
      click: zoomToFeature,
      mouseover: highlightFeature,
      mouseout: resetStyle
    })
  };

  /***********************
  * Begin helper functions
  ************************/
  function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
      weight: 3,
      opacity: 1,
      color: 'black'
    });

    updateInfo(layer.feature.properties);
    $infoTip.show();
  };

  function zoomToFeature(e) {
    highlightFeature(e);
    map.fitBounds(e.target.getBounds());
  };

  function resetStyle(e) {
    if ($(window).width() > 1200) {
      $infoTip.hide();
    }

    e.target.setStyle({
      opacity: .5,
      weight: 1,
      color: '#2E64FE'
    })
  }
  /**********************
  * End helper functions
  ***********************/
};

// Add an info box to the main map
function createInfo() {
  // Event handler to change position of tooltip depending on mouse position (on desktop only)
  $('#map').bind('mousemove', function(e) {
    if ($(window).width() > 1200) { // info box shouldn't hide on mobile unless the user clicks the close button
      $infoTip.css({left: e.pageX - 100, top: e.pageY + 20})
    }
  })

  // Event handler to change display of tooltip for mobile or desktop
  $(window).resize(function() {
    $infoTip.hide();
    toggleMobile();
  });

  // Only display the close button on mobile
  $closeButton.on('click', function() {
    $infoTip.hide();
  })

  $infoTip.hide(); // Don't display info tip until user mouses over or clicks on map
};

/* Depending on the size of the display, have tooltip follow the mouse or stick to the
bottom of the screen. */
function toggleMobile() {
  if ($(window).width() < 1200) {
    $closeButton.show();
    $infoTip.css({left: '', top: ''}); // Remove css styles added by mousemove event handler
    $infoTip.toggleClass('fixed-bottom', true);
    $infoTip.toggleClass('follow', false);
    $infoTip.show();
  }
  else {
    $closeButton.hide();
    $infoTip.toggleClass('fixed-bottom', false);
    $infoTip.toggleClass('follow', true);
  }
}

/* Add event listeners to autocomplete input field and query Google
 * Places API */
function initInput() {
  var input = document.getElementById('address-input');
  var options = {types: ['address']}
  autocomplete = new google.maps.places.Autocomplete(input, options);

  autocomplete.addListener('place_changed', onPlaceChanged)
}

// Pan map to the address selected by the user
function onPlaceChanged() {
  var lat = autocomplete.getPlace().geometry.location.lat();
  var lng = autocomplete.getPlace().geometry.location.lng();
  map.setView(new L.LatLng(lat, lng), 15);
}

// Finally, run main function to generate the map
initInput();
getPrecincts(addPrecincts);

<|endoftext|>


<commit_before>(function() {
	'use strict'; // jslint

	// Namespace for libremanga
	/*var Lm = {
		Models : {},
		Views : {},
		Collection : {}
	};

	// Model
	Lm.Models.MangaList = Backbone.Model.extend({
		urlRoot : 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0')
	});

	// Collection
	Lm.Collection.MangaList = Backbone.Collection.extend({
		url : 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0'),
		parse : function(x, a) {
			console.log(x, a);
		}
	});

	// View
	Lm.Views.MangaList = Backbone.View.extend({

	});

	var manga = new Lm.Models.MangaList();
	manga.fetch();
	console.log(manga);
	var mangaList = new Lm.Collection.MangaList({});

	var mangaListView = new Lm.Views.MangaList({});

	var mangaList = {},
		mangaListContainer = $('#manga_list');*/

	/*$.ajax({
		url 	: 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0'),
		type 	: 'GET',
		dataType : 'json',
		success : function(res) {
			mangaList = (res.manga.length > 0) ? res : null;
		}
	}).done(function() {

		// Save list to textfile for caching
		// Display list in Datatable
		$.each(mangaList.manga, function(i, val) {
			mangaListContainer.append('
' + val.t + '
');
		});
	});*/

	// Constant Variables
	var MANGA_API_URL 			= 'http://www.mangaeden.com/api/manga/',
		MANGA_CHAPTER_API_URL 	= 'http://www.mangaeden.com/api/chapter/',
		MANGA_CHAPTER_IMAGE_URL = 'http://cdn.mangaeden.com/mangasimg/';

	// PREFIX jQuery variables with $ (dollar sign)
	var $headerContent	= $('#main_header'),
		$content		= $('#wrap'),		// For scroll fixed
		$loader			= $('.loader'),
		$mangaList		= $('#manga_list');

	var	mangaCache = {},				// Cache manga
		mangaChapterCache = {};			// Cache manga chapter

	var shareURL = function() {
		$('.share_fb').on('click', function() {
			window.open(
				'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),
				'facebook-share-dialog',
				'width=626,height=436'
			);
			return false;
		});

		$('.share_twitter').on('click', function() {
			window.open(
				'https://twitter.com/share?url=http%3A%2F%2Flibremanga.com',
				'twitter-tweet-dialog',
				'width=626,height=436'
			);
			return false;
		});

		$('.share_gplus').on('click', function() {
			window.open(
				'https://plus.google.com/share?url=http%3A%2F%2Flibremanga.com',
				'google-share-dialog',
				'width=626,height=436'
			);
			return false;
		});
	};

	// Inspired from codrops
	var didScroll = false,
		changeHeaderOn = 5;

	var scrollPage = function() {
		var sy = scrollY(),
			$fixedHeader = $('#manga_details_wrap header');
		//console.log(sy);
		if (sy >= changeHeaderOn ) {
			$fixedHeader.addClass('fixed_top');
		}
		else {
			$fixedHeader.removeClass('fixed_top');
		}
		didScroll = false;
	};

	var scrollY = function() {
		return $content.scrollTop();
	};

	// Append manga info to the DOM
	var showMangaInfo = function(data) {
		$headerContent.append(_.template($('#manga_details').html(), data));
	};

	// Append manga chapter image to the image gallery
	var showMangaChapterImage = function(data) {
		$headerContent.append(_.template($('#manga_chapter_view').html(), data));
	};

	var processMangaChapter = function(data, modal, button, parent) {
		button.removeClass('loading');			// Removes fallback loading state to the link
		parent.removeClass('disable_dom');		// Enable all manga chapter list links
		$mangaList.removeClass('disable_dom');	// Enable sidebar manga list links
		showMangaChapterImage(data);			// Call showMangaChapterImage function
		$(modal).modal('show');					// Show modal with manga chapter images
		$('#custom_backdrop').remove();			// Removes custom bootstrap backdrop
	};

	// TODO: Add image gallery
	// TODO: loading message on click chapters

	var viewChapterClickEvent = function(classname) {
		$('a.' + classname).on('click', function(e) {
			e.preventDefault();

			var _this				= $(this),
				chapterNum			= _this.data('chapter'),
				chapterID			= _this.data('id'),
				mangaTitle			= _this.data('manga-title'),
				modalID				= '#manga_chapter' + chapterID,
				$mangaChapterList	= $('#manga_chapters_list'),
				custom_backdrop		= '

loading...

';

			_this.addClass('loading');					// Add fallback loading state to the link
			$mangaChapterList.addClass('disable_dom');	// Disable all manga chapter list links to prevent api call stack up
			$mangaList.addClass('disable_dom');			// Disable sidebar manga list links to prevent api call stack up
			$(custom_backdrop).appendTo(document.body); // Implements custom bootstrap backdrop

			if(chapterID in mangaChapterCache) {
				processMangaChapter(mangaChapterCache[chapterID], modalID, _this, $mangaChapterList);
			} else {
				$.ajax({
					url :  'proxy.php?url=' + encodeURIComponent(MANGA_CHAPTER_API_URL) + chapterID,
					type : 'GET',
					dataType : 'json',
					success : function(res) {
						res['id'] 			= chapterID;	// Hooks chapter ID to the response
						res['num'] 			= chapterNum;	// Hooks chapter number to the response
						res['manga_title'] 	= mangaTitle;	// Hooks manga title to the response
						mangaChapterCache[chapterID] = res; // save manga chapter to cache
					}
				}).done(function(data, status) {
					if(status == 'success') {
						processMangaChapter(data, modalID, _this, $mangaChapterList);
					} else {
						console.log(data, status);
					}
				});
			}
		});
	};

	var processManga = function(manga, button) {
		$loader.hide();							// Hides loader
		$mangaList.removeClass('disable_dom');  // Disable the click/pointer event in mangaList
		button.removeClass('loading');			// Remove loading class
		showMangaInfo(manga);					// Show manga
		shareURL();
	};

	var init = function() {

		// Bind scrolling event
		$content.bind('scroll', function() {
			//console.log('scrolling');
			if(!didScroll) {
				didScroll = true;
				scrollPage();
			}
		});

		$loader.hide(); // Hide loader on load page

		// DONE: Disabled sidebar or manga list link on ajax loading to prevent dom content stack up.
		// TODO: Image caching in localstorage or sessionstorage
		// TODO: Store API response to json text file
		// TODO: Integrage Backbone MVC

		// Add function to click event
		$('a.manga').on('click', function(e) {
			e.preventDefault();

			$headerContent.empty();
			$loader.show();
			$mangaList.addClass('disable_dom');

			var _this = $(this),			// Cache self
				mangaID = _this.data('id'); // Cache manga id

			// Remove class 'current' in all list
			_.each($('a.manga'), function(value, key, list) {
				if(list.hasClass('current')) {
					list.removeClass('current');
				}
			});

			_this.addClass('current'); // Add class 'current' to self
			_this.addClass('loading'); // Add class 'loading' to self

			// Check if manga is in cache, if TRUE load the cache and prevent from calling API again
			if(mangaID in mangaCache) {
				processManga(mangaCache[mangaID], _this);	// Show manga from cache
				viewChapterClickEvent('manga_chapter');		// Add click event to chapters
			} else {

				// Use this if php proxy is not supported
				var apiUrl = window.location.href + 'assets/json/' + mangaID + '/manga.json';

				// Call API
				$.ajax({
					url 	: 'proxy.php?url=' + encodeURIComponent(MANGA_API_URL) + mangaID,
					//url 	: apiUrl,
					//type 	: 'GET',
					dataType: 'json',
					success : function(res) {
						mangaCache[mangaID] = res; // save manga to cache object
					}
				}).done(function(data, status) {
					if(status == 'success') {
						processManga(data, _this);
						viewChapterClickEvent('manga_chapter');
					} else {
						console.log(data, status);
					}
				});
			}
		});

		$(document).on('click', '.modal_fullscreen', function(e) {
			e.preventDefault();
			var _this = $(this),
				parent = _this.closest('.modal');

			if(parent.hasClass('fullscreen')) {
				// Normal Screen
				parent.removeClass('fullscreen')
					.find('.modal-body').css({
						height : '400px',
						'paddingTop' : '15px'
					});
				parent.find('.modal-header').css('padding', '9px 15px')
					.find('h3').css({
						'line-height': '30px',
						'font-size' : '24.5px'
					});
				parent.find('.modal-header button').css({
					'font-size': '20px',
					'marginTop': '2px'
				});
				parent.find('.modal-footer').css('display', 'block');
				_this.children().attr('class', ' icon-resize-full').css('vertical-align', '2px');
				_this.attr('title', 'Fullscreen');
			} else {
				// Fullscreen
				parent.addClass('fullscreen')
					.find('.modal-body').css({
						height : '89%',
						'paddingTop' : 0
					});
				parent.find('.modal-header').css('padding', '5px')
					.find('h3').css({
						'line-height': '14px',
						'font-size' : '14px'
					});
				parent.find('.modal-header button').css({
					'font-size': '14px',
					'marginTop': '-1px'
				});
				parent.find('.modal-footer').css('display', 'none');
				_this.children().attr('class', ' icon-resize-small').css('vertical-align', '-1px');
				_this.attr('title', 'Normal screen');
			}
		});

		shareURL();
	};

	init();

}());<commit_msg>clean code, move css to css file and clean code<commit_after>(function() {
	'use strict'; // jslint

	// Namespace for libremanga
	/*var Lm = {
		Models : {},
		Views : {},
		Collection : {}
	};

	// Model
	Lm.Models.MangaList = Backbone.Model.extend({
		urlRoot : 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0')
	});

	// Collection
	Lm.Collection.MangaList = Backbone.Collection.extend({
		url : 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0'),
		parse : function(x, a) {
			console.log(x, a);
		}
	});

	// View
	Lm.Views.MangaList = Backbone.View.extend({

	});

	var manga = new Lm.Models.MangaList();
	manga.fetch();
	console.log(manga);
	var mangaList = new Lm.Collection.MangaList({});

	var mangaListView = new Lm.Views.MangaList({});

	var mangaList = {},
		mangaListContainer = $('#manga_list');*/

	/*$.ajax({
		url 	: 'proxy.php?url=' + encodeURIComponent('http://www.mangaeden.com/api/list/0'),
		type 	: 'GET',
		dataType : 'json',
		success : function(res) {
			mangaList = (res.manga.length > 0) ? res : null;
		}
	}).done(function() {

		// Save list to textfile for caching
		// Display list in Datatable
		$.each(mangaList.manga, function(i, val) {
			mangaListContainer.append('
' + val.t + '
');
		});
	});*/

	// Constant Variables
	var MANGA_API_URL 			= 'http://www.mangaeden.com/api/manga/',
		MANGA_CHAPTER_API_URL 	= 'http://www.mangaeden.com/api/chapter/',
		MANGA_CHAPTER_IMAGE_URL = 'http://cdn.mangaeden.com/mangasimg/';

	// PREFIX jQuery variables with $ (dollar sign)
	var $headerContent	= $('#main_header'),
		$content		= $('#wrap'),		// For scroll fixed
		$loader			= $('.loader'),
		$mangaList		= $('#manga_list');

	var	mangaCache = {},				// Cache manga
		mangaChapterCache = {};			// Cache manga chapter

	var shareURL = function() {
		$('.share_fb').on('click', function() {
			window.open(
				'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),
				'facebook-share-dialog',
				'width=626,height=436'
			);
			return false;
		});

		$('.share_twitter').on('click', function() {
			window.open(
				'https://twitter.com/share?url=http%3A%2F%2Flibremanga.com',
				'twitter-tweet-dialog',
				'width=626,height=436'
			);
			return false;
		});

		$('.share_gplus').on('click', function() {
			window.open(
				'https://plus.google.com/share?url=http%3A%2F%2Flibremanga.com',
				'google-share-dialog',
				'width=626,height=436'
			);
			return false;
		});
	};

	// Inspired from codrops
	var didScroll = false,
		changeHeaderOn = 5;

	var scrollPage = function() {
		var sy = scrollY(),
			$fixedHeader = $('#manga_details_wrap header');
		//console.log(sy);
		if (sy >= changeHeaderOn ) {
			$fixedHeader.addClass('fixed_top');
		}
		else {
			$fixedHeader.removeClass('fixed_top');
		}
		didScroll = false;
	};

	var scrollY = function() {
		return $content.scrollTop();
	};

	// Append manga info to the DOM
	var showMangaInfo = function(data) {
		$headerContent.append(_.template($('#manga_details').html(), data));
	};

	// Append manga chapter image to the image gallery
	var showMangaChapterImage = function(data) {
		$headerContent.append(_.template($('#manga_chapter_view').html(), data));
	};

	var processMangaChapter = function(data, modal, button, parent) {
		button.removeClass('loading');			// Removes fallback loading state to the link
		parent.removeClass('disable_dom');		// Enable all manga chapter list links
		$mangaList.removeClass('disable_dom');	// Enable sidebar manga list links
		showMangaChapterImage(data);			// Call showMangaChapterImage function
		$(modal).modal('show');					// Show modal with manga chapter images
		$('#custom_backdrop').remove();			// Removes custom bootstrap backdrop
	};

	// TODO: Add image gallery
	// TODO: loading message on click chapters

	var viewChapterClickEvent = function(classname) {
		$('a.' + classname).on('click', function(e) {
			e.preventDefault();

			var _this				= $(this),
				chapterNum			= _this.data('chapter'),
				chapterID			= _this.data('id'),
				mangaTitle			= _this.data('manga-title'),
				modalID				= '#manga_chapter' + chapterID,
				$mangaChapterList	= $('#manga_chapters_list'),
				custom_backdrop		= '

loading...

';

			_this.addClass('loading');					// Add fallback loading state to the link
			$mangaChapterList.addClass('disable_dom');	// Disable all manga chapter list links to prevent api call stack up
			$mangaList.addClass('disable_dom');			// Disable sidebar manga list links to prevent api call stack up
			$(custom_backdrop).appendTo(document.body); // Implements custom bootstrap backdrop

			if(chapterID in mangaChapterCache) {
				processMangaChapter(mangaChapterCache[chapterID], modalID, _this, $mangaChapterList);
			} else {
				$.ajax({
					url :  'proxy.php?url=' + encodeURIComponent(MANGA_CHAPTER_API_URL) + chapterID,
					type : 'GET',
					dataType : 'json',
					success : function(res) {
						res['id'] 			= chapterID;	// Hooks chapter ID to the response
						res['num'] 			= chapterNum;	// Hooks chapter number to the response
						res['manga_title'] 	= mangaTitle;	// Hooks manga title to the response
						mangaChapterCache[chapterID] = res; // save manga chapter to cache
					}
				}).done(function(data, status) {
					if(status == 'success') {
						processMangaChapter(data, modalID, _this, $mangaChapterList);
					} else {
						console.log(data, status);
					}
				});
			}
		});
	};

	var processManga = function(manga, button) {
		$loader.hide();							// Hides loader
		$mangaList.removeClass('disable_dom');  // Disable the click/pointer event in mangaList
		button.removeClass('loading');			// Remove loading class
		showMangaInfo(manga);					// Show manga
		shareURL();
	};

	var checkRemoveAndAddClass = function($el, checkRemClass, addClass) {
		if($el.hasClass(checkRemClass)) {	// Check if the element has a class
			$el.removeClass(checkRemClass)	// Remove the class
			$el.addClass(addClass)			// Add new class
		}
	};

	var init = function() {

		// Bind scrolling event
		$content.bind('scroll', function() {
			//console.log('scrolling');
			if(!didScroll) {
				didScroll = true;
				scrollPage();
			}
		});

		$loader.hide(); // Hide loader on load page

		// DONE: Disabled sidebar or manga list link on ajax loading to prevent dom content stack up.
		// TODO: Image caching in localstorage or sessionstorage
		// TODO: Store API response to json text file
		// TODO: Integrage Backbone MVC

		// Add function to click event
		$('a.manga').on('click', function(e) {
			e.preventDefault();

			$headerContent.empty();
			$loader.show();
			$mangaList.addClass('disable_dom');

			var _this = $(this),			// Cache self
				mangaID = _this.data('id'); // Cache manga id

			// Remove class 'current' in all list
			_.each($('a.manga'), function(value, key, list) {
				if(list.hasClass('current')) {
					list.removeClass('current');
				}
			});

			_this.addClass('current'); // Add class 'current' to self
			_this.addClass('loading'); // Add class 'loading' to self

			// Check if manga is in cache, if TRUE load the cache and prevent from calling API again
			if(mangaID in mangaCache) {
				processManga(mangaCache[mangaID], _this);	// Show manga from cache
				viewChapterClickEvent('manga_chapter');		// Add click event to chapters
			} else {

				// Use this if php proxy is not supported
				var apiUrl = window.location.href + 'assets/json/' + mangaID + '/manga.json';

				// Call API
				$.ajax({
					url 	: 'proxy.php?url=' + encodeURIComponent(MANGA_API_URL) + mangaID,
					//url 	: apiUrl,
					//type 	: 'GET',
					dataType: 'json',
					success : function(res) {
						mangaCache[mangaID] = res; // save manga to cache object
					}
				}).done(function(data, status) {
					if(status == 'success') {
						processManga(data, _this);
						viewChapterClickEvent('manga_chapter');
					} else {
						console.log(data, status);
					}
				});
			}
		});

		$(document).on('click', '.modal_fullscreen', function(e) {
			e.preventDefault();
			var _this = $(this),
				parent = _this.closest('.modal');

			if(parent.hasClass('fullscreen')) {
				// Normal Screen
				parent.removeClass('fullscreen')
					.find('.modal-body')
						.removeClass('mb_fullscreen');
				parent.find('.modal-header')
					.removeClass('mh_fullscreen');
				parent.find('.modal-footer')
					.removeClass('mf_fullscreen');
				checkRemoveAndAddClass(_this.children(), 'icon-resize-small', 'icon-resize-full');
				_this.attr('title', 'Fullscreen');
			} else {
				// Fullscreen
				parent.addClass('fullscreen')
					.find('.modal-body')
						.addClass('mb_fullscreen');
				parent.find('.modal-header')
					.addClass('mh_fullscreen');
				parent.find('.modal-footer')
					.addClass('mf_fullscreen');
				checkRemoveAndAddClass(_this.children(), 'icon-resize-full', 'icon-resize-small');
				_this.attr('title', 'Normal screen');
			}
		});

		shareURL();
	};

	init();

}());<|endoftext|>


<commit_before>if (!process.env.WEBDRIVER) {
	console.info("No WEBDRIVER, skipping this test");
	return;
}

var expect = require('expect.js');
var express = require('express');
var webdriver = require("selenium-webdriver");
var project = require('../package.json').name;
var getPort = require('gport');
var request = require('request');

var host = "http://localhost";

function getEnvCaps() {
	var envCaps = process.env.WEBDRIVER;
	if (!envCaps) return {};
	try {
		envCaps = eval('(function() { return {' + envCaps + '};})();');
	} catch(ex) {
		console.error("Cannot use WEBDRIVER env caps", envCaps);
		return {};
	}
	return envCaps;
}

function getBrowser() {
	var browser;
	var prefs = new webdriver.logging.Preferences();
	prefs.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.DEBUG);

	return new webdriver.Builder()
	.usingServer(process.env.WEBDRIVER_SERVER || 'http://hub-cloud.browserstack.com/wd/hub')
	.withCapabilities(Object.assign({
		'browserstack.user': process.env.BROWSERSTACK_USER,
		'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY,
		'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
		build: process.env.TRAVIS_BUILD_NUMBER,
		acceptSslCerts: true,
		browserConnectionEnabled: true,
		newtworkConnectionEnabled: true,
		project: project,
		"browserstack.debug": true,
		"browserstack.local": process.env.BROWSERSTACK_LOCAL,
		"browserstack.video": false,
		"browserstack.localIdentifier": process.env.BROWSERSTACK_LOCAL_IDENTIFIER
	}, getEnvCaps()))
	.setLoggingPrefs(prefs)
	.build();
}

function testPageForStrings(browser, url, strings) {
	return browser.get(url).then(function() {
		return browser.sleep(3000).then(function() {
			return browser.getPageSource();
		}).then(function(html) {
			strings.forEach(function(str) {
				expect(html).to.contain(str);
			});
		});
	});
}

describe("Rendering", function suite() {
	this.timeout(360000); // some browser VM can be slow
	var server, base, browser;

	before(function(done) {
		browser = getBrowser();
		var app = express();
		app.set('views', __dirname + '/public');
		app.get('*', express.static(app.get('views')));
		getPort(9901, function(port) {
			if (port > 9999) return done(new Error("Test might fail on Safari because port is "
				+ port + ", see\nhttps://www.browserstack.com/question/664"));
			server = app.listen(port, function(err) {
				if (err) console.error(err);
				base = host + ':' + server.address().port;
				done();
			});
		});
	});

	after(function() {
		server.close();
		return browser.quit();
	});

	after(function() {
		var status = this.test.parent.tests.every(function(test) {
			return test.state == "passed";
		}) ? "completed" : "error";
		server.close();
		return browser.getSession().then(function(session) {
			var bsUrl = `https://www.browserstack.com/automate/sessions/${session.getId()}.json`;
			return new Promise(function(resolve, reject) {
				console.info("Notifying browserstack", status, bsUrl);
				request.put({
					url: bsUrl,
					json: true,
					body: {
						status: status,
						reason: ''
					},
					auth: {
						user: process.env.BROWSERSTACK_USER,
						pass: process.env.BROWSERSTACK_ACCESS_KEY
					}
				}, function(err, res, body) {
					console.info("Response", res.statusCode, body);
					if (err) console.error(err);
					resolve();
				});
			})
		}).then(function() {
			return browser.quit();
		});
	});

	it("should run build and setup", function() {
		return testPageForStrings(browser, base + '/build.html', [
			'data-page-stage="3"',
			'
0
',
			'
0
'
		]);
	});

	it("should run build and patch and setup", function() {
		return testPageForStrings(browser, base + '/patch.html', [
			'data-page-stage="3"',
			'
0
',
			'
0
',
			'
0
'
		]);
	});

	it("should run build and patch and setup, call replace and run patch again", function() {
		return testPageForStrings(browser, base + '/replace.html', [
			'data-page-stage="3"',
			'
0
',
			'
1
',
			'
0
',
			'
/replace.html?toto=1
'
		]);
	});

	it("should run build and patch and setup, call push and run patch again", function() {
		return testPageForStrings(browser, base + '/push.html', [
			'data-page-stage="3"',
			'
0
',
			'
1
',
			'
0
',
			'
/push.html?toto=1
'
		]);
	});

	it("should run route and build and setup", function() {
		return testPageForStrings(browser, base + '/route.html?template=build', [
			'data-page-stage="3"',
			'
0
',
			'
0
'
		]);
	});

	it("should run route and imports", function() {
		return testPageForStrings(browser, base + '/route.html?template=import', [
			'data-page-stage="3"',
			"I'm setup0",
			"your body0"
		]);
	});

	it("should render doc with stylesheet and script", function() {
		return testPageForStrings(browser, base + '/order-stylesheets-scripts.html', [
			'
squared
'
		]);
	});

	it("should load stylesheet before remote script when rendering", function() {
		return testPageForStrings(browser, base + '/route.html?template=order-stylesheets-scripts', [
			'data-page-stage="3"',
			'
squared
'
		]);
	});

	it("should run route and load script before import", function() {
		return testPageForStrings(browser, base + '/route.html?template=import-depending-on-script', [
			'data-page-stage="3"',
			"I'm setup0",
			"your body770"
		]);
	});
});

<commit_msg>Remove duplicate after hook<commit_after>if (!process.env.WEBDRIVER) {
	console.info("No WEBDRIVER, skipping this test");
	return;
}

var expect = require('expect.js');
var express = require('express');
var webdriver = require("selenium-webdriver");
var project = require('../package.json').name;
var getPort = require('gport');
var request = require('request');

var host = "http://localhost";

function getEnvCaps() {
	var envCaps = process.env.WEBDRIVER;
	if (!envCaps) return {};
	try {
		envCaps = eval('(function() { return {' + envCaps + '};})();');
	} catch(ex) {
		console.error("Cannot use WEBDRIVER env caps", envCaps);
		return {};
	}
	return envCaps;
}

function getBrowser() {
	var browser;
	var prefs = new webdriver.logging.Preferences();
	prefs.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.DEBUG);

	return new webdriver.Builder()
	.usingServer(process.env.WEBDRIVER_SERVER || 'http://hub-cloud.browserstack.com/wd/hub')
	.withCapabilities(Object.assign({
		'browserstack.user': process.env.BROWSERSTACK_USER,
		'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY,
		'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
		build: process.env.TRAVIS_BUILD_NUMBER,
		acceptSslCerts: true,
		browserConnectionEnabled: true,
		newtworkConnectionEnabled: true,
		project: project,
		"browserstack.debug": true,
		"browserstack.local": process.env.BROWSERSTACK_LOCAL,
		"browserstack.video": false,
		"browserstack.localIdentifier": process.env.BROWSERSTACK_LOCAL_IDENTIFIER
	}, getEnvCaps()))
	.setLoggingPrefs(prefs)
	.build();
}

function testPageForStrings(browser, url, strings) {
	return browser.get(url).then(function() {
		return browser.sleep(3000).then(function() {
			return browser.getPageSource();
		}).then(function(html) {
			strings.forEach(function(str) {
				expect(html).to.contain(str);
			});
		});
	});
}

describe("Rendering", function suite() {
	this.timeout(360000); // some browser VM can be slow
	var server, base, browser;

	before(function(done) {
		browser = getBrowser();
		var app = express();
		app.set('views', __dirname + '/public');
		app.get('*', express.static(app.get('views')));
		getPort(9901, function(port) {
			if (port > 9999) return done(new Error("Test might fail on Safari because port is "
				+ port + ", see\nhttps://www.browserstack.com/question/664"));
			server = app.listen(port, function(err) {
				if (err) console.error(err);
				base = host + ':' + server.address().port;
				done();
			});
		});
	});

	after(function() {
		var status = this.test.parent.tests.every(function(test) {
			return test.state == "passed";
		}) ? "completed" : "error";
		server.close();
		return browser.getSession().then(function(session) {
			var bsUrl = `https://www.browserstack.com/automate/sessions/${session.getId()}.json`;
			return new Promise(function(resolve, reject) {
				console.info("Notifying browserstack", status, bsUrl);
				request.put({
					url: bsUrl,
					json: true,
					body: {
						status: status,
						reason: ''
					},
					auth: {
						user: process.env.BROWSERSTACK_USER,
						pass: process.env.BROWSERSTACK_ACCESS_KEY
					}
				}, function(err, res, body) {
					console.info("Response", res.statusCode, body);
					if (err) console.error(err);
					resolve();
				});
			})
		}).then(function() {
			return browser.quit();
		});
	});

	it("should run build and setup", function() {
		return testPageForStrings(browser, base + '/build.html', [
			'data-page-stage="3"',
			'
0
',
			'
0
'
		]);
	});

	it("should run build and patch and setup", function() {
		return testPageForStrings(browser, base + '/patch.html', [
			'data-page-stage="3"',
			'
0
',
			'
0
',
			'
0
'
		]);
	});

	it("should run build and patch and setup, call replace and run patch again", function() {
		return testPageForStrings(browser, base + '/replace.html', [
			'data-page-stage="3"',
			'
0
',
			'
1
',
			'
0
',
			'
/replace.html?toto=1
'
		]);
	});

	it("should run build and patch and setup, call push and run patch again", function() {
		return testPageForStrings(browser, base + '/push.html', [
			'data-page-stage="3"',
			'
0
',
			'
1
',
			'
0
',
			'
/push.html?toto=1
'
		]);
	});

	it("should run route and build and setup", function() {
		return testPageForStrings(browser, base + '/route.html?template=build', [
			'data-page-stage="3"',
			'
0
',
			'
0
'
		]);
	});

	it("should run route and imports", function() {
		return testPageForStrings(browser, base + '/route.html?template=import', [
			'data-page-stage="3"',
			"I'm setup0",
			"your body0"
		]);
	});

	it("should render doc with stylesheet and script", function() {
		return testPageForStrings(browser, base + '/order-stylesheets-scripts.html', [
			'
squared
'
		]);
	});

	it("should load stylesheet before remote script when rendering", function() {
		return testPageForStrings(browser, base + '/route.html?template=order-stylesheets-scripts', [
			'data-page-stage="3"',
			'
squared
'
		]);
	});

	it("should run route and load script before import", function() {
		return testPageForStrings(browser, base + '/route.html?template=import-depending-on-script', [
			'data-page-stage="3"',
			"I'm setup0",
			"your body770"
		]);
	});
});

<|endoftext|>


<commit_before>$(function(){

    var deadline;

    $('.start').click(function(){
        deadline = $('.date').val();
        setInterval(countDown, 1000);
    });

    function countDown(){
        var remainingTime = getRemainingTime(deadline);

        var days = remainingTime.days;
        var hours = remainingTime.hours;
        var minutes = remainingTime.minutes;
        var seconds = remainingTime.seconds;

        var counter = days + 'd '+ hours + 'h ' + minutes + 'm ' + seconds + 's';

        $('.counter').html(counter);
    }

    setInterval(count, 1000);

    function count(){
        // on créé une variable pour stocker l'information
        var now = new Date();
        var hour = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();

        // pour voir les variables
        // console.log(now);
        // console.log(hour, minutes, seconds);

        // on créé le texte a mettre dans le html
        var counter = hour + 'h ' + minutes + 'm ' + seconds + 's';
        // console.log(counter);

        // on le remplace dans le HTML
        $('.counter').html(counter);
    }

    function getRemainingTime(endtime){
        var t = Date.parse(endtime) - Date.parse(new Date());
        var seconds = Math.floor( (t/1000) % 60 );
        var minutes = Math.floor( (t/1000/60) % 60 );
        var hours = Math.floor( (t/(1000*60*60)) % 24 );
        var days = Math.floor( t/(1000*60*60*24) );
        return {
            'total': t,
            'days': days,
            'hours': hours,
            'minutes': minutes,
            'seconds': seconds
        };
    }

});
<commit_msg>added gist and clearInterval()<commit_after>$(function(){

    var deadline;

    $('.start').click(function(){
        deadline = $('.date').val();
        clearInterval(firstInterval);
        setInterval(countDown, 1000);
    });

    function countDown(){
        var remainingTime = getRemainingTime(deadline);

        var days = remainingTime.days;
        var hours = remainingTime.hours;
        var minutes = remainingTime.minutes;
        var seconds = remainingTime.seconds;

        var counter = days + 'd '+ hours + 'h ' + minutes + 'm ' + seconds + 's';

        $('.counter').html(counter);
    }

    var firstInterval = setInterval(count, 1000);

    function count(){
        // on créé une variable pour stocker l'information
        var now = new Date();
        var hour = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();

        // pour voir les variables
        // console.log(now);
        // console.log(hour, minutes, seconds);

        // on créé le texte a mettre dans le html
        var counter = hour + 'h ' + minutes + 'm ' + seconds + 's';
        // console.log(counter);

        // on le remplace dans le HTML
        $('.counter').html(counter);
    }

    // see https://gist.github.com/dot-louis/b6cd42ed74ed448415bd
    function getRemainingTime(endtime){
        var t = Date.parse(endtime) - Date.parse(new Date());
        var seconds = Math.floor( (t/1000) % 60 );
        var minutes = Math.floor( (t/1000/60) % 60 );
        var hours = Math.floor( (t/(1000*60*60)) % 24 );
        var days = Math.floor( t/(1000*60*60*24) );
        return {
            'total': t,
            'days': days,
            'hours': hours,
            'minutes': minutes,
            'seconds': seconds
        };
    }

});
<|endoftext|>


<commit_before>/*
 Copyright 2015 OpenMarket Ltd

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

angular.module('versionService', [])
.service('versionService', ['$http', '$q',
function ($http, $q) {
	var pendingVersionDefer = $q.defer();
	var versionService = this;
    versionService.version = "unknown";
    versionService.getVersion = function() {
        return pendingVersionDefer.promise;
    };

    $http.get("/VERSION").then(function(response) {
        console.log("Version %s", response.data);
        versionService.version = response.data;
        pendingVersionDefer.resolve();
    },
    function(err) {
        console.error("Failed to get web client version.");
        pendingVersionDefer.resolve();
    });

}]);

<commit_msg>Not from the root path please..<commit_after>/*
 Copyright 2015 OpenMarket Ltd

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

angular.module('versionService', [])
.service('versionService', ['$http', '$q',
function ($http, $q) {
	var pendingVersionDefer = $q.defer();
	var versionService = this;
    versionService.version = "unknown";
    versionService.getVersion = function() {
        return pendingVersionDefer.promise;
    };

    $http.get("VERSION").then(function(response) {
        console.log("Version %s", response.data);
        versionService.version = response.data;
        pendingVersionDefer.resolve();
    },
    function(err) {
        console.error("Failed to get web client version.");
        pendingVersionDefer.resolve();
    });

}]);

<|endoftext|>