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 += '00';
	} else {
		for( var i=0; i<decimals; i++ ){
			if( !arr[1].charAt(i) ){
				out += '0';
			} else {
				out += arr[1].charAt(i);
			}
		}
	}
	return out;
}


jQuery.removeAfter = function(el,tag){
    element = $('#'+el);
    var aElements = $(tag,element.parent());
    var index = (aElements.index(element));

    for(i=(index+1);i<aElements.length;i++) {
        $('#'+$(aElements.get(i)).attr('id')).remove();
    }
}


jQuery.moneyFormat = function( float ){
	return $.numFormat( float, 2, ',', '.' );	
}

jQuery.fn.vCenter = function(options) {
	var pos = {
	  sTop : function() {
	    return window.pageYOffset
	    || document.documentElement && document.documentElement.scrollTop
	    ||  document.body.scrollTop;
	  },
	  wHeight : function() {
	    return window.innerHeight
	    || document.documentElement && document.documentElement.clientHeight
	    || document.body.clientHeight;
	  }
	};
	
	return this.each(function(index) {
	  if (index == 0) {
	    var $this = $(this);
	    var elHeight = $this.height();
	    var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
	    $this.css({
	      position: 'absolute',
	      marginTop: '0',
	      top: elTop
	    });
	  }
	});
}

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.TegelPopup = function(buttonId, itemId) {
	this.initialize(buttonId, itemId);
}

