<commit_before>// Grid's starting dimension
var rows = 16;
var columns = 16;

// Check the box dimension
var mbWidth = parseFloat($('.magic-box').css('width'));
var mbHeight = parseFloat($('.magic-box').css('height'));

// Color settings
var startColor = "#C9C9C9";
var usedColor = "black";

// Operating variables
var clicked = false;
var rand = false;
var erase = false;
var temp = usedColor;

// Set the size of the pixel based
// on the current size of the grid
var setFields = function (r, c) {
	var boxWidth = (mbWidth / c) + 'px';
	var boxHeight = (mbHeight / r) + 'px';
	$('.magic-field').css('width', boxWidth);
	$('.magic-field').css('height', boxHeight);
}

// Generate the grid and set base color
var createBox = function (rows, columns) {
	$('div.magic-field').remove();
	var i;
	var boxes = columns * rows
	for (i = 0; i < boxes; i++) {
		$('.magic-box').append('

');
	}
}

// Change the color of pixels you move the cursor
// when the mouse button is pressed
var paintFields = function (color) {
  	$('.magic-box').on('mouseover', 'div', function() {
        if(clicked) {
        	// Random color functionality
        	if (rand) {
        		$(document).mousemove(function() {
					color = random();
				});
        	}
            $(this).css('background-color', color);
        }
    })
}

// Specify the size of the grid
var userFields = function () {
	var r = prompt("Specify the number of rows (1-64):\n(Warning: Large values could be really slow.)");
	if (isNaN(r)) {
		alert("The value must be a number, mate!");
		return false;
	} else if (r < 1 || r > 64) {
		alert("The value must be a number between 1 and 64.");
		return false;
	}
	createBox(r, r);
	paintFields(usedColor);
	setFields(r, r);
}

// Clean the grid
var reset = function () {
	$('.magic-field').css('background-color', startColor);
}

// Generate and return random color in CSS value form
var random = function () {
	var r = Math.floor((Math.random() * 255));
	var g = Math.floor((Math.random() * 255));
	var b = Math.floor((Math.random() * 255));
	var rgb = "rgb(" + r + "," + g + "," + b +")";
	return rgb;
}

$(document).ready(function() {
	$(document).mousedown(function() {
		clicked = true;
	}).mouseup(function() {
		clicked = false;
	});

	$('.colors button').click(function() {
		erase = false;
		rand = false;
		$('.eraser').removeClass('active');
		$('.random').removeClass('active');
		paintFields(usedColor);
	});

	$('.random').on('click', function () {
		if (!rand) {
			usedColor = random();
			erase = false;
			$('.eraser').removeClass('active');
			rand = true;
			$(this).addClass('active');
		} else {
			rand = false;
			paintFields(temp);
			$(this).removeClass('active');
		}
	});

	$('.eraser').on('click', function () {
		if (!erase) {
			rand = false;
			$('.random').removeClass('active');
			erase = true;
			paintFields(usedColor);
			$(this).addClass('active');
		} else {
			erase = false;
			paintFields(temp);
			$(this).removeClass('active');
		}
	});

	createBox(rows, columns);
	paintFields(usedColor);
	setFields(rows, columns);
})
<commit_msg>Another description added<commit_after>// Grid's starting dimension
var rows = 16;
var columns = 16;

// Check the box dimension
var mbWidth = parseFloat($('.magic-box').css('width'));
var mbHeight = parseFloat($('.magic-box').css('height'));

// Color settings
var startColor = "#C9C9C9";
var usedColor = "black";

// Operating variables
var clicked = false;
var rand = false;
var erase = false;
var temp = usedColor;

// Set the size of the pixel based
// on the current size of the grid
var setFields = function (r, c) {
	var boxWidth = (mbWidth / c) + 'px';
	var boxHeight = (mbHeight / r) + 'px';
	$('.magic-field').css('width', boxWidth);
	$('.magic-field').css('height', boxHeight);
}

// Generate the grid and set base color
var createBox = function (rows, columns) {
	$('div.magic-field').remove();
	var i;
	var boxes = columns * rows
	for (i = 0; i < boxes; i++) {
		$('.magic-box').append('

');
	}
}

// Change the color of pixels you move the cursor
// when the mouse button is pressed
var paintFields = function (color) {
  	$('.magic-box').on('mouseover', 'div', function() {
        if(clicked) {
        	// Random color functionality
        	if (rand) {
        		$(document).mousemove(function() {
					color = random();
				});
        	}
            $(this).css('background-color', color);
        }
    })
}

// Specify the size of the grid
var userFields = function () {
	var r = prompt("Specify the number of rows (1-64):\n(Warning: Large values could be really slow.)");
	if (isNaN(r)) {
		alert("The value must be a number, mate!");
		return false;
	} else if (r < 1 || r > 64) {
		alert("The value must be a number between 1 and 64.");
		return false;
	}
	createBox(r, r);
	paintFields(usedColor);
	setFields(r, r);
}

// Clean the grid
var reset = function () {
	$('.magic-field').css('background-color', startColor);
}

// Generate and return random color in CSS value form
var random = function () {
	var r = Math.floor((Math.random() * 255));
	var g = Math.floor((Math.random() * 255));
	var b = Math.floor((Math.random() * 255));
	var rgb = "rgb(" + r + "," + g + "," + b +")";
	return rgb;
}

$(document).ready(function() {
	// variable needed to trigger painting on click
	$(document).mousedown(function() {
		clicked = true;
	}).mouseup(function() {
		clicked = false;
	});

	$('.colors button').click(function() {
		erase = false;
		rand = false;
		$('.eraser').removeClass('active');
		$('.random').removeClass('active');
		paintFields(usedColor);
	});

	$('.random').on('click', function () {
		if (!rand) {
			usedColor = random();
			erase = false;
			$('.eraser').removeClass('active');
			rand = true;
			$(this).addClass('active');
		} else {
			rand = false;
			paintFields(temp);
			$(this).removeClass('active');
		}
	});

	$('.eraser').on('click', function () {
		if (!erase) {
			rand = false;
			$('.random').removeClass('active');
			erase = true;
			paintFields(usedColor);
			$(this).addClass('active');
		} else {
			erase = false;
			paintFields(temp);
			$(this).removeClass('active');
		}
	});

	createBox(rows, columns);
	paintFields(usedColor);
	setFields(rows, columns);
})
<|endoftext|>


<commit_before>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'color-random': {
          'onclick':  function(){
              random_color();
          },
        },
        'darken': {
          'onclick': function(){
              darken_lighten(0);
          },
        },
        'lighten': {
          'onclick': function(){
              darken_lighten(1);
          },
        },
        'wcag': {
          'onclick': wcag_switch,
        },
        'wcag-background-use': {
          'onclick': function(){
              wcag_set('background');
          },
        },
        'wcag-foreground-use': {
          'onclick': function(){
              wcag_set('foreground');
          },
        },
      },
      'keybinds': {
        71: {
          'todo': function(){
              random_color('green');
          },
        },
        72: {
          'todo': function(){
              document.getElementById('hex').value = core_random_hex();
              update_fromhex();
          },
        },
        75: {
          'todo': function(){
              darken_lighten(0);
          },
        },
        76: {
          'todo': function(){
              darken_lighten(1);
          },
        },
        78: {
          'todo': function(){
              wcag_set('background');
          },
        },
        79: {
          'todo': function(){
              wcag_set('foreground');
          },
        },
        82: {
          'todo': function(){
              random_color('red');
          },
        },
        83: {
          'todo': wcag_switch,
        },
        85: {
          'todo': function(){
              random_color('blue');
          },
        },
      },
      'title': 'ColorSelector.htm',
    });

    // Event fires when user changes hex text input.
    document.getElementById('hex').oninput = update_fromhex;

    // Event fires when user updates the hex-color color input.
    document.getElementById('hex-color').oninput = function(){
        document.getElementById('hex').value =
          document.getElementById('hex-color').value.substring(
            1,
            7
          );

        update_fromhex();
    };

    document.getElementById('wcag-background-color').oninput = function(){
        update_wcag(
          'wcag-background',
          'wcag-background-color',
          document.getElementById('wcag-background-color').value.length
        );
    };

    document.getElementById('wcag-background').oninput = function(){
        update_wcag(
          'wcag-background-color',
          'wcag-background',
          false
        );
    };

    document.getElementById('wcag-foreground-color').oninput = function(){
        update_wcag(
          'wcag-foreground',
          'wcag-foreground-color',
          document.getElementById('wcag-foreground-color').value.length
        );
    };

    document.getElementById('wcag-foreground').oninput = function(){
        update_wcag(
          'wcag-foreground-color',
          'wcag-foreground',
          false
        );
    };

    document.getElementById('hex').value = core_random_hex();
    update_fromhex();

    update_wcag(
      'wcag-background',
      'wcag-background-color',
      false
    );
    update_wcag(
      'wcag-foreground',
      'wcag-foreground-color',
      false
    );

    var colors = [
      'blue',
      'green',
      'red',
    ];

    for(var color in colors){
        document.getElementById(colors[color] + '-random').onclick = function(){
            var id = this.id;
            // Event fires when color button is clicked.
            random_color(id.substring(0, id.indexOf('-')));
        };

        document.getElementById(colors[color]).oninput = function(){
            // Event fires when colors[color] slider is being slided.
            update_fromslider(this.id);
        };

        document.getElementById(colors[color] + '-1').oninput = function(){
            var id = this.id;
            // Event fires when user changes colors[color] 1 text input.
            update_from1(id.substring(0, id.indexOf('-')));
            update_hex();
        };

        document.getElementById(colors[color] + '-255').oninput = function(){
            var id = this.id;
            // Event fires when user changes colors[color] 255 text input.
            update_from255(id.substring(0, id.indexOf('-')));
            update_hex();
        };
    }
}
<commit_msg>moved some event binds to events arg<commit_after>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'color-random': {
          'onclick':  function(){
              random_color();
          },
        },
        'darken': {
          'onclick': function(){
              darken_lighten(0);
          },
        },
        'hex': {
          'oninput': update_fromhex,
        },
        'hex-color': {
          'oninput': function(){
              document.getElementById('hex').value =
                document.getElementById('hex-color').value.substring(
                  1,
                  7
                );

              update_fromhex();
          },
        },
        'lighten': {
          'onclick': function(){
              darken_lighten(1);
          },
        },
        'wcag': {
          'onclick': wcag_switch,
        },
        'wcag-background': {
          'oninput': function(){
              update_wcag(
                'wcag-background-color',
                'wcag-background',
                false
              );
          },
        },
        'wcag-background-color': {
          'oninput': function(){
              update_wcag(
                'wcag-background',
                'wcag-background-color',
                document.getElementById('wcag-background-color').value.length
              );
          },
        },
        'wcag-background-use': {
          'onclick': function(){
              wcag_set('background');
          },
        },
        'wcag-foreground': {
          'oninput': function(){
              update_wcag(
                'wcag-foreground-color',
                'wcag-foreground',
                false
              );
          },
        },
        'wcag-foreground-color': {
          'oninput': function(){
              update_wcag(
                'wcag-foreground',
                'wcag-foreground-color',
                document.getElementById('wcag-foreground-color').value.length
              );
          },
        },
        'wcag-foreground-use': {
          'onclick': function(){
              wcag_set('foreground');
          },
        },
      },
      'keybinds': {
        71: {
          'todo': function(){
              random_color('green');
          },
        },
        72: {
          'todo': function(){
              document.getElementById('hex').value = core_random_hex();
              update_fromhex();
          },
        },
        75: {
          'todo': function(){
              darken_lighten(0);
          },
        },
        76: {
          'todo': function(){
              darken_lighten(1);
          },
        },
        78: {
          'todo': function(){
              wcag_set('background');
          },
        },
        79: {
          'todo': function(){
              wcag_set('foreground');
          },
        },
        82: {
          'todo': function(){
              random_color('red');
          },
        },
        83: {
          'todo': wcag_switch,
        },
        85: {
          'todo': function(){
              random_color('blue');
          },
        },
      },
      'title': 'ColorSelector.htm',
    });

    document.getElementById('hex').value = core_random_hex();
    update_fromhex();

    update_wcag(
      'wcag-background',
      'wcag-background-color',
      false
    );
    update_wcag(
      'wcag-foreground',
      'wcag-foreground-color',
      false
    );

    var colors = [
      'blue',
      'green',
      'red',
    ];

    for(var color in colors){
        document.getElementById(colors[color] + '-random').onclick = function(){
            var id = this.id;
            // Event fires when color button is clicked.
            random_color(id.substring(0, id.indexOf('-')));
        };

        document.getElementById(colors[color]).oninput = function(){
            // Event fires when colors[color] slider is being slided.
            update_fromslider(this.id);
        };

        document.getElementById(colors[color] + '-1').oninput = function(){
            var id = this.id;
            // Event fires when user changes colors[color] 1 text input.
            update_from1(id.substring(0, id.indexOf('-')));
            update_hex();
        };

        document.getElementById(colors[color] + '-255').oninput = function(){
            var id = this.id;
            // Event fires when user changes colors[color] 255 text input.
            update_from255(id.substring(0, id.indexOf('-')));
            update_hex();
        };
    }
}
<|endoftext|>


