/* Millerstore
	(c) 2006-2009 Omines - www.omines.nl
	
	All rights explicitly reserved - unauthorized reproduction strictly prohibited
*/

// Compatibility stuff
Element.implement({
	effect: function(property, options){
		return new Fx.Tween(this, $extend({property: property}, options));
	},

	effects: function(property, options){
		return new Fx.Tween(this, $extend({property: property}, options));
	}
});

// Site class - main active content wrapper
var Site = {
	delay: 0,
	regionIndex: -1,
	start: function()
	{
		new SmoothScroll({duration:300, transition:Fx.Transitions.Expo.easeOut});
		this.initDropshadows();
		this.initAccordion();
		this.initRegionAccordion();
		this.initTicker();
		this.initSearchForm();
		if ($('flashmap'))
			this.initFlashMap();
		Ellipses.start();
		$$('input.DatePicker').each( function(el){
			new DatePicker(el);
		});
		if (typeof GMapLoad == 'function')
			GMapLoad();
	},
	initSearchForm: function()
	{
		if ($('searchblock'))
		{
			var jsonUrl	= '/json/search/provinces';
			window.addEvent('domready', function() {
				var ProvinceList = new JSONSelectBoxBuilder($('ProvinceId'), {
					element: $('ProvinceId'),
					jsonLocation: jsonUrl,
					defaultText: $('ProvinceId').getFirst('option').get('text'),
					idValue: 0
				});
				$('RegionId').addEvent('change', function() {
					ProvinceList.setId(this.getSelected().get('value'));
					ProvinceList.populate(0);
				});
				ProvinceList.setId($('RegionId').getSelected().get('value'));
				ProvinceList.populate(0);
			});
			
			$('searchtypes').getElements('a').each(function (el){
				el.addEvent('click', function(event){
					event.stop();
					el.getParent('ul').getElements('li').each(function (e){
						e.removeClass('active');
					});
					el.getParent('li').addClass('active');
					$('PropertyTypeId').set('value', el.getFirst('img').get('alt'));
				});
			});
		}
	},
	initTicker: function()
	{
		if ($('imagelist'))
		{
			this.ticker = new ImageTicker($('imagelist'));
			$('imagelistcontainer').addEvent('mouseenter', function(event){
				Site.ticker.morph.pause();
			});
			$('imagelistcontainer').addEvent('mouseleave', function(event){
				Site.ticker.morph.resume();
			});
			$('tickerUpButton').addEvent('mouseenter', function(event){
				Site.ticker.moveUp();
			});
			$('tickerDownButton').addEvent('mouseenter', function(event){
				Site.ticker.moveDown();
			});
		}
	},
	initDropshadows: function()
	{
		$$('.shadow').each(function(el) {
			var txt = el.get('text');
			el.setStyle('z-index', 0);
			el.setStyle('position', 'relative');
			new Element('span', {'html': txt, 'class': 'dropshadow-tl'}).inject(el, 'top');
			new Element('span', {'html': txt, 'class': 'dropshadow-br'}).inject(el, 'top');
		}, this);
	},
	initAccordion: function()
	{
		if ($('accordion'))
			var myAccordion = new FadeAccordion($('accordion').getChildren('h3.toggler'), $('accordion').getChildren('div.element'), {
			    fixedHeight: 369,
			    duration: 800,
			    onActive: function (toggler, element){
					if (Browser.Engine.trident && !document.documentMode)
					{
						this.elements[this.previous].setStyle('display', 'block');
						this.elements[(this.previous - 1 + this.elements.length) % this.elements.length].setStyle('display', 'none');
					}
				},
			    onBackground: function (toggler, element){
					this.fadeTimer = $clear(this.fadeTimer);
					if (this.images[this.previous]){
						this.images[this.previous].each(function(el, idx){
							if (idx == 0 && !Browser.Engine.trident)
								el.addClass('active').setStyles({opacity: 1, filter: 'alpha(opacity=100)'});
							else
								el.removeClass('active').setStyles({opacity: 0, filter: 'alpha(opacity=0)', visibility: 'hidden'});
						});
					}
				},
			    onComplete: function(idx){
					//element.addClass('activeelement');
					this.startLoop();
		    	}
			});
	},
	initRegionAccordion: function()
	{
		if ($('regionselector'))
			this.regionAccordion = new FadeAccordion($('regionselector').getElements('li.regionToggler'), $('regionselector').getElements('ul.regionElement'), {
			    display: this.regionIndex,
				duration: 400,
			    alwaysHide: true,
			    initialDisplayFx: false
			});
	},
	initFlashMap: function()
	{
        var so = new SWFObject("static/map/italyMap.swf", "interactiveItalyMap", "537px", "690", "8");
        so.addParam("wmode", "transparent");
        so.write("flashmap");
	}
};

