/*
TODO
1: test D.isReady in IE + slow machines
2: Add argument support for bind: done
*/

DEBUG = 1

Function.prototype.bind = function() {
  var __m_____ = this, args = Util.to_array(arguments), obj = args.shift();
  return function() { return __m_____.apply(obj, args.concat(Util.to_array(arguments)));}
}
Function.prototype.delay = function(ms, bind){
	return setTimeout(this.bind(bind || this), ms);
},
Function.prototype.periodical = function(ms, bind){
	return setInterval(this.bind(bind || this), ms);
}

Array.prototype.each = function(block) {
	for (var a=0; a<this.length;a++) {
		block(this[a], a);
	}
}
var D = {
	init: function() { this.isReady() },
	isReady: function() {
		this.n = typeof this.n == 'undefined' ? 0 : this.n + 1;
		if (typeof document.getElementsByTagName != 'undefined' 
			&& (document.getElementsByTagName('body')[0] != null || document.body != null)) {	
				D.Event.dispatch('ready')
		} else if(this.n < 60) { setTimeout('D.isReady()', 10); } // this needs testing on IE
	},
	Event: {
		//internal event manager
		listeners: {},
		add: function(evnt, cb) {
			if (!this.listeners[evnt]) this.listeners[evnt] = [];
			this.listeners[evnt].push(cb);
		},
		remove: function(evnt) { delete this.listeners[evnt] },
		get: function(name) { return this.listeners[name] },
		dispatch: function(evntname) {
			cb = this.get(evntname)
			if (cb) for (i=0; i<cb.length;i++) cb[i].apply();
		}
	},
	Element: {
		by_id: function(id) {
			return document.getElementById(id)
		},
		by_class: function(classn) {
			alert('not implemented')
		},
		by_tag: function(tagname, parent) {
			if (!parent) parent = document
			return Util.to_array(parent.getElementsByTagName(tagname))
		}
	},
	$: function(el, parent) {
		typ = el.charAt(0)
		switch (typ) {
			case '#':
				return this.Element.by_id(el.replace('#', ''))
			break;
			case '.':
				return this.Element.by_class(el.replace('.', ''))
			break;
			default:
				return this.Element.by_tag(el, parent)
			break;
		}
	},
	e: function(block) {
	    var el;
	    if ('string'==typeof block) {
	        el=document.createTextNode(block);
	    } else {
	        el=document.createElement(block.tag);
	        delete(block.tag);
	        if ('undefined'!=typeof block.children) {
	            if ('string'==typeof block.children ||
	                'undefined'==typeof block.children.length
	            ) {
	                el.appendChild(D.e(block.children));
	            } else {
	                //array
	                for (var i=0, child=null; 'undefined'!=typeof (child=block.children[i]); i++) {
	                    el.appendChild(D.e(child));
	                }
	            }
	            delete(block.children);
	        }
			if ('undefined'!=typeof block.events) { 
				for (ev in block.events)
					E.add(el, ev, block.events[ev])
				
				delete block.events
			}

	        for (attr in block) {
				if (attr == 'class')
					el.className = block[attr]
				else
	            	el[attr]=block[attr];
	        }
	    }

	    return el;
	},
	children: function(el) {
		return el.childNodes
	},
	Children: {
		count: function() { return el.childNodes.length },
		by_class: function(classname, el) {}
	},
	__append: function(el, els) {
		if ('string'==typeof els) {
			el.appendChild(document.createTextNode(els));
			return;
		}
		try {
			el.appendChild(els)
		} catch(e) {
			try {
				for (var i=0;i<els.length;i++) {
					el.appendChild(els[i])
				}
			} catch (e) {
				if (DEBUG) alert(e);
			}
		}
		
	},
	__insert: function(els, el) {
		try {
			el.parentNode.insertBefore(els, el)
		} catch(e) {
			try {
				els.parentNode.insertBefore(el, els)
			} catch (e) {
				if (DEBUG) alert(e)
			}
		}
	},
	Insert: {
		before: function(els, el) {
			D.__insert(els, el)
		},
		first: function(el, els) {
			if (el.firstChild)
				D.__insert(el.firstChild, els)
			else
				D.__append(el, els)
		},
		last: function(el, els) {
			D.__append(el, els)
		},
		at: function(el, els, pos) {
			alert(el.childNodes[0])
			D.__insert(el.childNodes[pos], els)
		}
		
	},
	Style: {
		apply: function(elem, styles) {
			for (style in styles) {
				elem.style[style] = styles[style]
				if (style == 'opacity' && window.ActiveXObject) {
						elem.style.filter = "alpha(opacity="+styles[style]*100+")";
				}
			}
		}
	}
}


