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

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

(function () {

	Logo = {
	};

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

	Logo.queryObj = new queryObj();

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

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

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

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

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

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

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

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

	Logo.kinetic.stripes = new Array();

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

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

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

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

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

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl,scp) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log(dataUrl)
				$('#logo').css("display", "none");
				$('body').append(pngLogo);
			}
		}
	});

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

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

(function () {

	Logo = {
	};

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

	Logo.queryObj = new queryObj();

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

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

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

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

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

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

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

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

	Logo.kinetic.stripes = new Array();

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

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

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

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

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

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl,scp) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log(dataUrl)
				$('#logo').css("display", "none");
				$('body').append(pngLogo);
			}
		}
	});

})();<|endoftext|>


<commit_before>// Snap SVG code

window.onload = function () {
  // wrap svg on page with Snap
  var share = Snap('#share');

  // load svg file
  Snap.load("img/animated-share.svg", function (s) {
    // now save some vector groups into variables
    var speech = s.select('#speech'),
        phone = s.select('#phone'),
        submit = s.select('#submit'),
        text = s.select('#text');

    // add speech bubble and text to share svg
    share.append(speech);
    share.append(text);

    //animate the speech bubble pointer
    var pointer = speech.select('#pointer');
    pointer.animate({
      transform: "t100,0"
    }, 600, mina.backin);
  });
}
<commit_msg>fixed transform values<commit_after>// Snap SVG code

