jQuery(document).ready(function($) {
	var currSlide = 0;
	initBindings();

	if($('#slideshow').length){
		initSlideshow();
	};
	if($('#volunteers #map_canvas').length){
		$('#volunteers #map_canvas').maps({
			json_url: '/json?volunteers'
		});
	};
	if($('#results #map_canvas').length){
		$('#results #map_canvas').maps({
			json_url: '/json?projects&results_check=on'
		});
	};
	if($('#donators #map_canvas').length){
		$('#donators #map_canvas').maps({
			json_url: '/json?projects'
		});
	};

	if($('#regioEvents').length){
		$('#regioEvents').maps({
			json_url: '/json?regioagenda'
		});
	};
	$('#freeDonation').tipsy({
		gravity: 'n',
		fade: true
	});
	$('[data-tipsy]').tipsy({
		gravity: "w",
		html: true,
		fade: true
	});

	if($('#adoptionSlideshow').length){
		initSmallSlideshow();
	};

	if($('#breaking').length){
		$('#breaking').hide();
		var projectID = $('#breaking').attr('data-id');
		if(!($.cookie(projectID) == 'true')){
			if(($.cookie("breakingopen") == 'true')){
				$('#breaking').show();
			} else {
				$('#breaking').delay(800).slideDown();
				$.cookie("breakingopen", "true");
			}
		}

		$('#breaking .close').click(function(event){
			event.preventDefault();
			$('#breaking').slideUp();
			$.cookie(projectID, "true");
		});
	};
	
	// if($('#home #twitter').length){
	// 	jQuery("#twitter .inner").tweet({
	// 		avatar_size: 45,
	// 		count: 4,
	// 		username: "lcj",
	// 		query: "from:WenDjongeren OR from:WoordenDaad OR from:EvertJanBrouwer OR from:WDAldwin OR from:RinaMolenaar OR from:djnieuwenhuisv",
	// 		refresh_interval: 180,
	// 		filter: function(t){ return ! /^@\w+/.test(t["tweet_raw_text"]); },
	// 		loading_text: "searching twitter...",
	// 		template: function(i){return  i["user"] + i["text"] + i["time"]}
	// 	}).bind("empty", function() { $(this).append("<p>Er is al meer dan 5 dagen niets getweet!</p>"); });
	// };


	if($('.zoom').length){
		$('.zoom').fancybox({
			type: 'image'
		});
	};

	if($('body .login').length){
		$('#userNavigation').hide();
		$('body .login').click(function(event){event.preventDefault();$('#userNavigation').slideDown();});
		$('#userNavigation .close').click(function(event){event.preventDefault();$('#userNavigation').slideUp();});
	};

	if($('.comityList').length){
		$('.comityList .details').hide();
		$('.comityList .group').click(function(event){
			event.preventDefault();
			$(this).toggleClass('active');
			target = $(this).attr('href');
			$(target).slideToggle();
		});
	};
	if($('.winkels').length){
		if(window.location.hash !== ''){
			$(window.location.hash).show();
			$(window.location.hash).prev('a').addClass('active');
		}
	};

	// Deobfuscate data-obfuscate attributes (see String#obfuscate)
	function deobfuscate(s) {
		var strrev = function(s) { return s.split('').reverse().join(''); };
		var hexes = s.match(/(.{2,2})/g);
		var ords = [];

		for(var i = 0; i < hexes.length; i++) {
			var hex = strrev(hexes[i]);
			ords.push(parseInt(hex, 16) + (i % 5));
		}

		return String.fromCharCode.apply(null, ords);
	}
	$('[data-deob]').each(function() {
		$this = $(this);
		for (var i = this.attributes.length - 1; i >= 0; i--) {
			var attrNode = this.attributes[i];
			var match = attrNode.nodeName.match(/^data\-deob-(.+)$/);
			if(!match || !match[1])
				continue;
			
			var attr = match[1];
			var value = attrNode.nodeValue;
			
			var deobf = deobfuscate(value);
			if(attr === 'content') {
				$this.html(deobf);
			} else {
				$this.attr(attr, deobf);
			}
			$this.removeAttr(attrNode.nodeName);
		}
		$this.removeAttr('data-deob');
	});

	/**
	 * Hide dashboard tags attributes (more reliable than CSS3 selector)
	 * @see http://james.padolsey.com/javascript/regex-selector-for-jquery/
	 */
	jQuery.expr[':'].regex = function(elem, index, match) {
	    var matchParams = match[3].split(','),
	        validLabels = /^(data|css):/,
	        attr = {
	            method: matchParams[0].match(validLabels) ? 
	                        matchParams[0].split(':')[0] : 'attr',
	            property: matchParams.shift().replace(validLabels,'')
	        },
	        regexFlags = 'ig',
	        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
	    return regex.test(jQuery(elem)[attr.method](attr.property));
	}
	$('p:regex(class, attribute\\-\\w+\\-tags)').hide();
});

