Object.extend(Event, {
	_domReady : function() {
		if (arguments.callee.done) return;
		arguments.callee.done = true;
		
		if (this._timer){
			clearInterval(this._timer);
		}
		
		this._readyCallbacks.each(function(f) { f() });
		this._readyCallbacks = null;
	},
	
	onDOMReady: function(f) {
		if (!this._readyCallbacks)
		{
			var domReady = this._domReady.bind(this);
			
			if (document.addEventListener)
			document.addEventListener("DOMContentLoaded", domReady, false);
			
			/*@cc_on @*/
			/*@if (@_win32)
			document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
			document.getElementById("__ie_onload").onreadystatechange = function() {
			if (this.readyState == "complete") domReady(); 
			};
			/*@end @*/
			
			if (/WebKit/i.test(navigator.userAgent))
			{ 
				this._timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) domReady(); 
				}, 10);
			}
			
			Event.observe(window, 'load', domReady);
			Event._readyCallbacks =  [];
		}
		Event._readyCallbacks.push(f);
	}
});


var Tabs = Class.create();
Tabs.prototype = {
	initialize: function(options)
	{
		this.options = {
			max_width: parseInt( Element.getStyle($('tabs_container'),'width')),
			ul: $$('#tabs_container ul').first(),
			all_tabs: $$('#tabs_container ul li'),
			container: $('offerads_content'),
			realsize: 0,
			current: 0,
			count_left: 2,
			
			controller:		$('controller').innerHTML,	//contain controller name
			offers_link:	$('offers_link').innerHTML,	//used as first part of the offer link
			public_path:	$('public_path').innerHTML,	//images path
			
			//labels
			promo_label:	$('promo_label').innerHTML,	//used as alt text for the red label with offer type
			city_label:		$('city_label').innerHTML,	//contain 'city' label according to current site language
			area_label:		$('area_label').innerHTML,	//contain 'area' label according to current site language
			square_meters_label: $('square_meters_label').innerHTML,	//contain 'square meters' label according to current site language
			price_label:	$('price_label').innerHTML	//contain 'price' label according to current site language
		};
		
		
		Object.extend(this.options, options || {});
		
		var clicked;
		this.clicked = true;		
		
		Event.observe( $('tabs_right_arrow'), 'click', function(){
			if (this.clicked == false) {
				this.clicked = true;
				this.prepareSwitchTab(1);
			}
		}.bind(this));
		
		Event.observe( $('tabs_left_arrow'), 'click', function(){
			if (this.clicked == false) {
				this.clicked = true;
				this.prepareSwitchTab(-1);
			}
		}.bind(this));
		
		//used to cashe cities data
		this.showCity = new Array();
		
		//save offers data for default selected city
		var filter_id = this.returnCityId(this.options.all_tabs[this.options.current]);
		this.showCity[filter_id] = this.options.container.innerHTML;
		
		
		var loader_margin;
		
		if(this.options.controller == 'application')
		{
			this.options.count_left = 2;
			loader_margin = 75;
		}
		else{
			this.options.count_left = 5;
			loader_margin = 45;
		}
		
		//set loading image
		var loading;
		this.loading = '<center><img src="' + this.options.public_path + '/files/images/loading.gif" alt="Loading" style="margin: ' + loader_margin + 'px"/></center>';

		var first_time;
		this.first_time = true;	
		
		
		this.calculate_width_ul();
		this.showTabs();
		this.clicked = false;
		
		this.options.all_tabs.each( function(el,ind){
			Event.observe( el, 'click', function(){
				if (this.clicked == false) {
					this.options.current = ind;
					this.first_time = false;
					this.clicked = true;
					this.showTabs();
				}
			}.bind(this) );
		}.bind(this));
		
		return true;
	},
	
	calculate_width_ul: function()
	{
		this.options.all_tabs.each( function(el){
			this.options.realsize += el.offsetWidth;
		}.bind(this));
		return;
	},
	
	showTabs: function()
	{
//		if (this.first_time != true) {
//			document.getElementById('tabs_hover').style.display = 'block';			
//			document.getElementById('tabs').style.display = 'none';			
//		}
		var current_width = 0;
		this.putContent();

		if ( this.options.realsize <= this.options.max_width )
		{
			this.options.all_tabs.each( function(el,ind){
				Element.removeClassName( el, 'current' );
				if ( ind == this.options.current )
				{
					Element.addClassName( el, 'current' );
				}
				el.style.visibility = 'visible';
			}.bind(this));
			return;
		}
	
		
		this.options.all_tabs.each( function(el){
			if ( el.parentNode )
			{
				el.parentNode.removeChild(el);
			}
		}.bind(this));
		
		
		var start = Math.abs( this.options.count_left - this.options.all_tabs.length + 1 - this.options.current );
		if ( start >= this.options.all_tabs.length )
		{
			start -= this.options.all_tabs.length;
		}
		
		do
		{
			if ( ++start >= this.options.all_tabs.length ) start = 0;
			
			this.options.ul.appendChild( this.options.all_tabs[start] );
			Element.show( this.options.all_tabs[start] );
			current_width += this.options.all_tabs[start].offsetWidth;
			
			Element.removeClassName( this.options.all_tabs[start], 'current' );
			if ( this.options.current == start )
			{
				Element.addClassName( this.options.all_tabs[start], 'current' );
			}
			
			if ( current_width <= this.options.max_width )
			{
				this.options.all_tabs[start].style.visibility = 'visible';
			}
			else
			{
				Element.hide( this.options.all_tabs[start] );	
				break;
			}
			
		} while( current_width < this.options.max_width );
	},
	
	prepareSwitchTab: function( pos )
	{
		this.options.current += pos;
		if ( this.options.current < 0 ) {
			this.options.current = this.options.all_tabs.length - 1
		}
		
		if ( this.options.current >= this.options.all_tabs.length ) {
			this.options.current = 0
		}
		this.showTabs();
	},
	
	putContent: function()
	{
		var filter_id = this.returnCityId(this.options.all_tabs[this.options.current]);
		
		var url = 'offerads/get/'+ this.options.controller;
		var pars = 'filter_id=' + filter_id;
		
		
		if(this.showCity[filter_id]) {
			this.options.container.innerHTML = this.showCity[filter_id];
			this.clicked = false;
		}
		else
		{
			this.options.container.innerHTML = this.loading;
			new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: this.reloadOfferads.bind(this)} );
		}
		
		return;
	},
	
	reloadOfferads: function(request, json)
	{
		this.clicked = false;
//		if (this.first_time != true) {
//			document.getElementById('tabs_hover').style.display = 'none';			
//			document.getElementById('tabs').style.display = 'block';			
//		}
		if ( json && json.length )
		{
			var len = json.length;
			var html = '';
			
			for ( i = 0; i < len; i++ )
			{
				var obj = json[i];
				
				var estate_name = obj.real_estate_name.replace(' ', '-');
				var city_name = obj.city_name.replace(' ', '-');
				var quarter = (obj.quarter_name != null) ? obj.quarter_name.replace(' ', '-'): '';
				
				html += '<div class="box">'
				html +='<a href="'+ this.options.offers_link + '/' + obj.id + '/' + estate_name + '/' + city_name + '/' + quarter + '">';
					if(obj.top_offer == 1)
						html += '<strong class="promobanner">'+ this.options.promo_label +'</strong>';
					else if(obj.stage_id == 4)
						html += '<strong class="exclusive_offer">'+ this.options.promo_label +'</strong>';
					else if(obj.is_new == 1)
						html += '<strong class="new_offer">'+ this.options.promo_label +'</strong>';
					else
						html += '<strong class="default_offer">'+ this.options.promo_label +'</strong>';
					
					if (obj.default_pic == 1)
						html += '<img alt="'+ obj.real_estate_name +'" src="'+ this.options.public_path +'/files/images/default_offer.gif" />';
					else
					{
						if (obj.path && obj.path != '_medium_thumb.jpg')
							html += '<img alt="'+ obj.real_estate_name +'" src="'+ this.options.public_path +'/files/'+ obj.path +'" />';
						else
						{
							html += '<img alt="'+ obj.real_estate_name +'" src="'+ this.options.public_path +'/files/images/nopicture_offerads';
							if (this.options.controller == "application")
								html += '_index'; 
							
							html += '.gif" />';
						}
					}
					html += '</a>'
					html += '<div class="info">'
					html += '<h4 style="text-transform: uppercase">'+ obj.real_estate_name +'</h4>'
						html += '<dl>'
							html += '<dt>'+ this.options.city_label +'</dt>'
								html += '<dd>'+ obj.city_name +'</dd>'
							html += '<dt>'+ this.options.area_label +'</dt>'
								html += '<dd>'+ obj.area + ' '+ this.options.square_meters_label +'</dd>'
							html += '<dt>'+ this.options.price_label +' </dt>'
								html += '<dd><strong>'+ obj.sell_price +'</strong> &euro;</dd>'
						html += '</dl>'
					html += '</div>'
				html += '</div><!-- end div class="box" -->';
			}//end for
			
			var filter_id = this.returnCityId(this.options.all_tabs[this.options.current]);
			this.showCity[filter_id] = html;
			this.options.container.innerHTML = this.showCity[filter_id];
		}
	},//end reloadOfferads()
	
	
	returnCityId: function(elem)
	{
		return parseFloat(elem.id.toString().replace('filter_', ''));
	}
};

var Tab;
Event.onDOMReady( function(){
	if ( $('tabs_container') ) {
		Tab = new Tabs();
	}
} );
