/*******************************
    Utility Functions
    Author: Jack Lukic - KNI
 *******************************/
$.extend(base, {
	
	// handles chromeframe pop-up
	chromeFrameInstall: function() {
		var chromeOptions = { 
			node: 'banner',
			destination: 'index.html',
			// make this true to use onmissing to create custom install implementation
			preventPrompt: true,
			onmissing: function() {
				if(confirm('This website requires Google\'s Chrome Frame plugin to be compatible with IE6). Proceed to download site?')) {
					window.location = 'http://www.google.com/chromeframe';
				}
				else {
					window.location	= 'http://www.mozilla.org';
				}
			}
		};
		try {
			CFInstall.check(chromeOptions);	
		}
		catch(error) {
			// Chrome frame library not included on this page	
			console.log("Could not initiate chrome frame install:\n" + error);
		}
	},
	
	// finds current section by examing body tag
	findSection: function() {
		return $('body').attr('id');	
	},
	
	// handles user agent checking
	isiPad: function() {
		return navigator.userAgent.match(/iPad/i) != null;
	},
	
	isiPhone: function() {
		return navigator.userAgent.match(/iPhone/i) != null;
	},
	isFirefox: function(){
		return navigator.userAgent.match(/Firefox/i) != null;	
	},
	isOldIE: function(){
		return ($.browser.msie && parseInt($.browser.version, 10) < 9)
			? true
			: false
		;
	},
	// bool an email field by regex
	isEmail: function(email) {
		var emailRegEx=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
		if(emailRegEx.test(email)) {
			return true;
		}
		return false;
	},
	// Checks keycode to verify alphanumeric input
	alphaKey: function(e) {
		if(e.keyCode != 16 && e.keyCode != 8 && e.keyCode != 13 && e.keyCode != 20 && e.keyCode != 20 && e.keyCode != '')
			return true	
		else
			return false;
	},
	// writes a cookie
	writeCookie: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else {
			var expires = "";
		}
		console.log("Writing '"+name+"' as value '"+value+"' for "+days+" days");
		document.cookie = name+"="+value+expires+"; path=/";
		return true;
	},
	// Reads a cookie
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') {
				c = c.substring(1,c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				var value = c.substring(nameEQ.length,c.length);
				console.log("'"+name+"' is read as '"+value+"'");
				return value;
			}
		}
		return '';
	},
	getQueryVariable: function(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split('&');
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split('=');
			if (pair[0] == variable) {
				if(pair[1]==undefined){
					return 'null';
				} else{
					return pair[1];
				}
			}
		}
	},
	formatUSCurrency: function(num){
		num = num.toString().replace(/\$|\,/g, "");
		if (isNaN(num)) num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num * 100 + 0.50000000001);
		cents = num % 100;
		num = Math.floor(num / 100).toString();
	
		if (cents < 10) cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
			num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
			
		return (((sign) ? "" : '-') + '$' + num + '.' + cents);
	
	},
	
	openModalLogin: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$login = $('.modal.signin'),
			$close = $login.find("a.close"),
			$submitBtn = $login.find("input.login");

		if(isOldIE) {
			$.dimScreen(0, 0.7);
			var $dimmer = $('#dimmer');
			$login.show();
			// close on dimmer click
			$dimmer.one('click', base.closeModalLogin);
			
		}
		else {
			
			$.dimScreen(200, 0.7, function() {
			// selectors
			var $dimmer = $('#dimmer');

			// animate up and in
			$login
				.css({
					opacity: 0
				})
				.show()
				.animate({
					opacity: 1,
					marginTop: '-=10px'
				}, 350, 'easeOutQuad'
			)
			;
			// close on dimmer click
			$dimmer.one('click', base.closeModalLogin);
			
			});
		} // end if
		$close.click(function(){ base.closeModalLogin(); return false; });
		$submitBtn.click(function(){ base.sendModalLogin(); return false; });
	}, // end openModalLogin
	closeModalLogin: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$login = $('.modal.signin')
			;		
		if(isOldIE) {
			$login.hide();
			$.unDimScreen(0);
		}
		else {
			// reset help
			$login
				.hide()
				.removeAttr('style')
			;
			// undim screen
			$.unDimScreen(200);
		}
	},
	sendModalLogin: function(){

		// check for errors
		var email = $("input#email").val(),
		pass = $("input#pass").val(),
		errors = false,
		errorMsg;
		// cleanup
		$("input, label").removeClass("error");
		
		if (email == ""){
			$("#lbl-email").addClass("error");
			$("#email").addClass("error");
			errors=true;
			errorMsg = "No email provided";
		} else {
			if (!base.isEmail(email)){
				$("#lbl-email").addClass("error");
				$("#email").addClass("error");
				errors=true;
				errorMsg = "invalid email" + email;
			}
		}
		if (pass == ""){
			$("#lbl-pass").addClass("error");
			$("#pass").addClass("error");
			errors=true;
			errorMsg = "no password provided";
		}
		
		if (!errors){
			// post login values, cross fingers for positive reply
			$.getJSON("api/rest/?method=users.login&format=json",{email: email, password: pass},
				function(obj){
					if (obj.failed){
						$("#lbl-email").addClass("error");
						$("#email").addClass("error");
						$("#lbl-pass").addClass("error");
						$("#pass").addClass("error");
					} else {
						// save user email to DOM
						$("#loggedInUserEmail").val(email);
						// are we on the bottle builder?
						// spawn the name dialog
						if ($("body").attr("id") == "builderPage"){
							base.userID = obj.data['id'];
							$('.modal.signin').hide();					
							
							base.openBottleSave();
							
						}
					}
					
				}
			);
		}
		
		return false;
	},
	openBottleSave: function(){
		
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$nameDialog = $('.modal.savebottle'),
			$close = $nameDialog.find("a.close"),
			$saveBtn = $nameDialog.find("input.save"),
			$dimmer = $("#dimmer");

		if ($dimmer.exists()){
			$nameDialog.show();
			$dimmer.one('click', base.closeBottleSave);
		} else {
			if(isOldIE) {
				$.dimScreen(0, 0.7);
				$nameDialog.show();
				// close on dimmer click
				$dimmer.one('click', base.closeBottleSave);
				
			}
			else {
				
				$.dimScreen(200, 0.7, function() {
				// selectors
				var $dimmer = $('#dimmer');
	
				// animate up and in
				$nameDialog
					.css({
						opacity: 0
					})
					.show()
					.animate({
						opacity: 1,
						marginTop: '-=10px'
					}, 350, 'easeOutQuad'
				)
				;
				// close on dimmer click
				$dimmer.one('click', base.closeBottleSave);
				
				});
			}
		} // end if
		$close.click(function(){ base.closeBottleSave(); return false; });
		$saveBtn.click(function(){ base.saveBottle(); return false; });
	},
	closeBottleSave: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$nameDialog = $('.modal.savebottle')
			;		
		if(isOldIE) {
			$nameDialog.hide();
			$.unDimScreen(0);
		}
		else {
			// reset help
			$nameDialog
				.hide()
				.removeAttr('style')
			;
			// undim screen
			$.unDimScreen(200);
		}
	},
	saveBottle: function(){
		$("#lbl-bottleName").removeClass("error");
		$("#bottleName").removeClass	("error");
			
		var bottleName = $("#bottleName").val(),
		errors = false,
		errorMsg = "",
		email = $("#loggedInUserEmail").val();
		
		if (!bottleName){
			$("#lbl-bottleName").addClass("error");
			$("#bottleName").addClass("error");
			errors=true;
		}
		if (!errors){
			$.getJSON("api/rest/?method=bottles.saveBottleName&format=json",{name: bottleName, saved_id: base.bottleBuilderID, user_id: base.userID },
				function(data){
					if(data["failed"] == false){
					 	base.gotoPage("./account/bottles/detail/"+base.bottleBuilderID+"/");
					}
					// base.closeBottleSave();
				}
			);
			
		}
	},
	startSaveBottle: function(bottle_id){
		// save that ID!
		base.bottleBuilderID = bottle_id;
		
		// ready to save a bottle, first check if logged in
		if ($("#loggedInUserEmail").val()){
			base.openBottleSave();
		} else {
			base.openModalLogin();
		}
	},
	bottleArtworkSaved: function(fileObj, serverResponse){
		var html = "";
		var response = jQuery.parseJSON(serverResponse);

		
		
		html += '<tr id="row'+response.data.file_id+'">';
		html += '	<td class="left small filedetails">';
		html += '		<a href="./'+fileObj.filePath+'" class="filename">'+fileObj.name+'</a> <span class="filesize">'+base.readablizeBytes(fileObj.size)+'</span><br />';
		html += '		<a href="#" rel="'+response.data.file_id+'" class="remove">x Remove</a> ';
		html += '	</td>';
		html += '	<td class="right">';	
		html += '	<div id="note'+response.data.file_id+'Hold" data-id="'+response.data.file_id+'" class="notes">';
		html += '		<div class="editable" rel="note'+response.data.file_id+'">';
		html += '			Click here to add a note about this file.';
		html += '		</div>';
		html += '		<div class="editfields hidden" id="note'+response.data.file_id+'Edit">';
		html += '			<textarea class="textarea inlinedit" id="note'+response.data.file_id+'" rel="'+response.data.file_id+'"></textarea>';
		html += '			<div class="button blue save"><a href="#"  rel="note'+response.data.file_id+'">Save</a></div>';
		html += '			<div class="button white cancel"><a href="#" rel="note'+response.data.file_id+'">Cancel</a></div>';
		html += '		</div>';
		html += '	</div>';
		
		html += '	</td>';
		html += '</tr>';
		
		
		$("table#file-list tbody").append(html);
	},
	bottlePDFSaved: function(fileObj, serverResponse){
		var html = "";
		var response = jQuery.parseJSON(serverResponse);
		var bottleID = $("#bottleID").val();
		
		// i understand the ghetto nature of outputting HTML like this but for speeds sake, I'm going with it
		
		html += '<tr id="pdf-content">';
		html += '	<td class="first left small last" >';
		html += '		<div class="button blue"><a href="./'+fileObj.filePath+'" class="icon pdf" target="_blank">View .pdf</a></div>';
		html += '				<span class="pdffilename">'+fileObj.name+'</span>';
		html += '	</td>';
		html += '	<td class="first right last">';
		html += '		<div class="msg">';
		html += '			<div id="note'+bottleID+'Hold" data-id="'+bottleID+'" class="notes">';
		html += '				<div class="editable" rel="note'+bottleID+'">';
		html += ' 					Add a note for this customer to see.';
		html += '				</div>';
		html += '				<div class="editfields hidden" id="note'+bottleID+'Edit">';
		html += '					<textarea class="textarea inlinedit" id="note'+bottleID+'" rel="'+response.data.file_id+'"></textarea>';
		html += '					<div class="button blue addpdf"><a href="#"  rel="note'+bottleID+'">Save</a></div>';
		html += '					<div class="button white cancel"><a href="#" rel="note'+bottleID+'">Cancel</a></div>';
		html += '				</div>';
		html += '			</div>';
		html += '		</div>';
		html += '	</td>';
		html += '</tr>';

		
		if ($("#pdf-missing").exists()){ $("#pdf-missing").hide(); }
		$("table#pdfList tbody").html(html);
	},
	addPDFComment: function(bottleID, pdfComment) {
		$.getJSON("api/rest/?method=bottles.editPDFComment&format=json",{comment: pdfComment, bottle_id: bottleID},
		   function(data) {
				if(data["failed"] == false){
					$("#note"+bottleID+"Hold").find("div.editable").html(pdfComment);
					$("#note"+bottleID+"Hold").find(".editable").show();
					$("#note"+bottleID+"Hold").find(".editfields").hide();
				} else {
					alert(base.errorSaving);
				}
			}
		);
	},
	approvePDF: function(bottleID){
		$.getJSON("api/rest/?method=bottles.approve&format=json",{bottle_id: bottleID},
		   function(data) {
				if(data["failed"] == false){
					$("table.review .tools").fadeOut();
					$("table.review .msg").append('<div class="pagestatus approved"><h3><strong>PDF Proof Approved</strong></h3></div>');
				} else {
					alert(base.errorSaving);
				}
			}
		);
	},
	readablizeBytes: function (bytes) {
		// from: http://web.elctech.com/2009/01/06/convert-filesize-bytes-to-readable-string-in-javascript/
		var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
		var e = Math.floor(Math.log(bytes)/Math.log(1024));
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
	},
	removeSavedBottle: function(bottleID){
		var confirmDelete = confirm(base.confirmDeleteMessage);
		if (confirmDelete){
			// TODO: NEED TO POST THIS INFORMATION TO A DB FOR REMOVAL
			$.getJSON("api/rest/?method=bottles.removeSavedBottle&format=json",
				{bottle_id: bottleID},
				function(data)
				{
					if(data["failed"] == false){
						$("#myBottle"+bottleID).fadeOut(700, 
							function(){ 
								base.padList($("ul.bottlelist li"), base.bottleItemsPerRow, true); 
							}
						);
					}
				}
			);

		}	
	},
	renameSavedBottle: function(targ, id, type) {
		var newValue= "";
		
		// TITLE FIELD? send to different API endpoint with different vars
		if (type == "title"){		
			newValue = $("#"+targ+"Hold").find(".editfields .textfield").val();
	
			$.getJSON("api/rest/?method=bottles.saveBottleName&format=json",{name: newValue, saved_id: id, user_id:0},
			   function(data) {
					if(data["failed"] == false){
						$("#"+targ+"Hold").find("h3.editable").html(newValue);
						$("#"+targ+"Hold").find(".editable").show();
						$("#"+targ+"Hold").find(".editfields").hide();
					} else {
						$("#bottleTitle").val("ERROR SAVING!");
					}
					
			   });
				   
				   
			} else {
		   // NOTE FIELD? send to different API endpoint with different vars
			newValue = $("#"+targ+"Hold").find(".editfields .textarea").val();
			   
			   $.getJSON("api/rest/?method=bottles.editFileNotes&format=json",{note_id: id, notes_txt: newValue},
				   function(data) {
						if(data["failed"] == false){
							$("#"+targ+"Hold").find(".editable").html(newValue);
							$("#"+targ+"Hold").find(".editable").show();
							$("#"+targ+"Hold").find(".editfields").hide();
						} else {
							$("#"+targ+"Hold").find(".editable").html("ERROR SAVING!");
							$("#"+targ+"Hold").find(".editable").show();
							$("#"+targ+"Hold").find(".editfields").hide();
						}
						
				   });
				 
				   
			}	
		
	},
	quickBottleRename: function(bottleID, bottleTitle) {
		$.getJSON("api/rest/?method=bottles.saveBottleName&format=json",{name: bottleTitle, saved_id: bottleID, user_id:0},
			   function(data) {
					if(data["failed"] == false){
						// do nothing
						
					} else {
						alert(base.errorSaving);
					}
					
			   });
	},
	renameCartOrder: function(targ, id, type) {
		var newValue= "";
		newValue = $("#"+targ+"Hold").find(".editfields .textfield").val();
		$.getJSON("api/rest/?method=orders.renameOrder&format=json",{name: newValue, order_id: id},
		   function(data) {
				if(data["failed"] == false){
					$("#"+targ+"Hold").find("h3.editable").html(newValue);
					$("#"+targ+"Hold").find(".editable").show();
					$("#"+targ+"Hold").find(".editfields").hide();
				} else {
					$("#bottleTitle").val("ERROR SAVING!");
				}
				
		   });	
	},
	// called from Bottle Detail page
	addBottleToCart: function(bottleID, isAdmin)
	{
		// not being called from admin page
		if (!isAdmin){
			// send to addToCart - API will decipher user_id and current card id
			$.getJSON("api/rest/?method=orders.addToCart&format=json",{bottle_id: bottleID},
			  function(data) {
				if(data["failed"] == false){
					base.gotoPage("./account/cart/");
				} else {
					alert(base.addToCartErrorMessage);
				}
		   });	
		} else {
			
			// being sent from admin page - which means this could be for ANY user
			var orderID = $("#order-id").val();
			// send to addToCart - API will decipher user_id and current card id
			$.getJSON("api/rest/?method=orders.addToCart&format=json",{bottle_id: bottleID, order_id: orderID},
			  function(data) {
				if(data["failed"] == false){
					base.gotoPage("./admin/order/"+orderID+"/");
					//alert("supposedly added to cart");
				} else {
					alert(base.addToCartErrorMessage);
				}
		   });	
		}
	},
	// called from My Cart page - does the same as above but different callback reaction
	addColorway: function(bottleID, orderID)
	{
		
		$.getJSON("api/rest/?method=orders.addToCart&format=json",{bottle_id: bottleID, order_id: orderID},
		
			  function(data) {
					if(data["failed"] == false){
						var $newID = data['data'],
							$link = $("#addMore"+bottleID),
							$form = $("#addMore"+bottleID).parents('form'),
							itemIndex = $('td.addmore a').index($link),
							$parentTD = $link.parents('tr'),
							$lastRow = $parentTD.prev('.configuration'),
							$labelRow = $parentTD.parents('table').find('tr.first.configuration td:first-child').eq(itemIndex),
							numberConfigurations = $labelRow.attr('rowspan'),
							numberAdded = (typeof $form.data('added') != 'undefined')
								? $form.data('added')
								: 1
							;
					
							$lastRow
								.clone(true)
								.attr("id","")
								.find("td.left").remove().end()					
								.addClass('new')
			
								.removeClass('first')
								.find('select, input')
									.each(function() {
										var $field = $(this),
											fieldName = $field.attr('name'),
											name = fieldName.split('-')[0],
											newFieldName = fieldName.replace(name, 'added'+numberAdded);
										;
										$field.attr('name',  newFieldName);
										
									})
									.end()
								.find('input.id')
									.val($newID)
									.end()
								.insertAfter($lastRow)
							;
							$labelRow.attr('rowspan', numberConfigurations+1);
							$form.data('added', numberAdded + 1);
							
							base.tallyCart();
						
					} else {
						alert(base.addToCartErrorMessage);
					}
					
			   });	
	},
	removeBottleFromCart: function(configID)
	{
		$.getJSON("api/rest/?method=orders.removeColorway&format=json",{config_id: configID},
		
			  function(data) {
				  if (data["failed"] == false){
					  base.tallyCart();
				  }
					/*if(data["failed"] == false){
						alert("bottle removed" + configID);
					} else {
						alert("bottle not removed: " + data);
					}*/
					
			   });	
	},
	finalizeOrder: function(){
		var orderID = $("#order-id").val();

		$.getJSON("api/rest/?method=orders.finalize&format=json",{order_id: orderID},
		
			  function(data) {
				  if (data["failed"] == false){
					 base.gotoPage("./account/orders/saved/");
				  } else {
					  alert(base.errorSaving);
				  }
					
			   });	
	},
	updateOrderStatus: function(orderStatus, orderID){
		
		$.getJSON("api/rest/?method=orders.setStatus&format=json",{status: orderStatus, order_id: orderID},
		
			  function(data) {
				  if (data["failed"] == false){
					 $(".ordersort").find(".button a").html("Saved!");
					 base.timer = setTimeout(function() {
						 $(".ordersort").find(".button a").html("Save");
					}, 3000);
				  } else {
					  alert(base.errorSaving);
				  }
					
			   });	
	},
	openPDFFeedbackModal: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$login = $('.modal.feedback'),
			$close = $login.find("a.close"),
			$submitBtn = $login.find("input.submit");

		if(isOldIE) {
			$.dimScreen(0, 0.7);
			var $dimmer = $('#dimmer');
			$login.show();
			// close on dimmer click
			$dimmer.one('click', base.closePDFFeedbackModal);
			
		}
		else {
			
			$.dimScreen(200, 0.7, function() {
			// selectors
			var $dimmer = $('#dimmer');

			// animate up and in
			$login
				.css({
					opacity: 0
				})
				.show()
				.animate({
					opacity: 1,
					marginTop: '-=10px'
				}, 350, 'easeOutQuad'
			)
			;
			// close on dimmer click
			$dimmer.one('click', base.closePDFFeedbackModal);
			
			});
		} // end if
		$close.click(function(){ base.closePDFFeedbackModal(); return false; });
		$submitBtn.click(function(){ base.sendPDFFeedbackModal(); return false; });
	}, // end openModalLogin
	closePDFFeedbackModal: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$login = $('.modal.feedback')
			;		
		if(isOldIE) {
			$login.hide();
			$.unDimScreen(0);
		}
		else {
			// reset help
			$login
				.hide()
				.removeAttr('style')
			;
			// undim screen
			$.unDimScreen(200);
		}
	},
	sendPDFFeedbackModal: function(){

		// check for errors
		var feedback = $("textarea#feedback").val(),
		bottleID = $("#bottleID").val(),
		errors = false,
		errorMsg;
		// cleanup
		$("textarea, label").removeClass("error");
		
		if (feedback == ""){
			$("#lbl-feedback").addClass("error");
			$("#feedback").addClass("error");
			errors=true;
			errorMsg = "Please provide some feedback.";
		}
		
		if (!errors){
			// post login values, cross fingers for positive reply
			$.getJSON("api/rest/?method=bottles.editPDFReply&format=json",{bottle_id: bottleID, reply: feedback},
				function(obj){
					if (obj.failed){
						$("#lbl-feedback").addClass("error");
						$("#feedback").addClass("error");
					} else {
						// passed
						$("table.review td div.msg").append("<div class='reply'>"+feedback+"</div>");
						$("table.review td div.tools").fadeOut();
						base.closePDFFeedbackModal();
					}
					
				}
			);
		}
		
		return false;
	},
	// called from Cart page -> headed to Review page
	finalizeSave: function (endDestination){
		//base.saveCart();
		//window.location.href=endDestination;
		base.saveCart(base.gotoPage(endDestination));
	},
	gotoPage: function(endDestination){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 8);
		if (isOldIE){
			endDestination = endDestination.replace(".","");
			window.location = base.urlRoot+endDestination;
		} else {
			window.location = endDestination;
		}
	},
	adminCompleteOrder: function(){
		var orderID = $("#order-id").val();
		
		$.getJSON("api/rest/?method=orders.setStatus&format=json",{status: "completed", order_id: orderID},
			function(data) {
				if (data["failed"] == false){
				 	base.gotoPage("./admin/orders/completed/");
				} else {
					alert(base.errorSaving);
				}	
			});	
	},
	openBottleAddModal: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$modal = $('.modal.addbottles'),
			$close = $modal.find("a.close")
			//$submitBtn = $login.find("input.submit");

		if(isOldIE) {
			$.dimScreen(0, 0.7);
			var $dimmer = $('#dimmer');
			$modal.show();
			// close on dimmer click
			$dimmer.one('click', base.closeBottleAddModal);
			
		}
		else {
			
			$.dimScreen(200, 0.7, function() {
			// selectors
			var $dimmer = $('#dimmer');

			// animate up and in
			$modal
				.css({
					opacity: 0
				})
				.show()
				.animate({
					opacity: 1,
					marginTop: '-=10px'
				}, 350, 'easeOutQuad'
			)
			;
			// close on dimmer click
			$dimmer.one('click', base.closeBottleAddModal);
			
			});
		} // end if
		$close.click(function(){ base.closeBottleAddModal(); return false; });
		
	}, // end openModalLogin
	closeBottleAddModal: function(){
		var isOldIE = ($.browser.msie && parseInt($.browser.version, 10) < 9),
			$modal = $('.modal.addbottles')
			;		
		if(isOldIE) {
			$modal.hide();
			$.unDimScreen(0);
		}
		else {
			// reset help
			$modal
				.hide()
				.removeAttr('style')
			;
			// undim screen
			$.unDimScreen(200);
		}
	},
	requestPDFApproval: function(bottleID, userID){
		$.getJSON("api/rest/?method=bottles.requestPDFApproval&format=json",{bottle_id: bottleID, user_id: userID},
		
			  function(data) {
				  if (data["failed"] == false){
					 $("#statusMsg").html("User has been requested for PDF approval.").fadeIn();
					  base.timer = setTimeout(function() {
						 $("#statusMsg").fadeOut();
					}, 3000);
				  }
					/*if(data["failed"] == false){
						alert("bottle removed" + configID);
					} else {
						alert("bottle not removed: " + data);
					}*/
					
			   });		
	}
	/*sendPDFFeedbackModal: function(){

		// check for errors
		var feedback = $("textarea#feedback").val(),
		bottleID = $("#bottleID").val(),
		errors = false,
		errorMsg;
		// cleanup
		$("textarea, label").removeClass("error");
		
		if (feedback == ""){
			$("#lbl-feedback").addClass("error");
			$("#feedback").addClass("error");
			errors=true;
			errorMsg = "Please provide some feedback.";
		}
		
		if (!errors){
			// post login values, cross fingers for positive reply
			$.getJSON("api/rest/?method=bottles.editPDFReply&format=json",{bottle_id: bottleID, reply: feedback},
				function(obj){
					if (obj.failed){
						$("#lbl-feedback").addClass("error");
						$("#feedback").addClass("error");
					} else {
						// passed
						$("table.review td div.msg").append("<div class='reply'>"+feedback+"</div>");
						$("table.review td div.tools").fadeOut();
						base.closePDFFeedbackModal();
					}
					
				}
			);
		}
		
		return false;
	}*/
});

