var balloon1Div;
var balloon2Div;
var balloon3Div;
var activeBalloon = null;

var balloonContentActieCoupon ;
var balloonContentSalonFinder ;
var balloonContentTwitter ;
var balloonContentAanmeldenNieuwsbrief;
var ScrollerHolderWidth = 468;
var ScrollerSlideWidth = 117;

// Slider: to move one slide at a time
// Holder: to move by all slides that fit in one holder
var ScrollerMoveBy = 'Holder';
var ScrollerID = 'Scroller';
var ScrollerSpeed = 7500;

var LargeImageHolder = 'ImageLarge';


function MoveScroller( Direction ) {
	if( ScrollerMoveBy == 'Holder' ) {
		var MoveX = ScrollerHolderWidth;
	} else {
		var MoveX = ScrollerSlideWidth;
	}
	var position = $('#' + ScrollerID ).position();
	if( Direction == 'Left' ) {
		if( position.left < 0 ) {
			$( '#' + ScrollerID ).animate({
				left: '+=' + MoveX + ''
			}, ' + ScrollerSpeed + ', function() {
			    // Animation complete.
			});				
		}	
	} else {
		var ScrollerWidth = $('#' + ScrollerID ).width();
		if( ( position.left - ScrollerSlideWidth - ScrollerHolderWidth ) > ( 0 - ScrollerWidth  ) ) {
			$( '#' + ScrollerID ).animate({
				left: '-=' + MoveX + ''
			}, ' + ScrollerSpeed + ', function() {
			    // Animation complete.
			});				
		}
	}		
}

$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};

$(document).ready( function() {

	/* for transparency shade */
	var mcHeight = $("#MainContent").height();
    var mHeight = $("#Menu").height();
    var setHeight = (mHeight>mcHeight)?mHeight:mcHeight;
    $("#MiddleHolder").height(setHeight);
    
    /* for slogan */
    var mcSlogan = $('div.MainContent div.Slogan');
    var mcText = $('div.MainContent div.Text');
    var divFadeOut = $('div.FadeOut');
    var divMiddleHolder = $('div#MiddleHolder');
    var pauseTime = 2000;
    if(mcSlogan !== undefined) {
    	mcSlogan.pause(pauseTime).fadeOut(1, function(){
    		// add fade
    		divFadeOut.switchClass('Small', 'Large', 100);
    		divMiddleHolder.switchClass('Small', 'Large', 100);
    		mcText.fadeIn(1);    		
    	});
    }else{ // no slogan show text directly
    	if(mcText !== undefined){ 
    		mcText.show();
    	}else{ // skip
    	}	
    }   
    
	InitMenu();
	InitBalloons();
	
	
	
	$('div.GoLeft').bind('click', function() {
		MoveScroller( 'Left' );		
	});

	$('div.GoRight').bind('click', function() {
		MoveScroller( 'Right' );		
	});
	
	//init background changer
	$("#Scroller").ChangeBackground({Resource: AbsPath + 'includes/Components/handleNewBackgroundRequest.php',
									 ImagePath: AbsPath + 'upload/Achtergrond/',
									 ContentTrigger: '#ckBgShowText' 											});
	
	//init actionviewer
	$('#Action').Actions({	activeImg: AbsPath + 'images/actionscroller_nav_active.jpg',
							inactiveImg: AbsPath + 'images/actionscroller_nav.jpg',
							requestUrl: AbsPath + 'includes/Components/handleActionsRequests.php',
							navDiv: '.Navigation',
							imageWrapper: '.Image'																});
});

