if ( typeof window.dumplog != 'function' ) {
	function dumplog(variable){
		if (window.console !== undefined) {
			console.log(variable);
		}
	}
}

function isMobile() {
	if(
		navigator.userAgent.match(/Android/i) ||
		navigator.userAgent.match(/webOS/i) ||
		navigator.userAgent.match(/iPhone/i) ||
		navigator.userAgent.match(/iPad/i) ||
		navigator.userAgent.match(/iPod/i)
	) {
		return true;
	}
	return false;
}

function textareaResize(taEl) {
	var taObj	= jQuery(taEl);
	var lineHeight = parseInt( taObj.css('lineHeight') );

	if ( taEl.scrollHeight > taObj.height() ) {
		taObj.css('height', taEl.scrollHeight+'px');
	} else {
		var counter = 20;
		do {
			taObj.css('height', (taObj.height()-lineHeight)+'px');
			counter--;
		} while ( taEl.scrollHeight == taObj.height() && taObj.height() > 0 && counter > 0 );
		taObj.css('height', (taObj.height()+lineHeight)+'px');
	}
	
	if ( taObj.height() <= taObj.attr('rows')*lineHeight) {
		taObj.css('height', (taObj.attr('rows')*lineHeight)+'px');
	} else {
		taObj.css('height', (taObj.height()+lineHeight)+'px');
	}
}

function plusone(params) {
}
	
$(document).ready(function() {
	initContainer();
});

function initContainer(selector) {
	if ( selector == null ) {
		selector = 'body';
	}

	var container = jQuery(selector);
	
	
	if ( isMobile() != true ) {
		container.find(".gallery a").fancybox({
			'titlePosition'		: 'over',
			'showCloseButton'	: true,
			'onStart'			: function(args){ stopAllVideos(null);}
		});
	}

	if ( isMobile() != true ) {
		if ( window.location.search.indexOf('popup') >= 0 ) {
			window.location = (window.location+'').replace('popup', 'p');
		} else {
			container.find("a.popup").each(function(){
				var linkEl = jQuery(this);
				var href = linkEl.attr('href');
		
				if ( window.location.href.indexOf(linkEl.attr('href')) >= 0 ) {
					linkEl.removeClass('popup');
					return;
				}
		
				if ( linkEl.attr('href').indexOf('?') >= 0 ) {
					linkEl.attr('href', linkEl.attr('href')+'&amp;popup');
				} else {
					linkEl.attr('href', linkEl.attr('href')+'?popup');
				}
			});
		
			container.find("a.popup").fancybox({
				'overlayOpacity': 0.7,
				'overlayColor': '#000000',
				'width': 640,
				'height': '90%',
				'autoDimensions': false,
				'padding':	0,
				'autoScale': false,
				'onStart': function() {
					jQuery('body, html').css({
						'overflow': 'hidden'
					});
				},
				'onComplete': function() {
					initContainer('#fancybox-inner');
					
					if ( navigator.userAgent.match(/MSIE 6/i) == null ) {
						var width = jQuery('#fancybox-wrap').width();
						jQuery('#fancybox-wrap').addClass('inline');
						jQuery(window).unbind("resize.fb");
						jQuery('#fancybox-wrap').css({
							'position': 'fixed',
							'top': '0px',
							'bottom': '0px',
							'left': '0px',
							'right': '0px',
							'overflow': 'auto',
							'width': 'auto',
							'height': 'auto'
						}).bind('click', function(){$.fancybox.close(); });
						jQuery('#fancybox-outer').css({
							'margin': 'auto',
							'width': width+'px',
							'height': 'auto',
							'padding': 0
						});
						jQuery('#fancybox-inner').css({
							'margin': 'auto',
							'height': 'auto',
							'position': 'relative'
						}).unbind('click').bind('click', function(){return false;});
						jQuery('#fancybox-inner').children().unbind('click').bind('click', function(){return true;});
					}
				},
				'onClosed': function() {
					if ( navigator.userAgent.match(/MSIE 6/i) == null ) {
						jQuery(window).bind("resize.fb", jQuery.fancybox.center);
						jQuery('body').css({
							'overflow': ''
						});
						jQuery('html').css({
							'overflow': ''
						});
						jQuery('#fancybox-outer').css({
							'margin': '',
							'width': '',
							'height': '',
							'padding': ''
						});
						jQuery('#fancybox-wrap').css({
							'position': '',
							'top': '',
							'bottom': '',
							'left': '',
							'right': '',
							'overflow': '',
							'width': '',
							'height': ''
						});
						jQuery('#fancybox-inner').css({
							'margin': '',
							'height': '',
							'position': ''
						})
					}
				}
			});
		}
	}
	
	container.find('a[class^="target_"]').unbind('click').bind('click', function(){
		var target = null;

		var classList = this.className.split(/\s+/);
		for (var c in classList ) {
			if ( classList[c].indexOf('target_') == 0  && classList[c].length > 7) {
				target = classList[c].substr(7);
				if ( target == 'self' || target == 'top' || target == 'blank' ) {
					target = '_'+target;
				}
				break;
			}
		}
		
		window.open(this.href, target);
		return false;
	});
	
	initSpecialContentToggle(container);
	
	initChapters(container);
	if ( container.get(0).tagName.toLowerCase() == 'body' ) {
		gotoChapter(window.location.hash, true);
	}

	container.find("a.teaser").fancybox({
		'width'				: 940,		
		'height'			: '85%',
		'centerOnScroll'	: true,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'overlayOpacity'	: 0.8,
		'speedIn'		   : 400,
		'speedOut'		  : 400,
		'margin'			: 0,
		'padding'		   : 0,
		'changeFade'		: 'slow',
		'type'				: 'iframe'
	});
	
	for ( var v in videolist ) {
		videolist[v]();
	}
	
	initAjaxForm();
	
	if ( typeof window['gapi'] != 'undefined' ) {
		gapi.plusone.go();
	}
}




