<!--
/**
 * NiceProduce.com V2.0
 * @author Karl Stanton
 * @version 0.2
 * 
 */	


// Our NiceProduce Object
function NiceProduce () {};

// Initialize the Site
NiceProduce.initialize = function () {

	var IE = /*@cc_on!@*/false;

	// Fix labels in FireFox
	if (!IE){
		labels = document.getElementsByTagName('label');
		for(var i=0;i<labels.length;i++){
			labels[i].style.display = '-moz-inline-box;';	
		}
	}
	// Dropdown interactivity
	$("#drop_brand, #drop_product").change(function (){
		window.location = "http://niceproduce.com/" + $(this).val() + "/";
	});

	
	// Kick start items
	NiceProduce.Items();
	NiceProduce.Cart();
	NiceProduce.Checkout();
	NiceProduce.Events();
	NiceProduce.Register();
	NiceProduce.Account();
	
	if (typeof(current_page) !== 'undefined' && current_page === "gallery"){
		NiceProduce.Gallery();
	}
	
};

// Tails a random number at the end of a string
NiceProduce.cachebuster = function(){
	var cachebuster = parseInt(Math.random()*99999999); // cache buster
	return "c="+cachebuster;
};



// Customer & Registration ------------------------------------------------------------------------

NiceProduce.Customer = {};

NiceProduce.Customer.SubscribeSuccess = function () {
	$("#newsletter").val('');
};






// Cart Object ------------------------------------------------------------------------------------

/**
 * Instantiates the Cart object. Binds all the current items in the display
 * Triggers events
 */
NiceProduce.Cart = function () {
	
	NiceProduce.Cart.BindCartItems();
	
	NiceProduce.Cart.ValidateAddressForm();
	
	// For the little x delete button
	$("#cart-delete").hover(function () {
		$(this).show();
	}, function () {
		$(this).hide();
	}).click(function () {
		NiceProduce.Cart.DeleteCartSidebar(NiceProduce.Cart.Current_Line_ID,NiceProduce.Cart.Current_Size,1);
	});
	
	var select = $("select", "#quantities");
	var addtocart = $("input.add-to-cart", "#quantities");
	
	// Reset the select boxes
	select.each(function() {
		this.selectedIndex = 0
	});
	select.change(function () {
		// Seek out other selects to see if their selectedIndex are greater than 0
		var total = 0;
		select.each(function () {
			if (this.selectedIndex > 0) {
				total++;
			}
		});
		
		if (total > 0) {
			addtocart.addClass("on");
		} else {
			addtocart.removeClass("on");
		}
	});
	
	// For the add to cart button
	addtocart.click(function () {
		NiceProduce.Cart.Add();
		return false;
	});
	
	// Check to see if we have anything in the cart before we fire off
	$("a.checkout:not(#checkoutHistory)", '#sidebar').click(function () {
		if ($(this).hasClass("on")) {
			window.location = "/cart/";
		}
		return false;
	});
	
};

/**
 * Binds events to the cart items in the cart sidebar
 */
NiceProduce.Cart.BindCartItems = function () {
	
	$("li a", "#shopping-cart").unbind().click(function(){
		$("li div", "#shopping-cart").hide();
		$(this).next("div").show();
		return false;
	}).hover(function () {
		$("#cart-delete").css({
			left: $(this).position().left + $(this).width(),
			top: $(this).position().top
		}).show();

		// Set the current stock ID & size
		NiceProduce.Cart.Current_Line_ID = $(this).parent().attr("class").split("-")[0].split("li")[1];
		NiceProduce.Cart.Current_Size    = $(this).parent().attr("class").split("-")[1];

		$(this).css("background-color", "#366e00");
	}, function () { 
		$("#cart-delete").hide();
		$(this).css("background-color", "#78AA00");
	});
	
};

