/**
 * Bootstrap.js - Bootstrap for all Javascript functionality
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

var galleryCt, overlay;

WS.DOM.ready(function() {
	if($('js-error-panel')) {
		$('js-error-panel').hide();
	}
	
	// External links
	var a = document.getElementsByTagName('a');
	for(var i = 0; i < a.length; i++) {
		if(/external/.test(a[i].rel)) {
			a[i].target = '_blank';
		}
	}
	
	// IE6 hover
	if(WS.browser.IE6){var hoverEls=$('navigation').getElementsByTagName('li');for(var i=0;i<hoverEls.length;i++){WS.Event.addEvent(hoverEls[i],'mouseover',function(){WS.addClass(this,'iehover');});WS.Event.addEvent(hoverEls[i],'mouseout',function(){WS.removeClass(this,'iehover');});}}
	
	// Toggle input values
	var inputs = WS.DOM.getElementsByClass('toggle-value');
	for(var j = 0; j < inputs.length; j++) {
		var v = inputs[j].value;
		inputs[j].onfocus = function() {
			if(this.value == v) {
				this.value = '';
			}
			WS.addClass(this, 'focus');
		};
		inputs[j].onblur = function() {
			if(this.value == '') {
				this.value = v;
				WS.removeClass(this, 'focus');
			}
		};
	}
	
	// Homepage carousel
	if($('carousel')) {
		new Carousel('carousel-viewport', $$('#carousel-content .carousel-item'), $$('a.carousel-control', 'a.carousel-jumper'), {
			auto: true,
			frequency: 5,
			circular: true,
			beforeMove: function() {
				$('carousel-title').fade({ duration: 0.5, from: 1, to: 0.01 });
				$('carousel-price').fade({ duration: 0.5, from: 1, to: 0.01 });
			},
			afterMove: function(current) { // Added "this.current" in "this.options.afterMove(this.current);" [file: carousel.js]
				$('carousel-title').innerHTML = WS.DOM.getChild(current, 1).alt; // Now we can access the carousel's current slide
				$('carousel-title').appear({ duration: 0.5 });
				var values = current.id.split('-');
				setCarouselPrice(values[0], values[1]);
			}
		});
	}
	
	// Product detail gallery-wrap
	if($('gallery-wrap')) {
		overlay = $('loading-overlay').hide();
		
		galleryCt = new Carousel('inner-thumbnails', $$('#thumbnails-content a'), $$('#thumbnails a.carousel-control', '#thumbnails a.carousel-jumper'), {
			duration: 0.5
		});
		
		Event.observe('main-image', 'load', function() {
			setTimeout(function() {
				overlay.hide();
			}, 100);
		});
		
		$$('#thumbnails-content a').each(function(el) {
			Event.observe(el, 'click', function(e) {
				Event.stop(e);
				thumbChanged(el);
				setImage(el.href);				
			});
		});
	}
	
	// Testimonials
	if($('testimonials')) {
		new Carousel('testimonial-scroller', $$('#testimonial-scroller blockquote'), $$('#testimonials a.carousel-control', '#testimonials a.carousel-jumper'), {
			auto: true,
			frequency: 8,
			circular: true
		});
	}
	
	// Set select
	if($$('.set-select').length > 0) {
		Event.observe($('sets'), 'click', function() {
			$$('.set-select').each(function(el) {
				if(el.checked) {
					var values = el.value.split('-');
					var roomname = window.location.href.split('/')[window.location.href.split('/').length-1];
					window.location.href = 'http://www.babykamer.nl/babykamer/'+values[0]+'/'+values[1]+'/'+roomname;
				}
			});
		});
	}
	
	// Colorpicker select
	if($('colorpicker-select')) {
		WS.Event.addEvent('colorpicker-select', 'change', function() {
			$('order-colorpicker-select').selectedIndex = this.selectedIndex;
			colorChanged(this);
		});
	}
	
	if($('order-colorpicker-select')) {
		WS.Event.addEvent('order-colorpicker-select', 'change', function(){
			$('colorpicker-select').selectedIndex = this.selectedIndex;
			colorChanged(this);
		});
	}
	
	// Colorpicker select cart
	/*var cartSelects = WS.DOM.getElementsByClass('color-select');
	for(var i = 0; i < cartSelects.length; i++) {
		WS.Event.addEvent(cartSelects[i], 'change', function(e) {
			var el = WS.Event.getTarget(e);
			var values = el.value.split('-');
			var postBody = 'roomid=' + values[1] + '&colorid=' + values[2] + '&roomkey=' + values[3];
			WS.Ajax.request('http://www.babykamer.nl/getcartprice', function(response) {
				$('price').innerHTML = response;
			}, postBody);
		});
	}*/
	
	// Tabs
	var productTabs = new Tabs('product-tabs');
	productTabs.initialize();
	
	var relatedTabs = new Tabs('related-tabs');
	relatedTabs.initialize();
	
	// Form validation
	var checkoutVal = new WS.Validation('checkout-form');
	checkoutVal.initialize();
	
	var contactVal = new WS.Validation('contact-form');
	contactVal.initialize();
	
	var tellafriendVal = new WS.Validation('tellafriend-form');
	tellafriendVal.initialize();
	
	// Lightwindow
	if($('tellafriend')) {
		$('tellafriend').observe('click', function(e) {
			Event.stop(e);
			myLightWindow.activateWindow({
				href: this.href,
				title: this.title,
				width: 520,
				height: 260,
				type: 'external'
			});
		});
	}
	
	if($('tellafriendroom')) {
		$('tellafriendroom').observe('click', function(e) {
			Event.stop(e);
			myLightWindow.activateWindow({
				href: this.href,
				title: this.title,
				width: 520,
				height: 260,
				type: 'external'
			});
		});
	}
	
	// Checkout form
	if($('checkout-form')) {
		var initialPrice = parseFloat(priceFormat($('checkout-price').innerHTML));
		
		var additions = {
			deliver: 75.00,
			assembly: 175.00,
			ideal: 1.00,
			rembours: 15.00
		};
		
		if($('deliver').checked) {
			setCheckoutPrice(initialPrice+additions.deliver);
		}
		
		if(!$('shipment-week').checked) {
			$('shipment-week-value').disabled = true;
		}
		
		WS.Event.addEvent('checkout-form', 'click', function(e) {
			var newPrice = initialPrice;
			
			/*if($('pickup').checked) {
				$('rembours').checked = false;
				$('rembours').disabled = true;
			}
			else if($('rembours').disabled) {
				$('rembours').disabled = false;
			}*/
			
			if($('deliver').checked || $('assembly').checked) {
				$('cash').checked = false;
				$('cash').disabled = true;
				if($('deliver').checked) {
					newPrice += additions.deliver;
				} else if($('assembly').checked) {
					newPrice += additions.assembly;
				}
			} else if($('cash').disabled) {
				$('cash').disabled = false;
			}
			
			if($('shipment-week').checked) {
				$('shipment-week-value').disabled = false;
			} else {
				$('shipment-week-value').disabled = true;
			}
			
			/*if($('ideal').checked) {
				newPrice += additions.ideal;
			}*/
			if($('rembours').checked) {
				newPrice += additions.rembours;
			}
			
			setCheckoutPrice(newPrice);
		});
	}
	
	
	if($$('.cart-overview .color-select').length > 0) {
		$$('.cart-overview .color-select').each(function(el) {
			WS.Event.addEvent(el, 'change', function(e) {
				var color = el.value.split('-');				
				var postBody = 'roomid=' + color[1] + '&colorid=' + color[2] + '&productkey=' + color[3];
				WS.Ajax.request('http://www.babykamer.nl/setcolor', function(response) {
					
				}, postBody);
			});
		});		
	}
});