<commit_before>var CandleValue = 70;
var used = false;
var CandleImgOff;
var CandleImgOnA;
var CandleImgOnB;
var lit = false;
var count = 1;
var timer = 3/8;

CandleValue = Cookies.get('candleLeft');

if(used == false) {

    CandleValue = 70;

}

$("#switch").click(function () {

    if(lit) {

        lit = false;
        $("#switch").attr("src","img/Switch0n.png");

    } else if (!lit && CandleValue > 0) {

        lit = true;
        $("#switch").attr("src","img/Switch0ff.png");
        used = true;
        Cookies.set('used', used);

    }

});

setInterval(function () {

    CandleCookie();

    if(lit) {

        TurnOn();

        if(count == 1) {
            count = 0;

        } else if(count == 0) {
            count = 1;

        }

        console.log (count);

        CandleValue = CandleValue - 1;

        if(CandleValue == 0) {

            lit = false;
            TurnOff();

        }

        console.log("Candle Left: " + CandleValue);

    } else if (!lit) {

        TurnOff();

    }

    Candle();

}, 0.5 * 1000);

function TurnOff () {

    $("#background").removeClass("light");
    $("#background").addClass("dark");
    $("#text").removeClass("visible");
    $("#text").addClass("notVisible");
    $("#textDark").addClass("visible");
    $("#textDark").removeClass("notVisible");
}

function TurnOn () {

    $("#background").removeClass("dark");
    $("#background").addClass("light");
    $("#text").removeClass("notVisible");
    $("#text").addClass("visible");
    $("#textDark").removeClass("visible");
    $("#textDark").addClass("notVisible");
}

function Candle () {

    if(CandleValue >= 60) {
        if(!lit) {
            $("#img").attr("src","img/CandleOff5.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1A.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2A.png");

            }

        }

    }

    if(59 > CandleValue && CandleValue > 50) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffB.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1B.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2B.png");

            }

        }

    }

    if(50 >= CandleValue && CandleValue > 40) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffC.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1C.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2C.png");

            }

        }

    }

    if(40 >= CandleValue && CandleValue > 30) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffD.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/COn1D.png");

            } else if (count == 0) {
                $("#img").attr("src","img/COn2D.png");

            }

        }

    }

    if(30 >= CandleValue && CandleValue > 20) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffE.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1E.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2E.png");

            }

        }

    }

    if(20 >= CandleValue && CandleValue > 10) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffF.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1F.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2F.png");

            }

        }

    }

    if(10 >= CandleValue && CandleValue > 0) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffG.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1G.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2G.png");

            }

        }

    }

    if(CandleValue == 0) {
        $("#img").attr("src","img/CandleOffH.png");
        used = true;
        Cookies.set('used', used);

    }
}

function CandleCookie () {
    Cookies.set('candleLeft', CandleValue);

}<commit_msg>.......<commit_after>var CandleValue = 70;
var used = false;
var CandleImgOff;
var CandleImgOnA;
var CandleImgOnB;
var lit = false;
var count = 1;
var timer = 3/8;

CandleValue = Cookies.get('candleLeft');

if(used == false) {

    CandleValue = 70;

}

$("#switch").click(function () {

    if(lit) {

        lit = false;
        $("#switch").attr("src","img/Switch0n.png");

    } else if (!lit && CandleValue > 0) {

        lit = true;
        $("#switch").attr("src","img/Switch0ff.png");
        used = true;
        Cookies.set('used', used);

    }

});

setInterval(function () {

    CandleCookie();

    if(lit) {

        TurnOn();

        if(count == 1) {
            count = 0;

        } else if(count == 0) {
            count = 1;

        }

        console.log (count);

        CandleValue = CandleValue - 1;

        if(CandleValue == 0) {

            lit = false;
            TurnOff();

        }

        console.log("Candle Left: " + CandleValue);

    } else if (!lit) {

        TurnOff();

    }

    Candle();

}, 0.5 * 1000);

function TurnOff () {

    $("#background").removeClass("light");
    $("#background").addClass("dark");
    $("#text").removeClass("visible");
    $("#text").addClass("notVisible");
    $("#textDark").addClass("visible");
    $("#textDark").removeClass("notVisible");
}

function TurnOn () {

    $("#background").removeClass("dark");
    $("#background").addClass("light");
    $("#text").removeClass("notVisible");
    $("#text").addClass("visible");
    $("#textDark").removeClass("visible");
    $("#textDark").addClass("notVisible");
}

function Candle () {

    if(CandleValue >= 60) {
        if(!lit) {
            $("#img").attr("src","img/CandleOff5.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1A.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2A.png");

            }

        }

    }

    if(59 > CandleValue && CandleValue > 50) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffB.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1B.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2B.png");

            }

        }

    }

    if(50 >= CandleValue && CandleValue > 40) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffC.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1C.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2C.png");

            }

        }

    }

    if(40 >= CandleValue && CandleValue > 30) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffD.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/COn1D.png");

            } else if (count == 0) {
                $("#img").attr("src","img/COn2D.png");

            }

        }

    }

    if(30 >= CandleValue && CandleValue > 20) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffE.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1E.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2E.png");

            }

        }

    }

    if(20 >= CandleValue && CandleValue > 10) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffF.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1F.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2F.png");

            }

        }

    }

    if(10 >= CandleValue && CandleValue > 0) {
        if(!lit) {
            $("#img").attr("src","img/CandleOffG.png");

        } else if (lit) {
            if(count == 1) {
                $("#img").attr("src","img/CandleOn1G.png");

            } else if (count == 0) {
                $("#img").attr("src","img/CandleOn2G.png");

            }

        }

    }

    if(CandleValue == 0) {
        $("#img").attr("src","img/CandleOffH.png");

    }

    if(CandleValue < 70) {
        used = true;
        Cookies.set('used', used);

    }
}