NiceProduce.Cart.ValidateAddressForm = function () {

	$('#cart-form').submit(function () {
	
		var valid = 0;
		
		var inputs = ['street1','postcode','suburb','state'];
		
		// Loop and validate on empty fields
		for (var i = 0; i < inputs.length; i++) {
		
			var theInput = $('#' + inputs[i]);
		
			if (theInput.val() == '') {
				theInput.addClass('error');
				valid++;
			}
			else {
				theInput.removeClass('error');
			}
			
		
		}

		if (valid > 0) {
			return false;
		}
	
		
	});

};

/**
 * Updates the cart LI's with returned data from our webservice
 * @param {Object} json - JSON object built by PHP
 */
NiceProduce.Cart.UpdateDisplay = function (json) {

	var id, item, totals;
	
	if (typeof(json.redirect) !== 'undefined') {
	
		$('p:eq(0)', '#cart').html('You have 0 items in your cart');
		$('p:eq(1)', '#cart').html('AUD $0.00');
		$('#shopping-cart').remove();
	
		return;
	}
	
	// Cycle through the JSON objects
	for (item in json.data.items) {

		id = item;
		item = json.data.items[item];
		totals = json.data.totals;
		var cart = $("#shopping-cart");
		
		// Make the cart LI
		var li_id = ".li" + id + "-" + item[1];
		var li = $(li_id, "#shopping-cart");
		var li_data = NiceProduce.Cart.UpdateDisplay.BuildLi(li_id, item);

		// Decide whether to append or replace
		if (li.length === 0) {
			
			// First see if we have a UL in place
			if (cart.length === 0) {
				$("#cart").children("p:first").after('<ul id="shopping-cart"></ul>');
			}
			
			// Now create the LI			
			var new_li = $(li_data);
			new_li.click(function() {
				$(this).next("div").show();
				return false;
			});
			new_li.hide().appendTo($("#shopping-cart")).fadeIn();

		// Replace the old LI with the new data
		} else {

			// If the quantity returned 0, then delete the row			
			if (item[2] === 0) {
				$(li).remove();

			// Or, replace the data
			} else {
				$(li).replaceWith(li_data);
				$(li_id, "#shopping-cart").children("a").css("background-color", "#366e00");
				$(li_id).show().children("a").animate({
					backgroundColor: "#78AA00"
				}, 500);
			}
			
		}
		
		$("#total-items").html(totals.total_items + ' in your cart');
		$("#total-price").html(totals.total_price);
		
	}

	// Now style the checkout button
	cart = $("#shopping-cart");
	if (cart.length > 0 && cart.children().length > 0) {
		$("a.checkout").addClass("on");
		
		var msg = totals.total_items + ' in your cart. The total is <span>' + totals.total_price + '</span>. <a href="/cart/">View your cart</a>.';
		var header_cart = $('#header_cart');
		if (header_cart.length === 0) {
			$("div#menu").after('<div id="header_cart" style="display:none;">' + msg + '</div>');
			$('#header_cart').fadeIn();
		} else {
			header_cart.html(msg);
		}
		
	} else {
		$("a.checkout").removeClass("on");
		
		$('#header_cart').fadeOut().remove();
		
	}
	
	NiceProduce.Cart.BindCartItems();
};

/**
 * Builds the LI when we are injecting a new cart item into the side bar
 * @param {Object} clss
 * @param {Object} item
 */
NiceProduce.Cart.UpdateDisplay.BuildLi = function (cls, item) {
	cls = cls.substring(1, cls.length);
	return "<li class='" + cls + "'><a href='#'>" + item[0] + " (<span>" + item[2] + "</span>)</a><div>Size: " + item[1] + " / Colour: " + item[3] + "</div></li>"; 
}

/** 
 * Adds a garment or object to the shopping cart via AJAX
 */
