/****************************************************
 * Title: Solving Puzzle in JavaScript
 * File: graphics.js
 * Author: Osami Yamamoto (osami@meijo-u.ac.jp)
 * Date: Fri Feb 14 15:16:29 JST 2014
 ****************************************************/

/*========================*
 * draw_bg(context, w, h)
 *========================*/
function draw_bg(context, w, h){
    context.beginPath()
    context.moveTo(0, 0)
    context.lineTo(w, 0)
    context.lineTo(w, h)
    context.lineTo(0, h)
    context.lineTo(0, 0)
    context.closePath()
    context.fillStyle= 'rgb(220, 220, 220)'
    context.fill()
} /* draw_bg */

/*========================*
 * draw_base(context)
 *========================*/
function draw_base(context){
    context.fillStyle="black"
    for (var i = 0; i < 3; i++){
	var centerx = i * 110 + 55
	for (var j = 0; j < 2; j++){
	    var centery = j * 110 + 55
	    context.beginPath()
	    context.arc(centerx, centery, 40, 0, Math.PI * 2)
	    context.closePath()
	    context.fillStyle="rgb(230, 230, 230)"
	    context.fill()
	    context.fillStyle="black"
	    context.stroke()
	}
    }
} /* draw_base */

function draw_base_balls(context, pat){
    var ppat = pat.split("")
    for (var i = 0; i < 3; i++){
	var centerx = i * 110 + 55
	for (var j = 0; j < 2; j++){
	    var centery = j * 110 + 55
	    var k = j * 3 + i
	    var c = ppat[k]
	    if (c == 'B' || c == 'R'){
		if (c == 'B') context.fillStyle= "rgba(0, 0, 255, 0.7)"
		else context.fillStyle= "rgba(255, 0, 0, 0.7)"
		context.beginPath()
		context.arc(centerx, centery, 37, 0, Math.PI * 2)
		context.closePath()
		context.fill()
	    }  /* if */
	} /* for */
    } /* for */
} /* draw_base_balls */

var agenda_counter = 0
var agenda_context = 0
var agenda_w = 0
var agenda_h = 0
var raf = window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame || function(){}

/*========================*
 * play_agenda0(context, w, h)
 *========================*/
function play_agenda0(context, w, h){
    agenda_counter = 0
    agenda_context = context
    agenda_w = w
    agenda_h = h
    play_agenda()
}

/*========================*
 * play_agenda()
 *========================*/
function play_agenda(){
    if (agenda_counter < agenda.length){
	var context = agenda_context
	draw_bg(context, agenda_w, agenda_h)
	draw_base(context)
	var ag = agenda[agenda_counter]
	draw_base_balls(context, ag.base_pat)
	var c = ag.color
	var x = ag.posx
	var y = ag.posy
	var r = ag.rad
	if (c == 'B' || c == 'R'){
	    if (c == 'B') context.fillStyle= "rgba(0, 0, 255, 0.7)"
	    else context.fillStyle= "rgba(255, 0, 0, 0.7)"
	    context.beginPath()
	    context.arc(x, y, r, 0, Math.PI * 2)
	    context.closePath()
	    context.fill()
	}  /* if */
	agenda_counter += 1
	raf(play_agenda)
    }
} /* play_agenda */