// Coffee 2 Home Functions.
//
// The purpose of this is to load content into the page without having
// to refresh anything.

// New Function

function loadContent(wpType, wpId, wpParent) {

	$('#gallery').hide();
	$('#content').hide();

	var jsonUrl = './php/wpdata.php?type=' + wpType;

	if(typeof(wpParent) != 'undefined') {
		// wpId can be anything if wpParent is set.
		jsonUrl = jsonUrl + '&parent=' + wpParent;
		if(wpParent == 397) {
			loadContent('article', 496);
		} else if (wpParent == 398) {
			loadContent('article', 497);
		}
		else if (wpParent == 413)
		{
			jsonUrl = './php/wpdata.php?type=image&parent=413';
			wpType = 'video';
		}
	} else {
		jsonUrl = jsonUrl + '&id=' + wpId;
	}


	$.getJSON(
		jsonUrl,
		function(output)
		{
			if(wpType == 'product')
			{

				var html = '';
				var products = 0;

				for ( i in output) {
					products++;
				}

				if(products > 5) {

					var html = '<div class="carousel"><ul>';
					for ( i in output) {
						html += '<li class="product-link"><a onclick="return infoOverlay(\'product\',' + output[i]['id'] + ')">';
						html += '<img src="wpdata/' + output[i]['images'][0]['id'] + '-s.jpg" width="128" height="150" />';
						html += '<span class="small-title">' + output[i]['title'] + '</span>';
						html += '</a></li>';
					}
					html += '</ul></div><div class="prev product-control"> </div><div class="next product-control"> </div>';
					$('#gallery')
						.html(html)
						.show();

					$('.carousel').jCarouselLite({
						btnNext: ".next",
						btnPrev: ".prev",
						visible: 5
					});

				} else {
					for ( i in output) {
						html += '<span class="product-link"><a onclick="return infoOverlay(\'product\',' + output[i]['id'] + ')">';
						html += '<img src="wpdata/' + output[i]['images'][0]['id'] + '-s.jpg" />';
						html += '<span class="small-title">' + output[i]['title'] + '</span>';
						html += '</a></span>';
					}

					$('#gallery')
						.html(html)
						.show();
					
				}

			} else if(wpType == 'image') {

				var html = '<div class="carousel"><ul>';
				for ( i in output) {
					html += '<li class="photo-link"><a href="wpdata/' + output[i]['id'] + '-l.jpg">';
					html += '<img src="wpdata/' + output[i]['id'] + '-g.jpg" width="128" />';
					html += '</a></li>';
				}
				html += '</ul></div><div class="prev"> </div><div class="next"> </div>';

				$('#gallery')
					.html(html)
					.show();

				$('.carousel').jCarouselLite({
					btnNext: ".next",
					btnPrev: ".prev",
					visible: 5
				});

				$('.carousel a').lightBox();
			
			} else if(wpType == 'video') {

				var html = '<div class="carousel video-list"><ul>';
				for ( i in output) {
					html += '<li class="photo-link"><a href="' + output[i]['title'] + '" rel="prettyPhoto">';
					html += '<img src="wpdata/' + output[i]['id'] + '-g.jpg" width="128" />';
					html += '</a></li>';
				}
				html += '</ul></div><div class="prev"> </div><div class="next"> </div>';

				$('#gallery')
					.html(html)
					.show();

				$('.carousel').jCarouselLite({
					btnNext: ".next",
					btnPrev: ".prev",
					visible: 5
				});

				$(".video-list a").prettyPhoto();//$('.video-list a').lightBox();
				
				
			} else {

				var html = '<h1>' + output['db_' + wpId]['title'] + '</h1>' + output['db_' + wpId]['content'];

				$('#content')
					.html(html)
					.show();
				
			}
		}
	);
}

// Overlay functions

function createDesat() {

	$('body').append('<div class="desat"></div>');

	$('.desat')
		.width($(document).width())
		.height($(document).height());

}

function resizeDesat() {
	$('.desat')
		.width($(document).width())
		.height($(document).height());	
}

function preloaderComplete() {
	$('.desat').fadeOut(4000);
}

function createOverlay() {

	$('body').append('<div class="overlay-bg"></div>');
	$('body').append('<div class="overlay"></div>');

	$('.overlay-bg')
		.width($(document).width())
		.height($(document).height());

	$('.overlay-bg').click( function () {
		destroyOverlay() 
	});

}


function destroyOverlay() {

	$('.overlay-bg').remove();
	$('.overlay').remove();

}