/*******************************
       Namespaced Functions
 *******************************/
 
// basic definition
base.nameSpace = {};

base.nameSpace.example = function () {
}

 

base.validateAccountInfo = function(){
		
		
		returnFalse		= false;
		
			// block 1
			var id		= $("#accountinfo #id").val();
			var fname 	= $('#accountinfo #firstname').val();			
			var lname 	= $('#accountinfo #lastname').val();
			var pass 	= $("#accountinfo #pass").val();
			var passconf= $('#accountinfo #passconf').val();
			
			// block 2
			var address	= $('#accountinfo #address').val();
			var city	= $('#accountinfo #city').val();
			var state	= $('#accountinfo #state').val();
			var country	= $('#accountinfo #country').val();
			var zip		= $('#accountinfo #zip').val();
			var phone	= $('#accountinfo #phone').val();
			var email	= $('#accountinfo #email').val();
			var company = $('#accountinfo #company').val();
			var accountnum 	= $('#accountinfo #account_number').val();
			var resalenum	= $('#accountinfo #resale_number').val();
			
			// block 3
			var shippingBool 	= $("#accountinfo #billing_as_shipping").attr("checked");
			var shippingAddress	= $('#accountinfo  #shipping_address').val();
			var shippingCity	= $('#accountinfo #shipping_city').val();
			var shippingState	= $('#accountinfo #shipping_state').val();
			var shippingCountry	= $('#accountinfo #shipping_country').val();
			var shippingZip		= $('#accountinfo #shipping_zip').val();
			var shippingPhone	= $('#accountinfo #shipping_phone').val();
			
			
			// inline error checking
			var errorMessages 	= [];
			var errorFields		= [];
			var errorReport		= "";
			
			if(fname == '') {
				errorMessages.push(base.errors.noFirstName);
				errorFields.push("firstname");
			}
			if(lname == '') {
				errorMessages.push(base.errors.noLastName);
				errorFields.push("lastname");
			}
			// only check this if an ID is present (i.e. they have an account already)
			if (!id){
				if (pass != passconf){
					errorMessages.push(base.errors.passwordMatch);
					errorFields.push("passconf");
				}
				if (pass == ""){
					errorMessages.push(base.errors.passwordBlank);
					errorFields.push("pass");
				}
				if (passconf == ""){
					errorFields.push("passconf");
				}
			}
			
			// show errors on block 1
			if (errorMessages.length > 0){
				$("#accountinfo-one").addClass("error");
				$("#accountinfo-one .helper").html("ERROR").addClass("error").css("display","block");
				for (i=0;i<=errorMessages.length-1;i++){
					errorReport	+= errorMessages[i] + "<br />";
					$("#lbl-"+errorFields[i]).addClass("error");
					$("#"+errorFields[i]).addClass("error");
					$("#"+errorFields[i]).css("background-position","0px -68px");
				}
				$("#accountinfo-one p").html(errorReport);
				
				
				returnFalse = true;
				
			}
			
			/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
			// block 2
				// inline error checking
			var errorMessagesTwo 	= [];
			var errorFieldsTwo		= [];
			var errorReportTwo		= "";
			
			if(!address) {
				errorMessagesTwo.push(base.errors.noAddress);
				errorFieldsTwo.push("address");
			} 
			if(city == '') {
				errorMessagesTwo.push(base.errors.noCity);
				errorFieldsTwo.push("city");
			}
			if (state == ''){
				errorMessagesTwo.push(base.errors.noState);
				errorFieldsTwo.push("state");
			}
			if (!country){
				errorMessagesTwo.push(base.errors.noCountry);
				errorFieldsTwo.push("country");
			}
			if (zip == ""){
				errorMessagesTwo.push(base.errors.noZipcode);
				errorFieldsTwo.push("zip");
			}
			if (phone == ""){
				errorMessagesTwo.push(base.errors.noPhone);
				errorFieldsTwo.push("phone");
			}
			if (email == ""){
				errorMessagesTwo.push(base.errors.noEmail);
				errorFieldsTwo.push("email");
			} else {
				if (!base.isEmail(email)){
					errorMessagesTwo.push(base.errors.invalidEmail);
					errorFieldsTwo.push("email");
				}
			}
			if (company == ""){
				errorMessagesTwo.push(base.errors.noCompany);
				errorFieldsTwo.push("company");
			}
			/*if (accountnum == ""){
				errorMessagesTwo.push(base.errors.noAccount);
				errorFieldsTwo.push("account_number");
			}
			if (resalenum == ""){
				errorMessagesTwo.push(base.errors.noResale);
				errorFieldsTwo.push("resale_number");
			}*/
			// show errors on block 1
			if (errorMessagesTwo.length > 0){
				$("#accountinfo-two").addClass("error");
				$("#accountinfo-two .helper").html("ERROR").addClass("error").css("display","block");
				
				for (i=0;i<=errorMessagesTwo.length-1;i++){
					errorReportTwo	+= errorMessagesTwo[i] + "<br />";
					$("#lbl-"+errorFieldsTwo[i]).addClass("error");
					$("#"+errorFieldsTwo[i]).addClass("error");
					$("#"+errorFieldsTwo[i]).css("background-position","0px -68px");
					
					if ($("#lbl-"+errorFieldsTwo[i]).parents(".selectpair").exists()){
						$("#lbl-"+errorFieldsTwo[i]).parents(".selectpair").addClass("error");
					}
					
				}
				
				
				$("#accountinfo-two p").html(errorReportTwo);
				
				returnFalse = true;
			}
			
			/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
			// block 3
			// inline error checking
			if (!shippingBool){
				var errorMessagesThree 	= [];
				var errorFieldsThree	= [];
				var errorReportThree	= "";
				
				if(!shippingAddress) {
					errorMessagesThree.push(base.errors.noAddress);
					errorFieldsThree.push("shipping_address");
				} 
				if(shippingCity == '') {
					errorMessagesThree.push(base.errors.noCity);
					errorFieldsThree.push("shipping_city");
				}
				if (shippingState == ''){
					errorMessagesThree.push(base.errors.noState);
					errorFieldsThree.push("shipping_state");
				}
				if (!shippingCountry){
					errorMessagesThree.push(base.errors.noCountry);
					errorFieldsThree.push("shipping_country");
				}
				if (shippingZip == ""){
					errorMessagesThree.push(base.errors.noZipcode);
					errorFieldsThree.push("shipping_zip");
				}
				if (shippingPhone == ""){
					errorMessagesThree.push(base.errors.noPhone);
					errorFieldsThree.push("shipping_phone");
				}
				
				// show errors on block 1
				if (errorMessagesThree.length > 0){
					$("#accountinfo-three").addClass("error");
					$("#accountinfo-three .helper").html("ERROR").addClass("error").css("display","block");
					
					for (i=0;i<=errorMessagesThree.length-1;i++){
						errorReportThree	+= errorMessagesThree[i] + "<br />";
						$("#lbl-"+errorFieldsThree[i]).addClass("error");
						$("#"+errorFieldsThree[i]).addClass("error");
						$("#"+errorFieldsThree[i]).css("background-position","0px -68px");
						
						
						if ($("#lbl-"+errorFieldsThree[i]).parents(".selectpair").exists()){
							$("#lbl-"+errorFieldsThree[i]).parents(".selectpair").addClass("error");
						}
						
					}
					$("#accountinfo-three p").html(errorReportThree);
					
					returnFalse = true;
				}
			}
		
			
			if (returnFalse)
			{
				return false;
			} else {
				return true;
			}
}
base.cleanupAccountErrors = function(){ 
	$("#accountinfo-one").removeClass("error");
	$("#accountinfo-two").removeClass("error");
	$("#accountinfo-three").removeClass("error");
	
	$("#accountinfo-one p").html();
	$("#accountinfo-two p").html();
	$("#accountinfo-three p").html();
	
	$("#accountinfo .helper").removeClass("error");
	
	$("#accountinfo label").removeClass("error");
	$("#accountinfo input").removeClass("error");
	// hate to do it this way but was getting display error otherwise
	$("#accountinfo input:not(#submitbutton)").css("background-position","0px 0px");
}