function CandleCookie () {
    Cookies.set('candleLeft', CandleValue);

}<|endoftext|>


<commit_before>(function() {
    function normalizeOrigin(str) {
        var re = /\:\d+/,
            index = str.indexOf(str.match(re)),
            normalizedOrigin = str.substr(0, index);
        return (index > -1) ? normalizedOrigin : str;
    }

    var LOADING = 'loading',
        ONLINE = 'online',
        OFFLINE = 'offline',
        ORIGIN = normalizeOrigin(location.origin),
        TEMPLATE_URL = ORIGIN + ':{port}/html/js/aui/aui/aui.js';

    YUI().use('aui-base', 'jsonp', 'jsonp-url', function(A) {
        var nav = A.one('.nav');

        nav.delegate('click', function(event) {
            var currentTarget = event.currentTarget,
                port = currentTarget.getData('port'),
                href = currentTarget.attr('href'),
                formattedHREF = ORIGIN + ':' + port + '/?js_fast_load=0';

            currentTarget.attr('href', formattedHREF);
        }, 'a');

        console.log('js');

        nav.all('.portal-instance-link').each(function(item, index) {
            var url = A.Lang.sub(TEMPLATE_URL, { port: item.getData('port') });
            console.log('url: ', url);

            return;
            var service = new A.JSONPRequest(url, {
                on: {
                    success: function() {
                        // to-do print online status
                    },
                    failure: function() {
                        item.one('.status').text(OFFLINE).show();

                        item.one('.link-text').setStyle('color', 'gray');

                        item.addClass('disabled');
                    }
                }
            });

            service.send();
        });
    });
})();<commit_msg> - javascript causes ios loader to freak out<commit_after>(function() {
    'use strict';

    function normalizeOrigin(str) {
        var re = /\:\d+/,
            index = str.indexOf(str.match(re)),
            normalizedOrigin = str.substr(0, index);
        return (index > -1) ? normalizedOrigin : str;
    }

    var ORIGIN = normalizeOrigin(location.origin);

    YUI().use('aui-base', 'jsonp', 'jsonp-url', function(A) {
        var nav = A.one('.nav');

        nav.delegate('click', function(event) {
            var currentTarget = event.currentTarget,
                port = currentTarget.getData('port'),
                formattedHREF = ORIGIN + ':' + port + '/?js_fast_load=0';

            currentTarget.attr('href', formattedHREF);
        }, 'a');

        // var TEMPLATE_URL = ORIGIN + ':{port}/html/js/aui/aui/aui.js';

        // var strings = {
        //     loading: 'loading',
        //     online: 'online',
        //     offline: 'offline'
        // };

        // nav.all('.portal-instance-link').each(function(item, index) {
            // var url = A.Lang.sub(TEMPLATE_URL, { port: item.getData('port') });

            // var service = new A.JSONPRequest(url, {
            //     on: {
            //         success: function() {
            //             // to-do print online status
            //         },
            //         failure: function() {
            //             item.one('.status').text(OFFLINE).show();

            //             item.one('.link-text').setStyle('color', 'gray');

            //             item.addClass('disabled');
            //         }
            //     }
            // });

            // service.send();
        // });
    });
})();<|endoftext|>