var FadeAccordion = new Class({
	Extends: Fx.Accordion,
	images: new Array(),
	delay: 5000,
	initialize: function(togglers, elements, properties){
		this.parent(togglers, elements, properties);
		elements.each(function(el, index){
			this.images[index] = el.getFirst().getChildren('.image');
			this.images[index].each(function(e){
				e.setStyle('opacity', 0);
			});
		}, this);
	},
	startLoop: function(){
		this.currentPicture = 0;
		this.crossFade();
	},
	crossFade: function()
	{
		this.images[this.previous][this.currentPicture % this.images[this.previous].length].get('tween').start('opacity', 1);
		if (this.images[this.previous].length < (this.currentPicture + 2))
			this.fadeTimer = this.display.delay(this.delay, this, (this.previous + 1) % this.togglers.length);
		else
			this.fadeTimer = this.doNext.delay(this.delay, this);
	},
	doNext: function()
	{
		this.images[this.previous][this.currentPicture].removeClass('active').get('tween').start('opacity', 0);
		this.images[this.previous][(++this.currentPicture) % this.images[this.previous].length].addClass('active');
		this.crossFade();
	}
});

//Ellipses class - controls ellipsis elements on the site
var Ellipses = {
	start: function()
	{
		this.boundmove = this.mousemove.bindWithEvent(this);
		this.boundout = this.mouseout.bindWithEvent(this);
		this.count = 1;
		this.lookup = new Array();
		this.hovertip = new Element('span', {'class':'ellipsisHover'}).injectInside(document.body);
		this.hovertip.addEvent('mouseleave', this.boundout).addEvent('mousemove', this.boundmove);
		$$('.ellipsis').each(this.prepare, this);
	},
	prepare: function(el)
	{	
		var parent = el.getParent();
		var clipWidth = parent.offsetWidth - (el.offsetLeft - parent.offsetLeft);
		if(el.offsetWidth > clipWidth)
		{
			el.addEvent('mouseenter', this.hover.bindWithEvent(this));
			if(el.id == '')
				el.id = 'ellipsis'+this.count++;
			var content = el.get('text');
			this.lookup[el.id] = content;
			el.title = '';
			if(!window.ie)
			{
				content = content.substring(0, (clipWidth / (el.offsetWidth)) * content.length);
				do {
					el.set('html', content+'&hellip;');
					content = content.substring(0, content.length - 1);
				} while(el.offsetWidth > clipWidth);
			}
		}
	},
	hover: function(e)
	{
		var el = e.target;
		var cnt = this.lookup[el.id];
		this.hovertip.setStyles(el.getStyles('font-size','font-style','color'));
		this.hovertip.setStyles({position:'absolute',left:el.getLeft()-2,top:el.getTop()-2,visibility:'hidden'});
		if(el.get('tag') == 'a')
			cnt = '<a href="'+el.href+'">'+cnt+'</a>';
		this.hovertip.set('html', cnt);
		el.addEvent('mouseleave', this.boundout).addEvent('mousemove', this.boundmove);
		if(this.fx) this.fx.cancel();
		this.show.delay(150, this);
		this.target = el;
	},
	mousemove: function(e)
	{
		$clear(this.timer);
	},
	mouseout: function(e)
	{
		var c = e.target.getCoordinates();
		if(c.left > e.client.x || c.right < e.client.x || c.top > e.client.y || c.bottom < e.client.y)
			this.timer = this.hide.delay(250, this);
	},
	show: function(e)
	{
		this.fx	= new Fx.Tween(this.hovertip, {duration:'short'});
		this.fx.start('opacity', 0.5, 1);
		//this.fx = new Fx.Style(this.hovertip, 'opacity').start(0.5, 1);
	},
	hide: function(e)
	{
		this.fx.cancel();
		this.hovertip.setStyle('visibility','hidden');
		if(this.target)
			this.target.removeEvent('mouseleave', this.boundout).removeEvent('mousemove', this.boundmove);
		this.target = null;
	}
};