window.onload = function () {
  // wrap svg on page with Snap
  var share = Snap('#share');

  // load svg file
  Snap.load("img/animated-share.svg", function (s) {
    // now save some vector groups into variables
    var speech = s.select('#speech'),
        phone = s.select('#phone'),
        submit = s.select('#submit'),
        text = s.select('#text');

    // add speech bubble and text to share svg
    share.append(speech);
    share.append(text);

    //animate the speech bubble pointer
    var pointer = speech.select('#pointer');
    pointer.animate({
      transform: "t50,0"
    }, 500, mina.backin);
  });
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
$(document).ready(function() {
///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
  var twitchUserName = ['DarkAcreJack','sideshowmatt','blackdynamitetv','johanmoney','sblindside','frogsama','vvarrentv',"thenutzxd",'jamaica105','michiganspartan','ritterriffic','kazzandrah','vexnextv','stonertrixx'];

///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////

  //Iterate through the array of usernames and call getTwitch
  twitchUserName.forEach(function(name) {
    getTwitch(name)
  });
///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
  //Activate Nav Pills
  $(".selector").click(function() {
		var status = $(this).attr('id');
		if (status === "all-streams") {
			$(".online, .offline").show();
      $("#all-streams").addClass("active");
      $("#online, #offline").removeClass("active");
		} else if (status === "online") {
			$(".online").show();
			$(".offline").hide();
      $("#online").addClass("active");
      $("#all-streams, #offline").removeClass("active");
		} else {
			$(".offline").show();
			$(".online").hide();
      $("#offline").addClass("active");
      $("#all-streams, #online").removeClass("active");
		}
	});

});

//GET TWITCH API INFO
  function getTwitch(twitchUserName){
    $.ajax({
      type:"GET",
      url:"https://api.twitch.tv/kraken/streams/" + twitchUserName,
      headers:{
        'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
      success: function twitchData(data) {
        // Call 'streams' and if the channel is active, get stream data
        if(data.stream !== null){

          var streamImage = data.stream.preview.large;
          var streamGame = data.stream.game;
          var streamInfo = data.stream.channel.status;
          var streamLogo = data.stream.channel.logo;
          var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
          var defaultImage = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
          var streamCard=" ";

          //IF EVERYTHING IS A SUCCESS IT BUILDS A STREAMCARD//
            if (streamLogo !== null){
              streamCard = "
" + "
" + "ONLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

" + streamGame.toUpperCase() + ": " + streamInfo.toUpperCase() + "

";
              $(".card-container").append(streamCard);
            }else{
              streamCard = "
" + "
" + "ONLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

" + streamGame.toUpperCase() + ": " + streamInfo.toUpperCase() + "

";
              $(".card-container").append(streamCard);
            }

       } else {
          // If the channel is offline, get channel data
          $.ajax({
            type:"GET",
            url:"https://api.twitch.tv/kraken/channels/" + twitchUserName,
            headers:{
              'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
            success: function(data){
              var streamBanner = data.video_banner;
              var streamLogo = data.logo;
              var streamError = data.status;
              var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
              var streamCard = " ";

              //IF THERE IS NO CHANNEL INFO
              if (streamError == 404 || streamBanner == null || streamLogo == null){
                $.ajax({
                  type:"GET",
                  url:"https://api.twitch.tv/kraken/users/" + twitchUserName,
                  headers:{
                    'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
                  success: function(data){
                    var streamMessage = data.error;
                    // var streamBanner = data.video_banner;
                    var defaultImage = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
                    var defaultThumb = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
                    //IF ACCOUNT HAS BEEN CLOSED BUILD STREAMCARD
                    if(streamMessage == "Unprocessable Entity"){
                      streamCard = "
" + "
" + "OFFLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

This Twitch account has been closed.

";
                      $(".card-container").append(streamCard);
		                } else if (streamMessage == "Not Found"){
                        //IF IT NEVER EXISTED
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

This Twitch account never existed.

";
                        $(".card-container").append(streamCard);
                    }else if (streamBanner == null && streamLogo == null){
                        //IF Banner AND  Logo don't Work
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                        $(".card-container").append(streamCard);
                    }
                    else if (streamBanner == null){
                        //IF Banner Doesn't Exist
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                        $(".card-container").append(streamCard);
                    }
                  }
                })
              } else { // If account exists, but user is not currently streaming, build streamCard

                streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                $(".card-container").append(streamCard);
              }
            }
          })
        }
      }
    })

  }
<commit_msg>Update main.js<commit_after>///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
$(document).ready(function() {
///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
  var twitchUserName = ['DarkAcreJack','sideshowmatt','blackdynamitetv','johanmoney','sblindside','frogsama','vvarrentv',"thenutzxd",'jamaica105','michiganspartan','ritterriffic','kazzandrah','vexnextv','stonertrixx'];

///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////

  //Iterate through the array of usernames and call getTwitch
  twitchUserName.forEach(function(name) {
    getTwitch(name)
  });
///////////////////////////////////////////////////
///////////////////////////////////////////////////
///////////////////////////////////////////////////
  //Activate Nav Pills
  $(".selector").click(function() {
		var status = $(this).attr('id');
		if (status === "all-streams") {
			$(".online, .offline").show();
      $("#all-streams").addClass("active");
      $("#online, #offline").removeClass("active");
		} else if (status === "online") {
			$(".online").show();
			$(".offline").hide();
      $("#online").addClass("active");
      $("#all-streams, #offline").removeClass("active");
		} else {
			$(".offline").show();
			$(".online").hide();
      $("#offline").addClass("active");
      $("#all-streams, #online").removeClass("active");
		}
	});

});

//GET TWITCH API INFO
  function getTwitch(twitchUserName){
    $.ajax({
      type:"GET",
      url:"https://api.twitch.tv/kraken/streams/" + twitchUserName,
      headers:{
        'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
      success: function twitchData(data) {
        // Call 'streams' and if the channel is active, get stream data
        if(data.stream !== null){

          var streamImage = data.stream.preview.large;
          var streamGame = data.stream.game;
          var streamInfo = data.stream.channel.status;
          var streamLogo = data.stream.channel.logo;
          var sreamEmbed = ''
          var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
          var defaultImage = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
          var streamCard=" ";

          //IF EVERYTHING IS A SUCCESS IT BUILDS A STREAMCARD//
            // if (streamLogo !== null){
              streamCard = "
" + "
" + " ONLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

" + streamGame.toUpperCase() + ": " + streamInfo.toUpperCase() + "

";
              $(".card-container").append(streamCard);
            // }else{
            //   streamCard = "
" + "
" + "ONLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

" + streamGame.toUpperCase() + ": " + streamInfo.toUpperCase() + "

";
            //   $(".card-container").append(streamCard);
            // }

       } else {
          // If the channel is offline, get channel data
          $.ajax({
            type:"GET",
            url:"https://api.twitch.tv/kraken/channels/" + twitchUserName,
            headers:{
              'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
            success: function(data){
              var streamBanner = data.video_banner;
              var streamLogo = data.logo;
              var streamError = data.status;
              var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
              var streamCard = " ";

              //IF THERE IS NO CHANNEL INFO
              if (streamError == 404 || streamBanner == null || streamLogo == null){
                $.ajax({
                  type:"GET",
                  url:"https://api.twitch.tv/kraken/users/" + twitchUserName,
                  headers:{
                    'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
                  success: function(data){
                    var streamMessage = data.error;
                    // var streamBanner = data.video_banner;
                    var defaultImage = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
                    var defaultThumb = "https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif";
                    //IF ACCOUNT HAS BEEN CLOSED BUILD STREAMCARD
                    if(streamMessage == "Unprocessable Entity"){
                      streamCard = "
" + "
" + "OFFLINE" + "
" + "" + '
' + "
" + "
" + twitchUserName.toUpperCase() + "

This Twitch account has been closed.

";
                      $(".card-container").append(streamCard);
		                } else if (streamMessage == "Not Found"){
                        //IF IT NEVER EXISTED
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

This Twitch account never existed.

";
                        $(".card-container").append(streamCard);
                    }else if (streamBanner == null && streamLogo == null){
                        //IF Banner AND  Logo don't Work
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                        $(".card-container").append(streamCard);
                    }
                    else if (streamBanner == null){
                        //IF Banner Doesn't Exist
                        streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                        $(".card-container").append(streamCard);
                    }
                  }
                })
              } else { // If account exists, but user is not currently streaming, build streamCard

                streamCard = "
" + "
" + "OFFLINE" + "
" + ""+ '
' + "
" + "
" + twitchUserName.toUpperCase() + "

Not currently streaming.

";
                $(".card-container").append(streamCard);
              }
            }
          })
        }
      }
    })

  }
<|endoftext|>


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

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

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

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

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

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

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

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

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

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

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

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

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

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

  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    } else {
      $('#windows-software-download-link').attr("href", "https://s3-us-west-2.amazonaws.com/q-desktop/2.0.1/Das-Keyboard-Q-ia32-Setup-2.0.1.exe");
      $('#windows-software-download-link').append(" 32 bit");

    }
  }
}

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

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

  formatJSONCode();
  loadDownloadLinkDependingOnOsArchitechture();

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

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

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<commit_msg>Commented change of download link depending on architecture<commit_after>function redirectToHomePage() {
  window.location.pathname = 'index';
}

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

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

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

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

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

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

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

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

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

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

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

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

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

  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    } else {
      $('#windows-software-download-link').attr("href", "https://s3-us-west-2.amazonaws.com/q-desktop/2.0.1/Das-Keyboard-Q-ia32-Setup-2.0.1.exe");
      $('#windows-software-download-link').append(" 32 bit");

    }
  }
}

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

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

  formatJSONCode();
 // loadDownloadLinkDependingOnOsArchitechture();

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

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

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


<commit_before>var game;
var started = false;
function startGame(){
	if(!started){
		changePhaseTo('gameplay');
		game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
		started = true;
	}
}

function changePhaseTo(id, payload){

	if (id === 'end') {
		var name = payload.name;
		document.getElementById('end').innerHTML  = ' ';
		document.getElementById('game').remove();
	} else if (id === 'gameplay'){
		document.getElementById('menu').remove();
	}

}

function Opponent () {

	var randomUpTo = function(higherBound){
		return Math.random() * higherBound;
	}

	var x = randomUpTo(game.world.width);
	var y = randomUpTo(game.world.height);
	this.value = game.add.sprite(x, y, 'enemy1');

	var value = this.value;

	game.physics.arcade.enable(value);
	value.body.collideWorldBounds = true;

	value.animations.add('left', [0, 1, 2, 3], 10, true);
	value.animations.add('right', [0, 1, 2, 3], 10, true);

	this.value.body.velocity.x = randomUpTo(400);
	this.value.body.velocity.y = randomUpTo(400);

	var bounceRate = 0.95;
	this.value.body.bounce.y = bounceRate;
	this.value.body.bounce.x = bounceRate;

	this.value._obj = this;
}

Opponent.prototype.move = function() {
	this.value.animations.play('left');
};

function preload() {

	game.load.image('background1', 'assets/background_layout_stars_one.png');
	game.load.image('background2', 'assets/background_layout_stars_two.png');
	game.load.image('background3', 'assets/background_layout_stars_three.png');
	game.load.image('ground', 'assets/platform.png');
	game.load.image('ground2', 'assets/ground.png');
	game.load.image('star', 'assets/star.png');
	game.load.image('moon', 'assets/moon.png');
	game.load.spritesheet('blueplayer', 'assets/blueplayer_16.png', 64, 32);
	game.load.spritesheet('redplayer', 'assets/redplayer_16.png', 64, 32);
	game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
	game.load.spritesheet('enemy1', 'assets/enemy3.png', 32, 32);
	game.load.audio('music', ['assets/music.mp3', 'assets/music.ogg']);
	game.load.audio('chachacha', ['assets/chachacha.mp3', 'assets/chachacha.ogg']);

}

function Score(x, y, name){
	this.value = 0;
	this.text = "";
	this.name = name;
	this.at(x,y);
}

function getQueryParams(qs) {
	qs = qs.split('+').join(' ');

	var params = {},
	tokens,
	re = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	}

	return params;
}

