/**
 * 
 */
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
Prototype.Browser.IE9 = false;

var FreeCodeWeb = Class.create({
	contactForm: null,
	effects: {enabled: true, speed: 1},
	ie_shit: null,
	
	initialize: function() {
		var hash = document.location.hash.split(';');
		if (hash[0] == '#course') {
			var course_id = hash[1];
			var course_link = $('course-item-' + course_id);
			if (!course_link)
				return;
			this.scrollTo(course_link, -50);
			setTimeout(function(){
				course_overview(course_link);
			},700);
		}
		
		/* But ugly */
		if (Prototype.Browser.IE6 || Prototype.Browser.IE7) {
			//alert("Please install a decent browser you moron\n\nDebug: " + navigator.userAgent);
			this.ie_shit = true;
			this.effects.enabled = false;
			
		/* Works, kindof */
		} else if (Prototype.Browser.IE8) {
			this.ie_shit = true;
			this.effects.enabled = false;
		}
		
		
		new PeriodicalExecuter(function(pe){
			var ul = $$('#widget_twitter_vjck ul').first();
			var post_size = 70;
			var posts = ul.select('li').size();
			var maxMargin = -(post_size * posts);
			
			var margin = -(parseInt( ul.getStyle('marginTop').match(/(\d+)/ig)[0] ));
			var setMargin = (margin - post_size);
			
			//console.log("Current: " + margin + ", set: " + setMargin + ", max: " + maxMargin);
			
			if ( setMargin <= maxMargin ) {
				new Effect.Tween(null, margin, setMargin, {duration: 0.3}, function(p){
					ul.setStyle({marginTop: p + 'px'});
				});
				setMargin = 0;
				ul.setStyle({marginTop: '70px'});
				margin = 70;
			}
			new Effect.Tween(null, margin, setMargin, {duration: 0.3}, function(p){
				ul.setStyle({marginTop: p + 'px'});
			});
			
		},5);
		
	},
	
	historyChange: function(newLocation,historyData) {
		var newLocation = newLocation.split(';');
		switch(newLocation[0]) {
		case 'contactus':
			var form = $('form_contact_footer');
			this.scrollTo($('footer'));
			var context = this;
			setTimeout(function(){
				context.flashContactForm(form);
			},600);
			break;
		}
	},

	flashContactForm: function(form) {
		var container = $('contact_container');
		var opacity;
		/*
		 * TODO: Fallback for IE (fargen blir hengende)
		 */
		
		setTimeout(function(){
			$('contact_container').setStyle({backgroundColor: 'transparent'});
		},1200);
		
		new Effect.Tween(null, 0.1, 90, {duration:0.2}, function(p){
			opacity = roundNumber( (p/100), 2);
			setBackgroundAlpha($('contact_container'), 40,68,119,opacity);
		});
		// Fade out
		setTimeout(function(){
			var opacity;
			new Effect.Tween(null, 90, 0.1, {duration:0.6}, function(p) {
				opacity = roundNumber( (p/100), 2);
				setBackgroundAlpha($('contact_container'), 40,68,119,opacity);
			});
		},500);
		
	},
	sendContactForm: function(form, callback) {
		new Ajax.Request('/message.php',{
			method: 'post',
			parameters: form.serialize(true),
			onSuccess: function(t) {
				var response = t.responseJSON;
				if (callback) {
					callback(response);
				} else {
					var myPopup = new popup({position: 'center'});
					if (response.ok) {
						myPopup.setContent('<div class="message"><h2>' + _('Thank you for your request!') + '</h2><p>' + _('Your message is sent and we will get back to you within 24 hours. A copy is sent to you by e-mail.') + '</p></div>');
					}
					myPopup.show();
				}
			}
		});
	},
	scrollTo: function(el, offset) {
		if (offset == undefined)
			offset = 0;
		var scrollOffset = document.viewport.getScrollOffsets();
		var elementPos = el.positionedOffset();
		new Effect.Tween(null, Math.floor(scrollOffset.top), Math.floor(elementPos.top + offset), {duration:0.5}, function(p){
			scrollTo(0,p);
		})
	}
});