var ImageTicker = new Class({
	speed: 2000,
	direction: 1,		// -1 = scroll upwards, 1 = scroll downwards
	running: true,
	justSwitched: false,
	initialize: function(el, direction, speed)
	{
		this.el			= el;
		this.direction	= direction ? direction : this.direction;
		this.speed		= speed ? speed : this.speed;
		this.morph = new Fx.Morph(this.el, {
			duration: this.speed,
			onComplete: function() {
				if (this.direction == -1)
				{
					if (this.justSwitched)
						this.justSwitched = false;
					else
						this.el.setStyle('top', 1).getFirst('div.image').dispose().inject(this.el);
				}
				this.loop();
			}.bind(this)
		});
		this.loop();
	},
	loop: function()
	{
		if (this.running)
		{
			if (this.direction == 1)
			{
				if (this.justSwitched)
					this.justSwitched = false;
				else
				{
					this.el.getLast('div.image').dispose().injectBefore(this.el.getFirst('div.image'));
					this.el.setStyle('top', this.el.getFirst('div.image').getSize().y * -this.direction);
				}
				this.morph.start({top: 1});
			}
			else
			{
				this.morph.start({top: this.el.getFirst('div.image').getSize().y * this.direction});
			}
		}
	},
	moveUp: function()
	{
		if (this.direction == 1)
			this.justSwitched = true;
		this.direction = -1;
	},
	moveDown: function()
	{
		if (this.direction == -1)
			this.justSwitched = true;
		this.direction = 1;
	},
	stop: function()
	{
		this.running = false;
	},
	go: function()
	{
		this.running = true;
		this.loop();
	}
});

//JSONSelectBoxBuilder
var JSONSelectBoxBuilder = new Class ({
	Implements: [Options, Events],
	options: {
		element: '',
		jsonLocation: '',
		idValue: 0,
		defaultText: ''
	},
	initialize: function(obj, options)
	{
		this.setOptions(options);
	},
	setId: function(value)
	{
		this.options.idValue = value;
	},
	clear: function()
	{
		this.options.element.empty();
		new Element('option', {value:0, text:this.options.defaultText}).inject(this.options.element);
	},
	populate: function(selectedId)
	{
		this.selectedId = selectedId;
		new Request.JSON({
			url: this.options.jsonLocation + '/' + this.options.idValue,
			method:'get',
			onSuccess: function(response)
			{
				this.clear();
				if (response.data[0])
					response.data.each(function(item){
						if (this.selectedId == item.id)
							new Element('option', {value:item.id, text:item.value, selected:'selected'}).inject(this.options.element);
						else
							new Element('option', {value:item.id, text:item.value}).inject(this.options.element);
					}, this);
			}.bind(this)
		}).send();
	}
});

