/*
	Beware, this is made of win.
	Below lines of awesomeness...
*/
var SlideToAction = new Class({
	include: Options,
	
	Options: {
		callback : function(){ alert('unlocked!'); },
		hiddenElement: "percent",
		slideText:"",
		releaseText:""
	},
	
	initialize: function(container, options) {
		this.setOptions(options);
		
		this.container = $(container);
		
		if (!this.container)
			return;
			
		this.isMouseDown = false;
		this.lastPos;
		this.percent = 0;
		this.captchaPercent = -10;
		this.hitEnd = false;
		this.releaseEnd = true;
		this.hiddenElement = $(this.options.hiddenElement);
		
		this.captcha = $E("div", {"class":"slider_captcha"});
		this.handle = $E("div", {"class":"slider_handle"});
		this.messageRight = $E("div", {"class":"slider_message_right"}).update(this.options.slideText);
		this.messageLeft = $E("div", {"class":"slider_message_left"}).update(this.options.releaseText);	
		this.sliderMiddle = $E("div", {"class":"slider_middle"});
		
		this.track = $E("div", {"class":"slider_container"})
					.insert($E("div", {"class":"slider_left"}))
					.insert($E("div", {"class":"slider_right"}))
					.insert(this.sliderMiddle.insert(this.messageLeft).insert(this.messageRight))
					.insert(this.captcha)
					.insert(this.handle)
					.insertTo(this.container);
		
		$(document).on({
			mousedown: function(e) { this.prepareSlider(e); }.bind(this),
			mouseup: function(e) { this.handleMouseUp(e); }.bind(this),
			mousemove: function(e) { this.slide(e); }.bind(this),
			selectstart: function(e) { this.interceptSelection(e); }.bind(this),
			
			//Mobile Webkit
			touchstart: function(e) { this.mouseEventEmulator(e); }.bind(this),
			touchmove: function(e) { this.mouseEventEmulator(e); }.bind(this),
			touchend: function(e) { this.mouseEventEmulator(e); }.bind(this),
			touchcancel: function(e) { this.mouseEventEmulator(e); }.bind(this)
		});
		
		this.captcha.setStyle("background: url(/handler/CaptchaHandler.ashx?captchaWidth=" + this.sliderMiddle.dimensions().width + ") no-repeat 50% 50%");
		this.handleMorph = new Fx.Morph(this.handle);
		this.messageRightMorph = new Fx.Morph(this.messageRight);
		this.messageLeftMorph = new Fx.Morph(this.messageLeft);
	},
	
	mouseEventEmulator: function(e) {
		var touches = e._.changedTouches,
			first = touches[0],
			type = "";
		
		switch(e.type) {
			case "touchstart": type = "mousedown"; break;
			case "touchmove":  type = "mousemove"; break;
			case "touchend":   type = "mouseup"; break;
			default: return;
		}
		
		var simulatedEvent = document.createEvent("MouseEvent");
		simulatedEvent.initMouseEvent(type, true, true, window, 1, 
									  first.screenX, first.screenY, 
									  first.clientX, first.clientY, false, 
									  false, false, false, 0/*left*/, null);
		first.target.dispatchEvent(simulatedEvent);
		
		if (this.isMouseDown)
			e._.preventDefault();
	},
	
	interceptSelection: function(e) {
		if (this.isMouseDown) {
			e.stop();
		}
	},
	
	prepareSlider: function(e) {
		if (e.find(".slider_handle")) {
			this.isMouseDown = true;
			this.lastPos = e.position();
			e.stop();
		}
	},
	
	handleMouseUp: function(e) {
		if (this.isMouseDown) {
			this.isMouseDown = false;
			this.release(e);
			this.doCallback();
		}
	},
	
	slide: function(e) {
		if (this.isMouseDown) {		
			var pos = e.position(),
				currentPos = {
				  y: this.handle.getStyle('top').toFloat(),
				  x: this.handle.getStyle('left').toFloat()
				},
				delta = {
				  y: pos.y - this.lastPos.y,
				  x: pos.x - this.lastPos.x
				},
				newPos = {
				  y: (currentPos.y + delta.y < 0) ? 0 : currentPos.y + delta.y,
				  x: (currentPos.x + delta.x < 0) ? 0 : currentPos.x + delta.x
				};
				
			if ((this.track.dimensions().width ) - (newPos.x + this.handle.dimensions().width) < 0) {
				newPos.x = this.track.dimensions().width - this.handle.dimensions().width;
			}
			
			this.percent = (newPos.x) / (this.track.dimensions().width - this.handle.dimensions().width);
			this.handle.setStyle("left", newPos.x + "px");
			this.messageRight.setStyle("opacity", 1 - this.percent * 5);
			this.lastPos = pos;
			
			var deltaBigSmall = (this.track.dimensions().width - this.sliderMiddle.dimensions().width) / 2,
				midHandlePos = (newPos.x + this.handle.dimensions().width / 2);
				
			this.captchaPercent = Math.round( (midHandlePos / this.sliderMiddle.dimensions().width - (deltaBigSmall / this.sliderMiddle.dimensions().width)) * 100);
			
			this.showDropMessage();
		}
	},
	
	showDropMessage: function() {
		if (!this.hitEnd && this.percent >= 1) {
			this.hitEnd = !this.hitEnd;
			this.releaseEnd = !this.releaseEnd;
			
			this.messageLeftMorph.cancel();
			this.messageLeftMorph.start(
				{opacity: "1"},
				{duration: "short"}
			);
		} else if(!this.releaseEnd && this.percent < 1) {
			this.releaseEnd = !this.releaseEnd ;
			this.hitEnd = !this.hitEnd;
				
			this.messageLeftMorph.cancel();
			this.messageLeftMorph.start(
				{opacity: "0"}, 
				{duration: "short"}
			);
		}					
	},
	
	doCallback: function() {
		//if (this.percent >= 1) {
		if (this.percent > 0) {
			this.options.callback();
		}
	},
	
	release: function(e) {
		this.hiddenElement.setValue(this.captchaPercent);
		
		this.handleMorph.cancel();
		this.handleMorph.start(
			{left: "0px"}, 
			{duration: "short"}
		);
		
		this.messageRightMorph.cancel();
		this.messageRightMorph.start(
			{opacity: "1"}, 
			{duration: "short"}
		);
			
		this.messageLeftMorph.cancel();
		this.messageLeftMorph.start(
			{opacity: "0"}, 
			{duration: "short"}
		);
	}
});