<commit_before>var accessMode;
var user;
if (!Cookie.get("UserRoleID")) {
	$("#referer").val(window.location);
} else {
	var url = $("#signout").attr("href");
	$("#signout").attr("href", url + "?refererURL=" + window.location)
}
var BaseRouter = Backbone.Router.extend({
	objectName : null,

	activeView : null,

	initialize : function() {
		this.route("", "objectList");
		this.route(":id", "singleObject");
		this.route("new", "newObject");
		this.route(":id/entities", "entityList");
		this.route(":id/entities/new", "newEntity");
		this.route(":id/entities/#:entityID", "EntityDetails");
		this.route(":id/entities/import", "entityImport");
		this.route("housekeeping", "housekeeping");
	},
	isLoginFailure : function() {
		if (window.location.href.indexOf('login=failed') !== -1) {
			return true;
		}

		return false;
	},
	isAuthorized : function(routeType) {
		var roleID = Cookie.get("UserRoleID");

		$('#alerts').html('');
		/*var routeType;
		var caller = arguments.callee.caller;

		if (callerName === "objectList") {
			routeType = "list";
		}*/

		if (objects[this.objectName] !== undefined) {
			if (objects[this.objectName][roleID] !== undefined) {
				if(typeof(objects[this.objectName][roleID]) === "boolean"){
					if (objects[this.objectName][roleID]) {
						return true;
					}
				} else {
					if (objects[this.objectName][roleID][routeType]  !== undefined) {
						return true;
					}
				}
			} else if (objects[this.objectName][99] !== undefined) {
				return true;
			}

		} else {
			return true;
		}

		if (this.isLoginFailure()) {
			var alert_msg = '
'+
			'
' + 'Login failed.'+
			'

' + 'Please try again with your correct credentials.'+
			'
' + 'If you don´t remember your credentials go to ' + 'Password Recovery'+ '.' +
			'

' + 'In case you´re not registered yet, you might want to ' + 'Sign Up'+ ' here.' +
	    	'
';
		} else {
			var alert_msg = '
'+
			'
Access not granted.'+
			'

' + 'Please login to access this content.' +
			'
' + 'If you don´t remember your credentials go to ' + 'Password Recovery'+ '.' +
			'

' + 'In case you´re not registered yet, you might want to ' + 'Sign Up'+ ' here.' +
	    	'
';
		}

		$('#alerts').html(alert_msg);

		return false;
	},
	isWatchedObject : function (object, watchlist) {
		var watchlistItems = watchlist.get('WatchlistItems');

		var item;
		for(var i=0; i<watchlistItems.length; i++) {
			if (object.get('OntologyClass')) {
				if (parseInt(object.get('OntologyClass').id) === parseInt(watchlistItems.models[i].get('ontologyClassID')) && parseInt(object.id) === parseInt(watchlistItems.models[i].get('entityID'))) {
					return true;
				}
			} else if (object.type === "OntologyClass") {
				if (parseInt(object.id) === parseInt(watchlistItems.models[i].get('entityID'))) {
					return true;
				}

			}

		}

		return false;
	},
	objectList : function() {
		if (this.isAuthorized('list')) {
			var objectList = new window[this.objectName + "Collection"]();

			var objectlistView = new ObjectListView({el : $('#content'),
				collection : objectList, objectName : this.objectName});

			objectlistView.render();
		}
	},
	entityList : function() {
		if (this.isAuthorized('list')) {
			var entityList = new window[this.objectName + "Entity" + "Collection"]();

			var entitylistView = new EntityListView({el : $('#content'),
				collection : entityList, objectName : this.objectName});

			entitylistView.render();
		}
	},
	singleObject : function(id) {
		if (this.isAuthorized('single')) {
			var object = window[this.objectName].findOrCreate({
				id : id
			});

			var dataservices = new DataServiceCollection();
			dataservicesPromise = dataservices.fetch();

			accessMode = "read";

			object.type = this.objectName;

			objectPromise = object.fetch();

			if (Cookie.get("UserID")) {
				user = User.findOrCreate({
					id : Cookie.get("UserID")
				});

				if (!user.get('Watchlist')) {
					var watchlist = new Watchlist();

					watchlist.urlRoot = user.urlRoot + "/" + user.id + "/watchlists";

					watchlistPromise = watchlist.fetch();
				} else {
					var watchlist = user.get('Watchlist');
				}

				var self = this;

				$.when(objectPromise, watchlistPromise).then(function() {
					user.set('Watchlist', watchlist);

					if (self.isWatchedObject(object, watchlist)) {
						object.isWatched = true;
					}
					var objectView = new SingleObjectView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					app.activeView = objectView;
				});
			} else {
				$.when(objectPromise).then(function() {
					var objectView = new SingleObjectView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					app.activeView = objectView;

					var ontologyClass = new OntologyClass();

					ontologyClass.urlRoot = ontologyClass.urlRoot + "?name=" + object.type;

					ontologyClassPromise = ontologyClass.fetch();

					$.when(ontologyClassPromise).then(function() {
						var ontologyInformationView = new OntologyInformationView({
							el : $('#ontologyInformation'),
							model : ontologyClass
						});

						$("#ontologyInformation").append(ontologyInformationView.render().el);
					});

				});
			}
		}
	},
	EntityDetails : function(id, entityID) {
		var entityBase = window[this.objectName].findOrCreate({
			id : id
		});
		entityBase.type = this.objectName;

		entityBasePromise = entityBase.fetch();

		$.when(entityBasePromise).then(function() {
			var object = window[entityBase.type + "Entity"].findOrCreate({
				id : entityID
			});

			object.type = entityBase.type + "Entity";

			object.set(entityBase.type, entityBase);

			accessMode = "read";

			object.fetch({
				success : function() {
					var objectView = new SingleEntityView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					var watchlist = new Watchlist();

					watchlist.urlRoot = self.user.urlRoot + "/" + self.user.id + "/watchlists";

					objectView.user.set('Watchlist', watchlist);

					watchlist.fetch();
				}
			});
		});

	},
	entityImport : function(id) {
		if (isAuthorized(this.objectName, Cookie.get("UserRoleID"))) {
			var object = window[this.objectName].findOrCreate({
				id : id
			});

			accessMode = "read";

			object.type = this.objectName;

			objectPromise = object.fetch();

			$.when(objectPromise).then(function() {
				var entityImportView = new EntityImportView({
					el : $('#content'),
					model : object
				});

				entityImportView.render();
			});
		} else {
			var alert_msg = '
'+
			'Authentication Warning'+
			'
' + 'Login Failed'+
			'
' + '' + 'Password Recovery '+ '' +
	    	'
';

			$('#alerts').html(alert_msg);
		}
	},
	newObject : function() {
		var object = window[this.objectName].findOrCreate({
			id : null
		});

		accessMode = "edit";

		object.type = this.objectName;

		var objectView = new SingleObjectView({
			el : $('#content'),
			model : object
		});

		objectView.render();
	},
	newEntity : function(id) {
		var entityBase = window[this.objectName].findOrCreate({
			id : id
		});
		entityBase.type = this.objectName;

		entityBasePromise = entityBase.fetch();

		$.when(entityBasePromise).then(function() {
			var object = window[entityBase.type + "Entity"].findOrCreate({
				id : null
			});
			object.type = entityBase.type + "Entity";

			object.set(entityBase.type, entityBase);

			accessMode = "edit";

			var objectView = new SingleEntityView({
				el : $('#content'),
				model : object
			});

			objectView.render();

		});
	},

	intro : function() {
		intro_view = new IntroView({
			el : $('#content')
		});

		intro_view.render();
	}
});
tpl.loadTemplates([
	   '../../layouts/objectlist',
	   '../../layouts/entitylist',
	   '../../layouts/singleobject',
	   '../../layouts/ontologyinformation',
	   '../../layouts/concreteinformation',

	   '../../components/accordiongroup',
	   '../../components/accordionitem',
	   '../../components/backgrid',
	   '../../components/backgrid_actions',

	   '../../components/input_datepicker',
	   '../../components/input_textarea',
	   '../../components/input_text',
	   '../../components/input_tags',
	   '../../components/input_highcharts',
	   '../../components/input_select',
	   '../../components/input_locationmap',
	   '../../components/input_datepicker',
	   '../../components/input_checkbox'
   ], true,
function() {
	app = new AppRouter();
	Backbone.history.start();
});<commit_msg>ENGU-5 Broken Router Extension<commit_after>var accessMode;
var user;
if (!Cookie.get("UserRoleID")) {
	$("#referer").val(window.location);
} else {
	var url = $("#signout").attr("href");
	$("#signout").attr("href", url + "?refererURL=" + window.location)
}
var BaseRouter = Backbone.Router.extend({
	objectName : null,

	activeView : null,

	initialize : function() {
		this.route("", "objectList");
		this.route(":id", "singleObject");
		this.route("new", "newObject");
		this.route(":id/entities", "entityList");
		this.route(":id/entities/new", "newEntity");
		this.route(":id/entities/#:entityID", "EntityDetails");
		this.route(":id/entities/import", "entityImport");
		this.route("housekeeping", "housekeeping");
	},
	isLoginFailure : function() {
		if (window.location.href.indexOf('login=failed') !== -1) {
			return true;
		}

		return false;
	},
	isAuthorized : function(routeType) {
		var roleID = Cookie.get("UserRoleID");

		$('#alerts').html('');
		/*var routeType;
		var caller = arguments.callee.caller;

		if (callerName === "objectList") {
			routeType = "list";
		}*/

		if (objects[this.objectName] !== undefined) {
			if (objects[this.objectName][roleID] !== undefined) {
				if(typeof(objects[this.objectName][roleID]) === "boolean"){
					if (objects[this.objectName][roleID]) {
						return true;
					}
				} else {
					if (objects[this.objectName][roleID][routeType]  !== undefined) {
						return true;
					}
				}
			} else if (objects[this.objectName][99] !== undefined) {
				return true;
			}

		} else {
			return true;
		}

		if (this.isLoginFailure()) {
			var alert_msg = '
'+
			'
' + 'Login failed.'+
			'

' + 'Please try again with your correct credentials.'+
			'
' + 'If you don´t remember your credentials go to ' + 'Password Recovery'+ '.' +
			'

' + 'In case you´re not registered yet, you might want to ' + 'Sign Up'+ ' here.' +
	    	'
';
		} else {
			var alert_msg = '
'+
			'
Access not granted.'+
			'

' + 'Please login to access this content.' +
			'
' + 'If you don´t remember your credentials go to ' + 'Password Recovery'+ '.' +
			'

' + 'In case you´re not registered yet, you might want to ' + 'Sign Up'+ ' here.' +
	    	'
';
		}

		$('#alerts').html(alert_msg);

		return false;
	},
	isWatchedObject : function (object, watchlist) {
		var watchlistItems = watchlist.get('WatchlistItems');

		var item;
		for(var i=0; i<watchlistItems.length; i++) {
			if (object.get('OntologyClass')) {
				if (parseInt(object.get('OntologyClass').id) === parseInt(watchlistItems.models[i].get('ontologyClassID')) && parseInt(object.id) === parseInt(watchlistItems.models[i].get('entityID'))) {
					return true;
				}
			} else if (object.type === "OntologyClass") {
				if (parseInt(object.id) === parseInt(watchlistItems.models[i].get('entityID'))) {
					return true;
				}

			}

		}

		return false;
	},
	objectList : function() {
		if (this.isAuthorized('list')) {
			var objectList = new window[this.objectName + "Collection"]();

			var objectlistView = new ObjectListView({el : $('#content'),
				collection : objectList, objectName : this.objectName});

			objectlistView.render();
		}
	},
	entityList : function() {
		if (this.isAuthorized('list')) {
			var entityList = new window[this.objectName + "Entity" + "Collection"]();

			var entitylistView = new EntityListView({el : $('#content'),
				collection : entityList, objectName : this.objectName});

			entitylistView.render();
		}
	},
	singleObject : function(id) {
		if (this.isAuthorized('single')) {
			var object = window[this.objectName].findOrCreate({
				id : id
			});

			var dataservices = new DataServiceCollection();
			dataservicesPromise = dataservices.fetch();

			accessMode = "read";

			object.type = this.objectName;

			objectPromise = object.fetch();

			if (Cookie.get("UserID")) {
				user = User.findOrCreate({
					id : Cookie.get("UserID")
				});

				if (!user.get('Watchlist')) {
					var watchlist = new Watchlist();

					watchlist.urlRoot = user.urlRoot + "/" + user.id + "/watchlists";

					watchlistPromise = watchlist.fetch();
				} else {
					var watchlist = user.get('Watchlist');
				}

				var self = this;

				$.when(objectPromise, watchlistPromise).then(function() {
					user.set('Watchlist', watchlist);

					if (self.isWatchedObject(object, watchlist)) {
						object.isWatched = true;
					}
					var objectView = new SingleObjectView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					app.activeView = objectView;
				});
			} else {
				$.when(objectPromise).then(function() {
					var objectView = new SingleObjectView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					app.activeView = objectView;

					var ontologyClass = new OntologyClass();

					ontologyClass.urlRoot = ontologyClass.urlRoot + "?name=" + object.type;

					ontologyClassPromise = ontologyClass.fetch();

					$.when(ontologyClassPromise).then(function() {
						var ontologyInformationView = new OntologyInformationView({
							el : $('#ontologyInformation'),
							model : ontologyClass
						});

						$("#ontologyInformation").append(ontologyInformationView.render().el);
					});

				});
			}
		}
	},
	EntityDetails : function(id, entityID) {
		var entityBase = window[this.objectName].findOrCreate({
			id : id
		});
		entityBase.type = this.objectName;

		entityBasePromise = entityBase.fetch();

		$.when(entityBasePromise).then(function() {
			var object = window[entityBase.type + "Entity"].findOrCreate({
				id : entityID
			});

			object.type = entityBase.type + "Entity";

			object.set(entityBase.type, entityBase);

			accessMode = "read";

			object.fetch({
				success : function() {
					var objectView = new SingleEntityView({
						el : $('#content'),
						model : object
					});

					objectView.render();

					var watchlist = new Watchlist();

					watchlist.urlRoot = self.user.urlRoot + "/" + self.user.id + "/watchlists";

					objectView.user.set('Watchlist', watchlist);

					watchlist.fetch();
				}
			});
		});

	},
	entityImport : function(id) {
		if (isAuthorized(this.objectName, Cookie.get("UserRoleID"))) {
			var object = window[this.objectName].findOrCreate({
				id : id
			});

			accessMode = "read";

			object.type = this.objectName;

			objectPromise = object.fetch();

			$.when(objectPromise).then(function() {
				var entityImportView = new EntityImportView({
					el : $('#content'),
					model : object
				});

				entityImportView.render();
			});
		} else {
			var alert_msg = '
'+
			'Authentication Warning'+
			'
' + 'Login Failed'+
			'
' + '' + 'Password Recovery '+ '' +
	    	'
';

			$('#alerts').html(alert_msg);
		}
	},
	newObject : function() {
		var object = window[this.objectName].findOrCreate({
			id : null
		});

		accessMode = "edit";

		object.type = this.objectName;

		var objectView = new SingleObjectView({
			el : $('#content'),
			model : object
		});

		objectView.render();
	},
	newEntity : function(id) {
		var entityBase = window[this.objectName].findOrCreate({
			id : id
		});
		entityBase.type = this.objectName;

		entityBasePromise = entityBase.fetch();

		$.when(entityBasePromise).then(function() {
			var object = window[entityBase.type + "Entity"].findOrCreate({
				id : null
			});
			object.type = entityBase.type + "Entity";

			object.set(entityBase.type, entityBase);

			accessMode = "edit";

			var objectView = new SingleEntityView({
				el : $('#content'),
				model : object
			});

			objectView.render();

		});
	},

	intro : function() {
		intro_view = new IntroView({
			el : $('#content')
		});

		intro_view.render();
	}
});<|endoftext|>


