<commit_before>"use strict"

/* ********************************************************************************** */
/*										PROJECT     								  */
/* ********************************************************************************** */

var project;

function Project(name, namespace){
	this.name = name;
	this.namespace = namespace;
}

$( "#addProject" ).click(function(){
	if($( "#projectName").val() != '' && $( "#projectNamespace").val() != ''){
		$('#projectAlert').css('display', 'none');
		addProject($( "#projectName").val(),$( "#projectNamespace").val());
		$( "#profilePanel" ).css("display","block");
		$( "#generateXML" ).css("display","block");
	}else{
		$('#projectAlert').css('display', 'block');
	}
});

function addProject(projectName, projectNamespace){
	project = new Project(projectName,projectNamespace);
	generateXMLFromArray();
	console.log(project);
}

/* ********************************************************************************** */
/*										  PROFILE     								  */
/* ********************************************************************************** */

var profiles = [];

function Profile(name){
	this.name = name;
}

$( "#addProfile" ).click(function(){
	if($( "#profileName").val() != ''){
		$('#profileAlert').css('display', 'none');
		addProfile($( "#profileName").val());

		$( "#viewPanel" ).css("display","block");
		$( "#dragArea" ).css("display","block");

	}else{
		$('#profileAlert').css('display', 'block');
	}
});