function initSpecialContentToggle (container){
	container.find('.togglelist .title').unbind('click').bind('click', function(){
		animateSpecialContent( jQuery(this) );
		return false;
	});
}

function animateSpecialContent(linkEl) {
	var duration		= 500;
	var detailsEl		= linkEl.parent().children('.info');
	var tease_height	= 50;
	
	var cur_height = (detailsEl.css('display') == 'none') ? 0 : detailsEl.height();
	var full_height = detailsEl.css({'display': 'block', 'overflow': 'hidden', 'height': 'auto'}).outerHeight();
	detailsEl.height(cur_height);
	
	if ( linkEl.hasClass('open')){
		linkEl.removeClass('open').addClass('closed');
		detailsEl.stop().addClass('animating').animate({'height' : '1px'}, duration, function() {
			detailsEl.css('display', 'none');
			detailsEl.removeClass('animating');
		});
	}
	else {
		linkEl.removeClass('closed').addClass('open');
		detailsEl.stop().addClass('animating').animate({'height': full_height+'px'}, duration, function() {
			detailsEl.removeClass('animating');
		});
	}
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


function initChapters(container) {
	var gotos = container.find('a.goto');
	gotos.each(function(){
		var thisEl = jQuery(this);

		thisEl.unbind('click').bind('click', function(e) {
			if ( (id_pos = thisEl.attr('href').lastIndexOf('#')) >= 0 ) {
				targetChapter = thisEl.attr('href').substr( id_pos );
				return gotoChapter(targetChapter) == true ? false : true;
			}
		});
	});
	
	var chapters = container.find('.chapter');
	
	if ( isMobile() ) {
		chapters.find('.videoWrapper').find('embed, object').css('display', 'none');
	}
	chapters.each(function(){
		var chapterEl = jQuery(this);
		var maskEl = chapterEl.find('.mask');

		if ( maskEl.length != 1 ) {
			return;
		}
		
		var panels = maskEl.children('div');
		panels.css('display', 'block');
		var width = 0;
		panels.each(function(pos, el) {
			width += panels.eq(pos).outerWidth(true);
			panels.not(':eq(0)').css('height', '10px');
		});
		
		maskEl.width( width );

		chapterEl.find('.chapter_nav ul a').unbind('click').bind('click', function(e){
			var linkEl = jQuery(this);
			showSubChapter(linkEl);
			return false;
		});
		
		chapterEl.find('.shortlinks a.goto').unbind('click').bind('click', function(e){
			var linkEl		= jQuery(this);
			var chapterEl	= linkEl.closest('.chapter');
			var navEl		= chapterEl.find('.chapter_nav ul a[href="'+linkEl.attr('href')+'"]');
			
			var target		= navEl.attr('href');
			
			var chapter_id		= null;
			var subchapter_id	= null;
			
			if ( target.indexOf('/') > 0 ) {
				chapter_id		= target.substr(0, target.indexOf('/') );
				subchapter_id	= target.substr( target.indexOf('/')+1 );
			} else {
				chapter_id = target;
			}
			
			if ( chapter_id !== null ) {
				gotoChapter(
									chapter_id,
									false,
									function() {
										
									});
			}
			
			if ( subchapter_id !== null ) {
				showSubChapter(navEl, false);
			}
		});
	});
}

function gotoChapter(target, fast, callback_after) {
	var chapter_id = null;
	var subchapter_id = null;
	
	if ( target.indexOf('/') > 0 ) {
		chapter_id = target.substr(0, target.indexOf('/') );
		subchapter_id = target.substr( target.indexOf('/')+1 );
	} else {
		chapter_id = target;
	}
	
	var chapterEl = jQuery(chapter_id);

	if ( chapterEl.length > 0 ) {
		var callback = function(){
			var linkEl = chapterEl.find('.chapter_nav a[href$="'+target+'"]');
			if ( linkEl.length > 0 ) {
				showSubChapter(linkEl, true);
			} else {
				jQuery('body').find('.head a').removeClass('active').filter('a[href$="'+chapter_id+'"]').addClass('active');
				window.location.hash = target;
			}
			if ( typeof callback_after == 'function' ) {
				callback_after();
			}
		}

		if ( fast == true || isMobile() == true ) {
			jQuery('body').stop().scrollTo( chapterEl, 0);
			callback();
		} else {
			jQuery('body').stop().scrollTo( chapterEl, 1000, callback);
		}
		return true;
	} else {
		return false;
	}
}


function showSubChapter(linkEl, fast) {
	var new_hash = '';
	if ( (id_pos = linkEl.attr('href').lastIndexOf('#')) >= 0 ) {
		new_hash = linkEl.attr('href').substr( id_pos );
	}

	if ( new_hash != '' && (!linkEl.hasClass('active') || window.location.hash != new_hash || fast == 1) ) {

		var chapterEl	= linkEl.parents('.chapter:eq(0)'); 
		var mEl			= chapterEl.find('.mask');
		var targetEl	= mEl.children('div:eq('+ linkEl.parent().index() +')');
		var position	= targetEl.position();

		jQuery('body').find('a[href$="'+mEl.parents('div.chapter').attr('id')+'"]').each(function(){
			var t = jQuery(this);
			if ( t.parent().parent()[0].tagName.toLowerCase() == 'ul' ) {
				t.parent().parent().find('a.goto, #nav_e_1 a').removeClass('active');
			}
			t.addClass('active');
		});

		mEl.css('height', mEl.height()+'px');	// set mask height from auto to a pixel value

		mEl.children('div').css('height', 'auto'); // set contents heights from pixel values to auto
		var height = targetEl.height(); // get the height of the target element


		if ( isMobile() ) {
			chapterEl.find('.chapter_container').not(targetEl).find('object, embed').css('display', 'none');
		}

		var callback = function() {
			// check if the user switch between panels inside active chapter
			if ( window.location.hash.substring(1, chapterEl.attr('id').length+1) == chapterEl.attr('id') ) {
				stopAllVideos(chapterEl.get(0)); // stop videos inside the panels
			}
			if ( isMobile() ) {
				targetEl.find('object, embed').css('display', 'block');
			}
		};
		
		if ( fast == true ) {
			// set the mask position and the height
			mEl.stop(true).css({'left': '-'+position.left+'px', 'height': height+'px'});
			mEl.children('div').not(targetEl).css('height', '10px'); // set a minimun temporary height to the non active contents
			mEl.css('height', 'auto'); // reset the mask height to auto, this allows resizing the target content and automatic resize of the mask
			callback();
		} else {
			// animate the mask position and the height
			mEl.stop(true).animate({'left': '-'+position.left+'px', 'height': height+'px'}, 1000, function(){
				mEl.children('div').not(targetEl).css('height', '10px'); // set a minimun temporary height to the non active contents
				mEl.css('height', 'auto'); // reset the mask height to auto, this allows resizing the target content and automatic resize of the mask
				callback();
			});
		}

		linkEl.parent().parent().find('a.active').removeClass('active');
		linkEl.addClass('active');
		
		window.location.hash = new_hash;
	}
}

if ( videolist == undefined ) {
	var videolist = new Array();
}

function initVideo( swfObjectContainer, container) {
	if (typeof(swfObjectContainer) == 'object' && $('#' + container).length != 0) {
		swfObjectContainer.write(container);
	} else if (typeof(swfObjectContainer) == 'string' && $('#' + container).length != 0) {
		$('#' + container).html(swfObjectContainer);
	} else {
		//dumplog('initVideo: not found: '+container+' | '+typeof(swfObject)+' | #'+container+' | '+$('#'+container).length);
	}
}

function stopAllVideos(selector) {
	try {
		var videos = null;
		
		if ( selector == undefined ) {
			videos = jQuery(':not(.stopped_video) embed[src*=".youtube"]');
		} else {
			videos = jQuery(selector).find('div:not([class*="stopped_video"]) embed[src*=".youtube"]');
		}

		if ( videos.length > 0 ) {
			videos.each(function(pos, el){
				stopVideo(el);
			});
		}
	} catch(e){}
}

function stopVideo(video) {
	jQuery(video).parents('div:eq(0)').addClass('stopped_video');
	try {
		video.pauseVideo();
	} catch(e) {
		var parent	= jQuery(video).parent();
		var copy	= parent.html();
		parent.html( copy );
	}
}


/**
 * @author robertr
 */
if ( typeof window.dump != 'function' ) {
	function dumplog(variable){
		if (window.console !== undefined) {
			console.log(variable);
		}
	}
}
/*
 * ajaxForm
 */
var formInputFilter = new Array('radio', 'checkbox', 'submit', 'reset', 'button', 'hidden', 'image');
function initAjaxForm() {

	var ajaxFormWrappers = $('.ajaxForm.formContent').not('.init');

	if  ( ajaxFormWrappers.length > 0 ) {
		ajaxFormWrappers.each(function(formNo, formContentEl) {
			var jFormAreaEl = $(formContentEl);
			jFormEl = jFormAreaEl.find('form');
			
			if ( jFormEl.length == 1) {
				var textInput = jFormEl.find('textarea, input').not('*[type="' + formInputFilter.join('"], *[type="') + '"]');
				
				textInput.unbind('click, focus').bind('click, focus', function(){
					var fieldEl = jQuery(this);
					clearFieldDefaults(fieldEl);
				});
				
				textInput.unbind('blur').bind('blur', function(){
					var fieldEl = jQuery(this);
					var fieldId = fieldEl.attr('id');
					if (fieldId == null || fieldId == '' ) {
						return true;
					}
					
					var labelEl = jQuery('label[for="'+fieldId+'"]');
					if ( labelEl.length == 1 ) {
						if ( fieldEl.get(0).tagName.toLowerCase() == 'input' && fieldEl.attr('value') == '' ) {
							fieldEl.attr('value', labelEl.html() );
						} else if ( fieldEl.get(0).tagName.toLowerCase() == 'textarea' && fieldEl.html() == '' ) {
							fieldEl.html( labelEl.html() );
						}
					}
				});

				
				jFormAreaEl.addClass('init');
				var formAction = jFormAreaEl.find('form').attr('action');
				if ( formAction == '' || formAction.substr(0,1) == '/' || formAction.indexOf(window.location.protocol+'//'+window.location.hostname) === 0 ) {
					dumplog('redefine onsubmit');
					jFormEl.onSubmit = 'executeAjaxForm(this); return false;';
					jFormEl.attr('onSubmit', 'executeAjaxForm(this); return false;');
					jFormEl.find('input[type="submit"]').unbind('click').bind('click', function(){
						executeAjaxForm(jFormEl.get(0));
						return false;
					});
				}
				dumplog('initAjaxForm: configure a existing form ('+formAction+')');
			} else {
				dumplog('initAjaxForm: detect a invalid form');
				dumplog(formUrl);
			}
		});
	} else {
		dumplog('initAjaxForm: no ajax forms where found');
	}
	dumplog('initAjaxForm: complete');
}





function executeAjaxForm(formElement) {
	dumplog('executeAjaxForm: enter');
	var jFormEl = $(formElement);
	var jFormAreaEl = $(formElement).parents('.formContent');
	var formUrl = jFormEl.attr('action');

	if (formUrl != undefined && formUrl != '') {
		var dataString = '';

		
		jFormEl.find('textarea, input').not('*[type="' + formInputFilter.join('"], *[type="') + '"]').each(function(){
			var fieldEl = jQuery(this);
			clearFieldDefaults(fieldEl);
		});

		

		for(i=0; i < formElement.elements.length; i++) {
			var field = formElement.elements[i];
			switch (field.tagName) {
				case 'INPUT':
						if ( field.type == 'text' || field.type == 'password' || field.type == 'hidden' ) {
							dataString += '&'+field.name+'='+escape(field.value);
						}
					break;
				case 'SELECT':
						dataString += '&'+field.name+'='+escape(field.value);
					break;
				case 'TEXTAREA':
					dataString += '&'+field.name+'='+escape(field.value);
				break;
			}
		}

		var formMethod = formElement.method.toLowerCase() == 'post' ? 'POST' : 'GET';
		dumplog(formMethod);
		
		$.ajax({
			type: formMethod,
			url: formUrl,
			data: 'ajax=1'+dataString,
			beforeSend: function(){
				jFormAreaEl.append('<div class="loading">&nbsp;</div>');
			},
			complete: function(){
				jFormAreaEl.find('.loading').fadeOut("fast", function(){
					$(this).remove();
				});
			}, //stop showing loading when the process is complete
			success: function(html){ //so, if data is retrieved, store it in html
				if (html.indexOf('</html>') == -1) {
					dumplog('replace content inside the form area');
					dumplog(jFormAreaEl);
					jFormAreaEl.html(html);
					jFormAreaEl.removeClass('init');
					initAjaxForm();
				}
			}
		}); //close $.ajax(
	}
	dumplog('executeAjaxForm: complete');	
}








function clearFieldDefaults(fieldEl) {
	if ( fieldEl != undefined ) {
		try {
			var fieldId = fieldEl.attr('id');
			if (fieldId == null || fieldId == '' ) {
				return true;
			}
			
			var labelEl = jQuery('label[for="'+fieldId+'"]');
			if ( labelEl.length == 1 ) {
				if ( fieldEl.get(0).tagName.toLowerCase() == 'input' && fieldEl.attr('value') == labelEl.html() ) {
					fieldEl.attr('value', '');
				} else if ( fieldEl.get(0).tagName.toLowerCase() == 'textarea' && fieldEl.html() == labelEl.html() ) {
					fieldEl.html('');
				}
			}
		} catch(e) {};
	}
}















