/*
* URL handling class
*/
EchoUrl = Class.create();
Object.extend(EchoUrl.prototype, {
	initialize: function(url){
		this.url = new String(url);
	},
	get: function(){
		return this.url;
	},
	addArgument: function(argName, argValue){

		if(this.url.lastIndexOf(argName, this.url.length) != -1 && this.url.lastIndexOf(argName, this.url.length) > this.url.lastIndexOf("/", this.url.length))
		{
			this.url = this.url.sub("[&|?]"+argName+"=[0-9A-z\-_]+", "");
		}

		if(this.url.indexOf("?", 0) == -1) //new querystring yet
			this.url += "?"+argName+"="+argValue;
		else
			this.url += "&"+argName+"="+argValue;
	}
});


function randOrd(){
return (Math.round(Math.random())-0.5); }

/*
* Array randomizer
*/

/* 
* Base EchoUpdater
*/
EchoUpdater = Class.create();
Object.extend(EchoUpdater.prototype, {
	setOptions: function(options) {
		this.options = {
		exposureTime:		5,
		transitionTime:		1,
		incrFrom:  			0,
		incrTo:     		1,
		incrRandom:			false
		}

		Object.extend(this.options, options || {});
		this.incrIndex = 0;
		this.incrNums = Array();

		var a = 0;
		for(i=this.options.incrFrom;i<=this.options.incrTo;i++){
			this.incrNums[a] = i;
			a++;
		}

		if(this.options.incrRandom)
			this.incrNums.sort(randOrd);

		this._incrIncr();
	},
	_incrIncr: function(){
		if(this.incrIndex >= this.incrNums.size())
			this.incrIndex = 0;

		this.url.addArgument("inc", this.incrNums[this.incrIndex]);
		this.incrIndex++;
	}
});


/*
* EchoUpdater fade effect
*/
EchoUpdater.PeriodicalFader = Class.create();
Object.extend(Object.extend(EchoUpdater.PeriodicalFader.prototype, EchoUpdater.prototype), {
	initialize: function(element, url, options)
	{
		this.element = $(element);
		this.url = new EchoUrl(url);
		this.setOptions(options);

		new Ajax.Updater(this.element, this.url.get(), {asynchronous:false});
		setTimeout(this._fadeOut.bind(this), this.options.exposureTime * 1000);
	},
	_fadeOut: function()
	{
		new Effect.Opacity(this.element, {duration:this.options.transitionTime, from:1.0, to:0});
		setTimeout(this._changeContent.bind(this), this.options.transitionTime * 1000);
	},
	_fadeIn: function()
	{
		new Effect.Opacity(this.element, {duration:this.options.transitionTime, from:0, to:1.0});
		setTimeout(this._fadeOut.bind(this), this.options.exposureTime * 1000);
	},
	_changeContent: function()
	{
		this._incrIncr();
		new Ajax.Updater(this.element, this.url.get(), {asynchronous:false, onSuccess:function(){this._fadeIn()}.bind(this)});
	}
});

/* 
* EchoUpdater slide effect
*/
EchoUpdater.PeriodicalSlider = Class.create();
Object.extend(Object.extend(EchoUpdater.PeriodicalSlider.prototype, EchoUpdater.prototype), {
	initialize: function(element, url, options)
	{
		this.element = $(element);
		this.url = new EchoUrl(url);
		this.setOptions(options);

		this.height = Element.getHeight(this.element);
		this.boxesCount = 0;
		this.boxesTotalHeight = 0;
		this.element.makeClipping();

		this._populate();
	},
	_populate: function(){
		var box = document.createElement("div");
		this.element.appendChild(box);
				/* L & D */
		this.boxesCount++;
				

		if(this.boxesCount <2 ) {
			new Ajax.Updater(box, 'payment_read.php', {asynchronous:false});
		} else {
		
			new Ajax.Updater(box, 'blank.php', {asynchronous:false});
		
		}
				/* L & D */
		this._incrIncr();

		this.boxesTotalHeight += box.getHeight();
		

		if(this.boxesTotalHeight < this.height && this.boxesCount < 9) //20 is just here to be sure we don't load forever
			setTimeout(this._populate.bind(this), 100);
		else
			setTimeout(this._pushOnTop.bind(this), this.options.exposureTime * 1000);

	},
	_pushOnTop: function()
	{
		var box = document.createElement("div");

		Element.makePositioned(box);
		//box.setStyle({zoom: 1});
		box.setStyle({display: 'none'}); 

		this._incrIncr();
		new Ajax.Updater(box, this.url.get(), {asynchronous:false});

		this.element.insertBefore(box, this.element.firstChild);
		Effect.SlideDown(box, {duration:this.options.transitionTime, afterFinish:function(){this._pushOk();}.bind(this)});
	},
	_pushOk: function(){
		this.element.removeChild(this.element.lastChild);
		setTimeout(this._pushOnTop.bind(this), this.options.exposureTime * 1000);
	}
});


