﻿// jQuery WipeTouch 1.1.0
//
// Developed and maintained by Devv: http://devv.com
// This plugin is based on TouchWipe by Andreas Waltl: http://www.netcu.de
//
// USAGE
// $(selector).wipetouch(config);
//
// The wipe events should expect the result object with the following properties:
// speed - the wipe speed from 1 to 5
// x - how many pixels moved on the horizontal axis
// y - how many pixels moved on the vertical axis
//
// EXAMPLE
//		$(document).wipetouch({
//			allowDiagonal: true,
//			wipeLeft: function(result) { alert("Left on speed " + result.speed) },
//			wipeTopLeft: function(result) { alert("Top left on speed " + result.speed) },
//			wipeBottomLeft: function(result) { alert("Bottom left on speed " + result.speed) }
//		});
//
//
// More details at http://wipetouch.codeplex.com/
//
// LATEST CHANGES
// 1.1.0
// - New: tapToClick, if true will identify taps and and trigger a click on the touched element. Default is false.
// - Changed: events wipeBottom*** and wipeTop*** renamed to wipeDown*** and wipeUp***.
// - Changed: better touch speed calculation (was always too fast before).
// - Changed: speed will be an integer now (instead of float).
// - Changed: better wipe detection (if Y movement is more than X, do a vertical wipe instead of horizontal).
// - Bug fix: added preventDefault to touchStart and touchEnd internal events (this was missing).
// - Other general tweaks to the code.
//
//
// If you want to compress this code, we recommend Jasc: http://jasc.codeplex.com

