/* Image Zoom 2.0 andreaslagerkvist.com/jquery/image-zoom */
jQuery(document).ready(function() {
    jQuery(".booking").autoZoom({type:'booking',speed:600});
    jQuery(".voucher").autoZoom({type:'voucher',speed:600});
});

jQuery.fn.autoZoom = function (conf) {
	// Some config. If you set dontFadeIn: 0 and hideClicked: 0 imgzoom will act exactly like fancyzoom
	var config = jQuery.extend({
	    type:           'booking',// jab: initialize with either booking or voucher screen
	    borderWidth:    4,      // jab: total border width + margins of the imgzoom box other than its own negative margin (if any)
		speed:			270,	// Animation-speed of zoom
		dontFadeIn:		1,		// 1 = Do not fade in, 0 = Do fade in
		hideClicked:	0,		// Whether to hide the image that was clicked to bring up the imgzoom
		imageMargin:	15,		// Margin from image-edge to window-edge if image is larger than screen
		className:		'jquery-image-zoom',
		loading:		'Laden...',
		loadingImg:     '/js/ajax_small.gif',
		loadingImgWidth: 64,
		loadingImgHeight: 64
	}, conf);
	config.doubleSpeed = config.speed / 2; // Used for fading in the close-button

    return this.click(doOver);

	function doOver(e) {
		// Make sure the target-element is a link (or an element inside a link)
		var clickedElement = jQuery(e.target); // The element that was actually clicked
		var clickedLink = clickedElement.is('a') ? clickedElement : clickedElement.parents('a'); // If it's not an a, check if any of its parents is
		if (clickedLink) {
			// These functions are used when the imaeg starts and stops loading (displays either 'loading..' or fades out the clicked img slightly)
			clickedLink.oldText	= clickedLink.text();
			clickedLink.setLoadingImg = function () { clickedLink.text(config.loading);	};
			clickedLink.setNotLoadingImg = function () { clickedLink.text(clickedLink.oldText);	};
			if (jQuery('div.' + config.className).length) {	return false; }
			clickedLink.setNotLoadingImg();
			// Now set some vars we need
			var hideClicked	= 0; // Whether to hide clicked link (set in config but always true for non-image-links)
			var offset = clickedLink.offset(); // Offset of clicked link (or image inside)

		    var invoice = jQuery('<form class="cmxform" id="commentForm" method="post" action=""><img style="width:182px;height:19px;margin:5px auto 10px" width="182" height="19" src="images/info-offertes.gif" border="0" /> \
		        <p>Wil je een offerte op maat - of gewoon wat informatie? Vul onderstaand formulier in en je hoort van ons binnen de 24 uur - en dit het hele jaar door. Onze offertes zijn geheel vrijblijvend. Wat je (nog) niet weet mag je overslaan; Slechts enkele velden zijn verplicht. <a class="showvoucher" href="#">Voor kadobons kan je hier terecht</a>. Natuurlijk kan je ons ook opbellen (0496/02.29.03). We horen graag van je!</p> \
                <fieldset> \
                   <legend>Mijn Gegevens</legend> \
                   <p><label for="name">Naam:</label>        <input id="name" name="name" size="33" /></p> \
                   <p><label for="company"></label>          <input id="iscompany" name="iscompany" type="checkbox" /> <font id="isco">Ik ben hier voor mijn bedrijf</font></p> \
                   <p><label for="pref">Contact via:</label> <input id="prefe" name="pref" type="radio" value="Email" checked="checked" /> Email&nbsp;&nbsp; <input id="preft" name="pref" type="radio" value="GSM / Tel nr." /> GSM / Tel.</p> \
                   <p><label for="email">Email:</label>      <input id="email" name="email" size="33" /></p> \
                </fieldset> \
                <fieldset> \
                   <legend>Mijn Stoelmassage(s)</legend> \
                   <p><label for="date">Wanneer:</label>     <input id="date" name="date" type="text" size="18"> &nbsp;<small>Meerdere data? Vermeld ze hieronder!</small></p> \
                   <p><label for="location">Waar:</label>    <input id="location" name="location" type="text" size="33"></p> \
                   <p><label for="comment">Details:</label>  <textarea id="comment" name="comment" cols="38" rows="6"></textarea></p> \
                </fieldset><div id="mess"><strong></strong>  <input class="submit" type="submit" value="Bevestigen" /></div></form>');

		    var voucher = jQuery('<form class="cmxform" id="commentForm" method="post" action=""><img style="width:182px;height:19px;margin:5px auto 10px" width="182" height="19" src="images/kadobons.gif" border="0" /> \
		        <p>Via dit formulier kan je kadobons aanvragen. We zullen je dan zo snel mogelijk contacteren om je bestelling verder te bespreken. <a class="showinvoice" href="#">Klik hier</a> als je eerder z&eacute;lf van onze diensten gebruik wil maken of gewoon wat informatie zoekt. We zijn ook steeds bereikbaar op 0496/02.29.03.</p> \
                <fieldset> \
                   <legend>Mijn Gegevens</legend> \
                   <p><label for="name">Naam:</label>        <input id="name" name="name" size="33" /></p> \
                   <p><label for="company"></label>          <input id="iscompany" name="iscompany" type="checkbox" /> <font id="isco">Ik ben hier voor mijn bedrijf</font></p> \
                   <p><label for="pref">Contact via:</label> <input id="prefe" name="pref" type="radio" value="Email" checked="checked" /> Email&nbsp;&nbsp; <input id="preft" name="pref" type="radio" value="GSM / Tel" /> GSM / Tel.</p> \
                   <p><label for="email">Email:</label>      <input id="email" name="email" size="33" /></p> \
                </fieldset> \
                <fieldset> \
                   <legend>Mijn Kadobon(s)</legend> \
                   <p><label for="for">Voor wie:</label>              <input id="for" name="for" size="33" /> <small>(meerdere kan ook)</small></p> \
                   <p><label for="volume">Hoeveel:</label>            <input id="volume" name="volume" type="text" size="2" value="1" /> <font id="vollabel">massage per bon</font> &nbsp;<small>(we maken 1 bon per begunstigde)</small></p> \
                   <p><label for="deliverwho">Versturen naar:</label> <input id="who1" name="deliverwho" type="radio" value="Mij" checked="checked" /> Mij&nbsp;&nbsp; <input id="who2" name="deliverwho" type="radio" value="Begunstigde" /> Begunstigde</p> \
                   <p><label for="deliverhow">Hoe bezorgen:</label>   <input id="how1" name="deliverhow" type="radio" value="Email" checked="checked" /> Email <small>(om zelf uit te printen)</small>&nbsp;&nbsp; <input id="how2" name="deliverhow" type="radio" value="Post" /> Post <small>(2 dagen)</small></p> \
                   <p id="delto" style="display:none"><label for="deliverto">Email:</label><input id="deliverto" name="deliverto" size="33" /> <small>(meerdere kan ook)</small></p> \
                   <p><label for="details">Details:</label>           <textarea id="details" name="details" cols="38" rows="4"></textarea></p> \
                </fieldset><div id="mess"><strong></strong>           <input class="submit" type="submit" value="Bevestigen" /></div></form>');

		    var imgzoom	= jQuery('<div style="width:455px;height:554px;padding:8px 15px" class="content"></div>').hide().css('position', 'absolute').append(config.type=='voucher'?voucher:invoice).appendTo(document.body); // We don't want any class-name or any other contents part from the image when we calculate the new dimensions of the imgzoom


            var loadinfo = function(){
                jQuery("#commentForm input[name=pref]").click(function(evt) { var val = jQuery(this).val(); jQuery('fieldset label[for=email]').fadeOut(function(){jQuery(this).html(val+':').fadeIn('slow'); jQuery('#email').focus(); }); });
                jQuery("#commentForm input[name=iscompany]").click(function(evt) {
                    if (jQuery(this).attr('checked')) {
                        jQuery('#commentForm #isco').fadeOut(function(){jQuery(this).html('<input id="company" name="company" size="30" />').fadeIn('slow'); jQuery('#company').focus(); });
                        jQuery('fieldset label[for=company]').fadeOut(function(){jQuery(this).html('Bedrijf:').fadeIn('slow')});
                    } else {
                        jQuery('#commentForm #isco').fadeOut(function(){jQuery(this).html('Ik ben hier voor mijn bedrijf').fadeIn('slow')});
                        jQuery('fieldset label[for=company]').fadeOut(function(){jQuery(this).html('').fadeIn('slow')});
                    }
                });
            };
            var submitinvoice = function(form) {
                jQuery.ajax({
                    type: "POST",
                    url: "info.php",
                    data: "name="+ escape(jQuery(form).find('#name').attr('value')) + "&"
                        + "iscompany="+ escape(jQuery(form).find('input[name=iscompany]').attr('checked')) + "&"
                        + "company="+ escape(jQuery(form).find('#company').attr('value')) + "&"
                        + "pref="+ escape(jQuery(form).find('input[name=pref]:checked').attr('value')) + "&"
                        + "email="+ escape(jQuery(form).find('#email').attr('value')) + "&"
                        + "date=" + escape(jQuery(form).find('#date').attr('value')) + "&"
                        + "location=" + escape(jQuery(form).find('#location').attr('value')) + "&"
                        + "comment=" + escape(jQuery(form).find('#comment').attr('value')),
                    dataType: 'html',
                    success: function(data){
                        jQuery("#commentForm").fadeOut(function(){jQuery("#commentForm").replaceWith(data).fadeIn();});
                    }
                });
            };
            var submitvoucher = function(form) {
                jQuery.ajax({
                    type: "POST",
                    url: "info.php",
                    data: "name="+ escape(jQuery(form).find('#name').attr('value')) + "&"
                        + "iscompany="+ escape(jQuery(form).find('input[name=iscompany]').attr('checked')) + "&"
                        + "company="+ escape(jQuery(form).find('#company').attr('value')) + "&"
                        + "pref="+ escape(jQuery(form).find('input[name=pref]:checked').attr('value')) + "&"
                        + "email="+ escape(jQuery(form).find('#email').attr('value')) + "&"
                        + "for=" + escape(jQuery(form).find('#for').attr('value')) + "&"
                        + "volume=" + escape(jQuery(form).find('#volume').attr('value')) + "&"
                        + "deliverwho=" + escape(jQuery(form).find('input[name=deliverwho]:checked').attr('value')) + "&"
                        + "deliverhow=" + escape(jQuery(form).find('input[name=deliverhow]:checked').attr('value')) + "&"
                        + "deliverto=" + escape(jQuery(form).find('#deliverto').attr('value')) + "&"
                        + "details=" + escape(jQuery(form).find('#details').attr('value')),
                    dataType: 'html',
                    success: function(data){
                        jQuery("#commentForm").fadeOut(function(){jQuery("#commentForm").replaceWith(data).fadeIn();});
                    }
                });
            };
            var loadinvoice = function(){
                loadinfo();
                jQuery("#commentForm").validate({
                   errorPlacement: function(error, element) { element.parent().parent().nextAll("div#mess").children('strong').html(error); },
                   rules: { name: { required: true, minlength: 2 }, email: { required: true, email: { depends: function(element) { return jQuery("#prefe").attr("checked") }}, phone: { depends: function(element) { return jQuery("#preft").attr("checked") }} } },
                   messages: { name: { required: "Je naam niet vergeten a.u.b.", minlength: "Je naam is korter dan 3 tekens." }, email: { required: "Je hebt geen email adres of tel. nummer ingevuld.", email: "Je email-adres bevat een fout." } },
                   submitHandler: submitinvoice
                });
                jQuery("#date").datetimepicker({
                    dateFormat: 'dd/mm/yy',
                    dayNames: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
                    dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
                    dayNamesShort: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
                    firstDay: 1,
                    monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'],
                    monthNamesShort: ['Jan','Feb','Maa','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'],
                    showWeek: false,
                    nextText: 'Verder',
                    prevText: 'Vorige',
                    stepHour: 1,
    	            stepMinute: 5,
                	timeFormat: 'hhumm',
	                separator: ' om ',
	                hourGrid: 0,
	                minuteGrid: 0,
	                timeText: 'Start:',
                	hourText: 'uren',
                	minuteText: 'minuten',
                	currentText: 'Ga naar nu',
                	closeText: 'Klaar'
                });
                jQuery('.showvoucher').click(function(evt) { // bind voucher post-popup switch link
                    jQuery('#commentForm').fadeOut(function(){jQuery(this).replaceWith(voucher).fadeIn('slow', loadvoucher)});
                    return false;
                });
            };
            var loadvoucher = function(){
                loadinfo();
                jQuery("#commentForm").validate({
                   errorPlacement: function(error, element) { element.parent().parent().nextAll("div#mess").children('strong').html(error); },
                   rules: { name: { required: true, minlength: 2 }, email: { required: true, email: { depends: function(element) { return jQuery("#prefe").attr("checked") }}, phone: { depends: function(element) { return jQuery("#preft").attr("checked") }} }, volume: {required:true, digits:true, min:1, max:999} },
                   messages: { name: { required: "Je naam niet vergeten a.u.b.", minlength: "Je naam is korter dan 3 tekens." }, email: { required: "Je hebt geen email adres of tel. nummer ingevuld.", email: "Je email-adres bevat een fout." }, volume: { required:'Je bent vergeten het aantal massages per bon in te vullen.', digits:'Gebruik cijfers voor het aantal massages per bon a.u.b.', min:'Minimum 1 massage per bon...', max:'Wil je echt meer dan 999 massages per bon?' } },
                   submitHandler: submitvoucher
                });
                jQuery("#volume").change(function(){if (jQuery(this).attr('value') != '1')jQuery('#vollabel').html('massages per bon')});
                jQuery("#commentForm input[name=deliverwho]").click(function(evt) {
                    if (jQuery(this).val() == 'Mij') { jQuery('#delto').fadeOut(); jQuery('#details').fadeOut(function(){jQuery(this).attr('rows','4').fadeIn('slow')}); }
                    else jQuery('#details').fadeOut(function(){jQuery('#delto').fadeIn('slow');jQuery(this).attr('rows','2').fadeIn('slow')});
                });
                jQuery("#commentForm input[name=deliverhow]").click(function(evt) {
                    var val = jQuery(this).val() == 'Email' ? 'Email:' : 'Adres:';
                    jQuery('fieldset label[for=deliverto]').fadeOut(function(){jQuery(this).html(val).fadeIn('slow')});
                });
                jQuery('.showinvoice').click(function(evt) { // bind invoice post-popup switch link
                    jQuery('#commentForm').fadeOut(function(){jQuery(this).replaceWith(invoice).fadeIn('slow', loadinvoice)});
                    return false;
                });
            };

			if (config.type == 'voucher') loadvoucher();
            else loadinvoice();

            jQuery.validator.addMethod("phone", function(phone_number, element) {
                phone_number = phone_number.replace(/\s+/g, "");
            	return this.optional(element) || phone_number.length > 9 && phone_number.match(/^[0-9\s\-\/\.\+\(\)\[\]]+$/);
            }, "Je GSM/tel.nr. is te kort of bevat speciale tekens.");

            var imgzoomBefore = { width: clickedLink.outerWidth(), height: clickedLink.outerHeight(), left: offset.left, top: offset.top };
		    var imgzoomAfter = { width:	455, height: 554 };
			var windowDim = { width: jQuery(window).width(), height: jQuery(window).height() };
			// Center imgzoom
			imgzoomAfter.left = (windowDim.width - imgzoomAfter.width) / 2 + jQuery(window).scrollLeft();
			imgzoomAfter.top = (windowDim.height - imgzoomAfter.height) / 2 + jQuery(window).scrollTop();

			var closeButton	= jQuery('<a class="imgZoomClose" href="#">Close</a>').appendTo(imgzoom).hide(); // The button that closes the imgzoom (we're adding this after the calculation of the dimensions)
			if (hideClicked) clickedLink.css('visibility', 'hidden');
			// Now animate the imgzoom from its small size to its large size, and then fade in the close-button
			imgzoom.addClass(config.className).css(imgzoomBefore).show().animate(imgzoomAfter, config.speed, "swing", function () { closeButton.fadeIn(config.doubleSpeed); jQuery("#commentForm input[name=name]").focus(); });
			// This function closes the imgzoom
			var hideImgzoom = function () { closeButton.fadeOut(config.doubleSpeed, function () {
			    imgzoom.animate(imgzoomBefore, config.doubleSpeed, function () { clickedLink.css('visibility', 'visible'); imgzoom.remove(); });
    	    }); return false; };
    	    // Bind the close button
			closeButton.click(hideImgzoom);
			// Finally return false from the click so the browser doesn't actually follow the link...
			return false;
		}
	}
};

