/*
 * Epicenter is designed, developed and scripted by Agile Technologies
 *
 * Learn more about us at http://www.agiletech.ie
 *
 */
$(document).ready(function(){
		

	$('#home_zones_list ul li:last a').css("margin-bottom","0px");
	var selabout;
	$('#home_logo, #aboutbox h1').click(function(e) { e.preventDefault(); $('#aboutbox h1').parents('#aboutbox').addClass('aboutbox_on'); });
	$('.sponsors_grid a:nth-child(3n)').css("marginRight","0");

	$('#aboutbox #aboutbox_close').click(function() { $(this).parents('#aboutbox').removeClass('aboutbox_on'); });

	if (jQuery.browser.msie) { // PNG support for IE6
	  if(parseInt(jQuery.browser.version) == 6) {
	      $('#home_logo img, #home_slogan, #home_date, #home_rotation li img,.zonelist_sel div,.home_screen_bg, #logo a img, #nav .current, #nav .ui-state-active, #topnav span i,#sponsor_box').ifixpng();
	  }	
	}


	// Sponsor carousel
	
	logo_down=function(n){
		if(n<2){
			//$('#sponsors_wrap').children('div').css({top:-58});
		}
		if(n>0){
			$('#sponsors_wrap').children('div').each(function(){ $(this).animate({'top': -(58*(n-1))},300+Math.floor(Math.random()*500));});
		}

		if(n>2)n=0;
	
	
	
		lt=setTimeout('logo_down('+(n+1)+')',7000);
	};
	
	
	logo_down(0);


window.scrolled=false;

jQuery.extend( jQuery.easing,
{	
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	}

});

String.prototype.cut_object=function(obj){
	var l=this,pos;
	if((pos=l.indexOf('#'))>0){
		l=l.substr(0,pos);
	}

	return l+'&cut_object='+obj;
}

String.prototype.money=function(){
	// Converts number into Money (excludes support for thousands..)
	var num=this;
	num=Math.floor(num*100+0.500000001);
	var cents=num%100;
	num=Math.floor(num/100);
	if(cents<10)cents+='0';
	return '&euro;'+num+'.'+cents;
}


///////////////////////// TWITTER ///////////////////////

function add_links(t){
	t=t.replace(/</g,'');
	t=t.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) { 
			return '<a href="'+m+'" target=_blank>'+m+'</a>'; });

	t=t.replace(/@[A-Za-z0-9_-]+/g, function(m) { 
			return '<a href="http://twitter.com/'+m.substr(1)+'" target=_blank>'+m+'</a>'; });
	return t;
}