var winningScore = getQueryParams(document.location.search)["score"] || 500;

Score.prototype.increase = function() {
	this.value += 10;
	this.scoreText.text = this.show(this.value);
	if(this.value >= winningScore){
		throw Won();
	}
};

Score.prototype.decrease = function() {
	this.value -= 3;
	this.scoreText.text = this.show(this.value);
};

Score.prototype.show = function(score) {
	return this.name + '\'s score: ' + score;
};

Score.prototype.at = function(x, y) {
	this.scoreText = game.add.text(x, y, this.show(0), { fontSize: '32px', fill: '#fff' });
};

var players;
var cursors;
var blueplayer;
var redplayer;
var opponents;
var stars;
var scores;
var music;
var chachacha;

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	music = game.sound.play('music');
	background1 = game.add.sprite(0, 0, 'background1');
	background2 = game.add.sprite(0, 0, 'background2');
	background3 = game.add.sprite(0, 0, 'background3');
	background4 = game.add.sprite(game.width, 0, 'background1');
	background5 = game.add.sprite(game.width, 0, 'background2');
	background6 = game.add.sprite(game.width, 0, 'background3');
	moon = game.add.sprite(1000, 500, 'moon');
	ground2 = game.add.sprite(0,game.world.height-64, 'ground2');
	ground3 = game.add.sprite(1600,game.world.height-64, 'ground2');

	scores = createScores();
	cursors = createControls();
	players = createPlayers(cursors, scores);
	opponents= createOpponents();
	stars = createStars();

}

function createScores () {
	return {
		player1: new Score(16, 16, 'red'),
		player2: new Score(550, 16, 'blue')
	};
}

function createPlayers(cursors, scores){
	var players = [];

	{
		var player = new Player('redplayer', 32, game.height - 150, game);
		player.setCursor(cursors.arrows);
		player.setScore(scores.player1);
		players.push(player);
	}

	{
		var player = new Player('blueplayer', 32, 150, game);
		player.setCursor(cursors.wasd);
		player.setScore(scores.player2);
		players.push(player);
	}
	return players;
}

function createOpponents(){
	var opponents = game.add.group();
	var numberOfOpponents = 7;
	opponents.enableBody = true;
	for (var i = 0; i < numberOfOpponents; i++) {
		opponents.add(new Opponent().value);
	}
	return opponents;
}

