var frogIdCounter = 0;

var RIPPLES = [ "url('images/water/ripple1.png')",
                "url('images/water/ripple2.png')",
                "url('images/water/ripple3.png')",
                "url('images/water/ripple4.png')",
                "url('images/water/ripple5.png')" ];

var FROG_IMAGES = [ "url('images/frog/frog_north.png')",
                    "url('images/frog/frog_nne.png')",
                    "url('images/frog/frog_ne.png')",
                    "url('images/frog/frog_ene.png')",
                    "url('images/frog/frog_east.png')",
                    "url('images/frog/frog_ese.png')",
                    "url('images/frog/frog_se.png')",
                    "url('images/frog/frog_sse.png')",
                    "url('images/frog/frog_south.png')",
                    "url('images/frog/frog_ssw.png')",
                    "url('images/frog/frog_sw.png')",
                    "url('images/frog/frog_wsw.png')",
                    "url('images/frog/frog_west.png')",
                    "url('images/frog/frog_wnw.png')",
                    "url('images/frog/frog_nw.png')",
                    "url('images/frog/frog_nnw.png')" ];

var FROG_JUMPING_IMAGES = [ "url('images/frog/frog_jumping_north.png')",
                            "url('images/frog/frog_jumping_south.png')",
                            "url('images/frog/frog_jumping_east.png')",
                            "url('images/frog/frog_jumping_west.png')" ];


// preload the frog images
for (var i = 0; i < FROG_IMAGES.length; i++) {
	var img = new Image();
	var url = FROG_IMAGES[i].substring(FROG_IMAGES[i].indexOf("'") + 1, FROG_IMAGES[i].lastIndexOf("'"));
	img.src = url;
}

// preload the jumping frog images
for (var i = 0; i < FROG_JUMPING_IMAGES.length; i++) {
	var img = new Image();
	var url = FROG_IMAGES[i].substring(FROG_JUMPING_IMAGES[i].indexOf("'") + 1, FROG_JUMPING_IMAGES[i].lastIndexOf("'"));
	img.src = url;
}

var FROG_JUMP_RATE = 0.08;

function FrogSprite(g) {

	this.game = g;
	this.id = ++frogIdCounter;
	this.jumping = false;
	this.rotate = false;
	
	this.splashed = false;
	this.rippleIndex = 0;
	
	this.counter = 0;
	
	var lpg = this.game.getLillyPadGrid();
	var fg = this.game.getFrogGrid();
	var bg = this.game.getBugGrid();
	
	this.x = getRandomInt(0, ROWS - 1);
    this.y = getRandomInt(0, COLS - 1);
    while (!lpg[this.x][this.y] || fg[this.x][this.y] || bg[this.x][this.y]) {
    	this.x = getRandomInt(0, ROWS - 1);
        this.y = getRandomInt(0, COLS - 1);
    }
    
    // first, the "normal" frog div
    
    this.contentDiv = document.createElement("div");
    this.contentDiv.onmousedown = function(event) {
        dragStart(event, this.id);	
    }
    this.contentDiv.frog = this;
    this.contentDiv.id = "frog" + this.id;
    this.contentDiv.style.width = "40px";
    this.contentDiv.style.height = "40px";
    this.contentDiv.style.position = "absolute";
    this.contentDiv.style.top = this.posX + "px";
    this.contentDiv.style.left = this.posY + "px";
    this.contentDiv.style.zIndex = "2";

    this.setDirection(getRandomInt(0, 3));
    this.setPosition();
    
    // now, the "jumping" frog div
    
    this.jumpingDiv = document.createElement("div");
    this.jumpingDiv.style.display = "none";
    this.jumpingDiv.style.width = "40px";
    this.jumpingDiv.style.height = "48px";
    this.jumpingDiv.style.position = "absolute";
    this.jumpingDiv.style.top = this.jposX + "px";
    this.jumpingDiv.style.left = this.jposY + "px";
    this.jumpingDiv.style.zIndex = "2";
    this.jumpingDiv.style.backgroundImage = FROG_JUMPING_IMAGES[0];

    
    this.game.gameElement.appendChild(this.contentDiv);
    this.game.gameElement.appendChild(this.jumpingDiv);
	
}

FrogSprite.prototype.setPosition = function() {
	
    this.posX = (this.x) * 40;
    this.posY = (this.y) * 40;

    if (this.direction == NORTH) {
    	this.jposX = ((this.x) * 40) + 4;
    	this.jposY = ((this.y) * 40);
    } if (this.direction == SOUTH) {
    	this.jposX = ((this.x) * 40) - 4;
    	this.jposY = ((this.y) * 40);
    } else if (this.direction == EAST) {
    	this.jposX = ((this.x) * 40);
    	this.jposY = ((this.y) * 40) + 4;
    } else if (this.direction == WEST) {
    	this.jposX = ((this.x) * 40);
    	this.jposY = ((this.y) * 40) - 4;
    }
	
}