<commit_before>requirejs.config({
	baseUrl: "js",
	packages: [
		{
			name: "databindings",
			location: "//rawgit.com/OHDSI/Circe/multihomed/js/modules/databindings"
		},
		{
			name: "circe",
			location: "//rawgit.com/OHDSI/Circe/multihomed/js/modules/circe"
		}
	],
	config: {
		text: {
			useXhr: function (url, protocol, hostname, port) {
				return true;
			}
		}
	},
	paths: {
		// application configuration
		"appConfig" : "config",
		// 3rd party libs
		"jquery": "http://cdn.rawgit.com/jquery/jquery/1.11.2/dist/jquery.min",
		"jquery-ui": "jqueryui/jquery-ui.min",
		"d3": "http://cdn.rawgit.com/mbostock/d3/v3.5.5/d3.min",
		"knockout": "http://cdn.rawgit.com/knockout/knockout/v3.3.0/dist/knockout",
		"director": "director.1.2.6.min",
		"databindings/knockout.selectOnFocus": "http://cdn.rawgit.com/One-com/knockout-select-on-focus/v0.1.5/lib/knockout.selectOnFocus",
		"datatables": "jqueryui/jquery.dataTables.min",
		// OHDSI components
		"cohortbuilder": "http://rawgit.com/OHDSI/Circe/multihomed/js/modules/cohortbuilder",
		"conceptsetbuilder": "http://rawgit.com/OHDSI/Circe/multihomed/js/modules/conceptsetbuilder",
		"feasibilitystudy": "modules/feasibilitystudy",
		"webapi" : "http://rawgit.com/OHDSI/Circe/multihomed/js/modules/WebAPIProvider",

		"vocabularyprovider": "http://rawgit.com/OHDSI/Circe/multihomed/js/modules/WebAPIProvider/VocabularyProvider",
		// plugins
		"text": "requirejs/plugins/text",
		"css": "requirejs/plugins/css",
		"json": "requirejs/plugins/json",
		"ColVis": "jqueryui/dataTables.colVis.min"
	},
	shim: {
		"director": { exports: "Router" }
	},
	map: {
		"*": {
			"webapi/FeasibilityAPI" : "modules/WebAPIProvider/FeasibilityAPI",
		}
	},
	deps: ['jquery',
				 'jquery-ui',
				 'jqueryui/jquery.ui.autocomplete.scroll',
				 'css!jqueryui/jquery.dataTables.css',
				 'css!jqueryui/dataTables.colVis.css'
				]
});

require(['jquery','knockout', 'app', 'director' ], function ($, ko, App, Router) {
	var calypsoApp = new App();
	ko.applyBindings(calypsoApp, document.getElementById('wrapper'));

	var router = Router(calypsoApp.routes);
	router.init('/');
	calypsoApp.router = router;

	$(window).bind('beforeunload', function () {
			if (calypsoApp.selectedStudy() &&  calypsoApp.dirtyFlag() && calypsoApp.dirtyFlag().isDirty())
					return "Changes will be lost if you do not save.";
	});
});<commit_msg>Update main.js to point to proper CDN from rawgit.<commit_after>requirejs.config({
	baseUrl: "js",
	packages: [
		{
			name: "databindings",
			location: "//rawgit.com/OHDSI/Circe/master/js/modules/databindings"
		},
		{
			name: "circe",
			location: "//rawgit.com/OHDSI/Circe/master/js/modules/circe"
		}
	],
	config: {
		text: {
			useXhr: function (url, protocol, hostname, port) {
				return true;
			}
		}
	},
	paths: {
		// application configuration
		"appConfig" : "config",
		// 3rd party libs
		"jquery": "http://cdn.rawgit.com/jquery/jquery/1.11.2/dist/jquery.min",
		"jquery-ui": "jqueryui/jquery-ui.min",
		"d3": "http://cdn.rawgit.com/mbostock/d3/v3.5.5/d3.min",
		"knockout": "http://cdn.rawgit.com/knockout/knockout/v3.3.0/dist/knockout",
		"director": "director.1.2.6.min",
		"databindings/knockout.selectOnFocus": "http://cdn.rawgit.com/One-com/knockout-select-on-focus/v0.1.5/lib/knockout.selectOnFocus",
		"datatables": "jqueryui/jquery.dataTables.min",
		// OHDSI components
		"cohortbuilder": "http://rawgit.com/OHDSI/Circe/master/js/modules/cohortbuilder",
		"conceptsetbuilder": "http://rawgit.com/OHDSI/Circe/master/js/modules/conceptsetbuilder",
		"feasibilitystudy": "modules/feasibilitystudy",
		"webapi" : "http://rawgit.com/OHDSI/Circe/master/js/modules/WebAPIProvider",

		"vocabularyprovider": "http://rawgit.com/OHDSI/Circe/master/js/modules/WebAPIProvider/VocabularyProvider",
		// plugins
		"text": "requirejs/plugins/text",
		"css": "requirejs/plugins/css",
		"json": "requirejs/plugins/json",
		"ColVis": "jqueryui/dataTables.colVis.min"
	},
	shim: {
		"director": { exports: "Router" }
	},
	map: {
		"*": {
			"webapi/FeasibilityAPI" : "modules/WebAPIProvider/FeasibilityAPI",
		}
	},
	deps: ['jquery',
				 'jquery-ui',
				 'jqueryui/jquery.ui.autocomplete.scroll',
				 'css!jqueryui/jquery.dataTables.css',
				 'css!jqueryui/dataTables.colVis.css'
				]
});

require(['jquery','knockout', 'app', 'director' ], function ($, ko, App, Router) {
	var calypsoApp = new App();
	ko.applyBindings(calypsoApp, document.getElementById('wrapper'));

	var router = Router(calypsoApp.routes);
	router.init('/');
	calypsoApp.router = router;

	$(window).bind('beforeunload', function () {
			if (calypsoApp.selectedStudy() &&  calypsoApp.dirtyFlag() && calypsoApp.dirtyFlag().isDirty())
					return "Changes will be lost if you do not save.";
	});
});<|endoftext|>