/**
 * Handle thumb onclick event
 * 
 * @param {Object} el The ANCHOR element firing onclick
 */
function thumbChanged(el) {
	var values = el.id.split('-');
	var colors = $('colorpicker-select').getElementsByTagName('option');
	for(var i = 0; i < colors.length; i++) {
		var color = colors[i].value.split('-');
		if(color[1] == values[2]) {
			$('order-colorpicker-select').selectedIndex = i;
			$('colorpicker-select').selectedIndex = i;
			var postBody = 'roomid=' + color[0] + '&colorid=' + color[1];
			WS.Ajax.request('http://www.babykamer.nl/getprice', function(response) {
				parsePrice(response);
			}, postBody);
		}
	}
}

function cartColorChanged(el) {
	var values = el.id.split('-');
	console.log(values);	
}

/**
 * Sets the gallery image to display
 * 
 * @param {String} src The source of the image
 */
function setImage(src) {
	overlay.show();
	$('main-image').src = src;
	$('gallery-zoom').href = src.replace(/resources\/(.*)\//, 'resources/$1/large/');
};

/**
 * Handle colorpicker onchange event
 * 
 * @param {Object} select The SELECT element firing onchange
 */
function colorChanged(select) {
	var values = select.value.split('-');
	var item = $('color-hook-' + values[1]);
	
	if(item) {	
		galleryCt.moveTo(item);
		setImage(item.href);
	}
	
	if(values[3] == 'room') {
		var postBody = 'roomid=' + values[0] + '&colorid=' + values[1] + '&setid=' + values[2] + '&type=room';
	} else if(values[3] == 'product') {
		var postBody = 'productid=' + values[0] + '&colorid=' + values[1] + '&setid=' + values[2] + '&type=product';
	}
	WS.Ajax.request('http://www.babykamer.nl/getprice', function(response) {
		parsePrice(response);
	}, postBody);
}

/**
 * Set the correct prices for the current color
 * 
 * @param {Object} json The JSON object containing the prices
 */
function parsePrice(json) {	
	var prices = WS.Util.parseJSON(json);
	//console.log(prices);
	$('our-price-tag').innerHTML = prices.oPrice;
	//$('retail-price').innerHTML = prices.rPrice;
	$('shop-price').innerHTML = prices.sPrice;
	$('our-price').innerHTML = prices.oPrice;
	
	var paragraphs = $('gallery-wrap').getElementsByTagName('p');
	var label = paragraphs[0];
	if(label) {
		label.parentNode.removeChild(label);
	}
	if(prices.label != 'none' && prices.label != null) {
		$('gallery-wrap').appendChild(getLabelElement(prices.label));
	}
	
	/**
	 * Vanaf vandaag (11-02-10) ook bij binnenkort leverbaar te bestellen.
	 */
	/*if(prices.label == 'soon' || prices.label == 'soldout') {
		$('order-submit').disabled = true;
		$('order-submit').innerHTML = 'Niet te bestellen';
	} else {
		$('order-submit').disabled = false;
		$('order-submit').innerHTML = 'Bestellen';
	}*/
	if(prices.label == 'soldout') {
		$('order-submit').disabled = true;
		$('order-submit').innerHTML = 'Niet te bestellen';
	} else {
		$('order-submit').disabled = false;
		$('order-submit').innerHTML = 'Bestellen';
	}
}

/**
 * Set the price for the homepage carousel
 * 
 * @param {Mixed} rId The room ID
 * @param {Mixed} cId The color ID
 */
function setCarouselPrice(rId, cId) {
	var postBody = 'roomid=' + rId + '&colorid=' + cId + '&type=room';
	WS.Ajax.request('http://www.babykamer.nl/getprice', function(response) {
		var prices = WS.Util.parseJSON(response);
		$('carousel-price').innerHTML = '&euro; ' + prices.oPrice;
		$('carousel-price').appear({ duration: 0.5 });
	}, postBody);
}

/**
 * Prepares a price string so it can be converted with parseFloat
 * 
 * @param {String} str The price string to format
 */
function priceFormat(str) {
	return str.replace('.', '').replace(',', '.');
}

/**
 * Sets the formatted price for the checkout form
 * 
 * @param {Number} price The price to be formatted
 */
function setCheckoutPrice(price) {
	if(price > 0) {
		$('checkout-price').innerHTML = WS.Util.number_format(price, 2, ',', '.');
	}
}

function getLabelElement(label) {
	switch(label) {
		case 'specialaction':
			var el = document.createElement('P');
			el.className = 'label actie-label';
			el.innerHtml = 'Actie!';
			return el;
		break;
		case 'lastfew':
			var el = document.createElement('P');
			el.className = 'label opisop-label';
			el.innerHtml = 'Op = Op!';
			return el;
		break;
		case 'new':
			var el = document.createElement('P');
			el.className = 'label nieuw-label';
			el.innerHtml = 'Nieuw!';
			return el;
		break;
		case 'soldout':
			var el = document.createElement('P');
			el.className = 'label uitverkocht-label';
			el.innerHtml = 'Uitverkocht!';
			return el;
		break;
		case 'tempsoldout':
			var el = document.createElement('P');
			el.className = 'label tijdelijk-uitverkocht-label';
			el.innerHtml = 'Tijdelijk uitverkocht!';
			return el;
		break;
		case 'soon':
			var el = document.createElement('P');
			el.className = 'label binnenkort-label';
			el.innerHtml = 'Binnenkort leverbaar!';
			return el;
		break;
		default: 
			return null;
		break;
	}
}