var E = {
	add: function(obj, evt, func) {
		if (document.addEventListener) obj.addEventListener(evt, func, false);
		else if(document.attachEvent) obj.attachEvent('on'+evt,func);
		},
	remove: function(obj, evt, func) {
			obj.removeEventListener(evt, func, false);
		},
	get: function(e, p) {
			var e = e || window.event;
			if (p) E.pd(e);
			return t = e.target || e.srcElement;
		},
	pd: function(e) {
			if (e.stopPropagation) e.stopPropagation();	 
			else if(e.cancelBubble) e.cancelBubble = true;			
			if (e.preventDefault) e.preventDefault();
			else e.returnValue = false; 
	},
	pos: function(e) {
		var left = 0;
		var top  = 0;
		while (e.offsetParent){
			left += e.offsetLeft;
			top  += e.offsetTop;
			e     = e.offsetParent;
		}
		left += e.offsetLeft;
		top  += e.offsetTop;

		return {x:left, y:top};
	}
}


var R = {
	__GET: {},
	filename: '',
	query_string: location.search || '',
	type: '',
	uri: location.href,
	initialized: false,
	
	init: function() {
		ps = this.uri
				
		this.type = ps.match(/^https?|ftp|file/);		
		ps = ps.replace(/https?:\/\/|file:\/|ftp:\/\//g, '');
		
		ps = ps.split('/');
		psl = ps.length
		 
		ps[psl-1] = ps[psl-1].split('?');
		this.filename = (ps[psl-1].length > 1) ? ps[psl-1].shift() : ps.pop();
		
		params = location.search.slice(1).split('&');
		for (i=0;i<params.length;i++) {
			x = params[i].split('=');
			this.__GET[x[0]] = unescape(x[1]);
		}
		this.initialized = true;
	},
	get: function(key) {
		if (!this.initialized) this.init();
		
		return (this.__GET[key] != undefined) ? this.__GET[key] : false;
	},
	set: function(params) {
		if (!this.initialized) this.init();
		
		//params {'key':'value', 'key2':'value2'}
		try {
			for (key in params) {
				if (key != '')
					this.__GET[key] = params[key];
			}
		} catch(e) {}
	},
	serialize: function() {
		params = [];
		for (key in this.__GET)
			if (key != '')
				if (this.__GET[key] != undefined)
					params.push(key + '=' + escape(this.__GET[key]))
		
		return params.join('&');
		
	},
	Cookie: {
		set: function(name,value,days,path,domain,secure) {
			if (!days) days = 360;
			var date = new Date();
		    date.setTime(date.getTime() + (days*24*60*60*1000) );
		   	expires = date.toGMTString();
		  	
		   document.cookie = name + "=" + escape(value) +
		    ((expires) ? "; expires=" + expires : "") +
		    ((path) ? "; path=" + path : "") +
		    ((domain) ? "; domain=" + domain : "") +
		    ((secure) ? "; secure" : "");
		},

		get: function(name) {
		  var nameEQ = name + "=";
		  var ca = document.cookie.split(';');
		  for(var i=0;i < ca.length;i++) {
		    var c = ca[i];
		    while (c.charAt(0)==' ') c = c.substring(1,c.length);
		    if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		  }
		  return null;
		}
	}
}

var Util = {
		clean: function(parobj) {
			var notWhiteSpaceNode = /\S/;				
			for (i=0;i<parobj.childNodes.length;i++){
				if ((parobj.childNodes[i].nodeType == 3) 
				&& (!notWhiteSpaceNode.test(parobj.childNodes[i].nodeValue))) {
					parobj.removeChild(parobj.childNodes[i]);
						i--;
				}
			}
		},
		to_array: function(it) {
			if (!it) return [];
			if (it.toArray)
				return it.toArray();
		 	else {
		    	var r = [];
		    	for (var i = 0; i < it.length; i++)
					r.push(it[i]);
				return r;
			}
		}
	}

var Transitions = {
		linear: function(t, b, c, d){
			return c*t/d + b;
		},
		sineInOut: function(t, b, c, d){
			return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
		}
	};

var Effect = {
	options: {
		onStart: function() {},
		onComplete: function() {},
		transition: Transitions.sineInOut,
		duration: 500,
		unit: 'px',
		fps: 50
	},
	mergeOptions: function(options) {
		if (!options) return;
		for (opt in options) {
			this.options[opt] = options[opt]
		}
	},
	step: function(){
		var time = new Date().getTime();
		if (time < this.time + this.options.duration){
			this.cTime = time - this.time;
			this.setNow();
		} else {
			this.options.onComplete(this.element, this);
			this.clearTimer();
			this.now = this.to;
		}
		this.increase();
	},
	
	set: function(to){
		this.now = to;
		this.increase();
		return this;
	},
	
	setNow: function(){
		this.now = this.compute(this.from, this.to);
	},

	compute: function(from, to){
		return this.options.transition(this.cTime, from, (to - from), this.options.duration);
	},
	animate: function(from, to){
		if (!this.options.wait) this.clearTimer();
		if (this.timer) return;
		this.options.onStart(this.element, this);
		this.from = from;
		this.to = to;
		this.time = new Date().getTime();
		this.timer = this.step.periodical(Math.round(1000/this.options.fps), this);
		return this;
	},
	
	clearTimer: function(){
		clearTimeout(this.timer);
		clearInterval(this.timer);
		this.timer = null;
	},
	
	setStyle: function(element, property, value){
		element.style[property] = value + this.options.unit;
	},
	init: function(el, property, options){
		this.element = el;
		this.mergeOptions(options);
		this.property = property;
	},
	goTo: function(val){
		return this.custom(this.now || 0, val);
	},
	increase: function(){
		this.setStyle(this.element, this.property, this.now);
	},
	hide: function(){
		return this.set(0);
	}
}
fxopacity = function(el, property, options) {
	this.init(el, 'height', options);
	this.increase = function(){
		D.Style.apply(this.element, {
			'opacity': Math.round(this.now*10)/10
		})
	}
}
fxopacity.prototype = Effect


/**
 * reflection.js v1.6
 *
 * Contributors: Cow http://cow.neondragon.net
 *               Gfx http://www.jroller.com/page/gfx/
 *               Sitharus http://www.sitharus.com
 *               Andreas Linde http://www.andreaslinde.de
 *               Tralala, coder @ http://www.vbulletin.org
 *
 * Freely distributable under MIT-style license.
 */
 
/* From prototype.js */
document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = new Array();
  
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}