var VideoTeasers = new Class({
	initialize: function(teaserContainer, movie) {
		this.teaserContainer = $(teaserContainer);
		this.movie = $(movie);
		var _ref = this;
		
		this.teaserContainer.find('a').each(function(element, i) {
			element.on({
				click: function(e) { 
					if (element.get("rel")) {
						e.stop(); 
						_ref.sendToActionScript(element.get("rel"));
						_ref.highlightElement(element.get("rev"));
					} else if (element.get("href") != "#") {
						//e.stop();
						//Lightbox.load(element.get("href"));
						
						
					}
				}
			})
		});		
	},
	
	highlightElement: function(num) {
		this.teaserContainer.children().each(function(element, i) {
			element.removeClass("active");
			
			if (i == num) {
				element.addClass("active");
			}
		});
	},
		
	sendToActionScript: function(value) {
		if (value) {
			this.movie._.sendToActionScript(value);
		}
	}
});

var GoogleMap = new Class({
	include: Options,
	
	Options: {
		map : "map"
	},
	
	initialize: function(options, links) {
		this.setOptions(options);
			
		if (!GBrowserIsCompatible())
			return;
			
		this.map = new GMap2($(this.options.map)._);
		this.map.addControl(new GLargeMapControl());
		this.setupLinks(links)
	},
	
	setupLinks: function(links) {
		var ref = this;
		
		links.each(function(link, i) {
			element = $(link);
			
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.image = "/images/common/marker.png";
			baseIcon.iconSize = new GSize(18, 37);
			baseIcon.shadow = "/images/common/markershadow.png";
			baseIcon.shadowSize = new GSize(45, 35);
		
			markerOptions = { icon:baseIcon };

			var latLng = element.get("rel").split(","),
				markerText = element.get("rev"),
				marker = new GMarker(new GLatLng(latLng[0], latLng[1]), markerOptions);
			
			GEvent.addListener(marker, "click", function() { 
				marker.openInfoWindowHtml(markerText) 
			});
			
		

			ref.map.addOverlay(marker);
			
			element.on({
				click: function(e) { ref.map.setCenter(new GLatLng(latLng[0], latLng[1]), 15); e.stop(); }.bind(this)
			})
			
			if (!i) {
				ref.map.setCenter(new GLatLng(latLng[0], latLng[1]), 15);
			}
		});
	},
	
	jumpToCoords: function(coords, markerText) {
		this.map.setCenter(new GLatLng(coords.lat, coords.lng), 15);
		this.marker = new GMarker(new GLatLng(coords.lat, coords.lng));
		
		GEvent.addListener(this.marker, "click", function() { 
			marker.openInfoWindowHtml(markerText) 
		});
        map.addOverlay(this.marker);
	}
});