Site.Main.prototype = {
	initialize: function(){
		$.log( 'Site.Main.initialize' );
		this.initListItems();
		this.initProductItems();
		this.initSlideShow();

		Cufon.replace("h2");		
		
		if( window.subtemplate == 'shop_checkout' ){
			window.template = 'shop_checkout';
		}
		switch( window.template ){
			case "shop_checkout":	
				if ($("#tegelpopup9").length) {
					$("#tegelpopup9").remove();
				}
				if ($("#tegelpopup105").length) {
					$("#tegelpopup105").remove();
				}
				new Site.TegelPopup('#addtegeltext9', 9);
				new Site.TegelPopup('#addtegeltext105', 105);
				this.checkoutForm = new CheckoutForm("#frm_checkout");				
				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;
			case "shop":				
				this.setupInfoPopUps();
				this.setupProductsCart();
				this.setupBonbonsBoxCart();
				this.setupInformation();
				new Site.TegelPopup('#addtegeltext9', 9);
				new Site.TegelPopup('#addtegeltext105', 105);
				break;
		}
        
		if ($("#afdrukken").length > 0 ) {
			$.log( 'Afdrukken bestaat' );
			//$.printSelection('#contentarea');
			$("#afdrukken a").bind('click', function(){
				$.log( 'Afdrukken clicked' );
				$.printSelection('#contentarea');
			} );
		}        


	},
	setupInfoPopUps: function() {
		
		var holder = this;
		
		$('#infoPopUp').hide();
		
		$('.productitem, .bonbonitem').each(function(index) {
			
			$(this).data('infopopup', jQuery.parseJSON($(this).find('.info').attr("rel")));
			var productitem = $(this);
			
			$(this).find('.visual a').click(function(e){
				
				e.preventDefault();
				holder.openInfoPopUp(productitem.data('infopopup'));
				
			});
			
			$(this).find('.info a').click(function(e){
				
				e.preventDefault();
				holder.openInfoPopUp(productitem.data('infopopup'));
				
			});
			
		});
		
		$(window).scroll(function(e) {
		  	
		  	e.preventDefault();
			$('#infoPopUp').fadeOut('fast', function() {
				$('#infoPopUp #content').html('');
			});
			
		});
		
		$('#infoPopUp, #infoPopUp #close').click(function(e){
				
			e.preventDefault();
			$('#infoPopUp').fadeOut('fast', function() {
				$('#infoPopUp #content').html('');
			});
			
		});
		
	},
	openInfoPopUp: function(obj) {
		$('#infoPopUp').fadeOut('fast', function() {
			$('#infoPopUp #content').html('');
			$('#infoPopUp #content, #infoPopUp #image').html('');
			
			//var content = (unescape(obj.content));
			//content = content.split('+').join(' ');
			
			var content = obj.content;
			
			$('#infoPopUp #content').html('<h3>'+obj.title+'</h3>'+content );
			$('#infoPopUp #image').html('<img src="'+obj.image+'" />');
			$('#infoPopUp').vCenter();
			$('#infoPopUp').fadeIn();
		});
		
				
	},
	setupProductsCart: function(){
		$("ul.cart .amount input").replaceNumInputs();
		
		var holder = this;
		
		$('ul.products li, ul.cart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());


			$(this).find('.addtocart').bind('click', function(e) {
				
				e.preventDefault();
				var parent = $(this).parents('li');

                if ($('.chooseletter').length) {
                   var currentLetterSelect = parent.find('select[name='+parent.data('id') +'_letter]');
                   $.log("Has letter: " + currentLetterSelect.val());
                   parent.data('letter',currentLetterSelect.val());
                   $('.chooseletter').removeAttr('style');
                   if (  parent.data('letter') == 0) {
                      if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
                        currentLetterSelect.attr('style', 'background-color: #ff0000;');
                      } else {
                          currentLetterSelect.attr('style', 'border: solid 1px #ff0000;');
                      }
                      return;
                   }
                }

				
				holder.onAddProductToCart( parent);
				
			});
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountCart( parent, 0);
				
			});
		});
		
		$('ul.products li').each(function(index) {
			$(this).find('.price').html('&euro; '+$.moneyFormat($(this).data('price')));
		});
		
		$('ul.products .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountProduct( parent, $(this).val() );
		} );
		
		$('ul.cart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountCart( parent, $(this).val() );
		} );
		
		$('ul.products .amount input').trigger('change');
		
		$('#cart .ordertop a, #cart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.checkOut();
		} );
		
		var current_percentage = $('#percentage').val();
		this.updatePercentageBoxCart(current_percentage);
	},
	checkOut: function() {
		
		if($('ul.cart li').length > 0) {
			$('#checkoutformid').trigger('submit');
		}else {
			return false;
		}
	},
	onChangeAmountProduct: function( e, amount){
		$.log( "addNumInput:: "+e.data('price'));
		
		var amount = Number(amount);
		if(amount <= 0) {
			amount = 1;
		}
		
	},
	onChangeAmountCart: function( e, amount){
		if(amount <= 0) {
			$.log("remove from cart");
			
			var update_str = {index:e.data('unique_id'),amount:amount};
		
			var holder = this;
			$.post("shop?p=removeCartItem",update_str,function( data ){
				holder.onChangeAmountCartReady( data );				 
			},"text");
			
			return;
		}

		if ($("#tegelpopup9").length) {
            if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
                $("#tegelpopup9").remove();
            } else {
                $("#tegelpopup9").remove();						
            }
		}

		if ($("#tegelpopup105").length) {
            if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
                $("#tegelpopup105").remove();
            } else {
                $("#tegelpopup105").remove();						
            }
		}		
		
		
		$.log('index:: '+ e.data('unique_id') +' amount:: '+amount);
		
		var update_str = {index:e.data('unique_id'),amount:amount};
		
		var holder = this;
		$.post("shop?p=updateCartItem",update_str,function( data ){
			holder.onChangeAmountCartReady( data );				 
		},"text");
	},
	onChangeAmountCartReady: function(data) {		
		$('#cart').html(data);
		
		$(".cart .amount input").replaceNumInputs();
		
		var holder = this;
				
		$('ul.cart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());
			
			
			//als tegel dan
			if ($(this).data('id') == 9 ) {
                // dirty fix to get it working under ie 7 and lower
                if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
                    window.location.reload();
                } else {                
                    window.site.tegelpopup9 =  new Site.TegelPopup('#addtegeltext9', 9);					
                }
			}
			if ($(this).data('id') == 105 ) {
                // dirty fix to get it working under ie 7 and lower
                if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
                    window.location.reload();
                } else {                
					window.site.tegelpopup105 =  new Site.TegelPopup('#addtegeltext105', 105);					
                }
			}
			
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountCart( parent, 0);
				
			});
			
		});
		
		$('#cart .ordertop a, #cart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.checkOut();
		} );
				
		$('ul.cart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountCart( parent, $(this).val() );
		} );
		
	},
	onAddProductToCart: function(e) {
		
		var amount = e.find('input[name=amount]').val();
		if(amount <= 0) {
			return;
		}
		$.log( "onAddProductToCart:: id="+e.data('id')+" price="+e.data('price')+" amount="+amount);
		
		var update_str = {id:e.data('id'),amount:amount,letter:e.data('letter')};
		
		var holder = this;
		$.post("shop?p=addToCart",update_str,function( data ){
			holder.onAddProductToCartReady( data );				 
		},"text");
		
	},
	onAddProductToCartReady: function( data ){
		$('#cart').html(data);
		
		$("#cart .amount input").replaceNumInputs();
		var holder = this;
				
		$('ul.cart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());
          $.log('Debug ' + $(this).find('select[name='+$(this).data('id') +'_letter]').val());
         if ($('.chooseletter').length) {
            $(this).data('letter',$(this).find('select[name='+$(this).data('id') +'_letter]').val());
         }
			
			//als tegel dan
			if ($(this).data('id') == 9 ) {
				window.site.tegelpopup9 =  new Site.TegelPopup('#addtegeltext9', 9);
			}
			if ($(this).data('id') == 105 ) {
				window.site.tegelpopup105 =  new Site.TegelPopup('#addtegeltext105', 105);
			}
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountCart( parent, 0);
				
			});
		});
		
		$('#cart .ordertop a, #cart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.checkOut();
		} );
				
		$('ul.cart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountCart( parent, $(this).val() );
		} );
	},
	setupBonbonsBoxCart: function(){
		
		$('#boxcart').data('box_id', $('#b_id').val());
		$('#boxcart').data('weight', $('#maxweight').val());
		
		$("ul.boxcart .amount input").replaceNumInputs();
		
		var holder = this;
		
		$('ul.bonbons li, ul.boxcart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());
         
			
			$(this).find('.addtocart').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onAddBonbonToBoxCart( parent);
				
			});
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountBoxCart( parent, 0);
				
			});
		});
		
		$('ul.bonbons li').each(function(index) {
			$(this).find('.price').html('&euro; '+$.moneyFormat($(this).data('price')));
		});
		
		$('ul.bonbons .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountBonbons( parent, $(this).val() );
		} );
		
		$('ul.boxcart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountBoxCart( parent, $(this).val() );
		} );
		
		$('#boxcart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.gotoBoxDesign();
		} );
		
		$('.boxdesignitem').bind('click',function(e){
			e.preventDefault();
			holder.selectBoxDesign($(this));
		});
		
		$('#sidebar .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.addBoxToCart();
		} );
		
		$('ul.bonbons .amount input').trigger('change');
	},
	onChangeAmountBonbons: function( e, amount){
		$.log( "addNumInput:: "+e.data('price'));
		
		var amount = Number(amount);
		if(amount <= 0) {
			amount = 1;
		}
		
	},
	onChangeAmountBoxCart: function( e, amount){
		if(amount <= 0) {
			$.log("remove from cart");
			
			var update_str = {b_id:$('#boxcart').data('box_id'),index:e.data('unique_id'),amount:amount};
		
			var holder = this;
			$.post("shop?p=removeBoxCartItem",update_str,function( data ){
				var current_percentage = $('#percentage').val();
			
				holder.onAddBonbonToBoxCartReady( data );
				holder.updatePercentageBoxCart(current_percentage);
			},"text");
			
			return;
		}
		
		$.log('index:: '+ e.data('unique_id') +' amount:: '+amount);
		
		var update_str = {b_id:$('#boxcart').data('box_id'), index:e.data('unique_id'),amount:amount};
		
		var holder = this;
		$.post("shop?p=updateBoxCartItem",update_str,function( data ){
			var current_percentage = $('#percentage').val();
			
			holder.onAddBonbonToBoxCartReady( data );
			holder.updatePercentageBoxCart(current_percentage);				 
		},"text");
	},
	updatePercentageBoxCart: function(current_percentage) {
		
		if(current_percentage > 0) {
			
			var w = $('#progressbar').width();
			var percent = w / 100;
			
			var position = (0 - w) + (current_percentage * percent)+'px';
			
			$('#progressbar').css( {backgroundPosition: position+" -20px"} );
		}
		
		var percentage = $('#percentage').val();
		
		if(percentage < 100) {
			var w = $('#progressbar').width();
			var percent = w / 100;
			
			var position = (0 - w) + (percentage * percent)+'px';
			
			$('#progressbar').animate({backgroundPosition: position+" -20px"},
                  {duration: 'slow'});
                  
			$('#progressbar').bind('click', function(e) {
				
				e.preventDefault();
				
			});
			
		}else if(percentage == 100) {
			
			$('#progressbar').css( {backgroundPosition: "0 0"} );
			
			$('#progressbar').bind('click', function(e) {
				
				e.preventDefault();
				if($('#percentage').val() == 100) {
					$('#boxcartform').trigger('submit');
				}
				
			});
			
		}else {
			
			$('#progressbar').css( {backgroundPosition: "-294px 0px"} );
			
			$('#progressbar').bind('click', function(e) {
				
				e.preventDefault();
				
			});
			
		}		
		
	},
	onChangeAmountBoxCartReady: function(data) {
		$('#boxcart').html(data);
		
		$(".boxcart .amount input").replaceNumInputs();
		
		var holder = this;
				
		$('ul.boxcart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountBoxCart( parent, 0);
				
			});
		});
				
		$('ul.boxcart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountBoxCart( parent, $(this).val() );
		} );
		
		$('#boxcart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.gotoBoxDesign();
		});
		
	},
	onAddBonbonToBoxCart: function(e) {
		
		var amount = e.find('input[name=amount]').val();
		if(amount <= 0) {
			return;
		}
		$.log( "onAddBonbonToBoxCart:: b_id: "+$('#boxcart').data('box_id')+"id="+e.data('id')+" price="+e.data('price')+" amount="+amount);
		
		var update_str = {b_id:$('#boxcart').data('box_id'), id:e.data('id'),amount:amount};
		
		var holder = this;
		$.post("shop?p=addToBoxCart",update_str,function( data ){
			var current_percentage = $('#percentage').val();
			
			holder.onAddBonbonToBoxCartReady( data );
			holder.updatePercentageBoxCart(current_percentage);				 
		},"text");
		
	},
	onAddBonbonToBoxCartReady: function( data ){
		
		$('#boxcart').html(data);
		
		$(".boxcart .amount input").replaceNumInputs();
		
		var holder = this;
				
		$('ul.boxcart li').each(function(index) {
			
			$(this).data('id', $(this).find('input[name=id]').val());
			$(this).data('unique_id', $(this).find('input[name=unique_id]').val());
			$(this).data('price',$(this).find('input[name='+$(this).data('id') +'_price]').val());
			
			$(this).find('.removefromcart a').bind('click', function(e) {
				
				e.preventDefault();
				
				var parent = $(this).parents('li');
				
				holder.onChangeAmountBoxCart( parent, 0);
				
			});
		});
				
		$('ul.boxcart .amount input').bind('change',function(){
			var parent = $(this).parents('li');
			holder.onChangeAmountBoxCart( parent, $(this).val() );
		});
		
		$('#boxcart .orderbottom a').bind('click',function(e){
			e.preventDefault();
			holder.gotoBoxDesign();
		});
	},
	gotoBoxDesign: function () {
		if($('#percentage').val() == 100) {
			$('#boxcartform').trigger('submit');
		}
	},
	selectBoxDesign: function (el) {
		
		$('.boxdesignitem').removeClass('selected');
		el.addClass('selected');
		
		$('#bd_id').attr('value',el.attr('id'));
		
	},
	addBoxToCart: function () {
		if($('#bd_id').val() > 0) {
			$('#boxdesignform').trigger('submit');
		}
	},
	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") );
							});
	},
	initProductItems: function(){
		var holder = this;
		$(".productitem .link").hover(function(){
				$(this).addClass("productitem_hover");
			},
			function(){
				$(this).removeClass("productitem_hover");
			}).click(function(){
				
			});
	},
	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);
    },
	setupInformation: function() {
		$('#hoe_werkt_het').hide();
		$('#show_bonbon_doosjes').live('click', function(){
			$('#hoe_werkt_het').toggle();
			$('#overzicht_bonbon_doosjes').toggle();
			if ($("#hoe_werkt_het").is(":visible")){
				$('#show_bonbon_doosjes .show_bonbon_doosjes_text').html("Toon onze bonbondozen");
			} else {
				$('#show_bonbon_doosjes .show_bonbon_doosjes_text').html("Hoe werkt het?");
			}
		});
				
	}
};