function gotoCart() {
	var offset = $('.sc-area').offset();
	$('html, body').scrollTop( offset.top );
}

function centerOverlay() {

	// Position the overlay in the center of the stage.

	$('.overlay-bg')
		.width($(document).width())
		.height($(document).height());
	
	var overlayWidth = 800;
	var overlayHeight = 460;

	var browserWidth = $(window).width();
	var browserHeight = $(window).height();

	var targetLeft = Math.round((browserWidth - overlayWidth) / 2);
	var targetTop = Math.round((browserHeight - overlayHeight) / 2);


	$('.overlay')
		.css('left', targetLeft)
		.css('top', targetTop);
}

function infoOverlay(wpType, wpId) {

	destroyOverlay();

	createOverlay();

	centerOverlay();

	// Loading thing here.

	$.getJSON("./php/wpdata.php?type=" + wpType + "&id=" + wpId,
		function(output){

			for(i in output) {

				$('.overlay').append('<div class="overlay-close" onclick="destroyOverlay();">X</div>')

				$('.overlay').append('<div class="overlay-images"></div>');
				var display = '';

				for(q in output[i]['images']) {
					$('.overlay-images').append('<img src="wpdata/' + output[i]['images'][q]['id'] + '-o.jpg" ' + display + ' id="image_' + output[i]['images'][q]['id'] + '" class="image_' + q + '" />');
					display = 'style="display: none;"'
				}

				$('.overlay-images').append('<a onclick="return imgScroller(-1);" class="image-scroller image-prev">&lt;</a><a onclick="return imgScroller(1);" class="image-scroller image-next">&gt;</a>');

				$('.overlay').append('<div class="overlay-info"><h1 class="product-title">' + output[i]['title'] + '</h1>' + output[i]['description'] + '</div>');

				$('.overlay-info').append('<input type="hidden" value="' + wpId + '" name="productId" id="productId" />')

				sizesCheck = output[i]['sizes'].indexOf(',');
				var packageOptions = new Array();
				packageOptions = output[i]['sizes'].split(',');

				var priceOptions = new Array();
				priceOptions = output[i]['price'].split(',');

				priceCount = priceOptions.length;

				if(sizesCheck > -1) {
					sizeHtml = '';
					var displayPrice = true;
					for(s in packageOptions) {

						if(priceCount == 1) {
							if(displayPrice == true) {
								$('.overlay-info').append('<h2 class="unit-price">$<span class="price">' + output[i]['price'] + '</span></h2>')
								displayPrice = false;
							}
							sizeHtml += '<option value="' + packageOptions[s] + '" rel="' + priceOptions[0] + '">' + packageOptions[s] + '</option>';
						} else {
							sizeHtml += '<option value="' + packageOptions[s] + '" rel="' + priceOptions[s] + '">' + packageOptions[s] + ' - $' + priceOptions[s] + '</option>';
						}
					}
					$('.overlay-info').append('<p><label><span>Package Size</span><select id="productPackage"></select></label></p>');
					$('#productPackage').append(sizeHtml);
				} else {
					sizeTest = output[i]['sizes'].split('');
					if(sizeTest.length > 1) {
						$('.overlay-info').append('<h2 class="unit-price">' + output[i]['sizes'] + ' - $<span class="price">' + output[i]['price'] + '</span></h2>')
					} else {
						$('.overlay-info').append('<h2 class="unit-price">$<span class="price">' + output[i]['price'] + '</span></h2>')
					}
				}
				

				if(output[i]['featured'] == 1) {
					var grindOptions = new Array();


					grindOptions = ['Beans', 'French', 'Plunger', 'Filter', 'Espresso', 'Turkish'];

					$('.overlay-info').append('<p><label><span>Grind</span><select id="productGrind"></select></label></p>');

					for(s in grindOptions) {
						$('#productGrind').append('<option>' + grindOptions[s] + '</option>');
					}
				}

				$('.overlay-info').append('<p><label><span>Quantity</span><select id="productQuantity"></select></label></p>');
				for(s = 1; s <= 10; s++) {
					$('#productQuantity').append('<option>' + s + '</option>');
				}
				

				$('.overlay-info').append('<a class="add-to-cart">Add to Cart <span>&gt;</span></a>');

				// This can be fancified later.
				$('.overlay').show();

			}

		}
	);

	return false;

}

