﻿///////////////////////////////////////////////////////////////////////////////
// Main

function Main(){
	this.blocks = []
	this.currBlock = null
	
	var els, i, n, b
	
	els = $(".block")
	n = els.length
	for(i=0; i<n; i++){
		b = $(new Block(els[i]))
		b.bind("deselected", $.proxy(this.onDeselectedBlock, this))
		b.bind("selected", $.proxy(this.onSelectedBlock, this))
		this.blocks.push(b)
	}
}

Main.prototype.onDeselectedBlock = function(e){
	if(this.currBlock) this.currBlock.shrink()
	this.currBlock = null
}

Main.prototype.onSelectedBlock = function(e){
	if(this.currBlock) this.currBlock.shrink()
	this.currBlock = e.currentTarget
	this.currBlock.expand()
}

///////////////////////////////////////////////////////////////////////////////
// Block

function Block(el){
	var r1 = Math.floor(Math.random() * 4)
	var r2 = r1 * 125
	this.el = $(el)
	this.el.css({ "margin-left":r2+"px" })
	this.h2 = $(this.el.children("h2"))
	this.h2.css({ "cursor":"pointer" })
	this.h2.bind("mouseenter", $.proxy(this.onOver, this))
	this.h2.bind("mouseleave", $.proxy(this.onOut, this))
	this.h2.bind("click", $.proxy(this.onClick, this))
	this.content = $(this.el.children(".content"))
	this.content.hide()
}

Block.prototype.onOver = function(e){
	this.h2.css({ "background-color":"#000000", "color":"#ffffff" })
}

Block.prototype.onOut = function(e){
	this.h2.css({ "background-color":"#ffffff", "color":"#000000" })
}

Block.prototype.onClick = function(e){
	this.el.toggleClass("expanded")
	this.isExpanded = this.el.hasClass("expanded")
	var event = (this.isExpanded) ? "selected" : "deselected"
	$(this).trigger(event)
}

Block.prototype.expand = function(){
	this.el.addClass("expanded")
	this.content.show("blind")
}

Block.prototype.shrink = function(){
	this.el.removeClass("expanded")
	this.content.hide("blind")
}

///////////////////////////////////////////////////////////////////////////////
// Rectangle

function Rectangle(x, y, w, h){
	this.x = x
	this.y = y
	this.w = w
	this.h = h
}

Rectangle.prototype.intersectsWith = function(rect){
	if(this.x >= rect.x + rect.w) return false
	if(this.y >= rect.y + rect.h) return false
	if(this.x + this.w <= rect.x) return false
	if(this.y + this.h <= rect.y) return false
	return true
}

Rectangle.prototype.intersectionWith = function(rect){
	var r = new Rectangle(0, 0, 0, 0)
	if(this.intersectsWith(rect))
	{
		r.x = Math.max(this.x, rect.x)
		r.y = Math.max(this.y, rect.y)
		r.w = Math.min(this.x+this.w, rect.x+rect.w) - r.x
		r.h = Math.min(this.y+this.h, rect.y+rect.h) - r.y
	}
	return r
}

