function showVideo(player, video) {
	var banner = document.getElementById('flashbanner');
	if (banner) banner.style.display = 'none';

	var ovl = document.createElement('div');
	ovl.id = 'overlay';

	var content = document.createElement('div');
	content.id = 'overlay_content';

	var flashHolder = document.createElement('span');
	flashHolder.id = 'flashcontent';
	content.appendChild(flashHolder);

	var closeLink = document.createElement('a');
	closeLink.href = '#';
	closeLink.onclick = closeVideo;
	closeLink.id = 'overlay_close';
	closeLink.innerHTML = '| close';
	content.appendChild(closeLink);

	var body = document.getElementsByTagName('body')[0];
	body.appendChild(content);
	body.appendChild(ovl);

        window.setTimeout(function() {
            // call v2.2 of swfobject:
            //swfobject.embedSWF(player, "flashcontent", "450", "350", "7");

            var so = new SWFObject(player, "mymovie", "450", "350", "7", "#ffffff");
            so.addVariable("file", video);
            so.addParam("align", "middle");
            so.write("flashcontent");
	}, 100);
	return false;
}

function closeVideo() {
    var banner = document.getElementById('flashbanner');
    if (banner) banner.style.display = 'block';

	if (document.all) {
		// it seems removing flash programmatically causes crash in ie
		document.location.reload();
	} else {
		var t = $find('overlay');
		t.parentNode.removeChild(t);
		t = $find('overlay_content');
		t.parentNode.removeChild(t);
	}
}

function switchToTab(e) {
    if (!e || !e.id) return;
    $$('#featurecontrol span').invoke('removeClassName', 'selected');
	e.addClassName('selected');
    e.show();
	var t = e.id;
	t = t.replace('showfeature', 'featurebox');
	var newbox = $(t);
	if (!newbox) return;
	$$('#features .holder').invoke('hide');
	newbox.show();
	$$('#' + t + ' .holder').invoke('show');
    $$(t + ' .thumbnail').invoke('setStyle', {width: '133px'});
}

function switchFeature(evt) {
	var e = Event.element(evt);
	switchToTab(e);
}

CrossFader = Class.create();
CrossFader.prototype = {
	_timer: null,
	_current: 0,
	_enabled: false,

	initialize: function(objects, time) {
		if (!objects || !objects.length) return;
		$(objects[0]).show();
		if (objects.length < 2) return;
		this._objects = objects;
		this._delay = time;
		this._enabled = true;
		this._setupPager();
		this.start();
	},
	_setupPager: function() {
		var container = $(this._objects[0]).up('.fpbox');
		var div = $(document.createElement('div')).addClassName('badge_pager');
		container.appendChild(div);
		this._pagers = [];
		for (var i = this._objects.length-1; i >= 0 ; i--) {
			this._pagers[i] = $(document.createElement('div')).update(i+1);
 			if (i == this._current) this._pagers[i].addClassName('selected');
			div.appendChild(this._pagers[i]);
		};
		Event.observe(div, 'click', this._pagerClicked.bindAsEventListener(this));
	},
	_pagerClicked: function(evt) {
		var e = Event.element(evt);
		if (e.hasClassName('badge_pager')) return;
		for (var i = 0; i < this._pagers.length; i++) {
			if (this._pagers[i] == e) {
				this.switchTo(i);
			}
		}
	},
	start: function() {
		if (!this._enabled) return;
		if (this._timer) window.clearInterval(this._timer);
		this._timer = window.setInterval(this._next.bind(this), this._delay);
	},
	_switchTo: function(which) {
		if (this._effectOut) {
			this._effectOut.cancel();
			this._effectIn.cancel();
		}
		this._pagers[this._current].removeClassName('selected');
		this._pagers[which].addClassName('selected');
		this._effectOut = Effect.Fade(this._objects[this._current], {duration: 0.5});
		this._effectIn  = Effect.Appear(this._objects[which], {duration: 1});
		this._current = which;
	},
	_next: function() {
		var t = this._current + 1;
		if (t == this._objects.length) t = 0;
		this._switchTo(t);
	},
	switchTo: function(which) {
		if (!this._enabled) return;
		this.start();
		this._switchTo(which);
	}
};