function addProfile(profileName){
	profiles.push(new Profile(profileName));
	$( "#profileList" ).append("
" + profileName + "
");
	generateXMLFromArray();
	$( "#profileName").val('');
	console.log(profiles);
}

/* ********************************************************************************** */
/*										  VIEW       								  */
/* ********************************************************************************** */
var viewCounter = 0;
var views = [];

function View(id, name) {
	this.id = id;
	this.name = name;
	this.cordX = 5;
	this.cordY = 5;
	this.attributes = [];
}

$( "#addView" ).click(function() {
	if($( "#viewName").val() != ''){
		$('#viewAlert').css('display', 'none');
		addView($( "#viewName").val());
	}else{
		$('#viewAlert').css('display', 'block');
	}
});

function addView(viewName){

	viewCounter++;
	viewName = viewName;

	var singleView = new View(viewCounter,viewName);

	views.push(singleView);

	console.log(views);
	console.log("CLICKED ADD VIEW");

	$( ".dragContainer" ).append( "

" + viewName + "<button  type='button' id='" + viewName + "' onClick=removeView(\"" + viewName + "\")>x</button>

<button type='button' class='opener' id='" + viewName + "'  onClick=openAttributeDialog(\"" + viewName + "\")>+</button>

 Viewnr:" + viewCounter + "

" );

	generateXMLFromArray();

	$( function() {
		  $( ".draggable" ).draggable({
		  	  containment:"parent",
			  drag: function() {
				  var $this = $(this);
            	  var thisPos = $this.position();
				  var parentPos = $this.parent().position();

				  var x = thisPos.left - parentPos.left;
				  var y = thisPos.top - parentPos.top;

				  //console.log(x + ", " + y);

			  },
			  stop: function(event, ui){
			      var $this = $(this);
				  var id = $(this).attr("id");
            	  var thisPos = $this.position();
				  var parentPos = $this.parent().position();

				  var x = thisPos.left - parentPos.left;
				  var y = thisPos.top - parentPos.top;
				  console.log("Position x => " + x + " && Position y => " + y);
				  var viewIndex = getViewID(id)-1;
				  views[viewIndex].cordX = x;
				  views[viewIndex].cordY = y;
			  }
		  });
		  } );
}
function getViewID(viewName){
	for(var i = 0; i < views.length; i++){
		if(views[i].name === viewName){
			return views[i].id;
		}
	}
	return -1;
}

function getViewArrayIndex(viewName){
	for(var i = 0; i < views.length; i++){
		if(views[i].name === viewName){
			return i;
		}
	}
	return -1;
}

function removeView(viewName){
	$( "#" + viewName ).remove();
	console.log(views);
	views.splice(getViewArrayIndex(viewName));
	console.log(views);
	generateXMLFromArray();
}

/* ********************************************************************************** */
/*										 ATTRIBUTE      							  */
/* ********************************************************************************** */

/* HELPER

*/

function Action(functionName, name, description, view){
	this.functionName = functionName;
	this.name = name;
	this.description = description;
	this.view = view;
}

function Input(name, description, view){
	this.name = name;
	this.description = description;
	this.view = view;
}

function Output(name, description, type, view){
	this.name = name;
	this.description = description;
	this.type = type;
	this.view = view;
}

function Transition(description, name, target, view){
	this.description = description;
	this.name = name;
	this.target= target;
	this.view = view;
}

var attributes = [];
var attribute;

function openAttributeDialog(viewName){
	console.log("ATTRIBUTE ADD BUTTON CLICKED");
	resetAttributeInput();
	//$( "#viewNameHelper" ).html(viewName);
    //$( "#dialog" ).data('viewName', viewName).dialog( "open" );
	//var actualView = $("#dialog").data('param_1')
	$( "#dialog" ).dialog( "open" );
	$("#acutalView").html(viewName);

	setAttributeForm(viewName);
}

$("#attributeSelect").change(function() {
	$("#attributeValuesForm").remove();
	attribute = $("#attributeSelect").val();
	setAttributeForm($( "#viewName").val());
	console.log("Gewählt:" + attribute);
});

function addAttribute(viewName){
	var functionAttribute = $("#functionAttribute").val();
	var nameAttribute = $("#nameAttribute").val();
	var descriptionAttribute = $("#descriptionAttribute").val();
	var typeAttribute =  $("#typeAttribute").val();
	var targetAttribute = $("#targetAttribute").val();
	var targetSelectOptions = $("#targetSelectOptions").val();
	var targetAttribute = $("#targetAttribute").val();

	attribute = $("#attributeSelect").val();

	console.log("Button CLICKED ADD ATTRIBUTE");
	console.log(viewName);

	if(attribute == "action"){

		if(functionAttribute != '' && nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Action(functionAttribute, nameAttribute, descriptionAttribute, viewName));
			//$( "#"+ viewName ).append("
F: " + functionAttribute + "
");
			$( "#"+ viewName ).append("
A: " + nameAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + descriptionAttribute + "
");
			console.log(attributes);

			views[getViewArrayIndex(viewName)].attributes.push(new Action(functionAttribute, nameAttribute, descriptionAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "input"){

		if( nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Input(nameAttribute, descriptionAttribute, viewName));
			$( "#"+ viewName ).append("
I: " + nameAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + descriptionAttribute + "
");
			console.log(attributes);

			views[getViewArrayIndex(viewName)].attributes.push(new Input(nameAttribute, descriptionAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "output"){

		if( nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Output(nameAttribute, descriptionAttribute, typeAttribute, viewName));
			$( "#"+ viewName ).append("
O: " + nameAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + descriptionAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + typeAttribute + "
");
			console.log(attributes);

			views[getViewArrayIndex(viewName)].attributes.push(new Output(nameAttribute, descriptionAttribute, typeAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "transition"){
		console.log(nameAttribute + " -> " + descriptionAttribute + " -> " + targetAttribute);
		if( nameAttribute != '' && descriptionAttribute != '' && targetAttribute != null){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Transition(nameAttribute, descriptionAttribute, targetAttribute, viewName));
			//$( "#"+ viewName ).append("
N: " + nameAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + descriptionAttribute + "
");
			//$( "#"+ viewName ).append("
D: " + targetAttribute + "
");
			$( "#"+ viewName ).append("
T : ( " + viewName + " / " + targetAttribute + " )
");
			console.log(attributes);

			views[getViewArrayIndex(viewName)].attributes.push(new Transition(nameAttribute, descriptionAttribute, targetAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	generateXMLFromArray();
}

/*

functionAttribute
name
description
type
target

*/
function resetAttributeInput(){
	$("#functionAttribute").val('');
	$("#nameAttribute").val('');
	$("#descriptionAttribute").val('');
	$("#typeAttribute").val('');
	$("#targetAttribute").val('');
	$("#targetSelectOptions").val('');
}

function setAttributeForm(viewName){

	$("#functionAttribute").val('');
	$("#nameAttribute").val('');
	$("#descriptionAttribute").val('');
	$("#typeAttribute").val('');
	$("#targetAttribute").val('');
	$("#targetSelectOptions").val('');

	switch ($("#attributeSelect").val()) {
		case "action":
			$("#functionAttributeInput").css("display", "block");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "input":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "output":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "block");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "transition":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "block");
			console.log(views);

			console.log(checkIfExists);
			for(var i = 0 ; i < views.length; i++){

				var checkIfExists = false;

				if(viewName == views[i].name){
					checkIfExists = true;
				}

				if(!checkIfExists){
					console.log( "abc 123 ");
					if($("option:contains('" + views[i].name + "')", "#targetAttribute").length<1){
						$("#targetAttribute").append(" <option value='" + views[i].name + "'>" + views[i].name + "</option>");
					}
				}
			}

			break;
	}
}

/* ********************************************************************************** */
/*										 DRAGGABLE       							  */
/* ********************************************************************************** */

$( function() {
	$( ".draggable" ).draggable({
		  containment:"parent",
	 });
} );

$( "#dialog" ).dialog({
	autoOpen: false,
	resizable: false,
    height: "auto",
	width:"50%",
    modal: true,
	dialogClass: 'no-close',
    buttons: {
		"Hinzufügen": function() {
          addAttribute($("#acutalView").text());
        },
        "Abbrechen": function() {
          $( this ).dialog( "close" );
        }
	},
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    }
});

/* ********************************************************************************** */
/*										 	 XML        							  */
/* ********************************************************************************** */

var xmlString;

$( "#generateXML" ).click(function() {
	generateXMLFromArray();
	sendXMLData();
});

function generateXMLFromArray(){
	//var editor;

	xmlString = "<";
	xmlString += "?xml version='1.0' encoding='UTF-8'?>\n\n";
	xmlString += "
\n";
	//xmlString += "	xsi:schemaLocation='org.accaptp accapto_model.xsd'>\n";
	//xmlString += "
no restrictions
\n\n";
	for(var p = 0; p < profiles.length; p++){
		xmlString += "
" + profiles[p].name + "
\n";
	}
	xmlString += "\n";
	for(var v = 0; v < views.length; v++){
		xmlString += "
\n";
			for(var a = 0; a < views[v].attributes.length; a++){
				var key;
				xmlString += "
 \n";
			}
		xmlString += "
\n\n";
	}

	xmlString += "
";

	console.log(xmlString);

	$("#xmlPrepare").text(xmlString);

	$(".cm-s-default").remove();
	var readOnlyCodeMirror = CodeMirror.fromTextArea(document.getElementById('xmlPrepare'), {
        mode: "xml",
        theme: "default",
        lineNumbers: true,
        readOnly: true
    });

}

function sendXMLData(){

	var dataString = "xmlString=" + xmlString + "&projectName=" + project.name;

	// AJAX Code To Submit xmlString to generate XML document.
	$.ajax({
		type: "POST",
		url: "xmlwriter.php",
		data: dataString,
		cache: false,
		success: function(result){
			alert(result);
		}
	});

}
	<commit_msg>bugFixes and clean<commit_after>"use strict"

/* ********************************************************************************** */
/*										PROJECT     								  */
/* ********************************************************************************** */

var project;

function Project(name, namespace){
	this.name = name;
	this.namespace = namespace;
}

$( "#addProject" ).click(function(){
	if($( "#projectName").val() != '' && $( "#projectNamespace").val() != ''){
		$('#projectAlert').css('display', 'none');
		addProject($( "#projectName").val(),$( "#projectNamespace").val());
		$( "#profilePanel" ).css("display","block");
		$( "#generateXML" ).css("display","block");
	}else{
		$('#projectAlert').css('display', 'block');
	}
});

function addProject(projectName, projectNamespace){
	project = new Project(projectName,projectNamespace);
	generateXMLFromArray();
}

/* ********************************************************************************** */
/*										  PROFILE     								  */
/* ********************************************************************************** */

var profiles = [];

function Profile(name){
	this.name = name;
}

$( "#addProfile" ).click(function(){
	if($( "#profileName").val() != ''){
		$('#profileAlert').css('display', 'none');
		addProfile($( "#profileName").val());

		$( "#viewPanel" ).css("display","block");
		$( "#dragArea" ).css("display","block");

	}else{
		$('#profileAlert').css('display', 'block');
	}
});

function addProfile(profileName){
	profiles.push(new Profile(profileName));
	$( "#profileList" ).append("
" + profileName + "
");
	generateXMLFromArray();
	$( "#profileName").val('');
}

/* ********************************************************************************** */
/*										  VIEW       								  */
/* ********************************************************************************** */
var viewCounter = 0;
var views = [];

function View(id, name) {
	this.id = id;
	this.name = name;
	this.cordX = 5;
	this.cordY = 5;
	this.attributes = [];
}

$( "#addView" ).click(function() {
	if($( "#viewName").val() != ''){
		$('#viewAlert').css('display', 'none');
		addView($( "#viewName").val());
	}else{
		$('#viewAlert').css('display', 'block');
	}
});

function addView(viewName){

	viewCounter++;
	viewName = viewName;

	var singleView = new View(viewCounter,viewName);

	views.push(singleView);

	$( ".dragContainer" ).append( "

" + viewName + "<button  type='button' id='" + viewName + "' onClick=removeView(\"" + viewName + "\")>x</button>

<button type='button' class='opener' id='" + viewName + "'  onClick=openAttributeDialog(\"" + viewName + "\")>+</button>

 Viewnr:" + viewCounter + "

" );

	generateXMLFromArray();

	$( function() {
		  $( ".draggable" ).draggable({
		  	  containment:"parent",
			  drag: function() {
				  var $this = $(this);
            	  var thisPos = $this.position();
				  var parentPos = $this.parent().position();

				  var x = thisPos.left - parentPos.left;
				  var y = thisPos.top - parentPos.top;
			  },
			  stop: function(event, ui){
			      var $this = $(this);
				  var id = $(this).attr("id");
            	  var thisPos = $this.position();
				  var parentPos = $this.parent().position();

				  var x = thisPos.left - parentPos.left;
				  var y = thisPos.top - parentPos.top;
				  var viewIndex = getViewID(id)-1;
				  views[viewIndex].cordX = x;
				  views[viewIndex].cordY = y;
			  }
		  });
		  } );
}
function getViewID(viewName){
	for(var i = 0; i < views.length; i++){
		if(views[i].name === viewName){
			return views[i].id;
		}
	}
	return -1;
}

function getViewArrayIndex(viewName){
	for(var i = 0; i < views.length; i++){
		if(views[i].name === viewName){
			return i;
		}
	}
	return -1;
}

function removeView(viewName){
	$( "#" + viewName ).remove();
	views.splice(getViewArrayIndex(viewName));
	generateXMLFromArray();
}

/* ********************************************************************************** */
/*										 ATTRIBUTE      							  */
/* ********************************************************************************** */

/* HELPER

*/

function Action(functionName, name, description, view){
	this.functionName = functionName;
	this.name = name;
	this.description = description;
	this.view = view;
}

function Input(name, description, view){
	this.name = name;
	this.description = description;
	this.view = view;
}

function Output(name, description, type, view){
	this.name = name;
	this.description = description;
	this.type = type;
	this.view = view;
}

function Transition(description, name, target, view){
	this.description = description;
	this.name = name;
	this.target= target;
	this.view = view;
}

var attributes = [];
var attribute;

function openAttributeDialog(viewName){
	resetAttributeInput();
	$( "#dialog" ).dialog( "open" );
	$("#acutalView").html(viewName);

	setAttributeForm(viewName);
}

$("#attributeSelect").change(function() {
	$("#attributeValuesForm").remove();
	attribute = $("#attributeSelect").val();
	setAttributeForm($( "#viewName").val());
});

function addAttribute(viewName){
	var functionAttribute = $("#functionAttribute").val();
	var nameAttribute = $("#nameAttribute").val();
	var descriptionAttribute = $("#descriptionAttribute").val();
	var typeAttribute =  $("#typeAttribute").val();
	var targetAttribute = $("#targetAttribute").val();
	var targetSelectOptions = $("#targetSelectOptions").val();
	var targetAttribute = $("#targetAttribute").val();

	attribute = $("#attributeSelect").val();

	if(attribute == "action"){

		if(functionAttribute != '' && nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Action(functionAttribute, nameAttribute, descriptionAttribute, viewName));
			$( "#"+ viewName ).append("
A: " + nameAttribute + "
");

			views[getViewArrayIndex(viewName)].attributes.push(new Action(functionAttribute, nameAttribute, descriptionAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "input"){

		if( nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Input(nameAttribute, descriptionAttribute, viewName));
			$( "#"+ viewName ).append("
I: " + nameAttribute + "
");

			views[getViewArrayIndex(viewName)].attributes.push(new Input(nameAttribute, descriptionAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "output"){

		if( nameAttribute != '' && descriptionAttribute != ''){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Output(nameAttribute, descriptionAttribute, typeAttribute, viewName));
			$( "#"+ viewName ).append("
O: " + nameAttribute + "
");

			views[getViewArrayIndex(viewName)].attributes.push(new Output(nameAttribute, descriptionAttribute, typeAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	if(attribute == "transition"){
		if( nameAttribute != '' && descriptionAttribute != '' && targetAttribute != null){
			$('#viewAttributeAlert').css('display', 'none');
			attributes.push(new Transition(nameAttribute, descriptionAttribute, targetAttribute, viewName));
			$( "#"+ viewName ).append("
T : ( " + viewName + " / " + targetAttribute + " )
");

			views[getViewArrayIndex(viewName)].attributes.push(new Transition(nameAttribute, descriptionAttribute, targetAttribute, viewName));

			resetAttributeInput();
		}else{
			$('#viewAttributeAlert').css('display', 'block');
		}

	}

	generateXMLFromArray();
}

/*

functionAttribute
name
description
type
target

*/
function resetAttributeInput(){
	$("#functionAttribute").val('');
	$("#nameAttribute").val('');
	$("#descriptionAttribute").val('');
	$("#typeAttribute").val('');
	$("#targetAttribute").val('');
	$("#targetSelectOptions").val('');
}

function setAttributeForm(viewName){

	$("#functionAttribute").val('');
	$("#nameAttribute").val('');
	$("#descriptionAttribute").val('');
	$("#typeAttribute").val('');
	$("#targetAttribute").val('');
	$("#targetSelectOptions").val('');

	switch ($("#attributeSelect").val()) {
		case "action":
			$("#functionAttributeInput").css("display", "block");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "input":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "output":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "block");
			$("#targetAttributeInput").css("display", "none");
			break;
		case "transition":
			$("#functionAttributeInput").css("display", "none");
			$("#nameAttributeInput").css("display", "block");
			$("#descriptionAttributeInput").css("display", "block");
			$("#typeAttributeInput").css("display", "none");
			$("#targetAttributeInput").css("display", "block");
			console.log(views);
			for(var i = 0 ; i < views.length; i++){

				if($("#targetAttribute option[value='" + views[i].name + "']").length < 1){
					$("#targetAttribute").append(" <option value='" + views[i].name + "'>" + views[i].name + "</option>");
				}
			}

			break;
	}
}

/* ********************************************************************************** */
/*										 DRAGGABLE       							  */
/* ********************************************************************************** */

$( function() {
	$( ".draggable" ).draggable({
		  containment:"parent",
	 });
} );

$( "#dialog" ).dialog({
	autoOpen: false,
	resizable: false,
    height: "auto",
	width:"50%",
    modal: true,
	dialogClass: 'no-close',
    buttons: {
		"Hinzufügen": function() {
          addAttribute($("#acutalView").text());
        },
        "Abbrechen": function() {
          $( this ).dialog( "close" );
        }
	},
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    }
});

/* ********************************************************************************** */
/*										 	 XML        							  */
/* ********************************************************************************** */

var xmlString;

$( "#generateXML" ).click(function() {
	generateXMLFromArray();
	sendXMLData();
});

function generateXMLFromArray(){
	//var editor;

	xmlString = "<";
	xmlString += "?xml version='1.0' encoding='UTF-8'?>\n\n";
	xmlString += "
\n";
	//xmlString += "	xsi:schemaLocation='org.accaptp accapto_model.xsd'>\n";
	//xmlString += "
no restrictions
\n\n";
	for(var p = 0; p < profiles.length; p++){
		xmlString += "
" + profiles[p].name + "
\n";
	}
	xmlString += "\n";
	for(var v = 0; v < views.length; v++){
		xmlString += "
\n";
			for(var a = 0; a < views[v].attributes.length; a++){
				var key;
				xmlString += "
 \n";
			}
		xmlString += "
\n\n";
	}

	xmlString += "
";

	$("#xmlPrepare").text(xmlString);

	$(".cm-s-default").remove();
	var readOnlyCodeMirror = CodeMirror.fromTextArea(document.getElementById('xmlPrepare'), {
        mode: "xml",
        theme: "default",
        lineNumbers: true,
        readOnly: true
    });

}

function sendXMLData(){

	var dataString = "xmlString=" + xmlString + "&projectName=" + project.name;
	// AJAX Code To Submit xmlString to generate XML document.
	$.ajax({
		type: "POST",
		url: "xmlwriter.php",
		data: dataString,
		cache: false,
		success: function(result){
			var tmpPath = "downloadXML.php?filename=" + result;
			$("#downloadXML").css("display","block");
			$("#downloadXML").attr("href", tmpPath);
			alert(result);
		}
	});

}
	<|endoftext|>


<commit_before>/*jshint jquery: true*/

//$(function () {
//  $(".img_highres").off().on("load", function () {
//    var id = $(this).attr("id");
//    var highres = $(this).attr("src").toString();
//    alert(highres);
//    var target = '#'+id.substring(4);
//    $(target).css("background-image", "url(../" + highres + ")");
//  });
//});
window.onload(function () {
  $('#cobble').append('');
  $(".img_highres").off().on("load", function () {
    $("body").css({
      "background-image": "url(../assets/dark_cobble1920.jpg)"
    });
  });
});

$(document).ready(function () {

  //  var bio = $('.bio');
  //  bio.append('
before Testing
').delay(5000, function() {
  //    bio.append('
Testing, testing
');
  //  });

});

//
//  var strings = ['Hello World!',
//     'This is Joe Howarth speaking',
//       'hmm, what should I write?',
//       'Well, this is MY site after all,
 so I\'ll talk a little about myself!',
//       '...'];
//
//  var bio = $('.bio');
//  var p = '
_
';
//  $('.bio').append('
_ _
');
//  var line = $('bio :nth-child(1)');
//  line.append('hello-world').after(p);
//
//

//
//  function typedCallbackFn() {
//
//    if (counter++ >= strings.length - 1) {
//      return;
//    }
////    alert(strings[counter]);
//    bio.append(p);
//    line = bio.children.eq(counter);
//    line.append(strings[counter]);
///    typedCallbackFn();
////    line.typed({
////      strings: [strings[counter]],
////      typeSpeed: 8,
////      callback: typedCallbackFn()
////    });
//
//  }
//  typedCallbackFn();
//    $('.bio:first-child').append('').children('span').typed({
//        strings: [strings[counter++]],
//        typeSpeed: 5,
//        callback: typedCallbackFn
//      }
//    });
//  $("#type-area").typed({
//    strings: ["First sentence."],
//    typeSpeed: 10
//  });

//  function type(string, element) {
//    (function writer(i) {
//      if (string.length <= i++) {
//        element.value = string;
//        return;
//      }
//      element.value = string.substring(0, i);
//      if (element.value[element.value.length - 1] != " ") element.focus();
//      var rand = Math.floor(Math.random() * (100)) + 140;
//      setTimeout(function () {
//        writer(i);
//      }, rand);
//    })(0);
//  }
//
//  var elem = $('#type-area')[0];
//  type("testing", elem);
//  alert('past type');

var toIn = $('.bio').children().first();
//  toIn.fadeOut().delay.next().fadeOut();
toIn.siblings().show();

function cycleIn(animTime, interTime) {
  // fades in siblings,
  toIn = toIn.fadeIn(animTime).next();
  if (toIn.length !== 0) {
    setTimeout(function () {
      cycleIn(animTime, interTime);
    }, interTime);
  }
}
//cycleIn(1000, 1500); // executes above
<commit_msg>img issues fixed? (2)<commit_after>/*jshint jquery: true*/

//$(function () {
//  $(".img_highres").off().on("load", function () {
//    var id = $(this).attr("id");
//    var highres = $(this).attr("src").toString();
//    alert(highres);
//    var target = '#'+id.substring(4);
//    $(target).css("background-image", "url(../" + highres + ")");
//  });
//});
$(window).on('load', function () {
  $('#cobble').append('');
  $(".img_highres").off().on("load", function () {
    $("body").css({
      "background-image": "url(../assets/dark_cobble1920.jpg)"
    });
  });
});

$(document).ready(function () {

  //  var bio = $('.bio');
  //  bio.append('
before Testing
').delay(5000, function() {
  //    bio.append('
Testing, testing
');
  //  });

});

//
//  var strings = ['Hello World!',
//     'This is Joe Howarth speaking',
//       'hmm, what should I write?',
//       'Well, this is MY site after all,
 so I\'ll talk a little about myself!',
//       '...'];
//
//  var bio = $('.bio');
//  var p = '
_
';
//  $('.bio').append('
_ _
');
//  var line = $('bio :nth-child(1)');
//  line.append('hello-world').after(p);
//
//

//
//  function typedCallbackFn() {
//
//    if (counter++ >= strings.length - 1) {
//      return;
//    }
////    alert(strings[counter]);
//    bio.append(p);
//    line = bio.children.eq(counter);
//    line.append(strings[counter]);
///    typedCallbackFn();
////    line.typed({
////      strings: [strings[counter]],
////      typeSpeed: 8,
////      callback: typedCallbackFn()
////    });
//
//  }
//  typedCallbackFn();
//    $('.bio:first-child').append('').children('span').typed({
//        strings: [strings[counter++]],
//        typeSpeed: 5,
//        callback: typedCallbackFn
//      }
//    });
//  $("#type-area").typed({
//    strings: ["First sentence."],
//    typeSpeed: 10
//  });

//  function type(string, element) {
//    (function writer(i) {
//      if (string.length <= i++) {
//        element.value = string;
//        return;
//      }
//      element.value = string.substring(0, i);
//      if (element.value[element.value.length - 1] != " ") element.focus();
//      var rand = Math.floor(Math.random() * (100)) + 140;
//      setTimeout(function () {
//        writer(i);
//      }, rand);
//    })(0);
//  }
//
//  var elem = $('#type-area')[0];
//  type("testing", elem);
//  alert('past type');

var toIn = $('.bio').children().first();
//  toIn.fadeOut().delay.next().fadeOut();
toIn.siblings().show();

function cycleIn(animTime, interTime) {
  // fades in siblings,
  toIn = toIn.fadeIn(animTime).next();
  if (toIn.length !== 0) {
    setTimeout(function () {
      cycleIn(animTime, interTime);
    }, interTime);
  }
}
//cycleIn(1000, 1500); // executes above
<|endoftext|>


<commit_before>var app = angular.module('pathFind2016', ['mm.foundation','bzm-range-slider']);

app.controller('CanvasCtrl', function($scope) {
    const asphalt = 1;
    const dirt = 2;
    const closed = 3;
    const asphaltColor = "#fff86b";
    const dirtColor = "#8f7f42";
    const closedColor = "#000000";

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var start = -1;
    var end = -1;
    var asphaltCoef = 1;
    var dirtCoef = 10;
    var closedCoef = 100;

    function Node(x, y) {
        this.x = x;
        this.y = y;
        this.siblings = [];
    }
    Node.prototype.addSibling = function(i, type) {
        this.siblings.push({ind: i, type: type});
    }

    $scope.data = [
        new Node(50, 150),
        new Node(100, 140),
        new Node(205, 150),
        new Node(105, 85),
        new Node(200, 90),
        new Node(200, 300),
        new Node(100, 250),
        new Node(200, 250),
        new Node(280, 255),
        new Node(240, 155),
        new Node(275, 95),
        new Node(274, 45),
        new Node(350, 260),
    ];

    $scope.path = [];
    $scope.paramType = 1;

    $scope.road = {
        type: 1
    }

    function connect(ind1, ind2, type) {
        $scope.data[ind1].addSibling(ind2, type);
        $scope.data[ind2].addSibling(ind1, type);
    }

    function draw(data, path) {
        function drawNode(node, bgcolor, color, width) {
            context.beginPath();
            context.arc(node.x, node.y, width, 0, 2*Math.PI, false);
            context.fillStyle = color;
            context.fill();
            context.lineWidth = 2;
            context.strokeStyle = bgcolor;
            context.stroke();
        }

        function drawConnection(node1, node2, color, width) {
            context.beginPath();
            context.moveTo(node1.x, node1.y);
            context.lineTo(node2.x, node2.y);
            context.strokeStyle = color;
            context.lineWidth = width;
            context.stroke();
        }

        for(var i=0; i<data.length; i++) {
            for(var j=0; j<data[i].siblings.length; j++) {
                if (data[i].siblings[j].ind > i) {
                    var color = "#000000"
                    drawConnection(data[i], data[data[i].siblings[j].ind], color, 20);
                }
            }
        }
        data.forEach(function (node) {
            var color = "";
            for(var i=0; i<node.siblings.length; i++) {
                switch (node.siblings[i].type) {
                    case asphalt:
                        color = asphaltColor;
                    break;
                    case dirt:
                        color = dirtColor;
                    break;
                    case closed:
                        color = closedColor;
                    break;
                }
            }
            drawNode(node, "#000000", color, 9);
        });
        for(var i=0; i<data.length; i++) {
            for(var j=0; j<data[i].siblings.length; j++) {
                if (data[i].siblings[j].ind > i) {
                    var color = "";
                    switch (data[i].siblings[j].type) {
                        case asphalt:
                            color = asphaltColor;
                        break;
                        case dirt:
                            color = dirtColor;
                        break;
                        case closed:
                            color = closedColor;
                        break;
                    }

                    drawConnection(data[i], data[data[i].siblings[j].ind], color, 16);
                }
            }
        }

        for (var i=0; i < path.length - 1; i++) {
            drawConnection(data[path[i]], data[path[i+1]], "#000000", 20);
        }
        for (var i=0; i < path.length; i++) {
            drawNode(data[path[i]], "#000000", "#FF0000", 9);
        }
        for (var i=0; i < path.length - 1; i++) {
            drawConnection(data[path[i]], data[path[i+1]], "#FF0000", 16);
        }

        for(var i=0; i<data.length; i++) {
            var color = "#000000";
            if (i == start) {
                color = "#0000FF";
            }
            if (i == end) {
                color = "#00FF00";
            }
            drawNode(data[i], color, color, 5);
        }
    }

    function findPath(data, start, end) {
        function getLength(data, i, j) {
            var coeff = 1;
            for(var k=0; k<data[i].siblings.length; k++) {
                if (data[i].siblings[k].ind == j) {
                    switch(data[i].siblings[k].type) {
                        case asphalt:
                            coeff = asphaltCoef;
                            break;
                        case dirt:
                            coeff = dirtCoef;
                            break;
                        case closed:
                            coeff = closedCoef;
                        break;
                    }
                    break;
                }
            }
            return coeff*Math.sqrt((data[i].x - data[j].x)*(data[i].x - data[j].x) +
                (data[i].y - data[j].y)*(data[i].y - data[j].y));
        }

        if ((start < 0) || (end < 0))
            return;

        var queue = [];
        var nodes = [];
        data.forEach(function (elem) {nodes.push({len: -1, parent: -1})});
        queue.push(start);
        nodes[start].len = 0;
        while (queue.length > 0) {
            var i = queue.shift();
            data[i].siblings.forEach(
                function(s) {
                    var j = s.ind;
                    var len = getLength(data, i, j);
                    if ((nodes[j].len < 0) || (nodes[j].len > len + nodes[i].len)) {
                        queue.push(j);
                        nodes[j].len = nodes[i].len + len;
                        nodes[j].parent = i;
                    }
                }
            );
        }
        var path = [end];
        var parent = nodes[end].parent;
        while (parent != -1) {
            path.push(parent);
            parent = nodes[parent].parent;
        }
        $scope.path = path;
    }

    function updateCanvas() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        draw($scope.data, $scope.path);
    }

    $scope.procClick = function(event) {
        function nodeClicked(data, x, y) {
            // console.log(x + " " + y);
            for(var i=0; i<data.length; i++) {
                if ((data[i].x - 15 < x) && (data[i].x + 15 > x) &&
                    (data[i].y - 15 < y) && (data[i].y + 15 > y)) {
                    return i;
                }
            }
            return -1;
        }

        function rodeClicked(data, x, y) {
            for(var i=0; i<data.length; i++) {
                for(var j=0; j<data[i].siblings.length; j++) {
                    var x1 = data[i].x;
                    var y1 = data[i].y;
                    var x2 = data[data[i].siblings[j].ind].x;
                    var y2 = data[data[i].siblings[j].ind].y;
                    if ((x + 15 < Math.min(x1, x2)) || (x - 15 > Math.max(x1, x2)) || (y + 15 < Math.min(y1, y2)) || (y - 15 > Math.max(y1, y2)))
                        continue;
                    var a = y2 - y1;
                    var b = x1 - x2;
                    var c = y1*x2 - x1*y2;
                    var dist = Math.abs(a*x + b*y + c)/Math.sqrt(a*a + b*b);
                    if ((dist < 15) && (dist > -15))
                        return {start:i, end:data[i].siblings[j].ind};
                }
            }
            return undefined;
        }

        var rect = canvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        var node = nodeClicked($scope.data, x, y);
        if (node >= 0) {
            switch ($scope.paramType) {
                case 1:
                    start = node;
                    break;
                case 2:
                    end = node;
                    break;
            }
            findPath($scope.data, start, end);
            updateCanvas();
        }
        else {
            var rode = rodeClicked($scope.data, x, y);
            if (rode) {
                for(var i=0; i<$scope.data[rode.start].siblings.length; i++) {
                    if ($scope.data[rode.start].siblings[i].ind == rode.end) {
                        $scope.data[rode.start].siblings[i].type = $scope.road.type;
                    }
                }
                for(var i=0; i<$scope.data[rode.end].siblings.length; i++) {
                    if ($scope.data[rode.end].siblings[i].ind == rode.start) {
                        $scope.data[rode.end].siblings[i].type = $scope.road.type;
                    }
                }
                findPath($scope.data, start, end);
                updateCanvas();
            }
        }
    }

    $scope.forgetPath = function() {
        start = -1;
        end = -1;
        $scope.path = [];
        updateCanvas();
    }

    $scope.asphaltCoefCB = function(value) {
        asphaltCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    $scope.dirtCoefCB = function(value) {
        dirtCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    $scope.closedCoefCB = function(value) {
        closedCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    connect(0, 1, asphalt);
    connect(1, 2, asphalt);
    connect(1, 3, asphalt);
    connect(2, 4, dirt);
    connect(2, 7, asphalt);
    connect(7, 5, asphalt);
    connect(1, 6, asphalt);
    connect(6, 7, dirt);
    connect(3, 4, asphalt);
    connect(4, 10, asphalt);
    connect(2, 9, asphalt);
    connect(8, 10, asphalt);
    connect(7, 8, asphalt);
    connect(10, 11, asphalt);
    connect(8, 12, asphalt);

    context.globalAlpha = 1.0;
    context.beginPath();
    canvas.width = 400;
    canvas.height = 400;
    updateCanvas();
});
<commit_msg>Create more complex map<commit_after>var app = angular.module('pathFind2016', ['mm.foundation','bzm-range-slider']);

app.controller('CanvasCtrl', function($scope) {
    const asphalt = 1;
    const dirt = 2;
    const closed = 3;
    const asphaltColor = "#fff86b";
    const dirtColor = "#8f7f42";
    const closedColor = "#000000";

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var start = -1;
    var end = -1;
    var asphaltCoef = 1;
    var dirtCoef = 10;
    var closedCoef = 100;

    function Node(x, y) {
        this.x = x;
        this.y = y;
        this.siblings = [];
    }
    Node.prototype.addSibling = function(i, type) {
        this.siblings.push({ind: i, type: type});
    }

    $scope.data = [
        new Node(50, 150),
        new Node(100, 140),
        new Node(205, 150),
        new Node(105, 85),
        new Node(200, 90),
        new Node(200, 300),
        new Node(100, 250),
        new Node(200, 250),
        new Node(280, 255),
        new Node(240, 155),
        new Node(275, 95),
        new Node(274, 45),
        new Node(350, 260),
        new Node(550, 260),
        new Node(430, 100),
        new Node(600, 350),
        new Node(630, 150),
        new Node(630, 40),
        new Node(570, 70),
        new Node(470, 200),
        new Node(20, 350),
        new Node(190, 360),
        new Node(100, 355),
        new Node(350, 370),
        new Node(360, 105),
        new Node(490, 360),
        new Node(480, 265),
        new Node(680, 100),
        new Node(530, 150),
        new Node(630, 270),
    ];

    $scope.path = [];
    $scope.paramType = 1;

    $scope.road = {
        type: 1
    }

    function connect(ind1, ind2, type) {
        $scope.data[ind1].addSibling(ind2, type);
        $scope.data[ind2].addSibling(ind1, type);
    }

    function draw(data, path) {
        function drawNode(node, bgcolor, color, width) {
            context.beginPath();
            context.arc(node.x, node.y, width, 0, 2*Math.PI, false);
            context.fillStyle = color;
            context.fill();
            context.lineWidth = 2;
            context.strokeStyle = bgcolor;
            context.stroke();
        }

        function drawConnection(node1, node2, color, width) {
            context.beginPath();
            context.moveTo(node1.x, node1.y);
            context.lineTo(node2.x, node2.y);
            context.strokeStyle = color;
            context.lineWidth = width;
            context.stroke();
        }

        for(var i=0; i<data.length; i++) {
            for(var j=0; j<data[i].siblings.length; j++) {
                if (data[i].siblings[j].ind > i) {
                    var color = "#000000"
                    drawConnection(data[i], data[data[i].siblings[j].ind], color, 20);
                }
            }
        }
        data.forEach(function (node) {
            var color = "";
            for(var i=0; i<node.siblings.length; i++) {
                switch (node.siblings[i].type) {
                    case asphalt:
                        color = asphaltColor;
                    break;
                    case dirt:
                        color = dirtColor;
                    break;
                    case closed:
                        color = closedColor;
                    break;
                }
            }
            drawNode(node, "#000000", color, 9);
        });
        for(var i=0; i<data.length; i++) {
            for(var j=0; j<data[i].siblings.length; j++) {
                if (data[i].siblings[j].ind > i) {
                    var color = "";
                    switch (data[i].siblings[j].type) {
                        case asphalt:
                            color = asphaltColor;
                        break;
                        case dirt:
                            color = dirtColor;
                        break;
                        case closed:
                            color = closedColor;
                        break;
                    }

                    drawConnection(data[i], data[data[i].siblings[j].ind], color, 16);
                }
            }
        }

        for (var i=0; i < path.length - 1; i++) {
            drawConnection(data[path[i]], data[path[i+1]], "#000000", 20);
        }
        for (var i=0; i < path.length; i++) {
            drawNode(data[path[i]], "#000000", "#FF0000", 9);
        }
        for (var i=0; i < path.length - 1; i++) {
            drawConnection(data[path[i]], data[path[i+1]], "#FF0000", 16);
        }

        for(var i=0; i<data.length; i++) {
            var color = "#000000";
            if (i == start) {
                color = "#0000FF";
            }
            if (i == end) {
                color = "#00FF00";
            }
            drawNode(data[i], color, color, 5);
        }
    }

    function findPath(data, start, end) {
        function getLength(data, i, j) {
            var coeff = 1;
            for(var k=0; k<data[i].siblings.length; k++) {
                if (data[i].siblings[k].ind == j) {
                    switch(data[i].siblings[k].type) {
                        case asphalt:
                            coeff = asphaltCoef;
                            break;
                        case dirt:
                            coeff = dirtCoef;
                            break;
                        case closed:
                            coeff = closedCoef;
                        break;
                    }
                    break;
                }
            }
            return coeff*Math.sqrt((data[i].x - data[j].x)*(data[i].x - data[j].x) +
                (data[i].y - data[j].y)*(data[i].y - data[j].y));
        }

        if ((start < 0) || (end < 0))
            return;

        var queue = [];
        var nodes = [];
        data.forEach(function (elem) {nodes.push({len: -1, parent: -1})});
        queue.push(start);
        nodes[start].len = 0;
        while (queue.length > 0) {
            var i = queue.shift();
            data[i].siblings.forEach(
                function(s) {
                    var j = s.ind;
                    var len = getLength(data, i, j);
                    if ((nodes[j].len < 0) || (nodes[j].len > len + nodes[i].len)) {
                        queue.push(j);
                        nodes[j].len = nodes[i].len + len;
                        nodes[j].parent = i;
                    }
                }
            );
        }
        var path = [end];
        var parent = nodes[end].parent;
        while (parent != -1) {
            path.push(parent);
            parent = nodes[parent].parent;
        }
        $scope.path = path;
    }

    function updateCanvas() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        draw($scope.data, $scope.path);
    }

    $scope.procClick = function(event) {
        function nodeClicked(data, x, y) {
            // console.log(x + " " + y);
            for(var i=0; i<data.length; i++) {
                if ((data[i].x - 15 < x) && (data[i].x + 15 > x) &&
                    (data[i].y - 15 < y) && (data[i].y + 15 > y)) {
                    console.log(i);
                    return i;
                }
            }
            return -1;
        }

        function rodeClicked(data, x, y) {
            for(var i=0; i<data.length; i++) {
                for(var j=0; j<data[i].siblings.length; j++) {
                    var x1 = data[i].x;
                    var y1 = data[i].y;
                    var x2 = data[data[i].siblings[j].ind].x;
                    var y2 = data[data[i].siblings[j].ind].y;
                    if ((x + 15 < Math.min(x1, x2)) || (x - 15 > Math.max(x1, x2)) || (y + 15 < Math.min(y1, y2)) || (y - 15 > Math.max(y1, y2)))
                        continue;
                    var a = y2 - y1;
                    var b = x1 - x2;
                    var c = y1*x2 - x1*y2;
                    var dist = Math.abs(a*x + b*y + c)/Math.sqrt(a*a + b*b);
                    if ((dist < 15) && (dist > -15))
                        return {start:i, end:data[i].siblings[j].ind};
                }
            }
            return undefined;
        }

        var rect = canvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        var node = nodeClicked($scope.data, x, y);
        if (node >= 0) {
            switch ($scope.paramType) {
                case 1:
                    start = node;
                    break;
                case 2:
                    end = node;
                    break;
            }
            findPath($scope.data, start, end);
            updateCanvas();
        }
        else {
            var rode = rodeClicked($scope.data, x, y);
            if (rode) {
                for(var i=0; i<$scope.data[rode.start].siblings.length; i++) {
                    if ($scope.data[rode.start].siblings[i].ind == rode.end) {
                        $scope.data[rode.start].siblings[i].type = $scope.road.type;
                    }
                }
                for(var i=0; i<$scope.data[rode.end].siblings.length; i++) {
                    if ($scope.data[rode.end].siblings[i].ind == rode.start) {
                        $scope.data[rode.end].siblings[i].type = $scope.road.type;
                    }
                }
                findPath($scope.data, start, end);
                updateCanvas();
            }
        }
    }

    $scope.forgetPath = function() {
        start = -1;
        end = -1;
        $scope.path = [];
        updateCanvas();
    }

    $scope.asphaltCoefCB = function(value) {
        asphaltCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    $scope.dirtCoefCB = function(value) {
        dirtCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    $scope.closedCoefCB = function(value) {
        closedCoef = value;
        if ($scope.data) {
            findPath($scope.data, start, end);
            updateCanvas();
        }
        return value;
    }

    connect(0, 1, asphalt);
    connect(1, 2, asphalt);
    connect(1, 3, asphalt);
    connect(2, 4, asphalt);
    connect(2, 7, asphalt);
    connect(7, 5, asphalt);
    connect(1, 6, asphalt);
    connect(6, 7, asphalt);
    connect(3, 4, asphalt);
    connect(4, 10, asphalt);
    connect(2, 9, dirt);
    connect(8, 10, asphalt);
    connect(7, 8, asphalt);
    connect(10, 11, asphalt);
    connect(8, 12, asphalt);
    connect(0, 20, dirt);
    connect(22, 20, asphalt);
    connect(22, 21, asphalt);
    connect(6, 22, asphalt);
    connect(22, 21, asphalt);
    connect(5, 21, asphalt);
    connect(23, 21, closed);
    connect(23, 12, asphalt);
    connect(24, 10, closed);
    connect(24, 14, asphalt);
    connect(24, 12, asphalt);
    connect(23, 25, asphalt);
    connect(26, 12, asphalt);
    connect(26, 25, asphalt);
    connect(26, 19, dirt);
    connect(26, 13, asphalt);
    connect(15, 13, asphalt);
    connect(15, 25, dirt);
    connect(14, 18, asphalt);
    connect(13, 16, asphalt);
    connect(18, 16, asphalt);
    connect(18, 17, dirt);
    connect(27, 17, dirt);
    connect(27, 16, asphalt);
    connect(19, 28, dirt);
    connect(18, 28, dirt);
    connect(13, 29, asphalt);
    connect(15, 29, dirt);

    context.globalAlpha = 1.0;
    context.beginPath();
    canvas.width = 700;
    canvas.height = 400;
    updateCanvas();
});
<|endoftext|>


<commit_before>require.config({
    baseUrl: "js"
});
define(
// Requirements
["map", "mini-map", "first-person", "lib/jquery", "lib/undo-manager"],

// Module definition
function (Map, MiniMap, FirstPerson, $, UndoManager) {
    // TODO
});<commit_msg>Add placeholder input handlers.<commit_after>require.config({
    baseUrl: "js"
});
define(
// Requirements
["map", "mini-map", "first-person", "lib/jquery", "lib/undo-manager"],

// Module definition
function (Map, MiniMap, FirstPerson) {
    // TODO

    // Handle keyboard input for movement.
    $(window).keydown(function(e) {
        switch (e.which) {
            // Left arrow
            case 37:
                e.preventDefault(); // Prevent scrolling the window.
                console.log("TODO: Handle move left.");
                break;
            // Up arrow
            case 38:
                e.preventDefault(); // Prevent scrolling the window.
                console.log("TODO: Handle move forward.");
                break;
            // Right arrow
            case 39:
                e.preventDefault(); // Prevent scrolling the window.
                console.log("TODO: Handle move right.");
                break;
            // Down arrow
            case 40:
                e.preventDefault(); // Prevent scrolling the window.
                // Not used
                break;
            default:
                break;
        }
    });

    // Handle mousewheel input for traversing movement history.
    $(window).on('mousewheel DOMMouseScroll',function(e){
        // To catch up or down scroll:
        e = e.originalEvent;
        // delta == 1 = down, delta == -1 = up;
        var delta = e.wheelDelta > 0 || e.detail < 0 ? 1 : -1;

        switch (delta) {
            // Scroll up
            case 1:
                e.preventDefault(); // Prevent scrolling the window.
                console.log("TODO: Handle redo.");
                break;
            // Scroll down
            case -1:
                e.preventDefault(); // Prevent scrolling the window.
                console.log("TODO: Handle undo.");
                break;
            default:
                break;
        }
    });
});<|endoftext|>


<commit_before>
var noteManager = function (options) {
    this.parameters = options;
    this.defaults = {
        defaultSort: 'newer'
    };
};

noteManager.prototype = {

    init: function() {
      // merge defaults options and user's ones
      this.options = $.extend({}, this.defaults, this.parameters);
      this.plugEvents();
    },

    plugEvents: function() {

      this.displayNotes();
      if (this.options.defaultSort === "older") {
        this.reverseOrder();
      }

      var that = this;

      $('button[type="submit"]').on('click', function(e){
        e.preventDefault();

        var note = that.getNote($(this).closest('form'));
        that.saveNote(note);
        that.clearForm();
        that.displaySingleNote(note);
      });

      $('#dropbox').on('click', $.proxy(function(){

        var id = this.createJSONfile($.parseJSON(localStorage.getItem("WebNotes")));
        // FIXME permission denied on univ server
        Dropbox.save("https://etudiant.univ-mlv.fr/~odaire/WebNotes/temp/WebNotes-"+id+".json", "WebNotes");

      }, this));

      $('#delete').on('click', $.proxy(function(){
        if (confirm("All notes will be deleted, are you sure ?")) {
          this.deleteNotes();
        }
      }, this));

      $(document).on('click', '.note button.delete', function(){
        var id = $(this).parent().attr('id');
        id = id.substr(5, id.length);
        that.deleteSingleNote(id);
      });

      $(document).on('click', '.note button.edit', function(){
        var id = $(this).parent().attr('id');
        id = id.substr(5, id.length);
        that.editNote(id);
      });

      // Only when editing a note
      $(document).on('click', '.note button[type="submit"]', function(e){
        e.preventDefault();
        var note = that.getNote($(this).closest('form'));
        that.saveNote(note);

        var id = $(this).closest('form').parent().attr('id');
        id = id.substr(5, id.length);
        that.deleteSingleNote(id);

        that.displaySingleNote(note);
      });

      $('#order').on('click', $.proxy(function(e){
        e.preventDefault();
        this.reverseOrder();
      }, this));
    },

    /******************
      CORE FUNCTIONS
    ******************/

    /**
     * Get form data and return it as a JSON object
     * @param {HTML Object} form   The form generating this note
     * @return {JSON}   Note as JSON object
     */
    getNote: function(form) {
      var title = form.find('.title').val(),
          content = form.find('textarea').val(),
          url = this.containsURL(content);
          today = this.formatDate(),
          date = today[0],
          time = today[1],
          tags = this.formatTags(form.find('.tags').val());

      var note = this.formatNote(title, content, date, time, tags, url);
      return note;
    },

    /**
     * Format note to JSON with form data
     * @param  {string} title     Note title
     * @param  {string} content   Note text content
     * @param  {string} date      Note date
     * @param  {string} time      Note hour
     * @param  {string} tags      Note tags
     * @param  {string} url       URL contained in note
     * @return {JSON}             Note as JSON object
     */
    formatNote: function(title, content, date, time, tags, url) {
      var note = {
            "title": title,
            "content": content,
            "date": date,
            "time": time,
            "tags": tags,
            "url": url,
          };

      return note;
    },

    /**
     * If notes already exist in local storage, add the new one and save
     * else create the object and save it in local storage.
     * @param  {JSON}
     */
    saveNote: function(note) {
      var notes;
      if (localStorage.getItem("WebNotes") === null) {
        notes = [ note ];
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }else{
        notes = $.parseJSON(localStorage.getItem("WebNotes"));
        notes.push(note);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }
    },

    /**
     * Display all notes
     */
    displayNotes: function() {
      if (localStorage.getItem("WebNotes") !== null) {

        var notes = $.parseJSON(localStorage.getItem("WebNotes"));
        var tags;

        for (var i = notes.length-1 ; i >= 0; i--) {
          tags = '';
          for (var j = 0; j < notes[i].tags.length; j++) {
            if (notes[i].tags[j]) {
              if (j === 0 ) {
                tags = '#' + notes[i].tags[j] + '';
              }else{
                tags = tags + ' #' + notes[i].tags[j] + '';
              }
            }
          }

          $('#main').append(
            '
'+
              '
'+notes[i].title+'
'+
              '
'+notes[i].content+'
'+
              '
'+ tags +'
'+
              ''+notes[i].date+' - '+notes[i].time+''+
              '<button class="edit">Edit</button>'+
              '<button class="delete">Delete</button>'+
            '
'
          );

          if (notes[i].url) {
            this.generateWidget(i, notes[i].url);
          }
        }

      }
    },

    /**
     * Display a single note
     * @param {JSON} note
     */
    displaySingleNote: function(note) {
      var tags = '';
      var notesLength = $.parseJSON(localStorage.getItem("WebNotes")).length;
      notesLength = notesLength-1; // Number of next note

      for (var j = 0; j < note.tags.length; j++) {
         if (note.tags[j]) {
          if (j === 0 ) {
            tags = '#' + note.tags[j] + '';
          }else{
            tags = tags + ' #' + note.tags[j] + '';
          }
        }
      }

      if (this.options.defaultSort === "older") {
        $('#main').append(
          '
'+
            '
'+note.title+'
'+
            '
'+note.content+'
'+
            '
'+ tags +'
'+
            ''+note.date+' - '+note.time+''+
            '<button class="edit">Edit</button>'+
            '<button class="delete">Delete</button>'+
          '
'
        );
      }else{
        $('#main').prepend(
          '
'+
            '
'+note.title+'
'+
            '
'+note.content+'
'+
            '
'+ tags +'
'+
            ''+note.date+' - '+note.time+''+
            '<button class="edit">Edit</button>'+
            '<button class="delete">Delete</button>'+
          '
'
        );
      }

      if (note.url) {
        this.generateWidget(notesLength, note.url);
      }
    },

    /**
     * Delete all notes
     */
    deleteNotes: function() {
      localStorage.removeItem("WebNotes");
      $('div[id^="note-"]').remove();
    },

    /**
     * Delete a single note
     * @param  {int} id  ID of the note to be deleted
     */
    deleteSingleNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      if (id != -1) {
        notes.splice(id, 1);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
        $('#note-'+id+'').remove();
      }
    },

    /**
     * Edit a note
     * @param  {int} id  ID of the note to be edited
     */
    editNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      var note = notes[id];

     $('#note-'+id).html(
        '<form>'+
          '<input type="text" class="title" value="'+note.title+'">'+
          '<textarea>'+note.content+'</textarea>'+
          '<input name="tags" class="tags" value="'+note.tags+'" />'+
          '<button type="submit">Save</button>'+
        '</form>'
      );

     $('.tags').tagsInput();
    },

    /******************
     TOOLKIT FUNCTIONS
    ******************/

    clearForm: function() {
      $('form input.title, form textarea').val('');
      $('div.tagsinput span').remove();
    },

    /**
     * Get current date and time and format it
     * @return {array}    containing current date and hour
     */
    formatDate: function() {
      var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth()+1; //January is 0!
      var yyyy = today.getFullYear();

      if(dd<10){
          dd='0'+dd;
      }
      if(mm<10){
          mm='0'+mm;
      }

      var h = today.getHours();
      var m = today.getMinutes();
      var s = today.getSeconds();

      today = dd+'/'+mm+'/'+yyyy;

      var time = h + 'h' + m + 'min' + s + 's';

      return [today, time];
    },

    /**
     * Convert a list of tags into an array
     * @param  {string} tags    list of tags
     * @return {array}          array of tags
     */
    formatTags: function(tags) {
      var tagsArray = tags.split(',');

      return tagsArray;
    },

    /**
     * Ajax request to generate a JSON file through a PHP script
     * @param  {JSON} notes    object containing all notes
     */
    createJSONfile: function(notes) {
      // TODO GET unique ID from php and return it
      $.ajax({
        type : "POST",
        url : "php-tools/json.php",
        dataType : 'json',
        data : {
            json : JSON.stringify(notes)
        },
        error: function(data){
          console.log('Error generating JSON');
          console.log(data);
        },
        success: function(data){
          return data;
        }
      });
    },

    /**
     * Display all notes in reverse order : old ones first
     */
    reverseOrder: function() {
      $('#main > div').each(function() {
        $(this).prependTo(this.parentNode);
      });
    },

    /**
     * Check for an URL inside a string
     * @param  {string} s
     * @return {string}   Matched URL
     */
    containsURL: function(s) {
      var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
      if (regexp.exec(s)) {
        return regexp.exec(s)[0];
      }
    },

    /**
     * Test for compatible websites and return a widget or a picture
     * @param  {int}    id  ID of the note containing the url
     * @param  {string} s   URL to be tested
     */
    generateWidget: function(id, s) {
      var regexp = /(youtube\.com|youtu\.be|soundcloud\.com|imdb\.com|allocine\.fr|jpe?g|gif|png)/;

      switch (regexp.exec(s)[0]) {
        case 'youtube.com':
        case 'youtu.be':
          s = this.getYoutubeId(s);
          var iframe = '';
          $('#note-'+id).prepend(iframe);
        break;

        case 'soundcloud.com':
          SC.initialize({
            client_id: config.SoundCloud_client_id
          });

          var track_url = s;
          SC.oEmbed(track_url, { auto_play: false, show_comments: false }, function(oEmbed) {
            $('#note-'+id).prepend(oEmbed.html);
          });
        break;

        case 'imdb.com':
          var movieTitle = this.getTitleFromUrl(s);
          var that = this;

          movieTitle.success(function(movieTitle){
            // Remove year from title
            var regex = /(\(.*\))/;
            movieTitle = movieTitle.replace(regex.exec(movieTitle)[0], '');

            var movie = that.getMovie(movieTitle);
            movie.success(function(movie){
              var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

              // Append the image
              var img = '';
              $('#note-'+id).prepend(img);

              // Change note url to image URL instead of IMDB's one
              // so that there is juste one API call (first time the note is saved)
              notes = $.parseJSON(localStorage.getItem("WebNotes"));
              notes[id].url = url;
              notes = JSON.stringify(notes);
              localStorage.setItem("WebNotes", notes);
            });
          });
        break;

        case 'allocine.fr':
          var movieTitle = this.getTitleFromUrl(s);
          var that = this;

          movieTitle.success(function(movieTitle){
            var movie = that.getMovie(movieTitle);

            movie.success(function(movie){
              var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

              // Append the image
              var img = '';
              $('#note-'+id).prepend(img);

              // Change note url to image URL instead of Allocine's one
              // so that there is juste one API call (first time the note is saved)
              notes = $.parseJSON(localStorage.getItem("WebNotes"));
              notes[id].url = url;
              notes = JSON.stringify(notes);
              localStorage.setItem("WebNotes", notes);
            });
          });
        break;

        case 'jpeg':
        case 'jpg':
        case 'png':
        case 'gif':
          var img = '';
          $('#note-'+id).prepend(img);
        break;
      }
    },

    /**
     * Get the ID from a Youtube video
     * @param  {string} url  URL of the video
     * @return {string}      ID of the video
     */
    getYoutubeId: function(url){
      var ID = '';
      url = url.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
      if(url[2] !== undefined) {
        ID = url[2].split(/[^0-9a-z_]/i);
        ID = ID[0];
      }else{
        ID = url;
      }
        return ID;
    },

    /**
     * Get the movie title from an IMDB/Allocine URL
     * @param  {strin} url  Webpage url
     */
    getTitleFromUrl: function(url) {
      return $.ajax({
        type : "POST",
        url : "php-tools/getTitle.php",
        data : {
            'url' : url
        }
      });
    },

    /**
     * Call to The Movie Database API in order to get infos about a movie
     * @param  {string} movie  Name of the movie
     */
    getMovie: function(movieTitle) {
      movieTitle = encodeURI(movieTitle);
      var url = 'http://api.themoviedb.org/3/search/movie?query='+movieTitle+'&api_key='+config.TMDB_api_key;
      var path;

     return $.ajax({
        type : "GET",
        url : url,
        dataType: "jsonp",
      });

    },

};

<commit_msg>Confirm before deleting a single note<commit_after>
var noteManager = function (options) {
    this.parameters = options;
    this.defaults = {
        defaultSort: 'newer'
    };
};

noteManager.prototype = {

    init: function() {
      // merge defaults options and user's ones
      this.options = $.extend({}, this.defaults, this.parameters);
      this.plugEvents();
    },

    plugEvents: function() {

      this.displayNotes();
      if (this.options.defaultSort === "older") {
        this.reverseOrder();
      }

      var that = this;

      $('button[type="submit"]').on('click', function(e){
        e.preventDefault();

        var note = that.getNote($(this).closest('form'));
        that.saveNote(note);
        that.clearForm();
        that.displaySingleNote(note);
      });

      $('#dropbox').on('click', $.proxy(function(){

        var id = this.createJSONfile($.parseJSON(localStorage.getItem("WebNotes")));
        // FIXME permission denied on univ server
        Dropbox.save("https://etudiant.univ-mlv.fr/~odaire/WebNotes/temp/WebNotes-"+id+".json", "WebNotes");

      }, this));

      $('#delete').on('click', $.proxy(function(){
        if (confirm("All notes will be deleted, are you sure ?")) {
          this.deleteNotes();
        }
      }, this));

      $(document).on('click', '.note button.delete', function(){
        if (confirm("All notes will be deleted, are you sure ?")) {
          var id = $(this).parent().attr('id');
          id = id.substr(5, id.length);
          that.deleteSingleNote(id);
        }
      });

      $(document).on('click', '.note button.edit', function(){
        var id = $(this).parent().attr('id');
        id = id.substr(5, id.length);
        that.editNote(id);
      });

      // Only when editing a note
      $(document).on('click', '.note button[type="submit"]', function(e){
        e.preventDefault();
        var note = that.getNote($(this).closest('form'));
        that.saveNote(note);

        var id = $(this).closest('form').parent().attr('id');
        id = id.substr(5, id.length);
        that.deleteSingleNote(id);

        that.displaySingleNote(note);
      });

      $('#order').on('click', $.proxy(function(e){
        e.preventDefault();
        this.reverseOrder();
      }, this));
    },

    /******************
      CORE FUNCTIONS
    ******************/

    /**
     * Get form data and return it as a JSON object
     * @param {HTML Object} form   The form generating this note
     * @return {JSON}   Note as JSON object
     */
    getNote: function(form) {
      var title = form.find('.title').val(),
          content = form.find('textarea').val(),
          url = this.containsURL(content);
          today = this.formatDate(),
          date = today[0],
          time = today[1],
          tags = this.formatTags(form.find('.tags').val());

      var note = this.formatNote(title, content, date, time, tags, url);
      return note;
    },

    /**
     * Format note to JSON with form data
     * @param  {string} title     Note title
     * @param  {string} content   Note text content
     * @param  {string} date      Note date
     * @param  {string} time      Note hour
     * @param  {string} tags      Note tags
     * @param  {string} url       URL contained in note
     * @return {JSON}             Note as JSON object
     */
    formatNote: function(title, content, date, time, tags, url) {
      var note = {
            "title": title,
            "content": content,
            "date": date,
            "time": time,
            "tags": tags,
            "url": url,
          };

      return note;
    },

    /**
     * If notes already exist in local storage, add the new one and save
     * else create the object and save it in local storage.
     * @param  {JSON}
     */
    saveNote: function(note) {
      var notes;
      if (localStorage.getItem("WebNotes") === null) {
        notes = [ note ];
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }else{
        notes = $.parseJSON(localStorage.getItem("WebNotes"));
        notes.push(note);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }
    },

    /**
     * Display all notes
     */
    displayNotes: function() {
      if (localStorage.getItem("WebNotes") !== null) {

        var notes = $.parseJSON(localStorage.getItem("WebNotes"));
        var tags;

        for (var i = notes.length-1 ; i >= 0; i--) {
          tags = '';
          for (var j = 0; j < notes[i].tags.length; j++) {
            if (notes[i].tags[j]) {
              if (j === 0 ) {
                tags = '#' + notes[i].tags[j] + '';
              }else{
                tags = tags + ' #' + notes[i].tags[j] + '';
              }
            }
          }

          $('#main').append(
            '
'+
              '
'+notes[i].title+'
'+
              '
'+notes[i].content+'
'+
              '
'+ tags +'
'+
              ''+notes[i].date+' - '+notes[i].time+''+
              '<button class="edit">Edit</button>'+
              '<button class="delete">Delete</button>'+
            '
'
          );

          if (notes[i].url) {
            this.generateWidget(i, notes[i].url);
          }
        }

      }
    },

    /**
     * Display a single note
     * @param {JSON} note
     */
    displaySingleNote: function(note) {
      var tags = '';
      var notesLength = $.parseJSON(localStorage.getItem("WebNotes")).length;
      notesLength = notesLength-1; // Number of next note

      for (var j = 0; j < note.tags.length; j++) {
         if (note.tags[j]) {
          if (j === 0 ) {
            tags = '#' + note.tags[j] + '';
          }else{
            tags = tags + ' #' + note.tags[j] + '';
          }
        }
      }

      if (this.options.defaultSort === "older") {
        $('#main').append(
          '
'+
            '
'+note.title+'
'+
            '
'+note.content+'
'+
            '
'+ tags +'
'+
            ''+note.date+' - '+note.time+''+
            '<button class="edit">Edit</button>'+
            '<button class="delete">Delete</button>'+
          '
'
        );
      }else{
        $('#main').prepend(
          '
'+
            '
'+note.title+'
'+
            '
'+note.content+'
'+
            '
'+ tags +'
'+
            ''+note.date+' - '+note.time+''+
            '<button class="edit">Edit</button>'+
            '<button class="delete">Delete</button>'+
          '
'
        );
      }

      if (note.url) {
        this.generateWidget(notesLength, note.url);
      }
    },

    /**
     * Delete all notes
     */
    deleteNotes: function() {
      localStorage.removeItem("WebNotes");
      $('div[id^="note-"]').remove();
    },

    /**
     * Delete a single note
     * @param  {int} id  ID of the note to be deleted
     */
    deleteSingleNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      if (id != -1) {
        notes.splice(id, 1);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
        $('#note-'+id+'').remove();
      }
    },

    /**
     * Edit a note
     * @param  {int} id  ID of the note to be edited
     */
    editNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      var note = notes[id];

     $('#note-'+id).html(
        '<form>'+
          '<input type="text" class="title" value="'+note.title+'">'+
          '<textarea>'+note.content+'</textarea>'+
          '<input name="tags" class="tags" value="'+note.tags+'" />'+
          '<button type="submit">Save</button>'+
        '</form>'
      );

     $('.tags').tagsInput();
    },

    /******************
     TOOLKIT FUNCTIONS
    ******************/

    clearForm: function() {
      $('form input.title, form textarea').val('');
      $('div.tagsinput span').remove();
    },

    /**
     * Get current date and time and format it
     * @return {array}    containing current date and hour
     */
    formatDate: function() {
      var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth()+1; //January is 0!
      var yyyy = today.getFullYear();

      if(dd<10){
          dd='0'+dd;
      }
      if(mm<10){
          mm='0'+mm;
      }

      var h = today.getHours();
      var m = today.getMinutes();
      var s = today.getSeconds();

      today = dd+'/'+mm+'/'+yyyy;

      var time = h + 'h' + m + 'min' + s + 's';

      return [today, time];
    },

    /**
     * Convert a list of tags into an array
     * @param  {string} tags    list of tags
     * @return {array}          array of tags
     */
    formatTags: function(tags) {
      var tagsArray = tags.split(',');

      return tagsArray;
    },

    /**
     * Ajax request to generate a JSON file through a PHP script
     * @param  {JSON} notes    object containing all notes
     */
    createJSONfile: function(notes) {
      // TODO GET unique ID from php and return it
      $.ajax({
        type : "POST",
        url : "php-tools/json.php",
        dataType : 'json',
        data : {
            json : JSON.stringify(notes)
        },
        error: function(data){
          console.log('Error generating JSON');
          console.log(data);
        },
        success: function(data){
          return data;
        }
      });
    },

    /**
     * Display all notes in reverse order : old ones first
     */
    reverseOrder: function() {
      $('#main > div').each(function() {
        $(this).prependTo(this.parentNode);
      });
    },

    /**
     * Check for an URL inside a string
     * @param  {string} s
     * @return {string}   Matched URL
     */
    containsURL: function(s) {
      var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
      if (regexp.exec(s)) {
        return regexp.exec(s)[0];
      }
    },

    /**
     * Test for compatible websites and return a widget or a picture
     * @param  {int}    id  ID of the note containing the url
     * @param  {string} s   URL to be tested
     */
    generateWidget: function(id, s) {
      var regexp = /(youtube\.com|youtu\.be|soundcloud\.com|imdb\.com|allocine\.fr|jpe?g|gif|png)/;

      switch (regexp.exec(s)[0]) {
        case 'youtube.com':
        case 'youtu.be':
          s = this.getYoutubeId(s);
          var iframe = '';
          $('#note-'+id).prepend(iframe);
        break;

        case 'soundcloud.com':
          SC.initialize({
            client_id: config.SoundCloud_client_id
          });

          var track_url = s;
          SC.oEmbed(track_url, { auto_play: false, show_comments: false }, function(oEmbed) {
            $('#note-'+id).prepend(oEmbed.html);
          });
        break;

        case 'imdb.com':
          var movieTitle = this.getTitleFromUrl(s);
          var that = this;

          movieTitle.success(function(movieTitle){
            // Remove year from title
            var regex = /(\(.*\))/;
            movieTitle = movieTitle.replace(regex.exec(movieTitle)[0], '');

            var movie = that.getMovie(movieTitle);
            movie.success(function(movie){
              var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

              // Append the image
              var img = '';
              $('#note-'+id).prepend(img);

              // Change note url to image URL instead of IMDB's one
              // so that there is juste one API call (first time the note is saved)
              notes = $.parseJSON(localStorage.getItem("WebNotes"));
              notes[id].url = url;
              notes = JSON.stringify(notes);
              localStorage.setItem("WebNotes", notes);
            });
          });
        break;

        case 'allocine.fr':
          var movieTitle = this.getTitleFromUrl(s);
          var that = this;

          movieTitle.success(function(movieTitle){
            var movie = that.getMovie(movieTitle);

            movie.success(function(movie){
              var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

              // Append the image
              var img = '';
              $('#note-'+id).prepend(img);

              // Change note url to image URL instead of Allocine's one
              // so that there is juste one API call (first time the note is saved)
              notes = $.parseJSON(localStorage.getItem("WebNotes"));
              notes[id].url = url;
              notes = JSON.stringify(notes);
              localStorage.setItem("WebNotes", notes);
            });
          });
        break;

        case 'jpeg':
        case 'jpg':
        case 'png':
        case 'gif':
          var img = '';
          $('#note-'+id).prepend(img);
        break;
      }
    },

    /**
     * Get the ID from a Youtube video
     * @param  {string} url  URL of the video
     * @return {string}      ID of the video
     */
    getYoutubeId: function(url){
      var ID = '';
      url = url.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
      if(url[2] !== undefined) {
        ID = url[2].split(/[^0-9a-z_]/i);
        ID = ID[0];
      }else{
        ID = url;
      }
        return ID;
    },

    /**
     * Get the movie title from an IMDB/Allocine URL
     * @param  {strin} url  Webpage url
     */
    getTitleFromUrl: function(url) {
      return $.ajax({
        type : "POST",
        url : "php-tools/getTitle.php",
        data : {
            'url' : url
        }
      });
    },

    /**
     * Call to The Movie Database API in order to get infos about a movie
     * @param  {string} movie  Name of the movie
     */
    getMovie: function(movieTitle) {
      movieTitle = encodeURI(movieTitle);
      var url = 'http://api.themoviedb.org/3/search/movie?query='+movieTitle+'&api_key='+config.TMDB_api_key;
      var path;

     return $.ajax({
        type : "GET",
        url : url,
        dataType: "jsonp",
      });

    },

};

<|endoftext|>