function createStars(){
	var stars = game.add.group();
	var numberOfStars = 30;
	stars.enableBody = true;

	for (var i = 0; i < numberOfStars; i++) {
		createStar(stars);
	}

	return stars;
}

function createStar(stars){
	var star = stars.create(Math.random()*game.width, Math.random()*game.height, 'star');
	star.body.bounce.y = 0.7 + Math.random() * 0.2;
}

function createControls(){
	return {
		arrows: game.input.keyboard.createCursorKeys(),
		wasd: {
			up: game.input.keyboard.addKey(Phaser.Keyboard.W),
			down: game.input.keyboard.addKey(Phaser.Keyboard.S),
			left: game.input.keyboard.addKey(Phaser.Keyboard.A),
			right: game.input.keyboard.addKey(Phaser.Keyboard.D)
		}
	};
}

function update() {
	moveBackground(background1, 1);
	moveBackground(background2, 2);
	moveBackground(background3, 3);
	moveBackground(background6, 3);
	moveBackground(background4, 1);
	moveBackground(background5, 2);
	moveGround(ground2, 1);
	moveGround(ground3, 1);
	moonspawn(moon, 3)

	manage_collisions (game);
	players.forEach(function(player){
		player.move();
	});
}
var moonspawn = function(background, speed) {
	moveBackground(moon, speed);
	if(background.x < -300) {
		background.x = game.rnd.integerInRange(3000, 6000);
		background.y = game.rnd.integerInRange(-100, 500);
	}

}

var moveBackground = function(background, speed) {
	if (background.x < -game.width) {
		background.x = game.width;
	}
	background.x -= speed
}

var moveGround = function(ground, speed){
	var treshold = 2*game.width;
	if (ground.x < -treshold) {
		ground.x = treshold;
	}
	ground.x -= speed;
}

function manage_collisions (game) {
	players.forEach(function(player){
		player.canCollect(stars);
		player.canCollideWith(opponents);
	})
}<commit_msg>whitespace<commit_after>var game;
var started = false;
function startGame(){
	if(!started){
		changePhaseTo('gameplay');
		game = new Phaser.Game(800, 600, Phaser.AUTO, 'game',
			{ preload: preload,
			  create: create,
			  update: update
		 	});
		started = true;
	}
}

function changePhaseTo(id, payload){

	if (id === 'end') {
		var name = payload.name;
		document.getElementById('end').innerHTML  = ' ';
		document.getElementById('game').remove();
	} else if (id === 'gameplay'){
		document.getElementById('menu').remove();
	}

}

function Opponent () {

	var randomUpTo = function(higherBound){
		return Math.random() * higherBound;
	}

	var x = randomUpTo(game.world.width);
	var y = randomUpTo(game.world.height);
	this.value = game.add.sprite(x, y, 'enemy1');

	var value = this.value;

	game.physics.arcade.enable(value);
	value.body.collideWorldBounds = true;

	value.animations.add('left', [0, 1, 2, 3], 10, true);
	value.animations.add('right', [0, 1, 2, 3], 10, true);

	this.value.body.velocity.x = randomUpTo(400);
	this.value.body.velocity.y = randomUpTo(400);

	var bounceRate = 0.95;
	this.value.body.bounce.y = bounceRate;
	this.value.body.bounce.x = bounceRate;

	this.value._obj = this;
}

Opponent.prototype.move = function() {
	this.value.animations.play('left');
};

function preload() {

	game.load.image('background1', 'assets/background_layout_stars_one.png');
	game.load.image('background2', 'assets/background_layout_stars_two.png');
	game.load.image('background3', 'assets/background_layout_stars_three.png');
	game.load.image('ground', 'assets/platform.png');
	game.load.image('ground2', 'assets/ground.png');
	game.load.image('star', 'assets/star.png');
	game.load.image('moon', 'assets/moon.png');
	game.load.spritesheet('blueplayer', 'assets/blueplayer_16.png', 64, 32);
	game.load.spritesheet('redplayer', 'assets/redplayer_16.png', 64, 32);
	game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
	game.load.spritesheet('enemy1', 'assets/enemy3.png', 32, 32);
	game.load.audio('music', ['assets/music.mp3', 'assets/music.ogg']);
	game.load.audio('chachacha', ['assets/chachacha.mp3', 'assets/chachacha.ogg']);

}

function Score(x, y, name){
	this.value = 0;
	this.text = "";
	this.name = name;
	this.at(x,y);
}

function getQueryParams(qs) {
	qs = qs.split('+').join(' ');

	var params = {},
	tokens,
	re = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	}

	return params;
}

var winningScore = getQueryParams(document.location.search)["score"] || 500;

Score.prototype.increase = function() {
	this.value += 10;
	this.scoreText.text = this.show(this.value);
	if(this.value >= winningScore){
		throw Won();
	}
};

Score.prototype.decrease = function() {
	this.value -= 3;
	this.scoreText.text = this.show(this.value);
};

Score.prototype.show = function(score) {
	return this.name + '\'s score: ' + score;
};

Score.prototype.at = function(x, y) {
	this.scoreText = game.add.text(x, y, this.show(0), { fontSize: '32px', fill: '#fff' });
};

