jQuery.fn.debug = function() {
  return this.each(function(){
    $.log(this);
  });
};
jQuery.log = function(message) {
  if( window.console && $.browser.mozilla ) {
	console.debug(message);
  } else {
 //   alert(message);
  }
};
jQuery.numFormat = function( float, decimals, sep1, sep2 ){
	var out = '';
	var arr = String( float ).split('.');
	
	for( var i=0; i<arr[0].length; i++ ){
		if( (arr[0].length-i)==3 && i>0 ){
			out += sep2;
		}
		out += arr[0].charAt(i);	
	}
	out += sep1;
	if( arr.length == 1 ){
		out += '-';
	} else {
		for( var i=0; i<decimals; i++ ){
			if( !arr[1].charAt(i) ){
				out += '0';
			} else {
				out += arr[1].charAt(i);
			}
		}
	}
	return out;
}
jQuery.moneyFormat = function( float ){
	return $.numFormat( float, 2, ',', '.' );	
}

jQuery.printSelection = function (domid){
	  //var content=$(domid).html();
	  var content = "";
	  $(domid + " div.printable").each(function(i, e) {		  
		  content = content + $(e).html();
	  });

	  var imgTag = '';
	  if ($('#slide' + window.site.currentSlide).length > 0) {
		  var imgUrl = $('#slide' + window.site.currentSlide).css('background-image');
		  imgUrl = imgUrl.replace('url', 'src');
		  imgUrl = imgUrl.replace('(', '=');
		  imgUrl = imgUrl.replace(')', '');
		  imgTag = '<img ' + imgUrl + ' border="0"/>';		  
	  }
	  var imgLogo = '<div><span><img src="img/delelie_print_logo.jpg" border="0"/></span><div class="logotext">www.chocolaterie.nl</div></div>';
	  var pwin=window.open('','print_content','width=800,height=600');
	  var head = '<head><link rel="stylesheet" type="text/css" href="css/print.css" /></head>';	
	  var adres = '<div class="textcol textcol3"><div class="textholder"><h1></h1>';
	  adres += '<br><span><b>Chocolaterie De Lelie</b></span><br><span>Voorstraat 10</span><span class="seperator">|</span><span>2611 JP Delft</span><br><span>T 015 212 03 63</span><span class="seperator">|</span>E info@chocolaterie.nl</div></div>';
	  pwin.document.open();
	  pwin.document.write('<html>'+head+'<body onload="window.print()">' + imgLogo + '<div class="clear"></div><div id="printcontent">' + content + imgTag +  adres  + '</div><div class="clear"></div>' + imgLogo + '</body></html>');
	  pwin.document.close();

	  //setTimeout(function(){pwin.close();},1000);
	
} 

// Create Namespace
Site = {};
// MainClass
Site.Main = function(){
	this.initialize();	
}

