
var ajaxurl = "http://www.alabastine.nl/wp-admin/admin-ajax.php";

$(function() {

	$('#selects li').click(function() {
		var index = $('#dropdowns ul li').index(this);
		$('.sub-nav').hide();
		$($('.sub-nav')[index]).toggle();
		$('#dropdowns ul li').removeClass('current');
		$(this).addClass('current');
		return false; 
	});

	$('body').click(function() {
		$('.sub-nav').fadeOut('fast');
		$('#dropdowns ul li').removeClass('current');
	});

	$('#close-promos').click(function() {
		closePromos();
		
		return false;
	});
	
	$(".banner-promo").click(function(){ if($(this).find("a").length > 0) { closePromos(); window.location=$(this).find("a").attr("href"); return false; } });
	$('.banner-promo').hover(function(){ $(this).addClass('banner-hover') },function(){ $(this).removeClass('banner-hover')})
	
	$('.banner-promo a').click(function() {
		closePromos();
	});
	
	function closePromos() {
		$('#thepromos').fadeOut('fast');
	 	$('#show-promos').show();
	 	$('.set-orange').removeClass('promo-space');
				var expiresAfter = 7;
		if(expiresAfter == 0) {
			expiresAfter = 30;
		}

		$.cookie('wpan_hide_promos', '', { path: '/', expires: expiresAfter });
	}
 

	$('#show-promos').click(function() {
	 	$('#thepromos').fadeIn('fast');
	 	$('#show-promos').hide();
	 	$('.set-orange').addClass('promo-space');
		 	return false;
	});
 
	$('#close-tip, .close-note').click(function() {
	 	$('#select-tip, .note').fadeOut('fast');
	
		// Save closed item in cookie, so it will not come back
		var tooltipId = $(this).closest("div").attr("id");
		var cookieName = 'wpan_show_tooltips';
		var currentCookie = $.cookie(cookieName);
		if(currentCookie == null) {
			currentCookie = '';
		}
		
		var expiresAfter = 30;
		if(expiresAfter == 0) {
			expiresAfter = 30;
		}
		
		$.cookie(cookieName, currentCookie + (currentCookie != '' ? ',' : '') + tooltipId, { path: '/', expires: expiresAfter });
	});

	// Slideshow 
	var imgWrapper = $('#slide-big > img, #detail-img > img');
	// only show the first image, hide the rest
	imgWrapper.hide().filter(':first').show();
	$('.slide-list li a, .size-list a').click(function () {
		// check if this item doesn't have class "current"
		// if it has class "current" it must not execute the script again
		if (this.className.indexOf('current') == -1){
			imgWrapper.hide();
			imgWrapper.filter(this.hash).fadeIn(200);
			$('.slide-list li a, .size-list a').removeClass('current');
			$(this).addClass('current');
		}
		return false;
	});


	$('.start-slide').click(function() {
		$('#video-big, .start-slide, .start, .start-video').hide();
		$('#slide-big, .start-video, .slide-list').show();
	});

	$('.start-video').click(function() {
		$('#slide-big, .start-video, .slide-list').hide();
	 	$('#video-big, .start, .start-slide').show();
	});

	$('.mail-wish, .mail-brochure').click(function() {$('.wishmail-form').show(); });
	$('.close-wish').click(function() {$('.wishmail-form').hide(); });

	$('.add-friend').click(function() {
		$('.second-wish, .remove-friend').show();
	 	$('.add-friend').hide();
	});

	$('.remove-friend').click(function() {
		$('.add-friend').show();
	 	$('.remove-friend, .second-wish').hide();
	});
	
	// Tabs
	var tabContainers=$('#tabs > div');tabContainers.each(function(){this.id+= '-element';}).hide().filter(':first').show();
	$('#tabs ul.tab-nav a').click(function(){tabContainers.hide();tabContainers.filter(this.hash + '-element').show();$('#tabs ul.tab-nav a').removeClass('selected');$(this).addClass('selected');}).filter(':first').click();

	// open selected tab
	if ($('a[href=' + document.location.hash + ']').length) { $('a[href=' + document.location.hash + ']').trigger('click'); window.scrollTo(0,0); }
 
	$('.promo').hover(function(){ $(this).addClass('promo-hover') },function(){ $(this).removeClass('promo-hover')})
	$('.slides div ul, .prod-block, .prod-small').hover(function(){ $(this).addClass('slide-hover') },function(){ $(this).removeClass('slide-hover')})
	$('section.download').hover(function(){ $(this).addClass('dl-hover') },function(){ $(this).removeClass('dl-hover')})
	$('.overview').hover(function(){ $(this).addClass('overview-hover') },function(){ $(this).removeClass('overview-hover')})
	$('.steps').hover(function(){ $(this).addClass('steps-hover') },function(){ $(this).removeClass('steps-hover')})
	$('.brand-block').hover(function(){ $(this).addClass('brand-hover') },function(){ $(this).removeClass('brand-hover')})
	$('.news-block').hover(function(){ $(this).addClass('news-hover') },function(){ $(this).removeClass('news-hover')})
	$(".promo, .slides div ul, .prod-block, .prod-small, .news-block").click(function(){ window.location=$(this).find("a").attr("href");return false; });
	for(var i=0; i<$('#selects li').length; i++) {
		$("#dropdowns").prepend("<span id='nav-surface-" + i + "'>Afbeelding " + $('#nav-surface-item-' + i).html() + "</span>");
	}
	$(".video a").prepend("<span class='ply-bttn'>Video starten</span>");
	$(".related .video a").prepend("<em class='ply-bttn'>Video starten</em>");
	$("#video-big a").prepend("<span class='ply-bttn'>Video starten</span>");

	// Show / hide search
	/*
	$('form.search').hide();
	$('.show-search a, .close-search').click(function() {
		var index = $('.show-search a, .close-search').index(this);
		$('form.search').not($('form.search').eq(index)).fadeOut('fast');
		$('form.search').eq(index).toggle();
		return false; 
	});
	*/

	// Faq
	doFaqLinkThingy();

	// Slides on home 
	$('.slides div ul').each(function () { });  
	$('.slides div ul').hover(  
	    function () {  
	        $(this).siblings().css({'opacity': '0.5'});   
	        $(this).css({'opacity': '1.0'}).addClass('effect');  
	    }  
	);  
	$('.slides div').mouseleave(function () {  
	    $(this).children().fadeTo('100', '1.0').removeClass('effect');        
	});

	// Clear inputs on blur
	$("input").focus(function() { if( this.value == this.defaultValue ) {this.value = "";}}).blur(function() {if( !this.value.length ) {this.value = this.defaultValue;} });
	
	if($("#wish-form").length > 0) {
		$("#wish-form").submit(function() {
			var sendTo = $('#input-wish').val();
		
			var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		    if(pattern.test(sendTo)){
				$.post(ajaxurl, {
					send_to: sendTo,
					action: 'wpan_send_wishlist'
				}, function(result) {
					var result = cleanAjaxResults(result);
					var json = $.parseJSON(result);
	
					showMessage(json.message, json.success == 'true' ? '' : 'error');
				});
			}
			else {
				showMessage('Vul alstublieft een geldig emailadres is. Bedankt!', 'error');
				$('#input-wish').focus();
			}
		});
	}
});

