<commit_before>var questions = [
  Q1 = {
		question: "What does HTML means?",
		answer: "HyperText Markup Language"
  },
  Q2 = {
		question: "What does CSS means?",
		answer: "Cascading Style Sheet"
  },
  Q3 = {
		question: "Why the \"C\" in CSS, is called Cascading?",
		answer: "When CSS rules are duplicated, the rule to be use is chosen by cascading down from more general rules to the specific rule required"
  }
];

var question = document.getElementById('question');

var questionNum = 0,
	answeredQA = [];

// Generate random number to display random QA set
function createNum() {
	questionNum = Math.floor(Math.random() * 3);
	// Recursively create random questionNum so that last QA set will not be repeated
	if (answeredQA.indexOf(questionNum) !== -1) {
		createNum();
	}
	question.innerHTML = questions[questionNum].question;
	answeredQA.push(questionNum);
}

createNum();

var revealBtn = document.getElementById('reveal-answer');

function revealAns() {
	question.innerHTML = questions[questionNum].answer;
	revealBtn.value = "NEXT";
}

function nextSet() {
	createNum();
	question.innerHTML = questions[questionNum].question;
}

revealBtn.onclick = revealAns;

<commit_msg>Check for revealBtn value<commit_after>var questions = [
  Q1 = {
		question: "What does HTML means?",
		answer: "HyperText Markup Language"
  },
  Q2 = {
		question: "What does CSS means?",
		answer: "Cascading Style Sheet"
  },
  Q3 = {
		question: "Why the \"C\" in CSS, is called Cascading?",
		answer: "When CSS rules are duplicated, the rule to be use is chosen by cascading down from more general rules to the specific rule required"
  }
];

var question = document.getElementById('question');

var questionNum = 0,
	answeredQA = [];

// Generate random number to display random QA set
function createNum() {
	questionNum = Math.floor(Math.random() * 3);
	// Recursively create random questionNum so that last QA set will not be repeated
	if (answeredQA.indexOf(questionNum) !== -1) {
		createNum();
	}
	question.innerHTML = questions[questionNum].question;
	answeredQA.push(questionNum);
}

createNum();

var revealBtn = document.getElementById('reveal-answer');

function revealAns() {
	question.innerHTML = questions[questionNum].answer;
	revealBtn.value = "NEXT";

	if (this.value == "NEXT") {
		createNum();
		revealBtn.value = "REVEAL";
	}
}

function nextSet() {
	createNum();
	question.innerHTML = questions[questionNum].question;
}

revealBtn.onclick = revealAns;

<|endoftext|>


<commit_before>// Method chaining in jquery
$("li").css("color", "blue")
       .slideUp(1000)
       .slideDown(1000)
       .attr("title", "My Title");

// What is JSON
var employeesJSON = [{
    "firstName": "Goran",
    "lastName": "Djordjijevski",
    "gender": "Male",
    "years": 29
},
{
    "firstName": "Sara",
    "lastName": "Jovanovic",
    "gender": "Female",
    "years": 25
}];

var result = "";
result += "First Name = " + employeesJSON[0].firstName + "
";
result += "Last Name = " + employeesJSON[0].lastName + "
";
result += "Gender = " + employeesJSON[0].gender + "
";
result += "Years = " + employeesJSON[0].years + "
";

result += "First Name = " + employeesJSON[1].firstName + "
";
result += "Last Name = " + employeesJSON[1].lastName + "
";
result += "Gender = " + employeesJSON[1].gender + "
";
result += "Years = " + employeesJSON[1].years + "
"

// $("#result").html(result);

// DOM Manipulation methods
// var returnAttr = $("div").attr("title");
// console.log(returnAttr);

// $("div").each(function() {
//     console.log($(this).attr("title"));
// });

// DOM Manipulation methods with JSON object
var config = {
    "title": "New DIV Title",
    "style": "border: 1px solid red",
    "name": "MY DIV"
};

// DOM Manipulation with .wrap() method
// $("div").wrap("

");
// $("div").append("
add a new parent div container
");

// Add or remove class
$("#btn1").on("click", function() {
    $("h1").addClass("colorClass");
});

$("#btn2").on("click", function() {
    $("h1").removeClass("colorClass");
});

$("#btn3").on("click", function() {
    $("h1").addClass("colorClass italicClass");
});

$("#btn4").on("click", function() {
    $("h1").removeClass("colorClass italicClass");
});

$("#btn5").on("click", function() {
    $("h1").addClass("colorClass italicClass boldClass");
});

$("#btn6").on("click", function() {
    $("h1").removeClass("colorClass italicClass boldClass");
});

$("#btn7").on("click", function() {
    $("h1").toggleClass("colorClass italicClass boldClass");
});

$("input[type='text']").each(function() {
    $(this).focus(function() {
        $(this).toggleClass("textBoxStyle");
    });
});

// jQuery change event
// $("#ddlCity").change(function() {
//     var selectedValue = $(this).val();
//     $("#divResult").html(selectedValue);
// });

// $("input").change(function() {
//     var result = "";
//     if (result == "") {
//         result = $(this).val();
//     }
//     else {
//         result += ", " + $(this).val();
//     }

//     $("#divResult").html(result);
// });

$("img[src='img/help.png']").mouseover(function() {
    $("#" + getDivId(this)).fadeIn(500);
}).mouseout(function() {
    $("#" + getDivId(this)).fadeOut(500);
});

function getDivId(helpIcon) {
    var helpIconId = $(helpIcon).attr("id");
    return helpIconId.replace("img", "div");
}<commit_msg>Just added comment for mouse events.<commit_after>// Method chaining in jquery
$("li").css("color", "blue")
       .slideUp(1000)
       .slideDown(1000)
       .attr("title", "My Title");

// What is JSON
var employeesJSON = [{
    "firstName": "Goran",
    "lastName": "Djordjijevski",
    "gender": "Male",
    "years": 29
},
{
    "firstName": "Sara",
    "lastName": "Jovanovic",
    "gender": "Female",
    "years": 25
}];

var result = "";
result += "First Name = " + employeesJSON[0].firstName + "
";
result += "Last Name = " + employeesJSON[0].lastName + "
";
result += "Gender = " + employeesJSON[0].gender + "
";
result += "Years = " + employeesJSON[0].years + "
";

result += "First Name = " + employeesJSON[1].firstName + "
";
result += "Last Name = " + employeesJSON[1].lastName + "
";
result += "Gender = " + employeesJSON[1].gender + "
";
result += "Years = " + employeesJSON[1].years + "
"

// $("#result").html(result);

// DOM Manipulation methods
// var returnAttr = $("div").attr("title");
// console.log(returnAttr);

// $("div").each(function() {
//     console.log($(this).attr("title"));
// });

// DOM Manipulation methods with JSON object
var config = {
    "title": "New DIV Title",
    "style": "border: 1px solid red",
    "name": "MY DIV"
};

// DOM Manipulation with .wrap() method
// $("div").wrap("

");
// $("div").append("
add a new parent div container
");

// Add or remove class
$("#btn1").on("click", function() {
    $("h1").addClass("colorClass");
});

$("#btn2").on("click", function() {
    $("h1").removeClass("colorClass");
});

$("#btn3").on("click", function() {
    $("h1").addClass("colorClass italicClass");
});

$("#btn4").on("click", function() {
    $("h1").removeClass("colorClass italicClass");
});

$("#btn5").on("click", function() {
    $("h1").addClass("colorClass italicClass boldClass");
});

$("#btn6").on("click", function() {
    $("h1").removeClass("colorClass italicClass boldClass");
});

$("#btn7").on("click", function() {
    $("h1").toggleClass("colorClass italicClass boldClass");
});

$("input[type='text']").each(function() {
    $(this).focus(function() {
        $(this).toggleClass("textBoxStyle");
    });
});

// jQuery change event
// $("#ddlCity").change(function() {
//     var selectedValue = $(this).val();
//     $("#divResult").html(selectedValue);
// });

// $("input").change(function() {
//     var result = "";
//     if (result == "") {
//         result = $(this).val();
//     }
//     else {
//         result += ", " + $(this).val();
//     }

//     $("#divResult").html(result);
// });

// jQuery mouse events
$("img[src='img/help.png']").mouseover(function() {
    $("#" + getDivId(this)).fadeIn(500);
}).mouseout(function() {
    $("#" + getDivId(this)).fadeOut(500);
});

function getDivId(helpIcon) {
    var helpIconId = $(helpIcon).attr("id");
    return helpIconId.replace("img", "div");
}<|endoftext|>


<commit_before>function artistElement(artist) {
  var img = artist.images[0] || { url: 'https://placehold.it/64x64' }

  return `

        ${artist.name}

  `
}

function artistListElement(artists) {
  var html = ''

  artists.forEach(function(artist) {
    html += artistElement(artist)
  })

  return html
}

$('#artist-search').on('submit', function(event) {
  event.preventDefault()

  var name = $("#artistSearchInput").val()
  if (!name) {
    alert("Please enter and artist's name to search")
    return
  }

  spotifyApi.searchArtists(name)
    .then(function(data) {
      console.log('Search artists by "' + name + '"' , data)
      var artistList = artistListElement(data.artists.items)
      $('#search-artist-list').html(artistList)
    }, function(err) {
      console.error(err)
    })

})

$('#search-artist-list').on('click', '.artist', function(event) {
  $('.album-list').empty()
  var id = $(event.currentTarget).data('id')
  $("#selected-artist-list").append(event.currentTarget)
  selectedArtistIds.push(id)
})

$('#selected-artist-list').on('click', '.artist', function(event) {
  $('.album-list').empty()
  var id = $(event.currentTarget).data('id')
  var index = selectedArtistIds.indexOf(id)
  selectedArtistIds.splice(index, 1)
  $(event.currentTarget).remove()
  console.log("clicked selected")
})