var popup_contactform = Class.create(popup,{
	
	form: null,
	
	initialize: function($super) {
		var opt = Object.extend({heading: _('Send us a message, and we\'ll contact you!')}, arguments[1] || { });
		$super(opt);
		//$super(arguments[1]);
		
		var form = new Element('form', {method:'post', className: 'magicform', action:'javascript:;'}).setStyle({cssFloat: 'left'});
		var h2 = new Element('h2').update( this.options.heading );
		var input_name = new Element('input', {type: 'text', name: 'contactform[name]', value: _('Your name'), className: 'placeholder'}).setStyle({cssFloat: 'left'});
		var input_email = new Element('input', {type: 'text', name: 'contactform[email]', value: _('Your e-mail address'), className: 'placeholder'}).setStyle({cssFloat: 'right'});
		var input_body  = new Element('textarea', {name: 'contactform[message]', cols: '40', rows: '4', className: 'placeholder'}).setStyle({margin: '8px 0 3px 0',cssFloat: 'left', clear: 'both'}).setValue(_('Your message'));
		
		var input_uid = new Element('input', {type: 'hidden', name: 'contactform[consultant_id]', value: ''});
		var input_src = new Element('input', {type: 'hidden', name: 'contactform[form_context]', value: ''});
		
		var input_submit = new Element('input', {type: 'submit', value: _('Send'), className: 'smallbtn'}).setStyle({float: 'right'});
		
		var div = new Element('div');
		div.insert(h2);
		div.insert(input_name);
		div.insert(input_email);
		div.insert(input_body);
		
		div.insert(input_uid);
		div.insert(input_src);
		
		var div2 = new Element('div');
		var loader = new Element('div',{className: 'ajaxloader'}).setStyle({float: 'left', width: '16px',height: '16px', display: 'none'});
		var img = new Element('img', {alt: '', src: stylesheet_directory + '/gfx/ajax-loader-red.gif'});
		loader.insert(img);
		div2.insert(loader);
		var error = new Element('span', {className: 'error'}).setStyle({fontSize: '11px', color: '#C3272F'});
		
		div2.insert(error);
		div2.insert(input_submit);
		
		div.insert(div2);
		form.insert(div);
		
		form.observe('submit', this._onSubmit.bind(this));
		
		if (this.options.consultant_id != undefined) {
			input_uid.setValue(this.options.consultant_id);
		}
		var context = this._findContactContext();
		if (context) {
			var meta_heading = context.select('.meta_heading');
			var meta_body = context.select('.meta_body');
			if (!meta_heading.size() || !meta_body.size()) {
				input_body.setValue(context.innerHTML + "\n");
				//input_body.writeAttribute('placeholder', context.innerHTML + "\n");
				input_body.addClassName('placeholder-sticky');
			} else {
				h2.update(meta_heading.first().innerHTML);
				input_body.setValue(meta_body.first().innerHTML + "\n");
				//input_body.writeAttribute('placeholder', meta_body.first().innerHTML + "\n");
				input_body.addClassName('placeholder-sticky');
			}
		}
		input_src.setValue( (wp_breadcrumb || "") );
		
		this.form = form;
		this.setContent(form);
		//initPlaceholders();
		
	},
	
	_onSubmit: function() {
		var context = this;
		this._showLoader();
		this.container.select('span.error').first().update("");
		
		this.form.fire('form:beforesubmit');
		fcweb.sendContactForm(this.form, function(response){
			context._hideLoader();
			if (response.ok) {
				context.setContent('<div class="message"><h2>' + _('Thank you for your request!') + '</h2><p>' + _('Your message is sent and we will get back to you within 24 hours. A copy is sent to you by e-mail.') + '</p></div>');
				setTimeout(function(){
					if (context)
						context.close();
				},5000);
			} else {
				context.form.fire('form:aftersubmit');
				context._setFormError(response.message);
			}
		});
	},
	_showLoader: function() {
		this.container.select('.ajaxloader').first().show();
	},
	_hideLoader: function() {
		this.container.select('.ajaxloader').first().hide();
	},
	_setFormError: function(error) {
		this.container.select('span.error').first().update(error);
	},
	_findContactContext: function() {
		var check = this.options.hook.up('.meta_popup_context');
		if (check != undefined) {
			return check;
		}
		check = this.options.hook.down('.meta_popup_context');
		if (check != undefined) {
			return check;
		}
		check = this.options.hook.next('.meta_popup_context');
		if (check != undefined) {
			return check;
		}
		check = this.options.hook.previous('.meta_popup_context');
		if (check != undefined) {
			return check;
		}
		return false;
	}
});


var popup_callme = Class.create(popup,{
	form: null,
	
	initialize: function($super) {
		var opt = Object.extend({classNames: 'callme'}, arguments[1] || { });
		$super(opt);
		
		var form = new Element('form', {method:'post', className: '', action:'javascript:;'});
		var input = new Element('input', {type: 'text', className: 'phone placeholder', name: 'contactform[phone]', value: _('Your phone number')});
		var input_src = new Element('input', {type: 'hidden', name: 'contactform[form_context]', value: ''});
		var submit = new Element('input', {type: 'submit', className: 'submit', name: 'contactform[submit]', value: ''});
		
		form.insert(input);
		form.insert(submit);
		form.insert(input_src);
		
		form.observe('submit', this._onSubmit.bind(this));
		input_src.setValue( (wp_breadcrumb || "") );
		this.setContent(form);
		this.form = form;
		
		//initPlaceholders();
	},
	
	afterShow: function() {
		//input.focus();
	},
	_onSubmit: function() {
		var context = this;
		this.close();
		
		fcweb.sendContactForm(this.form, function(response){
			var responsePopup = new popup({position: 'center'});
			if (response.ok) {
				responsePopup.setContent('<div class="message"><h2>' + _('Thank you for your request!') + '</h2><p>' + _('We will call you as soon as possible.') + '</p></div>');
			} else {
				responsePopup.setContent('<div class="message"><h2>' + _('Error') + '!</h2><p>' + response.message + '</p></div>');
			}
			responsePopup.show();
		});
	}
});