$("table tr:nth-child(odd)").addClass("striped");

// Slideshow
function slideSwitch() {
    var $active = $('#slideshow img.active');
    if ( $active.length == 0 ) $active = $('#slideshow img:last');
    var $next =  $active.next().length ? $active.next()
        : $('#slideshow img:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}
 
$(function() {
    setInterval( "slideSwitch()", 5000 );
});

// Highlight form
	$('.maincontact input, .maincontact textarea').focus(function(){
		$(this).parents('div.row').addClass("current-form");
	}).blur(function(){
		$(this).parents('div.row').removeClass("current-form");
	});

// Smooth scroll AZ
$('a[href*=#]').click(function() {
   if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) {
        var $target = $(this.hash);
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
        if ($target.length) {
            var targetOffset = $target.offset().top;
            $('html,body').animate({scrollTop: targetOffset}, 1000);
            return false;
        }
    }
});


// LoopedSlider
if(typeof jQuery!='undefined'){jQuery(function($){$.fn.extend({loopedSlider:function(options){var settings=$.extend({},$.fn.loopedSlider.defaults,options);return this.each(function(){if($.fn.jquery<'1.3.2'){return}var $t=$(this);var o=$.metadata?$.extend({},settings,$t.metadata()):settings;var distance=0;var times=1;var slides=$(o.slides,$t).children().size();var width=$(o.slides,$t).children().outerWidth();var position=0;var active=false;var number=0;var interval=0;var restart=0;var pagination=$("."+o.pagination+" li a",$t);if(o.addPagination&&!$(pagination).length){var buttons=slides;$($t).append("<ul class="+o.pagination+">");$(o.slides,$t).children().each(function(){if(number<buttons){$("."+o.pagination,$t).append("<li><a rel="+(number+1)+" href=\"#\" >"+(number+1)+"</a></li>");number=number+1}else{number=0;return false}$("."+o.pagination+" li a:eq(0)",$t).parent().addClass("active")});pagination=$("."+o.pagination+" li a",$t)}else{$(pagination,$t).each(function(){number=number+1;$(this).attr("rel",number);$(pagination.eq(0),$t).parent().addClass("active")})}if(slides===1){$(o.slides,$t).children().css({position:"absolute",left:position,display:"block"});return}$(o.slides,$t).css({width:(slides*width)});$(o.slides,$t).children().each(function(){$(this).css({position:"absolute",left:position,display:"block"});position=position+width});$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width});if(slides>3){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width})}if(o.autoHeight){autoHeight(times)}$(".next",$t).click(function(){if(active===false){animate("next",true);if(o.autoStart){if(o.restart){autoStart()}else{clearInterval(sliderIntervalID)}}}return false});$(".previous",$t).click(function(){if(active===false){animate("prev",true);if(o.autoStart){if(o.restart){autoStart()}else{clearInterval(sliderIntervalID)}}}return false});if(o.containerClick){$(o.container,$t).click(function(){if(active===false){animate("next",true);if(o.autoStart){if(o.restart){autoStart()}else{clearInterval(sliderIntervalID)}}}return false})}$(pagination,$t).click(function(){if($(this).parent().hasClass("active")){return false}else{times=$(this).attr("rel");$(pagination,$t).parent().siblings().removeClass("active");$(this).parent().addClass("active");animate("fade",times);if(o.autoStart){if(o.restart){autoStart()}else{clearInterval(sliderIntervalID)}}}return false});if(o.autoStart){sliderIntervalID=setInterval(function(){if(active===false){animate("next",true)}},o.autoStart);function autoStart(){if(o.restart){clearInterval(sliderIntervalID);clearInterval(interval);clearTimeout(restart);restart=setTimeout(function(){interval=setInterval(function(){animate("next",true)},o.autoStart)},o.restart)}else{sliderIntervalID=setInterval(function(){if(active===false){animate("next",true)}},o.autoStart)}}}function current(times){if(times===slides+1){times=1}if(times===0){times=slides}$(pagination,$t).parent().siblings().removeClass("active");$(pagination+"[rel='"+(times)+"']",$t).parent().addClass("active")};function autoHeight(times){if(times===slides+1){times=1}if(times===0){times=slides}var getHeight=$(o.slides,$t).children(":eq("+(times-1)+")",$t).outerHeight();$(o.container,$t).animate({height:getHeight},o.autoHeight)};function animate(dir,clicked){active=true;switch(dir){case"next":times=times+1;distance=(-(times*width-width));current(times);if(o.autoHeight){autoHeight(times)}if(slides<3){if(times===3){$(o.slides,$t).children(":eq(0)").css({left:(slides*width)})}if(times===2){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:width})}}$(o.slides,$t).animate({left:distance},o.slidespeed,function(){if(times===slides+1){times=1;$(o.slides,$t).css({left:0},function(){$(o.slides,$t).animate({left:distance})});$(o.slides,$t).children(":eq(0)").css({left:0});$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width})}if(times===slides)$(o.slides,$t).children(":eq(0)").css({left:(slides*width)});if(times===slides-1)$(o.slides,$t).children(":eq("+(slides-1)+")").css({left:(slides*width-width)});active=false});break;case"prev":times=times-1;distance=(-(times*width-width));current(times);if(o.autoHeight){autoHeight(times)}if(slides<3){if(times===0){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:(-width)})}if(times===1){$(o.slides,$t).children(":eq(0)").css({position:"absolute",left:0})}}$(o.slides,$t).animate({left:distance},o.slidespeed,function(){if(times===0){times=slides;$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:(slides*width-width)});$(o.slides,$t).css({left:-(slides*width-width)});$(o.slides,$t).children(":eq(0)").css({left:(slides*width)})}if(times===2)$(o.slides,$t).children(":eq(0)").css({position:"absolute",left:0});if(times===1)$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width});active=false});break;case"fade":times=[times]*1;distance=(-(times*width-width));current(times);if(o.autoHeight){autoHeight(times)}$(o.slides,$t).children().fadeOut(o.fadespeed,function(){$(o.slides,$t).css({left:distance});$(o.slides,$t).children(":eq("+(slides-1)+")").css({left:slides*width-width});$(o.slides,$t).children(":eq(0)").css({left:0});if(times===slides){$(o.slides,$t).children(":eq(0)").css({left:(slides*width)})}if(times===1){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width})}$(o.slides,$t).children().fadeIn(o.fadespeed);active=false});break;default:break}}})}});$.fn.loopedSlider.defaults={container:".container",slides:".slides",pagination:"pagination",containerClick:false,autoStart:0,restart:0,slidespeed:1000,fadespeed:200,autoHeight:0,addPagination:false}})}
$(function(){ $.fn.loopedSlider.defaults.addPagination = true; $('#loopedSlider').loopedSlider(); });



