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: Validation for the product details deliver-country selectbox (step 4)
	
	deliverCountryValidation();
	
	// End: Validation for the product details deliver-country selectbox (step 4)
	
	// 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, selected_country, category_id, product_id) {
	
	deliverCountryValidation();
	
	if(selected_country.length == 0) {
		
		jQuery("#order-btn").attr("disabled", true);
		jQuery("#deliver_country_de_area").hide();
		jQuery("#deliver_dates_content").html('');
	}
	/*else if(selected_country == 'de') {
		
		jQuery("#deliver_country_de_area").show();
		jQuery("#deliver_dates_content").html('');
	}*/
	else {
		/*
		if(selected_country != 'de-a' && selected_country != 'de-b') {
			
			jQuery("#deliver_country_de_area").hide();
		}
		*/
		var params = { language: language, selected_country: selected_country, 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, selected_country: selected_country, 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);
		
		jQuery.ajaxSetup({ cache: false }); // for IE
		
		// do ajax call
		jQuery.ajax({
			url: 'includes/ajax/deliver_dates.php',
			method: 'GET',
			data: params,
			async: false,
			success: function(data) {
				if(data != 'failed') {
					
					jQuery("#order-btn").removeAttr("disabled");
					
					jQuery("#deliver_dates_content").html(data);
					jQuery("#dates-loader").addClass('hide');
					
					initDatepicker(showDatesNr);
				}
			}
		});
	}
}

function deliverCountryValidation() {
	
	var formObj = jQuery("form#productform");
	var countrySelect = jQuery("select[name='deliver_country']", formObj);
	var countryAreaSelect = jQuery("select[name='deliver_country_de_area']", formObj);
	var errorObj = jQuery(".error", countrySelect.parent());
	
	if(countrySelect.size()) {
		
		errorObj.hide();
		
		if((jQuery.getUrlVar('deliver_country') == 'false' && countrySelect.val().length == 0) || (countrySelect.val() == 'de' && countryAreaSelect.val() == 'de')) {
			errorObj.show();
			jQuery("#tabs").tabs('select', 3);
		}
		
		formObj.submit(function() {
			
			if(countrySelect.val().length == 0 || (countrySelect.val() == 'de' && countryAreaSelect.val() == 'de')) {
				errorObj.show();
				jQuery("#tabs").tabs('select', 3);
				return false;
			}
			
			return true;
		});
	}
}

function initDatepicker(nrDates) {
	
	// get the selected deliver country
	var deliverCountry = jQuery("select#deliver_country");
	var deliverCountryArea = jQuery("select#deliver_country_de_area");
	
	var skipDays = 1;
	if(deliverCountry.val() == 'de' && deliverCountryArea.val() == 'de-b') {
		skipDays = 2;
	}
	
	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: '+' + skipDays,
		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(selected_country == '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, ''];
		},
		onSelect: function(dateText, inst) {
			
			var theDate = jQuery(this).datepicker("getDate");
			var timeStamp = Math.round(theDate.getTime() / 1000);
			var selectedCountry = (deliverCountry.val() == 'de') ? deliverCountryArea.val() : deliverCountry.val();
			
			// check if date has an extra price add
			jQuery.get("includes/ajax/priceadd.php", { language: pickerLocale, selected_country: selectedCountry, selected_date: timeStamp }, function(data) {
				if(data.length > 0) {
					alert(data);
				}
			});
		},
		showOn: 'both',
		buttonImage: 'images/calendar_icon.gif',
		buttonImageOnly: true
	});
	
	jQuery('#deliver-date').datepicker('option', jQuery.datepicker.regional[pickerLocale]);
	
	// 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, type) {
	
	var productPrice = jQuery("#winkelwagen span.prijsproduct:first span.prijs span").html().replace(",", ".");
	var productTotalPrice = jQuery("#winkelwagen span.prijsproduct2:first span.prijs2 span").html().replace(",", ".");
	var acces_id = "#acces_"+checkobj;

	// checked on (plus)
	if(jQuery(acces_id).attr('checked') == true) {
		if(type == "text"){
			productPrice = parseFloat(productPrice) - parseFloat(price_add);
			productTotalPrice = parseFloat(productTotalPrice) - parseFloat(price_add);
		} else {
			productPrice = parseFloat(productPrice) + parseFloat(price_add);
			productTotalPrice = parseFloat(productTotalPrice) + parseFloat(price_add);
		}
	}
	// checked off (minus)
	else {
		if(type == "text"){
			productPrice = parseFloat(productPrice) + parseFloat(price_add);
			productTotalPrice = parseFloat(productTotalPrice) + parseFloat(price_add);
		} 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');
	
	jQuery("#cart_checkout_payments table tr").removeAttr('style');
	jQuery("#cart_checkout_payments table tr.row-" + method).css('background', '#E0E2D1');
	
	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) {
	
	var valid = false;
	
	if(country != 'nl') { return valid; }
	
	jQuery.ajax({
		async: false,
		url: 'includes/ajax/zipcheck.php',
		data: "country="+country+"&zipcode="+zipcode+"&number="+number,
		success: function(data) {
			if(data != 'failed') {
				var data = jQuery.secureEvalJSON(data);
				jQuery("#FormHandler input.zipcheck_address").val(data.street);
				jQuery("#FormHandler input.zipcheck_place").val(ucwords(data.place.toLowerCase()));
				valid = true;
			}
			else if(country == 'nl') {
				jQuery("#FormHandler input[name='deliver_number']").val('');
				alert(errormsg);
			}
		}
	});
	
	return valid;
}

/**
 * Checks if someone has selected a valid country
 */
function checkDeliveryCountry(dateChosen, error) {
	
	var country = (initCountry !== undefined && dateChosen === true) ? initCountry : false;
	var validCountries = ['nl', 'be'];
	
	var deliverChoice = "#FormHandler input[name='different_deliver_address']";
	var countryField = "#FormHandler select[name='country']";
	var countryDeliverField = "#FormHandler select[name='deliver_country']";
	
	// when a other delivery address is selected
	if(
		( jQuery(deliverChoice + ":checked").val() == 'y' && country !== false && jQuery(countryDeliverField).val() != country )
		||
		( jQuery(deliverChoice + ":checked").val() != 'y' && country !== false && jQuery(countryField).val() != country )
		||
		( jQuery(deliverChoice + ":checked").val() == 'y' && country === false && !in_array(jQuery(countryDeliverField).val(), validCountries) )
		||
		( jQuery(deliverChoice + ":checked").val() != 'y' && country === false && !in_array(jQuery(countryField).val(), validCountries) )
	) {
		
		alert(error);
		return false;
	}
	
	if(jQuery(deliverChoice + ":checked").val() != 'y') {
		
		jQuery(countryDeliverField).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();
	});
}

/**
 * The in_array compliant of PHP for Javascript
 */
function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}


/**
 * Get URL vars for jQuery
 * Example use:
 * 		Get object of URL parameters
 *		var allVars = jQuery.getUrlVars();
 *
 * 		Getting URL var by its nam
 *		var byName = jQuery.getUrlVar('name');
 */
jQuery.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