Site.TegelPopup.prototype = {
	initialize: function(buttonId, itemId){    
		$.log('ITEM_ID  = ' + itemId);
        if (itemId == 9) {
            var titleText = 'Tegel';
        } else {
            var titleText = 'Hart';
        }
		$("#tegelpopup" + itemId ).dialog( { title:titleText,width:600, height:700, modal:true, autoOpen: false } );
		$("#tegeltabs" + itemId).tabs();
		$("#tegeltabs" + itemId).hide();
		
		if ($("input[name=tegeltextradio"+ itemId+"]:checked").val() == 'different'){
		//$("#sametext").attr('checked', true);
		// set/choose same text for all tegels or different text for all tegels
			$("#differenttext" + itemId).attr('checked', true);
				$("input#different_or_same" + itemId).val("different");
				$("#tegeltabs" + itemId).show();
				$("#notegeltabs" + itemId).hide();
			} else {
			$("#sametext" + itemId).attr('checked', true);
				$("input#different_or_same" + itemId).val("same");
				$("#tegeltabs" + itemId).hide();
				$("#notegeltabs" + itemId).show();
			}		
		$("input[name=tegeltextradio" + itemId + "]").change(function(){
			if ($("input[name=tegeltextradio"+ itemId+"]:checked").val() == 'different') {
                
				if  ( $("#popup_same_tegels" + itemId).val().length > 0 ) {
					$("#popup"+itemId+"_tegels-0").text($("#popup_same_tegels" + itemId).text());					
				}
                
				$("input#different_or_same" + itemId).val("different");
				$("#tegeltabs" + itemId).show();
				$("#notegeltabs" + itemId).hide();
			} else {
				$("input#different_or_same" + itemId).val("same");
				$("#tegeltabs" + itemId).hide();
				$("#notegeltabs" + itemId).show();
			}		
		});	
		$(buttonId).click( function(e){
			//e.preventDefault();
						
			$("#tegelpopup" + itemId).dialog( "open" )
									.hide()
									.fadeIn();
$.log('KNOP = ' + buttonId);                                                    
			var holder = this;
			if ($("#popup_same_tegels" + itemId).length) {
				
				$("#popup_same_tegels" + itemId).keyup(
						function() {
							
							var allowedNumberOfLines = 5;
							var lineNr = $('#popup_same_tegels' + itemId).val().split("\n").length
							if (lineNr > allowedNumberOfLines) {
								alert("Maximaal 5 regels mogelijk!!");
								modifiedText = $(this).val().split("\n").slice(0, allowedNumberOfLines);
								$(this).val(modifiedText.join("\n"));
							}
						});			
			}
			if ($("textarea[id^=popup"+itemId+"_tegels-]").length) {
				$("textarea[id^=popup"+itemId+"_tegels-]").each(					
				function(index) {
					$(this).keyup(
						function() {
							var allowedNumberOfLines = 5;
							var lineNr = $('#popup" + itemId+"_tegels-' + index).val().split("\n").length
							if (lineNr > allowedNumberOfLines) {
								alert("Maximaal 5 regels mogelijk!!");
								modifiedText = $(this).val().split("\n").slice(0, allowedNumberOfLines);
								$(this).val(modifiedText.join("\n"));
							}

						});				
				});
			}	
			});
		$("#savetegeltxtbutton" + itemId).click( function(){
			//e.preventDefault();	
			if (buttonId == '#addtegeltext' + itemId) {
				//save to user with ajax call
				var indexVal = $("#tegelindex" + itemId).attr('rel');
				
				var post_data = '';
				if ($("input[name=tegeltextradio" + itemId + "]:checked").val() == 'different') {					
					var len = $("textarea[id^=popup" + itemId + "_tegels-]").length;
					var txt = $("textarea[id^=popup" + itemId + "_tegels-]").map(function() {
						  return $(this).val();
					}).get();
					var post_data = {index:indexVal, 'tegeltext[]':txt, same_or_different:'different'};
				} else {
				var tegeltext = $("textarea#popup_same_tegels" + itemId).val();
					var post_data = {index:indexVal, 'tegeltext[]':tegeltext, same_or_different:'same'};
				}
				
				$.post("shop?p=saveTegelText",post_data,function( data ){
					$("#addtegeltext" + itemId + " span").html("Tegeltekst(en) aanpassen");
					$("#addtegeltext" + itemId + " span").addClass('tegel_saved');
				},"text");
				
			} else {
				//select all textareas in the tegel popup and save the text to the corresponding textareas in the form
				if ($("input[name=tegeltextradio" + itemId + "]:checked").val() == 'different') {
					$("textarea[id^=popup" + itemId + "_tegels-]").each(function(index) {
						var tegeltext = $("textarea#popup" + itemId + "_tegels-" + index).val();
				//.replace(/\n/g, "<br />")
						$("textarea#frm_tegels" + itemId + "-" + index).html(tegeltext);
						
					});
				} else {
					var tegeltext = $("textarea#popup_same_tegels" + itemId).val();
					//.replace(/\n/g, "<br />")
				$("textarea#frm_tegels" + itemId + "-0").html(tegeltext);
			}				
			}
			
			$("#tegelpopup" + itemId).dialog( "close" )
									.hide()
									.fadeOut();
		});
		

		
		
	}
};


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:: "+ this.id);
			// 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_radio_special":
					if( $("input[type='radio']:checked", e).val() == undefined ){
						this.setError( e, true );
						check = false;						
					} else {
						
						this.updateShippingPrice(e);
						
						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;
	},
	updateShippingPrice: function(e){
		var selected = $("input[type='radio']:checked", e).val();
		if( !selected ) return;
		var cost = parseFloat($("input[type='hidden'][name='"+selected+"']", e).val());
		var total = parseFloat($("input[type='hidden'][name='total']", e).val());
		
		var newtotal = total + cost;
		$("#shipping").html("&euro; "+ $.moneyFormat(cost));
		$("#total strong").html("&euro; "+ $.moneyFormat(newtotal));
		$("input[type='radio']:checked", e).val();
		
		$.log( "selected " + selected);
		$.log( "cost " + cost);
		$.log( "total " + total);
		$.log( "newtotal " + newtotal);
	},
	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;	
}