function relative_time(time_value){
	// credits to RedWoves for this function
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	var r = '';
	if (delta < 60) {
		r = 'a minute ago';
	} else if(delta < 120) {
		r = 'couple of minutes ago';
	} else if(delta < (45*60)) {
		r = (Math.round(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (90*60)) {
		r = 'an hour ago';
	} else if(delta < (24*60*60)) {
		r = '' + (Math.round(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		r = '1 day ago';
	} else {
		r = (Math.round(delta / 86400)).toString() + ' days ago';
	}

	return r;

}


$.extend({
	toJSON: function (value, whitelist) {
		var m = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\\"',
			'\\': '\\\\'
		};

        var a,          // The array holding the partial texts.
            i,          // The loop counter.
            k,          // The member key.
            l,          // Length.
            r = /["\\\x00-\x1f\x7f-\x9f]/g,
            v;          // The member value.
        switch (typeof value) {
        case 'string':
            return r.test(value) ?
                '"' + value.replace(r, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"' :
                '"' + value + '"';
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            if (typeof value.toJSON === 'function') {
                return $.toJSON(value.toJSON());
            }
            a = [];
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length'))) {
                l = value.length;
                for (i = 0; i < l; i += 1) {
                    a.push($.toJSON(value[i], whitelist) || 'null');
                }
                return '[' + a.join(',') + ']';
            }
            if (whitelist) {
                l = whitelist.length;
                for (i = 0; i < l; i += 1) {
                    k = whitelist[i];
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            }
            return '{' + a.join(',') + '}';
        }
    }
});



var updateTwitter_timeout;
var entry,tw,tname,url,progres_original;
function updateTwitter(first_run){
	if(!$('#twitter_progress').length)return;

	if(first_run==true){
		tw=$('.twitter');
		entry=tw.children('.entry').eq(0).remove();
		tname=tw.attr('rel');
	   	url="http://twitter.com/status/user_timeline/"+tname+".json?count=3&callback=?";
	   	progres_original=$('#twitter_progress').attr('src');
	}

	$('#twitter_progress').attr('src',$('#twitter_progress').attr('rel')).show();
	$.getJSON(url,function(data){
		$('#twitter_progress').fadeOut();
		$.each(data.reverse(),function(i,item){
			if(tw.children('[rel='+item.id+']').length){
				// already showing this tweet, continue to next one
				return;
			}
			entry.attr('rel',item.id);
			entry.children('.entry_text').html(add_links(item.text));
			entry.children('.entry_date').html(relative_time(item.created_at));
			entry.hide();
			entry.clone().prependTo(tw).slideDown();
		});
	});

	if(first_run){
		$('#twitter_progress').click(updateTwitter);
	}

	clearTimeout(updateTwitter_timeout);
	updateTwitter_timeout=setTimeout(updateTwitter,1000*60);
}

function fixLinkHere(){
	// Finds link to this page and makes it nice.
	var link=$('.link_here');
	if(link.find('a').length)return;	// don't do it twice

	var link_url=link.text();
	link.html("<a href='javascript:void(0)'>Link to this page</a>");
	link.find('a').click(function(ev){
		ev.preventDefault();
		prompt('Copy link to this page:',link_url);
	});
}


/////////////////////// home rotation /////////////////

window.times=3;
$('#home_logo').
	mouseout(function(){
		if(window.times--){
			$(this).parent().parent().effect('shake',{ times: 3,direction:'up',distance:3}, 20,function(){$(this).attr('style','')});
		}else{
			var e=$('#home_rotation_links1').add('#home_rotation_links2').find('img');
			e.eq(Math.floor(Math.random()*e.length)).animate({marginTop: "500"},500,'easeInQuad',function(){ 
				$(this).css({marginTop:0}).hide();
			});
			$(this).parent().parent().effect('shake',{ times: 6,direction:'up',distance:7}, 30,function(){$(this).attr('style','')});
			window.times=6;
		}
	});



////////////////////////// SPEAKERS ////////////////////////
function initSpeakers(speakers){
	// Work with speakers
	//$('.speaker_grid .speaker:nth-child(3n)').css('marginRight','4px');
	speakers.find('.descr').hide();
	$('.speaker_paginator_left').click();
	speakers.find('div.speaker').each(function(){
		var t=$(this);
		var hr=t.find('a').attr('href');
		t.find('a').each(function(){ $(this).replaceWith($(this).text()) })

		t.click(function(){

			var t=$(this);

			speakers.find('.selected').removeClass('selected');
			t.addClass('selected');

			$('.speaker_about').load(hr.cut_object('speaker'),null,function(){ fixLinkHere(); updateTwitter(true);});

			if(!window.scrolled){
				window.scrolled=true;
				$.scrollTo( $('#sponsor_box'), 800 );
			}

		});
	});

	// select first speaker if no speakers are selected yet
	window.scrolled=true;
	if(!speakers.find('div.selected').length)speakers.find('div.speaker:first').click();
	else { fixLinkHere(); updateTwitter(true); };
	window.scrolled=false;
}

function initAgenda(agenda){
	agenda.find('tbody').find('td').each(function(){
		var t=$(this);

		var a=t.find('a');
	   	if(!a.length)return;

		var hr=a.attr('href');
		//a.each(function(){ $(this).replaceWith($(this).text()) });

		t.click(function(e){
			e.preventDefault();

			var t=$(this);

			agenda.find('.selected').removeClass('selected');
			t.addClass('selected');

			$('.speaker_about').load(hr.cut_object('session'),function(){ fixLinkHere();});

			if(!window.scrolled){
				window.scrolled=true;
				$.scrollTo( $('.speaker_about'), 800 );
			}

		});
	});


	window.scrolled=false;
	var prev=null;
	agenda.find('div.day').each(function(){
		var t=$(this);
		if(!prev){
			t.find('.agenda_prev_day').hide();
		}
		if(t.is(':last-child')){
			t.find('.agenda_next_day').hide();
		}

		if(prev){
			t.hide();

			prev.find('.agenda_next_day').click(function(e){
				e.preventDefault();
				$(this).closest('.day').hide().next().show();
			});

			t.find('.agenda_prev_day').click(function(e){
				e.preventDefault();
				$(this).closest('.day').hide().prev().show();
			});
		}


		prev=t;
	});


}


	function speakerPaginator(n){
	}


	$('.speaker_paginator_right').click(function(){
		$('.speaker_holder').animate({"left": "-681"},1000);
		$('#speaker_paginator_text').text('2 of 2');
		$('.speaker_paginator_right').animate({'opacity':'0.2'}).css({'cursor':'default'});
		$('.speaker_paginator_left').css({'opacity':'1','cursor':'pointer'});
	});
	$('.speaker_paginator_left').click(function(){
		$('.speaker_holder').animate({"left": "0"},1000);
		$('#speaker_paginator_text').text('1 of 2');
		$('.speaker_paginator_left').animate({'opacity':'0.2'}).css({'cursor':'default'});
		$('.speaker_paginator_right').css({'opacity':'1','cursor':'pointer'});
	});

	$('.speaker_paginator_left').css({'opacity':'0.2'});

	initSpeakers($('.speaker_grid'));


////////////////////////// ZONES ////////////////////////

	var zones=$('#home_zones_list').children('ul');

	zones.find('.descr').hide();

	//if(!zones.children('.zonelist_sel').length)zones.children(':first').addClass('zonelist_sel');
	zones.children().click(function(e){
		e.preventDefault();
            
        var t=$(this);
		var descr=t.find('div.descr').html();
		
		if(!window.scrolled){
			window.scrolled=true;
			$.scrollTo( $('#sponsor_box'), 800 );
		}
		$('#home_screen_text').html(descr);
		$('#home_screen').find('img').attr('src','images/logo_'+t.attr('rel')+'.gif');
		zones.children('.zonelist_sel').removeClass('zonelist_sel');
		t.addClass('zonelist_sel');

		var l=t.children('a').attr('href');
		l=l.substr(0,l.indexOf('#')); //+'&cut_object=speakers';

		// see which tab is active
		if($('.zone_navigation').children('.selected').hasClass('speakers_tab')){
			// loading speakers
			l=l.replace(/&mode=[a-z]*/,'&mode=speakers&cut_object=speakers')
			$('.speaker_grid').show();
			$('.speaker_holder').load(l,function(){
				var speaker_cnt=$('.speaker_holder').children().length;
				//$('.speakers_tab').html('<b>Speakers</b>');
				initSpeakers($('.speaker_grid'));
			});
		}else{
			// loading agenda
			l=l.replace(/&mode=[a-z]*/,'&mode=agenda&cut_object=agenda')
			$('.agenda').load(l,function(){
				//var speaker_cnt=$('.speaker_holder').children().length;
				//$('.speakers_tab').text('Speakers ('+speaker_cnt+')');
				initAgenda($('.agenda'));
				
			});
		}

		
	});

/////////////////////////// TABS ///////////////////////

	fixLinkHere();
	var tabs=$('.zone_navigation');
	tabs.children().click(function(e){
		var t=$(this);
		tabs.children('.selected').removeClass('selected');
		t.addClass('selected');
		
		$('.speaker_about').empty();
		if(t.is('.speakers_tab')){
			$('.agenda').empty();
			$('.speaker_grid').show();
			$('.speaker_grid').find('.selected').removeClass('selected');
			if(!$('.speaker_holder').children().length){
				$('#home_zones_list').find('.zonelist_sel a').click();
			}
		}else{
			$('.agenda').show();
			$('.speaker_holder').empty();
			$('.speaker_grid').hide().find('.selected').removeClass('selected');
			if(!$('.agenda').children().length){
				$('#home_zones_list').find('.zonelist_sel a').click();
			}
		}
	}).find('a').each(function(){ $(this).replaceWith($(this).text()) })
//	$('.agenda').hide();



/*
	if(tw.length){
		updateTwitter();


	}

	*/


////////////////////////////////////// TICKET FORM ////////////////////////////////////
if($('#form_ticket').length){
	var ft=$('#form_ticket');
	ft.show();
	ft.next().hide();

	function money_recalc(t){
		var total=0;
		ft.find('input:checked').each(function(){ total+=parseFloat($(this).attr('rel')); });

		// lets see if any discounts apply. If you tamper with this code and order yourself a cheaper ticket, your money will
		// be refunded and your ticket will not be valid

		var days=ft.find('input:checked').filter('[rel=129]').length;
		var discount=0;

        if(days>3){
			discount=277;
        }else if(days>2){
			discount=158;
		}else if(days>1){
			discount=69;
		}

		if(t.attr('rel')==129){
			// recalculate only if day is clicked
			ft.find('.discount').stop().css({'background-color':null}).hide();
            if(days>3){
				ft.find('#discount_4d').effect('highlight',null,2000);
            }else if(days>2){
				ft.find('#discount_3d').effect('highlight',null,2000);
			}else if(days>1){
				ft.find('#discount_2d').effect('highlight',null,2000);
			}

			// Complimentary night
			if(days>1){
				ft.find('#gift_select').effect('highlight',null,2000);
				$('#evangelist_night').removeAttr('disabled');
			}else{
				ft.find('#gift_select').stop().css({'background-color':null}).hide();
				$('#evangelist_night').attr('disabled',true);
			}
		}

		$('#total_per_person').html((total-discount).toString().money());
		$('#total_per_person').attr('rel',(total-discount));
	}

	ft.find(':checkbox').each(function(){
		var t=$(this);
		t.click(function(){
			var i=t.parent().children('.item');
			var pr=t.attr('rel');
			if(this.checked){
				i.html(pr.money());
			}else{
				i.html('-');
			}

			money_recalc(t);
		});

	});

	var purchase_attendee=$('#purchase_attendees').children(':first').remove();
	$('#purchase_attendees').empty();

	function formParams(jq){
		var params={};
		jq.find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea")
		.filter(":enabled")
		.each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = $(this).val();
		});
		params['ajax_submit']=1;
		return params;
	}

	// adding
	var attendees=[];
	$('#add_attendee').click(function(){
		// First - verify few things
		var data=formParams($('#form_ticket_left'));
		if(!data.attendee_name)return $('#attendee_name').focus() & alert('Please specify name of a person who will attend the conference');

        if(data.day1 && data.day2 && !data.evangelist_night){
			if(!confirm("Proceed without choosing complimentary Evangelist Night?"))return;
		}

		if(!(data.day1 || data.day2 || data.day3 || data.day4))return alert("Please choose which days you are going to attend");

		ft.find("#attendee_name").val('');
		$('#evangelist_night').val('');

		$('#form_ticket_right').children().not('.filler').fadeIn();
		$('#form_ticket_right').children('.filler').hide();

		var new_attendee=purchase_attendee.clone().appendTo($('#purchase_attendees'));

		data.price=$('#total_per_person').attr('rel');

		new_attendee.find('i').text(data['attendee_name']);
		new_attendee.find('span').html($('#total_per_person').html());
		new_attendee.find('span').attr('rel',($('#total_per_person').attr('rel')));
		var i;
		new_attendee.find('input').attr('value',$.toJSON(data));

		attendees.push(data);
		var total_price=0;
		$.each(attendees,function(){
			total_price+=parseFloat(this.price);
		});

		$('#total_total').html(total_price.toString().money());
		$('#total_total').attr('rel',total_price);
	});


	$('#company_trigger').find('a').click(function(e){
		e.preventDefault();
		$('#company_trigger').hide().next().fadeIn().find('input').focus();
	});


	$('#checkout').click(function(){
		var data={};
		if($('#attendee_name').val()){
			$('#add_attendee').click();
		}
		data.attendees=attendees;
		data.company=$('#company_name').val();
		data.phone=$('#phone').val();
		$.ajax({
			type: "POST",
			url: 'tickets-2010.html?purchase=1',
			data: {data: $.toJSON(data)},
			success: function(res){
				if(res.substr(0,1)!='#'){
					alert('There seems to be a problem. Please call us on +353 1 443 4131 or email epicenter@irishdev.com regarding your purchase');
					return;
				}
				var f=$('#paypal_form');
				f[0].item_name.value='Epicenter ticket, REF='+res;
				f[0].amount.value=$('#total_total').attr('rel');
				f[0].submit()
			}
		});
	});

}




	
});

		if(!window.console){
            window.console={
                log: function(){
                // console / firebug is not present. Ignore all debug messages
                }
            }
        }