function PopulateContentBlock(blockType, block)
{
	new Request.JSON({
		url: '/json/search/sidebar/' + blockType,
		method:'get',
		onSuccess: function(response)
		{
			if (response.data)
			{
				if (block.getElement('h5'))
				{
					block.getElement('h4').set('text', response.data.CityName);
					block.getElement('h5').set('text', response.data.PropertyName);
				}
				else
					 block.getElement('h4').set('text', response.data.PropertyName);
				block.getElement('p').set('text', response.data.ShortDescription);
				if (block.getElement('img'))
					block.getElement('img').dispose();
				if (block.getElement('a[rel=milkbox]'))
					block.getElement('a[rel=milkbox]').dispose();
				if (response.data.ImageFileName)
				{
					if (response.data.HorizontalFileName)
						new Element('img', {src:'/assets/properties/horizontal/' + response.data.ImageFileName, alt:response.data.PropertyName}).addClass('panorama').injectInside(new Element('a', {href:response.data.LightBoxImage, rel:'milkbox'}).injectAfter(block.getElement('h4')));
					else
						new Element('img', {src:'/assets/properties/vertical/' + response.data.ImageFileName, alt:response.data.PropertyName}).addClass('portrait').injectInside(new Element('a', {href:response.data.LightBoxImage, rel:'milkbox'}).injectAfter(block.getElement('h3')));
					milkbox.prepareGalleries();
					milkbox.setGalleriesEvents();
				}
				block.getElements('div.left').getFirst('a').set('href', response.data.ReadMoreUrl);
				block.getElements('div.right').getFirst('a').set('href', response.data.RequestInfoUrl);
				block.getElements('span.price').set('text', response.data.Price);
			}
		}
	}).send();
}

function showLocation(locationId)
{   
	if (locationId > 0)
	{
		var block = $('locationinfo');
		new Request.JSON({
			url: '/json/location/info/' + locationId,
			method:'get',
			onSuccess: function(response)
			{
				if (response.data)
				{
					block.getElement('h3').set('text', response.data.LocationName);
					block.getElement('p').set('text', response.data.ShortDescription);
					if (block.getElement('img'))
						block.getElement('img').dispose();
					if (response.data.ImageFileName)
						new Element('img', {src:response.data.ImageFileName, alt:response.data.LocationName}).injectAfter(block.getElement('h3'));
				}
			}
		}).send();
	}
}
function sFl(idLocationToShow){
	var tests = document.interactiveItalyMap;
	var frame;

	switch(idLocationToShow){
		case 6:
			frame = 'Veneto';
			break;
		case 9:
			frame = 'Tuscany';
			break;
		case 17:
			frame = 'Puglia';
			break;
		case 15:
			frame = 'Campania';
			break;
		case 12:
			frame = 'Lazio';
			break;
		case 18:
			frame = 'Calabria';
			break;
		case 11:
			frame = 'Marche';
			break;
		case 10:
			frame = 'Umbria';
			break;
  }
  tests.TGotoLabel('/','show' + frame);
}

function selectLocation(locationId, propertyType)
{
	var regionType = 1;

	if (propertyType == regionType)
	{      
		//Shows the region information
		showLocation(locationId);

		//Gets the region index
		var selectedIndex = getRegionIndex(locationId)
       
		//Selects the acordion menu
		Site.regionAccordion.display(selectedIndex);
    }
}

function getRegionIndex(regionId)
{
	switch(regionId)
	{
		case 6: return 7;
		case 9: return 5;
		case 10: return 6;
		case 11: return 2;
		case 12: return 1;
		case 15: return 4;
		case 17: return 3;
		case 18: return 0;
	}
	return 0;
}

function getRegionByIndex(index)
{
	switch(index)
	{
		case 0: return 18;
		case 1: return 12;
		case 2: return 11;
		case 3: return 17;
		case 4: return 15;
		case 5: return 9;
		case 6: return 10;
		case 7: return 6;
	}
	return 0;
}



// Set event to start running active content when DOM is loaded
window.addEvent('domready', function() { Site.start(); });