var Reflection = {
	defaultHeight : 0.5,
	defaultOpacity: 0.2,
	
	add: function(image, options) {
		Reflection.remove(image);
		
		doptions = { "height" : Reflection.defaultHeight, "opacity" : Reflection.defaultOpacity }
		if (options) {
			for (var i in doptions) {
				if (!options[i]) {
					options[i] = doptions[i];
				}
			}
		} else {
			options = doptions;
		}
	
		try {
			var d = document.createElement('div');
			var p = image;
			
			var classes = p.className.split(' ');
			var newClasses = '';
			for (j=0;j<classes.length;j++) {
				if (classes[j] != "reflect") {
					if (newClasses) {
						newClasses += ' '
					}
					
					newClasses += classes[j];
				}
			}

			var reflectionHeight = Math.floor(p.height*options['height']);
			var divHeight = Math.floor(p.height*(1+options['height']));
			
			var reflectionWidth = p.width;
			
			if (document.all && !window.opera) {
				/* Copy original image's classes & styles to div */
				d.className = newClasses;
				p.className = 'reflected';
				
				d.style.cssText = p.style.cssText;
				p.style.cssText = 'vertical-align: bottom';
			
				var reflection = document.createElement('img');
				reflection.src = p.src;
				reflection.style.width = reflectionWidth+'px';
				
				reflection.style.marginBottom = "-"+(p.height-reflectionHeight)+'px';
				reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';
				
				d.style.width = reflectionWidth+'px';
				d.style.height = divHeight+'px';
				p.parentNode.replaceChild(d, p);
				
				d.appendChild(p);
				d.appendChild(reflection);
			} else {
				var canvas = document.createElement('canvas');
				if (canvas.getContext) {
					/* Copy original image's classes & styles to div */
					d.className = newClasses;
					p.className = 'reflected';
					
					d.style.cssText = p.style.cssText;
					p.style.cssText = 'vertical-align: bottom';
			
					var context = canvas.getContext("2d");
				
					canvas.style.height = reflectionHeight+'px';
					canvas.style.width = reflectionWidth+'px';
					canvas.height = reflectionHeight;
					canvas.width = reflectionWidth;
					
					d.style.width = reflectionWidth+'px';
					d.style.height = divHeight+'px';
					p.parentNode.replaceChild(d, p);
					
					d.appendChild(p);
					d.appendChild(canvas);
					
					context.save();
					
					context.translate(0,image.height-1);
					context.scale(1,-1);
					
					context.drawImage(image, 0, 0, reflectionWidth, image.height);
	
					context.restore();
					
					context.globalCompositeOperation = "destination-out";
					var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
					
					gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
					gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-options['opacity'])+")");
		
					context.fillStyle = gradient;
					if (navigator.appVersion.indexOf('WebKit') != -1) {
						context.fill();
					} else {
						context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
					}
				}
			}
		} catch (e) {
	    }
	},
	
	remove : function(image) {
		if (image.className == "reflected") {
			image.className = image.parentNode.className;
			image.parentNode.parentNode.replaceChild(image, image.parentNode);
		}
	}
}

