jQuery(document).ready(function() {
	
	// ALL a-href LINKS WITH EXTERNAL REL ATTRIB. SET TARGET
	// like: <a href="..." rel="extrnal">...</a> because target="_blank" isn't valid anymore?
	jQuery("body a[rel='external']").each(function() {
		jQuery(this).attr('target', '_blank');
	});
	
	// ALL a-href LINKS WITH POPUP REL ATTRIB. SET AS COLORBOX
	jQuery("body a.colorbox").each(function() {
		
		jQuery(this).colorbox({
			width: '550px',
			height: '600px',
			iframe: true,
			href: jQuery(this).attr('href') + '?popup=true',
			slideshow: false,
			onComplete: function() {
				
			}
		});
	});
	
	// JQUERY TABS (product details)
	
	if(jQuery("#tabs ul.tabs").size()) {
		
		jQuery("#tabs").tabs();
	}
	
	// End: JQUERY TABS (product details)
	
	
	// JQUERY GALLERIA (product details, tab 1)
	
	if(jQuery('#detail_images ul#galleria-images').size()) {
	
		jQuery('#detail_images ul#galleria-images').galleria({
			history: false,
			insert : '#detail_images div#galleria-large',
			onImage : function(image, caption, thumb) { // let's add some image effects for demonstration purposes
			
				// fade in the image & caption
				image.css('display','none').fadeIn(500);
				caption.css('display','none').fadeIn(500);
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500, 0.6);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title', 'Klik voor de volgende afbeelding!');
			},
			onThumb : function(thumb) { // thumbnail effects goes here
			
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.6';
				
				// fade in the thumbnail when finnished loading
				thumb.css({ opacity:_fadeTo }).fadeIn(1000);
				
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast', 1); },
					function() { _li.not('.active').children('img').fadeTo('fast', 0.6); } // don't fade out if the parent is active
				)
			}
		});
	
	}
	
	// End: JQUERY GALLERIA (product details, tab 1)
	
	
	// JQUERY IMAGES SHOW (product details, tab 2)
	
	if(jQuery("#related-products li").size()) {
		
		// first init the first image
		var firstImg = jQuery("#related-products li:first .info a").attr("href");
		
		jQuery("#related-image img").attr("src", firstImg);
		
		// initialize the mouseovers
		jQuery("#related-products li a.imglink").each(function() {
			
			// check the box
			jQuery(this).click(function() {
				
				jQuery("input:checkbox", jQuery(this).parent().prev()).each(function(j, checkbox) {
					if(checkbox.checked == false) {
						checkbox.checked = true;
					}
					else {
						checkbox.checked = false;
					}
				});
				
				return false;
			});
			
			// replace the image src
			jQuery(this).parent().mouseover(function() {
				var imgLink = jQuery("a.imglink", this).attr("href");
				jQuery("#related-image img").attr("src", imgLink);
			});
		});
	}
	
	// End: JQUERY IMAGES SHOW (product details, tab 2)
	
	// Start: CART COUPON TOGGLER
	
	if(jQuery("#cart_total .coupon #coupon-code-opener").size()) {
		
		jQuery("#cart_total .coupon #coupon-code-opener").click(function() {
			
			jQuery("#cart_total .coupon #coupon-code").removeClass("hide");
			jQuery("#cart_total .coupon #coupon-code input:first").focus();
			
			jQuery(this).addClass("hide");
		});
	}
	
	// End: CART COUPON TOGGLER
});

// JQUERY DATEPICKER (product details, tab 4)
	
function reloadDates(language, category_id, product_id) {
	
	var params = { language: language, cid: category_id, pid: product_id };
	var image = '<img src="images/ajax-loader.gif" alt="loader" />';
	var showDatesNr = 5;
	
	if(product_id === false) {
		params = { language: language, cid: category_id, short: true };
		image = '<img src="images/ajax-loader2.gif" alt="loader" />';
		showDatesNr = 1;
	}
	
	// add loading image
	jQuery("#deliver_dates_content").html(image);
	
	// do ajax call
	jQuery.get("includes/ajax/deliver_dates.php", params, function(data) {
		
		if(data != 'failed') {
			
			jQuery("#deliver_dates_content").html(data);
			jQuery("#dates-loader").addClass('hide');
			
			initDatepicker(showDatesNr);
		}
	});
}