var players;
var cursors;
var blueplayer;
var redplayer;
var opponents;
var stars;
var scores;
var music;
var chachacha;

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	music = game.sound.play('music');
	background1 = game.add.sprite(0, 0, 'background1');
	background2 = game.add.sprite(0, 0, 'background2');
	background3 = game.add.sprite(0, 0, 'background3');
	background4 = game.add.sprite(game.width, 0, 'background1');
	background5 = game.add.sprite(game.width, 0, 'background2');
	background6 = game.add.sprite(game.width, 0, 'background3');
	moon = game.add.sprite(1000, 500, 'moon');
	ground2 = game.add.sprite(0,game.world.height-64, 'ground2');
	ground3 = game.add.sprite(1600,game.world.height-64, 'ground2');

	scores = createScores();
	cursors = createControls();
	players = createPlayers(cursors, scores);
	opponents= createOpponents();
	stars = createStars();

}

function createScores () {
	return {
		player1: new Score(16, 16, 'red'),
		player2: new Score(550, 16, 'blue')
	};
}

function createPlayers(cursors, scores){
	var players = [];

	{
		var player = new Player('redplayer', 32, game.height - 150, game);
		player.setCursor(cursors.arrows);
		player.setScore(scores.player1);
		players.push(player);
	}

	{
		var player = new Player('blueplayer', 32, 150, game);
		player.setCursor(cursors.wasd);
		player.setScore(scores.player2);
		players.push(player);
	}
	return players;
}

function createOpponents(){
	var opponents = game.add.group();
	var numberOfOpponents = 7;
	opponents.enableBody = true;
	for (var i = 0; i < numberOfOpponents; i++) {
		opponents.add(new Opponent().value);
	}
	return opponents;
}

function createStars(){
	var stars = game.add.group();
	var numberOfStars = 30;
	stars.enableBody = true;

	for (var i = 0; i < numberOfStars; i++) {
		createStar(stars);
	}

	return stars;
}

function createStar(stars){
	var star = stars.create(Math.random()*game.width, Math.random()*game.height, 'star');
	star.body.bounce.y = 0.7 + Math.random() * 0.2;
}

function createControls(){
	return {
		arrows: game.input.keyboard.createCursorKeys(),
		wasd: {
			up: game.input.keyboard.addKey(Phaser.Keyboard.W),
			down: game.input.keyboard.addKey(Phaser.Keyboard.S),
			left: game.input.keyboard.addKey(Phaser.Keyboard.A),
			right: game.input.keyboard.addKey(Phaser.Keyboard.D)
		}
	};
}

function update() {
	moveBackground(background1, 1);
	moveBackground(background2, 2);
	moveBackground(background3, 3);
	moveBackground(background6, 3);
	moveBackground(background4, 1);
	moveBackground(background5, 2);
	moveGround(ground2, 1);
	moveGround(ground3, 1);
	moonspawn(moon, 3)

	manage_collisions (game);
	players.forEach(function(player){
		player.move();
	});
}
var moonspawn = function(background, speed) {
	moveBackground(moon, speed);
	if(background.x < -300) {
		background.x = game.rnd.integerInRange(3000, 6000);
		background.y = game.rnd.integerInRange(-100, 500);
	}

}

var moveBackground = function(background, speed) {
	if (background.x < -game.width) {
		background.x = game.width;
	}
	background.x -= speed
}

var moveGround = function(ground, speed){
	var treshold = 2*game.width;
	if (ground.x < -treshold) {
		ground.x = treshold;
	}
	ground.x -= speed;
}

function manage_collisions (game) {
	players.forEach(function(player){
		player.canCollect(stars);
		player.canCollideWith(opponents);
	})
}<|endoftext|>


<commit_before>constants = {
    workdays_per_week : 5,
    weeks_per_month : 4.33,
    workdays_per_month : 5 * 4.33,
    days_per_month : 30,
    sanitation_threshold : 500,
    violence_threshold : 900,
    transition_time : 200,
    output_low : 75,     // below this figure salary is too low
    output_almost : 90  // below this figure salary is almost enough
}

function to_rands(val) {
    return "R" + val;
}

function calculate_transport(household_size) {
    var trans_cost = $("#transport-cost").val();
    var trans_direction = $("#transport-direction").val();
    if (trans_direction == "oneway")
        var out = Math.round(2 * trans_cost * constants.workdays_per_month);
    else
        var out = Math.round(trans_cost * constants.workdays_per_month);

    $("#transport-total").html(to_rands(out));

    return out
}

function calculate_food(household_size) {
    var food_cost = $("#food-cost").val();
    // Account for nutrition programme. Effectively kids do not need 1 meal 5 days a week IF education is provided. 16/21*850 for kids
    // Suggests that this program covers at least 30% of daily requirements of the students - Department of Education
    var out = Math.round(food_cost * household_size * constants.days_per_month);

    $("#food-total").html(to_rands(out));

    return out
}

function calculate_rent(household_size) {
    var rent_cost = $("#rent-cost").val();
    var sanitation_comment = ""
    var violence_comment = ""
    var out = Math.round(rent_cost)

    //Need comments on sanitation and violence to update with rent options.
    if (rent_cost > 0 && rent_cost < constants.sanitation_threshold)
        sanitation_comment = "Low functionality of bathrooms. High likelihood of communal bathroom. Low likelihood of reliable trash collection."
    else
        sanitation_comment = "Personal bathroom facilities. Reliable trash collection"

    if (rent_cost > 0 && rent_cost < constants.violence_threshold)
        violence_comment = "High likelihood of experiencing gang violence and burglaries."
    else
        violence_comment = "Much lower likelihood of experiencing violence."

    $("#rent-total").html(to_rands(out));

    return out
}