function showProductImage(imageId) {
	$("#detail-img img").each(function() {
		if($(this).attr("id") == imageId) {
			$(this).show();
		}
		else {
			$(this).hide();
		}
	});
}


function doFaqLinkThingy() {
	$(".faqs .question").click(function(){ $(this).next(".answer").slideToggle(300).addClass("add-border").siblings(".answer").slideUp("slow"); return false; });
	$('.question').hover(function(){ $(this).addClass('hover-faq') },function(){ $(this).removeClass('hover-faq')})
}


function updateProductFinder( obj ) {
	var separator = "|::|";
	var termId = $(obj).val();
	var object = 'surface';
	var tasks = $('#pf_tasks').val().split(separator);
	var tasksId = tasks[0];
	var tasksUrl = tasks[1];
	if($(obj).attr("id") == 'pf_tasks') {
		$('#pf_surface').val('');
	}
	var surface = $('#pf_surface').val().split(separator);
	var surfaceId = surface[0];
	var surfaceUrl = surface[1];
	
	if($(obj).attr("id") == 'pf_tasks') {
		$('#pf_product').attr("disabled", "disabled");
		$('#pf_product option[value!=""]').remove();
		$("#pf_redirecturl").val(tasksUrl);
	}
	else if($(obj).attr("id") == 'pf_surface') {
		if($(obj).val() == '') {
			$('#pf_product option[value!=""]').remove();
		}
		object = 'product';
		
		$("#pf_redirecturl").val(surfaceUrl);
	}
	else if($(obj).attr("id") == 'pf_product') {
		$("#pf_redirecturl").val($(obj).val());
		return;
	}
	
	if(termId != '') {
		$.post(ajaxurl, {
			tasks_id: tasksId,
			tasks_url: tasksUrl,
			surface_id: surfaceId,
			surface_url: surfaceUrl,
			object: object, 
			action: 'wpan_get_surfaces'
		}, function(result) {
			result = cleanAjaxResults(result);
			
			$('#pf_' + object).removeAttr('disabled');
			$('#pf_' + object + ' option[value!=""]').remove(); // Remove all items, except first one
			$('#pf_' + object).append(result);
			
			$("#productfinder_submit").removeClass("surface").removeClass("product");
			$("#productfinder_submit").addClass(object);			
		});	
	}
}

function updateFaqTerms(term_surface) {
	if(term_surface != '') {
		$('#faq-surface-list li').each(function() {
			var id = $(this).attr("id");
			var tmp_surface = id.substring(id.lastIndexOf("_") + 1);

			if(tmp_surface == term_surface) {
				$(this).addClass('current');
			}
			else {
				$(this).removeClass('current');
			}
		});
		
		
		$.post(ajaxurl, {
			ondergrond: term_surface,
			post_type: 'faq',
			action: 'wpan_get_second_taxo'
		}, function(result) {
			result = cleanAjaxResults(result);
			if(result.length > 0) {
				$('#faqs-tasks').slideDown();
				$('#faqs-tasks ul.faq-list').html(result);
			}
			
			showFaqs(term_surface, '');
		});
	}
	
	return false;
}

function showFaqs(surface, tasks) {
	if(tasks != '') {
		$('#faqs-tasks ul li').each(function() {
			var id = $(this).attr("id");
			var tmp_task = id.substring(id.lastIndexOf("_") + 1);

			if(tmp_task == tasks) {
				$(this).addClass('current');
			}
			else {
				$(this).removeClass('current');
			}
		});
	}
	
	$.post(ajaxurl, {
		ondergrond: surface,
		taak: tasks,
		action: 'wpan_get_faqs'
	}, function(result) {
		result = cleanAjaxResults(result);
		
		try {
			var json = $.parseJSON(result);
		
			// Empty faq results first
			$('#faqs-results').html('');
		
			var resultsTitle = 'Onze excuses, er zijn geen antwoorden gevonden op uw vraag';
			var resultsContent = '<p>Please try a broader search.</p></section>';
			
			if(parseInt(json.count) > 0) {
				var faqCount = parseInt(json.count);
				resultsTitle = 'Alle <span id="faqs-count">' + faqCount + '</span> veelgestelde vragen';
				resultsContent = json.output;
			}
		
			$('#faqs-results').html('<h2>' + resultsTitle + '</h2>').append('<section name="faqs-answer" id="faqs-answers" class="faqs">' + resultsContent + '</section>');
			updateFaqsCount();
			$('#faqs-results').slideDown();
		
			doFaqLinkThingy();			
		}
		catch(e) {
			console.log(e);
		}
	});
}

function updateFaqsCount() {
	var faqsCount = $('#faqs-answers article.faq').length;
	$('#faqs-count').html(faqsCount);
}

