<commit_before>(function(){

	var tree = raw.models.tree();

	var chart = raw.chart()
		.title('Circle Packing')
		.description(
            "Nested circles allow to represent hierarchies and compare values. This visualization is particularly effective to show the proportion between elements through their areas and their position inside a hierarchical structure.
Based on http://bl.ocks.org/mbostock/4063530")
		.thumbnail("imgs/circlePacking.png")
        .model(tree)

	var diameter = chart.number()
        .title("Diameter")
        .defaultValue(800)
        .fitToWidth(true)

	var padding = chart.number()
        .title("Padding")
        .defaultValue(5)

	var sort = chart.checkbox()
        .title("Sort by size")
        .defaultValue(false)

	var colors = chart.color()
        .title("Color scale")

	var showLabels = chart.checkbox()
        .title("Show labels")
		.defaultValue(true)

	chart.draw(function (selection, data){

		if (!data.children.length) return;

		var margin = 10,
	    	outerDiameter = +diameter(),
	    	innerDiameter = outerDiameter - margin - margin;

		var x = d3.scale.linear()
		    .range([0, innerDiameter]);

		var y = d3.scale.linear()
		    .range([0, innerDiameter]);

		var pack = d3.layout.pack()
		    .padding(+padding())
		    .sort(function (a,b){ console.log(a); return sort() ? a.value-b.value : null; })
		    .size([innerDiameter, innerDiameter])
		    .value(function(d) { return +d.size; })

		var g = selection
		    .attr("width", outerDiameter)
		    .attr("height", outerDiameter)
            .append("g")
		    .attr("transform", "translate(" + margin + "," + margin + ")");

        var focus = data,
            nodes = pack.nodes(data);

        colors.domain(nodes.filter(function (d){ return !d.children; }), function (d){ return d.color; });

        g.append("g").selectAll("circle")
            .data(nodes)
            .enter().append("circle")
            .attr("class", function (d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
            .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })
            .attr("r", function (d) { return d.r; })
            .style("fill", function (d) { return !d.children ? colors()(d.color) : ''; })
            .style("fill-opacity", function (d){ return !d.children ? 1 : 0; })
            .style("stroke", '#ddd')
            .style("stroke-opacity", function (d) { return !d.children ? 0 : 1 })

        g.append("g").selectAll("text")
            .data(nodes.filter(function (d){ return showLabels(); }))
            .enter().append("text")
            .attr("text-anchor", "middle")
	   		.style("font-size","11px")
			.style("font-family","Arial, Helvetica")
            .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
            .text(function (d) { return d.label ? d.label.join(", ") : d.name; });

	})
})();<commit_msg>Removing console.log<commit_after>(function(){

	var tree = raw.models.tree();

	var chart = raw.chart()
		.title('Circle Packing')
		.description(
            "Nested circles allow to represent hierarchies and compare values. This visualization is particularly effective to show the proportion between elements through their areas and their position inside a hierarchical structure.
Based on http://bl.ocks.org/mbostock/4063530")
		.thumbnail("imgs/circlePacking.png")
        .model(tree)

	var diameter = chart.number()
        .title("Diameter")
        .defaultValue(800)
        .fitToWidth(true)

	var padding = chart.number()
        .title("Padding")
        .defaultValue(5)

	var sort = chart.checkbox()
        .title("Sort by size")
        .defaultValue(false)

	var colors = chart.color()
        .title("Color scale")

	var showLabels = chart.checkbox()
        .title("Show labels")
		.defaultValue(true)

	chart.draw(function (selection, data){

		if (!data.children.length) return;

		var margin = 10,
	    	outerDiameter = +diameter(),
	    	innerDiameter = outerDiameter - margin - margin;

		var x = d3.scale.linear()
		    .range([0, innerDiameter]);

		var y = d3.scale.linear()
		    .range([0, innerDiameter]);

		var pack = d3.layout.pack()
		    .padding(+padding())
		    .sort(function (a,b){ return sort() ? a.value-b.value : null; })
		    .size([innerDiameter, innerDiameter])
		    .value(function(d) { return +d.size; })

		var g = selection
		    .attr("width", outerDiameter)
		    .attr("height", outerDiameter)
            .append("g")
		    .attr("transform", "translate(" + margin + "," + margin + ")");

        var focus = data,
            nodes = pack.nodes(data);

        colors.domain(nodes.filter(function (d){ return !d.children; }), function (d){ return d.color; });

        g.append("g").selectAll("circle")
            .data(nodes)
            .enter().append("circle")
            .attr("class", function (d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
            .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })
            .attr("r", function (d) { return d.r; })
            .style("fill", function (d) { return !d.children ? colors()(d.color) : ''; })
            .style("fill-opacity", function (d){ return !d.children ? 1 : 0; })
            .style("stroke", '#ddd')
            .style("stroke-opacity", function (d) { return !d.children ? 0 : 1 })

        g.append("g").selectAll("text")
            .data(nodes.filter(function (d){ return showLabels(); }))
            .enter().append("text")
            .attr("text-anchor", "middle")
	   		.style("font-size","11px")
			.style("font-family","Arial, Helvetica")
            .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
            .text(function (d) { return d.label ? d.label.join(", ") : d.name; });

	})
})();<|endoftext|>


<commit_before>
init();

function init(){
	createCheckersBoard();
	addPiecesOnBoard();
}

function createCheckersBoard(){
	var  rowChangeColor = 0;
	var boxChangeColor = 0;
	var table = document.getElementById('board');
	for (var i = 0; i < 8; i++) {
		//Creating a row for each loop
		var row = table.insertRow();

		//This loop will add 8 blocks in each row
		for(var j = 0; j < 8; j++ ){
				var bloc = row.insertCell();

				if(rowChangeColor == 0){

					if(boxChangeColor == 0){
						bloc.className = 'white-box';
						boxChangeColor = 1;

					}else{
						bloc.className = 'black-box';
						boxChangeColor = 0;
					}
				}else{

					if(boxChangeColor == 0){
						bloc.className = 'black-box';
						boxChangeColor = 1;
					}else{
						bloc.className = 'white-box';
						boxChangeColor = 0;
					}

				}

				bloc.setAttribute('name', i+''+j);
				bloc.onclick = getPieceMovement;
		}

		rowChangeColor = (rowChangeColor == 0) ? 1:0;

	}
}

function addPiecesOnBoard(){
	var tbody = document.getElementById('board').children;
	var boardRowChildren = tbody[0].children;

	for(var i = 0; i < 8; i++){
		for(var j = 0; j < 8; j++){

			//The white pieces -------------------------------------
			if(i<3){
				var pieceWhite = document.createElement("div");
				if(i%2 == 0 && j%2 == 0){
					pieceWhite.className = 'white-piece';
					boardRowChildren[i].children[j].appendChild(pieceWhite);

				}else if(i%2 != 0 && j%2 != 0){
					pieceWhite.className = 'white-piece';
					boardRowChildren[i].children[j].appendChild(pieceWhite);
				}

			//The black pieces -------------------------------------
			}else if(i >= 5){
				var pieceBlack = document.createElement("div");
				if(i%2!=0 && j%2!=0){
					pieceBlack.className = 'black-piece';
					boardRowChildren[i].children[j].appendChild(pieceBlack);

				}else if(i%2==0 && j%2==0){
					pieceBlack.className = 'black-piece';
					boardRowChildren[i].children[j].appendChild(pieceBlack);
				}
			}

		}
	}
}

var board = [
    			 [-1, 0,-1, 0,-1, 0,-1, 0],
    		     [ 0,-1, 0,-1, 0,-1, 0,-1],
    			 [-1, 0,-1, 0,-1, 0,-1, 0],
    			 [ 0, 0, 0, 0, 0, 0, 0, 0],
    			 [ 0, 0, 0, 0, 0, 0, 0, 0],
    			 [ 0, 1, 0, 1, 0, 1, 0, 1],
    			 [ 1, 0, 1, 0, 1, 0, 1, 0],
    			 [ 0, 1, 0, 1, 0, 1, 0, 1]
			];

var isSelected = false;
var selectedPiece = null;
var rigthPiecePlace = null;
var leftPiecePlace = null;
var selectedPieceColor = null;
var pieceRemove = null;
var handPlay = 1;
var keepJumping = null;

function getPieceMovement(){

	var coordX = parseInt($(this).attr('name')[0]);
	var coordY = parseInt($(this).attr('name')[1]);

    if(handPlay == 1){
    	if(board[coordX][coordY] == 1){
            selectedPieceColor = handPlay;
    		getleftRightIndex(coordX, coordY);
    	}
    }

    if(handPlay == -1){
        if(board[coordX][coordY] == -1){
            selectedPieceColor = handPlay;
    		getleftRightIndex(coordX, coordY);
    	}
    }

	if(isSelected){
		if(rigthPiecePlace == (coordX + '' + coordY) ){
			moveSelectedPiece(coordX + '' + coordY, rigthPiecePlace, selectedPieceColor);
        }
		if(leftPiecePlace == (coordX + '' + coordY) ){
			moveSelectedPiece(coordX + '' + coordY, leftPiecePlace, selectedPieceColor);
        }
	}

	isSelected = true;
}

function getleftRightIndex(crdX, crdY){
    var topLeftBoxIndex = (selectedPieceColor == 1) ? ( ( (crdX > 0) && (crdY > 0) ) ? (crdX-1) + '' + (crdY-1) : null)
                                                    : ( ( (crdY > 0) ) ? (crdX+1) + '' + (crdY-1) : null);

	var topRightBoxIndex = (selectedPieceColor == 1) ? ( ( (crdX > 0) && (crdY+1 < 8) ) ? (crdX-1) + '' + (crdY+1) : null)
                                                     : ( ( (crdX+1 < 8) && (crdY+1 < 8) ) ? (crdX+1) + '' + (crdY+1) : null);

	selectedPiece = crdX + '' + crdY;

    if(keepJumping != null){
        return [topLeftBoxIndex, topRightBoxIndex];
    }

    coloredPiecePlaces(topLeftBoxIndex, topRightBoxIndex);
}

function coloredPiecePlaces(left, right) {

	if(left != null){
        var leftX = parseInt(left[0]);
        var leftY = parseInt(left[1]);
        leftPiecePlace = left;

		if( (leftX >= 0 && leftY >= 0) && board[leftX][leftY] == 0 && right != null && board[right[0]][right[1]] == 0){
    		$(this).css("background-color", "yellow");
    		$('.white-box[name=' + left + ']').css("background-color", "yellow");

		}else if(leftX >=0 && leftY >=0){

            if(board[leftX][leftY] == selectedPieceColor){
                if(right != null && board[right[0]][right[1]] == 0){
                    $('.white-box[name=' + right + ']').css("background-color", "yellow");
                    leftPiecePlace = right;
                }

            }else if(board[leftX][leftY] == 0 && right == null){
                $('.white-box[name=' + left + ']').css("background-color", "yellow");

            }else if(board[leftX][leftY] != selectedPieceColor && board[leftX][leftY] != 0){
                coloredOnJumpPiece(leftX, leftY, 'L');
            }
        }

    }

	if(right != null){
        var rightX = parseInt(right[0]);
        var rightY = parseInt(right[1]);
        rigthPiecePlace = right;

		if( (rightX < 8 && rightY < 8) && board[rightX][rightY] == 0 && left != null && board[left[0]][left[1]] == 0){
			$(this).css("background-color", "yellow");
			$('.white-box[name=' + right + ']').css("background-color", "yellow");

        }else if(rightX < 8 && rightY < 8){

            if(board[rightX][rightY] == selectedPieceColor){
                if(left != null && board[left[0]][left[1]] == 0){
                    $('.white-box[name=' + left + ']').css("background-color", "yellow");
                    rigthPiecePlace = left;
                }

            }else if(board[rightX][rightY] == 0 && left == null){
                $('.white-box[name=' + right + ']').css("background-color", "yellow");

            }else if(board[rightX][rightY] != selectedPieceColor && board[rightX][rightY] != 0){
                coloredOnJumpPiece(rightX, rightY, 'R');
            }
        }
    }

}

function coloredOnJumpPiece(x, y, side){
    var place = null;

    if(selectedPieceColor == 1 && side == 'R'){
        if(board[x-1][y+1] == 0){
            place = (board[x][y] == -1) ? (x-1).toString() + (y+1).toString() : null;
        }else{
            $('.white-box[name=' + leftPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == 1 && side == 'L'){
        if(board[x-1][y-1] == 0){
            place = (board[x][y] == -1) ? (x-1).toString() + (y-1).toString() : null;
        }
        else{
            $('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == -1 && side == 'R'){
        if(board[x+1][y+1] == 0){
            place = (board[x][y] == 1) ? (x+1).toString() + (y+1).toString() : null;
        }
        else{
            $('.white-box[name=' + leftPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == -1 && side == 'L'){
        if(board[x+1][y-1] == 0){
            place = (board[x][y] == 1) ? (x+1).toString() + (y-1).toString() : null;
        }
        else{
            $('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "yellow");
        }

    }

    rigthPiecePlace = (side == 'R') ? place : rigthPiecePlace;
    leftPiecePlace = (side == 'L') ? place : leftPiecePlace;

    if(place != null){
        $('.white-box[name=' + place + ']').css("background-color", "yellow");
        pieceRemove = (x).toString()+(y).toString();
        keepJumping = 1;
    }else{
        keepJumping = null;
    }

    return;

}

function moveSelectedPiece(currentPiecePlace, newPiecePlace, pieceColor){
	if(selectedPiece != null){

		if(newPiecePlace == currentPiecePlace ){

            if(pieceRemove != null){
                $('.white-box[name=' + pieceRemove + ']').children().remove();
                board[pieceRemove[0]][pieceRemove[1]] = 0;
                pieceRemove = null;
            }

            $('.white-box[name=' + selectedPiece + ']').children().remove();
            board[selectedPiece[0]][selectedPiece[1]] = 0;

			if(pieceColor==1){
				var pieceMove = $('.white-box[name=' + newPiecePlace + ']')
                if(newPiecePlace[0] == '0'){
                    $(pieceMove.append("
").children()[0]).append("
");
                    board[newPiecePlace[0]][newPiecePlace[1]] = 2;

                }else{
                    pieceMove.append("
");
				    board[newPiecePlace[0]][newPiecePlace[1]] = 1;

                }

			}else if(pieceColor==-1){
                var pieceMove = $('.white-box[name=' + newPiecePlace + ']');
                if(newPiecePlace[0] == '7'){
				    $(pieceMove.append("
").children()[0]).append("
");
				    board[newPiecePlace[0]][newPiecePlace[1]] = -2;

                }else{
                    pieceMove.append("
");
                    board[newPiecePlace[0]][newPiecePlace[1]] = -1;

                }
			}

			isSelected = false;

			$('.white-box[name=' + selectedPiece + ']').css("background-color", "white");
			$('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "white");
			$('.white-box[name=' + leftPiecePlace + ']').css("background-color", "white");

			selectedPiece = null;
			rigthPiecePlace = null;
			leftPiecePlace = null;

            onKeepJumping(newPiecePlace)

            handPlay = (handPlay == 1) ? -1 : 1;
		}

	}

}

function onKeepJumping(newPlace) {
    if(keepJumping != null){
        var leftRightBox = [];
        var coordX = parseInt(newPlace[0]);
        var coordY = parseInt(newPlace[1]);

        leftRightBox = getleftRightIndex(coordX, coordY);

        if(leftRightBox[0] != null){
            coloredOnJumpPiece(parseInt(leftRightBox[0][0]), parseInt(leftRightBox[0][1]), 'L');
        }

        if(leftRightBox[1] != null){
            coloredOnJumpPiece(parseInt(leftRightBox[1][0]), parseInt(leftRightBox[1][1]), 'R');
        }
    }

}
<commit_msg>Fix the bugs on turn-to-move when game freeze after QA<commit_after>
init();

function init(){
	createCheckersBoard();
	addPiecesOnBoard();
}

function createCheckersBoard(){
	var  rowChangeColor = 0;
	var boxChangeColor = 0;
	var table = document.getElementById('board');
	for (var i = 0; i < 8; i++) {
		//Creating a row for each loop
		var row = table.insertRow();

		//This loop will add 8 blocks in each row
		for(var j = 0; j < 8; j++ ){
				var bloc = row.insertCell();

				if(rowChangeColor == 0){

					if(boxChangeColor == 0){
						bloc.className = 'white-box';
						boxChangeColor = 1;

					}else{
						bloc.className = 'black-box';
						boxChangeColor = 0;
					}
				}else{

					if(boxChangeColor == 0){
						bloc.className = 'black-box';
						boxChangeColor = 1;
					}else{
						bloc.className = 'white-box';
						boxChangeColor = 0;
					}

				}

				bloc.setAttribute('name', i+''+j);
				bloc.onclick = getPieceMovement;
		}

		rowChangeColor = (rowChangeColor == 0) ? 1:0;

	}
}

function addPiecesOnBoard(){
	var tbody = document.getElementById('board').children;
	var boardRowChildren = tbody[0].children;

	for(var i = 0; i < 8; i++){
		for(var j = 0; j < 8; j++){

			//The white pieces -------------------------------------
			if(i<3){
				var pieceWhite = document.createElement("div");
				if(i%2 == 0 && j%2 == 0){
					pieceWhite.className = 'white-piece';
					boardRowChildren[i].children[j].appendChild(pieceWhite);

				}else if(i%2 != 0 && j%2 != 0){
					pieceWhite.className = 'white-piece';
					boardRowChildren[i].children[j].appendChild(pieceWhite);
				}

			//The black pieces -------------------------------------
			}else if(i >= 5){
				var pieceBlack = document.createElement("div");
				if(i%2!=0 && j%2!=0){
					pieceBlack.className = 'black-piece';
					boardRowChildren[i].children[j].appendChild(pieceBlack);

				}else if(i%2==0 && j%2==0){
					pieceBlack.className = 'black-piece';
					boardRowChildren[i].children[j].appendChild(pieceBlack);
				}
			}

		}
	}
}

var board = [
    			 [-1, 0,-1, 0,-1, 0,-1, 0],
    		     [ 0,-1, 0,-1, 0,-1, 0,-1],
    			 [-1, 0,-1, 0,-1, 0,-1, 0],
    			 [ 0, 0, 0, 0, 0, 0, 0, 0],
    			 [ 0, 0, 0, 0, 0, 0, 0, 0],
    			 [ 0, 1, 0, 1, 0, 1, 0, 1],
    			 [ 1, 0, 1, 0, 1, 0, 1, 0],
    			 [ 0, 1, 0, 1, 0, 1, 0, 1]
			];

var isSelected = false;
var selectedPiece = null;
var rigthPiecePlace = null;
var leftPiecePlace = null;
var selectedPieceColor = null;
var pieceRemove = null;
var handPlay = 1;
var keepJumping = null;
var opponentJump = null;
function getPieceMovement(){

	var coordX = parseInt($(this).attr('name')[0]);
	var coordY = parseInt($(this).attr('name')[1]);

    if(handPlay == 1){
    	if(board[coordX][coordY] == 1){
            selectedPieceColor = handPlay;
    		getleftRightIndex(coordX, coordY);
    	}
    }

    if(handPlay == -1){
        if(board[coordX][coordY] == -1){
            selectedPieceColor = handPlay;
    		getleftRightIndex(coordX, coordY);
    	}
    }

	if(isSelected){
		if(rigthPiecePlace == (coordX + '' + coordY) ){
			moveSelectedPiece(coordX + '' + coordY, rigthPiecePlace, selectedPieceColor);
        }
		if(leftPiecePlace == (coordX + '' + coordY) ){
			moveSelectedPiece(coordX + '' + coordY, leftPiecePlace, selectedPieceColor);
        }
	}

	isSelected = true;
}

function getleftRightIndex(crdX, crdY){
    var topLeftBoxIndex = (selectedPieceColor == 1) ? ( ( (crdX > 0) && (crdY > 0) ) ? (crdX-1) + '' + (crdY-1) : null)
                                                    : ( ( (crdY > 0) ) ? (crdX+1) + '' + (crdY-1) : null);

	var topRightBoxIndex = (selectedPieceColor == 1) ? ( ( (crdX > 0) && (crdY+1 < 8) ) ? (crdX-1) + '' + (crdY+1) : null)
                                                     : ( ( (crdX+1 < 8) && (crdY+1 < 8) ) ? (crdX+1) + '' + (crdY+1) : null);

	selectedPiece = crdX + '' + crdY;

    if(keepJumping != null){
        return [topLeftBoxIndex, topRightBoxIndex];
    }

    coloredPiecePlaces(topLeftBoxIndex, topRightBoxIndex);
}

function coloredPiecePlaces(left, right) {

	if(left != null){
        var leftX = parseInt(left[0]);
        var leftY = parseInt(left[1]);
        leftPiecePlace = left;

        //Color both side
		if( (leftX >= 0 && leftY >= 0) && board[leftX][leftY] == 0 && right != null && board[right[0]][right[1]] == 0){
    		$(this).css("background-color", "yellow");
    		$('.white-box[name=' + left + ']').css("background-color", "yellow");

		}else if(leftX >=0 && leftY >=0){
            coloredLeft_or_right_piece(left, right, 'L');
        }

    }

	if(right != null){
        var rightX = parseInt(right[0]);
        var rightY = parseInt(right[1]);
        rigthPiecePlace = right;

        //Color both side
		if( (rightX < 8 && rightY < 8) && board[rightX][rightY] == 0 && left != null && board[left[0]][left[1]] == 0){
			$(this).css("background-color", "yellow");
			$('.white-box[name=' + right + ']').css("background-color", "yellow");

        }else if(rightX < 8 && rightY < 8){
            coloredLeft_or_right_piece(left, right, 'R');
        }
    }

}

function coloredLeft_or_right_piece(leftPiece, rightPiece, pieceSide) {

    if(pieceSide == 'L'){
        var leftX = parseInt(leftPiece[0]);
        var leftY = parseInt(leftPiece[1]);

        if(board[leftX][leftY] == selectedPieceColor){
            if(rightPiece != null && board[rightPiece[0]][rightPiece[1]] == 0){
                $('.white-box[name=' + rightPiece + ']').css("background-color", "yellow");
                leftPiecePlace = rightPiece;
            }

        }else if(board[leftX][leftY] == 0 && rightPiece == null){
            $('.white-box[name=' + leftPiece + ']').css("background-color", "yellow");

        }else if(board[leftX][leftY] != selectedPieceColor && board[leftX][leftY] != 0){
            coloredOnJumpPiece(leftX, leftY, 'L');
        }

    }else{
        var rightX = parseInt(rightPiece[0]);
        var rightY = parseInt(rightPiece[1]);

        if(board[rightX][rightY] == selectedPieceColor){
            if(leftPiece != null && board[leftPiece[0]][leftPiece[1]] == 0){
                $('.white-box[name=' + leftPiece + ']').css("background-color", "yellow");
                rigthPiecePlace = leftPiece;
            }

        }else if(board[rightX][rightY] == 0 && leftPiece == null){
            $('.white-box[name=' + rightPiece + ']').css("background-color", "yellow");

        }else if(board[rightX][rightY] != selectedPieceColor && board[rightX][rightY] != 0){
            coloredOnJumpPiece(rightX, rightY, 'R');
        }

    }

}

function coloredOnJumpPiece(x, y, side){
    var place = null;

    if(selectedPieceColor == 1 && side == 'R'){
        if(board[x-1][y+1] == 0){
            place = (board[x][y] == -1) ? (x-1).toString() + (y+1).toString() : null;
        }else{
            $('.white-box[name=' + leftPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == 1 && side == 'L'){
        if(board[x-1][y-1] == 0){
            place = (board[x][y] == -1) ? (x-1).toString() + (y-1).toString() : null;
        }
        else{
            $('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == -1 && side == 'R'){
        if(board[x+1][y+1] == 0){
            place = (board[x][y] == 1) ? (x+1).toString() + (y+1).toString() : null;
        }
        else{
            $('.white-box[name=' + leftPiecePlace + ']').css("background-color", "yellow");
        }

    }else if(selectedPieceColor == -1 && side == 'L'){
        if(board[x+1][y-1] == 0){
            place = (board[x][y] == 1) ? (x+1).toString() + (y-1).toString() : null;
        }
        else{
            $('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "yellow");
        }

    }

    rigthPiecePlace = (side == 'R') ? place : rigthPiecePlace;
    leftPiecePlace = (side == 'L') ? place : leftPiecePlace;

    if(place != null){
        $('.white-box[name=' + place + ']').css("background-color", "yellow");
        pieceRemove = (x).toString()+(y).toString();
        keepJumping = 1;
    }else{
        keepJumping = null;
    }

    return;

}

function moveSelectedPiece(placeTomove, newPiecePlace, pieceColor){
	if(selectedPiece != null){

		if(newPiecePlace == placeTomove){

            if(pieceRemove != null){
                $('.white-box[name=' + pieceRemove + ']').children().remove();
                board[pieceRemove[0]][pieceRemove[1]] = 0;
                pieceRemove = null;
            }

            if(opponentJump != null){
                selectedPiece = opponentJump;
                opponentJump = null;
            }

            $('.white-box[name=' + selectedPiece + ']').children().remove();
            board[selectedPiece[0]][selectedPiece[1]] = 0;

			if(pieceColor==1){
				var pieceMove = $('.white-box[name=' + newPiecePlace + ']')
                if(newPiecePlace[0] == '0'){
                    $(pieceMove.append("
").children()[0]).append("
");
                    board[newPiecePlace[0]][newPiecePlace[1]] = 2;

                }else{
                    pieceMove.append("
");
				    board[newPiecePlace[0]][newPiecePlace[1]] = 1;

                }

			}else if(pieceColor==-1){
                var pieceMove = $('.white-box[name=' + newPiecePlace + ']');
                if(newPiecePlace[0] == '7'){
				    $(pieceMove.append("
").children()[0]).append("
");
				    board[newPiecePlace[0]][newPiecePlace[1]] = -2;

                }else{
                    pieceMove.append("
");
                    board[newPiecePlace[0]][newPiecePlace[1]] = -1;

                }
			}

			isSelected = false;

			$('.white-box[name=' + selectedPiece + ']').css("background-color", "white");
			$('.white-box[name=' + rigthPiecePlace + ']').css("background-color", "white");
			$('.white-box[name=' + leftPiecePlace + ']').css("background-color", "white");

			selectedPiece = null;
			rigthPiecePlace = null;
			leftPiecePlace = null;

            onKeepJumping(newPiecePlace)

            handPlay = (handPlay == 1) ? -1 : 1;

            //makeOpponentJump(newPiecePlace);
		}

	}

}

function onKeepJumping(newPlace) {
    if(keepJumping != null){
        var leftRightBox = [];
        var coordX = parseInt(newPlace[0]);
        var coordY = parseInt(newPlace[1]);

        leftRightBox = getleftRightIndex(coordX, coordY);

        if(leftRightBox[0] != null){
            coloredOnJumpPiece(parseInt(leftRightBox[0][0]), parseInt(leftRightBox[0][1]), 'L');
        }

        if(leftRightBox[1] != null){
            coloredOnJumpPiece(parseInt(leftRightBox[1][0]), parseInt(leftRightBox[1][1]), 'R');
        }
    }

}

function makeOpponentJump(placeMoved){
    var leftRightBox = [];
    var coordX = parseInt(placeMoved[0]);
    var coordY = parseInt(placeMoved[1]);

    if(selectedPieceColor == -1){
        keepJumping = 1;
        leftRightBox = getleftRightIndex(coordX, coordY);
        keepJumping = null;

        if(leftRightBox[0] != null){
            if(board[leftRightBox[0][0]][leftRightBox[0][1]] == 1){
                selectedPieceColor = 1;
                opponentJump = leftRightBox[0][0] + '' + leftRightBox[0][1];
                coloredOnJumpPiece(parseInt(selectedPiece[0]), parseInt(selectedPiece[1]), 'R');
            }
        }

        if(leftRightBox[1] != null){
            if(board[leftRightBox[1][0]][leftRightBox[1][1]] == 1){
                selectedPieceColor = 1;
                opponentJump = leftRightBox[1][0] + '' + leftRightBox[1][1];
                coloredOnJumpPiece(parseInt(selectedPiece[0]), parseInt(selectedPiece[1]), 'L');
            }
        }

    }else if(selectedPieceColor == 1){
        keepJumping = 1;
        leftRightBox = getleftRightIndex(coordX, coordY);
        keepJumping = null;

        if(leftRightBox[0] != null){
            if(board[leftRightBox[0][0]][leftRightBox[0][1]] == -1 && board[leftRightBox[1][0]][leftRightBox[1][1]] == 0){
                selectedPieceColor = -1;
                opponentJump = leftRightBox[0][0] + '' + leftRightBox[0][1];
                coloredOnJumpPiece(parseInt(selectedPiece[0]), parseInt(selectedPiece[1]), 'R');
            }

        }

        else if(leftRightBox[1] != null)
            if(board[leftRightBox[1][0]][leftRightBox[1][1]] == -1 && board[leftRightBox[0][0]][leftRightBox[0][1]] == 0){
                selectedPieceColor = -1;
                opponentJump = leftRightBox[1][0] + '' + leftRightBox[1][1];
                coloredOnJumpPiece(parseInt(selectedPiece[0]), parseInt(selectedPiece[1]), 'L');

        }

    }

}
<|endoftext|>


<commit_before>function createWorkspace(path, collectionId, menu, stopEventListener) {
  var safePath = '';
  $("#working-on").on('click', function () {
  }); // add event listener to mainNav

  if (stopEventListener) {
    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.removeEventListener('click', Florence.Handler, true);
    };
    return false;
  } else {
    var currentPath = '';
    if (path) {
      currentPath = path;
      safePath = checkPathSlashes(currentPath);
    }

    Florence.globalVars.pagePath = safePath;
    if (Florence.globalVars.welsh !== true) {
      document.cookie = "lang=" + "en;path=/";
    } else {
      document.cookie = "lang=" + "cy;path=/";
    }
    Florence.refreshAdminMenu();

    var workSpace = templates.workSpace(Florence.tredegarBaseUrl + safePath);
    $('.section').html(workSpace);

    document.getElementById('iframe').onload = function (e) {
      e.stopImmediatePropagation();
      $('.browser-location').val(Florence.tredegarBaseUrl + Florence.globalVars.pagePath);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.addEventListener('click', Florence.Handler, true);

      if (Florence.globalVars.welsh !== true) {
        $('#nav--workspace__welsh').empty().append('Language: English');
      } else {
        $('#nav--workspace__welsh').empty().append('Language: Welsh');
      }

      //click handlers
      $('.nav--workspace > li').click(function () {
        menu = '';
        if (Florence.Editor.isDirty) {
          var result = confirm("You have unsaved changes. Are you sure you want to continue");
          if (result === true) {
            Florence.Editor.isDirty = false;
            processMenuClick(this);
          } else {
            return false;
          }
        } else {
          processMenuClick(this);
        }
      });

      function processMenuClick(clicked) {
        var menuItem = $(clicked);

        $('.nav--workspace li').removeClass('selected');
        menuItem.addClass('selected');

        if (menuItem.is('#browse')) {
          loadBrowseScreen(collectionId, 'click');
        } else if (menuItem.is('#create')) {
          Florence.globalVars.pagePath = getPathName();
          loadCreateScreen(Florence.globalVars.pagePath, collectionId);
        } else if (menuItem.is('#edit')) {
          Florence.globalVars.pagePath = getPathName();
          loadPageDataIntoEditor(Florence.globalVars.pagePath, Florence.collection.id);
        } else {
          loadBrowseScreen(collectionId);
        }
      }

      $('#nav--workspace__welsh').on('click', function () {
        Florence.globalVars.welsh = Florence.globalVars.welsh === false ? true : false;
        createWorkspace(Florence.globalVars.pagePath, collectionId);
      });

      $('.workspace-menu').on('click', '.btn-browse-create', function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
        Florence.globalVars.pagePath = dest;
        $('.nav--workspace li').removeClass('selected');
        $("#create").addClass('selected');
        loadCreateScreen(Florence.globalVars.pagePath, collectionId);
      });

      $('.workspace-menu').on('click', '.btn-browse-edit', function () {
        var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
        Florence.globalVars.pagePath = dest;
        $('.nav--workspace li').removeClass('selected');
        $("#edit").addClass('selected');
        loadPageDataIntoEditor(Florence.globalVars.pagePath, collectionId);
      });

      if (menu === 'edit') {
        $('.nav--workspace li').removeClass('selected');
        $("#edit").addClass('selected');
        loadPageDataIntoEditor(Florence.globalVars.pagePath, collectionId);
      } else {
        //browse screen by default
        $('.nav--workspace li').removeClass('selected');
        $("#browse").addClass('selected');
        loadBrowseScreen(collectionId, 'click');
      }
    };
  }
}

<commit_msg>Take out default browse. Make it explicit<commit_after>function createWorkspace(path, collectionId, menu, stopEventListener) {
  var safePath = '';
  $("#working-on").on('click', function () {
  }); // add event listener to mainNav

  if (stopEventListener) {
    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.removeEventListener('click', Florence.Handler, true);
    };
    return false;
  } else {
    var currentPath = '';
    if (path) {
      currentPath = path;
      safePath = checkPathSlashes(currentPath);
    }

    Florence.globalVars.pagePath = safePath;
    if (Florence.globalVars.welsh !== true) {
      document.cookie = "lang=" + "en;path=/";
    } else {
      document.cookie = "lang=" + "cy;path=/";
    }
    Florence.refreshAdminMenu();

    var workSpace = templates.workSpace(Florence.tredegarBaseUrl + safePath);
    $('.section').html(workSpace);

    document.getElementById('iframe').onload = function (e) {
      e.stopImmediatePropagation();
      $('.browser-location').val(Florence.tredegarBaseUrl + Florence.globalVars.pagePath);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.addEventListener('click', Florence.Handler, true);

      if (Florence.globalVars.welsh !== true) {
        $('#nav--workspace__welsh').empty().append('Language: English');
      } else {
        $('#nav--workspace__welsh').empty().append('Language: Welsh');
      }

      //click handlers
      $('.nav--workspace > li').click(function () {
        menu = '';
        if (Florence.Editor.isDirty) {
          var result = confirm("You have unsaved changes. Are you sure you want to continue");
          if (result === true) {
            Florence.Editor.isDirty = false;
            processMenuClick(this);
          } else {
            return false;
          }
        } else {
          processMenuClick(this);
        }
      });

      function processMenuClick(clicked) {
        var menuItem = $(clicked);

        $('.nav--workspace li').removeClass('selected');
        menuItem.addClass('selected');

        if (menuItem.is('#browse')) {
          loadBrowseScreen(collectionId, 'click');
        } else if (menuItem.is('#create')) {
          Florence.globalVars.pagePath = getPathName();
          loadCreateScreen(Florence.globalVars.pagePath, collectionId);
        } else if (menuItem.is('#edit')) {
          Florence.globalVars.pagePath = getPathName();
          loadPageDataIntoEditor(Florence.globalVars.pagePath, Florence.collection.id);
        } else {
          loadBrowseScreen(collectionId);
        }
      }

      $('#nav--workspace__welsh').on('click', function () {
        Florence.globalVars.welsh = Florence.globalVars.welsh === false ? true : false;
        createWorkspace(Florence.globalVars.pagePath, collectionId, 'browse');
      });

      $('.workspace-menu').on('click', '.btn-browse-create', function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
        Florence.globalVars.pagePath = dest;
        $('.nav--workspace li').removeClass('selected');
        $("#create").addClass('selected');
        loadCreateScreen(Florence.globalVars.pagePath, collectionId);
      });

      $('.workspace-menu').on('click', '.btn-browse-edit', function () {
        var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
        Florence.globalVars.pagePath = dest;
        $('.nav--workspace li').removeClass('selected');
        $("#edit").addClass('selected');
        loadPageDataIntoEditor(Florence.globalVars.pagePath, collectionId);
      });

      if (menu === 'edit') {
        $('.nav--workspace li').removeClass('selected');
        $("#edit").addClass('selected');
        loadPageDataIntoEditor(Florence.globalVars.pagePath, collectionId);
      } else if (menu === 'browse') {
        $('.nav--workspace li').removeClass('selected');
        $("#browse").addClass('selected');
        loadBrowseScreen(collectionId, 'click');
      }
    };
  }
}

<|endoftext|>


<commit_before>(function() {
    'use strict';
    /*global  sap, jQuery, openui5, CKEDITOR, window */
    jQuery.sap.declare('openui5.CKEditor');

    // --- add CKEditor library to thirdparty modules else use CDN
    // var sPath = 'thirdparty.CKEditor.';
    // jQuery.sap.require(sPath + 'CKEditor');
    // jQuery.includeStyleSheet(jQuery.sap.getModulePath(sPath, '/') + 'content.css');

    var sCDNLink = 'http://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.3.2/ckeditor.js';
    jQuery.sap.includeScript(sCDNLink);

    sap.ui.core.Control.extend('openui5.CKEditor', {
        metadata: {
            properties: {
                'value': {
                    type: 'string',
                    group: 'Data',
                    bindable: 'bindable',
                    defaultValue: ''
                },
                'width': {
                    type: 'sap.ui.core.CSSSize',
                    group: 'Dimension',
                    defaultValue: '100%'
                },
                'height': {
                    type: 'sap.ui.core.CSSSize',
                    group: 'Dimension',
                    defaultValue: '200px'
                },
                'toolbar': {
                    type: 'string',
                    defaultValue: 'Full'
                },
                'inline': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: false
                },
                'editable': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: true
                },
                'required': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: false
                },
                'uiColor': {
                    type: 'string',
                    defaultValue: '#FAFAFA'
                }
            },
            events: {
                'change': {},
                'ready': {}
            }
        },
        renderer: function(oRm, oControl) {
            oRm.write('<textarea ');
            oRm.writeAttribute('id', oControl.getId() + '-textarea');
            oRm.write('>');
            oRm.write(oControl.getValue());
            oRm.write('</textarea>');
        }
    });

    /* Basic toolbar */
    openui5.CKEditor.prototype.toolBarBasic = [
        ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-']
    ];

    /* Standard toolbar */
    openui5.CKEditor.prototype.toolBarFull = [{
            name: 'basicstyles',
            items: ['Bold', 'Italic', 'Strike', 'Underline']
        }, {
            name: 'paragraph',
            items: ['BulletedList', 'NumberedList', 'Blockquote']
        }, {
            name: 'editing',
            items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
        }, {
            name: 'links',
            items: ['Link', 'Unlink', 'Anchor']
        }, {
            name: 'tools',
            items: ['SpellChecker', 'Maximize']
        },
        '/', {
            name: 'styles',
            items: ['Format', 'FontSize', 'TextColor', 'PasteText', 'PasteFromWord', 'RemoveFormat']
        }, {
            name: 'insert',
            items: ['Image', 'SpecialChar']
        }, {
            name: 'forms',
            items: ['Outdent', 'Indent']
        }, {
            name: 'clipboard',
            items: ['Undo', 'Redo']
        }, {
            name: 'document',
            items: ['PageBreak', 'Source']
        }
    ];

    openui5.CKEditor.prototype.init = function() {
        this.textAreaId = this.getId() + '-textarea';
    };

    openui5.CKEditor.prototype.setValue = function(sValue) {
        this.setProperty('value', sValue, true);
        if (this.editor && sValue !== this.editor.getData()) {
            this.editor.setData(sValue);

        }
    };

    openui5.CKEditor.prototype.getText = function() {
        return this.editor.document.getBody().getText();
    };

    openui5.CKEditor.prototype.setInline = function(bInline) {
        this.setProperty('inline', bInline, true);
    };

    openui5.CKEditor.prototype.setEditable = function(bEditable) {
        this.setProperty('inline', bEditable, true);
        if (this.editor) {
            this.editor.setReadOnly(!bEditable);
        }

    };

    openui5.CKEditor.prototype.onAfterRendering = function() {
        if (!this._bEditorCreated) {
            // first rendering: instantiate the editor
            this.afterFirstRender();
        } else {
            // subsequent re-rendering:
            this.editor = CKEDITOR.instances[this.textAreaId];
            var value;
            if (this.editor && (value = this.getValue())) {
                this.editor.setData(value);
            }
        }

    };
    openui5.CKEditor.prototype._getOptions = function() {
        var options = {};
        options.toolbar = (this.getToolbar() === 'Basic') ? this.toolBarBasic : this.toolBarFull;
        options.disableNativeSpellChecker = false;
        options.uiColor = this.getUiColor();
        options.height = this.getHeight();
        options.width = this.getWidth();
        options.toolbarStartupExpanded = true;
        options.disableNativeSpellChecker = false;
        options.removePlugins = 'scayt,contextmenu,tabletools,liststyle';
        options.browserContextMenuOnCtrl = true;
        return options;
    };

    openui5.CKEditor.prototype.afterFirstRender = function() {
        // wait until the script is ready
        if (!window.CKEDITOR || CKEDITOR.status !== 'loaded') {
            jQuery.sap.delayedCall(10, this, 'afterFirstRender'); // '10' to avoid busy waiting
            return;
        }

        CKEDITOR.disableAutoInline = true;
        if (this.getInline()) {
            this.editor = CKEDITOR.inline(this.textAreaId, this._getOptions());
        } else {
            this.editor = CKEDITOR.replace(this.textAreaId, this._getOptions());
        }

        this.editor.on('change', jQuery.proxy(this.onEditorChange, this));
        this.editor.on('blur', jQuery.proxy(this.onEditorChange, this));
        this.editor.on('mode', jQuery.proxy(this.onModeChange, this));
        this.editor.on('instanceReady', jQuery.proxy(this.onInstanceReady, this));
    };

    openui5.CKEditor.prototype.onEditorChange = function() {
        //on editor change update control value
        var oldVal = this.getValue(),
            newVal = this.editor.getData();

        if ((oldVal != newVal) && !this.bExiting) {
            this.setProperty('value', newVal, true); // suppress rerendering
            this.fireChange({
                oldValue: oldVal,
                newValue: newVal
            });
        }

    };

    openui5.CKEditor.prototype.onModeChange = function() {
        // update value after source has changed
        if (this.evtSource === true && this.editor.getCommand('source').state === CKEDITOR.TRISTATE_OFF) {
            this.onEditorChange();
        }

        if (this.editor.mode === 'source') {
            this.evtSource = true;
        } else {
            this.evtSource = false;
        }
    };

    openui5.CKEditor.prototype.onInstanceReady = function() {
        // overwrite gradient with solid background
        jQuery.sap.byId(this.editor.id + '_top').css('background', this.editor.getUiColor());
        jQuery.sap.byId(this.editor.id + '_bottom').css('background', this.editor.getUiColor());
    };

    openui5.CKEditor.prototype.exit = function() {
        this.editor.destroy();
    };

})();<commit_msg>inline test<commit_after>(function() {
    'use strict';
    /*global  sap, jQuery, openui5, CKEDITOR, window */
    jQuery.sap.declare('openui5.CKEditor');

    // --- add CKEditor library to thirdparty modules else use CDN
    // var sPath = 'thirdparty.CKEditor.';
    // jQuery.sap.require(sPath + 'CKEditor');
    // jQuery.includeStyleSheet(jQuery.sap.getModulePath(sPath, '/') + 'content.css');

    var sCDNLink = '//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.3.2/ckeditor.js';
    jQuery.sap.includeScript(sCDNLink);

    sap.ui.core.Control.extend('openui5.CKEditor', {
        metadata: {
            properties: {
                'value': {
                    type: 'string',
                    group: 'Data',
                    bindable: 'bindable',
                    defaultValue: ''
                },
                'width': {
                    type: 'sap.ui.core.CSSSize',
                    group: 'Dimension',
                    defaultValue: '100%'
                },
                'height': {
                    type: 'sap.ui.core.CSSSize',
                    group: 'Dimension',
                    defaultValue: '200px'
                },
                'toolbar': {
                    type: 'string',
                    defaultValue: 'Full'
                },
                'inline': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: false
                },
                'editable': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: true
                },
                'required': {
                    type: 'boolean',
                    group: 'Misc',
                    defaultValue: false
                },
                'uiColor': {
                    type: 'string',
                    defaultValue: '#FAFAFA'
                }
            },
            events: {
                'change': {},
                'ready': {}
            }
        },
        renderer: function(oRm, oControl) {
            oRm.write('<textarea ');
            oRm.writeAttribute('id', oControl.getId() + '-textarea');
            oRm.write('>');
            oRm.write(oControl.getValue());
            oRm.write('</textarea>');
        }
    });

    /* Basic toolbar */
    openui5.CKEditor.prototype.toolBarBasic = [
        ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-']
    ];

    /* Standard toolbar */
    openui5.CKEditor.prototype.toolBarFull = [{
            name: 'basicstyles',
            items: ['Bold', 'Italic', 'Strike', 'Underline']
        }, {
            name: 'paragraph',
            items: ['BulletedList', 'NumberedList', 'Blockquote']
        }, {
            name: 'editing',
            items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
        }, {
            name: 'links',
            items: ['Link', 'Unlink', 'Anchor']
        }, {
            name: 'tools',
            items: ['SpellChecker', 'Maximize']
        },
        '/', {
            name: 'styles',
            items: ['Format', 'FontSize', 'TextColor', 'PasteText', 'PasteFromWord', 'RemoveFormat']
        }, {
            name: 'insert',
            items: ['Image', 'SpecialChar']
        }, {
            name: 'forms',
            items: ['Outdent', 'Indent']
        }, {
            name: 'clipboard',
            items: ['Undo', 'Redo']
        }, {
            name: 'document',
            items: ['PageBreak', 'Source']
        }
    ];

    openui5.CKEditor.prototype.init = function() {
        this.textAreaId = this.getId() + '-textarea';
    };

    openui5.CKEditor.prototype.setValue = function(sValue) {
        this.setProperty('value', sValue, true);
        if (this.editor && sValue !== this.editor.getData()) {
            this.editor.setData(sValue);

        }
    };

    openui5.CKEditor.prototype.getText = function() {
        return this.editor.document.getBody().getText();
    };

    openui5.CKEditor.prototype.setInline = function(bInline) {
        this.setProperty('inline', bInline, true);
    };

    openui5.CKEditor.prototype.setEditable = function(bEditable) {
        this.setProperty('inline', bEditable, true);
        if (this.editor) {
            this.editor.setReadOnly(!bEditable);
        }

    };

    openui5.CKEditor.prototype.onAfterRendering = function() {
        if (!this._bEditorCreated) {
            // first rendering: instantiate the editor
            this.afterFirstRender();
        } else {
            // subsequent re-rendering:
            this.editor = CKEDITOR.instances[this.textAreaId];
            var value;
            if (this.editor && (value = this.getValue())) {
                this.editor.setData(value);
            }
        }

    };
    openui5.CKEditor.prototype._getOptions = function() {
        var options = {};
        options.toolbar = (this.getToolbar() === 'Basic') ? this.toolBarBasic : this.toolBarFull;
        options.disableNativeSpellChecker = false;
        options.uiColor = this.getUiColor();
        options.height = this.getHeight();
        options.width = this.getWidth();
        options.toolbarStartupExpanded = true;
        options.disableNativeSpellChecker = false;
        options.removePlugins = 'scayt,contextmenu,tabletools,liststyle';
        options.browserContextMenuOnCtrl = true;
        return options;
    };

    openui5.CKEditor.prototype.afterFirstRender = function() {
        // wait until the script is ready
        if (!window.CKEDITOR || CKEDITOR.status !== 'loaded') {
            jQuery.sap.delayedCall(10, this, 'afterFirstRender'); // '10' to avoid busy waiting
            return;
        }

        CKEDITOR.disableAutoInline = true;
        if (this.getInline()) {
            this.editor = CKEDITOR.inline(this.textAreaId, this._getOptions());
        } else {
            this.editor = CKEDITOR.replace(this.textAreaId, this._getOptions());
        }

        this.editor.on('change', jQuery.proxy(this.onEditorChange, this));
        this.editor.on('blur', jQuery.proxy(this.onEditorChange, this));
        this.editor.on('mode', jQuery.proxy(this.onModeChange, this));
        this.editor.on('instanceReady', jQuery.proxy(this.onInstanceReady, this));
    };

    openui5.CKEditor.prototype.onEditorChange = function() {
        //on editor change update control value
        var oldVal = this.getValue(),
            newVal = this.editor.getData();

        if ((oldVal != newVal) && !this.bExiting) {
            this.setProperty('value', newVal, true); // suppress rerendering
            this.fireChange({
                oldValue: oldVal,
                newValue: newVal
            });
        }

    };

    openui5.CKEditor.prototype.onModeChange = function() {
        // update value after source has changed
        if (this.evtSource === true && this.editor.getCommand('source').state === CKEDITOR.TRISTATE_OFF) {
            this.onEditorChange();
        }

        if (this.editor.mode === 'source') {
            this.evtSource = true;
        } else {
            this.evtSource = false;
        }
    };

    openui5.CKEditor.prototype.onInstanceReady = function() {
        // overwrite gradient with solid background
        jQuery.sap.byId(this.editor.id + '_top').css('background', this.editor.getUiColor());
        jQuery.sap.byId(this.editor.id + '_bottom').css('background', this.editor.getUiColor());
    };

    openui5.CKEditor.prototype.exit = function() {
        this.editor.destroy();
    };

})();<|endoftext|>


<commit_before>'use strict'

// TODO: prefill login form

let I = {}

Object.defineProperty(window, 'I', {
  get: () => I,
  set: (val) => Object.assign(I, val)
})

let BBF

Object.defineProperty(I, 'BaseBuyForm', {
  get: () => BBF,
  set: (val) => {
    BBF = val
    BBF.prototype.submit_handler = function () {
      if (!this.is_valid()) return false

      let $ = window.$
      let $buttons = $('.checkout_btn, .confirm_vat_btn')
      disable($buttons)
      $buttons.html($(' Loading...'))

      // don't close the window here
    }
  }
})

function disable ($el) {
  $el.prop('disabled', true)
  $el.css('opacity', 0.7)
  $el.css('-webkit-filter', 'grayscale(70%)')
}

function purchase_inject () {
  let $ = window.$
  let form = $('form.buy_form_widget')
  form.attr('target', '_self')

  // TODO: use `file:///` protocol instead, if that's no issue.
  let css = $(``)[0]

  css.onload = function () {
    console.log('CSS IN IFRAME LOADED')
  }

  document.body.appendChild(css)
}

function itch_inject () {
  let $ = window.$
  $('.header_widget, .footer').css('pointer-events', 'none')
}

function login_inject () {
  itch_inject()

  let CredentialsStore = require('electron').remote.require('./stores/credentials-store')
  let me = CredentialsStore.get_me()

  let $ = window.$
  let $page = $('.user_login_page')
  let $title = $page.find('.stat_header_widget h2')
  $title.text(`Verify password for ${me.username}`)

  let $form = $page.find('.form')

  let $username = $form.find('input[name=username]')
  $username.val(me.username)
  $username.closest('.input_row').css('display', 'none')

  let $password = $form.find('input[name=password]')
  $password.focus()

  $form.find('.buttons .line').css('display', 'none')
}

document.addEventListener('DOMContentLoaded', () => {
  let url = require('electron').remote.require('./util/url')
  let host = url.subdomain_to_domain(window.location.hostname)

  if (['itch.io', 'itch.ovh', 'localhost.com'].indexOf(host) === -1) {
    // don't inject anything on non-itch pages
    return
  }

  let tokens = window.location.pathname.split('/')
  let last_token = tokens[tokens.length - 1]

  switch (last_token) {
    case 'purchase':
      purchase_inject()
      break
    case 'login':
      login_inject()
      break
  }
})
<commit_msg>:clap: Closes #234<commit_after>'use strict'

// TODO: prefill login form

let I = {}

Object.defineProperty(window, 'I', {
  get: () => I,
  set: (val) => Object.assign(I, val)
})

let BBF

Object.defineProperty(I, 'BaseBuyForm', {
  get: () => BBF,
  set: (val) => {
    BBF = val
    BBF.prototype.submit_handler = function () {
      if (!this.is_valid()) return false

      let $ = window.$
      let $buttons = $('.checkout_btn, .confirm_vat_btn')
      disable($buttons)
      $buttons.html($(' Loading...'))
      $buttons.not(':eq(0)').hide()

      // don't close the window here
    }
  }
})

function disable ($el) {
  $el.prop('disabled', true)
  $el.css('opacity', 0.7)
  $el.css('-webkit-filter', 'grayscale(70%)')
}

function purchase_inject () {
  let $ = window.$
  let form = $('form.buy_form_widget')
  form.attr('target', '_self')

  // TODO: use `file:///` protocol instead, if that's no issue.
  let css = $(``)[0]

  css.onload = function () {
    console.log('CSS IN IFRAME LOADED')
  }

  document.body.appendChild(css)
}

function itch_inject () {
  let $ = window.$
  $('.header_widget, .footer').css('pointer-events', 'none')
}

function login_inject () {
  itch_inject()

  let CredentialsStore = require('electron').remote.require('./stores/credentials-store')
  let me = CredentialsStore.get_me()

  let $ = window.$
  let $page = $('.user_login_page')
  let $title = $page.find('.stat_header_widget h2')
  $title.text(`Verify password for ${me.username}`)

  let $form = $page.find('.form')

  let $username = $form.find('input[name=username]')
  $username.val(me.username)
  $username.closest('.input_row').css('display', 'none')

  let $password = $form.find('input[name=password]')
  $password.focus()

  $form.find('.buttons .line').css('display', 'none')
}

document.addEventListener('DOMContentLoaded', () => {
  let url = require('electron').remote.require('./util/url')
  let host = url.subdomain_to_domain(window.location.hostname)

  if (['itch.io', 'itch.ovh', 'localhost.com'].indexOf(host) === -1) {
    // don't inject anything on non-itch pages
    return
  }

  let tokens = window.location.pathname.split('/')
  let last_token = tokens[tokens.length - 1]

  switch (last_token) {
    case 'purchase':
      purchase_inject()
      break
    case 'login':
      login_inject()
      break
  }
})
<|endoftext|>


<commit_before>/*
 CKEditor Addons
 */
CKEDITOR.define("confirmChanges", {});
CKEDITOR.define("validateText", {});
CKEDITOR.define("getTextHistory", {});

CKEDITOR.newCommandWithExecution = function (executionFunc) {
    return {
        modes: {wysiwyg: 1, source: 1},// This command works in both editing modes.
        editorFocus: false,// This command will not auto focus editor before execution.
        canUndo: false,// This command requires no undo snapshot.
        exec: executionFunc
    }
};

CKEDITOR.plugins.add("documentSaver", {
    init: function (editor) {
        var pluginName = "documentSaver";
        editor.documentSnapshot = editor.getData();
        editor.blurHandler = function (e) {
            if (e.editor.checkDirty()) {
                e.editor.openDialog(pluginName);
            }
        };
        editor.focusHandler = function (e) {
            e.removeListener();
            e.editor.on('blur', e.editor.blurHandler);
        };
        var switchToolbarCommandFunction = function (e) {
            var element = e.element;
            if (e.elementMode == 1) {
                e.execCommand("toolbarswitch");
            }
            for (var key in CKEDITOR.instances) {
                var editor = CKEDITOR.instances[key];
                if (element == editor.element) {
                    return editor;
                }
            }
        };

        editor.on('blur', editor.blurHandler);

        function saveData(e, noCallback) {
            editor.documentSnapshot = e.getData();
            e.resetDirty();
            if (noCallback) {
                e.removeListener('blur', e.blurHandler);
                e.focusManager.unlock();
                e.element.$.blur();
                e.focusManager.blur();
                e.on("focus", e.focusHandler);
            }
        }

        var confirmBeforeSwitch = function (e, callback) {
            if (!callback) {
                e = switchToolbarCommandFunction(e);
            }
            CKEDITOR.fireOnce("confirmChangesEvent", {callback: callback}, e);
            saveData(e, !callback);
        };

        var confirmNoEvent = function (e, callback) {
            if (!callback) {
                e = switchToolbarCommandFunction(e);
            }
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, e);
            saveData(e, !callback);
        };

        var confirmWithEvent = function (e) {
            e = switchToolbarCommandFunction(e);
            var callback = Imcms.Events.getCallback("TextEditorRedirect");
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, e);
            e.resetDirty();
        };
        var confirmCommandWithEvent = CKEDITOR.newCommandWithExecution(confirmWithEvent);
        editor.addCommand("confirmChanges", confirmCommandWithEvent);
        editor.ui.addButton('confirm', {
            label: 'Save all changes',
            command: "confirmChanges",
            icon: "images/ic_apply.png"
        });

        var confirmCommandNoEvent = CKEDITOR.newCommandWithExecution(confirmNoEvent);
        editor.addCommand("confirmChangesWithoutEvent", confirmCommandNoEvent);

        var confirmCommandBeforeSwitch = CKEDITOR.newCommandWithExecution(confirmBeforeSwitch);
        editor.addCommand("confirmChangesBeforeSwitch", confirmCommandBeforeSwitch);

        var cancelCommandFunction = function (e) {
            var newEditor = switchToolbarCommandFunction(e),
                hideCommand = function (e) {
                    setTimeout(function () {
                        e.removeListener('instanceReady', hideCommand);
                        e.setData(e.documentSnapshot);
                        e.removeListener('blur', e.blurHandler);
                        e.focusManager.unlock();
                        e.element.$.blur();
                        e.focusManager.blur();
                        e.on("focus", e.focusHandler);
                    }, 1);
                };
            if (newEditor != e) {
                newEditor.on('instanceReady', hideCommand.bind(null, newEditor));

            } else {
                hideCommand(e);
            }
        };
        var cancelCommandDefinition = CKEDITOR.newCommandWithExecution(
            Imcms.Events.getCallbackOr("TextEditorRedirect", cancelCommandFunction)
        );
        editor.addCommand("cancelChanges", cancelCommandDefinition);
        editor.ui.addButton('cancel', {
            label: 'Cancel all changes and restore document to previous state',
            command: "cancelChanges",
            icon: "images/ic_cancel.png"
        });

        var saveCommandDefinition = CKEDITOR.newCommandWithExecution(function (e) {
            var $button = $('.' + e.id).find('.cke_button__savedata_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            confirmNoEvent(e, function () {
                $button.css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_save.png" + ")"
                });
            });
        });
        editor.addCommand("saveChanges", saveCommandDefinition);
        editor.ui.addButton('saveData', {
            label: 'Save all changes',
            command: "saveChanges",
            icon: "images/ic_save.png"
        });
    }
});
CKEDITOR.dialog.add("documentSaver", function (e) {
    return {
        title: 'Save changes',
        width: 200,
        height: 25,
        onOk: function () {
            e.execCommand("confirmChanges");
        },
        onCancel: function () {
            e.execCommand("cancelChanges");
        },
        onHide: function () {
            setTimeout(function () {
                e.focusManager.unlock();
                e.element.$.blur();
                e.focusManager.blur();
                $(e.focusManager.currentActive).blur();
            }, 500);
        },
        contents: [
            {
                id: 'general',
                label: 'Settings',
                elements: [
                    {
                        type: 'html',
                        onLoad: function (e) {
                            var $dialog = $(e.sender.parts.dialog.$);
                            $dialog.find(".cke_resizer.cke_resizer_ltr").hide(); // dialog resize triangle
                            // in Safari close button goes to wrong side,
                            $dialog.find(".cke_dialog_close_button").css("float", "right");
                        },
                        html: '
You have changed the text. Do you wish to save it?
'
                    }
                ]
            }
        ]
    };
});

CKEDITOR.defineToolbar = function (editor) {
    var prefix;

    if (editor.elementMode == 1) { // full-screen editor mode
        editor.config.maxToolbar = true;
        prefix = "max";

    } else {
        editor.config.maxToolbar = false;
        prefix = "min";
    }

    if (editor.element.data("contenttype") === "text") {
        return prefix + "PlainText";

    } else if (editor.element.data("contenttype") === "from-html") {
        return prefix + "TextToolbar";

    } else {
        return prefix + "HtmlToolbar";
    }
};

CKEDITOR.switchFormat = false;

CKEDITOR.plugins.add("switchFormatToHTML", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToHTML', {
            label: 'Switch format to HTML',
            command: "switchFormat",
            icon: "images/switch-between-html-and-text-mode.png"
        });
    }
});

CKEDITOR.plugins.add("switchFormatToText", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToText', {
            label: 'Switch format to text',
            command: "switchFormat",
            icon: "images/plain_text.png"
        });
    }
});

CKEDITOR.plugins.add("fileBrowser", {
    init: function (editor) {

        var onChooseFile = function () {
            Imcms.Editors.Content.showDialog({
                onApply: $.proxy(onFileChosen, this),
                onCancel: $.proxy(onFileChosen, this)
            });
            editor.focusManager.blur();
            editor.element.$.blur();
        };
        var onFileChosen = function (data) {
            if (data) {
                editor.insertHtml('
', 'unfiltered_html');
            }
            editor.focusManager.focus();
            editor.element.$.focus();
        };

        var openBrowserCommandDefinition = CKEDITOR.newCommandWithExecution(onChooseFile);
        editor.addCommand("openBrowser", openBrowserCommandDefinition);

        editor.ui.addButton('openBrowser', {
            label: 'Open Image Browser',
            command: "openBrowser",
            icon: "images/ic_images.png"
        });
    }
});

CKEDITOR.plugins.add("w3cValidator", {
    init: function (editor) {
        var w3cValidateCommand = function (e) {
            var $button = $('.' + e.id).find('.cke_button__w3cvalidate_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("validateText", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + (data.result ? "images/ic_valid.png" : "images/ic_invalid.png") + ")"
                    });

                    if (!data.result) {
                        $(e.element.$).data("w3cValidateData", data);
                        e.execCommand("w3cValidateDialog", data);
                    }
                }
            }, e);
        };
        var w3cValidateCommandDefinition = CKEDITOR.newCommandWithExecution(w3cValidateCommand);
        editor.addCommand("w3cValidate", w3cValidateCommandDefinition);
        editor.addCommand("w3cValidateDialog", new CKEDITOR.dialogCommand("w3cValidationResultDialog"));

        editor.ui.addButton('w3cValidate', {
            label: 'Validate Content over W3C',
            command: "w3cValidate",
            icon: "images/ic_w3c.png"
        });
    }
});
CKEDITOR.dialog.add("w3cValidationResultDialog", function (e) {
    var $wrapper = $("
"),
        $content = $("
").addClass("imcms-w3c-errors").appendTo($wrapper),
        data = $(e.element.$).data("w3cValidateData");

    $("
").append($("
").text("Validation Output: " + data.data.errors.length + " Errors")).appendTo($content);

    data.data.errors.forEach(function (item, pos) {
        var $container = $("
").addClass("imcms-w3c-error").appendTo($content),
            $errorMessage = $("
").text(pos + 1 + ". " + item.message.charAt(0).toUpperCase() + item.message.slice(1)).appendTo($container),
            $sourceContainer = $("
").appendTo($container),
            $source = $("").addClass("language-html").html(item.line + ": " + item.source.replace(/(<([^>]+)>)/ig, "")).appendTo($sourceContainer);

        Prism.highlightElement($source[0]);
    });

    return {
        title: 'Validation Result Dialog',
        width: 600,
        minHeight: 250,
        contents: [
            {
                id: 'w3cValidation',
                label: 'Validation',
                elements: [
                    {
                        type: 'html',
                        html: $("
").append($wrapper).html()
                    }
                ]
            }
        ]
    };
});

CKEDITOR.plugins.add("textHistory", {
    init: function (editor) {
        var textHistoryCommand = function (e) {
            var $button = $('.' + e.id).find('.cke_button__texthistory_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("getTextHistory", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_history.png" + ")"
                    });

                    $(e.element.$).data("textHistoryData", data);
                    e.execCommand("textHistoryDialog", data);
                }
            }, e);
        };
        var textHistoryCommandDefinition = CKEDITOR.newCommandWithExecution(textHistoryCommand);
        editor.addCommand("textHistory", textHistoryCommandDefinition);
        editor.addCommand("textHistoryDialog", new CKEDITOR.dialogCommand("textHistory"));

        editor.ui.addButton('textHistory', {
            label: 'Text History',
            command: "textHistory",
            icon: "images/ic_history.png"
        });
    }
});

CKEDITOR.dialog.add("textHistory", function (e) {
    var $wrapper = $("
").addClass("imcms-text-history"),
        $leftPanel = $("
").addClass("imcms-left-panel").appendTo($wrapper),

        $content = $("
").addClass("imcms-content")
            .css({
                "max-width": "600px",
                "float": "right"
            })
            .appendTo($wrapper),

        data = $(e.element.$).data("textHistoryData")
            .map(function (textHistoryData) {
                textHistoryData.modifiedDate = new Date(textHistoryData.modifiedDate);
                textHistoryData.type = (textHistoryData.type == "HTML")
                    ? "html"
                    : "from-html";
                return textHistoryData;
            })
            .sort(function (a, b) {
                return (a.modifiedDate > b.modifiedDate ? -1 : (a.modifiedDate == b.modifiedDate ? 0 : 1));
            }),

        groupedData = {},
        $selected = undefined,
        selectedItem,
        previousType;

    data.forEach(function (it) {
        var key = it.modifiedDate.format("dd/m/yy");

        if (!(key in groupedData)) {
            groupedData[key] = [];
        }

        groupedData[key].push(it);
    });

    var buttonsShowed = false;

    function addTextHistoryButton(text, onClick) {
        return $("<button>")
            .addClass("imcms-neutral")
            .css("float", "right")
            .html(text)
            .appendTo($wrapper)
            .click(onClick);
    }

    $.each(groupedData, function (key, list) {
        $("
").addClass("imcms-separator").text(key).appendTo($leftPanel);

        list.forEach(function (item) {
            $("
").appendTo($leftPanel)
                .append(item.modifiedDate.format("HH:MM:ss") + " | " + item.modifiedBy)
                .click(function () {
                    if (!buttonsShowed) {
                        addTextHistoryButton("View Page", function () {
                            if (selectedItem.type !== "html") {
                                $content.html($content.text());
                                selectedItem.type = "html";
                            }
                        });
                        addTextHistoryButton("View Source", function () {
                            if (selectedItem.type === "html") {
                                $content.text($content.html());
                                selectedItem.type = "from-html";
                            }
                        });
                        buttonsShowed = true;
                    }

                    if ($selected) {
                        $selected.removeClass("selected");
                    }

                    var callFunc = (item.type === "html")
                        ? "html"
                        : "text";

                    $content[callFunc](item.text);
                    $selected = $(this).addClass("selected");
                    selectedItem = item;
                    previousType = item.type;
                });
        })
    });

    return {
        title: 'Text History Dialog',
        width: 600,
        height: 400,
        contents: [
            {
                id: 'textHistory',
                label: 'Text History',
                elements: [
                    {
                        type: 'html',
                        onLoad: function () {
                            $("#" + this.domId).append($wrapper)
                        },
                        html: ""
                    }
                ]
            }
        ],
        buttons: [
            {
                id: "text history OK button",
                type: "button",
                label: "Write to textfield",
                title: "Write to textfield",
                "class":"cke_dialog_ui_button_ok",
                disabled: false,
                onClick: function () {
                    if (selectedItem) {
                        e.setData(""); // clear previous text
                        var contentType = $(e.element.$).data("contenttype");

                        var callFunc = (contentType === "html")
                            ? "insertHtml"
                            : "insertText";

                        e[callFunc](selectedItem.text);

                        if (selectedItem.type !== contentType) {
                            e.execCommand("switchFormat");
                        }
                    }
                }
            },
            CKEDITOR.dialog.cancelButton
        ]
    };
});<commit_msg>IMCMS-177 - Texteditor bar disappears: - Fixed mode switching.<commit_after>/*
 CKEditor Addons
 */
CKEDITOR.define("confirmChanges", {});
CKEDITOR.define("validateText", {});
CKEDITOR.define("getTextHistory", {});

CKEDITOR.newCommandWithExecution = function (executionFunc) {
    return {
        modes: {wysiwyg: 1, source: 1},// This command works in both editing modes.
        editorFocus: false,// This command will not auto focus editor before execution.
        canUndo: false,// This command requires no undo snapshot.
        exec: executionFunc
    }
};

CKEDITOR.plugins.add("documentSaver", {
    init: function (editor) {
        var pluginName = "documentSaver";
        editor.documentSnapshot = editor.getData();
        editor.blurHandler = function (event) {
            if (event.editor.checkDirty()) {
                event.editor.openDialog(pluginName);
            }
        };
        editor.focusHandler = function (event) {
            event.removeListener();
            event.editor.on('blur', event.editor.blurHandler);
        };
        var switchToolbarCommandFunction = function (event) {
            var element = event.element;
            if (event.elementMode == 1) {
                event.execCommand("toolbarswitch");
            }
            for (var key in CKEDITOR.instances) {
                var editor = CKEDITOR.instances[key];
                if (element == editor.element) {
                    return editor;
                }
            }
        };

        editor.on('blur', editor.blurHandler);

        function saveData(event, noCallback) {
            editor.documentSnapshot = event.getData();
            event.resetDirty();
            if (noCallback) {
                event.removeListener('blur', event.blurHandler);
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                event.on("focus", event.focusHandler);
            }
        }

        function switchModeCallback(e) {
            return function () {
                Imcms.BackgroundWorker.createTask({
                    showProcessWindow: true,
                    refreshPage: true
                })();
                $(e.element.$).click();
            };
        }

        var confirmBeforeSwitch = function (event) {
            var callback = switchModeCallback(event);
            event = switchToolbarCommandFunction(event);
            CKEDITOR.fireOnce("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmNoEvent = function (event, callback) {
            if (!callback) {
                event = switchToolbarCommandFunction(event);
            }
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmWithEvent = function (event) {
            event = switchToolbarCommandFunction(event);
            var callback = Imcms.Events.getCallback("TextEditorRedirect");
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            event.resetDirty();
        };
        var confirmCommandWithEvent = CKEDITOR.newCommandWithExecution(confirmWithEvent);
        editor.addCommand("confirmChanges", confirmCommandWithEvent);
        editor.ui.addButton('confirm', {
            label: 'Save all changes',
            command: "confirmChanges",
            icon: "images/ic_apply.png"
        });

        var confirmCommandNoEvent = CKEDITOR.newCommandWithExecution(confirmNoEvent);
        editor.addCommand("confirmChangesWithoutEvent", confirmCommandNoEvent);

        var confirmCommandBeforeSwitch = CKEDITOR.newCommandWithExecution(confirmBeforeSwitch);
        editor.addCommand("confirmChangesBeforeSwitch", confirmCommandBeforeSwitch);

        var cancelCommandFunction = function (event) {
            var newEditor = switchToolbarCommandFunction(event),
                hideCommand = function (event) {
                    setTimeout(function () {
                        event.removeListener('instanceReady', hideCommand);
                        event.setData(event.documentSnapshot);
                        event.removeListener('blur', event.blurHandler);
                        event.focusManager.unlock();
                        event.element.$.blur();
                        event.focusManager.blur();
                        event.on("focus", event.focusHandler);
                    }, 1);
                };
            if (newEditor != event) {
                newEditor.on('instanceReady', hideCommand.bind(null, newEditor));

            } else {
                hideCommand(event);
            }
        };
        var cancelCommandDefinition = CKEDITOR.newCommandWithExecution(
            Imcms.Events.getCallbackOr("TextEditorRedirect", cancelCommandFunction)
        );
        editor.addCommand("cancelChanges", cancelCommandDefinition);
        editor.ui.addButton('cancel', {
            label: 'Cancel all changes and restore document to previous state',
            command: "cancelChanges",
            icon: "images/ic_cancel.png"
        });

        var saveCommandDefinition = CKEDITOR.newCommandWithExecution(function (event) {
            var $button = $('.' + event.id).find('.cke_button__savedata_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            confirmNoEvent(event, function () {
                $button.css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_save.png" + ")"
                });
            });
        });
        editor.addCommand("saveChanges", saveCommandDefinition);
        editor.ui.addButton('saveData', {
            label: 'Save all changes',
            command: "saveChanges",
            icon: "images/ic_save.png"
        });
    }
});
CKEDITOR.dialog.add("documentSaver", function (event) {
    return {
        title: 'Save changes',
        width: 200,
        height: 25,
        onOk: function () {
            event.execCommand("confirmChanges");
        },
        onCancel: function () {
            event.execCommand("cancelChanges");
        },
        onHide: function () {
            setTimeout(function () {
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                $(event.focusManager.currentActive).blur();
            }, 500);
        },
        contents: [
            {
                id: 'general',
                label: 'Settings',
                elements: [
                    {
                        type: 'html',
                        onLoad: function (event) {
                            var $dialog = $(event.sender.parts.dialog.$);
                            $dialog.find(".cke_resizer.cke_resizer_ltr").hide(); // dialog resize triangle
                            // in Safari close button goes to wrong side,
                            $dialog.find(".cke_dialog_close_button").css("float", "right");
                        },
                        html: '
You have changed the text. Do you wish to save it?
'
                    }
                ]
            }
        ]
    };
});

CKEDITOR.defineToolbar = function (editor) {
    var prefix;

    if (editor.elementMode == 1) { // full-screen editor mode
        editor.config.maxToolbar = true;
        prefix = "max";

    } else {
        editor.config.maxToolbar = false;
        prefix = "min";
    }

    if (editor.element.data("contenttype") === "text") {
        return prefix + "PlainText";

    } else if (editor.element.data("contenttype") === "from-html") {
        return prefix + "TextToolbar";

    } else {
        return prefix + "HtmlToolbar";
    }
};

CKEDITOR.switchFormat = false;

CKEDITOR.plugins.add("switchFormatToHTML", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToHTML', {
            label: 'Switch format to HTML',
            command: "switchFormat",
            icon: "images/switch-between-html-and-text-mode.png"
        });
    }
});

CKEDITOR.plugins.add("switchFormatToText", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToText', {
            label: 'Switch format to text',
            command: "switchFormat",
            icon: "images/plain_text.png"
        });
    }
});