(function($)
{
	$.fn.wipetouch = function(settings)
	{
		// ------------------------------------------------------------------------
		// PLUGIN SETTINGS
		// ------------------------------------------------------------------------

		var config = {
			// Variables and options
			moveX:				40,		// minimum amount of horizontal pixels to trigger a wipe event
			moveY:				40,		// minimum amount of vertical pixels to trigger a wipe event
			preventDefault:		true,	// if true, prevents default events (click for example)
			allowDiagonal:		false,	// if false, will trigger horizontal and vertical movements so
										// wipeTopLeft, wipeDownLeft, wipeTopRight, wipeDownRight are ignored
			tapToClick:			false,	// if user taps the screen it will fire a click event on the touched element

			// Wipe events
			wipeLeft:			false,	// called on wipe left gesture
			wipeRight:			false,	// called on wipe right gesture
			wipeUp:				false,	// called on wipe up gesture
			wipeDown:			false,	// called on wipe down gesture
			wipeUpLeft:			false,	// called on wipe top and left gesture
			wipeDownLeft:		false,	// called on wipe bottom and left gesture
			wipeUpRight:		false,	// called on wipe top and right gesture
			wipeDownRight:		false,	// called on wipe bottom and right gesture

			wipeTopLeft:		false,	// DEPRECATED, USE WIPEUPLEFT
			wipeBottomLeft:		false,	// DEPRECATED, USE WIPEDOWNLEFT
			wipeTopRight:		false,	// DEPRECATED, USE WIPEUPRIGHT
			wipeBottomRight:	false	// DEPRECATED, USE WIPEDOWNRIGHT
		};

		if (settings)
		{
			$.extend(config, settings);
		}

		this.each(function()
		{
			// ------------------------------------------------------------------------
			// INTERNAL VARIABLES
			// ------------------------------------------------------------------------
			var startX; // where touch has started, left
			var startY; // where touch has started, top
			var startDate = false; // used to calculate timing and aprox. acceleration
			var curX; // keeps touch X position while moving on the screen
			var curY; // keeps touch Y position while moving on the screen
			var isMoving = false; // is user touching and moving?
			var touchedElement = false; // element which user has touched

			// ------------------------------------------------------------------------
			// TOUCH EVENTS
			// ------------------------------------------------------------------------

			// Called when user touches the screen
			function onTouchStart(e)
			{
				if (!isMoving && e.touches.length > 0)
				{
					if (config.preventDefault)
					{
						e.preventDefault();
					}

					// temporary fix for deprecated events, will be removed soon!!!
					if (config.allowDiagonal)
					{
						if (!config.wipeDownLeft) config.wipeDownLeft = config.wipeBottomLeft;
						if (!config.wipeDownRight) config.wipeDownRight = config.wipeBottomRight;
						if (!config.wipeUpLeft) config.wipeUpLeft = config.wipeTopLeft;
						if (!config.wipeUpRight) config.wipeUpRight = config.wipeTopRight;
					}

					startDate = new Date().getTime();

					startX = e.touches[0].pageX;
					startY = e.touches[0].pageY;
					curX = startX;
					curY = startY;
					isMoving = true;

					touchedElement = $(e.target);

					this.addEventListener('touchmove', onTouchMove, false);
				}
			}

			// Called when user untouches the screen
			function onTouchEnd(e)
			{
				this.removeEventListener('touchmove', onTouchMove, false);

				touchCalculate(e);
			}

			// Called when user is touching and moving on the screen
			function onTouchMove(e)
			{
				if (config.preventDefault)
				{
					e.preventDefault();
				}

				if (isMoving)
				{
					curX = e.touches[0].pageX;
					curY = e.touches[0].pageY;
				}
			}

			// ------------------------------------------------------------------------
			// CALCULATE TOUCH AND TRIGGER
			// ------------------------------------------------------------------------

			function touchCalculate(e)
			{
				var endDate = new Date().getTime();	// current date to calculate timing
				var ms = startDate - endDate; // duration of touch in milliseconds

				var x = curX;			// current left position
				var y = curY;			// current top position
				var dx = x - startX;	// diff of current left to starting left
				var dy = y - startY;	// diff of current top to starting top
				var ax = Math.abs(dx);	// amount of horizontal movement
				var ay = Math.abs(dy);	// amount of vertical movement

				// moved less than 15 pixels and touch duration less than 100ms,
				// if tapToClick is true then triggers a click and stop processing
				if (ax < 15 && ay < 15 && ms < 100)
				{
					resetTouch();

					touchedElement.trigger("click");
					return;
				}

				var toright = dx > 0;	// if true X movement is to the right, if false is to the left
				var tobottom = dy > 0;	// if true Y movement is to the bottom, if false is to the top

				// calculate speed from 1 to 5, being 1 slower and 5 faster
				var s = ((ax + ay) * 60) / ((ms) / 6 * (ms));

				if (s < 1) s = 1;
				if (s > 5) s = 5;

				var result = {speed: parseInt(s), x: ax, y: ay};

				if (ax >= config.moveX)
				{
					// check if it's allowed and call diagonal wipe events
					if (config.allowDiagonal && ay >= config.moveY)
					{
						if (toright && tobottom)
						{
							triggerEvent(config.wipeDownRight, result);
						}
						else if (toright && !tobottom)
						{
							triggerEvent(config.wipeUpRight, result);
						}
						else if (!toright && tobottom)
						{
							triggerEvent(config.wipeDownLeft, result);
						}
						else
						{
							triggerEvent(config.wipeUpLeft, result);
						}
					}
					else if (ax >= ay)
					{
						if (toright)
						{
							triggerEvent(config.wipeRight, result);
						}
						else
						{
							triggerEvent(config.wipeLeft, result);
						}
					}
				}

				if (ay >= config.moveY && ay > ax)
				{
					if (tobottom)
					{
						triggerEvent(config.wipeDown, result);
					}
					else
					{
						triggerEvent(config.wipeUp, result);
					}
				}

				if (config.preventDefault)
				{
					e.preventDefault();
				}

				resetTouch();
			}

			// Resets the cached variables
			function resetTouch()
			{
				startX = false;
				startY = false;
				startDate = false;
				isMoving = false;
			}

			// Triggers a wipe event passing a result object with
			// speed from 1 to 5, and x / y movement amount in pixels
			function triggerEvent(wipeEvent, result)
			{
				if (wipeEvent) wipeEvent(result);
			}

			// ------------------------------------------------------------------------
			// ADD TOUCHSTART AND TOUCHEND EVENT LISTENERS
			// ------------------------------------------------------------------------

			if ('ontouchstart' in document.documentElement)
			{
				this.addEventListener('touchstart', onTouchStart, false);
				this.addEventListener('touchend', onTouchEnd, false);
			}
		});

		return this;
	};
})(jQuery);