function addToCompare(productId) {
	var maxProducts = 3;
	var cookieName = 'wpan_compare';
	var expiresAfter = 7;
	var separator = ',';
	var currentCookie = $.cookie(cookieName);
	if(currentCookie == null) {
		currentCookie = '';
	}
	currentCookieArr = currentCookie.split(separator);
	if(currentCookieArr.length < maxProducts) {
		if(currentCookie != '') {		
			for(var i=0; i<maxProducts; i++) {
				if(currentCookieArr[i] == productId) {
					showMessage("<strong>Attentie:</strong> Dit product staat al in de vergelijking", "notification");
					return;
				}
			}
		}
		
		$.cookie(cookieName, currentCookie + (currentCookie != '' ? ',' : '') + productId, { path: '/', expires: expiresAfter });
		
		// Add to compare widget
		if($('section.widget_wpan_compare').length > 0) {
			// Get product info first
			$.post(ajaxurl, {
				product_id: productId,
				action: 'wpan_get_product_info'
			}, function(result) {
				result = cleanAjaxResults(result);

				// Hide "no products" message
				$('#wpan-compare-widget-error').empty().hide();

				try {
					var json = $.parseJSON(result);
					var nextCount = $('#widget-compare-product .related').length;

					var html = '<div class="related" style="display: none;" id="compare-product-item-' + nextCount + '">';
					html += '<span class="thumb">' + json.thumbnail + '</span> ';
					html += '<dl>';
					html += '<dt><a href="' + json.url + '">' + json.title + '</a></dt>'; 
					html += '</dl>';
					html += '</div>';

					$('#widget-compare-product').append(html);
					$('#compare-product-item-' + nextCount).fadeIn('normal', function() {
						$('#widget-compare-link').show();
					});
				}
				catch(e) {
					console.log(e);
				}
			});
		}
		
		showMessage("Het product is toegevoegd aan de vergelijking. Bekijk het <a href='http://www.alabastine.nl/vergelijken/'>vergelijkingsoverizcht</a>.", "");
	}
	else {
		showMessage("U kunt maximaal drie producten met elkaar vergelijken.", "notification");
	}
	
	return;
}

function removeFromCompare(productId) {
	var cookieName = 'wpan_compare';
	
	jConfirm('Weet u zeker dat u het item uit de vergelijking wilt halen?', '', function(r) {
		if(r == 'true' || r == true) {
			removeItemFromCookie(cookieName, productId);
			location.reload(true);
		}
	});
}

function addToWishlist(productId) {
	var cookieName = 'wpan_wishlist';
	var expiresAfter = 7;
	var separator = ',';
	var currentCookie = $.cookie(cookieName);
	if(currentCookie == null) {
		currentCookie = '';
	}
	currentCookieArr = currentCookie.split(separator);

	if(currentCookie != '') {		
		for(var i=0; i<currentCookieArr.length; i++) {
			if(currentCookieArr[i] == productId) {
				showMessage("<strong>Attentie:</strong> Het product bestaat al op uw boodschappenlijst. <a href=\"http://www.alabastine.nl/boodschappenlijst/\">Ga naar uw boodschappenlijst.</a>", "notification");
				return;
			}
		}
	}
	
	$.cookie(cookieName, currentCookie + (currentCookie != '' ? ',' : '') + productId, { path: '/', expires: expiresAfter });
	$('#wishlist-counter').html(parseInt($('#wishlist-counter').html()) + 1);
	
	showMessage("Het product is toegevoegd op uw boodschappenlijst", "");
	
	return;
}

function removeFromWishlist(productId) {
	var speed = "normal";
	var cookieName = 'wpan_wishlist';
	
	//jConfirm('Weet u zeker dat u het item van de boodschappenlijst wilt verwijderen', '', function(r) {
	//	if(r == 'true' || r == true) {
			removeItemFromCookie(cookieName, productId);

			$('#wishlist-section-' + productId).slideUp(speed, function() {
				$(this).remove();
			});

			$('#wishlist-counter').html(parseInt($('#wishlist-counter').html()) - 1);
			showMessage("Het product is weggehaald van uw boodschappenlijst", "");
	//	}
	//});
}

function clearWishlist() {
	jConfirm('Weet u zeker dat u deze lijst wilt leegmaken?', '', function(r) {
		if(r == 'true' || r == true) {
			$('#wishlist section.overview').fadeOut("normal");
			$.cookie('wpan_wishlist', null,  {path: '/', expires: -10 });
			$('#wishlist-counter').html("0");
			
			showMessage("De boodschappenlijst is leeg gemaakt", "notification");
		}
	});
}

function removeItemFromCookie(cookieName, item) {
	var expiresAfter = 7;
	var separator = ',';
	var currentCookie = $.cookie(cookieName);
	if(currentCookie == null) {
		currentCookie = '';
	}
	currentCookieArr = currentCookie.split(separator);
	
	var i = 0;
	
	while(i < currentCookieArr.length) {
		if(currentCookieArr[i] == item) {
			currentCookieArr.splice(i, 1);
		}
		else {
			i++;
		}
	}
	currentCookie = currentCookieArr.join(separator);
	$.cookie(cookieName, currentCookie, { path: '/', expires: expiresAfter });
}

function showMessage(msg, type) {
	$.alerts.draggable = false;
	$.alerts.okButton = '';
	$.alerts.overlayOpacity = 0;
	$.alerts.showClose = true;
	$.alerts.preventHide = false;
	$.alerts.closeText = "Sluit opmerking";
	
	jAlert(msg, type);
}

function cleanAjaxResults(result) {
	// Sometimes AJAX adds a zero in the results. Skip it!
	if(result.charAt(result.length - 1) == 0) {
		result = result.slice(0, -1);
	}
	else if(result.substring(result.length - 2) == "-1") {
		result = result.slice(0, -2);
	}
	
	return result;
}