Site.Main.prototype = {
	initialize: function(){
		$.log( 'Site.Main.initialize' );
		this.initListItems();

		this.initSlideShow();

		Cufon.replace("h2");

		switch( window.template ){
			case "workshop_reserveren":
				this.workshopForm = new WorkshopForm("#frm_reserveren");
				break;
			case "workshop_kadobon":
				this.workshopForm = new KadobonForm("#frm_kadobon");
				break;
			case "arrangement_reserveren":
				this.workshopForm = new ArrangementForm("#frm_reserveren");
				break;
			case "arrangement_kadobon":
				this.workshopForm = new KadobonForm("#frm_kadobon");
				break;
			case "dynamicform":
				this.form = new DynamicForm("#dynamicform");
				break;
			case "workshop_details":
			case "arrangementen_details":
				this.initDetails();
				break;
		}
        
		if ($("#afdrukken").length > 0 ) {
			$.log( 'Afdrukken bestaat' );
			//$.printSelection('#contentarea');
			$("#afdrukken a").bind('click', function(){
				$.log( 'Afdrukken clicked' );
				$.printSelection('#contentarea');
			} );
		}        


	},
	initListItems: function(){
		var holder = this;
		$(".listitem").hover(function(){
								$(this).addClass("listitem_hover");
							},
							function(){
								$(this).removeClass("listitem_hover");
							})
						.click(function(){
								window.document.location = ( $(".link a", $(this)).attr("href") );
							});
	},
	initDetails: function(){
		$.log( "initDetails" );
		$("#extra_details").hide();
		$("#extra_infobar").click( function(){ $("#extra_details").toggle("fast"); } )
							.hover( function(){ $(this).addClass("pointer"); },
									function(){ $(this).removeClass("pointer"); })
		
	},
    initSlideShow: function() {
		$.log("initSlideShow");
		//window.site.currentSlide = -1;
        this.replaceImageDivs();
        var slideCount = 0;
        $("#slideshow div.item").each(function(i, e) {
            $(e).hide();
            $(e).attr('id', 'slide' + i);
			
            slideCount++;
        });
        this.slideCount = slideCount;
        this.currentSlide = -1;
        setTimeout(this.showNextSlide, 10);
        if (this.slideCount > 1) {
            setInterval(this.showNextSlide, 5000);
        }
    },
    replaceImageDivs: function() {
        var holder = this;
        $("div.img").each(function(i, e) {
            $(e).replaceWith(holder.replaceImageDiv(e));
        });
    },
    replaceImageDiv: function(e) {
        var html = "";
        var src = $("div.src", e).html();
        var alt = $("div.alt", e).html();
//        var href = $("div.href", e).html();
//        var title = $("div.title", e).html();
		var href = "";
		
        if (alt == "" || alt == null) alt = "";

//        html += "<img src=\"" + src + "\" alt=\"" + title + "\" title=\"" + alt + "\" />";
        html += "<img src=\"" + src + "\" alt=\"Duijndam Caravans\" />";
		
        if (href != "" && href != null) {
            html = "<a href=\"" + href + "\" title=\"" + alt + "\">" + html + "</a>";
        }
        return html;
    },
    showNextSlide: function() {
        $.log('showNextSlide ' + window.site.currentSlide + ' ' + window.site.slideCount);
        $('#slide' + window.site.currentSlide).fadeOut(2000);
        if (window.site.currentSlide++ > window.site.slideCount - 2) {
            window.site.currentSlide = 0;
        }
        $('#slide' + window.site.currentSlide).fadeIn(1500);
    }
};