function addReflections() {
	var rimages = document.getElementsByClassName('reflect');
	for (i=0;i<rimages.length;i++) {
		var rheight = null;
		var ropacity = null;
		
		var classes = rimages[i].className.split(' ');
		for (j=0;j<classes.length;j++) {
			if (classes[j].indexOf("rheight") == 0) {
				var rheight = classes[j].substring(7)/100;
			} else if (classes[j].indexOf("ropacity") == 0) {
				var ropacity = classes[j].substring(8)/100;
			}
		}
		
		Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
	}
}

//var previousOnload = window.onload;
//window.onload = function () { if(previousOnload) previousOnload(); addReflections(); }



	
	
var Featured = {
	total: 0,
	current: 0,
	container: null,
	items: [],
	previous: function(ev) {
		targ = E.get(ev, true);
		this.show(this.current - 1);
	},
	next: function(ev) {
		targ = E.get(ev, true);
		this.show(this.current + 1);
	},
	set_current: function(num) {
		if (!num) num = 0;
		if (num > this.total - 1)
			this.current = 0;
		else if (num < 0)
			this.current = this.total - 1;
		else
			this.current = num;
	},
	show: function(item) {
		this.set_current(item);
		
		numh = D.$('#num_h');
		opacity = 0;
		D.Style.apply(this.container, { opacity:0, overflow:'hidden' })
		for (var i=0;i<this.total;i++) {
			if (i == this.current) {
				this.items[i].style.display = 'block';
				numh.childNodes[i].style.backgroundPosition = 'right top';
			} else {
				this.items[i].style.display = 'none';
				numh.childNodes[i].style.backgroundPosition = 'left top';
			}
		}
		_o = new fxopacity(this.container);
		_o.animate(opacity, 1);
	},
	show_clicked: function(ev) {
		targ = E.get(ev, true);
		id = targ.name.split('__')[1];
		this.show(parseInt(id) - 1);
	},
	init: function() {
		this.container = D.$('#fblawgcasts');
		Util.clean(this.container);
		this.items = this.container.childNodes;
		this.total = this.items.length;
		
		imgs = D.$('img', this.container);
		imgs.each(function(img) {
			img.className = 'reflect rheight30';
			img.width = '150';
			img.height = '150';
		})
		addReflections();
		
		//alert(this.items.length);
		
		nav_btn = function (name, eventcb) {
			return {
				tag: 'div',
				id: 'f_'+name,
				'class': 'f_nav',
				children: {
					tag: 'a',
					href: '#',
					children: name,
					events: {'click':eventcb}
				}
			}
		}
		temp_cindr = function(num) {
			temp_get_children = function() {
				c = [];
				for (var i=1;i<num+1;i++) {
					c.push({
						tag: 'a',
						href: '#',
						name: 'item__'+i,
						children: i+"",
						events: {'click':Featured.show_clicked.bind(Featured)}
					})
				}
				return c
			}
			return {
				tag: 'div',
				id: 'num_h',
				children: temp_get_children()
			}
		}
		nav = D.e({
			tag: 'div',
			id: 'featured_nav',
			children: [
				nav_btn('Next', this.next.bind(this)),
				temp_cindr(this.total),
				nav_btn('Previous', this.previous.bind(this))
				]
			});
		nav.style.opacity = 0.9;
		D.Insert.before(nav, this.container);
		delete temp_nav_btn, temp_cindr;
		this.show();
	}
}

//initialize

D.init()
D.Event.add('ready', Featured.init.bind(Featured));