function InitBalloons(){
	balloon1Div = $('div#balloon1');
	balloon2Div = $('div#balloon2');
	balloon3Div = $('div#balloon3');
	
	balloonContentActieCoupon = $('div#balloonContentActieCoupon');
	balloonContentSalonFinder = $('div#balloonContentSalonFinder');
	balloonContentTwitter = $('div#balloonContentTwitter');
	balloonContentAanmeldenNieuwsbrief = $('div#balloonContentAanmeldenNieuwsbrief');
	
	$('div.Footer div.Left .btnAchtergronden').bind('click', function(e) {
		if(balloon1Div.css('display') == 'none'){
			balloon2Div.css({display: 'none'});
			balloon3Div.css({display: 'none'});
			balloon1Div.css({display: 'block'});
		}else{
			balloon1Div.css({display: 'none'});
		}
	}); 
	
	$('div.Footer div.Right .btnActieCoupon').bind('click', function(e) {
		InitBalloon($(this), 257, balloonContentActieCoupon);
	});
	
	$('div.Footer div.Right .btnSalonFinder').bind('click', function(e) {
		InitBalloon($(this), 257, balloonContentSalonFinder);
	});	
	
	$('div.Footer div.Right .btnTwitter').bind('click', function(e) {		
		InitBalloon($(this), 257, balloonContentTwitter);
	});	
	
	$('div.Footer div.Right .btnAanmeldenNieuwsbrief').bind('click', function(e) {
		InitBalloon($(this), 340, balloonContentAanmeldenNieuwsbrief);
	});
}

function InitBalloon(btn, imageWidth, balloonContent) {
	var balloonContentDiv = balloonContent.parent();	
	if(balloonContent.css('display') == 'none' || balloonContentDiv.css('display') == 'none'){		
		var elementOffset = btn.offset();
		var btnWidth = btn.width();		
		
		// close all balloon divs
		var balloons = $('div.balloon');
		balloons.hide();
		
		// close all balloon content divs
		var balloons = $('div.balloonContent');
		balloons.hide();
		
		// alert(elementOffset.left +' -- ' + imageWidth +' -- ' + btnWidth  +' -- ' +(elementOffset.left - (imageWidth/2) + (btnWidth/2)));
		var offsetLeft = Math.round((elementOffset.left - (imageWidth/2) + (btnWidth/2)));
		
		balloonContentDiv.css({left: offsetLeft, display: 'block'});
		balloonContent.css({display: 'block'});			
	}else{		
		balloon3Div.css({display: 'none'});
		balloon2Div.css({display: 'none'});			
		balloon1Div.css({display: 'none'});
	}	
}

function resize(Background) {
	if( Background ) {
		if( !Background.aspectRatio ) {
			if( Background.offsetWidth && Background.offsetHeight ) {
				Background.aspectRatio = Background.offsetWidth / Background.offsetHeight;
			} else {
				return;
			}
		}
		var Width = window.innerWidth || document.body.clientWidth;
		var Height = window.innerHeight || document.body.clientHeight;
		if( ( Width/Height) > Background.aspectRatio ) {
			Background.style.width = '100%';
			Background.style.height = '';
		} else {
			Background.style.width = '';
			Background.style.height = '100%';
		}
	} else {
		alert("No background ID found");
	}
}

$( window ).bind( 'resize load', function() { 
	var BackgroundImg = document.getElementById( 'BackgroundImage' );
	resize(BackgroundImg);
	/* var BackgroundImg = document.getElementById( 'BackgroundImageOverlay' );
	resize(BackgroundImg);*/	
	//resize();
});


var orgMenuHeight;
var orgMiddleHolderHeight;
var orgMenuLiHeight = null;
var divMiddleHolder; 

function InitMenu(){
	orgMenuHeight = $('ul#Menu').height();
	orgMiddleHolderHeight = $('#MiddleHolder').height();
	divMiddleHolder = $('#MiddleHolder');
	
	$('ul#Menu li.Niv1 span').click(
        function() {
        	var thisli = $(this).parent();
        	var submenu = $('ul.SubMenu', thisli);
        	var orgSubmenuHeight = submenu.attr("scrollHeight");
        	
        	if(thisli.hasClass('Active')){ // active
        		// close menu item
        		submenu.animate({height: '0px'}, 400, function(){
        			thisli.removeClass('Active');        			
        		});        		       
        		
        		divMiddleHolder.animate({height: orgMiddleHolderHeight+'px'}, 400, function(){});   
        	}else{ // inactive
        		// close possible menu items
        		$('ul#Menu li.Niv1').each(function(index){
        			var menuLi = $(this);
        			if(menuLi.hasClass('Active')){
        				var submenuUl = $('ul.SubMenu', menuLi);
        				submenuUl.animate({height: '0px'}, 400, function(){
        					menuLi.removeClass('Active');
        				});
        			}else{ // skip
        			}
        		});
        		
        		// var h = submenu.outerHeight() + orgSubmenuHeight;
        		submenu.animate({height: orgSubmenuHeight+'px'}, 400, function(){
        			thisli.addClass('Active');
        		});
        		
        		h = orgMiddleHolderHeight+orgSubmenuHeight;
        		divMiddleHolder.animate({height: h+'px'}, 400, function(){});        		
        	}	
        }
  	);
	
	/* open allready active menu item
	$('ul#Menu li.Niv1 span').each(function(index){
		var thisspan = $(this);
		var thisli = thisspan.parent();
		
		if(thisspan.hasClass('Active')){			
			// var submenu = $('ul.SubMenu', thisli);
			thisli.removeClass('Active');
			thisspan.trigger('click');
		}else{ // skip
		}
	});*/
}