var CollapsibleBox = Class(Observer, {
	include: Options,
	
	Options: {
		showText : "Show",
		hideText : "Hide"
	},
	
	initialize: function(box, handle, options) {
		this.setOptions(options);
		
		this.box = $(box);
		this.handle = $(handle)
			
		if (!this.box || !this.handle)
			return;
			
		this.handle.update(this.options.showText)
		this.initialDimension = this.box.dimensions();
		
		this.box.setStyle({"height": "0"});
		
		this.handle.on({
			click: function(e) { this.onMenuClick(e); e.stop(); }.bind(this)
		});
		
		this.morph = new Fx.Morph(this.box, {onFinish: function() { window.scrollTo(0, this.box.position().y)}.bind(this) });
	},
	
	onMenuClick: function(e) {
		this.morph.cancel();
		this.morph.start(
			{height: (this.isOpen ? 0 : this.initialDimension.height) + "px"}, 
			{duration: "short"}
		);
		
		this.isOpen = !this.isOpen;
		this.handle.toggleClass("up");
		this.handle.update((this.isOpen) ? this.options.hideText : this.options.showText);
		this.fire((this.isOpen) ? "menuopen" : "menuclose", this);
	}
});


var Rotator = new Class({
	include: Options,
	
	Options: {
		auto: true,
		showbuttons: false,
		delay: 3500,
		fx: "morph",
		buttonnext: false,
		buttonprevious: false
	},
	
	initialize: function(list, options) {
		this.setOptions(options);
		this.list = $(list);
		this.interval = null;
		
		if (!this.list)
			return;
			
		this.currentIndex = 0;
		this.size = 0;
		this.listLength = this.list.children().length;
		this.setListSize();
		
		if (this.options.auto) {
			this.setMouseHooks();
			this.setAutoOn();
		}
		
		if (this.options.showbuttons) {
			this.btnPrev = (this.options.buttonprevious) ? $(this.options.buttonprevious) : $E("a", {"href": "#", "class": "previous"}).update("previous").insertTo(this.list.parent());
			this.btnNext = (this.options.buttonnext) ? $(this.options.buttonnext) : $E("a", {"href": "#", "class": "next"}).update("next").insertTo(this.list.parent());
			
			this.btnPrev.on({
				click: function(e) { this.previous(); e.stop(); }.bind(this)
			});
			
			this.btnNext.on({
				click: function(e) { this.next(); e.stop(); }.bind(this)
			});
		}
	
		this.fade = new Fx.Fade(this.list);
		this.morph = new Fx.Morph(this.list);
	},
	
	setMouseHooks: function() {
		var ref = this;
		
		this.list.children().each(function(element) {
			element.on({
				mouseover: function(e) { ref.setAutoOff(); },
				mouseout: function(e) { ref.setAutoOn(); }
			})
		});
	},
	
	setAutoOn: function() {
		if (!this.interval) {
			this.interval = setInterval(function(){ this.next() }.bind(this), this.options.delay);
		}
	},
	
	setAutoOff: function() {
		if (this.interval) {
			clearInterval(this.interval);
			this.interval = null;
		}
	},
	
	previous: function() {
		if (this.currentIndex - 1 < 0) {
			this.list.children().last().insertTo(this.list.children().first(), "before");
			this.list.setStyle("left", "-" + this.getNextPosition() + "px");
		}
		
		this.doTransition(this.getPreviousPosition());
		this.currentIndex = (this.currentIndex - 1 <= 0) ? 0 : this.currentIndex - 1;
	},
	
	next: function() {
		if (this.currentIndex + 1 >= this.listLength) {
			this.list.children().first().insertTo(this.list.children().last(), "after");
			this.list.setStyle("left", "-" + this.getPreviousPosition() + "px");
		}

		this.doTransition(this.getNextPosition());
		this.currentIndex = (this.currentIndex + 1 >= this.listLength) ? this.listLength -1 : this.currentIndex + 1;
	},
	
	doTransition:function(nextPos) {
		switch(this.options.fx) {
			case "fade":
				this.fade.cancel();
				this.fade.start('in', {duration:"short", queue:"false"});
				this.list.setStyle("left", "-" + nextPos + "px");
				break;
			case "morph":
			default:
				this.morph.cancel();		
				this.morph.start(
					{"left": "-" + nextPos + "px"}, 
					{duration: "normal", transition: "Log"}
				);
				break;
		}
	},
	
	getNextPosition: function() {
		return ((this.currentIndex + 1 >= this.listLength ? this.listLength - 1 : this.currentIndex + 1)) * (this.size / this.listLength)
	},
	
	getPreviousPosition: function() {
		return ((this.currentIndex -1 <= 0 ? 0 : this.currentIndex - 1)) * (this.size / this.listLength);
	},
		
	setListSize: function() {
		this.list.children().each(function(element, i) {
			this.size += element.dimensions().width;
		}.bind(this));
		
		this.list.setWidth(this.size);
	}
});