function imgScroller(direction) {
	var min = 0;
	var max = $('.overlay-images img').size() - 1;
	var current = $('.overlay-images img:visible').attr('class');
	current = current.replace('image_', '');
	current = parseInt(current);
	var destination = current + direction;

	if(destination >= min && destination <= max) {
		$('.overlay-images img')
			.fadeOut('slow')
			.css('z-index', 100);
		$('.overlay-images img.image_' + destination)
			.fadeIn('slow')
			.css('z-index', 110);
	}

	return false;


}

function picOverlay(wpId) {
/*
	destroyOverlay();

	createOverlay();

	centerOverlay();

	// Loading thing here.

	$('.overlay').append('<div class="overlay-close" onclick="destroyOverlay();">X</div>')
	$('.overlay').append('<img src="wpdata/' + wpId + '-l.jpg" />')

	$('.overlay').show();
	return false;
 */

}


// Shopping Cart Functions
/*
function addItem() {

	// Information needed :
	//
	// id of the product.
	var productId = $('.productId').val();
	// id of the main image.
	var productImg = $('.overlay-images img:first').attr('id');
	productImg = productImg.replace('image_', '');
	// package size
	var productSize = parseInt($('#productPackage').val());
	// grind size
	var productGrind = parseInt($('#productGrind').val());
	// quantity
	var productQuantity = parseInt($('#productQuantity').val());
	// price
	var productPrice = parseFloat($('.price').text());

	// Check if there is already an entry in the shopping cart with the same size and grind.

}

function removeItem(item) {

}

function changeQuantity(item, quantity) {

}
 */

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + "; path=/";
}