function calculate_education(household_size) {
    var kids = $("#education-kids").val()
    var education_cost = $("#education-cost").val()
    var out = education_cost * (kids);

    $("#education-total").html(to_rands(out));

    return out
}

function calculate_health(household_size) {

    var health_cost = $("#health-cost").val();
    var out = health_cost * household_size;
    var health_comment = ""

    $("#health-total").html(to_rands(out))

    return out
}

function calculate_communication(household_size) {
    var communication_cost = $("#communication-cost").val();
    var out = communication_cost * household_size

    $("#communication-total").html(to_rands(out))

    return out
}

function calculate_recreation(household_size) {
    var recreation_cost = $("#recreation-cost").val();
    var out = recreation_cost * household_size;

    $("#recreation-total").html(to_rands(out))

    return out
}

function calculate_other(household_size) {
    var out = $("#other-cost").val() * household_size;

    $("#other-total").html(to_rands(out))

    return out
}

function calculate_expenditure(household_size) {
    var total = 0;

    total += calculate_rent(household_size);
    total += calculate_food(household_size);
    total += calculate_transport(household_size);
    total += calculate_education(household_size);
    total += calculate_health(household_size);
    total += calculate_communication(household_size);
    total += calculate_recreation(household_size);
    total += calculate_other(household_size);

    return Math.round(total)
}

function highlight_output(class_name) {
    var available_classes = ['label-danger', 'label-warning', 'label-success']
    if ($.inArray(class_name, available_classes) > -1) {
        for (var i = 0; i < available_classes.length; i++)
        {
            var tmp = available_classes[i];
            $("#output-percentage").removeClass(tmp);
        }
        $("#output-percentage").addClass(class_name);
    }
}

function update_display(class_name) {
    var transition_time = constants.transition_time;
    var available_classes = ['display-landing', 'display-results', 'display-assumptions']

    if ($.inArray(class_name, available_classes) > -1) {

        for (var i = 0; i < available_classes.length; i++)
        {
            var tmp = available_classes[i];
            // hide some stuff
            if (tmp != class_name) {
                $("." + tmp).each(function() {
                    if (!$(this).hasClass(class_name)) {
                        $(this).slideUp(transition_time);
                    }
                });
            }

            // show some stuff
            $("." + class_name).each(function() {
                $(this).slideDown(transition_time);
            })
        }
    }
}

function validate_input(household_size, pay_rate, pay_amount) {
    if (!$.isNumeric(pay_amount)) {
        $("#pay-amount").parents('.form-group').addClass('has-error');
        $("#pay-amount").focus();
        pay_amount = false;
    }
    if (household_size && pay_rate && pay_amount){
        // update user feedback text
        $("#household-size-feedback").html(household_size + " people")
        return true
    }
    return false
}

function update_output() {

    // read input
    var household_size = $("#household-size").val();
    var pay_rate = $("#pay-rate").val();
    var pay_amount = $("#pay-amount").val();

    if (validate_input(household_size, pay_rate, pay_amount)) {
        var monthly_expenditure = calculate_expenditure(household_size);

        // calculate monthly pay
        var monthly_pay = 0;
        // Assumption using DoL info - a month includes 4.33 weeks and a week is for 5 work days.
        if (pay_rate == "day")
            monthly_pay = pay_amount * constants.workdays_per_month;
        else if (pay_rate == "week")
            monthly_pay = pay_amount * constants.weeks_per_month;
        else if (pay_rate == "month")
            monthly_pay = pay_amount;

        var output_percentage = (monthly_pay / monthly_expenditure);
        output_percentage *= 100;
        output_percentage = Math.round(output_percentage);

        var output_statement = "Try out the fair wage tool and see how your pay reflects living costs in South Africa.";
        if ((output_percentage > 0) && (output_percentage < constants.output_low)) {
            output_statement = "You're paying too little given the living costs and the size of your domestic worker's household. Take time to reassess how much you're paying by using our tool.";
            highlight_output('label-danger');
        } else if ((output_percentage >= 75) && (output_percentage < constants.output_almost)) {
            output_statement = "You're nearly there! Take time to reassess the wage by using our tool or discussing costs with your domestic worker.";
            highlight_output('label-warning');
        } else if ((output_percentage >= constants.output_almost) && (output_percentage < 100)) {
            output_statement = "You're very close to paying a fair wage given the living costs and the size of your domestic worker's household. Share your results!";
            highlight_output('label-warning');
        } else {
            output_statement = "You're covering your domestic worker's Minimal Need. Share your results!";
            highlight_output('label-success');
        }

        // show results to the user
        $("#output-amount").html(to_rands(monthly_pay))
        $("#output-monthly-need").html(to_rands(monthly_expenditure))

        $("#output-percentage").html(output_percentage + "%")
        $("#output-statement").html(output_statement);
        change_twitter_text("I am paying " + output_percentage + "%" + " of my domestic worker's minimal need. Calculate how much you are paying.");
        return true
    }
    return false
}

function change_twitter_text(txt) {
    if (typeof(twttr) != "undefined") {
        // Remove existing iframe
        $('#tweetBtn iframe').remove();
        // Generate new markup
        var tweetBtn = $('')
            .addClass('twitter-share-button')
            .addClass('pull-right')
            .attr('href', 'http://twitter.com/share')
            .attr('data-via', 'code4sa')
            .attr('data-text', txt)
            .attr('data-hashtags', 'fairwage');
        $('#tweetBtn').append(tweetBtn);
        console.log(twttr)
        console.log(txt)
        twttr.widgets.load();
    }
}

