/*-----------------------------------------------------------------------------
Javascript Common Functions

author:    bubi blomer
website:   http://www.maal4.nl
-----------------------------------------------------------------------------*/

/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<div id='preview'><table><tr class='top'><td class='topLeft'>&nbsp;</td><td class='topMiddle'>&nbsp;</td><td class='topRight'>&nbsp;</td></tr><tr><td class='middleLeft'>&nbsp;</td><td class='imageContainer'><img src='"+ this.rel +"' alt='Image preview' /></td><td class='middleRight'>&nbsp;</td></tr><tr><td class='bottomLeft'>&nbsp;</td><td class='bottomMiddle'>&nbsp;</td><td class='bottomRight'>&nbsp;</td></tr></table></div>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.show();						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

function mandjeClose(){
	confirm('Jouw maandje is niet leeg, wilt uw nog weg gaan?');
};

/* =Jquery
-----------------------------------------------------------------------------*/

$(document).ready(function() {
	
	
	
	//orange color if levertijd is Unavailable
	if($("img.levertijdCheck[src*='iconUnavailable']").length){
		$("img.levertijdCheck").parent().next('span').css({'color':'#FF9933'});
	};
	
	//if mandje not leeg do alert on window close
	if ($('td.artikel').length >=2 ){
		//console.log('yes do onunload')
		//$('body').attr('onUnload','mandjeClose()')
	};
	
	//image Hover for Mandje
	imagePreview();
	
	//Hover last tbody tr
	$('table.mandjeTable tbody.withBg tr:last, table.mandjeTable tbody.withBg tr:not(".last")').hover(function() {
		$(this).css({
			'background':'url(/images/bgHoverTrLast.png) no-repeat'
		});
	}, function() {
		$(this).css({
			'background':'url(/images/bgTrLast.png) no-repeat'
		})
	});
	
	//Styling last tbody tr
	$('table.mandjeTable tbody.withBg tr:last').css({
		'height':'28px',
		'background':'url(/images/bgTrLast.png) no-repeat'
	});
		
	//Hide last <hr class="sideDivider" />
	$('#colRight .rightBox hr.sideDivider:last').hide();
	
	
	// LEFT MENU FUNCTIONS
		// Open active subActive menu
		if( $('ul li a.special').hasClass('subActive') ) {
			$('ul li a.special.subActive').parents('ul').show();
			$('ul li a.special.subActive').parents('ul').siblings('a').addClass('subActive');
			$('ul li a.special.subActive').parents('ul.subCategorie').siblings('a.mainCategorie').addClass('active');
		} else if( $('ul li a.last').hasClass('subActive') ){
			$('ul li a.last.subActive').parents('ul').show();
			$('ul li a.last.subActive').parents('ul.subCategorie').siblings('a.mainCategorie').addClass('active');
		};
		
        $("#middleLeftMenu li a.mainCategorie").click(function(){
    		
    		if($(this).next("ul").is(":visible")) {
    			$(this).next("ul").slideUp("slow");
    			$(this).toggleClass("active");
    		};
    		
    		if($(this).next("ul").is(":hidden")) {
    			$("#middleLeftMenu").find("a.subWithCategories").next("ul").slideUp("slow");
    			$("#middleLeftMenu").find("a.subWithCategories").removeClass("subActive");
    			$("#middleLeftMenu").find("a.active").next("ul").slideUp("slow");
    			$("#middleLeftMenu").find("a.active").removeClass("active");
    			$(this).toggleClass("active");
    			$(this).next("ul").slideDown("slow");
    		};
    		
    		return false;
    	});
    	
    	$("#middleLeftMenu li a.subWithCategories").click(function(){
    	   if($(this).next("ul").is(":visible")) {
    	        $(this).toggleClass('subActive');
    			$(this).next("ul").slideUp("slow");
    		};
    		
    		if($(this).next("ul").is(":hidden")) {
                $("#middleLeftMenu").find("a.subWithCategories").next("ul").slideUp("slow");
    			$("#middleLeftMenu").find("a.subWithCategories").removeClass("subActive");
                $(this).toggleClass('subActive');
                $(this).next("ul").slideDown("slow");
    		};
    		
    		return false;
    	});
    
    //Active Submenu LI BG
	//var test = $('a.special.subActive').parents('li').get(1);
	//console.log($(test).find('a.subWithCategories').html())
	//$(test).find('a.subWithCategories').addClass('subActive');
	
	// LIGHTBOX FUNCTIONS
		
		$('a.lightbox').click(function() {
			
			var imgSrc = $(this).attr('href');
			//console.log(img.attr('src'));			
			
			$('#imageLightbox').modal({
				opacity: 90,
				overlayCss: {
			
					backgroundColor: '#FFF',
					cursor: 'hand'
				
				},
				containerCss: {
			
				minHeight: 400,
				minWidth: 400,
				backgroundColor: 'transparent',
				border: 'none'
				
				},
				overlayClose: true,
				onOpen: function(dialog){
					dialog.overlay.show();
					dialog.overlay.click(function() { $.modal.close(); })
					dialog.container.show();
					dialog.container.css({'top':'50px'})
					dialog.data.fadeIn(100);
					dialog.data.click(function() { $.modal.close(); })					
				},
				onShow: function(dialog) {
					$('#imageLightbox td.imageContainer').append('<img src="'+imgSrc+'" alt="" width="350" />');
					$('#simplemodal-container').width();
					$('#imageLightbox td.imageContainer').width();
					var w = $('#imageLightbox td.imageContainer').width();
					$('#simplemodal-container').width(w+60);
					//alert($('#imageLightbox td.imageContainer img').width());
				},
				onClose: function() {

					$.modal.close();
					$('#imageLightbox td.imageContainer').empty();
					
				},
				closeHTML: '<a class="specialClose" href="javascript:return false;" class="" title="Close"><img src="/images/sluiten.png" alt=""></a>',
				close: false
			})
			
			
			return false;
			
		});
    
    //aanbevelen modal
    $('#aanbevelen').click(function() {
    	
    	var productId = $(this).attr('rel');
		
		$('#productIdAanbevelenUrl').val(window.location);
		
		$('#aanbevelenForm').parents('table').width('430px'); //Same size as minWidth of MODAL
    	    	
    	
    	$('#aanbevelenModal').modal({
			opacity: 90,
			overlayCss: {
				
				backgroundColor: '#FFF',
				cursor: 'hand'
				
			},
			containerCss: {
			
				minHeight: 500,
				minWidth: 430,
				backgroundColor: 'transparent',
				border: 'none'
				
			},
			overlayClose: true,
			close: false,
			onOpen: function(dialog) {
				
				dialog.overlay.show();
				dialog.overlay.click(function() { $.modal.close(); })
				dialog.container.show();
				dialog.data.fadeIn(100);
				
				$('#aanbevelenForm').validate({
					submitHandler: function(form) {
						
						if($(form).valid()) { 
							var formData = $(form).serialize();
							//console.log(formData);
							
							$.post("/scripts/handleAjax.php", 
									formData,
									function(data, textstatus){
										
										//if post was succesful show thank you page
										if(data === "true") {
											//console.log(data);
											//hide original form after ajax post
											$('#aanbevelenForm').hide();
											
											//show hidden thank you form
											$('#AanbevelenFormThanks').show();
										} else { 
										
											$('#aanbevelenForm').hide();
											$('#AanbevelenFormError').show();
											
										}
										
									}, "text");
						}
					}

				});
			}
    	});
    	
    	return false;
    	
    });
    
    //stelVraagModal modal
    $('#stelVraag').click(function() {
    	
    	var productId = $(this).attr('rel');
    	
    	//$('#productIdStelVraag').val(productId)
		
		$('#stelVraagForm').parents('table').width('430px'); //Same size as minWidth of MODAL
    	    	
    	
    	$('#stelVraagModal').modal({
    		opacity: 90,
			overlayCss: {
				
				backgroundColor: '#FFF',
				cursor: 'hand'
				
			},
			containerCss: {
			
				minHeight: 500,
				minWidth: 430,
				backgroundColor: 'transparent',
				border: 'none'
				
			},
			overlayClose: true,
			close: false,
			onOpen: function(dialog) {
				
				dialog.overlay.show();
				dialog.overlay.click(function() { $.modal.close(); })
				dialog.container.show();
				dialog.data.fadeIn(100);
				
				$('#stelVraagForm').validate({
					submitHandler: function(form) {
						
						if($(form).valid()) { 
						
							var formData = $(form).serialize();
							//console.log(formData);
							
							$.post("/scripts/handleAjax.php", 
									formData,
									function(data, textstatus){
										//console.log(data)
										//console.log(textstatus)
										//if post was succesful show thank you page
										if(data === "true") {
											//hide original form after ajax post
											$('#stelVraagForm').hide();
											
											//show hidden thank you form
											$('#stelVraagFormThanks').show();
											
										} else { 
										
											$('#stelVraagForm').hide();
											$('#stelVraagFormError').show();
											
										}
									}, "text");
						}
						
					}

				});
			}
    	});
    	
    	return false;
    	
    });
    
    // Verwijder MAndje Modal
    $('a.verwijderModal').click(function() {
    	
    	var articleName = $(this).attr('rel');
    	var articleId = $(this).attr('id');
    	
    	$('#verwijderModalOverlay').modal({
    		/* opacity: 100, */
    		overlayCss: {
    		
			    backgroundColor: '#FFF',
			    cursor: 'hand'
			    
			  },
			  containerCss: {
			   
			    height: 130,
			    width: 255,
			    backgroundColor: 'transparent',
			    background: 'transparent url(/images/bgPopup.png) no-repeat',
			    border: '1px solid transparent',
			    padding: '10px 20px',
			    top: '10%'
			    
			  },
			  onOpen: function(dialog){
			  
			  	dialog.overlay.show();
				$('#simplemodal-container').css({'top':'20%'})
				dialog.container.show();
				$('#articleName').empty();
				$('#articleName').append(articleName);
				$('#verwijderId').val(articleId);
				dialog.overlay.click(function() { $.modal.close(); })
				dialog.data.fadeIn(100);
				$('#popupNee').click(function() {
					$.modal.close();
					return false;
				});
				
			  },
			  close: false
    	});
    	
    	return false;
    });
	
	//loginForms
	$('#showAccountAanmaken').click(function(){
		
		$('#loginTerug').removeClass('terugHome');
		
		$('#loginForm').slideUp('fast', function() {
			$('#showAccountAanmaken').fadeOut('fast', function() {
				$('#showAccountAanmakenForm').slideDown('slow');
			});
			
		});
		
		return false;
	});
	
	//login terug buttun functionality
	$('#loginTerug').click(function() {
		
		if($(this).hasClass('terugHome')) { 
			history.back();
		} else {
			$('#showAccountAanmakenForm').slideUp('slow', function() {
				$('#loginForm').slideDown('fast');
				$('#loginTerug').addClass('terugHome');
				$('#showAccountAanmaken').fadeIn();
			});
		}
		
		return false;
	});
	
	//afwijkend click
	$('#afwijkend').click(function() {

		$('#afwijkendAfleveradres').slideDown('slow');
		
	});
	
	//Bovenstaand click
	$('#bovenstaand').click(function() {

		$('#afwijkendAfleveradres').slideUp('slow');
		
	});
	
	/* validation defaults */
	
	jQuery.validator.setDefaults({
		errorPlacement: function(error, element){
			element.parent().append(error)
		},
		errorElement: "span",
		
		rules: {
			//LoginForm
			sEmail2: {
				required: true,
				email: true
			},
			sPassword: {
				required: true
			},
			// END LoginForm
			
			//----------------------------

			//Account Aanmaken Form
			iSex: {
				required: true
			},
			sNaam: {
				required: true
			},
			sAchter: {
				required: true
			},
			sStraat: {
				required: true
			},
			iHuis: {
				required: true,
				digits: true
			},
			sPostcode: {
				required: true,
				minlength: 6,
				maxlength: 6
			},
			sWoonplaats: {
				required: true
			},
			sTel: {
				required: function() {
					var bol = $('#sMob').val() == '';
					return bol;
				},
				phone: true
			},
			sMob: {
				required: function() {
					var bol = $('#sTel').val() == '';
					return bol;
				},
				phone: true
			},
			sEmail: {
				required: true,
				email: true,
				remote: {
					url: '/scripts/check.php?do=email',
					type: 'get',
					data: {
						v: function(){
							return $('#sEmail').val();
						}
					}
				}
			},
			emailAanmaken: {
				required: true,
				email: true
			},
			//Afwijkend Adres
			sStraat1: {
				required: "#afwijkend:checked"
			},
			iHuis1: {
				required: "#afwijkend:checked",
				digits: true
			},
			sPostcode1: {
				required: "#afwijkend:checked",
				minlength: 6,
				maxlength: 6
			},
			sWoonplaats1: {
				required: "#afwijkend:checked"
			},
			//Aanbevelen Adres
			naamAanbevelen: {
				required: true
			},
			emailAanbevelen: {
				required: true,
				email: true
			},
			naamOntvangerAanbevelen: {
				required: true
			},
			emailOntvangerAanbevelen: {
				required: true,
				email: true
			},
			berichtAanbevelen: {
				required: true
			},
			//stelVraag Adres
			naamStelVraag: {
				required: true
			},
			emailStelVraag: {
				required: true,
				email: true
			},
			berichtStelVraag: {
				required: true
			},
			//email vergeten form
			sEmailVergeten: {
				required: true,
				email: true
			},
			//passwordWijzigen
			pw: {
				required: true
			},
			pw1: {
				required: true
			},
			pw2: {
				required: true,
				equalTo: '#pw1'
			}
		},
		messages: {
			emailLogin: "Email is incorrect",
			passwordLogin: "Nog Nodig",
			sEmail: {
				remote: 'dit e-mail adres is al in gebruik, klik <a href="#" class="emailVergeten">hier</a> als u uw wachtwoord vergeten bent.'
			}
			
		}
	});
	
	$.validator.addMethod("lettersonly", function(value, element) {
        return this.optional(element) || /^[a-z]+$/i.test(value);

	}, "De postcode moet bestaan uit 4 cijfers en 2 letters");
	
	$.validator.addMethod("phone", function(phone_number, element) {
		var digits = "0123456789";
		var phoneNumberDelimiters = "()- ext.";
		var validWorldPhoneChars = phoneNumberDelimiters + "+";
		var minDigitsInIPhoneNumber = 10;
		s=stripCharsInBag(phone_number,validWorldPhoneChars);
		return this.optional(element) || isInteger(s) && s.length == minDigitsInIPhoneNumber;
	}, "Er is geen correct telefoonnummer ingevoerd");
	
	function isInteger(s) { 
		var i;
		for (i = 0; i < s.length; i++) {
			// Check that current character is number.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		
		// All characters are numbers.
		return true;
	};
	
	function stripCharsInBag(s, bag) { 
		var i;
		
		var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++) {
			// Check that current character isn't whitespace.
			var c = s.charAt(i);
			if (bag.indexOf(c) == -1) returnString += c;
		}
		
		return returnString;
	};
	
	/* formValidation */
	
	$('.submit').click(function() {
		var thisForm = $(this).parents('form');
		if(thisForm.valid()) {
			
			if($(thisForm).attr('id') === 'ingeloggedForm'){
				if($(this).attr('id') === 'previousStap'){
					doSubmit('previous')
				} else {
					doSubmit('next');
				}
				
			} else {
				thisForm.submit();
			}
			
			
		};
		//console.log(thisForm.attr('id'));
		return false;
	});
	
	/*
	 * Translated default messages for the jQuery validation plugin.
	 * By Joost Baaij http://www.spacebabies.nl/ joost@spacebabies.nl
	 * Language: NL
	 * Skipped date/dateISO/number.
	 */
	jQuery.extend(jQuery.validator.messages, {
		required: "Dit veld is verplicht.",
		maxlength: jQuery.format("U kunt niet meer dan {0} karakters invoeren."),
		minlength: jQuery.format("U dient minimaal {0} karakters in te voeren."),
		rangelength: jQuery.format("U dient minimaal {0} en maximaal {1} karakters in te voeren."),
		email: "Een geldig emailadres is verplicht.",
		url: "Een geldig URL is verplicht.",
		date: "Een geldige datum is verplicht.",
		number: "Een geldig getal is verplicht.",
		digits: "Gebruik alleen cijfers.",
		equalTo: "Herhaal de invoer nogmaals.",
		range: jQuery.format("U dient een waarde tussen {0} en {1} in te voeren."),
		max: jQuery.format("U dient een waarde kleiner dan of gelijk aan {0} in te voeren."),
		min: jQuery.format("U dient een waarde groter dan of gelijk aan {0} in te voeren."),
		creditcard: "Een geldig creditcardnummer is verplicht."
	});
	
	//Click handler for error modal from already used emailadres
	$("a.emailVergeten").live("click", function() {
		
		
		var email = $(this).parent().siblings('input.error').val();
		//console.log(email);
		
		$('#wachtwoordVergetenModal').modal({
			opacity: 90,
			overlayCss: {
				backgroundColor: '#FFF',
				cursor: 'hand'
			},
			containerCss: {
				minHeight: 500,
				minWidth: 430,
				backgroundColor: 'transparent',
				border: 'none'
			},
			overlayClose: true,
			close: false,
			onOpen: function(dialog) {
				dialog.overlay.show();
				dialog.overlay.click(function() { $.modal.close(); })
				dialog.container.show();
				dialog.data.fadeIn(100);
				//add the email
				$('#sEmailVergeten').val(email);
				$('#wachtwoordVergetenForm').validate({
					submitHandler: function(form) {
						if($(form).valid()) { 
							var formData = $(form).serialize();
							//console.log(formData);
							$.post("/scripts/handleAjax.php", 
									formData,
									function(data, textstatus){
										//if post was succesful show thank you page
										if(data === "true") {
											//hide original form after ajax post
											$('#wachtwoordVergetenForm').hide();
											
											//show hidden thank you form
											$('#wachtwoordVergetenFormSucces').show();
										} else if (data === 'false') {
											
											$('#wachtwoordVergetenForm').hide();
											$('#wachtwoordVergetenFormError').show();
											
										}
									}, "text");
						}
					}

				});
			}
		});
		return false;
	});
	
	//Hide ul.acnhorList if empty
	if($('ul.acnhorList li').length === 0) { $('ul.acnhorList').hide(); }
	
	//betalling methode click function
	$('#idealBetaling').click(function() {
		$('#ideal').attr('checked','checked');
		$(this).parents('form').submit();
		return false;
	})
	
	$('#vooruitBetaling').click(function() {
		$('#vooruit').attr('checked','checked');
		$(this).parents('form').submit();
		return false;
	})
	
	//no image click cancel
	$('a.noImage').click(function() {
		return false;
	});
	
	$('#top').click(function() {
		window.location="/";
	});
	
	
}); // END DOCUMENT READY FUNCTION