/* 
* EchoUpdater slide effect from an array
*/
EchoUpdater.PeriodicalArraySlider = Class.create();
Object.extend(Object.extend(EchoUpdater.PeriodicalArraySlider.prototype, EchoUpdater.prototype), {
	initialize: function(element, url, options)
	{
		this.element = $(element);
		this.url = new EchoUrl(url);
		this.setOptions(options);

		this.height = Element.getHeight(this.element);
		this.boxesCount = 0;
		this.boxesTotalHeight = 0;
		this.element.makeClipping();

		this._populate();
	},
	_populate: function(){
		var box = document.createElement("div");
		this.element.appendChild(box);

		box.innerHTML="<div class='recent_service'> test 1</div>"+getCurrTime();
		this._incrIncr();

		this.boxesTotalHeight += box.getHeight();
		this.boxesCount++;

		if(this.boxesTotalHeight < this.height && this.boxesCount < 20) //20 is just here to be sure we don't load forever
			setTimeout(this._populate.bind(this), 100);
		else
			setTimeout(this._pushOnTop.bind(this), this.options.exposureTime * 1000);

	},
	_pushOnTop: function()
	{
		var box = document.createElement("div");

		Element.makePositioned(box);
		//box.setStyle({zoom: 1});
		box.setStyle({display: 'none'}); 

		this._incrIncr();
		box.innerHTML="<div class='recent_service'> test 2</div>"+getCurrTime();

		this.element.insertBefore(box, this.element.firstChild);
		Effect.SlideDown(box, {duration:this.options.transitionTime, afterFinish:function(){this._pushOk();}.bind(this)});
	},
	_pushOk: function(){
		this.element.removeChild(this.element.lastChild);
		setTimeout(this._pushOnTop.bind(this), this.options.exposureTime * 1000);
	}
});