$(document).ready(function() {

    $("#pay-amount").focus();

    // initialize dropdown selects
    $("#pay-rate").selectpicker().on("change", function() {
        update_output();
    })
    $("#pay-amount").on("change", function() {
        update_output();
    })
    $('#assumption-container .selectpicker').selectpicker().on("change",function() {
        update_output();
    });

    // update output based on default input values
    update_output();

    // update on click
    $("#go-button").on('click', function(e) {
        e.preventDefault();
        if (update_output())
        {
            update_display('display-results');
        }
    })

    $("#show-assumptions-btn").on('click', function() {
        update_display('display-assumptions');
    })

    function rand_formater(value) {
        return value + ' rand';
    }

    function child_formater(value) {
        if (value == 1)
            return '1 child';
        else
            return value + ' children';
    }

    function people_formater(value) {
        if (value == 1)
            return '1 person';
        else
            return value + ' people';
    }

    $(this).find(".slider").each(function(i) {
        var tmp_formater = rand_formater;
        if ($(this).attr("data-slider-formater") == "children")
            tmp_formater = child_formater;
        else if ($(this).attr("data-slider-formater") == "people")
            tmp_formater = people_formater;

        $(this).slider({ tooltip: 'always', formater: tmp_formater })
            .on('slideStop', function(event) {
                $(this).attr("data-slider-val", $(this).val())
                update_output()
            });
    })
});

<commit_msg>Changed twitter message<commit_after>constants = {
    workdays_per_week : 5,
    weeks_per_month : 4.33,
    workdays_per_month : 5 * 4.33,
    days_per_month : 30,
    sanitation_threshold : 500,
    violence_threshold : 900,
    transition_time : 200,
    output_low : 75,     // below this figure salary is too low
    output_almost : 90  // below this figure salary is almost enough
}

function to_rands(val) {
    return "R" + val;
}

function calculate_transport(household_size) {
    var trans_cost = $("#transport-cost").val();
    var trans_direction = $("#transport-direction").val();
    if (trans_direction == "oneway")
        var out = Math.round(2 * trans_cost * constants.workdays_per_month);
    else
        var out = Math.round(trans_cost * constants.workdays_per_month);

    $("#transport-total").html(to_rands(out));

    return out
}

function calculate_food(household_size) {
    var food_cost = $("#food-cost").val();
    // Account for nutrition programme. Effectively kids do not need 1 meal 5 days a week IF education is provided. 16/21*850 for kids
    // Suggests that this program covers at least 30% of daily requirements of the students - Department of Education
    var out = Math.round(food_cost * household_size * constants.days_per_month);

    $("#food-total").html(to_rands(out));

    return out
}

function calculate_rent(household_size) {
    var rent_cost = $("#rent-cost").val();
    var sanitation_comment = ""
    var violence_comment = ""
    var out = Math.round(rent_cost)

    //Need comments on sanitation and violence to update with rent options.
    if (rent_cost > 0 && rent_cost < constants.sanitation_threshold)
        sanitation_comment = "Low functionality of bathrooms. High likelihood of communal bathroom. Low likelihood of reliable trash collection."
    else
        sanitation_comment = "Personal bathroom facilities. Reliable trash collection"

    if (rent_cost > 0 && rent_cost < constants.violence_threshold)
        violence_comment = "High likelihood of experiencing gang violence and burglaries."
    else
        violence_comment = "Much lower likelihood of experiencing violence."

    $("#rent-total").html(to_rands(out));

    return out
}

function calculate_education(household_size) {
    var kids = $("#education-kids").val()
    var education_cost = $("#education-cost").val()
    var out = education_cost * (kids);

    $("#education-total").html(to_rands(out));

    return out
}

function calculate_health(household_size) {

    var health_cost = $("#health-cost").val();
    var out = health_cost * household_size;
    var health_comment = ""

    $("#health-total").html(to_rands(out))

    return out
}

function calculate_communication(household_size) {
    var communication_cost = $("#communication-cost").val();
    var out = communication_cost * household_size

    $("#communication-total").html(to_rands(out))

    return out
}

function calculate_recreation(household_size) {
    var recreation_cost = $("#recreation-cost").val();
    var out = recreation_cost * household_size;

    $("#recreation-total").html(to_rands(out))

    return out
}

function calculate_other(household_size) {
    var out = $("#other-cost").val() * household_size;

    $("#other-total").html(to_rands(out))

    return out
}

function calculate_expenditure(household_size) {
    var total = 0;

    total += calculate_rent(household_size);
    total += calculate_food(household_size);
    total += calculate_transport(household_size);
    total += calculate_education(household_size);
    total += calculate_health(household_size);
    total += calculate_communication(household_size);
    total += calculate_recreation(household_size);
    total += calculate_other(household_size);

    return Math.round(total)
}

function highlight_output(class_name) {
    var available_classes = ['label-danger', 'label-warning', 'label-success']
    if ($.inArray(class_name, available_classes) > -1) {
        for (var i = 0; i < available_classes.length; i++)
        {
            var tmp = available_classes[i];
            $("#output-percentage").removeClass(tmp);
        }
        $("#output-percentage").addClass(class_name);
    }
}