function flipSearchPage(evt) {
	Event.stop(evt);
	var e = Event.element(evt);
	var h = e.href.split('#');
	updateSearch($('searchBooks') || $('featurebox_search'), urlDecode(h[1]), h[2]);
}

function updateSearch(bookSpace, query, page) {
	if (!bookSpace) return;
    if ($('prevPage')) Event.stopObserving($('prevPage'), 'click');
    if ($('nextPage')) Event.stopObserving($('nextPage'), 'click');
	switchToTab($('showfeature_search'));
	bookSpace.update('<div id="loading_white"></div>');
    new Ajax.Updater(bookSpace, searchPath, {
        parameters: { 'q': query, 'page': page },
        onComplete: function() {
        	if ($('prevPage')) Event.observe($('prevPage'), 'click', flipSearchPage);
        	if ($('nextPage')) Event.observe($('nextPage'), 'click', flipSearchPage);
        }
    });
};

function setupSearch() {
	if (!$) return;
	var bookSpace = $('searchBooks') || $('featurebox_search');
	var search = $('searchButton');
	if (!bookSpace || !search) return;
	Event.observe(search, 'click', function(evt) {
		Event.stop(evt);
		updateSearch(bookSpace, $F('for'), 1);
	});
    Event.observe($('searchForm'), 'submit', function(evt) {
        Event.stop(evt);
        updateSearch(bookSpace, $F('for'), 1);
    });
	Event.observe($('for'), 'focus' , function() {
		var f = $('for');
		f.setStyle({'color': '#000'});
		if ($F(f) == 'Search books') f.value = '';
	});
	Event.observe($('for'), 'blur' , function() {
		var f = $('for');
		f.setStyle({'color': '#A1A1A1'});
		if ($F(f) == '') f.value = 'Search books';
	});
	$$('.quicksearch').each(function(e) {
		Event.observe(e, 'click', function(evt) {
			Event.stop(evt);
			updateSearch(bookSpace, e.className.replace('quicksearch ', ''), 1);
		});
	});

};

function flipRecentPage(evt) {
    Event.stop(evt);
    var e = Event.element(evt);
    var h = e.href.split('#');
    updateRecent($('newBooks'), h[1]);
};
function updateRecent(bookSpace, page) {
    if (!bookSpace) return;
    if ($('prevRecPage')) Event.stopObserving($('prevRecPage'), 'click');
    if ($('nextRecPage')) Event.stopObserving($('nextRecPage'), 'click');
    new Ajax.Updater(bookSpace, recentPath, {
        parameters: { 'page': page },
        onComplete: function() {
            fixThumbnails();
            if ($('prevRecPage')) Event.observe($('prevRecPage'), 'click', flipRecentPage);
            if ($('nextRecPage')) Event.observe($('nextRecPage'), 'click', flipRecentPage);
        }
    });
};
function setupRecent() {
    if (!$) return;
    var bookSpace = $('newBooks');
    var start = $('startRecent');
    if (!bookSpace || !start) return;
    Event.observe(start, 'click', function(evt) {
        Event.stop(evt);
        updateRecent(bookSpace, 1);
    });
};

function updateFeatured($page) {
	var e = $('featurebox_new');
	e.update('<div id="loading_white"></div>');
    new Ajax.Updater($('featurebox_new'), featureURL, {
	   parameters: {page: $page}
    });
	e.addClassName('loaded');
};
function showCommunity() {
    $('msgPopup').hide();
    $('text').value = '';
	$('msgEmail').show();
    Effect.Appear('message-popup');
};
function sendCommunity() {
	if ($F('text')) {
	    var form = $('contact-form');
	    var params = Form.serialize(form);
        new Ajax.Request(form.action, {
	    	'parameters': params
		});
	}

	return closeMessagePopup();
};
var __crossfader = null;
function init() {
	$$('#featurecontrol span').each(function(e) {
		Event.observe(e, 'click', switchFeature);
	});
	if ($('showfeature_new')) {
		Event.observe($('showfeature_new'), 'click', function() {
			if (!$('featurebox_new').hasClassName('loaded')) {
				$('featurebox_new').update('<div id="loading_white"></div>')
				updateFeatured(1);
			}
		});
	};
	__crossfader = new CrossFader($$('.badge'), 6000);
	setupSearch();
	setupRecent();
};

Event.observe(window, 'load', init);