CKEDITOR.plugins.add("fileBrowser", {
    init: function (editor) {

        var onChooseFile = function () {
            Imcms.Editors.Content.showDialog({
                onApply: $.proxy(onFileChosen, this),
                onCancel: $.proxy(onFileChosen, this)
            });
            editor.focusManager.blur();
            editor.element.$.blur();
        };
        var onFileChosen = function (data) {
            if (data) {
                editor.insertHtml('
', 'unfiltered_html');
            }
            editor.focusManager.focus();
            editor.element.$.focus();
        };

        var openBrowserCommandDefinition = CKEDITOR.newCommandWithExecution(onChooseFile);
        editor.addCommand("openBrowser", openBrowserCommandDefinition);

        editor.ui.addButton('openBrowser', {
            label: 'Open Image Browser',
            command: "openBrowser",
            icon: "images/ic_images.png"
        });
    }
});

CKEDITOR.plugins.add("w3cValidator", {
    init: function (editor) {
        var w3cValidateCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__w3cvalidate_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("validateText", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + (data.result ? "images/ic_valid.png" : "images/ic_invalid.png") + ")"
                    });

                    if (!data.result) {
                        $(event.element.$).data("w3cValidateData", data);
                        event.execCommand("w3cValidateDialog", data);
                    }
                }
            }, event);
        };
        var w3cValidateCommandDefinition = CKEDITOR.newCommandWithExecution(w3cValidateCommand);
        editor.addCommand("w3cValidate", w3cValidateCommandDefinition);
        editor.addCommand("w3cValidateDialog", new CKEDITOR.dialogCommand("w3cValidationResultDialog"));

        editor.ui.addButton('w3cValidate', {
            label: 'Validate Content over W3C',
            command: "w3cValidate",
            icon: "images/ic_w3c.png"
        });
    }
});
CKEDITOR.dialog.add("w3cValidationResultDialog", function (event) {
    var $wrapper = $("
"),
        $content = $("
").addClass("imcms-w3c-errors").appendTo($wrapper),
        data = $(event.element.$).data("w3cValidateData");

    $("
").append($("
").text("Validation Output: " + data.data.errors.length + " Errors")).appendTo($content);

    data.data.errors.forEach(function (item, pos) {
        var $container = $("
").addClass("imcms-w3c-error").appendTo($content),
            $errorMessage = $("
").text(pos + 1 + ". " + item.message.charAt(0).toUpperCase() + item.message.slice(1)).appendTo($container),
            $sourceContainer = $("
").appendTo($container),
            $source = $("").addClass("language-html").html(item.line + ": " + item.source.replace(/(<([^>]+)>)/ig, "")).appendTo($sourceContainer);

        Prism.highlightElement($source[0]);
    });

    return {
        title: 'Validation Result Dialog',
        width: 600,
        minHeight: 250,
        contents: [
            {
                id: 'w3cValidation',
                label: 'Validation',
                elements: [
                    {
                        type: 'html',
                        html: $("
").append($wrapper).html()
                    }
                ]
            }
        ]
    };
});

CKEDITOR.plugins.add("textHistory", {
    init: function (editor) {
        var textHistoryCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__texthistory_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("getTextHistory", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_history.png" + ")"
                    });

                    $(event.element.$).data("textHistoryData", data);
                    event.execCommand("textHistoryDialog", data);
                }
            }, event);
        };
        var textHistoryCommandDefinition = CKEDITOR.newCommandWithExecution(textHistoryCommand);
        editor.addCommand("textHistory", textHistoryCommandDefinition);
        editor.addCommand("textHistoryDialog", new CKEDITOR.dialogCommand("textHistory"));

        editor.ui.addButton('textHistory', {
            label: 'Text History',
            command: "textHistory",
            icon: "images/ic_history.png"
        });
    }
});

CKEDITOR.dialog.add("textHistory", function (event) {
    var $wrapper = $("
").addClass("imcms-text-history"),
        $leftPanel = $("
").addClass("imcms-left-panel").appendTo($wrapper),

        $content = $("
").addClass("imcms-content")
            .css({
                "max-width": "600px",
                "float": "right"
            })
            .appendTo($wrapper),

        data = $(event.element.$).data("textHistoryData")
            .map(function (textHistoryData) {
                textHistoryData.modifiedDate = new Date(textHistoryData.modifiedDate);
                textHistoryData.type = (textHistoryData.type == "HTML")
                    ? "html"
                    : "from-html";
                return textHistoryData;
            })
            .sort(function (a, b) {
                return (a.modifiedDate > b.modifiedDate ? -1 : (a.modifiedDate == b.modifiedDate ? 0 : 1));
            }),

        groupedData = {},
        $selected = undefined,
        selectedItem,
        previousType;

    data.forEach(function (it) {
        var key = it.modifiedDate.format("dd/m/yy");

        if (!(key in groupedData)) {
            groupedData[key] = [];
        }

        groupedData[key].push(it);
    });

    var buttonsShowed = false;

    function addTextHistoryButton(text, onClick) {
        return $("<button>")
            .addClass("imcms-neutral")
            .css("float", "right")
            .html(text)
            .appendTo($wrapper)
            .click(onClick);
    }

    $.each(groupedData, function (key, list) {
        $("
").addClass("imcms-separator").text(key).appendTo($leftPanel);

        list.forEach(function (item) {
            $("
").appendTo($leftPanel)
                .append(item.modifiedDate.format("HH:MM:ss") + " | " + item.modifiedBy)
                .click(function () {
                    if (!buttonsShowed) {
                        addTextHistoryButton("View Page", function () {
                            if (selectedItem.type !== "html") {
                                $content.html($content.text());
                                selectedItem.type = "html";
                            }
                        });
                        addTextHistoryButton("View Source", function () {
                            if (selectedItem.type === "html") {
                                $content.text($content.html());
                                selectedItem.type = "from-html";
                            }
                        });
                        buttonsShowed = true;
                    }

                    if ($selected) {
                        $selected.removeClass("selected");
                    }

                    var callFunc = (item.type === "html")
                        ? "html"
                        : "text";

                    $content[callFunc](item.text);
                    $selected = $(this).addClass("selected");
                    selectedItem = item;
                    previousType = item.type;
                });
        })
    });

    return {
        title: 'Text History Dialog',
        width: 600,
        height: 400,
        contents: [
            {
                id: 'textHistory',
                label: 'Text History',
                elements: [
                    {
                        type: 'html',
                        onLoad: function () {
                            $("#" + this.domId).append($wrapper)
                        },
                        html: ""
                    }
                ]
            }
        ],
        buttons: [
            {
                id: "text history OK button",
                type: "button",
                label: "Write to textfield",
                title: "Write to textfield",
                "class":"cke_dialog_ui_button_ok",
                disabled: false,
                onClick: function () {
                    if (selectedItem) {
                        event.setData(""); // clear previous text
                        var contentType = $(event.element.$).data("contenttype");

                        var callFunc = (contentType === "html")
                            ? "insertHtml"
                            : "insertText";

                        event[callFunc](selectedItem.text);

                        if (selectedItem.type !== contentType) {
                            event.execCommand("switchFormat");
                        }
                    }
                }
            },
            CKEDITOR.dialog.cancelButton
        ]
    };
});<|endoftext|>