base.validateLoginInfo = function(){
		
	returnFalse		= false;
		
	// block 1
	var email 	= $('#logininfo #email').val();			
	var pass 	= $("#logininfo #pass").val();
			
			
	// inline error checking
	var errorMessages 	= [];
	var errorFields		= [];
	var errorReport		= "";
			
	if (email == ""){
		errorMessages.push(base.errors.noEmail);
		errorFields.push("email");
	} else {
		if (!base.isEmail(email)){
			errorMessages.push(base.errors.invalidEmail);
			errorFields.push("email");
		}
	}
	if (pass == ""){
		errorMessages.push(base.errors.passwordBlank);
		errorFields.push("pass");
	}
	// show errors on block 1
	if (errorMessages.length > 0){
		$("#logininfo-one").addClass("error");
		$("#logininfo-one .helper").html("ERROR").addClass("error").css("display","block");
		for (i=0;i<=errorMessages.length-1;i++){
			errorReport	+= errorMessages[i] + "<br />";
			$("#lbl-"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).css("background-position","0px -68px");
		}
		$("#logininfo-one p").html(errorReport);

		returnFalse = true;
			
	}
	if (returnFalse)
	{
		return false;
	} else {
		return true;
	}
}

base.cleanupLoginErrors = function(){ 
	$("#logininfo-one").removeClass("error");

	$("#logininfo-one p").html();
	
	$("#logininfo .helper").removeClass("error");
	
	$("#logininfo label").removeClass("error");
	$("#logininfo input").removeClass("error");
	// hate to do it this way but was getting display error otherwise
	$("#logininfo input:not(#submitbutton)").css("background-position","0px 0px");
}