FrogSprite.prototype.setDirection = function(dir) {
	
	this.direction = dir;
	if (this.direction == NORTH) {
		this.contentDiv.style.backgroundImage = FROG_IMAGES[0];
	} else if (this.direction == SOUTH) {
		this.contentDiv.style.backgroundImage = FROG_IMAGES[8];
	} else if (this.direction == EAST) {
		this.contentDiv.style.backgroundImage = FROG_IMAGES[4];
	} else if (this.direction == WEST) {
		this.contentDiv.style.backgroundImage = FROG_IMAGES[12];
	}
	
}

FrogSprite.prototype.startJump = function() {
	
	if (!this.jumping && !this.splashed) {
		
		this.jumping = true;
		
		if (this.direction == NORTH && this.x == 0) {
			this.rotate = true;
			this.direction = SOUTH;
		} else if (this.direction == SOUTH && this.x == ROWS - 1) {
			this.rotate = true;
			this.direction = NORTH;
		} else if (this.direction == EAST && this.y == COLS - 1) {
			this.rotate = true;
			this.direction = WEST;
		} else if (this.direction == WEST && this.y == 0) {
			this.rotate = true;
			this.direction = EAST;
		} else {
		
			if (this.direction == NORTH) {
				this.jumpingDiv.style.backgroundImage = FROG_JUMPING_IMAGES[0];
				this.jumpingDiv.style.width = "40px";
				this.jumpingDiv.style.height = "48px";
			} else if (this.direction == SOUTH) {
				this.jumpingDiv.style.backgroundImage = FROG_JUMPING_IMAGES[1];
				this.jumpingDiv.style.width = "40px";
				this.jumpingDiv.style.height = "48px";
			} else if (this.direction == EAST) {
				this.jumpingDiv.style.backgroundImage = FROG_JUMPING_IMAGES[2];
				this.jumpingDiv.style.width = "48px";
				this.jumpingDiv.style.height = "40px";
			} else if (this.direction == WEST) {
				this.jumpingDiv.style.backgroundImage = FROG_JUMPING_IMAGES[3];
				this.jumpingDiv.style.width = "48px";
				this.jumpingDiv.style.height = "40px";
			}

			this.jumpingDiv.style.display = "block";
			this.contentDiv.style.display = "none";

		}
		
		var lp = this.game.getLillyPadGrid()[this.x][this.y];
		if (lp) {
			lp.movedOff();
		}

		
		this.setPosition();
		
	}
	
}

FrogSprite.prototype.stopJump = function() {
	
	this.jumping = false;
	this.rotate = false;
	this.setDirection(this.direction);
	this.setPosition();
	this.jumpingDiv.style.display = "none";
	this.contentDiv.style.display = "block";
	this.counter = 0;
	
	var lp = this.game.getLillyPadGrid()[this.x][this.y];
	if (!lp) {
		this.rippleIndex = 0;
		this.splashed = true;
		this.contentDiv.style.backgroundImage = RIPPLES[this.rippleIndex];
		splashSound.play();
	} else {
		lp.landedOn();
	}

}

FrogSprite.prototype.eat = function() {

	var targetX = this.x;
	var targetY = this.y;

	if (this.direction == NORTH) {
		targetX--;
	} else if (this.direction == SOUTH) {
		targetX++;
	} else if (this.direction == EAST) {
		targetY++;
	} else if (this.direction == WEST) {
		targetY--;
	}

	if (targetX < 0 || targetX > (ROWS - 1)) {
		return;
	} else if (targetY < 0 || targetY > (COLS - 1)) {
		return;
	} else {
	
		var bug = this.game.getBugGrid()[targetX][targetY];
		if (bug) {
			bug.eat();
			eatSound.play();
		}
	
	}
	
}