<commit_before>(function(window, document) {

    'use strict';

        // {Object} - Rutas y descripción de las imágenes.
    var config,

        // {NodeList} - Almacena los nodos celda de la cuadrícula.
        cells,

        // {Array} - Almacena la pareja actualmente seleccionada. Cada
        //           elemento se representa con un objeto literal con
        //           tres propiedades: El nodo "celda", el nodo "imagen",
        //           y el nombre de la imagen.
        couple = [],

        // {Boolean} - Bandera de bloqueo para evitar que se seleccionen más de
        //             dos imágenes al mismo tiempo.
        locked = false;

    config = {
        themesPath: 'img/shapes/',
        currentTheme: 'superheroes',
        themes: {
            superheroes: {
                dirpath: 'superheroes/',
                suffix: 'sph',
                ext: '.jpg'
            }
        }
    };

    // TODO: Usar algún metodo del DOM para obtener todas celdas de la cuadrícula.
    cells = document.querySelectorAll('.grid-cell');

    // TODO: Añadir manejadores del evento 'click' a todas las celdas.
    for (var i = 0; i < cells.length; i++) {
        cells[i].addEventListener('click', clickHandler, false);
    }

    // TODO: Llamada a la función principal `setImages()`.
    setImages(config, cells);

    //---------------------------- Funciones -----------------------------------

    /**
     * Crea imágenes y las añade a las celdas.
     * @param {Object} config - rutas y descripción de las imágenes.
     * @param {NodeList} cells - Las celdas de la cuadrícula.
     */
    function setImages(config, cells) {
        var size = cells.length,
            half = size / 2,
            set1 = createRandomSet(half),
            set2 = createRandomSet(half),
            img1,
            img2,
            i;

        for (i = 0; i < size; i += 2) {
            // TODO: Crear todas las imágenes y añadirlas a las celdas de
            // la cuadrícula. Las imágenes se van añadiendo de dos en dos,
            // configurando la ruta de cada imagen a partir de los conjuntos de
            // números aleatorios `set1` y `set2`.
            img1 = new Image();
            img2 = new Image();
            img1.draggable = false;
            img2.draggable = false;
            img1.src = createImgPath(config, set1[i / 2]);
            img2.src = createImgPath(config, set2[i / 2]);
            cells[i].appendChild(img1);
            cells[i + 1].appendChild(img2);
        }
    }

    /**
     * Crea ruta de una imagen.
     * @param {Object} config - rutas y descripción de las imágenes.
     * @param {Number} n - el número identificador de la imagen.
     */
    function createImgPath(config, n) {
        var currentTheme, themes;

        themes = config.themes;
        currentTheme = config.currentTheme;

        return config.themesPath +
                themes[currentTheme].dirpath +
                themes[currentTheme].suffix +
                n + themes[currentTheme].ext;
    }

    /**
     * Crea un array con números aleatorios no repetidos empezando por 1.
     * @param {Number} size - el tamaño del array.
     */
    function createRandomSet(size) {
        var xs, i, j, k;

        for (i = 1, xs = []; i <= size; i++) {
            xs[i - 1] = i;
        }

        i = size;
        while (i > 1) {
            i--;
            j = Math.random() * i | 0;
            k = xs[i];
            xs[i] = xs[j];
            xs[j] = k;
        }

        return xs;
    }

    /**
     * Manejador del evento 'click'.
     */
    function clickHandler() {
        var self = this,
            img,
            imgName,
            item1,
            item2;

        if (!locked) {

            // TODO:
            // - Eliminar el manejador del evento en la celda actual (para evitar más clicks).
            // - Obtener el nodo imagen de la celda, mostrar la imagen y
            //   almacenar un nuevo objeto al array `couple`.
            self.removeEventListener('click', clickHandler, false);
            img = self.firstElementChild;
            img.style.opacity = 1;
            imgName = img.src.split('/').pop();
            couple.push({cell: self, img: img, imgName: imgName});

            if (couple.length === 2) {

                // TODO: Levantar la bandera de bloqueo y extraer la pareja.
                locked = true;
                item1 = couple.pop();
                item2 = couple.pop();

                if (item1.imgName === item2.imgName) {

                    // Bajar de nuevo la bandera de bloqueo.
                    locked = false;

                } else {

                    // Crear un temporizador de 2 segundos para ocultar de nuevo
                    // ambas imágenes, añadir de nuevo los manejadores del evento
                    // 'click' de sus celdas y bajar de nuevo la bandera de bloqueo.
                    setTimeout(function() {
                        item1.cell.addEventListener('click', clickHandler, false);
                        item2.cell.addEventListener('click', clickHandler, false);
                        item1.img.style.opacity = 0;
                        item2.img.style.opacity = 0;
                        locked = false;
                    }, 2000);
                }
            }
        }
    }

}(window, document));
<commit_msg>Remove TODO comments<commit_after>(function(window, document) {

    'use strict';

        // {Object} - Rutas y descripción de las imágenes.
    var config,

        // {NodeList} - Almacena los nodos celda de la cuadrícula.
        cells,

        // {Array} - Almacena la pareja actualmente seleccionada. Cada
        //           elemento se representa con un objeto literal con
        //           tres propiedades: El nodo "celda", el nodo "imagen",
        //           y el nombre de la imagen.
        couple = [],

        // {Boolean} - Bandera de bloqueo para evitar que se seleccionen más de
        //             dos imágenes al mismo tiempo.
        locked = false;

    config = {
        themesPath: 'img/shapes/',
        currentTheme: 'superheroes',
        themes: {
            superheroes: {
                dirpath: 'superheroes/',
                suffix: 'sph',
                ext: '.jpg'
            }
        }
    };

    cells = document.querySelectorAll('.grid-cell');

    for (var i = 0; i < cells.length; i++) {
        cells[i].addEventListener('click', clickHandler, false);
    }

    setImages(config, cells);

    //---------------------------- Funciones -----------------------------------

    /**
     * Crea imágenes y las añade a las celdas.
     * @param {Object} config - rutas y descripción de las imágenes.
     * @param {NodeList} cells - Las celdas de la cuadrícula.
     */
    function setImages(config, cells) {
        var size = cells.length,
            half = size / 2,
            set1 = createRandomSet(half),
            set2 = createRandomSet(half),
            img1,
            img2,
            i;

        for (i = 0; i < size; i += 2) {
            img1 = new Image();
            img2 = new Image();
            img1.draggable = false;
            img2.draggable = false;
            img1.src = createImgPath(config, set1[i / 2]);
            img2.src = createImgPath(config, set2[i / 2]);
            cells[i].appendChild(img1);
            cells[i + 1].appendChild(img2);
        }
    }

    /**
     * Crea ruta de una imagen.
     * @param {Object} config - rutas y descripción de las imágenes.
     * @param {Number} n - el número identificador de la imagen.
     */
    function createImgPath(config, n) {
        var currentTheme, themes;

        themes = config.themes;
        currentTheme = config.currentTheme;

        return config.themesPath +
                themes[currentTheme].dirpath +
                themes[currentTheme].suffix +
                n + themes[currentTheme].ext;
    }

    /**
     * Crea un array con números aleatorios no repetidos empezando por 1.
     * @param {Number} size - el tamaño del array.
     */
    function createRandomSet(size) {
        var xs, i, j, k;

        for (i = 1, xs = []; i <= size; i++) {
            xs[i - 1] = i;
        }

        i = size;
        while (i > 1) {
            i--;
            j = Math.random() * i | 0;
            k = xs[i];
            xs[i] = xs[j];
            xs[j] = k;
        }

        return xs;
    }

    /**
     * Manejador del evento 'click'.
     */
    function clickHandler() {
        var self = this,
            img,
            imgName,
            item1,
            item2;

        if (!locked) {
            self.removeEventListener('click', clickHandler, false);
            img = self.firstElementChild;
            img.style.opacity = 1;
            imgName = img.src.split('/').pop();
            couple.push({cell: self, img: img, imgName: imgName});

            if (couple.length === 2) {
                locked = true;
                item1 = couple.pop();
                item2 = couple.pop();

                if (item1.imgName === item2.imgName) {
                    locked = false;
                } else {
                    setTimeout(function() {
                        item1.cell.addEventListener('click', clickHandler, false);
                        item2.cell.addEventListener('click', clickHandler, false);
                        item1.img.style.opacity = 0;
                        item2.img.style.opacity = 0;
                        locked = false;
                    }, 2000);
                }
            }
        }
    }

}(window, document));
<|endoftext|>


<commit_before>
$( document ).ready(function(){

	$("#content").hide();

	$("#know_more").click(function(){
	  $("#content").show();
	  // this.hide();
	});

	var form = $('form');
	$("form").on("submit",function( event ) {
  		event.preventDefault();
  		console.log("not");
  		// $.ajax({
    //         type: form.attr('method'),
    //         url: form.attr('action'),
    //         data: form.serialize(),
    //         dataType: 'json',
    //         success: function (data) {
    //         	console.log(data);
    //         },
    //         error: function(err){
    //         	console.log(err);
    //         }
    //     });
    $.ajax({
	url: 'https://www51.e-goi.com/api/public/commons/ping',
	contentType: 'application/json',
	type: 'POST',
	dataType: 'json',
	data: JSON.stringify({
		foo: "This text is left of",
		bar: "this text..."
	}),
	success: function(data) {
		var output = data.responseText;
		console.log(output);
		// ... do something useful
	}
});
  		// Submit ajax form and treat answer.
	});

});
<commit_msg>Revert<commit_after>
$( document ).ready(function(){

	$("#content").hide();

	$("#know_more").click(function(){
	  $("#content").show();
	  // this.hide();
	});

	// var form = $('form');
	// $("form").on("submit",function( event ) {
 //  		event.preventDefault();
 //  		console.log("not");
 //  		// $.ajax({
 //    //         type: form.attr('method'),
 //    //         url: form.attr('action'),
 //    //         data: form.serialize(),
 //    //         dataType: 'json',
 //    //         success: function (data) {
 //    //         	console.log(data);
 //    //         },
 //    //         error: function(err){
 //    //         	console.log(err);
 //    //         }
 //    //     });
 //    $.ajax({
	// url: 'https://www51.e-goi.com/api/public/commons/ping',
	// contentType: 'application/json',
	// type: 'POST',
	// dataType: 'json',
	// data: JSON.stringify({
	// 	foo: "This text is left of",
	// 	bar: "this text..."
	// }),
	// success: function(data) {
	// 	var output = data.responseText;
	// 	console.log(output);
	// 	// ... do something useful
	// }
	// });
 //  		// Submit ajax form and treat answer.
	// });

});
<|endoftext|>


<commit_before>(function(globals){ // IIFE: Immediately Invoked Function Expression
})(window || module && module.exports || this);