$(document).ready(function () {
	$(".dislike, .colorbox-iframe").colorbox({iframe:true, innerWidth:700, innerHeight:520});
	$(".video-link").colorbox({iframe:true, innerWidth:525, innerHeight:344});
	$("#detail-img a.colorbox, a.colorbox").colorbox();
	
	
	var searchUrl = 'http://www.alabastine.nl/wp-content/uploads/wpan-data/all-products.json';
	//var searchUrl = 'http://www.alabastine.nl/search-xml/';
	$.getJSON(searchUrl, function(data) {
		$('input#s').autocomplete( data, {
			minChars: 1,
			max: 5, 
			width: 180,
			matchContains: true,
			highlightItem: false,
			selectFirst: true,
			dataType: 'json',
		    extraParams: {
		        format: 'json'
		    },
			parse: function(data) {
				var parsed = [];
		        for (var i = 0; i < data.length; i++) {
		            parsed[parsed.length] = {
		                data: data[i],
		                value: data[i].post_title,
		                result: data[i].post_title
		            };
		        }

		        return parsed;
			},
			formatItem: function(item) {
				return item.post_title;
		    }

		});
	});
	
	$('.scroll').click(function(event) {
		//prevent the default action for the click event
		event.preventDefault();

		var full_url = this.href;
		var parts = full_url.split("#");
		var trgt = parts[1];
		var target_offset = parseInt($("#"+trgt).offset().top);

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_offset}, 500);
	});
	
	
	if($("#single-product").length > 0 || $("#single-tutorial").length > 0) {
		var referrer = document.referrer;
		if(referrer) {
			var postType = 'product';
			var html = '<a href="javascript: history.go(-1)">';
			if($("#single-product").length > 0) {
				html += '(Terug naar het overzicht)';

			}
			else if($("#single-tutorial").length > 0) {
				postType = 'tutorial';
				html += 'Terug naar het product';
			}
			
			html += '</a>';

			if($("#single-tutorial").length > 0 && referrer.indexOf('/product/') > -1) {
				var h1 = $("#single-" + postType + " h1").html($("#single-" + postType + " h1").html() + " " + html);
			}
		}
	}
	
	if($("#productfinder_submit").length > 0) {
		$("#productfinder_submit").click(function() {
			if($("#pf_redirecturl").val() != '') {
				window.location = $("#pf_redirecturl").val();
				return false;
			}
		});
		
		// Reset product finder form
		$('#pf_tasks').val('');
		$('#pf_surface option[value!=""], #pf_product option[value!=""]').remove();
		$('#pf_surface, #pf_product').attr('disabled', 'disabled');
	}	
});


(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest).css("overflow","hidden");
		});
	}
})(jQuery);

$(".slides div ul, .slide-container div ul").equalHeights(235,235);
$(".slides div .title, .slide-container li.title").equalHeights(45,45);


/**
 * jQuery cookies from http://plugins.jquery.com/project/Cookie
 */