FrogSprite.prototype.update = function(elapsed) {
	
	if (this.jumping && !this.rotate) {
	
		if (this.direction == NORTH) {
		
			this.jposX = this.jposX - (elapsed * FROG_JUMP_RATE);
		
			if (this.jposX <= ((this.x - 1) * 40)) {
				this.x -= 1;
				this.stopJump();
			}
		
		} else if (this.direction == SOUTH) {
				
			this.jposX = this.jposX + (elapsed * FROG_JUMP_RATE);
			
			if (this.jposX >= ((this.x + 1) * 40)) {
				this.x += 1;
				this.stopJump();
			}
			
		} else if (this.direction == EAST) {
			
			this.jposY = this.jposY + (elapsed * FROG_JUMP_RATE);
			
			if (this.jposY >= ((this.y + 1) * 40)) {
				this.y += 1;
				this.stopJump();
			}
			
		} else if (this.direction == WEST) {
			
			this.jposY = this.jposY - (elapsed * FROG_JUMP_RATE);
			
			if (this.jposY <= ((this.y - 1) * 40)) {
				this.y -= 1;
				this.stopJump();
			}
			
		}
	
	} else if (this.jumping && this.rotate) {

		this.counter += elapsed;

		var offset = 0;
		if (this.direction == WEST) {
			offset = 4;
		} else if (this.direction == NORTH) {
			offset = 8;
		} else if (this.direction == EAST) {
			offset = 12;
		}
			
		var idx = Math.floor(this.counter / 62.5) + offset;
		if (idx > (offset + 8)) {
			this.stopJump();
		} else {
			this.contentDiv.style.backgroundImage = FROG_IMAGES[idx % 16];
		}

		
	} else if (this.splashed) {
	
		this.counter += elapsed;
		if (this.counter >= 200) {
			if (this.rippleIndex < 4) {
				this.contentDiv.style.backgroundImage = RIPPLES[++this.rippleIndex];
				this.counter = this.counter - 200;
			} else {
				this.contentDiv.style.display = "none";
				this.splashed = false;
				this.game.removeFrog(this);
			}
		}
		
	}
	
	this.contentDiv.style.top = Math.floor(this.posX) + "px";
	this.contentDiv.style.left = Math.floor(this.posY) + "px";

	this.jumpingDiv.style.top = Math.floor(this.jposX) + "px";
	this.jumpingDiv.style.left = Math.floor(this.jposY) + "px";

}

var dragObj = new Object();

function dragStart(event, id) {

    var el;
    var x, y;

    // If an element id was given, find it. Otherwise use the element being
    // clicked on.

    if (id) {
    
        dragObj.elNode = document.getElementById(id);
        
    } else {
    
        if (browser.isIE) {
            dragObj.elNode = window.event.srcElement;
        }
        
        if (browser.isNS) {
            dragObj.elNode = event.target;
        }

        // If this is a text node, use its parent element.

        if (dragObj.elNode.nodeType == 3) {
            dragObj.elNode = dragObj.elNode.parentNode;
        }
        
    }

    // Get cursor position with respect to the page.

    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }
    
    if (browser.isNS) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Save starting positions of cursor and element.

    dragObj.cursorStartX = x;
    dragObj.cursorStartY = y;

    // Capture mousemove and mouseup events on the page.

    if (browser.isIE) {
        document.attachEvent("onmouseup", dragStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    
    if (browser.isNS) {
        document.addEventListener("mouseup", dragStop, true);
        event.preventDefault();
    }
    
    frogTapSound.play();
    
}

function dragStop(event) {

    var x, y;

    // Get cursor position with respect to the page.

    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
            + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
            + document.body.scrollTop;
    }

    if (browser.isNS) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    var movedX = x - dragObj.cursorStartX;
    var movedY = dragObj.cursorStartY - y;
    
    if (Math.abs(movedX) > Math.abs(movedY)) {
    	if (movedX >= 20) {
    		//alert("frog will now face right");
    		dragObj.elNode.frog.setDirection(EAST);
    		ribbitSound.play();
    	} else if (movedX <= -20) {
    		//alert("frog will now face left");
    		dragObj.elNode.frog.setDirection(WEST);
    		ribbitSound.play();
    	}
    } else {
    	if (movedY >= 20) {
    		//alert("frog will now face up");
    		dragObj.elNode.frog.setDirection(NORTH);
    		ribbitSound.play();
    	} else if (movedY <= -20) {
    		//alert("frog will now face down");
    		dragObj.elNode.frog.setDirection(SOUTH);
    		ribbitSound.play();
    	}
    }
    
    // Stop capturing mousemove and mouseup events.

    if (browser.isIE) {
        document.detachEvent("onmouseup", dragStop);
    }
    
    if (browser.isNS) {
        document.removeEventListener("mouseup", dragStop, true);
    }
    
}

function Browser() {

	var ua, s, i;

	this.isIE = false;
	this.isNS = false;
	this.version = null;

	ua = navigator.userAgent;

	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}

	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}

	// Treat any other "Gecko" browser as NS 6.1.

	s = "Gecko";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = 6.1;
		return;
	}
	
}

var browser = new Browser();