(function(globals){ // IIFE: Immediately Invoked Function Expression
// Don't worry if that seems a little funky...

  /**
   * Internal representation of the game board in its current state.
   *
   * @see game.board
   * @see game.tracer
   * @see initial
   * @var {Array} of {Array} of {String|null}
   */
  var board = initial(); // initialize the `board`

  /**
   * List of moves for the "Catalan Opening: Closed Variation" suitable for use
   * as arguments to `applyMove` below.
   *
   * @see applyMove
   * @var {Array} of...?
   */
  var moves = [
    { from: { rank: 6, file: 3},
      to: { rank: 4, file: 3}
    },
    { from: { rank: 0, file: 6},
      to: { rank: 2, file: 5}
    }
    ]; // END moves

    // console.log(moves);
// [[6,3], [0,6], [6,2], [1,4], [6,6], [1,3], [7,5], [0,5], [7,6]],
// [[4,3], [2,5], [4,2], [2,4], [5,6], [3,3], [6,6], [1,4], [5,5]]
// var from = moves[0];
// var to = moves[1];
// console.log(from[[0]], to[[0]]);

  // var current = [[4,3], [2,5], [4,2], [2,4], [5,6], [3,3], [6,6], [1,4], [5,5]];

  // You don't need to understand `globals` yet...
  var game = (globals.game = {
    /**
     * Provide a _copy_ of the game board in order to update the View from it
     *
     * @return {Array} of {Array} of {String|null}
     */
    board: function(){
      return board.map(function(row){
        return row.slice();
      });
    },
    /**
     * Reset the internal game board to it's initial state.
     *
     * @return {Object} the game object for Method Chaining
     */
    reset: function(){
      board = initial();

      return this; // `this` referes to the object `reset` belongs to... AKA `game`
    },
    /**
     * Advance the internal game board to the next move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    next: function(){
      // Doesn't this seem to be missing something?
      return this;
    },
    /**
     * Advance the internal game board to the previous move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    prev: function(){
      // Another good place for code...
      return this;
    },
    /**
     * Advance the internal game board to the last move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    end: function(){
      // Write some code here...
      return this;
    },
    /**
     * Provide a printable representation of the game board for use as a tracer
     *
     * @return {String} representation of `board`
     * @todo Refactor to use Array methods?
     */
    tracer: function(){
      var bullet = '';

      for ( var rank = 0; rank < board.length; rank++ ){
        bullet += '|';
        for ( var file = 0; file < board[rank].length; file++ ){
          bullet += (board[rank][file] || ' ') + '|';
        }
        bullet += '\n';
      }

      return bullet;
    },
    /**
     * Apply a move to the game board, given a `from` and `to` position that both
     * contain values for `rank` and `file`.
     *
     * @param {Object} from with `rank` and `file`
     * @param {Object} to with `rank` and `file`
     * @return undefined
     *
     * @todo Fill me in! ...and remove this comment.
     */
    applyMove: function(from, to) {
      // TODO: Apply the move `from` and `to` to the `board`
      board[4][3] = board[6][3];
      board[6][3] = null;
      // moves[0].to = moves[0].from; // place we are moving `to` is assigned piece we are moving `from`
      // moves[0].from = null;
      // console.log(moves.join('\n'));

      // for (var i = 0; i < from.length; i++) {
      //   for (var j = 0; j < to.length; j++) {
      //     from[[i]] = to[[j]];
      //   }
      //   return to[[j]];
      // }
    } // END applyMove
  }); // END game
  console.log(game.tracer());

  // console.log(game.applyMove.to);
  // return board.join('\n' + '|');
// console.log(board.from[j]);
// for (var i = 0; i < to.length; i++){
//   board.to[i] = board.from;
//     for (var j = 0; j < from.length; j++) {
//       board.from[j] = ' ';
//         return board.join('\n');
//     }
//     console.log(board.from[j]);
// }
  /**
   * Provide the initial state of the game board, useful for any game.
   *
   * @return {Array} of {Array} of {String|null}
   */
  function initial(){
    return [
      [ 'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R' ],
      [ 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P' ],
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      [ 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p' ],
      [ 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r' ],
    ];
  } // END initial

// You are not expected to understand anything below this line...
})(window || module && module.exports || this);

// ([6][3], [4][3]),
// ([0][6], [2][5]),
// ([6][2], [4][2]),
// ([1][4], [2][4]),
// ([6][6], [5][6]),
// ([1][3], [3][3]),
// ([7][5], [6][6]),
// ([0][5], [1][4]),
// ([7][6], [5][5])
<commit_msg>added all moves to<commit_after>(function(globals){ // IIFE: Immediately Invoked Function Expression
})(window || module && module.exports || this);

(function(globals){ // IIFE: Immediately Invoked Function Expression
// Don't worry if that seems a little funky...

  /**
   * Internal representation of the game board in its current state.
   *
   * @see game.board
   * @see game.tracer
   * @see initial
   * @var {Array} of {Array} of {String|null}
   */
  var board = initial(); // initialize the `board`

  /**
   * List of moves for the "Catalan Opening: Closed Variation" suitable for use
   * as arguments to `applyMove` below.
   *
   * @see applyMove
   * @var {Array} of...?
   */
  var moves = [
    { from: { rank: 6, file: 3},
      to: { rank: 4, file: 3}
    },

    { from: { rank: 0, file: 6},
      to: { rank: 2, file: 5}
    },

    { from: { rank: 6, file: 2},
      to: { rank: 4, file: 2}
    },

    { from: { rank: 1, file: 4},
      to: { rank: 2, file: 4}
    },

    { from: { rank: 6, file: 6},
      to: { rank: 5, file: 6}
    },

    { from: { rank: 1, file: 3},
      to: { rank: 3, file: 3}
    },

    { from: { rank: 7, file: 5},
      to: { rank: 6, file: 6}
    },

    { from: { rank: 0, file: 5},
      to: { rank: 1, file: 4}
    },

    { from: { rank: 7, file: 6},
      to: { rank: 5, file: 5}
    }

    ]; // END moves

    // console.log(moves);
// [[6,3], [0,6], [6,2], [1,4], [6,6], [1,3], [7,5], [0,5], [7,6]],
// [[4,3], [2,5], [4,2], [2,4], [5,6], [3,3], [6,6], [1,4], [5,5]]
// var from = moves[0];
// var to = moves[1];
// console.log(from[[0]], to[[0]]);

  // var current = [[4,3], [2,5], [4,2], [2,4], [5,6], [3,3], [6,6], [1,4], [5,5]];

  // You don't need to understand `globals` yet...
  var game = (globals.game = {
    /**
     * Provide a _copy_ of the game board in order to update the View from it
     *
     * @return {Array} of {Array} of {String|null}
     */
    board: function(){
      return board.map(function(row){
        return row.slice();
      });
    },
    /**
     * Reset the internal game board to it's initial state.
     *
     * @return {Object} the game object for Method Chaining
     */
    reset: function(){
      board = initial();

      return this; // `this` referes to the object `reset` belongs to... AKA `game`
    },
    /**
     * Advance the internal game board to the next move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    next: function(){
      // Doesn't this seem to be missing something?
      return this;
    },
    /**
     * Advance the internal game board to the previous move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    prev: function(){
      // Another good place for code...
      return this;
    },
    /**
     * Advance the internal game board to the last move.
     *
     * @return {Object} the game object for Method Chaining
     * @todo Make this work!
     */
    end: function(){
      // Write some code here...
      return this;
    },
    /**
     * Provide a printable representation of the game board for use as a tracer
     *
     * @return {String} representation of `board`
     * @todo Refactor to use Array methods?
     */
    tracer: function(){
      var bullet = '';

      for ( var rank = 0; rank < board.length; rank++ ){
        bullet += '|';
        for ( var file = 0; file < board[rank].length; file++ ){
          bullet += (board[rank][file] || ' ') + '|';
        }
        bullet += '\n';
      }

      return bullet;
    },
    /**
     * Apply a move to the game board, given a `from` and `to` position that both
     * contain values for `rank` and `file`.
     *
     * @param {Object} from with `rank` and `file`
     * @param {Object} to with `rank` and `file`
     * @return undefined
     *
     * @todo Fill me in! ...and remove this comment.
     */
    applyMove: function(from, to) {
      // TODO: Apply the move `from` and `to` to the `board`
      board[4][3] = board[6][3];
      board[6][3] = null;
      // moves[0].to = moves[0].from; // place we are moving `to` is assigned piece we are moving `from`
      // moves[0].from = null;
      // console.log(moves.join('\n'));

      // for (var i = 0; i < from.length; i++) {
      //   for (var j = 0; j < to.length; j++) {
      //     from[[i]] = to[[j]];
      //   }
      //   return to[[j]];
      // }
    } // END applyMove
  }); // END game
  console.log(game.tracer());

  // console.log(game.applyMove.to);
  // return board.join('\n' + '|');
// console.log(board.from[j]);
// for (var i = 0; i < to.length; i++){
//   board.to[i] = board.from;
//     for (var j = 0; j < from.length; j++) {
//       board.from[j] = ' ';
//         return board.join('\n');
//     }
//     console.log(board.from[j]);
// }
  /**
   * Provide the initial state of the game board, useful for any game.
   *
   * @return {Array} of {Array} of {String|null}
   */
  function initial(){
    return [
      [ 'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R' ],
      [ 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P' ],
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      [ 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p' ],
      [ 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r' ],
    ];
  } // END initial

// You are not expected to understand anything below this line...
})(window || module && module.exports || this);

// ([6][3], [4][3]),
// ([0][6], [2][5]),
// ([6][2], [4][2]),
// ([1][4], [2][4]),
// ([6][6], [5][6]),
// ([1][3], [3][3]),
// ([7][5], [6][6]),
// ([0][5], [1][4]),
// ([7][6], [5][5])
<|endoftext|>


<commit_before>$(document).ready(function(){
    $("#podium_view").hide();
    $("#map_view").hide();

    $("#view1").click(function(){
        $("#classroom_view").show();
        $("#podium_view").hide();
        $("#map_view").hide();
        $("#photo_viewer h2").show();
    });
    $("#view2").click(function(){
      $("#classroom_view").hide();
      $("#podium_view").show();
      $("#map_view").hide();
      $("#photo_viewer h2").show();
    });
    $("#view3").click(function(){
      $("#classroom_view").hide();
      $("#podium_view").hide();
      $("#map_view").show();
      $("#photo_viewer h2").hide();
    });

    $(".map-container")
	.click(function(){
			$(this).find("iframe").addClass("clicked")})
	.mouseleave(function(){
			$(this).find("iframe").removeClass("clicked")});

});

if (Modernizr.deviceorienation) {
    alert("This browser supports device orientation");
  }
<commit_msg>fixes, typos<commit_after>$(document).ready(function(){
    $("#podium_view").hide();
    $("#map_view").hide();

    $("#view1").click(function(){
        $("#classroom_view").show();
        $("#podium_view").hide();
        $("#map_view").hide();
        $("#photo_viewer h2").show();
    });
    $("#view2").click(function(){
      $("#classroom_view").hide();
      $("#podium_view").show();
      $("#map_view").hide();
      $("#photo_viewer h2").show();
    });
    $("#view3").click(function(){
      $("#classroom_view").hide();
      $("#podium_view").hide();
      $("#map_view").show();
      $("#photo_viewer h2").hide();
    });

    $(".map-container")
	.click(function(){
			$(this).find("iframe").addClass("clicked")})
	.mouseleave(function(){
			$(this).find("iframe").removeClass("clicked")});

});

if (Modernizr.deviceorientation) {
    $("#photo_viewer h2").addClass("hidden");
  }
<|endoftext|>


<commit_before><commit_msg>Moved code from index.html to here<commit_after>$(document).ready(function(){
    var me = mips_emulator();
    console.log("Editor value: "+$("#editor").val());
    var editor = CodeMirror.fromTextArea(
        document.getElementById("editor"),{
          lineNumbers: true,
          mode: "text/css",
          matchBrackets: true,
      //viewportMargin: 'Infinity'
    });
    editor.on('blur', function(){
        alert('Analyzing code');
        me.setCode($("#editor").val());
    });
    $("#step").click(function(){
      // TODO: hook this up to a mips engine
      alert("Step through function here");
    });
    $("#run").click(function(){
      // TODO: hook this up to a mips engine
      alert("Run Fucntion here");
    });
});<|endoftext|>


<commit_before>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html);
	  pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');

        // Switch out .svg for .png for  elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        $('div.is-sortable').sortable({
             placeholder: "form__group is-sorting",
             helper: "clone",
             opacity: 0.9,
             start: function(e, ui) {
                $(ui.helper).addClass('is-dragging');
            }
        }).disableSelection();

        var fixHelper = function(e, ui) {
            ui.children().each(function() {
                $(this).width($(this).width());
            });
            return ui;
        };

        $('.table.is-sortable tbody').sortable({
            placeholder: "is-sorting",
            helper: fixHelper,
            opacity: 0.9,
            create: function() {
                $(this).find('tr > td:first-of-type').each(function(i) {
                    var $this = $(this),
                        label = $(this).text();

                    i++;

                    $this.html('' + i + ' ' + label);
                });
            },
            start: function(e, ui) {
                $(ui.helper).addClass('is-dragging');
            },
            update: function(e, ui) {
                var $item = $(ui.item);

                $item.addClass('has-success fade', function() {
                    setTimeout(function() {
                        $item.removeClass('has-success fade');
                    }, 2500);
                });

                $(this).find('.js-sortable-count').each(function(i) {

                    console.log($(this).text());

                    var $this = $(this);

                    i++;

                    $this.text(i);
                });

            }
        }).disableSelection();

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });
    });

}(jQuery));
<commit_msg>Fix Spacing in main.js declaration<commit_after>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html);
	pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');

        // Switch out .svg for .png for  elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        $('div.is-sortable').sortable({
             placeholder: "form__group is-sorting",
             helper: "clone",
             opacity: 0.9,
             start: function(e, ui) {
                $(ui.helper).addClass('is-dragging');
            }
        }).disableSelection();

        var fixHelper = function(e, ui) {
            ui.children().each(function() {
                $(this).width($(this).width());
            });
            return ui;
        };

        $('.table.is-sortable tbody').sortable({
            placeholder: "is-sorting",
            helper: fixHelper,
            opacity: 0.9,
            create: function() {
                $(this).find('tr > td:first-of-type').each(function(i) {
                    var $this = $(this),
                        label = $(this).text();

                    i++;

                    $this.html('' + i + ' ' + label);
                });
            },
            start: function(e, ui) {
                $(ui.helper).addClass('is-dragging');
            },
            update: function(e, ui) {
                var $item = $(ui.item);

                $item.addClass('has-success fade', function() {
                    setTimeout(function() {
                        $item.removeClass('has-success fade');
                    }, 2500);
                });

                $(this).find('.js-sortable-count').each(function(i) {

                    console.log($(this).text());

                    var $this = $(this);

                    i++;

                    $this.text(i);
                });

            }
        }).disableSelection();

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });
    });

}(jQuery));
<|endoftext|>