var popup_calendar = Class.create(popup,{
	iframe: null,
	loader: null,
	calendars: null,
	
	initialize: function($super) {
		var opt = Object.extend({classNames: 'calendar'}, arguments[1] || { });
		$super(opt);
		
		this.calendars = $H({
			cal_1: {id: '18kqu3ni4k1rkhret639g5l4m4', title: 'ITIL og Service Management',  color: '060D5E'},
			cal_2: {id: '0babjtu8sdem681g2kem05s2rg', title: 'PRINCE2 og Prosjektledelse',  color: '711616'},
			cal_3: {id: '1ap0j8t38juui70rsmgip2q0og', title: 'Mellomvare fra ForgeRock',    color: '5C2BC9'},
			cal_4: {id: 't0akieihhjr5mf16b4pipgej9g', title: 'Linux for Brukere',           color: '129ECF'},
			cal_5: {id: 'fveo80ilm799brbqfgkuu75lpg', title: 'Linux systemadministrasjon',  color: 'B7CC12'},
			cal_6: {id: 'eho9sulcqs3905fi30beg6qi30', title: 'Wiki-kurs',                   color: 'CA730C'}
		});
		
		var container = new Element('div');
		
		var leftcol = new Element('div', {className: 'leftcol'});
		
		var filter = new Element('div', {className: 'filter'});
		var a;
		var init_link;
		
		a = new Element('a', {href: 'javascript:;', cal_id: '1', className: 'radio blue uppercase'}).update('<span></span>ITIL og Service Management');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		init_link = a;
		
		a = new Element('a', {href: 'javascript:;', cal_id: '2', className: 'radio red uppercase'}).update('<span></span>PRINCE2 og Prosjektledelse');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		a = new Element('a', {href: 'javascript:;', cal_id: '3', className: 'radio purple uppercase'}).update('<span></span>Mellomvare-kurs fra forgerock');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		a = new Element('a', {href: 'javascript:;', cal_id: '4', className: 'radio lime uppercase'}).update('<span></span>Linux brukerkurs');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		a = new Element('a', {href: 'javascript:;', cal_id: '5', className: 'radio cyan uppercase'}).update('<span></span>Linux system-administrasjon');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		a = new Element('a', {href: 'javascript:;', cal_id: '6', className: 'radio orange uppercase'}).update('<span></span>Wikikurs');
		a.observe('click', this.changeCalendar.bind(this));
		filter.insert(a);
		
		leftcol.insert(filter);
		
		var rightcol = new Element('div', {className: 'rightcol'});
		
		var loader = new Element('div', {className: 'calendar_loader'}).setStyle({display: 'none'}).update('<img src="' + stylesheet_directory + '/gfx/ajax-loader-blue-2.gif" alt="">');
		rightcol.insert(loader);
		
		var iframe = new Element('iframe', {src: '', className: 'iframe', frameborder: '0', scrolling:'no'});
		rightcol.insert(iframe);
		
		container.insert(leftcol);
		container.insert(rightcol);
		
		this.iframe = iframe;
		this.loader = loader;
		
		this.setContent(container);
		
		this.changeCalendar(init_link);
		
	},
	
	changeCalendar: function(event) {
		if (event.tagName != undefined)
			var link = event;
		else
			var link = event.element();
		var cal_id = link.readAttribute('cal_id');
		
		var cal = this.calendars.get('cal_'+cal_id);
		//var iframe = $('calendar_iframe');
		$(link).siblings().invoke('removeClassName', 'checked');
		$(link).addClassName('checked');
		
		this.loader.show();
		var context = this;
		this.iframe.observe('load', function(){
			context.loader.hide();
		});
		/*
		this.iframe.onload = function(){
			context.loader.hide();
		};
		*/
		this.iframe.src = 'https://www.google.com/calendar/hosted/freecode.no/embed?' + 
		'showTitle=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&height=450&wkst=2&hl=no' + 
		'&bgcolor=%23FFFFFF' + 
		'&color=%23' + cal.color +
		'&src=freecode.no_' + cal.id + '%40group.calendar.google.com&ctz=Europe%2FOslo';
		
	}
});