jQuery.cookie = function(name, value, options) {
	
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: 'OK',         			// text for the OK button
		cancelButton: 'Annuleren', 			// text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		hideTimeout: 4000, 					// number of miliseconds before dialog disappears
		preventHide: true,					// Prevent the automatic hide of the dialog
		showClose: false, 					// Show close link
		closeText: 'x',						// Close text
		// Public methods
		
		alert: function(message, type, title, callback) {
			$.alerts._show(title, message, type, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			$.alerts._show(title, message, 'notification', null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			$.alerts._show(title, message, 'notification', value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, messageType, value, type, callback, showClose, closeText) {
			$.alerts._hide();
			$.alerts._overlay('show');
			$("BODY").append(
			  '<div id="popup_container">' +
				( $.alerts.showClose ? '<a href="javascript:;" class="close-popup" id="popup_close_btn">' + $.alerts.closeText + '</a>' : '' ) +
				( title != '' ? '<h1 id="popup_title"></h1>' : '' ) + 
			    '<div id="popup_content">' +
			      '<p id="popup_message"></p>' +
				'</div>' +
			  '</div>');
			
			$('#popup_container').fadeIn("normal");
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			if($.alerts.showClose) {
				$("#popup_close_btn").click(function() {
					$.alerts._hide();
				});
			}
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999
			});
			
			$("#popup_title").text(title);
			$("#popup_message").addClass(messageType);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
						
			switch( type ) {
				case 'alert':
					if($.alerts.okButton != '') {
						$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					}
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});

					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$.alerts.okButton = 'OK';
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
			
			if(!$.alerts.preventHide) {
				setTimeout('$.alerts._hide()', $.alerts.hideTimeout);
			}
		},
		
		_hide: function() {
			$("#popup_container").fadeOut("normal", function() {
				$(this).remove();
				$.alerts._overlay('hide');
				$.alerts._maintainPosition(false);
			});
			
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
					
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, type, title, callback) {
		$.alerts.alert(message, type, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);

// ColorBox v1.3.17.1 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2011 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function ($, document, window) {
	var
	// ColorBox Default Settings.	
	// See http://colorpowered.com/colorbox for details.
	defaults = {
		transition: "elastic",
		speed: 300,
		width: false,
		initialWidth: "600",
		innerWidth: false,
		maxWidth: false,
		height: false,
		initialHeight: "450",
		innerHeight: false,
		maxHeight: false,
		scalePhotos: true,
		scrolling: true,
		inline: false,
		html: false,
		iframe: false,
		fastIframe: true,
		photo: false,
		href: false,
		title: false,
		rel: false,
		opacity: 0.9,
		preloading: true,
		current: "image {current} of {total}",
		previous: "previous",
		next: "next",
		close: "close",
		open: false,
		returnFocus: true,
		loop: true,
		slideshow: false,
		slideshowAuto: true,
		slideshowSpeed: 2500,
		slideshowStart: "start slideshow",
		slideshowStop: "stop slideshow",
		onOpen: false,
		onLoad: false,
		onComplete: false,
		onCleanup: false,
		onClosed: false,
		overlayClose: true,		
		escKey: true,
		arrowKey: true,
        top: false,
        bottom: false,
        left: false,
        right: false,
        fixed: false,
        data: false
	},
	
	// Abstracting the HTML and event identifiers for easy rebranding
	colorbox = 'colorbox',
	prefix = 'cbox',
	
	// Events	
	event_open = prefix + '_open',
	event_load = prefix + '_load',
	event_complete = prefix + '_complete',
	event_cleanup = prefix + '_cleanup',
	event_closed = prefix + '_closed',
	event_purge = prefix + '_purge',
	
	// Special Handling for IE
	isIE = $.browser.msie && !$.support.opacity, // Detects IE6,7,8.  IE9 supports opacity.  Feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome, hence the user-agent test.
	isIE6 = isIE && $.browser.version < 7,
	event_ie6 = prefix + '_IE6',

	// Cached jQuery Object Variables
	$overlay,
	$box,
	$wrap,
	$content,
	$topBorder,
	$leftBorder,
	$rightBorder,
	$bottomBorder,
	$related,
	$window,
	$loaded,
	$loadingBay,
	$loadingOverlay,
	$title,
	$current,
	$slideshow,
	$next,
	$prev,
	$close,
	$groupControls,

	// Variables for cached values or use across multiple functions
	settings = {},
	interfaceHeight,
	interfaceWidth,
	loadedHeight,
	loadedWidth,
	element,
	index,
	photo,
	open,
	active,
	closing,
    handler,
    loadingTimer,
	
	publicMethod,
	boxElement = prefix + 'Element';
	
	// ****************
	// HELPER FUNCTIONS
	// ****************

	// jQuery object generator to reduce code size
	function $div(id, cssText) { 
		var div = document.createElement('div');
		if (id) {
            div.id = prefix + id;
        }
		div.style.cssText = cssText || '';
		return $(div);
	}

	// Convert % values to pixels
	function setSize(size, dimension) {
		dimension = dimension === 'x' ? $window.width() : $window.height();
		return (typeof size === 'string') ? Math.round((/%/.test(size) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size;
	}
	
	// Checks an href to see if it is a photo.
	// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
	function isImage(url) {
		return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
	}
	
	// Assigns function results to their respective settings.  This allows functions to be used as values.
	function process(settings) {
		for (var i in settings) {
			if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
			    settings[i] = settings[i].call(element);
			}
		}
        
		settings.rel = settings.rel || element.rel || 'nofollow';
		settings.href = settings.href || $(element).attr('href');
		settings.title = settings.title || element.title;
        
        if (typeof settings.href === "string") {
            settings.href = $.trim(settings.href);
        }
	}

	function trigger(event, callback) {
		if (callback) {
			callback.call(element);
		}
		$.event.trigger(event);
	}

	// Slideshow functionality
	function slideshow() {
		var
		timeOut,
		className = prefix + "Slideshow_",
		click = "click." + prefix,
		start,
		stop,
		clear;
		
		if (settings.slideshow && $related[1]) {
			start = function () {
				$slideshow
					.text(settings.slideshowStop)
					.unbind(click)
					.bind(event_complete, function () {
						if (index < $related.length - 1 || settings.loop) {
							timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
						}
					})
					.bind(event_load, function () {
						clearTimeout(timeOut);
					})
					.one(click + ' ' + event_cleanup, stop);
				$box.removeClass(className + "off").addClass(className + "on");
				timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
			};
			
			stop = function () {
				clearTimeout(timeOut);
				$slideshow
					.text(settings.slideshowStart)
					.unbind([event_complete, event_load, event_cleanup, click].join(' '))
					.one(click, start);
				$box.removeClass(className + "on").addClass(className + "off");
			};
			
			if (settings.slideshowAuto) {
				start();
			} else {
				stop();
			}
		} else {
            $box.removeClass(className + "off " + className + "on");
        }
	}

	function launch(elem) {
		if (!closing) {
			
			element = elem;
			
			process($.extend(settings, $.data(element, colorbox)));
			
			$related = $(element);
			
			index = 0;
			
			if (settings.rel !== 'nofollow') {
				$related = $('.' + boxElement).filter(function () {
					var relRelated = $.data(this, colorbox).rel || this.rel;
					return (relRelated === settings.rel);
				});
				index = $related.index(element);
				
				// Check direct calls to ColorBox.
				if (index === -1) {
					$related = $related.add(element);
					index = $related.length - 1;
				}
			}
			
			if (!open) {
				open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
				
				$box.show();
				
				if (settings.returnFocus) {
					try {
						element.blur();
						$(element).one(event_closed, function () {
							try {
								this.focus();
							} catch (e) {
								// do nothing
							}
						});
					} catch (e) {
						// do nothing
					}
				}
				
				// +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5'
				$overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show();
				
				// Opens inital empty ColorBox prior to content being loaded.
				settings.w = setSize(settings.initialWidth, 'x');
				settings.h = setSize(settings.initialHeight, 'y');
				publicMethod.position(0);
				
				if (isIE6) {
					$window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () {
						$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
					}).trigger('resize.' + event_ie6);
				}
				
				trigger(event_open, settings.onOpen);
				
				$groupControls.add($title).hide();
				
				$close.html(settings.close).show();
			}
			
			publicMethod.load(true);
		}
	}

	// ****************
	// PUBLIC FUNCTIONS
	// Usage format: $.fn.colorbox.close();
	// Usage from within an iframe: parent.$.fn.colorbox.close();
	// ****************
	
	publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
		var $this = this, autoOpen;
		
		if (!$this[0] && $this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit.
			return $this;
		}
		
		options = options || {};
		
		if (callback) {
			options.onComplete = callback;
		}
		
		if (!$this[0] || $this.selector === undefined) { // detects $.colorbox() and $.fn.colorbox()
			$this = $('<a/>');
			options.open = true; // assume an immediate open
		}
		
		$this.each(function () {
			$.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options));
			$(this).addClass(boxElement);
		});
		
		autoOpen = options.open;
		
		if ($.isFunction(autoOpen)) {
			autoOpen = autoOpen.call($this);
		}
		
		if (autoOpen) {
			launch($this[0]);
		}
		
		return $this;
	};

	// Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
	// This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only
	// having to run once, instead of each time colorbox is opened.
	publicMethod.init = function () {
		// Create & Append jQuery Objects
		$window = $(window);
		$box = $div().attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''});
		$overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide();
		
		$wrap = $div("Wrapper");
		$content = $div("Content").append(
			$loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'),
			$loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")),
			$title = $div("Title"),
			$current = $div("Current"),
			$next = $div("Next"),
			$prev = $div("Previous"),
			$slideshow = $div("Slideshow").bind(event_open, slideshow),
			$close = $div("Close")
		);
		$wrap.append( // The 3x3 Grid that makes up ColorBox
			$div().append(
				$div("TopLeft"),
				$topBorder = $div("TopCenter"),
				$div("TopRight")
			),
			$div(false, 'clear:left').append(
				$leftBorder = $div("MiddleLeft"),
				$content,
				$rightBorder = $div("MiddleRight")
			),
			$div(false, 'clear:left').append(
				$div("BottomLeft"),
				$bottomBorder = $div("BottomCenter"),
				$div("BottomRight")
			)
		).children().children().css({'float': 'left'});
		
		$loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none');
		
		$('body').prepend($overlay, $box.append($wrap, $loadingBay));
		
		$content.children()
		.hover(function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		}).addClass('hover');
		
		// Cache values needed for size calculations
		interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6
		interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
		loadedHeight = $loaded.outerHeight(true);
		loadedWidth = $loaded.outerWidth(true);
		
		// Setting padding to remove the need to do size conversions during the animation step.
		$box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();
		
        // Setup button events.
        $next.click(function () {
            publicMethod.next();
        });
        $prev.click(function () {
            publicMethod.prev();
        });
        $close.click(function () {
            publicMethod.close();
        });
		
		$groupControls = $next.add($prev).add($current).add($slideshow);
		
		// Adding the 'hover' class allowed the browser to load the hover-state
		// background graphics.  The class can now can be removed.
		$content.children().removeClass('hover');
		


        
		$overlay.click(function () {
			if (settings.overlayClose) {
				publicMethod.close();
			}
		});
		
		// Set Navigation Key Bindings
		$(document).bind('keydown.' + prefix, function (e) {
            var key = e.keyCode;
			if (open && settings.escKey && key === 27) {
				e.preventDefault();
				publicMethod.close();
			}
			if (open && settings.arrowKey && $related[1]) {
				if (key === 37) {
					e.preventDefault();
					$prev.click();
				} else if (key === 39) {
					e.preventDefault();
					$next.click();
				}
			}
		});
	};
	
	publicMethod.remove = function () {
		$box.add($overlay).remove();
		$('.' + boxElement).removeData(colorbox).removeClass(boxElement);
	};

	publicMethod.position = function (speed, loadedCallback) {
        var animate_speed, top = 0, left = 0;
        
        // remove the modal so that it doesn't influence the document width/height        
        $box.hide();
        
        if (settings.fixed && !isIE6) {
            $box.css({position: 'fixed'});
        } else {
            top = $window.scrollTop();
            left = $window.scrollLeft();
            $box.css({position: 'absolute'});
        }
        
		// keeps the top and left positions within the browser's viewport.
        if (settings.right !== false) {
            left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0);
        } else if (settings.left !== false) {
            left += setSize(settings.left, 'x');
        } else {
            left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2;
        }
        
        if (settings.bottom !== false) {
            top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0);
        } else if (settings.top !== false) {
            top += setSize(settings.top, 'y');
        } else {
            top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2;
        }
        
        $box.show();
        
		// setting the speed to 0 to reduce the delay between same-sized content.
		animate_speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed;
        
		// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
		// but it has to be shrank down around the size of div#colorbox when it's done.  If not,
		// it can invoke an obscure IE bug when using iframes.
		$wrap[0].style.width = $wrap[0].style.height = "9999px";
		
		function modalDimensions(that) {
			// loading overlay height has to be explicitly set for IE6.
			$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
			$loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
		}
		
		$box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, {
			duration: animate_speed,
			complete: function () {
				modalDimensions(this);
				
				active = false;
				
				// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
				$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
				$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
				
				if (loadedCallback) {
					loadedCallback();
				}
			},
			step: function () {
				modalDimensions(this);
			}
		});
	};

	publicMethod.resize = function (options) {
		if (open) {
			options = options || {};
			
			if (options.width) {
				settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
			}
			if (options.innerWidth) {
				settings.w = setSize(options.innerWidth, 'x');
			}
			$loaded.css({width: settings.w});
			
			if (options.height) {
				settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
			}
			if (options.innerHeight) {
				settings.h = setSize(options.innerHeight, 'y');
			}
			if (!options.innerHeight && !options.height) {				
				var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be.
				settings.h = $child.height();
				$child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation
			}
			$loaded.css({height: settings.h});
			
			publicMethod.position(settings.transition === "none" ? 0 : settings.speed);
		}
	};

	publicMethod.prep = function (object) {
		if (!open) {
			return;
		}
		
		var speed = settings.transition === "none" ? 0 : settings.speed;
		
		$window.unbind('resize.' + prefix);
		$loaded.remove();
		$loaded = $div('LoadedContent').html(object);
		
		function getWidth() {
			settings.w = settings.w || $loaded.width();
			settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
			return settings.w;
		}
		function getHeight() {
			settings.h = settings.h || $loaded.height();
			settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
			return settings.h;
		}
		
		$loaded.hide()
		.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
		.css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'})
		.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);
		
		$loadingBay.hide();
		
		// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
		//$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'});
		
        $(photo).css({'float': 'none'});
        
		// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
		if (isIE6) {
			$('select').not($box.find('select')).filter(function () {
				return this.style.visibility !== 'hidden';
			}).css({'visibility': 'hidden'}).one(event_cleanup, function () {
				this.style.visibility = 'inherit';
			});
		}
		
		function setPosition(s) {
			publicMethod.position(s, function () {
				var prev, prevSrc, next, nextSrc, total = $related.length, iframe, complete;
				
				if (!open) {
					return;
				}
				
                function removeFilter() {
                    if (isIE) {
                        $box[0].style.removeAttribute('filter');
                    }
                }
                
				complete = function () {
                    clearTimeout(loadingTimer);
					$loadingOverlay.hide();
					trigger(event_complete, settings.onComplete);
				};
				
				if (isIE) {
					//This fadeIn helps the bicubic resampling to kick-in.
					if (photo) {
						$loaded.fadeIn(100);
					}
				}
				
				$title.html(settings.title).add($loaded).show();
				
				if (total > 1) { // handle grouping
					if (typeof settings.current === "string") {
						$current.html(settings.current.replace(/\{current\}/, index + 1).replace(/\{total\}/, total)).show();
					}
					
					$next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next);
					$prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous);
					
					prev = index ? $related[index - 1] : $related[total - 1];
					next = index < total - 1 ? $related[index + 1] : $related[0];
					
					if (settings.slideshow) {
						$slideshow.show();
					}
					
					// Preloads images within a rel group
					if (settings.preloading) {
						nextSrc = $.data(next, colorbox).href || next.href;
						prevSrc = $.data(prev, colorbox).href || prev.href;
						
						nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc;
						prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc;
						
						if (isImage(nextSrc)) {
							$('<img/>')[0].src = nextSrc;
						}
						
						if (isImage(prevSrc)) {
							$('<img/>')[0].src = prevSrc;
						}
					}
				} else {
					$groupControls.hide();
				}
				
				if (settings.iframe) {
					iframe = $('<iframe/>').addClass(prefix + 'Iframe')[0];
					
					if (settings.fastIframe) {
						complete();
					} else {
						$(iframe).one('load', complete);
					}
					iframe.name = prefix + (+new Date());
					iframe.src = settings.href;
					
					if (!settings.scrolling) {
						iframe.scrolling = "no";
					}
					
					if (isIE) {
                        iframe.frameBorder = 0;
						iframe.allowTransparency = "true";
					}
					
					$(iframe).appendTo($loaded).one(event_purge, function () {
						iframe.src = "//about:blank";
					});
				} else {
					complete();
				}
				
				if (settings.transition === 'fade') {
					$box.fadeTo(speed, 1, removeFilter);
				} else {
                    removeFilter();
				}
				
				$window.bind('resize.' + prefix, function () {
					publicMethod.position(0);
				});
			});
		}
		
		if (settings.transition === 'fade') {
			$box.fadeTo(speed, 0, function () {
				setPosition(0);
			});
		} else {
			setPosition(speed);
		}
	};

	publicMethod.load = function (launched) {
		var href, setResize, prep = publicMethod.prep;
		
		active = true;
		
		photo = false;
		
		element = $related[index];
		
		if (!launched) {
			process($.extend(settings, $.data(element, colorbox)));
		}
		
		trigger(event_purge);
		
		trigger(event_load, settings.onLoad);
		
		settings.h = settings.height ?
				setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
				settings.innerHeight && setSize(settings.innerHeight, 'y');
		
		settings.w = settings.width ?
				setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
				settings.innerWidth && setSize(settings.innerWidth, 'x');
		
		// Sets the minimum dimensions for use in image scaling
		settings.mw = settings.w;
		settings.mh = settings.h;
		
		// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
		// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
		if (settings.maxWidth) {
			settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
			settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
		}
		if (settings.maxHeight) {
			settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
			settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
		}
		
		href = settings.href;
		
        loadingTimer = setTimeout(function () {
            $loadingOverlay.show();
        }, 100);
        
		if (settings.inline) {
			// Inserts an empty placeholder where inline content is being pulled from.
			// An event is bound to put inline content back when ColorBox closes or loads new content.
			$div().hide().insertBefore($(href)[0]).one(event_purge, function () {
				$(this).replaceWith($loaded.children());
			});
			prep($(href));
		} else if (settings.iframe) {
			// IFrame element won't be added to the DOM until it is ready to be displayed,
			// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
			prep(" ");
		} else if (settings.html) {
			prep(settings.html);
		} else if (isImage(href)) {
			$(photo = new Image())
			.addClass(prefix + 'Photo')
			.error(function () {
				settings.title = false;
				prep($div('Error').text('This image could not be loaded'));
			})
			.load(function () {
				var percent;
				photo.onload = null; //stops animated gifs from firing the onload repeatedly.
				
				if (settings.scalePhotos) {
					setResize = function () {
						photo.height -= photo.height * percent;
						photo.width -= photo.width * percent;	
					};
					if (settings.mw && photo.width > settings.mw) {
						percent = (photo.width - settings.mw) / photo.width;
						setResize();
					}
					if (settings.mh && photo.height > settings.mh) {
						percent = (photo.height - settings.mh) / photo.height;
						setResize();
					}
				}
				
				if (settings.h) {
					photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px';
				}
				
				if ($related[1] && (index < $related.length - 1 || settings.loop)) {
					photo.style.cursor = 'pointer';
					photo.onclick = function () {
                        publicMethod.next();
                    };
				}
				
				if (isIE) {
					photo.style.msInterpolationMode = 'bicubic';
				}
				
				setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise.
					prep(photo);
				}, 1);
			});
			
			setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise.
				photo.src = href;
			}, 1);
		} else if (href) {
			$loadingBay.load(href, settings.data, function (data, status, xhr) {
				prep(status === 'error' ? $div('Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents());
			});
		}
	};
        
	// Navigates to the next page/image in a set.
	publicMethod.next = function () {
		if (!active && $related[1] && (index < $related.length - 1 || settings.loop)) {
			index = index < $related.length - 1 ? index + 1 : 0;
			publicMethod.load();
		}
	};
	
	publicMethod.prev = function () {
		if (!active && $related[1] && (index || settings.loop)) {
			index = index ? index - 1 : $related.length - 1;
			publicMethod.load();
		}
	};

	// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
	publicMethod.close = function () {
		if (open && !closing) {
			
			closing = true;
			
			open = false;
			
			trigger(event_cleanup, settings.onCleanup);
			
			$window.unbind('.' + prefix + ' .' + event_ie6);
			
			$overlay.fadeTo(200, 0);
			
			$box.stop().fadeTo(300, 0, function () {
                 
				$box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide();
				
				trigger(event_purge);
				
				$loaded.remove();
				
				setTimeout(function () {
					closing = false;
					trigger(event_closed, settings.onClosed);
				}, 1);
			});
		}
	};

	// A method for fetching the current element ColorBox is referencing.
	// returns a jQuery object.
	publicMethod.element = function () {
		return $(element);
	};

	publicMethod.settings = defaults;
    
	// Bind the live event before DOM-ready for maximum performance in IE6 & 7.
    handler = function (e) {
        // checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt.
        if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) {
            e.preventDefault();
            launch(this);
        }
    };
    
    if ($.fn.delegate) {
        $(document).delegate('.' + boxElement, 'click', handler);
    } else {
        $('.' + boxElement).live('click', handler);
    }
    
	// Initializes ColorBox when the DOM has loaded
	$(publicMethod.init);

}(jQuery, document, this));