function initDatepicker(nrDates) {
	
	var today_tolate = (servertime.replace(':', '') > checktime) ? true : false;
	var today = new Date();
		today.setFullYear(serverdate.split('-')[0]);
		today.setMonth(serverdate.split('-')[1]-1);
		today.setDate(serverdate.split('-')[2]);
		
	var disablecounter = 0;
	
	jQuery("#deliver-date").datepicker({
		//numberOfMonths: 2,
		minDate: '+1',
		maxDate: '+1y',
		showOtherMonths: true,
		selectOtherMonths: true,
		beforeShowDay: function(date) {
			
			// reset counter on day one, because jQuery fires this method twice!
			if(date.getDate() == 1 && date.getMonth() == parseInt(serverdate.split('-')[1]-1)) { disablecounter = (today_tolate) ? -1 : 0; }
			
			// when 'sunday' or 'monday', disable days
			if(date.getDay() == 0 || date.getDay() == 1) {
				
				return [false, ''];
			}
			
			// or in belgium, disable all saturdays
			if(language == 'be' && date.getDay() == 6) {
				
				return [false, ''];
			}
			
			// figure out the next 'nrDates' days, disable day
			if(today < date && disablecounter < nrDates) {
				
				disablecounter++;
				
				return [false, ''];
			}
			
			// figure out if date is ignored
			for(var i=0; i<ignored_dates.length; i++) {
				
				if(ignored_dates[i].getFullYear() == date.getFullYear() && ignored_dates[i].getMonth() == date.getMonth() && ignored_dates[i].getDate() == date.getDate()) {
					
					return [false, ''];
				}
			}
			
			// default
			return [true, ''];
		},
		showOn: 'both',
		buttonImage: 'images/calendar_icon.gif',
		buttonImageOnly: true
	});
	
	jQuery('#deliver-date').datepicker('option', jQuery.datepicker.regional['nl']);
	
	// binding event to the last radio button (other date)
	jQuery("#tabs-4 input[type='radio']:last").click(function() {
		jQuery("#tabs-4 input#deliver-date").focus();
	});
	
	jQuery("#tabs-4 img.ui-datepicker-trigger").click(function() {
		jQuery("#tabs-4 input[type='radio']:last").attr("checked", "checked");
	});
}

// End: JQUERY DATEPICKER (product details, tab 4)


/**
 * Toggle prices from the product-details
 */
function togglePrices(price_add, checkobj) {
	
	var productPrice = jQuery("#winkelwagen span.prijsproduct:first span.prijs span").html().replace(",", ".");
	var productTotalPrice = jQuery("#winkelwagen span.prijsproduct2:first span.prijs2 span").html().replace(",", ".");
	
	// checked on (plus)
	if(checkobj.checked == true) {
		
		productPrice = parseFloat(productPrice) + parseFloat(price_add);
		productTotalPrice = parseFloat(productTotalPrice) + parseFloat(price_add);
	}
	// checked off (minus)
	else {
		
		productPrice = parseFloat(productPrice) - parseFloat(price_add);
		productTotalPrice = parseFloat(productTotalPrice) - parseFloat(price_add);
	}
	
	// set prices into html
	jQuery("#winkelwagen span.prijsproduct:first span.prijs span").html(formatPrice(productPrice));
	jQuery("#winkelwagen span.prijsproduct2:first span.prijs2 span").html(formatPrice(productTotalPrice));
}

/**
 * Formats a price
 */
function formatPrice(price) {
	
	var newprice = new Number(price);
		newprice = newprice.toFixed(2);
		newprice = newprice.split(".");
	
		//if(newprice[1] == '00') {
			
		//	newprice[1] = '-';
		//}
		
		newprice = newprice.join(",");
	
	return newprice;
}