NiceProduce.Cart.Add = function () {

	// See if we have permission to send
	var addtocart = $("input.add-to-cart");
	if (addtocart.hasClass("on")) {
	
		var bundle = {
			dataType: "json",
			data: {
				'do': 1,
				'o': $.toJSON($("#quantities").serializeArray()),
				't': $("#quantities input[name='type']").val()
			},
			success: NiceProduce.Cart.UpdateDisplay
		};
		
		// Fire the bundle off
		NiceProduce.WebService("cart", bundle);
		
	}
	
	$("select", "#quantities").each(function() {
		this.selectedIndex = 0;
	});
	
	addtocart.removeClass("on");

}

/**
 * Deletes an item from the cart via AJAX
 * @param {Object} line_id	- ID of the stock line
 * @param {Object} size		- Size of the garment (not required)
 * @param {Object} qty		- Qty to remove
 * @param {Function} callback
 */
NiceProduce.Cart.Delete = function (line_id, size, qty, callback) {
	var bundle = {dataType: "json",
		data: {
			'do': 3,
			'l': line_id,
			'q': qty,
			's': size
		},
		success: callback
	};
	// Fire off to the web service
	NiceProduce.WebService("cart", bundle);
}

/**
 * This method adds the callback that is used on the sidebar only
 */
NiceProduce.Cart.DeleteCartSidebar = function (line_id, size, qty) {

	NiceProduce.Cart.Delete(line_id, size, qty, NiceProduce.Cart.UpdateDisplay);

};

/**
 * This method adds the callback that is used on the cart list and
 * checkout pages only
 */
NiceProduce.Cart.DeleteCartList = function (line_id, size, qty) {

	/*$('#item' + line_id + size).animate({
		opacity: 0
	}, 300, function() {
		$(this).remove();
	});*/
	
	NiceProduce.Cart.Delete(line_id, size, qty, NiceProduce.Cart.UpdateCartTotals);
	

};

NiceProduce.Cart.UpdateCartTotals = function (json) {

	if (typeof(json.redirect) !== 'undefined') {
		window.location.href = '/cart/';
		return;
	}

	// Or play on...
	var data = json.data;
	var line_id;
	var size;
	var line_total;
	var details;
	
	for (item in json.data.items) {

		line_id = item;	
		line_total = parseInt(data.items[line_id][5], 10);
		size = data.items[line_id][1];
		details = $('td.details tr', '#line' + line_id);
		
		$('p.subtotal').html('Subtotal: ' + data.totals.total_price);
		
		// Just update the DOM as we have more in stock
		if (line_total > 0) {
		
			var qty	= data.items[line_id][2];
			var total = data.items[line_id][5];//total
			
			// Update the HTML
			if (details.length > 1) {
			
				$('td.qty', '#item' + line_id + size).html(qty);
			
				$('td.total', '#item' + line_id + size).html(total);				
				
			}
			else {

				$('td.qty', '#line' + line_id).html(qty);
			
				$('td.total', '#line' + line_id).html(total);
			
			}
		
		// Remove the DOM element as the QTY is now 0
		} else {
		
			// Look to delete the size
			if (details.length > 1) {
				$('#item' + line_id + size).remove();			
			}
			// Or the whole line
			else {
				$('#line' + line_id).remove();
			}
			
		}

	}

};








/**
 *
 */
NiceProduce.Checkout = function () {

	$("#service_type").change(function () {
		NiceProduce.Checkout.UpdatePostage($(this));
	});
	
	$('input.getquote').click(function () {
	
		NiceProduce.Checkout.GetQuote($('#order_id').val());
		$(this).hide();
		
		//$('span.quoteSent').show();
		
		window.location.href = '/thanks/';
		
		return false;
	});
	
};

/**
 * Shows the checkout form
 */
NiceProduce.Checkout.ShowCheckout = function (data){
	$("#cart-list").append(data);
};

/**
 * Sends a request off to our webservice which hits AusPost asking for new postage calculation
 * @param {Object} el
 */