var people_list1_bghover = [];
var people_list1_bgorig  = [];
var people_list2_bghover = [];
var people_list2_bgorig  = [];

var people_lists = function() {
	
	var url_match = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	
	/* Small contact boxes */
	$$('ul.people-row').each(function(ul){
		
		/* Required for centering the ul, i think */
		ul.up().setStyle({width: (ul.getWidth()+1) + 'px'});
		
		var people_lis = $$('ul.people-row > li');
		var people_total = (people_lis.size() - 1);
		$$('ul.people-row > li').each(function(li, key) {
			if (key >= people_total)
				throw $break;
			if (key >= 4) {
				//li.hide();
			}
			var bgimg = li.getStyle('backgroundImage');
			var bgsrc;
			if (bgimg.match(url_match)) {
				bgsrc = RegExp.$1;
				/* Preload */
				people_list1_bghover[key] = new Image();
				people_list1_bghover[key].src = bgsrc.replace(/grayscale\//, "");
				
				/* Nødvendig for at IE/Webkit skal hente cache på mouseleave */
				people_list1_bgorig[key] = new Image();
				people_list1_bgorig[key].src = bgsrc;
			}
			li.observe('mouseenter', function(e){
				this.setStyle({'backgroundImage': "url('" + people_list1_bghover[key].src + "')"});
			});
			li.observe('mouseleave', function(e){
				this.setStyle({'backgroundImage': "url('" + people_list1_bgorig[key].src + "')"});
			});
		});
		ul.select('li.you a').first().observe('mouseenter', function(e) { e.element().up().addClassName('hover')});
		ul.select('li.you a').first().observe('mouseleave', function(e) { e.element().up().removeClassName('hover')});
	});
	
	/* Large contact boxes */
	$$('div.contactboxes').each(function(container){
		
		var boxes_loaded = 0;
		var boxes_total = container.select('.contactbox').size();
		
		container.select('.contactbox').each(function(box, key){ 
			var bgimg = box.getStyle('backgroundImage');
			var bgsrc;
			
			/* Preloading */
			if (bgimg.match(url_match)) {
				bgsrc = RegExp.$1;
				
				people_list2_bghover[key] = new Image();
				people_list2_bghover[key].src = bgsrc.replace(/grayscale\//, "");
				
				people_list2_bgorig[key] = new Image();
				people_list2_bgorig[key].observe('load', function(e){
					boxes_loaded++;
					if (boxes_loaded >= boxes_total) {
						container.select('.contactboxes-loader').first().hide();
						container.select('.contactboxes-wrap').first().show();
					} else {
						container.select('.contactboxes-loader .progress').first().update( boxes_loaded + ' av ' + boxes_total);
					}
				});
				people_list2_bgorig[key].src = bgsrc;
			}
			/* Init */
			if (box.hasClassName('you')) {
					box.select('a').first().observe('click',function(e){
						this.up().addClassName('click');
					});
					box.select('a').first().observe('mouseup',function(e){
						this.up().removeClassName('click');
					});
					box.select('a').first().observe('mouseenter',function(e){
						this.up().addClassName('hover');
					});
					box.select('a').first().observe('mouseleave',function(e){
						this.up().removeClassName('hover');
					});
			} else {
				box.observe('mouseenter', function(e){
					var hover = this.select('.hover').first();
					new Effect.Tween(null, 191, 0, {duration:0.3}, function(p){
						hover.setStyle({marginTop: p + 'px'});
					});
					this.setStyle({'backgroundImage': "url('" + people_list2_bghover[key].src + "')"});
				});
				box.observe('mouseleave', function(e){
					var hover = this.select('.hover').first();
					new Effect.Tween(null, 0, 191, {duration:0.3}, function(p){
						hover.setStyle({marginTop: p + 'px'});
					});
					this.setStyle({'backgroundImage': "url('" + people_list2_bgorig[key].src + "')"});
				});
				/* Remove empty links */
				box.select('ul.info a').each(function(link){
					(link.readAttribute('href') == "") ? link.up().hide() : null;
				});
			}
		});
	});
}




/* Helper functions */

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
function setBackgroundAlpha(el,r,g,b,a) {
	$(el).setStyle({
		backgroundColor: 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'
	});
	
	var alphaDec = Math.floor(255*a);
	var hex = "" + alphaDec.toString(16) + r.toString(16) + g.toString(16) + b.toString(16);
	if (Prototype.Browser.IE8)
		$(el).setStyle({
			'filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#' + hex + ', endColorstr=#' + hex + ');'
		});
	if (Prototype.Browser.IE6 || Prototype.Browser.IE7)
		$(el).setStyle({
			'-ms-filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#' + hex + ', endColorstr=#' + hex + ')'
		});
}