base.validateRetrievalInfo = function(){
		
	returnFalse		= false;
		
	// block 1
	var email 	= $('#retrieveinfo #email').val();			
			
			
	// inline error checking
	var errorMessages 	= [];
	var errorFields		= [];
	var errorReport		= "";
			
	if (email == ""){
		errorMessages.push(base.errors.noEmail);
		errorFields.push("email");
	} else {
		if (!base.isEmail(email)){
			errorMessages.push(base.errors.invalidEmail);
			errorFields.push("email");
		}
	}
	
	// show errors on block 1
	if (errorMessages.length > 0){
		$("#retrieveinfo-one").addClass("error");
		$("#retrieveinfo-one .helper").html("ERROR").addClass("error").css("display","block");
		for (i=0;i<=errorMessages.length-1;i++){
			errorReport	+= errorMessages[i] + "<br />";
			$("#lbl-"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).css("background-position","0px -68px");
		}
		$("#retrieveinfo-one p").html(errorReport);

		returnFalse = true;
			
	}
	if (returnFalse)
	{
		return false;
	} else {
		return true;
	}
}
base.validateResetInfo = function(){
	returnFalse		= false;
		
	// block 1
	var pass 	= $('#password').val();			
	var passconf = $('#passconf').val();
			
	// inline error checking
	var errorMessages 	= [];
	var errorFields		= [];
	var errorReport		= "";
			
	if (pass == ""){
		errorMessages.push(base.errors.passwordBlank);
		errorFields.push("password");
	} else {
		if (pass != passconf){
			errorMessages.push(base.errors.passwordMatch);	
			errorFields.push("passconf");
		}
	}
	
	// show errors on block 1
	if (errorMessages.length > 0){
		$("#retrieveinfo-one").addClass("error");
		$("#retrieveinfo-one .helper").html("ERROR").addClass("error").css("display","block");
		for (i=0;i<=errorMessages.length-1;i++){
			errorReport	+= errorMessages[i] + "<br />";
			$("#lbl-"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).css("background-position","0px -68px");
		}
		$("#retrieveinfo-one p").html(errorReport);
		
		returnFalse = true;
			
	}
	if (returnFalse)
	{
		return false;
	} else {
		return true;
	}
}
base.cleanupRetrievalErrors = function(){ 
	$("#retrieveinfo-one").removeClass("error");

	$("#retrieveinfo-one p").html();
	
	$("#retrieveinfo .helper").removeClass("error");
	
	$("#retrieveinfo label").removeClass("error");
	$("#retrieveinfo input").removeClass("error");
	// hate to do it this way but was getting display error otherwise
	$("#retrieveinfo input:not(#submitbutton)").css("background-position","0px 0px");
}