NiceProduce.Checkout.UpdatePostage = function (el) {
	var bundle = {
		data: {
			'do': 4,
			't': el.val()
		},
		success: NiceProduce.Checkout.UpdatePostageDisplay
	};
	NiceProduce.WebService("cart", bundle);
};

/**
 * Updates the postage information with the return from our AusPost webservice
 * @param {String} html
 */
NiceProduce.Checkout.UpdatePostageDisplay = function (html) {
	$('#shipping-cost').html(html);
};

/**
 * Sends quote request to server and relocates user to quote information page
 */
NiceProduce.Checkout.GetQuote = function (order_id) {
	var bundle = {
		data: {
			'do': 9
		},
		success: function () {
				//window.location = '/thanks/';
			}
		};
	NiceProduce.WebService("cart", bundle); 
};




// Items --------------------------------------------------------------------------------------
NiceProduce.Items = function () {

	
	// Set the default item id
	//var item_id;
	//item_id = $('img.on', '#sidebar').attr('class').match(/[0-9]+/, '');
	//NiceProduce.Items.CurrentItem = parseInt(item_id[0], 10);
	
	
	// Bind the thumbnail images to show the pre-loaded images
	$('a', '#product-thumbs').click(function () {
		
		NiceProduce.Items.SwitchDefaultImage(this);
		return false;
		
	});
	
	// Bind the colour thumbnails to show the other colur way
	$("img.colour", '#sidebar').click(function () {

		if (!$(this).hasClass('on')) {
			
			$('img.on', '#sidebar').removeClass('on');
			$(this).addClass('on');
		
			$('a', '#ib').each(function () {
			
				var a = $(this);
				
				if (a.hasClass('visible')) {
					a.removeClass('visible');
				} else {
					a.addClass('visible');
				}
			});

		}

		// Find the first image of the newly visible items, and set that to the new default
		NiceProduce.Items.SwitchDefaultImage('#ib a.visible:first');
	
		return false;
	});
	
};

NiceProduce.Items.SwitchDefaultImage = function (el) {

	var img = $(el).attr('class').replace(/thumb/, '');
	img = img.replace(/visible/,'');
	$('img.visible', '#ib_frame').removeClass('visible');
	$('img.p' + img, '#ib_frame').addClass('visible');
	
}






// Register ------------------------------------------------------------------------------------
NiceProduce.Register = function () {

	NiceProduce.Register.ValidateAccountRegisterForm();

	// Hook up the subscription AJAX
	$("#newsletter_rego").submit(function () {
		
		//ws_Register("subscribe", $("#newsletter").val(), $("#newsletter_rego span"));

		var address = $('#newsletter').val();

		if (/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/.test(address)){
			var bundle = {
				dataType: "html",
				data: {
					'do': 'subscribe',
					'address': $("#newsletter").val()
				},
				success: NiceProduce.Register.SayThanks
			};
			
			// Fire the bundle off
			NiceProduce.WebService("register", bundle);
		} else {

			$("#newsletter_rego span.msg").removeClass('thanks').addClass('error').text("Please enter a valid address");

		}


		
		return false;
		
	});
	
};

NiceProduce.Register.SayThanks = function (data) {
	$("#newsletter_rego span.msg").removeClass('error').addClass('thanks').text("Thank-you!");
};