Form = function( id ){
	this.id = id;
	this.init();
}
Form.prototype = {
	init: function(){
		var holder = this;
		$("#submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
							.click(function(){holder.onReleaseSubmit()});
	},
	onReleaseSubmit: function(){
		$.log( "submit released" );
		if( this.checkForm() ){
			$.log( "Form okay send it" );
			// remove hidden form elements from form so they won't be posted
			$( this.id + " div:hidden").remove();
			$( this.id ).submit();
		} else {
			$.log("Form error");
			$("#errormessage").fadeIn();
		}
	},
	oddEven: function(){
		$(this.id + " div.row").each( function(i,e){
							//$.log( i );
							if(i%2){
								$(this).addClass("even");
							} else {
								$(this).addClass("odd");
							}
						} );
	},
	checkForm: function(){
		var check = true;
		var holder = this;
		$( this.id + " div.row:visible").each( function(i,e){
													if( !holder.checkRow( e ) ) check = false;
												} );
		return check;
	},
	checkRow: function( e ){
		$.log( 'Form.checkRow' );
		var check = true;
		var label = $("label", e).html();
		
		if( label == null ) return true;
		
		// basic check
		if( label.indexOf("*") > -1 ){
			$.log( "checking row : "+$("label", e).html() );
			// verplicht
			var children = $("div.value", e).children();
			var type = $(children[0]).attr("class");
			
			//$.log(type);
			switch( type ){
				case "frm_text hasDatepicker":
				case "frm_text":
				case "formtext":
					$.log( "frm_text " + label + " = " +  $("input",e).val() );
					if( !$("input",e).val() ){
						this.setError( e, true );
						check = false;
					} else {
						this.setError( e, false );
					}
					break;
				case "frm_radio":
				case "formradio":
				case "radiorow":
					if( $("input[type='radio']:checked", e).val() == undefined ){
						this.setError( e, true );
						check = false;						
					} else {
						this.setError( e, false );
					}
					break;
				case "frm_select":
				case "frmradio":
					$.log( "frm_select " + $(".frm_select option:selected", e).val() == 0 );
					if( $("select option:selected", e).val() == 0  ){
						this.setError( e, true );
						check = false;						
					} else {
						this.setError( e, false );
					}
				default:
					break;
			}
		}

		if( !this.customRowCheck( e ) ) check = false;
		
		return check;
	},
	sentenceCase: function( val ){
		return val.substring(0,1).toUpperCase() + val.substr(1,val.length-1);
	},
	customRowCheck: function(e){
		// can be overridden in subclass
		return true;
	},
	validateEmail: function( email ){  
		$.log( "validateEmail " + email );
		var RE_EMAIL = /^[a-zA-Z.0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+.[a-z]{2,4}$/;
		return RE_EMAIL.test( email );
	},
    validateZip: function(zip) {
		$.log( "validateZip " + zip );
        var RE_ZIP = /^[0-9]{4}\s*[a-zA-Z]{2}$/;
        return RE_ZIP.test( zip );
    },	
	validatePhone: function(phone){
		$.log( "validatePhone " + phone );
		return( phone.replace(/\D/g,"").match(/[0-9]{10}/));
	},
	setError: function( e, error ){
		if( error ){
			$("label", e).addClass("error");
		} else {
			$("label", e).removeClass("error");
		}
	}
}

Form.prototype.customRowCheck = function( e ){
	var check = true;
	var label = $("label", e).html();
	// custom checks
	if( label.toLowerCase().indexOf("mail") > -1 ){
		if( !this.validateEmail( $("input",e).val() ) ){
			this.setError( e, true );
			check = false;
		} else {
			this.setError( e, false );
		}
	}

	if( label.toLowerCase().indexOf("postcode") > -1 ){
		if( !this.validateZip( $("input",e).val() ) ){
			this.setError( e, true );
			check = false;
		} else {
			this.setError( e, false );
		}
	}
	
	if( label.toLowerCase().indexOf("telefoon") > -1 && label.indexOf("*") > -1 ){
		if( !this.validatePhone( $("input",e).val() ) ){
			this.setError( e, true );
			check = false;
		} else {
			this.setError( e, false );
		}
	}
	
	if( $("#frm_voorwaarden",e).length > 0 ){
		if( !$("#frm_voorwaarden:checked").val() ){
			this.setError( e, true );
			check = false;
		} else {
			this.setError( e, false );
		}
	}
	
	return check;	
}


WorkshopForm = function( id ){
	$.log( 'WorkshopForm' );
	this.id = id;
	this.init();	
}
// copy methods from Form
WorkshopForm.prototype = new Form();

WorkshopForm.prototype.init = function(){
	$.log( 'WorkshopForm.init' );
	
	this.oddEven();
	
	if( $("#datepicker").length > 0 ){
		$("#datepicker").datepicker({	minDate: '+1D', 
										maxDate: '+1Y',
										beforeShowDay: this.limitDays});
		$("#datepicker").datepicker($.datepicker.regional['nl'])
						.datepicker('option', {dateFormat: 'DD, d MM, yy' } )
						.datepicker('setDate', null)
						.datepicker('option', {altField: '#gewenste_datum2', altFormat: 'yy-mm-dd'});
	}
	
	$("#voorwaardenpopup").dialog( { title:'Algemene voorwaarden',width:500, height:350, modal:true, autoOpen: false } ); 
	$("#leesvoorwaarden").click( function(){
								$("#voorwaardenpopup").dialog( "open" )
														.hide()
														.fadeIn();
								} );	
	$("#leesvoorwaarden").hover(function(){$(this).addClass("pointer")},function(){$(this).removeClass("pointer")});
	var holder = this;
	$("#submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
						.click(function(){holder.onReleaseSubmit()});
	
	$("#extra_rekening").hide();
	$("#extra_machtiging").hide();
	$("#extra_korting").hide();
	
	$("input, select").bind("change",function(){ holder.checkRow( $(this).closest(".row") ); });
	
	$("#betaalmethoden").hide();	
	$("input[name='betaalwijze']").bind( "change", function(){ holder.onChangeBetaalwijze(); } );

	$("input[name='cadeaubon']").bind( "change", function(){ holder.onChangeKortingsbon(); } );
	
	$("select[name='aantal']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	// add aantal
	$("select[name='aantal_plakkaten']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	
	$("input[name='bedrijfsuitje']").bind("change", function(){ holder.updateTotaalBedrag() });
	$("#extra_plakkaten").hide();
	$("input[name='vrijgezel']").bind("change", function(){ 
										$("#extra_plakkaten").toggle('fast');
										holder.updateTotaalBedrag();
									});
	
	// add aantal
	var str='<option value="0">Maak een keuze </option>';
	for( var i=1; i<=60; i++ ){
		str += '<option value="'+ i +'">'+ i +'</option>';
	}
	$("select[name='aantal']").html( str );
	
	// add aantal plakkaten
	var str='<option value="0">Maak een keuze </option>';
	for( var i=1; i<=60; i++ ){
		if( i==1 ){
			var selected = "selected=\"selected\"";
		} else {
			var selected = "";
		}
		str += '<option ' + selected + ' value="'+ i +'">'+ i +'</option>';
	}
	$("select[name='aantal_plakkaten']").html( str );
	
	
}

WorkshopForm.prototype.onChangeKortingsbon = function(){
	var val = $("input[name='cadeaubon']:checked").val();
	if( val ){
		$("#extra_korting").fadeIn();
	} else {
		$("#extra_korting").hide();
	}
}

WorkshopForm.prototype.onChangeBetaalwijze = function(){
	var val = $("input[name='betaalwijze']:checked").val();
	$.log( "onChangeBetaalwijze " + val );
	switch( val ){
		case "rekening":
			$("#extra_rekening").fadeIn();
			$("#extra_machtiging").hide();
			$("#betaalmethoden").hide();
			break;
		case "machtiging":
			$("#extra_machtiging").fadeIn();
			$("#extra_rekening").hide();
			$("#betaalmethoden").hide();
			break;
		default:
			$("#extra_rekening").hide();
			$("#extra_machtiging").hide();
			$("#betaalmethoden").show("fast");
			break;
	}
}

WorkshopForm.prototype.limitDays = function(date){
	var closedDays = eval( window.closedDays );
	day=date.getDay();
	var noweekend = [day>0&&day<7,""];
	if( noweekend[0] ){
		for (i = 0; i < closedDays.length; i++) {
				if (date.getFullYear() == closedDays[i][0] && date.getMonth() == closedDays[i][1] - 1 && date.getDate() == closedDays[i][2]) {
						return [false, closedDays[i][2] + '_day'];
				}
		}
		return [true, ''];
	} else {
		return noweekend;
	}
}

WorkshopForm.prototype.updateTotaalBedrag = function(){
	// check aantal
	var aantal = $("select[name='aantal']").val();
	if( aantal == 0 ) return;
	
	var extra = 0;
	
	if( $("input[name='bedrijfsuitje']:checked").val() == "1" ){
		extra += aantal * 2.5;
	}
	
	$.log( "aantal plakkaten: " + parseInt( $("select[name='aantal_plakkaten']").val() ) );
	
	if( $("input[name='vrijgezel']:checked").val() == "1" ){
		extra += parseInt( $("select[name='aantal_plakkaten']").val() ) * 7.5;
	}	
	
	var pricepp = parseInt(window["price"]);
	var price = pricepp * aantal + extra;
	$("#frm_totaal").html( aantal + ' x ' + '&euro; ' + $.moneyFormat(pricepp) + ' p.p = &euro; ' + $.moneyFormat(price) + ' incl. 6% BTW.' ) ;
}

/* --------------------------------------------------------------------- */

ArrangementForm = function( id ){
	$.log( 'ArrangementForm' );
	this.id = id;
	this.init();	
}

ArrangementForm.prototype = new WorkshopForm();

ArrangementForm.prototype.init = function(){
	$.log( 'ArrangementForm.init' );
	
	this.oddEven();
	
	if( $("#datepicker").length > 0 ){
		$("#datepicker").datepicker({	minDate: '+1D', 
										maxDate: '+1Y',
										beforeShowDay: this.limitDays});
		$("#datepicker").datepicker($.datepicker.regional['nl'])
						.datepicker('option', {dateFormat: 'DD, d MM, yy' } )
						.datepicker('setDate', null)
						.datepicker('option', {altField: '#gewenste_datum2', altFormat: 'yy-mm-dd'});
	}
	
	$("#voorwaardenpopup").dialog( { title:'Algemene voorwaarden',width:500, height:350, modal:true, autoOpen: false } ); 
	$("#leesvoorwaarden").click( function(){
								$("#voorwaardenpopup").dialog( "open" )
														.hide()
														.fadeIn();
								} );	
	
	$("#leesvoorwaarden").hover(function(){$(this).addClass("pointer")},function(){$(this).removeClass("pointer")});
	var holder = this;
	$("#submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
						.click(function(){holder.onReleaseSubmit()});
	
	$("#extra_rekening").hide();
	$("#extra_machtiging").hide();
	$("#extra_korting").hide();
	
	$("input, select").bind("change",function(){ holder.checkRow( $(this).closest(".row") ); });
	
	
	$("#betaalmethoden").hide();
	$("input[name='betaalwijze']").bind( "change", function(){ holder.onChangeBetaalwijze(); } );

	$("input[name='cadeaubon']").bind( "change", function(){ holder.onChangeKortingsbon(); } );
	
	$("select[name='aantal']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	$("input[name='tijdsduur']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	$("select[name='aantal_plakkaten']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	
	$("input[name='bedrijfsuitje']").bind("change", function(){ holder.updateTotaalBedrag() });
	$("#extra_plakkaten").hide();
	$("input[name='vrijgezel']").bind("change", function(){ 
										$("#extra_plakkaten").toggle('fast');
										holder.updateTotaalBedrag();
									});
	
	// add aantal
	var str='<option value="0">Maak een keuze </option>';
	for( var i=1; i<=60; i++ ){
		str += '<option value="'+ i +'">'+ i +'</option>';
	}
	$("select[name='aantal']").html( str );
	
	// add aantal plakkaten
	var str='<option value="0">Maak een keuze </option>';
	for( var i=1; i<=60; i++ ){
		if( i==1 ){
			var selected = "selected=\"selected\"";
		} else {
			var selected = "";
		}
		str += '<option ' + selected + ' value="'+ i +'">'+ i +'</option>';
	}
	$("select[name='aantal_plakkaten']").html( str );
	
}

ArrangementForm.prototype.updateTotaalBedrag = function(){
	// check aantal
	var aantal = $("select[name='aantal']").val();
	if( aantal == 0 ) return;
	
	var pricepp = parseInt(window["price"+selectedIndex]);

	if( window.price0 < 0  ){
		$("#frm_totaal").html( "Prijs op aanvraag" );
		return;
	}


	var extra = 0;
	
	if( $("input[name='bedrijfsuitje']:checked").val() == "1" ){
		extra += aantal * 2.5;
	}
	
	// $.log( "aantal plakkaten: " + parseInt( $("select[name='aantal_plakkaten']").val() ) );
	
	if( $("input[name='vrijgezel']:checked").val() == "1" ){
		extra += parseInt( $("select[name='aantal_plakkaten']").val() ) * 7.5;
	}	
	
	var selectedIndex = false;
	$("input[name='tijdsduur']").each( function(i,e){
									if( $(e).attr("checked") ){
										selectedIndex = i;
									}
								} );
	var price = pricepp * aantal + extra;
	$("#frm_totaal").html( aantal + ' x ' + '&euro; ' + $.moneyFormat(pricepp) + ' p.p = &euro; ' + $.moneyFormat(price) + ' incl. 6% BTW.' ) ;
}
/* ------------------------------------- */
KadobonForm = function( id ){
	this.id = id;
	this.init();
}
// copy methods from Form
KadobonForm.prototype = new Form();

KadobonForm.prototype.init = function(){
	
	this.oddEven();
	
	// add aantal
	var str='<option value="0">Maak een keuze </option>';

	for( var i=1; i<=60; i++ ){
		str += '<option value="'+ i +'">'+ i +'</option>';
	}
	
	$("select[name='aantal_personen']").html( str );
	
	$("#voorwaardenpopup").dialog( { title:'Algemene voorwaarden',width:500, height:350, modal:true, autoOpen: false } ); 
	$("#leesvoorwaarden").click( function(){
								$("#voorwaardenpopup").dialog( "open" )
													  .hide()
													  .fadeIn();
								} );
	$("#leesvoorwaarden").hover(function(){$(this).addClass("pointer")},function(){$(this).removeClass("pointer")});
	var holder = this;
	$("#submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
						.click(function(){holder.onReleaseSubmit()});
	
	$("input, select").bind("change",function(){ holder.checkRow( $(this).closest(".row") ); });
	
	$("select[name='aantal_personen']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	$("input[name='tijdsduur']").bind("change", function(){ holder.updateTotaalBedrag() });
	
	$("select[name='arrangement_id']").bind("change", function(){ holder.updateTotaalBedrag() });
	
}

KadobonForm.prototype.updateTotaalBedrag = function(){
	// check aantal
	$.log( 'updateTotaalBedrag' );
	
	var aantal = $("select[name='aantal_personen']").val();
	if( aantal == 0 ) return;
	
	var extra = 0;
	
	var id = $("select[name='arrangement_id']").val();
	if( id > 0 ){
		extra = window['arr_price_'+id];	
	}
	
	var selectedIndex = false;
	$("input[name='tijdsduur']").each( function(i,e){
									if( $(e).attr("checked") ){
										selectedIndex = i;
									}
								} );
	
	var pricepp = parseInt(window["price"+selectedIndex]) + extra;
	var price = pricepp * aantal;
	$("#frm_totaal").html( aantal + ' x ' + '&euro; ' + $.moneyFormat(pricepp) + ' p.p = &euro; ' + $.moneyFormat(price) + ' incl. 6% BTW.' ) ;
}

/* ----------------------------------------------- */
DynamicForm = function( id ){
	$.log( 'DynamicForm' );
	this.id = id;
	this.init();	
}
// copy methods from Form
DynamicForm.prototype = new Form();

DynamicForm.prototype.init = function(){
	$.log( 'DynamicForm.init' );
	$("input, select").bind("change",function(){ holder.checkRow( $(this).closest(".row") ); });
	this.oddEven();
	
	var holder = this;
	$(".submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
						.click(function(){holder.onReleaseSubmit()});
}



/* ----- Start Site ----- */

$(document).ready(function() {
	window.site = new Site.Main();
});

//new Site.Main();