base.padList = function($list, itemsPerRow) {
	
	var $list = $list.filter(':visible').removeClass('no-padding').removeClass('no-border');
	
	var trailingItems = $list.size() % itemsPerRow;
	
	// if entire row is trailing, use whole row
	
	// rewrote to not use bugged nth-child in jquery
	if ($list.size() > 2){
		if (trailingItems > 0 ){
	
			$list
				.each(function(i) {
					if(i != 0 && (i+1) % itemsPerRow == 0) {
						$(this).addClass('no-border');
					}
				}
			);
		
			$list
				.slice(-trailingItems)
					.addClass('no-border');
				
		} 
	}
	
}
base.heightenList = function($list ) {
	
	var $list = $list.filter(':visible');
	var maxHeight = 0;
	
	// rewrote to not use bugged nth-child in jquery
	$list
		.each(function(i) {
			if ($(this).height() > maxHeight){
				maxHeight = $(this).height();
			}
		}
	);
	$list.parents().filter("li")
		.height(maxHeight + 100);
		
		//alert(maxHeight);
}
base.addArtworkFile	= function($queueID, $uniqueID, $filename, $filesize){
	// uploadify1BBVFGHH becomes uploadify1
	var base = $queueID.replace($uniqueID,"");
	// uploadify1 becomes 1
	base = base.replace("uploadify","");
	// now base is just an integer that we can use in many ways
	$("#filelist"+base).append("<li><a href=\""+base.mediaDir + $filename+"\">"+$filename + " <em>("+$filesize+")</em></a></li>")
}
/*
base.removeSavedBottle = function($bottleID){
	var confirmDelete = confirm(base.confirmDeleteMessage);
	if (confirmDelete){
		// TODO: NEED TO POST THIS INFORMATION TO A DB FOR REMOVAL
		/*$.post("_include/function_deleteSavedBottle.php",
				{target: $bottleID},
				function(data)
				{
					if (data == "ok"){
						$(".bottlelist li#bottle"+$bottleID).fadeOut();
					}
				});
		$(".bottlelist li#bottle"+$bottleID).fadeOut(700, function(){ base.padList($("ul.bottlelist li"), base.bottleItemsPerRow, true); });
	}
}*/