function getCookie(c_name)
{
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function addProduct(productId, size, quantity, title, price, image) {

	/*
	var productIds = '';
	var sizes = '';
	var quantities = '';
	var title = '';
	var price = '';
	*/



	// Check to see if the user already has products in their basket.
	existingIds = getCookie('pId');
	existingSizes = getCookie('pS');
	existingQuantites = getCookie('pQ');
	existingTitles = getCookie('pT');
	existingPrices = getCookie('pP');
	existingImages = getCookie('pI');

	// Set the arrays that we're going to be using later.
	var productIds = [];
	var sizes = [];
	var quantities = [];
	var titles = [];
	var prices = [];
	var images = [];


	// If the cookies are set the user has products in their cart
	// Lets find out what they are.
	if(existingIds.length > 0) {
		if(existingIds.indexOf(',') !== -1) {
			productIds = existingIds.split(',');
			sizes = existingSizes.split(',');
			quantities = existingQuantites.split(',');
			titles = existingTitles.split(',');
			prices = existingPrices.split(',');
			images = existingImages.split(',');
		} else {
			productIds.push(existingIds);
			sizes.push(existingSizes);
			quantities.push(existingQuantites);
			titles.push(existingTitles);
			prices.push(existingPrices);
			images.push(existingImages);
		}
	}

	// Regardless of if the products have been set above or not,
	// add the new product to an array, so that we can update the cookie.
	productIds.push(productId);
	sizes.push(size);
	quantities.push(quantity);
	titles.push(title);
	prices.push(price);
	images.push(image);

	cookieIds = productIds.join(',');
	cookieSizes = sizes.join(',');
	cookieQuantities = quantities.join(',');
	cookieTitles = titles.join(',');
	cookiePrices = prices.join(',');
	cookieImages = images.join(',');

	setCookie('pId', cookieIds, 1);
	setCookie('pS', cookieSizes, 1);
	setCookie('pQ', cookieQuantities, 1);
	setCookie('pT', cookieTitles, 1);
	setCookie('pP', cookiePrices, 1);
	setCookie('pI', cookieImages, 1);

	updateCart();

}

function removeProduct(arrayIndex) {

	var newIds = [];
	var newSizes = [];
	var newQuantites = [];
	var newTitles = [];
	var newPrices = [];
	var newImages = [];

	existingIds = getCookie('pId');
	existingSizes = getCookie('pS');
	existingQuantites = getCookie('pQ');
	existingTitles = getCookie('pT');
	existingPrices = getCookie('pP');
	existingImages = getCookie('pI');

	productIds = existingIds.split(',');
	sizes = existingSizes.split(',');
	quantities = existingQuantites.split(',');
	titles = existingTitles.split(',');
	prices = existingPrices.split(',');
	images = existingImages.split(',');

	if(typeof(productIds) == 'object') {
		for(i = 0; i < productIds.length; i++) {
			if(i !== arrayIndex) {
				newIds.push(productIds[i]);
				newSizes.push(sizes[i]);
				newQuantites.push(quantities[i]);
				newTitles.push(titles[i]);
				newPrices.push(prices[i]);
				newImages.push(images[i]);
			}
		}
		setCookie('pId', newIds, 1);
		setCookie('pS', newSizes, 1);
		setCookie('pQ', newQuantites, 1);
		setCookie('pT', newTitles, 1);
		setCookie('pP', newPrices, 1);
		setCookie('pI', newImages, 1);
	} else {
		clearCart();
	}
	updateCart();

}

function clearCart() {

	// User wishes to clear their cart.

	var emptyArray = [];

	setCookie('pId', emptyArray, 1);
	setCookie('pS', emptyArray, 1);
	setCookie('pQ', emptyArray, 1);
	setCookie('pT', emptyArray, 1);
	setCookie('pP', emptyArray, 1);
	setCookie('pI', emptyArray, 1);

	updateCart();

}


function updateCart() {
	var productIds = [], sizes = [], quantities = [], titles = [], prices = [], images = [];
	
	var existingIds = getCookie('pId');
	var existingSizes = getCookie('pS');
	var existingQuantites = getCookie('pQ');
	var existingTitles = getCookie('pT');
	var existingPrices = getCookie('pP');
	var existingImages = getCookie('pI');

	if (existingIds.length > 0 && existingIds.indexOf(',') !== -1) {
		productIds = existingIds.split(',');
		sizes = existingSizes.split(',');
		quantities = existingQuantites.split(',');
		titles = existingTitles.split(',');
		prices = existingPrices.split(',');
		images = existingImages.split(',');
	} else if (existingIds.length > 0) {
		productIds.push(existingIds);
		sizes.push(existingSizes);
		quantities.push(existingQuantites);
		titles.push(existingTitles);
		prices.push(existingPrices);
		images.push(existingImages);
	}
	
	var html = '', _total = 0;
	
	for (i in productIds) {
		var prod_name = titles[i];
		var prod_price = parseInt(quantities[i]) * parseFloat(prices[i]);
		_total += prod_price;
		html += '<div class="cart-item cart-item-' + i + '">';
		html += '<img src="wpdata/' + images[i] + '-s.jpg" onclick="infoOverlay(\'product\', ' + productIds[i] + ')" />';
		html += '<div class="sc-title"><strong>' + prod_name + '</strong></div>';
		html += '<div class="sc-size">Size ' + sizes[i] + '</div>';
		html += '<div class="quantity">' + quantities[i] + '</div>';
		html += '<div class="sc-price">$' +	number_format(prod_price, 2, '.', ',') + '</div>';
		html += '<div class="sc-remove"><a href="#" class="cart-links cart-remove" onclick="removeProduct(' + i + '); return false;">X</a></div>';
		html += '</div>';
		//html += '<div class="cart-item cart-item-' + i + '"><p><strong>' + prod_name + '</strong><br />Size (' + sizes[i] + ') X ' + quantities[i] + '<br />$' + number_format(prod_price, 2, '.', ',') + '<br /><a href="#" class="cart-links" onclick="removeProduct(' + i + '); return false;">remove</a></p></div>';
	}
	
	$('#shopping-cart').html(html);
	if (_total == 0) {
		$('.cart-total').html('<p>You have no items on your cart!</p>');
	} else {
		$('.cart-total').html('<p class="total-value">TOTAL: $' + number_format(_total, 2, '.', ',') + '</p><p><a href="./php/checkout" class="cart-links checkout">Checkout</a></p>');
	}

}

function number_format (number, decimals, dec_point, thousands_sep) {
	// Formats a number with grouped thousands
	//
	// version: 906.1806
	// discuss at: http://phpjs.org/functions/number_format
	
	var n = number, prec = decimals;

	var toFixedFix = function (n,prec) {
		var k = Math.pow(10,prec);
		return (Math.round(n*k)/k).toString();
	};

	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
	var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

	var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

	var abs = toFixedFix(Math.abs(n), prec);
	var _, i;

	if (abs >= 1000) {
		_ = abs.split(/\D/);
		i = _[0].length % 3 || 3;

		_[0] = s.slice(0,i + (n < 0)) +
			  _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
		s = _.join(dec);
	} else {
		s = s.replace('.', dec);
	}

	var decPos = s.indexOf(dec);
	if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
		s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
	}
	else if (prec >= 1 && decPos === -1) {
		s += dec+new Array(prec).join(0)+'0';
	}
	return s;
}