/**
 * To toggle the show/hide for the delivery address
 */
function toggleDeliveryAddress(radioObj) {
	
	var radioValue = jQuery(radioObj).val();
	
	// toggle delivery address
	if(radioValue == 'y' && jQuery("#FormHandler .delivery-address").hasClass("hide")) {
		
		jQuery("#FormHandler .delivery-address").removeClass("hide");
	}
	else if(radioValue == 'n' && !jQuery("#FormHandler .delivery-address").hasClass("hide")) {
		
		jQuery("#FormHandler .delivery-address").addClass("hide");
	}
}

/**
 * For every payment method could be loaded some extra HTML
 * with some custom data for that payment method.
 */
function toggleFields(method) {
	
	// hide all first
	jQuery("#cart_checkout_payments .method-extra").addClass('hide');
	
	if(jQuery("#cart_checkout_payments #" + method + "_extra").size()) {
		
		jQuery("#cart_checkout_payments #" + method + "_extra").removeClass('hide');
	}
}

/**
 * Toggler to modify the cadeau-text
 */
function toggleModifyCadeauText() {
	
	if(jQuery("#cart_deliver_cadeaus .cadeautext_preview:visible").size()) {
		
		jQuery("#cart_deliver_cadeaus a.toggler").addClass('hide');
		jQuery("#cart_deliver_cadeaus .cadeautext_preview").addClass('hide');
		jQuery("#cart_deliver_cadeaus .cadeautext_editables").removeClass('hide');
	}
	else if(jQuery("#cart_deliver_cadeaus .cadeautext_editables:visible").size()) {
		
		jQuery("#cart_deliver_cadeaus a.toggler").removeClass('hide');
		jQuery("#cart_deliver_cadeaus .cadeautext_preview").removeClass('hide');
		jQuery("#cart_deliver_cadeaus .cadeautext_editables").addClass('hide');
		
		jQuery("#cart_deliver_cadeaus .cadeautext_preview span.line").each(function(index) {
			
			jQuery("#cart_deliver_cadeaus .cadeautext_editables input.line-"+index).val(jQuery(this).html());
		});
	}
}

/**
 * Loads the address for given zipcode and number
 */
function loadAddress(country, zipcode, number, errormsg) {
	
	jQuery.get('includes/ajax/zipcheck.php', { country: country, zipcode: zipcode, number: number }, function(data) {
		if(data != 'failed') {
			var data = jQuery.secureEvalJSON(data);
			jQuery("#FormHandler input.zipcheck_address").val(data.street).removeAttr('disabled').removeClass("disabled");
			jQuery("#FormHandler input.zipcheck_place").val(ucwords(data.place.toLowerCase())).removeAttr('disabled').removeClass("disabled");
		} else if(country == 'nl') {
			jQuery("#FormHandler input[name='deliver_number']").val('');
			alert(errormsg);
		}
	});
}

/**
 * Checks if someone has selected a valid country
 */
function checkDeliveryCountry(initCountry, error) {
	
	// when customer wants to deliver on other address AND the deliver-country isn't the same as choosen before
	if(jQuery("#FormHandler input[name='different_deliver_address']:checked").val() == 'y' && jQuery("#FormHandler select[name='deliver_country']").val() != initCountry) {
		
		alert(error);
		
		return false;
	}
	
	// otherwise, when not want to deliver on other address AND the country isn't the same as choosen before
	if(jQuery("#FormHandler input[name='different_deliver_address']:checked").val() != 'y' && jQuery("#FormHandler select[name='country']").val() != initCountry) {
		
		alert(error);
		
		return false;
	}
	
	if(jQuery("#FormHandler input[name='different_deliver_address']:checked").val() != 'y') {
		
		jQuery("#FormHandler select[name='deliver_country']").removeAttr('disabled').removeClass('disabled');
	}
	
	return true;
}

/**
 * The ucwords compliant of PHP for Javascript
 */
function ucwords(str) {
	
	return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
		return $1.toUpperCase();
	});
}