base.updateCartChoices = function($bottle, callback) {
	var $configuration = $bottle.closest('.configuration'),
		$bottleColorSelect = $configuration.find('.bottle-color'),
		$capColorSelect = $configuration.find('.cap-color'),
		$capTypeSelect = $configuration.find('.cap-type'),
				
		bottle = $bottle.val(),
		currentCapColor = $capColorSelect.val(),
		currentBottleColor = $bottleColorSelect.val(),
		currentCapType = $capTypeSelect.val()
	;
	if(typeof base.bottles[bottle] != 'undefined') {	
		var bottleConfig = base.bottles[bottle],
			bottleColors = bottleConfig.bottleColor,
			capTypeChoices = {},
			firstCapType = false
		;
		
		$.each(bottleConfig.cap, function(name, value) {
			firstCapType = (!firstCapType)
				? name
				: firstCapType
			;
			capTypeChoices[name] = name;
		});
		var selectedCapType = (jQuery.inArray(currentCapType, capTypeChoices) != -1)
			? currentCapType
			: firstCapType
		; 
		
		var
			capColorChoices = bottleConfig.cap[selectedCapType],
			newBottleSelectHTML = base.generateDropdownHTML(bottleColors, 'bottle-color', $bottleColorSelect.attr('name'), currentBottleColor),
			newCapTypeHTML = base.generateDropdownHTML(capTypeChoices, 'cap-type', $capTypeSelect.attr('name') , currentCapType),
			newCapSelectHTML = base.generateDropdownHTML(capColorChoices, 'cap-color', $capColorSelect.attr('name') , currentCapColor)
		;
		$bottleColorSelect
			.parent()
			.html(newBottleSelectHTML)
		;
		$capTypeSelect
			.parent()
			.html(newCapTypeHTML)
		;
		$capColorSelect
			.parent()
			.html(newCapSelectHTML)
		;
		if(typeof callback == 'function') {
			callback($bottle);
		}
	}	
}

base.saveCart = function(callback) {
	var $form = $('#cartform'),
		$saveText = $form.find('.refresh.cart'),
		$saveButton = $saveText.parent(),
		$newConfigurations = $form.find('.new.configuration'),
		$cartID = $("#card-id").val(),
		formData = $form.serialize(),
		ajaxSettings = {
			type: 'POST',
			url: base.cartAPI,
			dataType: 'json',
			data: formData,
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest, textStatus, errorThrown);
			},
			complete: function() {
				$saveButton.removeClass('loading');
			},
			success: function(response) {
				console.log(response);
				clearTimeout(base.timer);
				var text = $saveText.text();
				$saveButton.addClass('success');
				$saveText.text('Cart Updated!');
				base.timer = setTimeout(function() {
					$saveButton.removeClass('success');
					$saveText.text("");
				}, 3000);
				if(typeof response.success != 'undefined' && response.success) {
					// insert new ids					
					if($.isArray(response.api)) {
						// add new config ids
						$newConfigurations
							.each(function(index) {
								console.log(index);
								if(typeof response.api[index] != 'undefined') {
									console.log(response.api[index]);
									$(this)
										.find('input.id')
										.val(response.api[index])
									;
								}
							})
						;
					}
					
					if(typeof callback == 'function') {
						callback();	
					}
				} 
			}
		}
		if(!$saveButton.hasClass('loading') && !$saveButton.hasClass('success')) {
			$saveButton.addClass('loading');
			$saveText.text('Updating');
			$.ajax(ajaxSettings);
		}
		// button not ready, set interval to retry
		else {
			base.interval = setInterval(function() {
				if(!$saveButton.hasClass('loading') && !$saveButton.hasClass('success')) {
					clearInterval(base.interval);
					$saveButton.addClass('loading');
					$.ajax(ajaxSettings);
				}
			}, 100);
		}
	
	return false;
}