$('a.add-to-cart').live('click', function(){
	var prod_id = $('#productId').val();
	var prod_q = parseInt($('#productQuantity').val());
	var prod_s = $('#productPackage').val();
	var prod_p = 0;
	var prod_t = $('h1.product-title').text();
	var prod_i = $('.overlay-images img:first').attr('id');

	$('.price').each(
		function() {
			prod_p += parseFloat($('.price').text());
		}
	)

	/* Additional Changes */
	$('#productPackage').each(

		function () {

			if(prod_p == 0) {
				prod_p += parseFloat($('#productPackage option:selected').attr('rel'));
			}
			prod_t += ' ' + $('#productPackage option:selected').val();
		
		}

	);

	$('#productGrind').each(

		function () {

			prod_t += ' - ' + $('#productGrind option:selected').text();
		
		}

	);
	

	


	prod_i = prod_i.replace('image_', '');
	addProduct(prod_id, prod_s, prod_q, prod_t, prod_p, prod_i);
	destroyOverlay();
	gotoCart();
	return false;
});

$(function () {

	updateCart();

});

/* Mailer */

function mailer() {
	$('.mailer-alert')
		.removeClass('error')
		.removeClass('success')
		.hide();
	var post = $('.form').serialize();
	$.post('./php/mailer.php', post,
		function(data){
			if(data.success == true) {
				$('.mailer-alert').addClass('success');
				$('.mailer-alert').html('Thank you. Your message has been sent.');
			} else {
				$('.mailer-alert').html('');
				$('.mailer-alert').addClass('error');
				for(i in data.errors) {
					$('.mailer-alert').append('<p>' + data.errors[i] + '</p>');
				}
			}
			$('.mailer-alert').show();
		}, 'json');
}


/* Registration */

function register() {
	$('.register-alert')
		.removeClass('error')
		.removeClass('success')
		.hide();
	var post = $('.form').serialize();
	$.post('./php/register.php', post,
		function(data){
			if(data.success == true) {
				$('.register-alert').html('Thank you. You have successfully registered.');
				$('.register-alert').addClass('success');
				setCookie('userid', data.user, 1);
			} else {
				$('.register-alert').html('');
				for(i in data.errors) {
					$('.register-alert').append('<p>' + data.errors[i] + '</p>');
				}
				$('.register-alert').addClass('error');
			}
			$('.register-alert').show();
		}, 'json');

}

function opRegister() {
	$('.register-alert')
		.removeClass('error')
		.removeClass('success')
		.hide();
	var post = $('.form').serialize();
	$.post('./php/opregister.php', post,
		function(data){
			if(data.success == true) {
				$('.register-alert').html('Thank you. You have successfully registered .');
				$('.register-alert').addClass('success');
			} else {
				$('.register-alert').html('');
				for(i in data.errors) {
					$('.register-alert').append('<p>' + data.errors[i] + '</p>');
				}
				$('.register-alert').addClass('error');
			}
			$('.register-alert').show();
		}, 'json');
}


function login() {
	var post = $('.form').serialize();
	$('.login-alert').html('');
	$.post('./php/login.php', post,
		function(data){
			if(data.success == true) {
				$('.login-alert').append('<p class="green">Thank you. You have successfully logged in.</p>');
				setCookie('userid', data.user, 1);
				$('.form').addClass('hide');
				$('#content h2').addClass('hide');
				$('#content a').addClass('hide');
			} else {
				$('.login-alert').html('');
				for(i in data.errors) {
					$('.login-alert').append('<p>' + data.errors[i] + '</p>');
				}
			}
		}, 'json');

}

function resetPassword() {
	var post = $('.form').serialize();
	$('.login-alert').html('');
	$.post('./php/password.php', post,
		function(data){
			if(data.success == true) {
				$('.login-alert').append('<p>Thank you. An email has been sent to your email address detailing how to reset your password.</p>');
			} else {
				$('.login-alert').html('');
				for(i in data.errors) {
					$('.login-alert').append('<p>' + data.errors[i] + '</p>');
				}
			}
		}, 'json');

}


function salesPersonForm() {
	var userid = getCookie('userid');
	if(typeof(userid) == undefined || userid == 0) {
		alert('Please register or login before proceeding to checkout.');
		return false;
	} else {
		loadContent('article', 551);
	}
}


$(document).ready(
	function(){
		createDesat();

		$(window).resize( function () {
			$('.desat').each(function() {
				resizeDesat();
			})
			centerOverlay();
		});

		$('.sc-checkout a').click( function() {

			var userid = getCookie('userid');

			if(typeof(userid) == undefined || userid == 0) {
				alert('Please register or login before proceeding to checkout.');
				return false;
			}

			var discountCode = $('.discount-code input').val();
			setCookie('discountCode', discountCode, 1);


		})

	}
);