NiceProduce.Register.ValidateAccountRegisterForm = function () {

	$('#register').submit(function () {
	
		var valid = 0,
			inputs;
	
	
		// General inputs	
		if ($(this).hasClass('account')) {
			inputs = ['email','password_1','password_2'];
		}
		else {
			inputs = ['firstname','lastname','email','password_1','password_2'];
		}
		
		
		// Loop and validate on empty fields
		for (var i = 0; i < inputs.length; i++) {
		
			var theInput = $('#' + inputs[i]);
		
			if (theInput.val() == '') {
				theInput.addClass('error');
				valid++;
			}
			else {
				theInput.removeClass('error');
			}
			
		
		}
		
		// Special inputs
		
		theInput = $('#email');
		
		if (/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/.test(theInput.val())) {
			theInput.removeClass('error');		
		}
		else {
			theInput.addClass('error');
			valid++;
		}


		// Gender
		if (!$(this).hasClass('account')) {
			if (!$('#gender_m').is(':checked') && !$('#gender_f').is(':checked')) {
				valid++;
				$('#gender_m').parent().css('color', 'red');
			} else {
				$('#gender_m').parent().css('color', '#767676');
			}
		}
		



		// Now see if we are good
		if (valid > 0) {
			return false;
		}
	
		
	});

};






// Events --------------------------------------------------------------------------------------
NiceProduce.Events = function () {
	
}
NiceProduce.Events.GetMonth = function (month, year) {

	var bundle = {
		dataType: "html",
		data: {
			'do': 2,
			'm': month,
			'y': year
		},
		success: NiceProduce.Cart.UpdateCalendar
	};
	
	// Fire the bundle off
	NiceProduce.WebService("event", bundle);
	
};

NiceProduce.Cart.UpdateCalendar = function (data){
	$("#quickCalendar").html(data);
};





// Events --------------------------------------------------------------------------------------
NiceProduce.Account = function () {

	$('a.expand_closed').live('click', function (e) {
		
		$(this).parents('table').next().show();
		$(this).removeClass('expand_closed').addClass('expand_open');
		
		return false;
		
	});
	
	$('a.expand_open').live('click', function (e) {
		
		$(this).parents('table').next().hide();
		$(this).removeClass('expand_open').addClass('expand_closed');
		
		return false;
		
	});
	
	
};






// Gallery --------------------------------------------------------------------------------------
NiceProduce.Gallery = function () {

	var currentHash = window.location.hash.split('#')[1];

	// Load in an image
	if (currentHash !== undefined){
		NiceProduce.Gallery.GetNewImage(currentHash);
	}
	else {
		$('img', '#gallery div.current_photo').show();
	}

	NiceProduce.Gallery.current_image = 0;
	
	$('img', 'div.current_photo').live('click', function (e) {
	
		// Get the next image from the list
		var anchor = $('a', '#gallery .list')[NiceProduce.Gallery.current_image];
		
		var href	= anchor.getAttribute('href');
		var id		= href.split('#')[1];
		
		NiceProduce.Gallery.GetNewImage(id);
		NiceProduce.Gallery.current_image++;
	
	});


	$('a', '#gallery .list').live('click', function (e) {
		
		var href	= this.getAttribute('href');
		var id		= href.split('#')[1];
		NiceProduce.Gallery.GetNewImage(id);
	
		// Update the current image index.
		NiceProduce.Gallery.current_image = $('a', '#gallery .list').index(this);
		
		return false;
		
	});
		
};

NiceProduce.Gallery.GetNewImage = function (id) {

	// Set up the darkened div
	//var img = $('img', 'div.current_photo');
	//var mask = $('div.current_photo_mask', '#gallery');
	
	//mask.height(img.height()).width(img.width()).show();
	
	// Set new hash
	window.location.hash = id;
	
	var bundle	= {
		dataType: "json",
		data: {
			'do': 1,
			'id': id
		},
		success: NiceProduce.Gallery.LoadNewImage
	};
	
	// Fire the bundle off
	NiceProduce.WebService("gallery", bundle);
	
};

NiceProduce.Gallery.LoadNewImage = function (json) {

	var img = $('img', 'div.current_photo');

	img.attr('src', json.image);
	img.load(function(){
		img.show()
	});
	$('h3', 'div.photo').html(json.title);

};














// Webservices ------------------------------------------------------------------------------------