CheckoutForm = function( id ){
	$.log( 'CheckoutForm' );
	this.id = id;
	this.init();	
}
// copy methods from Form
CheckoutForm.prototype = new Form();

CheckoutForm.prototype.init = function(){
	$.log( 'CheckoutForm.init' );	
	this.oddEven();
	$("#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;
	
	if ($("#alt_address").is(":checked")) {
		
		$("#bezorgadres").show("fast");
		
	} else {
		
		$("#bezorgadres").hide();
		
	}
	
	$("#betaalmethoden").hide();	
	$("input[id='alt_address']").bind( "change", function(){ holder.onChangeAltAddress(); } );
	
	$("#submitbutton")	.hover(function(){$(this).addClass("pointer");},function(){$(this).removeClass("pointer")})
						.click(function(){holder.onReleaseSubmit()});
	
	$("input, select").bind("change",function(){ holder.checkRow( $(this).closest(".row") ); });
	
	
//	alert( $(".frm_radio_special").parent().parent() );
	
	this.updateShippingPrice( $(".frm_radio_special").parent().parent() );
	
}

CheckoutForm.prototype.onChangeAltAddress = function(){
	if ($("#alt_address").is(":checked")) {
		
		$("#bezorgadres").show("fast");
		
	} else {
		
		$("#bezorgadres").hide();
		
	}
}


/* ----------------------------------------------- */
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();