EchoCalendar = Class.create();
Object.extend(EchoCalendar.prototype, {
	initialize: function(element, options)
	{
		this.element = element;
		this.shownOneTime = false; //wether the calendar has been shown one time or not
		this.mainBox = document.createElement("div");
		this.header = document.createElement("div");
		this.header_date = document.createElement("div");
		this.header_next = document.createElement("div");
		this.header_prev = document.createElement("div");
		this.daysBox = document.createElement("div"); //box with all days inside
		this.dayNamesBox = document.createElement("div");
		this.clearer = document.createElement("div");
		this.dayObservers = new Array();

		this.dayBoxes = new Array(); //array of boxes for one day each

		this.offsets = Position.cumulativeOffset(element);
		this.current_date = new Date();
		this.current_month = this.current_date.getMonth();
		this.current_year = this.current_date.getFullYear();
		
		(options['outputFormat'] != undefined) ? this.outputFormat = options['outputFormat'].toLowerCase() : this.outputFormat = "us";
		if(options['monthes'] != undefined && options['monthes'].length == 12)
			this.monthes = options['monthes'];
		else
			this.monthes = new Array('January','February','March','April','May','June','July','August','Septembre','October','November','December');

		if(options['days'] != undefined && options['days'].length == 7)
			this.days= options['days'];
		else
			this.days = new Array('Sun','Mon','Tue','Wed','Thu','Wed','Sat');

		this.callbackFncName = '';

		this.hideListener = this._checkClick.bindAsEventListener(this);

		Element.makePositioned(this.mainBox);
		Element.hide(this.mainBox);

		this.offsets[1] += element.getHeight();

		Element.setStyle(this.mainBox, {
			position:"absolute",
			top: this.offsets[1]+"px",
			left: this.offsets[0]+"px",
			width: "189px",
			border: "1px solid #AAAAAA",
			backgroundColor: '#FFFFFF'
			});

		Element.setStyle(this.header,{
			width: "100%",
			height: "20px",
			borderBottom: "1px solid #AAAAAA",
			textAlign: "center"
			});
		Element.addClassName(this.header, "calendar_header");

		Element.setStyle(this.clearer, {clear:"both", height:"0px", fontSize:"0px"});

		Element.setStyle(this.header_prev,{marginLeft: "2px",float:"left", width:"20px", fontWeight:"bold", cursor: "pointer"});
		Element.setStyle(this.header_date,{float:"left", width:"135px"});
		Element.setStyle(this.header_next,{marginRight: "2px",float:"right", width:"20px", fontWeight:"bold", cursor: "pointer"});

		Element.setStyle(this.dayNamesBox, {width:"100%", height:"14px", border: "0px solid"});
		Element.addClassName(this.dayNamesBox, "calendar_days_names_box");
		//Element.setStyle(this.daysBox,{border: "1px solid"});

		this.header_prev.innerHTML = "&lt;&lt;";
		this.header_next.innerHTML = "&gt;&gt;";

		Event.observe(this.header_prev, 'click', this._prev.bindAsEventListener(this));
		Event.observe(this.header_next, 'click', this._next.bindAsEventListener(this));

		this.mainBox.appendChild(this.header);
		this.header.appendChild(this.header_prev);
		this.header.appendChild(this.header_date);
		this.header.appendChild(this.header_next);
		this.header.appendChild(this.clearer);

		this.mainBox.appendChild(this.dayNamesBox);
		this.mainBox.appendChild(this.daysBox);

		this._writeDaysNames();
		//this._update();
		document.body.appendChild(this.mainBox);
	},
	show: function(){
		if(!this.shownOneTime){
			this._update();
			this.shownOneTime = true;
		}

		Element.show(this.mainBox);
		Event.observe(document, "click", this.hideListener);
	},
	_hide: function(){
		Element.hide(this.mainBox);
	},
	_checkClick: function(event){
		//if the calendar is shown and there is a click outside of it, we hide it
		var mouseX = Event.pointerX(event);
		var mouseY = Event.pointerY(event);

		if( mouseX < this.offsets[0] ||  mouseX > (this.offsets[0] + Element.getWidth(this.mainBox)) 
			|| mouseY < this.offsets[1] - 40 || mouseY > (this.offsets[1] + Element.getHeight(this.mainBox)) )
		{
			this._hide();
			Event.stopObserving(document, "click", this.hideListener);
		}
	},
	_prev: function(){
		if( this.current_month == 0 ){
			this.current_month = 11;
			this.current_year--;
		}
		else
			this.current_month--;

		this._update();
	},
	_next: function(){
		if( this.current_month == 11 ){
			this.current_month = 0;
			this.current_year++;
		}
		else
			this.current_month++;

		this._update();
	},
	_writeDaysNames: function(){
		for(i=0; i<7;i++){
			var dayName = document.createElement("div");
			Element.setStyle(dayName, {textAlign:'center',width:"25px",float:"left",border:"1px solid #888"});
			Element.addClassName(dayName, "calendar_day_name");
			dayName.innerHTML = this.days[i];
			this.dayNamesBox.appendChild(dayName);
		}
		this.dayNamesBox.appendChild(this.clearer);
	},
	_update: function(){
		this.current_date = new Date(this.current_year, this.current_month, this.current_date.getDate());
		this.header_date.innerHTML = "<div style='height:18px;' class='calendar_header_date'>"+this.monthes[this.current_date.getMonth()]+" "+this.current_date.getFullYear()+"</div>";
		this.daysBox.innerHTML = '';
		var tmpDate = new Date(this.current_year, this.current_month, 1);
		var totalCases = 0;

		/*
		this.dayObservers.each(function(observer){
			if(observer != undefined)
				Event.
			}.bind(this));
		*/

		//we draw the empty days before the 1st
		for(i=0;i<tmpDate.getDay();i++)
		{
			var dayBox = document.createElement("div");
			Element.setStyle(dayBox, {backgroundColor:"#EEEEEE",textAlign:'center',float:"left",border:"1px solid #BBB",width:"25px", height:"16px"});
			Element.addClassName(dayBox, "calendar_day");
			this.daysBox.appendChild(dayBox);
			totalCases++;
		}

		//we draw the dates
		for(i=1;i<=31;i++)
		{
			tmpDate.setDate(i);
			var day = tmpDate.getDate();
			var dayBox = document.createElement("div");
			Element.setStyle(dayBox, {backgroundColor:"#EEEEEE",textAlign:'center',float:"left",border:"1px solid #BBB",width:"25px", height:"16px", cursor:"pointer"});
			Element.addClassName(dayBox, "calendar_day");

			dayBox.innerHTML = day;
			this.dayObservers[i] = this._outputDate.bindAsEventListener(this, day);
		    Event.observe(dayBox, "click", this.dayObservers[i]);
		    Event.observe(dayBox, "mouseover", this._highlightDay.bindAsEventListener(this, dayBox));
		    Event.observe(dayBox, "mouseout", this._unHighlightDay.bindAsEventListener(this, dayBox));

			if(day >= i){
				this.daysBox.appendChild(dayBox);
				totalCases++;
			}
		}

		//we draw the empty days after the last one
		var emptyCases = Math.abs(totalCases - (Math.ceil(totalCases / 7)) * 7);
		for(i=0;i< emptyCases ;i++)
		{
			var dayBox = document.createElement("div");
			Element.setStyle(dayBox, {backgroundColor:"#EEEEEE",textAlign:'center',float:"left",border:"1px solid #BBB",width:"25px", height:"16px"});
			Element.addClassName(dayBox, "calendar_day");
			this.daysBox.appendChild(dayBox);
		}

		this.daysBox.appendChild(this.clearer);
	},
	_highlightDay: function(event, box){
		Element.setStyle(box, {backgroundColor:"#FFFFFF"});
	},
	_unHighlightDay: function(event, box){
		Element.setStyle(box, {backgroundColor:"#EEEEEE"});
	},
	_outputDate: function(event, day){
		day = ""+day;
		month = ""+(this.current_month + 1);

		if(day.length == 1) day = "0"+day;
		if(month.length == 1) month = "0"+month;
	
		if(this.outputFormat == 'eu')
			this.element.value = day+"/"+month+"/"+this.current_year;
		else
			this.element.value = month+"/"+day+"/"+this.current_year;

		this._hide();
		if(this.callbackFncName != '')
			eval(this.callbackFncName);

	},
	setCallBack: function(callbackFncName){
		this.callbackFncName = callbackFncName;
	}
});