/**
 * Main controller of variables for our webservices. It's better to handle all URL's and payload
 * processing in one function rather than scatter across our NiceProduce object
 * @param {Object} type		- HTTP Method Type
 * @param {Object} payload	- Payload (Object consiting of dataType, data, beforeSend, success objects)
 */
NiceProduce.WebService = function (type, payload) {

	switch (type) {

	case "cart":
		payload.type = "POST";
		payload.url = '/system/webservices/webservice_cart.php';
		break;
	
	case "event":
		payload.type = "POST";
		payload.url = '/system/webservices/webservice_events.php';
		break;
	
	case "register":
		payload.type = "POST";
		payload.url = '/system/webservices/webservice_register.php';
		break;
		
	case "gallery":
		payload.type = "POST";
		payload.url = '/system/webservices/webservice_gallery.php';
		break;
	}
	

	
	// Now fire off to the AJAX handler
	NiceProduce.WebService.AJAX(payload);
	
}


/**
 * Our Global (Standard) AJAX Function
 * 
 * @param {String} url = location of webservice
 * @param {String} el 	= element to update with response
 * @param {String} pb 	= post back function to execute
 * 
 */
NiceProduce.WebService.AJAX = function (ajax) {

	var dataType = (ajax.dataType !== undefined) ? ajax.dataType : "html";
		
	// Hit jQuery's AJAX handler
	$.ajax({
		type: ajax.type,
		url: ajax.url,
		data: ajax.data,
		dataType: dataType,
		beforeSend: function () {
			//console.log('before');
			// Kick start the ajax loader
			//AP.loader = setTimeout('$("#loader").show()', 750);

			if (typeof ajax.beforeSend === "function") {
				ajax.beforeSend();	
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			console.log(XMLHttpRequest);
			console.log(textStatus);
			console.log(errorThrown);
		},
		success: function (data) {
			//console.log('success');	
			// Hide the AJAX Loader
			//clearTimeout(AP.loader);
			//$("#loader").hide();
			
			if (typeof ajax.success === "function") {
				ajax.success(data);
			}
		}
	});
};


// Make our logging life a little easier
jQuery.log = function(message) {
	//window.loadFirebugConsole();
	if(window.console) {
		console.debug(message);
	} else {
		alert(message);
	}
};



NiceProduce.initialize();




// Intialization and Garbage Collection
$(window).ready(function(){

}).unload(function(){
	$("*").unbind();
});
	
		
		
		/* Web Services */
		function ws_Events(a,attr,el){
			var url = '/system/webservices/webservice_events.php';
			switch(a){
				case "notify":
					NiceProduce.ajax(url+'?do='+a+'&eid='+attr[0]+'&cid='+attr[1],$(el),"");
					break;
				case 2:
					var ran_no=(Math.round((Math.random()*9999))); 
					NiceProduce.ajax(url+'?do=2&m='+attr[0]+'&y='+attr[1]+'&ran='+ran_no,$("quickCalendar"),"");
				default:
					break;
			}
		}
		function ws_Customer(a,attr,el){
			var url = '/system/webservices/webservice_customer.php';
			switch(a){
				case 1:
					NiceProduce.ajax(url+'?do='+a+'&=e'+$('login_email').value+'&p='+$('login_password').value,"");
					break;
			}
		}
		function ws_Register(a,attr,el){
			var url = '/system/webservices/webservice_register.php';
			switch (a){
				case "load_geo":
					// Seek suburb according to postcode
					if(attr.length >= 3){
						NiceProduce.ajax(url+'?do='+a+'&p='+attr,$(el),"listItemHighlight('list-address')");
					}
					break;
				case "subscribe":
					/** Insert Proper Validation Here **/
					if (attr.length !== 0) {
						NiceProduce.ajax(url+'?do=' + a + '&p=' + attr, $(el), "NiceProduce.Customer.SubscribeSuccess()");
					}
					break;
			}
		}

function em(e,s){
	location.href = 'mailto:'+e+'@niceproduce.com?subject='+s;
}


//-->