Prototype.Browser.IE6 = navigator.userAgent.indexOf('MSIE 6.') >= 0 && document.all;

var Carousel = Class.create({
	
	initialize: function(){
		
		document.observe('carousel:stop',this.stop.bind(this));
		document.observe('carousel:play',this.play.bind(this));
		
		if($('section-carousel')){
			this.selected = 0;
			this.player;
			this.speed = 0.5;
			var t = this;
			
			$$('div.section-carousel ul.pagina li').each(function(element){
				element.down().observe('click',t.set.bind(t));
			});
			
			this.play();
		}
	
	},
	
	show: function(number){
		
		var t = this;
		if(number > 4)
			number = 0
			
		$$('div.section-carousel ul.pagina li').each(function(element){
			element.removeClassName('selected');
		});
		$$('div.section-carousel ul.pagina li')[number].addClassName('selected');
		Effect.Fade($$('div.section-carousel ul.carousel li')[t.selected],{
			afterFinish: function(){
				Effect.Appear($$('div.section-carousel ul.carousel li')[number],{duration: t.speed});
				t.selected = number;
			},
			duration: t.speed
		});
	},
	
	play: function(){
		var t = this;
		t.player = new PeriodicalExecuter(function(pe){
			t.show((t.selected+1));
		}, 7);
	},
	
	stop: function(){
		this.player.stop();
	},
	
	set: function(event){
		event.preventDefault();
		var number = (Event.element(event).innerHTML - 1);		
		this.stop();
		this.show(number);
	}

})

var Caption = Class.create({

	initialize: function(){
		$$('.caption').each(function(element){
			if($(element).alt != ''){
				$(element).insert({after:'<p class="article-caption">'+$(element).alt+'</p>'});
			}
		});
	}
	
});

var Searchform = Class.create({

	initialize: function(){
		if($('q').value == ''){
			$('q').value = "Søk…";
			$('q').addClassName('deselected');
		}
		
		$('q').observe('focus',this.activate);
		$('q').observe('blur',this.deactivate);
	},
	
	activate: function(){
		if($('q').value == "Søk…")
			$('q').value = "";
		$('q').removeClassName('deselected');
	},
	
	deactivate: function(){
		if($('q').value == ""){
			$('q').value = "Søk…";
			$('q').addClassName('deselected');
		}
	}
	
});

var TagTuner = Class.create({

	initialize: function(){
		
		$('new-tag-form').observe('submit',this.search.bind(this));
		$('tag-submit').observe('click',this.search.bind(this));
		$('tag').observe('focus',this.activate);
		$('tag').observe('blur',this.deactivate);
		
		$('tag').value = "Søk på nøkkelord…";
		
		var t = this;
		$$('.close-tag').each(function(element){
			element.observe('click',t.remove.bind(t));
		})

		new Ajax.Autocompleter("tag", "tag-autocomplete", "/tags/", {
			minChars: 2,
			indicator: 'tag-indicator',
			select: 'tag-expanded'
		});
		
		
		if($('tags').getWidth() > 540){
			
			$('tags').setStyle({
				overflow:'hidden',
				width: '540px'
			});
			
			$('tags').down().setStyle({
				width: '1000px'
			});
			
		}
		
	},
	
	activate: function(){
		if($('tag').value == "Søk på nøkkelord…"){
			$('tag').value = "";
		}
		$('tag').removeClassName('deselected');
		document.fire('carousel:stop');
	},
	
	deactivate: function(){
		if($('tag').value == ""){
			$('tag').value = "Søk på nøkkelord…";
			$('tag').addClassName('deselected');
		}
		document.fire('carousel:play');
	},
		
	remove: function(e){
		Event.element(e).up().remove();
		this.search();
	},
	
	search: function(e){
		if(!(e == undefined))
			e.preventDefault();		
		
		var tags = Array();
		
		$$('.tag-name').each(function(element){
			tags.push(element.innerHTML);
		})
		
		if($('tag').value != 'Søk på nøkkelord…')
			tags.push($('tag').value);
		
		var url = 'http://rushprint.no/search?tag='+ Url.encode(tags.join(','));
		
		location = url;
	
	}
	
})

var Url = {

	decode: function(encodedString){
		return decodeURIComponent(encodedString);
	},
	
	encode: function(clearString){
		return encodeURIComponent(clearString).gsub(/%20/, '+');
	}

}

var Tooltip = Class.create({
	
	initialize: function(id){
		if($(id)){
			var t = this;
			$$('#'+id+' input').each(function(input){
				if($($(input).id + '-label') && $($(input).id + '-label').title != null){
					$(input).observe('focus',t.show);
					$(input).observe('blur',t.hide);
				}
			});
		};
		
	},
	
	show: function(event){
		var tooltip = '<div id="'+$(Event.element(event)).id+'-tooltip'+'" class="tooltip"><div class="pointer"></div>'+$(Event.element(event).id+'-label').title+'</div>';
		$(Event.element(event)).up().insert({top:tooltip});
		$($(Event.element(event)).id+'-tooltip').setStyle({top:($(Event.element(event)).positionedOffset().top - 40)+'px', left:($(Event.element(event)).positionedOffset().left)+'px'});
	},
	
	hide: function(event){
		$(Event.element(event).id+'-tooltip').remove();
	}
	
});