function HandleVoucherRequest(action, handlerUrl, data){
	$.ajax({
		type: 'POST',
		url: handlerUrl,
		data: {'action':action, 'data':data},
		dataType: 'json',
		async: false,
		error: function(xhr, status, errorThrown){
			alert('Er is een fout opgetreden tijdens het doorgeven van deze actie!');
		},     		
		success: function(data, status){
			if(data==undefined || data.rc==undefined){
				alert('Onverwachte reactie ontvangen van de server!');
			}else if(data.rc=='1'){
				var e = $('div.balloonData');
				e.html(data.c);				
			}else{
				alert(data.msg);
			}	   		
		}    	
	});
}

function loadProduct( productID ){
	//product bestaat, dus ophalen
	if( productID ){
		$.ajax({
			type: 'POST',
			url: AbsPath + 'includes/SpecialPages/Product/Ajax.php',
			data: 'productID=' + productID,
			dataType: 'json',
		    async: false,
			success: function(data) {
				$('#Producten').append(data.HTML);
				showProduct( data.productID );
			},				
		    error: function(xhr, status, errorThrown){
		        alert('Er is een fout opgetreden tijdens het doorgeven van deze actie!');           
		    }
		});
	} 
}

function hideProduct( productID ){
	//hide div 
	$("#Product"+productID).hide();
	$("#WhiteLayer").hide();
}

function showProduct( productID ){
	//show div 
	$("#Product"+productID).show();
	$("#WhiteLayer").show();
}

function toggleProduct( productID ){
	//controle of productID is meegegeven  
	if( productID ) { //true
		//controle of product div bestaat (in html)
		if( document.getElementById( 'Product'+productID ) ) { //true
			//block en hide div element
			showProduct( productID ); 
		} else {
			//div laden/opbouwen met inhoud
			loadProduct( productID );
			// <a onclick="myFun(this, id);"
			// myfunc(this, id){ a =
		}
	} else {
		//geen productID gegeven, alert
	}
	
}
function clickTab(tabElement, id, contentName){
	tab = $(tabElement);
	divProductID = 'Product'+id;
	
	// hideTabs
	tabs = $('div#'+divProductID+' a.ProdTab');
	tabs.addClass('Inactive');
	tabs.removeClass('Active');
	
	// hideTabsContent
	tabs = $('div#'+divProductID+' div.ProdContent');
	tabs.addClass('Inactive');
	tabs.removeClass('Active');	
		
	// showTab
	tab.addClass('Active');
	tab.removeClass('Inactive');

	// showTabContent
	element = 'div#'+divProductID+' div.Prod'+contentName;
	
	tabcontent = $(element);	
	tabcontent.addClass('Active');
	tabcontent.removeClass('Inactive');
}
					
function showTab(tab){
	tab.hasClass('Active');
	divFadeOut.switchClass('Active', 'Inactive', 1);
	alert(tab);	
} 