<commit_before>var ParaparaCanvas = require("./parapara-canvas");
var Frame = require("./frame");
var FramesController = require("./frames-controller");
var drawTools = require("./draw-tools");
var Menu = require("./menu");

var frameServer;
var colorPicker, lineWidthPicker;
var menu;
document.addEventListener("DOMContentLoaded", function() {
  frameServer = new FramesController(document.getElementById("frames"));
  frameServer.append(0, new Frame(new ParaparaCanvas(0, frameServer.element)));
  setListenerForCanvas(0);
  frameServer.setCurrentFrame(0);

  colorPicker = new drawTools.ColorPicker(document.getElementById("menu-colors"), "red");
  lineWidthPicker = new drawTools.LineWidthPicker(document.getElementById("menu-line-width"), 10);
  menu = new Menu();

  document.getElementById("menu-side-btn").addEventListener("click", function() {
    menu.toggleMenu();
  });
});

function setListenerForCanvas(frameId) {
  var pCanvas = frameServer.getCanvasElementByFrameId(frameId);
  pCanvas.addEventListener("mousedown", mouseDownCanvas);
  pCanvas.addEventListener("mouseup", mouseUpCanvas);
  pCanvas.addEventListener("mousemove", mouseMoveCanvas);
}
// TODO: これらは、ここで、いいのか。
// → parapara-canvas.js に取り込むような気もするが、
//   この情報をWebsocket で送ったり・・となるのであれば、
//   それを parapara-canvas.js でやっていいの？となる。
var isMouseDown = false;
var beforeMousePosition = {};
function mouseDownCanvas(event) {
  menu.hideMenu();
  menu.toggleOpenMenuButton(false);
  isMouseDown = true;
  beforeMousePosition = {x: event.clientX, y: event.clientY};
}
function mouseUpCanvas() {
  menu.toggleOpenMenuButton(true);
  isMouseDown = false;
}
function mouseMoveCanvas(event) {
  if (isMouseDown) {
    if (colorPicker.color === "white") {
      frameServer.frames[frameServer.currentFrameId].paraparaCanvas.eraseByLine(
        beforeMousePosition,
        {x: event.clientX, y: event.clientY},
        lineWidthPicker.lineWidth
      );
    } else {
      frameServer.frames[frameServer.currentFrameId].paraparaCanvas.drawLine(
        beforeMousePosition,
        {x: event.clientX, y: event.clientY},
        colorPicker.color,
        lineWidthPicker.lineWidth
      );
    }
    beforeMousePosition = {x: event.clientX, y: event.clientY};
  }
}<commit_msg>main.js framesController 変数の直し忘れを修正<commit_after>var ParaparaCanvas = require("./parapara-canvas");
var Frame = require("./frame");
var FramesController = require("./frames-controller");
var drawTools = require("./draw-tools");
var Menu = require("./menu");

var framesController;
var colorPicker, lineWidthPicker;
var menu;
document.addEventListener("DOMContentLoaded", function() {
  framesController = new FramesController(document.getElementById("frames"));
  framesController.append(0, new Frame(new ParaparaCanvas(0, framesController.element)));
  setListenerForCanvas(0);
  framesController.setCurrentFrame(0);

  colorPicker = new drawTools.ColorPicker(document.getElementById("menu-colors"), "red");
  lineWidthPicker = new drawTools.LineWidthPicker(document.getElementById("menu-line-width"), 10);
  menu = new Menu();

  document.getElementById("menu-side-btn").addEventListener("click", function() {
    menu.toggleMenu();
  });
});

function setListenerForCanvas(frameId) {
  var pCanvas = framesController.getCanvasElementByFrameId(frameId);
  pCanvas.addEventListener("mousedown", mouseDownCanvas);
  pCanvas.addEventListener("mouseup", mouseUpCanvas);
  pCanvas.addEventListener("mousemove", mouseMoveCanvas);
}
// TODO: これらは、ここで、いいのか。
// → parapara-canvas.js に取り込むような気もするが、
//   この情報をWebsocket で送ったり・・となるのであれば、
//   それを parapara-canvas.js でやっていいの？となる。
var isMouseDown = false;
var beforeMousePosition = {};
function mouseDownCanvas(event) {
  menu.hideMenu();
  menu.toggleOpenMenuButton(false);
  isMouseDown = true;
  beforeMousePosition = {x: event.clientX, y: event.clientY};
}
function mouseUpCanvas() {
  menu.toggleOpenMenuButton(true);
  isMouseDown = false;
}
function mouseMoveCanvas(event) {
  if (isMouseDown) {
    if (colorPicker.color === "white") {
      framesController.frames[framesController.currentFrameId].paraparaCanvas.eraseByLine(
        beforeMousePosition,
        {x: event.clientX, y: event.clientY},
        lineWidthPicker.lineWidth
      );
    } else {
      framesController.frames[framesController.currentFrameId].paraparaCanvas.drawLine(
        beforeMousePosition,
        {x: event.clientX, y: event.clientY},
        colorPicker.color,
        lineWidthPicker.lineWidth
      );
    }
    beforeMousePosition = {x: event.clientX, y: event.clientY};
  }
}<|endoftext|>