function initBindings(){

	if($('.toggle').length){
		$('.toggleTarget').hide();

		$('.toggle').click(function(event){

			if(this.nodeName == 'LABEL'){
				target = $(this).attr('rel');
				if($(this).hasClass('close')){
					if($('#'+target)[0].style.display == 'block'){
						$('#'+target).slideUp();
					}
				} else{
					if($('#'+target)[0].style.display == 'none'){
						$('#'+target).slideDown();
					}
				};
			} else{
				event.preventDefault();
				target = $(this).attr('href');
				$(target).slideToggle();
				$(this).toggleClass('active');
			};
		});

		// Opens non-closing toggle element's [rel] element
		$('label.toggle[rel]:not(.close)').has('input:checked').each(function() {
			var $this = $(this),
				$target = $('#'+$this.attr('rel'));
			$target.show();
		});

	};

	// Donation repetition text replace
	(function() {
		var $replaceTarget = $('#repetition-replace');
		var replace = function(el) {
			$el = $(el);
			$replaceTarget.html($el.attr('data-replace-text'));
		};
		$('input[name="donation[repetition][value]"]').click(function() {
			replace(this);
		});
		replace($('input[name="donation[repetition][value]"]:checked'));
	}());

	if($('#plusone-div').length){
		gapi.plusone.render("plusone-div",{"size": "medium"});
	}

	if($('#fb-div') && window['FB']){
		FB.XFBML.parse($("#fb-div").get(0));
	}


	if($('#info').length){$.localScroll({
		filter: 'toggle'
	});};

	if($('#mailafriend').length){
		$('#mailafriend').hide();
		if (window.location.hash == '#mailafriend'){$('#mailafriend').show();};
		$('#pageMeta .send').live('click', function(event){
			event.preventDefault();
			$('#mailafriend').slideToggle();
		});
	};
	if($('.print').length){
		$('.print').live('click', function(event){
			event.preventDefault();
			window.print();
		});
	};	
	if($('.album').length){

		if($('.album[id="projectSlideNav"]').length){
			initSlideCarousel();
		} else{
			initCarousel();
		}
	}
};

function initSmallSlideshow(){
	$('#adoptionSlideshow .slides').cycle({
		cleartypeNoBg: true,
		timeout: 6000,
		pause: true
	});
};



function initSlideshow(){
	var isInitiated=false;
	var $container = $('#slideshow .slides').cycle({
		cleartypeNoBg: true,
		timeout: 7500,
		before: setActiveState,
		pause: true
	});
	$('#slideshowNav li').each(function(i){
		$(this).css("cursor", "pointer");
		$(this).click(function(event){
			event.preventDefault();
			$container.cycle(i);
		});

	});
	function setActiveState(curr,next,opts){
		var currentSlideshow=opts.$cont;
		if(isInitiated){
			$('#slideshowNav li').removeClass("active");
			$($('#slideshowNav li')[opts.nextSlide]).addClass("active");
		};
		isInitiated=true;
	};
};


function initCarousel(){
	jQuery('.album ul').jcarousel({
		auto: 4,
		scroll: 1,
		wrap: 'last',
		initCallback: mycarousel_initCallback
	});
}

function mycarousel_initCallback(carousel){

	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});

	$('.album:not(.no-fancybox) li a').fancybox({
		'padding'       : 0,
		'autoScale'     : false,
		'transitionIn'  : 'none',
		'transitionOut' : 'none',
		'width'         : 568,
		'height'        : 378,
		'scrolling'     : 'no'
	});

}

function initSlideCarousel(){

	$('#projectSlideNav li a').each(function(event){
		if ($(this).attr('href') == $('#projectImg').attr('src')){
			$(this).addClass('active');
		};
	});

	jQuery('.album ul').jcarousel({
		scroll: 1,
		wrap: 'last',
		initCallback: slideshowCarouselCallback,
		itemFirstInCallback: setBigImg
	});
}

function slideshowCarouselCallback(carousel){
	$('#projectSlideNav li a').click(function(event){
		event.preventDefault();

		var item = getCurrentCarouselItem(this);
		if(carousel.last == $('#projectSlideNav li').length){
			setBigImg(carousel, $(this).parent('li'));
		}else {
			carousel.scroll(item);
		}; 



	});
}
function setBigImg(carousel, clicker){
	$('#projectSlideNav li a').removeClass('active');
	newimg = $(clicker).find('a').attr('href');
	target = $('#projectImg');
	target.attr('src', newimg);
	$(clicker).find('a').addClass('active');
}


function getCurrentCarouselItem(listitem){
	$(listitem).parent('li').each(function(){
		var leftPos = $(this).offset().left;
		if( leftPos >= 0){
			var id = $(this).attr('id').split("-");
			currSlide = id[1]*1+1;
			return false;
		}
	});
	return currSlide;
}