(function($) {
	$.fn.ChangeBackground = function(options) {
		options = $.extend( {
					Resource: '',
					ImagePath: '',
					ContentTrigger: null,
					Background: new Array()
		}, options);
		
		$.each( $(this).children('.Thumb'), function (i, r) {
			$(this).children('img').bind('click', function(e) {
				getImage($(this).parent('.Thumb').attr('id').substr(12));
			});
		});
		
		$(options.ContentTrigger).bind('click', function(e) {
			if($(this).is(':checked') === true) {
				$('#MainContent').show();
				$('#MiddleHolder').removeClass('Small').addClass('Large');
				$('.FadeOut').removeClass('Small').addClass('Large');
			} else {
				$('#MainContent').hide();
				$('#MiddleHolder').removeClass('Large').addClass('Small');
				$('.FadeOut').removeClass('Large').addClass('Small');
			}
		});
		
		function getImage( iImageId ) {
			$.ajax({
				   type: "POST",
				   url: options.Resource,
				   dataType: 'json',
				   data: {'iBackgroundId':iImageId },
				   async: false,
				   error: function(xhr, status, errorThrown) {
						alert('Unable to set new background');
				   },  
				   success: function( response ) {
					   	$('#ImageHolder').children('img').fadeOut(300, function(e) {
					   		$('#ImageHolder').children('img').attr('src', options.ImagePath + response.Picture).attr('src', options.ImagePath + response.Picture).delay(600).fadeIn(300, function(e) {
					   			
					   		});
					   	});
				   }
			});
		};
	}
})(jQuery);

(function($) {
	$.fn.Actions = function(options) {
		options = $.extend({
					activeImg: '',
					inactiveImg: '',
					requestUrl: '',
					navDiv: '',
					wrapper: null,
					imageWrapper: '',
					Current: 0,
					Actions: new Array()
		}, options);
		
		options.wrapper = $(this);
		
		$.ajax({
			   type: "POST",
			   url: options.requestUrl,
			   dataType: 'json',
			   data: {'paginaId':PageID },
			   async: false,
			   error: function(xhr, status, errorThrown) {
					$(this).css('display', 'none');
			   },  
			   success: function(msg) {
					$.each(msg, function(i , s) {
						options.Actions[i] = s;
					});

					init();
			   }
		});
		
		function init() {
			if(options.Actions.length <= 0) {
				options.wrapper.css('display', 'none');
				options.wrapper.next().removeClass('Action');
			} else {
				options.wrapper.children('.Wrapper').attr('href', options.Actions[0].Location);
				options.wrapper.children('.Wrapper').children('.Title').html(options.Actions[0].Title);
				options.wrapper.children('.Wrapper').children('.Text').html(options.Actions[0].Teaser);
				
				if( options.Actions[0].Image != undefined ) {
					options.wrapper.children('.Wrapper').children(options.imageWrapper).html('<img src="' + options.Actions[0].Image + '" alt="' + options.Actions[0].Title + '" />');
				}
				navigation();
			}
			
			//setInterval( 'slide()', 10000);
		};
		
		function navigation () {
			$.each(options.Actions, function(i) {
				var navImg = ( i == 0 ) ? options.activeImg : options.inactiveImg ;
				$(options.navDiv).html($(options.navDiv).html() + '<a href="javascript:void(0);"><img src="' + navImg + '" /></a>');
			});
			
			bindNavEvent();
		};
		
		function bindNavEvent() {
			$.each($(options.navDiv).children('a'), function(i) {
				$(this).bind('click', function(e) {
					setAction($(this), i);
				});
			});
		};
		
		function setAction( oNav, Action ) {
			$.each($(options.navDiv).children('a').children('img'), function(x){
				$(this).attr('src', options.inactiveImg);
				options.Current = Action;
			});
			
			oNav.children('img').attr('src', options.activeImg);
			
				options.wrapper.children('.Wrapper').hide(0, function() {
					options.wrapper.children('.Wrapper').children('.Title').html(options.Actions[Action].Title);
					options.wrapper.children('.Wrapper').children('.Text').html(options.Actions[Action].Teaser);
					options.wrapper.children('.Wrapper').attr('href', options.Actions[Action].Location);
						if( options.Actions[Action].Image != '' ) {
							options.wrapper.children('.Wrapper').children(options.imageWrapper).html('<img src="' + options.Actions[0].Image + '" alt="' + options.Actions[0].Title + '" />');
						} else {
							options.wrapper.children('.Wrapper').children(options.imageWrapper).html('');
						}
						
						options.wrapper.children('.Wrapper').delay(300).show();
				});
		};
		
		function slide () {
			//console.log('a');
		};
	}
})(jQuery);