var Formvalidation = Class.create({
	initialize: function(id){	
		if($(id)){	
			this.id = id;
			var t = this;
			$$('#'+id+' input').each(function(input){
				if($(input).hasClassName('required') || $(input).hasClassName('validate-email') || $(input).hasClassName('validate-url')){
					$(input).observe('focus',t.onTextBoxFocus);
					$(input).observe('blur',t.onTextBoxBlur.bind(t));
				}
			});
			
			$$('#'+id+' textarea').each(function(textarea){
				if($(textarea).hasClassName('required')){
					$(textarea).observe('focus',t.onTextBoxFocus);
					$(textarea).observe('blur',t.onTextBoxBlur.bind(t));			
				}
			});
		}
	},
	
	isValidEmail: function(string){
		var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
		return regex.test(string);
	},
	
	isValidUrl: function(string){
		var regex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		return regex.test(string);
	},
	
	onTextBoxFocus: function(event){
		event.element().removeClassName('invalid');
	},	
	
	onTextBoxBlur: function(event){

		var isValid = true;
		var textBox = event.element();
		
		if(textBox.hasClassName('required') && textBox.value.length === 0)
			isValid = false;
			
		if(textBox.value.length > 0 && textBox.hasClassName('validate-email') && !(this.isValidEmail(textBox.value)))
			isValid = false;

		if(textBox.value.length > 0 && textBox.hasClassName('validate-url') && !(this.isValidUrl(textBox.value)))
			isValid = false;
		
		if(!isValid) textBox.addClassName('invalid');
		else textBox.removeClassName('invalid');		
		this.toggleFormSubmit();
		
	},
	
	toggleFormSubmit: function(){
		
		var isValid = true;
		$$('#'+this.id+' input').each(function(input){
			if($(input).hasClassName('invalid')) isValid = false;
			if($(input).hasClassName('required') && $(input).value.length === 0)
				isValid = false;
			
		});
		$$('#'+this.id+' textarea').each(function(textarea){
			if($(textarea).hasClassName('invalid')) isValid = false;
			if($(textarea).hasClassName('required') && $(textarea).value.length === 0)
				isValid = false;

		});
		if(isValid){
			 $('submit').removeClassName('disabled');
			 $('submit').addClassName('enabled');
		} else {
			if(!($('submit').hasClassName('disabled'))) $('submit').addClassName = 'disabled';
			$('submit').removeClassName('enabled');
		}
		
	}
	
});


var Newsletter = Class.create({
	
	initialize: function(){
		
		var t = this;
		
		if(! $('window-container')){
			new Ajax.Request('http://rushprint.no/nyhetsbrev-ajax',{
				onSuccess: function(transport) {
					$('rssfeed').insert({ after:transport.responseText });
					$('subscribe').observe('click',t.subscribe);
					$('unsubscribe').observe('click',t.unsubscribe);
					$('window-close').observe('click',t.close);
				},
				
				parameters: {
					action: 'show'
				}
			});
		}
		
	},
	
	subscribe: function(){
		new Ajax.Request('/nyhetsbrev-ajax',{
		    onSuccess: function(transport){
		    	var response = transport.responseJSON;
		    	if(response.status){
		    		$('window').update('<div id="success">'+response.message+'</div>');
		    	} else {
		    		$('window').update('<div id="failure">'+response.message+'</div>');
		    	}
		    },
		    
		    parameters: {
		    	email: $('email').value,
		    	action: 'subscribe'
		    }
		});	
	},
	
	unsubscribe: function(){
		new Ajax.Request('/nyhetsbrev-ajax',{
		    onSuccess: function(transport){
		    	var response = transport.responseJSON;
		    	//$('window').update(response.message);
		    	if(response.status){
		    		$('window').update('<div id="success">'+response.message+'</div>');
		    	} else {
		    		$('window').update('<div id="failure">'+response.message+'</div>');
		    	}
		    },
		    
		    parameters: {
		    	email: $('email').value,
		    	action: 'unsubscribe'
		    }
		});		
	},
	
	close: function(){
		
		$('window-container').remove();
	
	}
	
});

Event.observe(window, 'load', function(){
		new Carousel();
	
	new Searchform();
	new TagTuner();

	//new Caption();

	
	new Tooltip('comment-form');
	new Formvalidation('comment-form');
	
	// $('newsletter').observe('click',function(event){
	// 		if(!Prototype.Browser.IE6){
	// 			event.preventDefault();
	// 			new Newsletter();
	// 		}
	// 	})
	
	if(Prototype.Browser.IE6){
		$('crumbs').insert('<div id="ie-notification" class="grid-width">Du har en eldre versjon av nettleseren Internet Explorer. For å gjøre det lettere for oss å utvikle enda bedre tjenester for deg håper vi at du gratis vil hente en <a href="http://www.microsoft.com/windows/internet-explorer/?ocid=ie8_s_94735d11-65d1-4bb8-bf6f-72d7b059a928" target="_blank">nyere versjon av Internett Explorer</a>, eller et bedre alternativ som <a href="http://www.firefox.com/" target="_blank">Firefox</a>, <a href="http://www.opera.com/" target="_blank">Opera</a>, <a href="http://www.apple.com/safari" target="_blank">Safari</a> eller <a href="http://www.google.com/chrome">Google Chrome</a>.</div>');
	}
	
});