base.findBottleCost = function($this, callback) {
	if(typeof $this == 'object') {
		var	$configuration = $this.parents('.configuration'),
			$bottle = $configuration.find('.bottle'),
			$quantity = $configuration.find('.quantity'),
			$imageColor = $configuration.find('.image-color'),
			$capType = $configuration.find('.cap-type'),
			
			$priceContainer = $configuration.find('.ppu'),
			$throbber = $priceContainer.find('.throbber'),
			$saveCart = $configuration.parents('form').find('.cart .refresh.button'),
			$price = $priceContainer.find('.price'),
			$priceNumber = $price.find('span'),
			
			bottle = $bottle.val(),
			quantity = $quantity.val(),
			imageColor = $imageColor.val(),
			capType = $capType.val(),
			
			ajaxSettings = {
				type: 'POST',
				url: base.priceAPI,
				dataType: 'json',
				data: {
					bottle: bottle,
					color: imageColor,
					quantity: quantity,
					cap: capType
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest, textStatus, errorThrown);
				},
				complete: function() {
					$saveCart.removeClass('loading');
					$throbber.hide();
					$price.show();
				},
				success: function(data) {
					if(typeof data.success != 'undefined' && data.success) {
						$priceNumber.html(data.price.cost);
						//base.saveCart();
						if(typeof callback == 'function') {
							callback();	
						}
					}
				}
			}
		;
		// show throbber
		$saveCart.addClass('loading');
		$throbber.show();
		$price.hide();
		$.ajax(ajaxSettings);
		
	}
}

base.generateDropdownHTML = function(choices, className, name, activeValue) {
	var customDropdown = '<select class="' + className +'" name="' + name +'"> \n',
		activeValue = (typeof activeValue != 'undefined')
			? activeValue
			: ''
	;	
	if(typeof choices == 'object') {
		jQuery.each(choices, function(value, name) {		
			if(value != activeValue) {
				customDropdown += '<option value="'+value+'">'+name+'</option> \n';
			}
			// active option
			else {
				customDropdown += '<option value="'+value+'" selected="selected">'+name+'</option> \n';						
			}
		});
		customDropdown += '</select>';
		return customDropdown;
	}
	return false;
}

base.tallyCart = function(){
	
	var $currentField = $(this),		
		$shippingCostPerCase = $('#shipping-per-case'),
		$taxRate = $('#tax-rate'),
		$minimumCases = $('#minimum-case'),
	
		$subTotal = $('#amt-subtotal'),
		$shippingTotal = $('#amt-shipping'),
		$taxTotal = $('#amt-tax'),
		$grandTotal = $('#amt-est-total'),	
		
		$configurations = $('tr.configuration'),	
	
		taxRate = +($taxRate.val()),
		shippingCostPerCase = $shippingCostPerCase.val(),
		minimumCases = $minimumCases.val(),
		editedValue = $currentField.val(),
		
		itemTotal = 0,
		totalItems = 0,
		totalCases = 0,
		totalBottles = 0,
		
		itemIndex = 0,
		totalItems = $configurations.size(),
		
		taxTotal = 0,
		shippingTotal = 0,
		currencyFormat = {
			format: '$#,###.00', 
			locale: 'en'
		}		
	;
	
	// fix non numeric values
	if(isNaN( $currentField.val() )) {
		$currentField.val('0');
	}
	
	// calculate individual item costs
	while(itemIndex < totalItems) {
		var $configuration = $configurations.eq(itemIndex),
			$pricePerBottle = $configuration.find('.ppu span'),
			$bottleQuantity = $configuration.find('.quantity'),
			$formPrice = $configuration.find('input.estimated-price'),
			$total = $configuration.find('.totalprice'),
			
			bottleQuantity = +($bottleQuantity.val()),
			pricePerBottle = +($pricePerBottle.html()),
			cost = 0
		;

		cost = (bottleQuantity * pricePerBottle);
		
		itemTotal += +(cost);
		totalCases += (bottleQuantity / 50);
		totalBottles += bottleQuantity;
			
		$formPrice.val(cost);	
		$total
			.html(cost)
			.format(currencyFormat)
		;
		
		itemIndex++;	
	}
	// calculate tax cost
	taxTotal = itemTotal * ( (1/100) * taxRate);
	
	// calculate shipping cost
	shippingTotal = shippingCostPerCase * Math.ceil(totalCases);
	if(editedValue && Math.floor(totalCases) < minimumCases && $currentField.size() == 1) {
		alert('You must order at least 4 cases (4 * 50 bottles). The number of bottles has been increased to fulfill the minimum order size requirements');
		$currentField.val((minimumCases * 50) - (totalBottles - editedValue));
	}
	
	// display numbers
	$subTotal
		.html(itemTotal)
		.format(currencyFormat)
	;
	$shippingTotal
		.html(shippingTotal)
		.format(currencyFormat)
		//.html($shippingTotal.html() + ' <br>($' + shippingCostPerCase + ' per case)')
	;
	$taxTotal
		.html(taxTotal)
		.format(currencyFormat)
	;
	$grandTotal
		.html(taxTotal + itemTotal)
		.format(currencyFormat)
	;	
	
	
	base.saveCart();
	
	
}

base.playMovie = function(id) {
	try {
		$$(id).flashPlay();
	}
	catch(err) {
		// couldnt access function
		console.log(err);
	}
}
base.pauseMovie = function(id) {
	try {
		$$(id).flashPause();
	}
	catch(err) {
		// couldnt access function
		console.log(err);
	}
}

/*
// parses an array of messages and returns html
base.generateErrors = function(messages) {
	if(typeof(messages) != 'undefined') {
		var html = '<h3>'+hbo.error.errorListTitle+'</h3>';
		html += '<ul>';
		$.each(messages, function(i, message){
			html += '	<li>'+message+'</li>';
		});
		html += '</ul>';
		return html;
	}
	return false;
}
*/

/*******************************
 
 		Feedback Functions
	
 *******************************/
base.cleanupFeedbackErrors = function(){ 
	$("#feedbackinfo-one").removeClass("error");
	
	$("#feedbackinfo-one p").html();
	
	$("#feedbackinfo .helper").removeClass("error");
	
	$("#feedbackinfo label").removeClass("error");
	$("#feedbackinfo input").removeClass("error");
	// hate to do it this way but was getting display error otherwise
	$("#feedbackinfo input:not(#submitbutton)").css("background-position","0px 0px");
}