function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
                new_embed.setAttribute('wmode', 'transparent');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for (j = 0; j < children.length; j++) {
                try {
                    if (children[j] != null) {
                        var theName = children[j].getAttribute('name');
                        if (theName != null && theName.match(/flashvars/i)) {
                            new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                        }
                    }
                }
                catch (err) {
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}

$=jQuery;
$(document).ready(function(){
	fix_flash();

	//add class to last items
	$('#menuBox li a:last, #footerCntr li:last').addClass('last');
	$('#update li:last').addClass('end');

	//hide
	$('.result_ok').hide();
	$('.result_not_ok').hide();
						   
	//yeshello
	$('.submit').live("click", function() {
		var this_id=this.id;
										
		$.ajax({
			url: '/wp-content/themes/peekrf/includes/ajax.php',
			type: 'POST',
			data: 'cmd=yeshello&'+$('form#'+this_id).serialize(),

			success: function(result) {
				//ok
				if(result.length==5) {
					$('#div_'+this_id+' p.result_not_ok').hide();
					$('#div_'+this_id+' p.result_ok').show();

					//analytics
					pageTracker._trackPageview('nb_aangemeld');
				}

				//not ok
				if(result.length==3) {
					$('#div_'+this_id+' p.result_ok').hide();
					$('#div_'+this_id+' p.result_not_ok').show();
				}
			}
		});
		return false;
	});
	
	//vraag_verstuurd
	if($('#vraag_verstuurd').size()==1) {
		//analytics
		pageTracker._trackPageview('vraag_verstuurd');
	}

	//call_me_back
	if($('#call_me_back').size()==1) {
		//analytics
		pageTracker._trackPageview('call_me_back');
	}

	//cycle thumbs
	if($('#slideshow > img').size() > 1 || $('#slideshow > div').size() > 1) {
		$('#slideshow').cycle({
			fx: 'scrollHorz',
			speed: 1500,
			timeout: 7000,
			next: '.next', 
			prev: '.prev',
			before: function(){
				$(this).parent().find('div.current').removeClass();
				
				
			},
			after: function(curr,next,opts) {
				$(this).addClass('current');
				if(slideshowopen==false) {
					currentdetail=opts.nextSlide-1;
				}
				
			}
		});
	}

	//cycle thumbs
	if($('.galleryBoxes > ul').size() > 1) {
		$('.galleryBoxes').cycle({
			fx: 'fade',
			speed: 1500,
			timeout: 0,
			next: '.gallery_next', 
			prev: '.gallery_prev1',
			after: function (curr, next, opts) {
				$('#paging').html((opts.currSlide+1) + "/" + opts.slideCount);
			}
		});
	}else $('.gallery').hide();

	//youtube
	$.fn.youquery = function(url, width, height){
		this.html('<iframe width="700" height="431" src="http://www.youtube.com/embed/'+url+'/?html5=1&rel=0" frameborder="0" allowfullscreen></iframe>');
	};

	//click on thumb
	$('.youtubethumb').live("click", function() {
		//image
		if(this.id) {
			//get id
			var id=this.id.replace("thumb_", "");
			$('#slideshow').cycle(parseInt(id));
		}

		//youtube
		if($(this).attr('youtube_key')) {
			//$('#youtube').html('<iframe width="700" height="431" src="http://www.youtube.com/embed/'+$(this).attr('youtube_key')+'" frameborder="0" allowfullscreen></iframe>');
			$('#youtube').youquery($(this).attr('youtube_key'));
		}
		return false; 
	});
	
	$('.thumb').live("click", function() {
		//image
		if(this.id) {
			//get id
			var id=this.id.replace("thumb_", "");
			
			$('#slideshow').cycle(parseInt(id));
		}

		//youtube
		if($(this).attr('youtube_key')) {
			//$('#youtube').html('<iframe width="700" height="431" src="http://www.youtube.com/embed/'+$(this).attr('youtube_key')+'" frameborder="0" allowfullscreen></iframe>');
			$('#youtube').youquery($(this).attr('youtube_key'));
		}
		return false; 
	});

	//first page (thumbs)
	$('.gallery_prev').live("click", function() {
		$('.galleryBoxes').cycle(0); 
		return false; 
	});

	//last page (thumbs)
	$('.gallery_next1').live("click", function() {
		$('.galleryBoxes').cycle($('.galleryBoxes > ul').size()-1); 
		return false; 
	});
	
	//go to
	$('#goto').live("change", function() {
		window.location.href=$(this).val();
	});

	//tooltips
	$('.sliderBox a.icon').hover(function(){
		$('.current div.beverages').show();
	}, function(){
		$('.current div.beverages').hide();
	});

	//colorbox
	//$("a[rel='colorbox']").colorbox({slideshow:true});

	//large img
	$('.sliderBox a.icon1').live("click", function() {
		start_slideshow();
		//var url=$('.current .url_container').html();
		//$('#colorbox'+url).click();
		return false; 
	});

	$('.sliderBox a.icon').live("click", function() {
		return false;
	});

	var checkFlash = function() {
		//check flash
		if(swfobject.hasFlashPlayerVersion("1")) {
			$('#slideshare_noflash').hide();
		}else $('#slideshare_flash').hide();
	}
	
	checkFlash();
});


$(window).resize(function() {
	$('.customslide').css('width',$(window).width());
	$('.customslide').css('height',$(window).height());
	$('#customslides').css('margin-left',($(window).width()*currentdetail*-1)+'px');	
	$('.customslideshow_pagenav').css('width',$(window).width());

});

function close_slideshow() {
	$('body').css("overflow",'');
	$('#customslideshow').remove();
	slideshowopen=false;
}


var slideshowopen;
function start_slideshow() {
	slideshowopen=true;
	//currentdetail=0;
	$(document).scrollTop(0);
	$('body').append('<div id="customslideshow"><div class="customslideshow_pagenav"><div id="customslideshow_navclose"></div><div id="customslideshow_navleft"></div><div id="customslideshow_navright"></div></div><div id="customslides"></div></div>');	
	
	$('#customslideshow').wipetouch({
	  tapToClick: true, 
	  wipeLeft: function(result) { slideshow_nav('right');  },
	  wipeRight: function(result) { slideshow_nav('left'); }
	});
	$("img[rel='colorbox']").each(function() {
		
		$('#customslides').append('<div class="customslide"><img src="'+$(this).attr('src')+'"/></div>');
		
	});
	$('body').css("overflow",'hidden');
	$('.customslideshow_pagenav').css('width',$(window).width());
	$('.customslide').css('width',$(window).width());
	$('.customslide').css('height',$(window).height());
	
	$('#customslideshow').mousedown(function() {
		start_swipe();
		
	}).mouseup(function() {
		swipe();
	});
	
	$('#customslides').css('margin-left',($(window).width()*currentdetail*-1)+'px');
	
	$('#customslideshow_navleft').click(function() {
		slideshow_nav('left');
	});
	
	$('#customslideshow_navright').click(function() {
		slideshow_nav('right');
	});
	
	$('#customslideshow_navclose').click(function() {
		close_slideshow();
		
	});
}
var swipepos= new Array();
var pagex;
var currentdetail=0;
function slideshow_nav(dir) {
	
	if(dir=='right') {
		currentdetail++;
		
	} else {
		currentdetail--;
	}

	if(currentdetail<0) {
		currentdetail = $('.customslide').length-1;	
	}
	
	if(currentdetail>$('.customslide').length-1) {
		currentdetail=0;	
	}

	$('#customslides').animate({
		'margin-left':($(window).width()*currentdetail*-1)+'px'	
	},1200);
}

$(document).mousemove(function(e){
    pagex = e.pageX;
});
 
function start_swipe() {
	swipepos = pagex;
}

function swipe() {
	var differ = pagex-swipepos;
	if(differ>50) {
		slideshow_nav('left')
	}
	if(differ<-50) {
		slideshow_nav('right')
	}
}