function authorize(clientId, redirectUri, scope) {
  var state = generateRandomString(16);
  // localStorage.setItem(stateKey, state);

  var scope = 'user-read-private user-read-email';
  var url = 'https://accounts.spotify.com/authorize';
  url += '?response_type=token';
  url += '&client_id=' + encodeURIComponent(client_id);
  url += '&scope=' + encodeURIComponent(scope);
  url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
  url += '&state=' + encodeURIComponent(state);

  var w = window.open(url, 'asdf', 'WIDTH=400,HEIGHT=500');
}

/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
function generateRandomString(length) {
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

$("#createPlaylist").click(function() {
  var scope = 'playlist-modify-public'
  var playlistName = $("#playlist-name").val()

  if (!playlistName) {
    alert("Playlist name can not be empty")
    return
  }

  localStorage.setItem(playlistNameKey, playlistName)
  localStorage.setItem(artistsKey, JSON.stringify(selectedArtistIds))

  authorize(client_id, redirect_uri, scope)
})

var spotifyApi = new SpotifyWebApi()
spotifyApi.setPromiseImplementation(Q)

var selectedArtistIds = []
var stateKey = 'spotify_auth_state'
var playlistNameKey = 'createplaylist-name'
var artistsKey = 'createplaylist-artists'

var client_id = 'fe25f2f0df964008b26bc9e34ed3496a';
var redirect_uri = '';

if (location.host == 'localhost:8000') {
  redirect_uri = 'http://localhost:8000/callback.html';
} else {
  redirect_uri = 'https://www.spotonplaylist.com/callback.html';
}
<commit_msg>Prevent adding artists more than once<commit_after>function artistElement(artist) {
  var img = artist.images[0] || { url: 'https://placehold.it/64x64' }

  return `

        ${artist.name}

  `
}

function artistListElement(artists) {
  var html = ''

  artists.forEach(function(artist) {
    html += artistElement(artist)
  })

  return html
}

$('#artist-search').on('submit', function(event) {
  event.preventDefault()

  var name = $("#artistSearchInput").val()
  if (!name) {
    alert("Please enter and artist's name to search")
    return
  }

  spotifyApi.searchArtists(name)
    .then(function(data) {
      console.log('Search artists by "' + name + '"' , data)
      var artistList = artistListElement(data.artists.items)
      $('#search-artist-list').html(artistList)
    }, function(err) {
      console.error(err)
    })

})

$('#search-artist-list').on('click', '.artist', function(event) {
  $('.album-list').empty()
  var id = $(event.currentTarget).data('id')
  if (selectedArtistIds.indexOf(id) > -1) {
    $(event.currentTarget).remove()
  } else {
    $("#selected-artist-list").append(event.currentTarget)
    selectedArtistIds.push(id)
  }
})

$('#selected-artist-list').on('click', '.artist', function(event) {
  $('.album-list').empty()
  var id = $(event.currentTarget).data('id')
  var index = selectedArtistIds.indexOf(id)
  selectedArtistIds.splice(index, 1)
  $(event.currentTarget).remove()
  console.log("clicked selected")
})

function authorize(clientId, redirectUri, scope) {
  var state = generateRandomString(16);
  // localStorage.setItem(stateKey, state);

  var scope = 'user-read-private user-read-email';
  var url = 'https://accounts.spotify.com/authorize';
  url += '?response_type=token';
  url += '&client_id=' + encodeURIComponent(client_id);
  url += '&scope=' + encodeURIComponent(scope);
  url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
  url += '&state=' + encodeURIComponent(state);

  var w = window.open(url, 'asdf', 'WIDTH=400,HEIGHT=500');
}

/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
function generateRandomString(length) {
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

$("#createPlaylist").click(function() {
  var scope = 'playlist-modify-public'
  var playlistName = $("#playlist-name").val()

  if (!playlistName) {
    alert("Playlist name can not be empty")
    return
  }

  localStorage.setItem(playlistNameKey, playlistName)
  localStorage.setItem(artistsKey, JSON.stringify(selectedArtistIds))

  authorize(client_id, redirect_uri, scope)
})

var spotifyApi = new SpotifyWebApi()
spotifyApi.setPromiseImplementation(Q)

var selectedArtistIds = []
var stateKey = 'spotify_auth_state'
var playlistNameKey = 'createplaylist-name'
var artistsKey = 'createplaylist-artists'

var client_id = 'fe25f2f0df964008b26bc9e34ed3496a';
var redirect_uri = '';

if (location.host == 'localhost:8000') {
  redirect_uri = 'http://localhost:8000/callback.html';
} else {
  redirect_uri = 'https://www.spotonplaylist.com/callback.html';
}
<|endoftext|>


<commit_before>// Closes the sidebar menu
$("#menu-close").click(function (e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});

// Opens the sidebar menu
$("#menu-toggle").click(function (e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});

// Scrolls to the selected menu item on the page
/*
$(function () {
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});
*/

//ajax get water reservoir data
$(function () {
	$.ajax({
		type: "GET",
		url: "http://128.199.223.114:10080",
		dataType: "jsonp",
		success: function (data) {

            //data.data[0] 石門水庫(新北、桃園、新竹)
            //data.data[1] 新山水庫(基隆)
            //data.data[2] 翡翠水庫(台北、新北)
            //data.data[3] 寶山水庫(新竹)
            //data.data[4] 寶山第二水庫(新竹)
            //data.data[5] 永和山水庫(新竹、苗栗)
            //data.data[6] 明德水庫(苗栗)
            //data.data[7] 鯉魚潭水庫(苗栗、台中)
            //data.data[8] 德基水庫(台中)
            //data.data[9] 石岡壩(台中)
            //data.data[10] 霧社水庫(南投)
            //data.data[11] 日月潭水庫(南投)
            //data.data[12] 仁義潭水庫(嘉義)
            //data.data[13] 蘭潭水庫(嘉義)
            //data.data[14] 烏山頭水庫(台南)
            //data.data[15] 曾文水庫(嘉義、台南)
            //data.data[16] 南化水庫(台南、高雄)
            //data.data[17] 阿公店水庫(高雄)
            //data.data[18] 牡丹水庫(屏東)

            var config = liquidFillGaugeDefaultSettings();
            for (var i = 0; i < data.data.length; i++) {
                  if(data.data[i].immediateStorage.replace('%','') <= 30){
            	// if(data.data[i].immediatePercentage.replace('%','') <= 30){
            		config.circleColor = "#FF7777";
            		config.textColor = "#FF4444";
            		config.waveTextColor = "#FFAAAA";
            		config.waveColor = "#FFDDDD";
            	}                  // else if(data.data[i].immediatePercentage.replace('%','') <= 60){
                        else if(data.data[i].immediateStorage.replace('%','') <= 60){
                          config.circleColor = "#808015";
                          config.textColor = "#555500";
                          config.waveTextColor = "#FFFFAA";
                          config.waveColor = "#AAAA39";
                    }
                    else {
                          config = liquidFillGaugeDefaultSettings();
                    }
                    config.waveAnimateTime = 2000;
                    config.waveHeight = 0.3;
                    config.waveCount = 1;
                  // loadLiquidFillGauge('fillgauge'+i, Number(data.data[i].immediatePercentage.replace('%','')), config);
                  loadLiquidFillGauge('fillgauge'+i, Number(data.data[i].immediateStorage.replace('%','')), config);
            };
            // var config1 = liquidFillGaugeDefaultSettings();
            // if(data.data[1].immediatePercentage.replace('%','') <= 30){
            // 	config1.circleColor = "#FF7777";
            // 	config1.textColor = "#FF4444";
            // 	config1.waveTextColor = "#FFAAAA";
            // 	config1.waveColor = "#FFDDDD";
            // }
            // else if(data.data[1].immediatePercentage.replace('%','') <= 60){
            // 	config1.circleColor = "#808015";
            // 	config1.textColor = "#555500";
            // 	config1.waveTextColor = "#FFFFAA";
            // 	config1.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge1", Number(data.data[1].immediatePercentage.replace('%','')), config1);

            // var config2 = liquidFillGaugeDefaultSettings();
            // if(data.data[2].immediatePercentage <= 30){
            // 	config2.circleColor = "#FF7777";
            // 	config2.textColor = "#FF4444";
            // 	config2.waveTextColor = "#FFAAAA";
            // 	config2.waveColor = "#FFDDDD";
            // }
            // else if(data.data[2].immediatePercentage <= 60){
            // 	config2.circleColor = "#808015";
            // 	config2.textColor = "#555500";
            // 	config2.waveTextColor = "#FFFFAA";
            // 	config2.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge2", Number(data.data[2].immediatePercentage.replace('%','')), config2);

            // var config3 = liquidFillGaugeDefaultSettings();
            // if(data.data[3].immediatePercentage <= 30){
            // 	config3.circleColor = "#FF7777";
            // 	config3.textColor = "#FF4444";
            // 	config3.waveTextColor = "#FFAAAA";
            // 	config3.waveColor = "#FFDDDD";
            // }
            // else if(data.data[3].immediatePercentage <= 60){
            // 	config3.circleColor = "#808015";
            // 	config3.textColor = "#555500";
            // 	config3.waveTextColor = "#FFFFAA";
            // 	config3.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge3", Number(data.data[3].immediatePercentage.replace('%','')), config3);

            // var config4 = liquidFillGaugeDefaultSettings();

            // config4.circleColor = "#808015";
            // config4.textColor = "#555500";
            // config4.waveTextColor = "#FFFFAA";
            // config4.waveColor = "#AAAA39";

            // loadLiquidFillGauge("fillgauge4", Number(data.data[4].immediatePercentage.replace('%','')), config4);

            // var config5 = liquidFillGaugeDefaultSettings();
            // config5.circleColor = "#FF7777";
            // config5.textColor = "#FF4444";
            // config5.waveTextColor = "#FFAAAA";
            // config5.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge5", Number(data.data[5].immediatePercentage.replace('%','')), config5);
            // var config6 = liquidFillGaugeDefaultSettings();
            // config6.circleColor = "#FF7777";
            // config6.textColor = "#FF4444";
            // config6.waveTextColor = "#FFAAAA";
            // config6.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge6", Number(data.data[6].immediatePercentage.replace('%','')), config6);
            // var config7 = liquidFillGaugeDefaultSettings();
            // config7.circleColor = "#FF7777";
            // config7.textColor = "#FF4444";
            // config7.waveTextColor = "#FFAAAA";
            // config7.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge7", Number(data.data[7].immediatePercentage.replace('%','')), config7);
            // var config8 = liquidFillGaugeDefaultSettings();
            // config8.circleColor = "#808015";
            // config8.textColor = "#555500";
            // config8.waveTextColor = "#FFFFAA";
            // config8.waveColor = "#AAAA39";
            // loadLiquidFillGauge("fillgauge8", Number(data.data[8].immediatePercentage.replace('%','')), config8);
            // var config9 = liquidFillGaugeDefaultSettings();
            // config9.circleColor = "#808015";
            // config9.textColor = "#555500";
            // config9.waveTextColor = "#FFFFAA";
            // config9.waveColor = "#AAAA39";
            // loadLiquidFillGauge("fillgauge9", Number(data.data[9].immediatePercentage.replace('%','')), config9);
            // var config10 = liquidFillGaugeDefaultSettings();
            // if(data.data[10].immediatePercentage.replace('%','') <= 30){
            // 	config10.circleColor = "#FF7777";
            // 	config10.textColor = "#FF4444";
            // 	config10.waveTextColor = "#FFAAAA";
            // 	config10.waveColor = "#FFDDDD";
            // }
            // else if(data.data[10].immediatePercentage.replace('%','') <= 60){
            // 	config10.circleColor = "#808015";
            // 	config10.textColor = "#555500";
            // 	config10.waveTextColor = "#FFFFAA";
            // 	config10.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge10", Number(data.data[10].immediatePercentage.replace('%','')), config10);
            // var config11 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge11", Number(data.data[11].immediatePercentage.replace('%','')), config11);
            // var config12 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge12", Number(data.data[12].immediatePercentage.replace('%','')), config12);
            // var config13 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge13", Number(data.data[13].immediatePercentage.replace('%','')), config13);
            // var config14 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge14", Number(data.data[14].immediatePercentage.replace('%','')), config14);
            // var config15 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge15", Number(data.data[15].immediatePercentage.replace('%','')), config15);
            // var config16 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge16", Number(data.data[16].immediatePercentage.replace('%','')), config16);
            // var config17 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge17", Number(data.data[17].immediatePercentage.replace('%','')), config17);
            // var config18 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge18", Number(data.data[18].immediatePercentage.replace('%','')), config18);
            // var config19 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge19", Number(data.data[19].immediatePercentage.replace('%','')), config19);
            // var config70 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge20", Number(data.data[20].immediatePercentage.replace('%','')), config70);

            // var config60 = liquidFillGaugeDefaultSettings();
            // config60.circleColor = "#FF7777";
            // config60.textColor = "#FF4444";
            // config60.waveTextColor = "#FFAAAA";
            // config60.waveColor = "#FFDDDD";
            // config60.circleThickness = 0.2;
            // config60.textVertPosition = 0.2;
            // config60.waveAnimateTime = 1000;
            // loadLiquidFillGauge("fillgauge60", Number(data.data[0].immediatePercentage.replace('%','')), config60);

            // var config70 = liquidFillGaugeDefaultSettings();
            // config70.circleColor = "#D4AB6A";
            // config70.textColor = "#553300";
            // config70.waveTextColor = "#805615";
            // config70.waveColor = "#AA7D39";
            // config70.circleThickness = 0.1;
            // config70.circleFillGap = 0.2;
            // config70.textVertPosition = 0.8;
            // config70.waveAnimateTime = 2000;
            // config70.waveHeight = 0.3;
            // config70.waveCount = 1;
            // loadLiquidFillGauge("fillgauge70", Number(data.data[2].immediatePercentage.replace('%','')), config70);

            // var config30 = liquidFillGaugeDefaultSettings();
            // config30.textVertPosition = 0.8;
            // config30.waveAnimateTime = 5000;
            // config30.waveHeight = 0.15;
            // config30.waveAnimate = false;
            // config30.waveOffset = 0.25;
            // config30.valueCountUp = false;
            // config30.displayPercent = false;
            // loadLiquidFillGauge("fillgauge30", Number(data.data[3].immediatePercentage.replace('%','')), config30);

            // var config40 = liquidFillGaugeDefaultSettings();
            // config40.circleThickness = 0.15;
            // config40.circleColor = "#808015";
            // config40.textColor = "#555500";
            // config40.waveTextColor = "#FFFFAA";
            // config40.waveColor = "#AAAA39";
            // config40.textVertPosition = 0.8;
            // config40.waveAnimateTime = 1000;
            // config40.waveHeight = 0.05;
            // config40.waveAnimate = true;
            // config40.waveRise = false;
            // config40.waveOffset = 0.25;
            // config40.textSize = 0.75;
            // config40.waveCount = 3;
            // loadLiquidFillGauge("fillgauge40", Number(data.data[14].immediatePercentage.replace('%','')), config40);

            // var config50 = liquidFillGaugeDefaultSettings();
            // config50.circleThickness = 0.4;
            // config50.circleColor = "#6DA398";
            // config50.textColor = "#0E5144";
            // config50.waveTextColor = "#6DA398";
            // config50.waveColor = "#246D5F";
            // config50.textVertPosition = 0.52;
            // config50.waveAnimateTime = 5000;
            // config50.waveHeight = 0;
            // config50.waveAnimate = false;
            // config50.waveCount = 2;
            // config50.waveOffset = 0.25;
            // config50.textSize = 1.2;
            // config50.minValue = 30;
            // config50.maxValue = 150
            // config50.displayPercent = false;
            // loadLiquidFillGauge("fillgauge50", Number(data.data[15].immediatePercentage.replace('%','')), config50);
      }
});
});
<commit_msg>Update main.js<commit_after>// Closes the sidebar menu
$("#menu-close").click(function (e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});

// Opens the sidebar menu
$("#menu-toggle").click(function (e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});

// Scrolls to the selected menu item on the page
/*
$(function () {
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});
*/

//ajax get water reservoir data
$(function () {
	$.ajax({
		type: "GET",
		url: "http://128.199.223.114:10080",
		dataType: "jsonp",
		success: function (data) {

            //data.data[0] 石門水庫(新北、桃園、新竹)
            //data.data[1] 新山水庫(基隆)
            //data.data[2] 翡翠水庫(台北、新北)
            //data.data[3] 寶山水庫(新竹)
            //data.data[4] 寶山第二水庫(新竹)
            //data.data[5] 永和山水庫(新竹、苗栗)
            //data.data[6] 明德水庫(苗栗)
            //data.data[7] 鯉魚潭水庫(苗栗、台中)
            //data.data[8] 德基水庫(台中)
            //data.data[9] 石岡壩(台中)
            //data.data[10] 霧社水庫(南投)
            //data.data[11] 日月潭水庫(南投)
            //data.data[12] 仁義潭水庫(嘉義)
            //data.data[13] 蘭潭水庫(嘉義)
            //data.data[14] 烏山頭水庫(台南)
            //data.data[15] 曾文水庫(嘉義、台南)
            //data.data[16] 南化水庫(台南、高雄)
            //data.data[17] 阿公店水庫(高雄)
            //data.data[18] 牡丹水庫(屏東)

            var config = liquidFillGaugeDefaultSettings();
            for (var i = 0; i < data.data.length; i++) {
                  if(data.data[i].immediateStorage.replace('%','') <= 30){
            	// if(data.data[i].immediatePercentage.replace('%','') <= 30){
            		config.circleColor = "#FF7777";
            		config.textColor = "#FF4444";
            		config.waveTextColor = "#FFAAAA";
            		config.waveColor = "#FFDDDD";
            	}                  // else if(data.data[i].immediatePercentage.replace('%','') <= 60){
                  else if(data.data[i].immediateStorage.replace('%','') <= 60){
                        config.circleColor = "#808015";
                        config.textColor = "#555500";
                        config.waveTextColor = "#FFFFAA";
                        config.waveColor = "#AAAA39";
                  }
                  else {
                        config = liquidFillGaugeDefaultSettings();
                  }
                    config.waveAnimateTime = 2000;
                    config.waveHeight = 0.2;
                    config.waveCount = 1;
                  // loadLiquidFillGauge('fillgauge'+i, Number(data.data[i].immediatePercentage.replace('%','')), config);
                  loadLiquidFillGauge('fillgauge'+i, Number(data.data[i].immediateStorage.replace('%','')), config);
                  document.getElementById("demo").innerHTML = data.data[i].reservoirName;
            };
            // var config1 = liquidFillGaugeDefaultSettings();
            // if(data.data[1].immediatePercentage.replace('%','') <= 30){
            // 	config1.circleColor = "#FF7777";
            // 	config1.textColor = "#FF4444";
            // 	config1.waveTextColor = "#FFAAAA";
            // 	config1.waveColor = "#FFDDDD";
            // }
            // else if(data.data[1].immediatePercentage.replace('%','') <= 60){
            // 	config1.circleColor = "#808015";
            // 	config1.textColor = "#555500";
            // 	config1.waveTextColor = "#FFFFAA";
            // 	config1.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge1", Number(data.data[1].immediatePercentage.replace('%','')), config1);

            // var config2 = liquidFillGaugeDefaultSettings();
            // if(data.data[2].immediatePercentage <= 30){
            // 	config2.circleColor = "#FF7777";
            // 	config2.textColor = "#FF4444";
            // 	config2.waveTextColor = "#FFAAAA";
            // 	config2.waveColor = "#FFDDDD";
            // }
            // else if(data.data[2].immediatePercentage <= 60){
            // 	config2.circleColor = "#808015";
            // 	config2.textColor = "#555500";
            // 	config2.waveTextColor = "#FFFFAA";
            // 	config2.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge2", Number(data.data[2].immediatePercentage.replace('%','')), config2);

            // var config3 = liquidFillGaugeDefaultSettings();
            // if(data.data[3].immediatePercentage <= 30){
            // 	config3.circleColor = "#FF7777";
            // 	config3.textColor = "#FF4444";
            // 	config3.waveTextColor = "#FFAAAA";
            // 	config3.waveColor = "#FFDDDD";
            // }
            // else if(data.data[3].immediatePercentage <= 60){
            // 	config3.circleColor = "#808015";
            // 	config3.textColor = "#555500";
            // 	config3.waveTextColor = "#FFFFAA";
            // 	config3.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge3", Number(data.data[3].immediatePercentage.replace('%','')), config3);

            // var config4 = liquidFillGaugeDefaultSettings();

            // config4.circleColor = "#808015";
            // config4.textColor = "#555500";
            // config4.waveTextColor = "#FFFFAA";
            // config4.waveColor = "#AAAA39";

            // loadLiquidFillGauge("fillgauge4", Number(data.data[4].immediatePercentage.replace('%','')), config4);

            // var config5 = liquidFillGaugeDefaultSettings();
            // config5.circleColor = "#FF7777";
            // config5.textColor = "#FF4444";
            // config5.waveTextColor = "#FFAAAA";
            // config5.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge5", Number(data.data[5].immediatePercentage.replace('%','')), config5);
            // var config6 = liquidFillGaugeDefaultSettings();
            // config6.circleColor = "#FF7777";
            // config6.textColor = "#FF4444";
            // config6.waveTextColor = "#FFAAAA";
            // config6.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge6", Number(data.data[6].immediatePercentage.replace('%','')), config6);
            // var config7 = liquidFillGaugeDefaultSettings();
            // config7.circleColor = "#FF7777";
            // config7.textColor = "#FF4444";
            // config7.waveTextColor = "#FFAAAA";
            // config7.waveColor = "#FFDDDD";
            // loadLiquidFillGauge("fillgauge7", Number(data.data[7].immediatePercentage.replace('%','')), config7);
            // var config8 = liquidFillGaugeDefaultSettings();
            // config8.circleColor = "#808015";
            // config8.textColor = "#555500";
            // config8.waveTextColor = "#FFFFAA";
            // config8.waveColor = "#AAAA39";
            // loadLiquidFillGauge("fillgauge8", Number(data.data[8].immediatePercentage.replace('%','')), config8);
            // var config9 = liquidFillGaugeDefaultSettings();
            // config9.circleColor = "#808015";
            // config9.textColor = "#555500";
            // config9.waveTextColor = "#FFFFAA";
            // config9.waveColor = "#AAAA39";
            // loadLiquidFillGauge("fillgauge9", Number(data.data[9].immediatePercentage.replace('%','')), config9);
            // var config10 = liquidFillGaugeDefaultSettings();
            // if(data.data[10].immediatePercentage.replace('%','') <= 30){
            // 	config10.circleColor = "#FF7777";
            // 	config10.textColor = "#FF4444";
            // 	config10.waveTextColor = "#FFAAAA";
            // 	config10.waveColor = "#FFDDDD";
            // }
            // else if(data.data[10].immediatePercentage.replace('%','') <= 60){
            // 	config10.circleColor = "#808015";
            // 	config10.textColor = "#555500";
            // 	config10.waveTextColor = "#FFFFAA";
            // 	config10.waveColor = "#AAAA39";
            // }
            // loadLiquidFillGauge("fillgauge10", Number(data.data[10].immediatePercentage.replace('%','')), config10);
            // var config11 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge11", Number(data.data[11].immediatePercentage.replace('%','')), config11);
            // var config12 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge12", Number(data.data[12].immediatePercentage.replace('%','')), config12);
            // var config13 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge13", Number(data.data[13].immediatePercentage.replace('%','')), config13);
            // var config14 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge14", Number(data.data[14].immediatePercentage.replace('%','')), config14);
            // var config15 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge15", Number(data.data[15].immediatePercentage.replace('%','')), config15);
            // var config16 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge16", Number(data.data[16].immediatePercentage.replace('%','')), config16);
            // var config17 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge17", Number(data.data[17].immediatePercentage.replace('%','')), config17);
            // var config18 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge18", Number(data.data[18].immediatePercentage.replace('%','')), config18);
            // var config19 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge19", Number(data.data[19].immediatePercentage.replace('%','')), config19);
            // var config70 = liquidFillGaugeDefaultSettings();
            // loadLiquidFillGauge("fillgauge20", Number(data.data[20].immediatePercentage.replace('%','')), config70);

            // var config60 = liquidFillGaugeDefaultSettings();
            // config60.circleColor = "#FF7777";
            // config60.textColor = "#FF4444";
            // config60.waveTextColor = "#FFAAAA";
            // config60.waveColor = "#FFDDDD";
            // config60.circleThickness = 0.2;
            // config60.textVertPosition = 0.2;
            // config60.waveAnimateTime = 1000;
            // loadLiquidFillGauge("fillgauge60", Number(data.data[0].immediatePercentage.replace('%','')), config60);

            // var config70 = liquidFillGaugeDefaultSettings();
            // config70.circleColor = "#D4AB6A";
            // config70.textColor = "#553300";
            // config70.waveTextColor = "#805615";
            // config70.waveColor = "#AA7D39";
            // config70.circleThickness = 0.1;
            // config70.circleFillGap = 0.2;
            // config70.textVertPosition = 0.8;
            // config70.waveAnimateTime = 2000;
            // config70.waveHeight = 0.3;
            // config70.waveCount = 1;
            // loadLiquidFillGauge("fillgauge70", Number(data.data[2].immediatePercentage.replace('%','')), config70);

            // var config30 = liquidFillGaugeDefaultSettings();
            // config30.textVertPosition = 0.8;
            // config30.waveAnimateTime = 5000;
            // config30.waveHeight = 0.15;
            // config30.waveAnimate = false;
            // config30.waveOffset = 0.25;
            // config30.valueCountUp = false;
            // config30.displayPercent = false;
            // loadLiquidFillGauge("fillgauge30", Number(data.data[3].immediatePercentage.replace('%','')), config30);

            // var config40 = liquidFillGaugeDefaultSettings();
            // config40.circleThickness = 0.15;
            // config40.circleColor = "#808015";
            // config40.textColor = "#555500";
            // config40.waveTextColor = "#FFFFAA";
            // config40.waveColor = "#AAAA39";
            // config40.textVertPosition = 0.8;
            // config40.waveAnimateTime = 1000;
            // config40.waveHeight = 0.05;
            // config40.waveAnimate = true;
            // config40.waveRise = false;
            // config40.waveOffset = 0.25;
            // config40.textSize = 0.75;
            // config40.waveCount = 3;
            // loadLiquidFillGauge("fillgauge40", Number(data.data[14].immediatePercentage.replace('%','')), config40);

            // var config50 = liquidFillGaugeDefaultSettings();
            // config50.circleThickness = 0.4;
            // config50.circleColor = "#6DA398";
            // config50.textColor = "#0E5144";
            // config50.waveTextColor = "#6DA398";
            // config50.waveColor = "#246D5F";
            // config50.textVertPosition = 0.52;
            // config50.waveAnimateTime = 5000;
            // config50.waveHeight = 0;
            // config50.waveAnimate = false;
            // config50.waveCount = 2;
            // config50.waveOffset = 0.25;
            // config50.textSize = 1.2;
            // config50.minValue = 30;
            // config50.maxValue = 150
            // config50.displayPercent = false;
            // loadLiquidFillGauge("fillgauge50", Number(data.data[15].immediatePercentage.replace('%','')), config50);
      }
});
});
<|endoftext|>


<commit_before>/*
███████ ██████  ██ ████████  ██████  ██████
██      ██   ██ ██    ██    ██    ██ ██   ██
█████   ██   ██ ██    ██    ██    ██ ██████
██      ██   ██ ██    ██    ██    ██ ██   ██
███████ ██████  ██    ██     ██████  ██   ██
2016 ~ Mark Hillard | (mark@)markhillard.com
*/

$(document).ready(function () {
    // BEGIN INITIALIZE CODEMIRROR
    // ------------------------------
    // js code
    var editorJS = document.editor = CodeMirror.fromTextArea(jscode, {
        mode: 'javascript',
        lineNumbers: true,
        lineWrapping: false,
        theme: 'dracula',
        tabSize: 4,
        indentUnit: 4,
        autoCloseBrackets: true,
        scrollbarStyle: 'overlay',
        styleActiveLine: true
    });

    // css code
    var editorCSS = document.editor = CodeMirror.fromTextArea(csscode, {
        mode: 'css',
        lineNumbers: true,
        lineWrapping: false,
        theme: 'dracula',
        tabSize: 4,
        indentUnit: 4,
        autoCloseBrackets: true,
        scrollbarStyle: 'overlay',
        styleActiveLine: true
    });

    // html code
    var editorHTML = document.editor = CodeMirror.fromTextArea(htmlcode, {
        mode: 'text/html',
        lineNumbers: true,
        lineWrapping: false,
        theme: 'dracula',
        tabSize: 4,
        indentUnit: 4,
        autoCloseBrackets: true,
        scrollbarStyle: 'overlay',
        styleActiveLine: true
    });
    // ------------------------------
    // END INITIALIZE CODEMIRROR

    // BEGIN CODE LOADING
    // ------------------------------
    var html;

    // load js
    function loadJS() {
        var iframe = document.getElementById('preview');
        var js = editorJS.getValue();
        var preview;

        if (iframe.contentDocument) {
            preview = iframe.contentDocument;
        } else if (iframe.contentWindow) {
            preview = iframe.contentWindow.document;
        } else {
            preview = iframe.document;
        }

        preview.open();
        preview.write(html + '


<commit_before>'use strict';

/* Services */
var simpleArmoryServices = angular.module('simpleArmoryServices', ['ngResource']);

simpleArmoryServices.factory('LoginService', ['$location', '$log', '$http', '$q', function ($location, $log, $http, $q) {
	return {
	  getCharacter: function($routeParams) {
  		$log.log("Fetching " + $routeParams.character + " from server " + $routeParams.realm + "...");

  		// ## TMP #################################################################
  		// ## Good to make sure I'm honest, will remove before we go live
  		var deferred = $q.defer();
  		setTimeout(function() {
  			deferred.resolve('hello world');
  		}, 1);
  		// ########################################################################

  		var jsonp = $http.jsonp(
  				'http://' + $routeParams.region +'.battle.net/api/wow/character/' + $routeParams.realm + '/' + $routeParams.character +'?fields=pets,mounts,achievements,guild,reputation&jsonp=JSON_CALLBACK',
  				{ cache: true})
  			.error(getCharacterError)
  			.then(getCharacterComplete);

  		return $q.all([jsonp, deferred.promise]);

  		function getCharacterError(data, status, headers, config) {
  			$log.log("Trouble fetching character from battlenet");
			$location.url("error");
  		}

  		function getCharacterComplete(data, status, headers, config) {
  			data.data.region = $routeParams.region;

  			// add faction
  			data.data.faction = [,'A','H','A','A','H','H','A','H','H','H','Alliance',,,,,,,,,,,'A',,,'A','H'][data.data.race];

			return data.data;
  		}
	  }
	}
}]);

simpleArmoryServices.factory('BlizzardRealmService', ['$resource', '$q', '$log', function ($resource, $q, $log) {

	return {
		getRealms: function() {
	  		$log.log("Fetching server list for us...");
	  		var usPromise = $resource(
		  		'http://us.battle.net/api/wow/realm/status',
		  		{
		  			jsonp: 'JSON_CALLBACK',
		  		},
		  		{
      				get: { method:'JSONP', }
   			 	}).get().$promise;

	  		$log.log("Fetching server list for eu...");
	  		var euPromise = $resource(
		  		'http://eu.battle.net/api/wow/realm/status',
		  		{
		  			jsonp: 'JSON_CALLBACK',
		  		},
		  		{
      				get: { method:'JSONP', }
   			 	}).get().$promise;

	  		return $q.all([usPromise, euPromise]);
	  	}
	}
}]);

simpleArmoryServices.factory('AchievementsService', ['$http', '$log', 'LoginService', '$routeParams', function ($http, $log, loginService, $routeParams) {
	return {
		getAchievements: function() {
			return loginService.getCharacter({'region': $routeParams.region, 'realm':$routeParams.realm, 'character':$routeParams.character})
				.then(function(character) {
					return $http.get('data/achievements.json', { cache: true})
    	            	.then(function(data, status, headers, config) {
    	        			return parseAchievementObject(data.data.supercats, character[0]);
    	            	});
				})
		}
	}

	function parseAchievementObject(supercats, character) {
		var obj = {};
		var completed = {};
		var totalPossible = 0;
		var totalCompleted = 0;
		var totalFoS = 0;
		$log.log("Parsing achievements.json...");

		// Build up lookup for achievements that character has completed
		angular.forEach(character.achievements.achievementsCompleted, function(ach, index) {
			// hash the achievement and its timestamp
			completed[ach] = character.achievements.achievementsCompletedTimestamp[index];
		});

		// Lets parse out all the super categories and build out our structure
		angular.forEach(supercats, function(supercat) {
			var possibleCount = 0;
			var completedCount = 0;

			// Add the supercategory to the object, so we can do quick lookups on category
			obj[supercat.name] = {};
			obj[supercat.name]['categories'] = [];

			angular.forEach(supercat.cats, function(cat) {
				var myCat = {'name': cat.name, 'zones': []};

				angular.forEach(cat.zones, function(zone) {
					var myZone = {'name': zone.name, 'achievements': []};

					angular.forEach(zone.achs, function(ach) {
						var myAchievement = ach, added = false;
						myAchievement['completed'] = completed[ach.id];

						// Always add it if we've completed it, it should show up regardless if its avaiable
						if (completed[ach.id]) {
							added = true;
							myZone['achievements'].push(myAchievement);

							// if this is feats of strength then I want to keep a seperate count for that since its not a percentage thing
							if (supercat.name == "Feats of Strength") {
								totalFoS++;
							}
						}

						// Update counts proper
						if (supercat.name != "Feats of Strength" && ach.obtainable && (ach.side == '' || ach.side == character.faction)){
							possibleCount++;
							totalPossible++;

							if (completed[ach.id]) {
								completedCount++;
								totalCompleted++;
							}

							// if we haven't already added it, then this is one that should show up in the page of achievements
							// so add it
							if (!added) {
								myZone['achievements'].push(myAchievement);
							}
						}
					});

					if (myZone.achievements.length > 0) {
						myCat['zones'].push(myZone);
					}
				});

				// Add the category to the obj
				obj[supercat.name]['categories'].push(myCat);
			});

			obj[supercat.name]['possible'] = possibleCount;
			obj[supercat.name]['completed'] = completedCount;

			// Add the FoS count if this is the FoS
			if (supercat.name == "Feats of Strength") {
				obj[supercat.name]['foSTotal'] = totalFoS;
			}
    	});

		// Add totals
		obj['possible'] = totalPossible;
		obj['completed'] = totalCompleted;

		// Data object we expose externally
		return obj;
	}
}]);

simpleArmoryServices.factory('MountsAndPetsService', ['$http', '$log', 'LoginService', '$routeParams', function ($http, $log, loginService, $routeParams) {
	return {
		getItems: function(jsonFile, characterProperty, collectedId) {
			return loginService.getCharacter({'region': $routeParams.region, 'realm':$routeParams.realm, 'character':$routeParams.character})
				.then(function(character) {
					return $http.get('data/' + jsonFile + '.json', { cache: true, isArray:true })
    	            	.then(function(data, status, headers, config) {

							$log.log("Parsing " + jsonFile + ".json...");
    	        			return parseItemsObject(data.data, character[0], characterProperty, collectedId);
    	            	});
				})
		}
	}

	function parseItemsObject(categories, character, characterProperty, collectedId) {
		var obj = { 'categories': [] };
		var collected = {};
		var totalCollected = 0;
		var totalPossible = 0;

		// Build up lookup for items that character has
		angular.forEach(character[characterProperty].collected, function(item, index) {
			collected[item[collectedId]] = item;
			totalCollected++;
		});

		// Lets parse out all the categories and build out our structure
		angular.forEach(categories, function(category) {

			// Add the item category to the item list
			var cat = { 'name': category.name, 'subCategories': [] };
			obj.categories.push(cat);

			angular.forEach(category.subcats, function(subCategory) {

				var subCat = { "name": subCategory.name, "items":[] };

				angular.forEach(subCategory.items, function(item) {

					var itm = item;

					// fix spellid typo
					itm.spellId = item.spellid;
					delete itm.spellid;

					itm.collected = collected[itm[collectedId]] != null;

					// Need to some extra work to determine what our url should be
                    // By default we'll use a spell id
                    var link = "spell="+itm.spellId;

                    // If the item id is available lets use that
                    if (item.itemId) {
                        link = "item="+item.itemId;
                    } else if (item.allianceId && character.faction == 'A') {
                        link = "item="+item.allianceId;
                    } else if (item.hordeId && character.faction == 'H') {
                        link = "item="+item.hordeId;
                    } else if (item.creatureId) {
                        link = "npc="+item.creatureId;
                    }

					itm.link = link;

					// What would cause it to show up in the UI:
					//	1) You have the item
					//  2) Its still obtainable
					//	3) You meet the class restriction
					//  4) You meet the race restriction
                    var hasthis = itm.collected;
					var showthis = (hasthis || item.obtainable);
                    if (item.allowableRaces.length > 0)
                    {
                    	var foundRace = false;
                    	angular.forEach(item.allowableRaces, function(race) {
							if (race == character.race) {
								foundRace = true;
							}
						});

						if (!foundRace) {
							showthis = false;
						}
                    }

					if (item.allowableClasses && item.allowableClasses.length > 0)
                    {
                    	var foundClass = false;
                    	angular.forEach(item.allowableClasses, function(allowedClass) {
							if (allowedClass == character.class) {
								foundClass = true;
							}
						});

						if (!foundClass) {
							showthis = false;
						}
                    }

					if (showthis) {
						subCat.items.push(itm);
						totalPossible++;
					}
				});

				if (subCat.items.length > 0) {
					cat.subCategories.push(subCat);
				}
			});
    	});

		// Add totals
		obj['collected'] = totalCollected;
		obj['possible'] = totalPossible;

		// Data object we expose externally
		return obj;
	}
}]);
<commit_msg>augment pet info<commit_after>'use strict';

/* Services */
var simpleArmoryServices = angular.module('simpleArmoryServices', ['ngResource']);

simpleArmoryServices.factory('LoginService', ['$location', '$log', '$http', '$q', function ($location, $log, $http, $q) {
	return {
	  getCharacter: function($routeParams) {
  		$log.log("Fetching " + $routeParams.character + " from server " + $routeParams.realm + "...");

  		// ## TMP #################################################################
  		// ## Good to make sure I'm honest, will remove before we go live
  		var deferred = $q.defer();
  		setTimeout(function() {
  			deferred.resolve('hello world');
  		}, 1);
  		// ########################################################################

  		var jsonp = $http.jsonp(
  				'http://' + $routeParams.region +'.battle.net/api/wow/character/' + $routeParams.realm + '/' + $routeParams.character +'?fields=pets,mounts,achievements,guild,reputation&jsonp=JSON_CALLBACK',
  				{ cache: true})
  			.error(getCharacterError)
  			.then(getCharacterComplete);

  		return $q.all([jsonp, deferred.promise]);

  		function getCharacterError(data, status, headers, config) {
  			$log.log("Trouble fetching character from battlenet");
			$location.url("error");
  		}

  		function getCharacterComplete(data, status, headers, config) {
  			data.data.region = $routeParams.region;

  			// add faction
  			data.data.faction = [,'A','H','A','A','H','H','A','H','H','H','Alliance',,,,,,,,,,,'A',,,'A','H'][data.data.race];

			return data.data;
  		}
	  }
	}
}]);

simpleArmoryServices.factory('BlizzardRealmService', ['$resource', '$q', '$log', function ($resource, $q, $log) {

	return {
		getRealms: function() {
	  		$log.log("Fetching server list for us...");
	  		var usPromise = $resource(
		  		'http://us.battle.net/api/wow/realm/status',
		  		{
		  			jsonp: 'JSON_CALLBACK',
		  		},
		  		{
      				get: { method:'JSONP', }
   			 	}).get().$promise;

	  		$log.log("Fetching server list for eu...");
	  		var euPromise = $resource(
		  		'http://eu.battle.net/api/wow/realm/status',
		  		{
		  			jsonp: 'JSON_CALLBACK',
		  		},
		  		{
      				get: { method:'JSONP', }
   			 	}).get().$promise;

	  		return $q.all([usPromise, euPromise]);
	  	}
	}
}]);

simpleArmoryServices.factory('AchievementsService', ['$http', '$log', 'LoginService', '$routeParams', function ($http, $log, loginService, $routeParams) {
	return {
		getAchievements: function() {
			return loginService.getCharacter({'region': $routeParams.region, 'realm':$routeParams.realm, 'character':$routeParams.character})
				.then(function(character) {
					return $http.get('data/achievements.json', { cache: true})
    	            	.then(function(data, status, headers, config) {
    	        			return parseAchievementObject(data.data.supercats, character[0]);
    	            	});
				})
		}
	}

	function parseAchievementObject(supercats, character) {
		var obj = {};
		var completed = {};
		var totalPossible = 0;
		var totalCompleted = 0;
		var totalFoS = 0;
		$log.log("Parsing achievements.json...");

		// Build up lookup for achievements that character has completed
		angular.forEach(character.achievements.achievementsCompleted, function(ach, index) {
			// hash the achievement and its timestamp
			completed[ach] = character.achievements.achievementsCompletedTimestamp[index];
		});

		// Lets parse out all the super categories and build out our structure
		angular.forEach(supercats, function(supercat) {
			var possibleCount = 0;
			var completedCount = 0;

			// Add the supercategory to the object, so we can do quick lookups on category
			obj[supercat.name] = {};
			obj[supercat.name]['categories'] = [];

			angular.forEach(supercat.cats, function(cat) {
				var myCat = {'name': cat.name, 'zones': []};

				angular.forEach(cat.zones, function(zone) {
					var myZone = {'name': zone.name, 'achievements': []};

					angular.forEach(zone.achs, function(ach) {
						var myAchievement = ach, added = false;
						myAchievement['completed'] = completed[ach.id];

						// Always add it if we've completed it, it should show up regardless if its avaiable
						if (completed[ach.id]) {
							added = true;
							myZone['achievements'].push(myAchievement);

							// if this is feats of strength then I want to keep a seperate count for that since its not a percentage thing
							if (supercat.name == "Feats of Strength") {
								totalFoS++;
							}
						}

						// Update counts proper
						if (supercat.name != "Feats of Strength" && ach.obtainable && (ach.side == '' || ach.side == character.faction)){
							possibleCount++;
							totalPossible++;

							if (completed[ach.id]) {
								completedCount++;
								totalCompleted++;
							}

							// if we haven't already added it, then this is one that should show up in the page of achievements
							// so add it
							if (!added) {
								myZone['achievements'].push(myAchievement);
							}
						}
					});

					if (myZone.achievements.length > 0) {
						myCat['zones'].push(myZone);
					}
				});

				// Add the category to the obj
				obj[supercat.name]['categories'].push(myCat);
			});

			obj[supercat.name]['possible'] = possibleCount;
			obj[supercat.name]['completed'] = completedCount;

			// Add the FoS count if this is the FoS
			if (supercat.name == "Feats of Strength") {
				obj[supercat.name]['foSTotal'] = totalFoS;
			}
    	});

		// Add totals
		obj['possible'] = totalPossible;
		obj['completed'] = totalCompleted;

		// Data object we expose externally
		return obj;
	}
}]);

simpleArmoryServices.factory('MountsAndPetsService', ['$http', '$log', 'LoginService', '$routeParams', function ($http, $log, loginService, $routeParams) {
	return {
		getItems: function(jsonFile, characterProperty, collectedId) {
			return loginService.getCharacter({'region': $routeParams.region, 'realm':$routeParams.realm, 'character':$routeParams.character})
				.then(function(character) {
					return $http.get('data/' + jsonFile + '.json', { cache: true, isArray:true })
    	            	.then(function(data, status, headers, config) {

							$log.log("Parsing " + jsonFile + ".json...");
    	        			return parseItemsObject(data.data, character[0], characterProperty, collectedId);
    	            	});
				})
		}
	}

	function parseItemsObject(categories, character, characterProperty, collectedId) {
		var obj = { 'categories': [] };
		var collected = {};
		var totalCollected = 0;
		var totalPossible = 0;

		// Build up lookup for items that character has
		angular.forEach(character[characterProperty].collected, function(item, index) {
			collected[item[collectedId]] = item;
			totalCollected++;
		});

		// Lets parse out all the categories and build out our structure
		angular.forEach(categories, function(category) {

			// Add the item category to the item list
			var cat = { 'name': category.name, 'subCategories': [] };
			obj.categories.push(cat);

			angular.forEach(category.subcats, function(subCategory) {

				var subCat = { "name": subCategory.name, "items":[] };

				angular.forEach(subCategory.items, function(item) {

					var itm = item;

					// fix spellid typo
					itm.spellId = item.spellid;
					delete itm.spellid;

					if (collected[itm[collectedId]]) {
						var fullItem = collected[itm[collectedId]];
						itm.collected =  true;

						// Add pet info if we have it
						if (fullItem.qualityId) {
							var quality = "";
							switch(fullItem.qualityId)
                            {
                                case 0:
                                	quality = "poor";
                                    break;
                                case 1:
                                    quality = "common";
                                    break;
                                case 2:
                                    quality = "uncommon";
                                    break;
                                case 3:
                                    quality = "rare";
                                    break;
								case 4:
                                    quality = "epic";
                                    break;
								case 5:
                                    quality = "legendary";
                                    break;
                            }

                            itm.quality = quality;
						}

						if (fullItem.stats) {
							if (fullItem.stats.breedId) {
								var breed = "";
								switch(fullItem.stats.breedId)
	                            {
	                                case 4:
	                                case 14:
	                                    breed = "P/P";
	                                    break;
	                                case 5:
	                                case 15:
	                                    breed = "S/S";
	                                    break;
	                                case 6:
	                                case 16:
	                                    breed = "H/H";
	                                    break;
	                                case 7:
	                                case 17:
	                                    breed = "H/P";
	                                    break;
	                                case 8:
	                                case 18:
	                                    breed = "P/S";
	                                    break;
	                                case 9:
	                                case 19:
	                                    breed = "H/S";
	                                    break;
	                                case 10:
	                                case 20:
	                                    breed = "P/B";
	                                    break;
	                                case 11:
	                                case 21:
	                                    breed = "S/B";
	                                    break;
	                                case 12:
	                                case 22:
	                                    breed = "H/B";
	                                    break;
	                                case 3:
	                                case 13:
	                                    breed = "B/B";
	                                    break;
	                            }

	                            itm.breed = breed;
							}

							itm.level = fullItem.stats.level;
						}
					}

					// Need to some extra work to determine what our url should be
                    // By default we'll use a spell id
                    var link = "spell="+itm.spellId;

                    // If the item id is available lets use that
                    if (item.itemId) {
                        link = "item="+item.itemId;
                    } else if (item.allianceId && character.faction == 'A') {
                        link = "item="+item.allianceId;
                    } else if (item.hordeId && character.faction == 'H') {
                        link = "item="+item.hordeId;
                    } else if (item.creatureId) {
                        link = "npc="+item.creatureId;
                    }

					itm.link = link;

					// What would cause it to show up in the UI:
					//	1) You have the item
					//  2) Its still obtainable
					//	3) You meet the class restriction
					//  4) You meet the race restriction
                    var hasthis = itm.collected;
					var showthis = (hasthis || item.obtainable);
                    if (item.allowableRaces.length > 0)
                    {
                    	var foundRace = false;
                    	angular.forEach(item.allowableRaces, function(race) {
							if (race == character.race) {
								foundRace = true;
							}
						});

						if (!foundRace) {
							showthis = false;
						}
                    }

					if (item.allowableClasses && item.allowableClasses.length > 0)
                    {
                    	var foundClass = false;
                    	angular.forEach(item.allowableClasses, function(allowedClass) {
							if (allowedClass == character.class) {
								foundClass = true;
							}
						});

						if (!foundClass) {
							showthis = false;
						}
                    }

					if (showthis) {
						subCat.items.push(itm);
						totalPossible++;
					}
				});

				if (subCat.items.length > 0) {
					cat.subCategories.push(subCat);
				}
			});
    	});

		// Add totals
		obj['collected'] = totalCollected;
		obj['possible'] = totalPossible;

		// Data object we expose externally
		return obj;
	}
}]);
<|endoftext|>


<commit_before>//Gmap3 currently use
$(document).on('pageshow','#home',function(event){
    /* Show map on screen */

   //Bounds for Abel Tasman Park
   var strictBounds = new google.maps.LatLngBounds(
   //The WestSouth point and The NorthEast point for the boundary area
   new google.maps.LatLng(-41.008678,172.814941),
   new google.maps.LatLng(-40.777178,173.086853)
   ),

   lastValidCenter = strictBounds.getCenter();

   var $map = $("#map");

   $map.gmap3({
    map: {
        options: {
                // center: [-40.9382511,172.9681819],
                center: [-40.930, 173.0509],
                // center: [-41.24437,174.7618546],

                zoom: 12,
                minZoom: 11,
                disableDefaultUI: true,

                mapTypeControlOptions: {
                    mapTypeIds: ["style1"]
                },
                mapTypeId: "style1"
            },//end of options

            events: {
                //For center the boundary area
                /*center_changed: function(map){
                    if(strictBounds.contains(map.getCenter())){
                            //still with valid bounds, so save the last vaild position
                            lastValidCenter = map.getCenter();
                            return;
                        }
                            //not vaild anymore
                            map.panTo(lastValidCenter);
                        }*/
                },//end of events

        },//end of map

        styledmaptype:{
            //This style is number 1 style
            id: "style1",
            options:{
            //COZ we do not want to show the style map button but we apply name to style 1
            name: "Style 1"
        },

        styles: [
        {
            "featureType": "water",
            "elementType": "geometry.fill",
            "stylers": [
            { "hue": "#00ffff" },
            { "color": "#1b8080" }
            ]
        },{
            "featureType": "road",
            "elementType": "geometry.fill",
            "stylers": [
            { "color": "#F24C32" },
            { "weight": 1 }
            ]
        }
        ]
        }//End of styledmaptype
        });//end of gmap3

/* show all categories */
$("#allButton").bind("click", function (event, ui) {
    var url = "http://intense-harbor-6396.herokuapp.com/category/all";
    // var url = "http://localhost:3000/all";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    });
});

/* Show only animals */
$("#animalButton").click(function () {
    var url = "http://intense-harbor-6396.herokuapp.com/category/animals";
    // var url = "http://localhost:3000/animals";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* show only plants */
$("#plantButton").bind("click", function () {
    var url = "http://intense-harbor-6396.herokuapp.com/category/plants";
    // var url = "http://localhost:3000/plants";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* show only other */
$("#otherButton").bind("click", function (event, ui) {
    var url = "http://intense-harbor-6396.herokuapp.com/category/other";
    // var url = "http://localhost:3000/other";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* Plot data onto map */
function mapStuff(data) {
    // loop through data
    $.each(data, function (key, val) {

        var animalIcon = "img/wildlife.png";
        var plantIcon = "img/palm-tree-export.png";
        var otherIcon = "img/panoramicview.png";

        if (val.category == "Plants") {
            icon = plantIcon;
        }

        else if (val.category == "Other") {
            icon = otherIcon;
        }

        else {
            icon = animalIcon;
        }

        $map.gmap3({
            marker: {
                values: [{
                    address: val.gps,
                    options: {
                        icon: icon,
                        animation: google.maps.Animation.DROP,
                    },
                    events: {
                        click: function (marker, event, context) {
                            var map = $(this).gmap3("get"),
                            infowindow = $(this).gmap3({
                                get: {
                                    name: "infowindow"
                                }
                            });
                            if (infowindow) {
                              infowindow.open(map, marker);
                              infowindow.setContent("
" + val.title + "

" + val.imagedesc + "
");
                          }
                          else {
                            $(this).gmap3({
                                infowindow: {
                                    address: val.gps,
                                    options: {
                                        maxWidth: 200,
                                        // content: '
'+val.content+'
',
                                        // content: val.content,
                                        content: "
" + val.title + "

" + val.imagedesc + "
",
                                        offset: {
                                            y: -32,
                                            x: 12
                                        }
                                    }
                                }
                            });
                        }
                    },
                    // close current infowindow
                    closeclick: function () {
                        var infowindow = $(this).gmap3({
                            get: {
                                name: "infowindow"
                            }
                        });
                        if (infowindow) {
                            infowindow.close();
                        }
                    }
                } // end of events options
            }]
        } // end of marker
    });
    }); //end of loop
    } //end of mapStuff function
});<commit_msg>nothing much<commit_after>//Gmap3 currently use
$(document).on('pageshow','#home',function(event){
    /* Show map on screen */

   //Bounds for Abel Tasman Park
   var strictBounds = new google.maps.LatLngBounds(
   //The WestSouth point and The NorthEast point for the boundary area
   new google.maps.LatLng(-41.008678,172.814941),
   new google.maps.LatLng(-40.777178,173.086853)
   ),

   lastValidCenter = strictBounds.getCenter();

   var $map = $("#map");

   $map.gmap3({
    map: {
        options: {
                // center: [-40.9382511,172.9681819],
                center: [-40.930, 173.0509],
                // center: [-41.24437,174.7618546],

                zoom: 12,
                minZoom: 11,
                disableDefaultUI: true,

                mapTypeControlOptions: {
                    mapTypeIds: ["style1"]
                },
                mapTypeId: "style1"
            },//end of options

            events: {
                //For center the boundary area
                /*center_changed: function(map){
                    if(strictBounds.contains(map.getCenter())){
                            //still with valid bounds, so save the last vaild position
                            lastValidCenter = map.getCenter();
                            return;
                        }
                            //not vaild anymore
                            map.panTo(lastValidCenter);
                        }*/
                },//end of events

        },//end of map

        styledmaptype:{
            //This style is number 1 style
            id: "style1",
            options:{
            //COZ we do not want to show the style map button but we apply name to style 1
            name: "Style 1"
        },

        styles: [
        {
            "featureType": "water",
            "elementType": "geometry.fill",
            "stylers": [
            { "hue": "#00ffff" },
            { "color": "#1b8080" }
            ]
        },{
            "featureType": "road",
            "elementType": "geometry.fill",
            "stylers": [
            { "color": "#F24C32" },
            { "weight": 1 }
            ]
        }
        ]
        }//End of styledmaptype
        });//end of gmap3

/* show all categories */
$("#allButton").bind("click", function (event, ui) {
    var url = "http://intense-harbor-6396.herokuapp.com/category/all";
    // var url = "http://localhost:3000/all";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    });
});

/* Show only animals */
$("#animalButton").click(function () {
    var url = "http://intense-harbor-6396.herokuapp.com/category/animals";
    // var url = "http://localhost:3000/animals";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* show only plants */
$("#plantButton").bind("click", function () {
    var url = "http://intense-harbor-6396.herokuapp.com/category/plants";
    // var url = "http://localhost:3000/plants";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* show only other */
$("#otherButton").bind("click", function (event, ui) {
    var url = "http://intense-harbor-6396.herokuapp.com/category/other";
    // var url = "http://localhost:3000/other";
    var data = [];
    $map.gmap3("clear");

    $.get(url, function (gps) {
        data = gps;
        mapStuff(data)
    })
});

/* Plot data onto map */
function mapStuff(data) {
    // loop through data
    $.each(data, function (key, val) {

        var animalIcon = "img/wildlife.png";
        var plantIcon = "img/palm-tree-export.png";
        var otherIcon = "img/panoramicview.png";

        if (val.category == "Plants") {
            icon = plantIcon;
        }

        else if (val.category == "Other") {
            icon = otherIcon;
        }

        else {
            icon = animalIcon;
        }

        $map.gmap3({
            marker: {
                values: [{
                    address: val.gps,
                    options: {
                        icon: icon,
                        animation: google.maps.Animation.DROP,
                    },
                    events: {
                        click: function (marker, event, context) {
                            var map = $(this).gmap3("get"),
                            infowindow = $(this).gmap3({
                                get: {
                                    name: "infowindow"
                                }
                            });
                            if (infowindow) {
                              infowindow.open(map, marker);
                              infowindow.setContent("
" + val.title + "

" + val.imagedesc + "
");
                          }
                          else {
                            $(this).gmap3({
                                infowindow: {
                                    address: val.gps,
                                    options: {
                                        maxWidth: 200,
                                        // content: '
'+val.content+'
',
                                        // content: val.content,
                                        content: "
" + val.title + "

" + val.imagedesc + "
",
                                        offset: {
                                            y: -32,
                                            x: 12
                                        }
                                    }
                                }
                            });
                        }
                    },
                    // close current infowindow
                    closeclick: function () {
                        var infowindow = $(this).gmap3({
                            get: {
                                name: "infowindow"
                            }
                        });
                        if (infowindow) {
                            infowindow.close();
                        }
                    }
                } // end of events options
            }]
        } // end of marker
    });
    }); //end of loop
    } //end of mapStuff function
});<|endoftext|>


<commit_before>var play_state = {

    /**
     * Creates the game world using the preloaded sprites
     *
     * @return {undefined}
     */
    create: function() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.add.sprite(0, 0, 'sky');

        this.platforms = game.add.group();
        this.platforms.enableBody = true;

        this.createFloor();

        this.createLargePlatform(600, 300);
        this.createSmallPlatform(230, 240);
        this.createSmallPlatform(100, 400);

        // Stars to collect
        this.stars = game.add.group();
        this.stars.enableBody = true;

        this.starBurst();

        // My player
        this.player = game.add.sprite(32, game.world.height - 150, 'dude');
        this.game.physics.arcade.enable(this.player);

        // Giving him some bounce
        this.player.body.bounce.y = 0.4;
        this.player.body.gravity.y = 300;
        this.player.body.collideWorldBounds = true;

        // He's ALIVE (animation)!
        // Note: Lookup flipping sprites
        this.player.animations.add('left', [0, 1, 2, 3], 10, true);
        this.player.animations.add('right', [5, 6, 7, 8], 10, true);

        // The crazy sphere
        this.sphere = game.add.sprite(32, game.world.height - 250, 'sphere');
        this.game.physics.enable(this.sphere, Phaser.Physics.ARCADE);
        this.sphere.body.velocity.x = 100;
        this.sphere.body.velocity.y = 100;
        this.sphere.body.collideWorldBounds = true;
        this.sphere.body.bounce.set(1);

        this.cursors = game.input.keyboard.createCursorKeys();

        this.scoreText = game.add.text(16, 16, 'score: 0', {fontSize: '32px', fill: '#000'});

        this.music = game.add.audio('awesome');
        this.music.play('', 0, 1, true);
    },

    /**
     * Game drawhandler that gets updated at regular intervals
     * @return {undefined}
     */
    update: function() {
        this.game.physics.arcade.collide(this.player, this.platforms);

        // We need this or the stars just go falling through the floor - funny but not useful
        this.game.physics.arcade.collide(this.stars, this.platforms);

        // Bouncy sphere
        this.game.physics.arcade.collide(this.sphere, this.platforms);
        this.game.physics.arcade.collide(this.sphere, this.player, this.sphereTouch, null, this);

        // Make the guy stay still when nowts being pressed
        this.player.body.velocity.x = 0;

        // Enables player to collect stars "collectStar" is the callback function
        this.game.physics.arcade.overlap(this.player, this.stars, this.collectStar, null, this);

        // The sphere will start eating stars after it has been hit twice
        this.game.physics.arcade.collide(this.sphere, this.stars, this.eatStar, null, this);

        // Sorting out left, right and stop
        if (this.cursors.left.isDown){
            this.player.body.velocity.x = -150;
            this.player.animations.play('left');
        }else if(this.cursors.right.isDown){
            this.player.body.velocity.x = 150;
            this.player.animations.play('right');
        }else{
            this.player.animations.stop();
            this.player.frame = 4;
        }

        // JUMP!
        if(this.cursors.up.isDown && this.player.body.touching.down){
            this.player.body.velocity.y = -350;
        }

    },

    /**
     * Event handler for when the player touches a star - collecting it.
     * Will update the score globally and the scoreboard on screen.
     *
     * @param  {object} player  sprite
     * @param  {object} star    sprite
     * @return {undefined}
     */
    collectStar: function(player, star){
        star.kill();

        score++;
        if (score >= 10) {
            this.game.state.start('win');
        }
        this.scoreText.text = 'Score: ' + score;
    },

    /**
     * Event handler for when the sphere/orb touches a star. Checks if its been
     *  hit by player more than 5 times and if it has then it will eat the
     * star, turning red to show its blood thirsty nature.
     *
     * @param  {object} sphere sprite
     * @param  {object} star   sprite
     * @return {undefined}
     */
    eatStar: function(sphere, star){
        if(sphereHit >= 5){
            sphere.tint = 0xff0000;
            star.kill();
            console.log('Eating stars?');
            score--;
            this.scoreText.text = 'Score: ' + score;
        }
    },

    /**
     * Event handler for when the sphere/globe is touched by player. This will
     * cause a burst of stars and increment sphereHit counter.
     *
     * @param  {object} sphere sprite
     * @param  {object} player sprite
     * @return {undefined}
     */
    sphereTouch: function(sphere, player){
        sphereHit++;
        this.starBurst();
    },

    /**
     * Drops 12 stars from the top of the level screen
     *
     * @return {undefined}
     */
    starBurst: function(){
        // Stars to collect
        for (var i = 0; i < 12; i++) {
            this.star = this.stars.create(i * 70, 0, 'star');
            // Let them fall is a lot easier than placing them so as to avoid being
            // put inside objects I guess?
            this.star.body.gravity.y = 300;

            this.star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }
    },

    createFloor: function() {
        var i = 0;
        for(i=0;i<7;i++){
            this.ground = this.platforms.create((128*i), game.world.height - 64, 'ground1');
            this.ground.scale.setTo(1, 1);
            this.ground.body.immovable = true;
        }
    },

    createSmallPlatform: function(x, y) {
        this.ledge = this.platforms.create(x, y, 'platforml');
        this.ledge.scale.setTo(0.5, 0.5);
        this.ledge.body.immovable = true;

        this.ledge = this.platforms.create(x+60, y, 'platformr');
        this.ledge.scale.setTo(0.5, 0.5);
        this.ledge.body.immovable = true;
    },

    createLargePlatform: function(x, y) {
        this.ledge = this.platforms.create(x, y, 'platform');
        this.ledge.scale.setTo(0.5, 0.5);
        this.ledge.body.immovable = true;

        this.ledge = this.platforms.create((x+60), y, 'platformr');
        this.ledge.scale.setTo(0.5, 0.5);
        this.ledge.body.immovable = true;

        this.ledge = this.platforms.create((x-60), y, 'platforml');
        this.ledge.scale.setTo(0.5, 0.5);
        this.ledge.body.immovable = true;
    }
};<commit_msg>setScaleAndSolid method creted<commit_after>var play_state = {

    /**
     * Creates the game world using the preloaded sprites
     *
     * @return {undefined}
     */
    create: function() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.add.sprite(0, 0, 'sky');

        this.platforms = game.add.group();
        this.platforms.enableBody = true;

        this.createFloor();

        this.createLargePlatform(600, 300);
        this.createSmallPlatform(230, 240);
        this.createSmallPlatform(100, 400);

        // Stars to collect
        this.stars = game.add.group();
        this.stars.enableBody = true;

        this.starBurst();

        // My player
        this.player = game.add.sprite(32, game.world.height - 150, 'dude');
        this.game.physics.arcade.enable(this.player);

        // Giving him some bounce
        this.player.body.bounce.y = 0.4;
        this.player.body.gravity.y = 300;
        this.player.body.collideWorldBounds = true;

        // He's ALIVE (animation)!
        // Note: Lookup flipping sprites
        this.player.animations.add('left', [0, 1, 2, 3], 10, true);
        this.player.animations.add('right', [5, 6, 7, 8], 10, true);

        // The crazy sphere
        this.sphere = game.add.sprite(32, game.world.height - 250, 'sphere');
        this.game.physics.enable(this.sphere, Phaser.Physics.ARCADE);
        this.sphere.body.velocity.x = 100;
        this.sphere.body.velocity.y = 100;
        this.sphere.body.collideWorldBounds = true;
        this.sphere.body.bounce.set(1);

        this.cursors = game.input.keyboard.createCursorKeys();

        this.scoreText = game.add.text(16, 16, 'score: 0', {fontSize: '32px', fill: '#000'});

        this.music = game.add.audio('awesome');
        this.music.play('', 0, 1, true);
    },

    /**
     * Game drawhandler that gets updated at regular intervals
     * @return {undefined}
     */
    update: function() {
        this.game.physics.arcade.collide(this.player, this.platforms);

        // We need this or the stars just go falling through the floor - funny but not useful
        this.game.physics.arcade.collide(this.stars, this.platforms);

        // Bouncy sphere
        this.game.physics.arcade.collide(this.sphere, this.platforms);
        this.game.physics.arcade.collide(this.sphere, this.player, this.sphereTouch, null, this);

        // Make the guy stay still when nowts being pressed
        this.player.body.velocity.x = 0;

        // Enables player to collect stars "collectStar" is the callback function
        this.game.physics.arcade.overlap(this.player, this.stars, this.collectStar, null, this);

        // The sphere will start eating stars after it has been hit twice
        this.game.physics.arcade.collide(this.sphere, this.stars, this.eatStar, null, this);

        // Sorting out left, right and stop
        if (this.cursors.left.isDown){
            this.player.body.velocity.x = -150;
            this.player.animations.play('left');
        }else if(this.cursors.right.isDown){
            this.player.body.velocity.x = 150;
            this.player.animations.play('right');
        }else{
            this.player.animations.stop();
            this.player.frame = 4;
        }

        // JUMP!
        if(this.cursors.up.isDown && this.player.body.touching.down){
            this.player.body.velocity.y = -350;
        }

    },

    /**
     * Event handler for when the player touches a star - collecting it.
     * Will update the score globally and the scoreboard on screen.
     *
     * @param  {object} player  sprite
     * @param  {object} star    sprite
     * @return {undefined}
     */
    collectStar: function(player, star){
        star.kill();

        score++;
        if (score >= 10) {
            this.game.state.start('win');
        }
        this.scoreText.text = 'Score: ' + score;
    },

    /**
     * Event handler for when the sphere/orb touches a star. Checks if its been
     *  hit by player more than 5 times and if it has then it will eat the
     * star, turning red to show its blood thirsty nature.
     *
     * @param  {object} sphere sprite
     * @param  {object} star   sprite
     * @return {undefined}
     */
    eatStar: function(sphere, star){
        if(sphereHit >= 5){
            sphere.tint = 0xff0000;
            star.kill();
            console.log('Eating stars?');
            score--;
            this.scoreText.text = 'Score: ' + score;
        }
    },

    /**
     * Event handler for when the sphere/globe is touched by player. This will
     * cause a burst of stars and increment sphereHit counter.
     *
     * @param  {object} sphere sprite
     * @param  {object} player sprite
     * @return {undefined}
     */
    sphereTouch: function(sphere, player){
        sphereHit++;
        this.starBurst();
    },

    /**
     * Drops 12 stars from the top of the level screen
     *
     * @return {undefined}
     */
    starBurst: function(){
        // Stars to collect
        for (var i = 0; i < 12; i++) {
            this.star = this.stars.create(i * 70, 0, 'star');
            // Let them fall is a lot easier than placing them so as to avoid being
            // put inside objects I guess?
            this.star.body.gravity.y = 300;

            this.star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }
    },

    createFloor: function() {
        var i = 0;
        for(i=0;i<7;i++){
            this.ground = this.platforms.create((128*i), game.world.height - 64, 'ground1');
            this.ground.scale.setTo(1, 1);
            this.ground.body.immovable = true;
        }
    },

    createSmallPlatform: function(x, y) {
        this.ledge = this.platforms.create(x, y, 'platforml');
        this.setScaleAndSolid(this.ledge);

        this.ledge = this.platforms.create(x+60, y, 'platformr');
        this.setScaleAndSolid(this.ledge);
    },

    createLargePlatform: function(x, y) {
        this.ledge = this.platforms.create(x, y, 'platform');
        this.setScaleAndSolid(this.ledge);
        this.ledge = this.platforms.create((x+60), y, 'platformr');
        this.setScaleAndSolid(this.ledge);
        this.ledge = this.platforms.create((x-60), y, 'platforml');
        this.setScaleAndSolid(this.ledge);
    },

    setScaleAndSolid: function(thing, scale){
        if(!scale){
            scale = 0.5;
        }
        thing.scale.setTo(scale, scale);
        thing.body.immovable = true;
    }
};<|endoftext|>