base.validateFeedbackInfo = function(){
		
	returnFalse		= false;
		
	// block 1
	var name	= $('#feedbackinfo #name').val();
	var email 	= $('#feedbackinfo #email').val();			
	var msg 	= $("#feedbackinfo #message").val();
			
			
	// inline error checking
	var errorMessages 	= [];
	var errorFields		= [];
	var errorReport		= "";
	
	if (msg == ""){
		errorMessages.push(base.errors.noMessage);
		errorFields.push("message");
	}
	if (email == ""){
		errorMessages.push(base.errors.noEmail);
		errorFields.push("email");
	} else {
		if (!base.isEmail(email)){
			errorMessages.push(base.errors.invalidEmail);
			errorFields.push("email");
		}
	}
	if (name == ""){
		errorMessages.push(base.errors.generic);
		errorFields.push("name");
	}
	
	// show errors on block 1
	if (errorMessages.length > 0){
		$("#feedbackinfo-one").addClass("error");
		$("#feedbackinfo-one .helper").html("ERROR").addClass("error").css("display","block");
		for (i=0;i<=errorMessages.length-1;i++){
			errorReport	+= errorMessages[i] + "<br />";
			$("#lbl-"+errorFields[i]).addClass("error");
			$("#"+errorFields[i]).addClass("error");
			if (errorFields[i] == "message"){
				$("#"+errorFields[i]).css("background-position","0px -344px");
			} else {
				$("#"+errorFields[i]).css("background-position","0px -68px");
			}
			
		}
		$("#feedbackinfo-one p").html(errorReport);

		returnFalse = true;
			
	}
	if (returnFalse)
	{
		return false;
	} else {
		return true;
	}
}

/*******************************
 
 		News Functions
	
 *******************************/

base.news = {};

base.news.loadNews = function() {
	// set record number to start from
	if(typeof(base.news.startResult) == 'undefined') {
		base.news.startResult = 0;	
	}
	// pull content
	$.ajax({
		type: "GET",
		url: base.newsFeed,
		dataType: "json",
		data: {
			startResult: base.news.startResult	
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			// error handling goes here	
			console.log(XMLHttpRequest, textStatus, errorThrown);
		},
		success: function(data) {
			// set new pointer
			base.startResult = data.startResult;
			
			var html = '<div class="newarticles">';
			// template each item
			$.each(data.articles, function(i, article) {
				// add html
				if(typeof(article.video) != 'undefined') {
					// video template code
					html += base.news.videoTemplate(article);
				}
				else {
					// normal article code
					html += base.news.template(article);							
				}	   
			});
			// add show more button code if more results
			html += base.news.moreTemplate(data.resultsLeft);
			html += '</div>';
			
			var $newsColumn = $('#leftcolumn.news');					
			// add to dom
			$newsColumn.find('.showmore').hide();
			$newsColumn.append(html);
			// activate videos					
			var $newVideos = $newsColumn.find('.newarticles:last-child .newsitem .newsexpanded');
			var $newShowMore = $newsColumn.find('.newarticles:last-child .showmore');
			base.news.activateVideo(data.articles);
			base.news.attachVideoEvents($newVideos);
			// attach new read more button
			$newShowMore.click(base.news.loadNews);
			// reattach events
   			setupZoom();
			// display
			$newsColumn.find('.newarticles').slideDown(2000,'easeOutQuint');
		}
	}); 
	return false;	
}

base.news.template = function(article) {
	console.log(article);
	return ''	+
	'	<div class="newsitem">'	+
	'		<div class="newsimage">'	+
	'			<a href="' + article.image.fullsize + '" rel="shadowbox[feature]"><img src="' + article.image.thumb + '" alt="' + article.image.alt + '"/></a>'	+
	'		</div>'	+
	'		<div class="newscontent">'	+
	'			<h3>' + article.title + '</h3>'	+
	'			<h4>' + article.date + ' &nbsp;|&nbsp; <a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pub=specializedwaterbottles">SHARE THIS</a></h4>'	+
	'			' + article.content	+	''	+
	'		</div>	'	+
	'		<div class="clear"></div>'	+
	'	</div>';
}

base.news.videoTemplate = function(article) {
	console.log(article);
	return ''	+
	'	<div class="newsitem">'	+
	'		<div class="newsexpanded">'	+
	'				<div class="flvvideo">'	+
	'					<div id="video-'+ article.video.id +'"></div>'	+
	'				</div>'	+
	'				<div class="closevideo">'	+
	'					<a href="#"><img src="_media/_images/close-x.png" alt="close-x" width="11" height="11" border="0" /></a>'	+
	'				</div>'	+
	'		</div>'	+
	'		<div class="newsimage">'	+
	'			<a class="expandvideo" href="#"><img src="' + article.image.thumb + '" alt="' + article.image.alt + '" /></a>'	+
	'		</div>'	+
	'		<div class="newscontent">'	+
	'			<h3>' + article.title + '</h3>'	+
	'			<h4>' + article.date + ' &nbsp;|&nbsp; <a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pub=specializedwaterbottles">SHARE THIS</a></h4>'	+
	'			' + article.content	+	''	+
	'		</div>	'	+
	'		<div class="clear"></div>'	+
	'	</div>';	
}

base.news.moreTemplate = function(numberLeft) {
	// limit more to ten at a time
	if(numberLeft > 10) {
		numberLeft = 10;	
	}
	// show more button
	if(numberLeft > 0) {
	return ''	+
		'<div class="showmore">'	+
		'	<a href="#">Show ' + numberLeft + ' more news items...</a>'
		'</div>'	;
	}
	// no more button
	else {
		return '';	
	}
}
base.news.activateVideo = function(articles) {
	// video params stay constant
	var flashParams = {	
		scale: "noscale", 
		bgcolor: "#000000", 
		menu: "false", 
		wmode: "transparent", 
		allowScriptAccess: "always", 
		allowFullScreen: "true" 
	};
	var expressInstall = '_swf/express-install.swf';
	
	// swfobj the videos
	$.each(articles, function(i, article) {
		if(typeof(article.video) != 'undefined') {
			var flashAttributes = {	id: 'movie-'+article.video.id,	name: 'movie-'+article.video.ids };
			var flashVars = { 
				copy_url: '',
				splash: article.video.splash,
				flv_url: article.video.highRes,
				low_res: article.video.lowRes,
				desc: article.video.description,
				autoplay: 'false' 
			};
			swfobject.embedSWF("_swf/flvPlayer.swf", "video-"+article.video.id, "640", "360", base.minimumFlashVersion, expressInstall, flashVars, flashParams, flashAttributes);    
		}
	});	
}

base.news.attachVideoEvents = function($this) {
	// iterate over every video item, attaching events relative to news item
	$this.each(function() {
		// selectors
		var $newsItem = $(this).parents('.newsitem')
		var $article = $newsItem.find('.newscontent');
		var $videoWrapper = $newsItem.find('.newsexpanded');
		var $expand = $newsItem.find('.expandvideo');
		var $close = $newsItem.find('.closevideo'); 
		var $movie = $newsItem.find('.flvvideo object');
		// find object id
		var flvID = $movie.attr('id');			
		// events
		$expand.click(function(){
			// add expand class to news item
			$newsItem.addClass('expand');
			$videoWrapper.animate({ height: '410px' }, 700, 'easeOutQuint', function(){
				// play movie
				base.playMovie(flvID);	
			});			
			return false;
		});
		$close.click(function(){
			base.pauseMovie(flvID);
			$newsItem.removeClass('expand');
			$videoWrapper.animate({ height: '1px'}, 350, 'easeOutQuint');
			return false;
		});
		
	});	
}
