﻿var WWDC = Class.create();
WWDC.prototype = {
	initialize: function(timer, url) {
		this.counttime=timer;
		this.starttime=timer;
		this.visiblebox=0;
		this.boxcount=0;
		this.updateElement=$('update_status');
		this.container=$('wwdc_container');
		this.secondsElement=$('update_text');
		this.counterbox=$('counter');
		this.alertbox=$('alert');
		this.url=url;		
		this.correctImages();
	},
	
	liveUpdate: function(pe) {
		this.counttime--;
		if (this.counttime==0) {
			pe.stop();
			this.updateElement.innerHTML='Updating...';
			this.secondsElement.innerHTML='';
			var id=this.getMaxId();
			new Ajax.Request(this.url, {postBody: 'id='+id, onComplete: this.ajaxResponse.bind(this)});
		} else
		{
			this.updateElement.innerHTML=this.counttime;
			if (this.counttime>24 && this.counttime<31 || this.counttime>4 && this.counttime<22) {
				this.secondsElement.innerHTML='sekund';
			} else if (this.counttime>21 && this.counttime<25 || this.counttime>1 && this.counttime<5) {
				this.secondsElement.innerHTML='sekundy';
			} else if (this.counttime==1) {
				this.secondsElement.innerHTML='sekundę';
			}

			if (this.visiblebox==0 && this.boxcount==2) {
				this.alertbox.morph('margin-top: -30px');
				this.visiblebox=1;
				this.boxcount=0;
			} else {
			if (this.boxcount==6) {
				this.alertbox.morph('margin-top: 0px');
				this.visiblebox=0;
				this.boxcount=0;
				}
			}
			this.boxcount+=1;
		}
	},
	
	startUpdate: function() {
		this.counttime=this.starttime;
		this.updateElement.innerHTML=this.counttime;
			if (this.counttime>24 && this.counttime<31 || this.counttime>4 && this.counttime<22) {
				this.secondsElement.innerHTML='sekund';
			} else if (this.counttime>21 && this.counttime<25 || this.counttime>1 && this.counttime<5) {
				this.secondsElement.innerHTML='sekundy';
			} else if (this.counttime==1) {
				this.secondsElement.innerHTML='sekundę';
			}
		new PeriodicalExecuter(this.liveUpdate.bind(this), 1);
	},
	
	getMaxId: function () {
		var element=$A(Element.getElementsByClassName(this.container, 'message')).first();
		if (element) {
			return element.id.sub('message','');
		} else {
			return 0;
		}
	}, 
	
	correctImages: function () {
		$A(this.container.getElementsByTagName('img')).each(function(item){
			if (Element.hasClassName(item, 'corrected')==false) {
				Element.addClassName(item, 'corrected');
				item.parentNode.parentNode.appendChild(item);
			};
		});
	},
	
	ajaxResponse: function(request) {
		if (request.responseText) {
			var text=request.responseText;
			text='<div class="animIt anim_wrapper" style="display: none;">'+text+'</div>'
			var test=new Insertion.Top(this.container,text);
			var element=$A(Element.getElementsByClassName(this.container, 'animIt')).first();
			Element.removeClassName(element,'animIt');
			element.hide();
			this.correctImages();
		    Effect.BlindDown(element);
		}
		this.startUpdate();
	}
	
}