function update_display(class_name) {
    var transition_time = constants.transition_time;
    var available_classes = ['display-landing', 'display-results', 'display-assumptions']

    if ($.inArray(class_name, available_classes) > -1) {

        for (var i = 0; i < available_classes.length; i++)
        {
            var tmp = available_classes[i];
            // hide some stuff
            if (tmp != class_name) {
                $("." + tmp).each(function() {
                    if (!$(this).hasClass(class_name)) {
                        $(this).slideUp(transition_time);
                    }
                });
            }

            // show some stuff
            $("." + class_name).each(function() {
                $(this).slideDown(transition_time);
            })
        }
    }
}

function validate_input(household_size, pay_rate, pay_amount) {
    if (!$.isNumeric(pay_amount)) {
        $("#pay-amount").parents('.form-group').addClass('has-error');
        $("#pay-amount").focus();
        pay_amount = false;
    }
    if (household_size && pay_rate && pay_amount){
        // update user feedback text
        $("#household-size-feedback").html(household_size + " people")
        return true
    }
    return false
}

function update_output() {

    // read input
    var household_size = $("#household-size").val();
    var pay_rate = $("#pay-rate").val();
    var pay_amount = $("#pay-amount").val();

    if (validate_input(household_size, pay_rate, pay_amount)) {
        var monthly_expenditure = calculate_expenditure(household_size);

        // calculate monthly pay
        var monthly_pay = 0;
        // Assumption using DoL info - a month includes 4.33 weeks and a week is for 5 work days.
        if (pay_rate == "day")
            monthly_pay = pay_amount * constants.workdays_per_month;
        else if (pay_rate == "week")
            monthly_pay = pay_amount * constants.weeks_per_month;
        else if (pay_rate == "month")
            monthly_pay = pay_amount;

        var output_percentage = (monthly_pay / monthly_expenditure);
        output_percentage *= 100;
        output_percentage = Math.round(output_percentage);

        var output_statement = "Try out the fair wage tool and see how your pay reflects living costs in South Africa.";
        if ((output_percentage > 0) && (output_percentage < constants.output_low)) {
            output_statement = "You're paying too little given the living costs and the size of your domestic worker's household. Take time to reassess how much you're paying by using our tool.";
            highlight_output('label-danger');
        } else if ((output_percentage >= 75) && (output_percentage < constants.output_almost)) {
            output_statement = "You're nearly there! Take time to reassess the wage by using our tool or discussing costs with your domestic worker.";
            highlight_output('label-warning');
        } else if ((output_percentage >= constants.output_almost) && (output_percentage < 100)) {
            output_statement = "You're very close to paying a fair wage given the living costs and the size of your domestic worker's household. Share your results!";
            highlight_output('label-warning');
        } else {
            output_statement = "You're covering your domestic worker's Minimal Need. Share your results!";
            highlight_output('label-success');
        }

        // show results to the user
        $("#output-amount").html(to_rands(monthly_pay))
        $("#output-monthly-need").html(to_rands(monthly_expenditure))

        $("#output-percentage").html(output_percentage + "%")
        $("#output-statement").html(output_statement);
        change_twitter_text("I pay my domestic worker R" + monthly_pay + " which is " + output_percentage + "% of their monthly need, how much do you pay?");
        return true
    }
    return false
}

function change_twitter_text(txt) {
    if (typeof(twttr) != "undefined") {
        // Remove existing iframe
        $('#tweetBtn iframe').remove();
        // Generate new markup
        var tweetBtn = $('')
            .addClass('twitter-share-button')
            .addClass('pull-right')
            .attr('href', 'http://twitter.com/share')
            .attr('data-url', 'http://bit.ly/1Gn9ZWS')
            .attr('data-via', 'code4sa')
            .attr('data-text', txt)
            .attr('data-hashtags', 'fairwage');
        $('#tweetBtn').append(tweetBtn);
        console.log(twttr)
        console.log(txt)
        twttr.widgets.load();
    }
}

$(document).ready(function() {

    $("#pay-amount").focus();

    // initialize dropdown selects
    $("#pay-rate").selectpicker().on("change", function() {
        update_output();
    })
    $("#pay-amount").on("change", function() {
        update_output();
    })
    $('#assumption-container .selectpicker').selectpicker().on("change",function() {
        update_output();
    });

    // update output based on default input values
    update_output();

    // update on click
    $("#go-button").on('click', function(e) {
        e.preventDefault();
        if (update_output())
        {
            update_display('display-results');
        }
    })

    $("#show-assumptions-btn").on('click', function() {
        update_display('display-assumptions');
    })

    function rand_formater(value) {
        return value + ' rand';
    }

    function child_formater(value) {
        if (value == 1)
            return '1 child';
        else
            return value + ' children';
    }

    function people_formater(value) {
        if (value == 1)
            return '1 person';
        else
            return value + ' people';
    }

    $(this).find(".slider").each(function(i) {
        var tmp_formater = rand_formater;
        if ($(this).attr("data-slider-formater") == "children")
            tmp_formater = child_formater;
        else if ($(this).attr("data-slider-formater") == "people")
            tmp_formater = people_formater;

        $(this).slider({ tooltip: 'always', formater: tmp_formater })
            .on('slideStop', function(event) {
                $(this).attr("data-slider-val", $(this).val())
                update_output()
            });
    })
});

<|endoftext|>