var MobileMenu = Class({
	initialize: function() {
		
		this.menuContainer = $("menucontainer");
		this.menu = $("menu");
		this.buttonMore = $("mobile_menu_botton_more");
		
		this.initialMenuDimension = this.menu.dimensions();
		this.initialButtonDimension = this.menuContainer.dimensions();
		
		this.isOpen = false;
		
		this.buttonMore.on({
			click: function(e) { this.onMenuClick(e); e.stop(); }.bind(this)
		});
		
		this.morph = new Fx.Morph(this.menuContainer);
	},
	
	onMenuClick: function(e) {
		this.morph.cancel();
		this.morph.start(
			{height: (this.isOpen ? this.initialButtonDimension.height : this.initialMenuDimension.height + this.initialButtonDimension.height) + "px"}, 
			{duration: "short"}
		);
		
		this.isOpen = !this.isOpen;
		this.buttonMore.toggleClass("up");
	}
});

var QuickNavMenu = Class({
	initialize: function() {
		this.menu = $("submenu");
		this.buttonHome = $("mobile_submenu_button_home");
		this.buttonMore = $("mobile_submenu_botton_more");
		
		if (!this.menu)
			return;
		
		if (!this.menu.children().length)
			this.buttonMore.setStyle({"display": "none"});
				
		this.initialDimension = this.menu.dimensions();
	
		this.menu.setStyle({"height": "0"});
		
		this.buttonMore.on({
			click: function(e) { this.onMenuClick(e); e.stop(); }.bind(this)
		});
		
		this.buttonHome.on({
			click: function(e) { history.go(-1) }.bind(this)
		});
		
		this.morph = new Fx.Morph(this.menu);
	},
	
	onMenuClick: function(e) {
		this.morph.cancel();
		this.morph.start(
			{height: (this.isOpen ? 0 : this.initialDimension.height) + "px"}, 
			{duration: "short"}
		);
		
		this.isOpen = !this.isOpen;
		this.buttonMore.toggleClass("up");
	}
});

