/*

Developed by:

      ___           ___                 
     /__/|         /__/\        ___     
    |  |:|         \  \:\      /  /\    
    |  |:|          \  \:\    /  /:/    
  __|  |:|      _____\__\:\  /__/::\    
 /__/\_|:|____ /__/::::::::\ \__\/\:\__ 
 \  \:\/:::::/ \  \:\~~\~~\/    \  \:\/\
  \  \::/~~~~   \  \:\  ~~~      \__\::/
   \  \:\        \  \:\          /__/:/ 
    \  \:\        \  \:\         \__\/  
     \__\/         \__\/               

*/
/*******************************
        Event Handlers
*******************************/

base.readyEvent = function() {
	
	
	$('a').click(function(){
		var href = $(this).attr('href');
		
		if((href=="#") || (href=="#/")){
			//alert('yes');
			return false;
		}
	});
	
	// what are we dealing with
	base.iPad = base.isiPad();
	base.iPhone = base.isiPhone();
	base.isOldIE = base.isOldIE();
	
	if(base.iPad) $('body').addClass('ipad');
	if(base.iPhone) $('body').addClass('iphone');
	
	
	if($.browser.msie){
		$('body').addClass('ie');
	}
	//version 8
	if($.browser.msie && parseInt($.browser.version, 10) < 9){
		$('body').addClass('oldie');
	}

	
	// os detection
	$.os = {
		name: (base.iPad || base.iPhone) 
			? 'mobileSafari' 
			: (/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase()))[0].replace('sunos', 'solaris')
	};
	
	
	// iDevice specific event ternarys
	base.handleClick = (base.iPad || base.iPhone) 
		? 'touchstart' 
		: 'click'
	;
	base.handleDown = (base.iPad || base.iPhone) 
		? 'touchstart' 
		: 'mousedown'
	;
	base.handleUp = (base.iPad || base.iPhone) 
		? 'touchend'
		: 'mouseup'
	;
	
	base.section = base.findSection();
	
	
	// replce fonts
	Cufon.replace('h2'); // Works without a selector engine
	Cufon.replace('#purist-nav li',{
		hover:true
	});
	Cufon.replace('#container .purist-center h3');
	Cufon.replace('.purist-center h4');
	Cufon.replace('h3.standaloneh3');
	// run the pngFix
	//$(document).pngFix(); 
		
	/*******************************
		     Dropdown Init
	*******************************/
	var $dropdown = $('#centeredcolumn div.dropdown');
	$dropdown.initDropdown({
		shadowOffset: -2				  
	});
	
	var selectedBottleBGOffsetX = -44;
	
	
	if(base.section=="adminPage"){
		
		$("#logininfo input").keypress(function() {
			if(e.which == 13){
			       $('form#logininfo').submit();
			 }
		});
		

	}
	
	// BOTTLES PAGE
	if(base.section == 'bottlesPage') {
		// hide bottle selector initially
		$("div#bottleselector").height('0px');
		
		$("div#bottleselector li").click(function(){
			$("li#bottle1").removeClass('selected');
			$("li#bottle2").removeClass('selected');
			$("li#bottle3").removeClass('selected');
			$("li#bottle4").removeClass('selected');
		});
	 	
		// click handler for browse more div
		$("a#browsemore").click(function(){
			// slideup/slidedown
			// -and-
			// toggle image src
			if($(this).hasClass('down')) {
				$(this).removeClass('down');
				$('img.arrow').attr('src','_media/_images/browsemore-arrow-down.png');
				$("div#bottleselector").animate( { height:0 }, {easing:'easeOutQuint', speed:1000} );
			} else {
				$(this).addClass('down');
				$('img.arrow').attr('src','_media/_images/browsemore-arrow-up.png');
				$("div#bottleselector").animate( { height:'129px' }, {easing:'easeOutQuint', speed:1000} );
			}
			
			return false;
		});
		
		// click handler for first bottle
		$("li#bottle1").click(function(){
			var ULpos = $("li#bottle1").offset();
			var newLeftPosition = ULpos.left + selectedBottleBGOffsetX;
			$("div#bottleselector").css("background-position", newLeftPosition+"px 0px");
			
			$("li#bottle1").addClass('selected');
		});
		
		// click handler for second bottle
		
		$("li#bottle2").click(function(){
			var ULpos = $("li#bottle2").offset();
			var newLeftPosition = ULpos.left + selectedBottleBGOffsetX;
			$("div#bottleselector").css("background-position", newLeftPosition+"px 0px");
			
			$("li#bottle2").addClass('selected');
	
		});
		
		// click handler for third bottle
		
		$("li#bottle3").click(function(){
			var ULpos = $("li#bottle3").offset();
			var newLeftPosition = ULpos.left + selectedBottleBGOffsetX;
			$("div#bottleselector").css("background-position", newLeftPosition+"px 0px");
			
			$("li#bottle3").addClass('selected');
	
		});
		
		// click handler for last bottle
		
		$("li#bottle4").click(function(){
			var ULpos = $("li#bottle4").offset();
			var newLeftPosition = ULpos.left + selectedBottleBGOffsetX;
			$("div#bottleselector").css("background-position", newLeftPosition+"px 0px");
			
			$("li#bottle4").addClass('selected');
	
		});
		
		//set arrow
		var selDIV = $("div#bottleselector li.selected");
		var ULpos = $(selDIV).offset(); 
		
		if(	(ULpos) && typeof(ULpos == 'object')  ) {
			var newLeftPosition = ULpos.left + selectedBottleBGOffsetX;
			$("div#bottleselector").css("background-position", newLeftPosition+"px 0px");
		}
		
		$("div#bottleselector li").click(function(){
			var href = $(this).attr('data-url');
		//	alert(path);
			var base = $('base').attr('href');
			window.location.href = base + href;	
		});
	}
	
	// PURIST PAGE
	if (base.section == 'puristPage'){
		
	}
	
	// BOTTLE BUILDER
	if (base.section == 'builderPage'){
		// highlight form fields on focus - unless they have ERROR class
		$('.fields .textfield').focus(function () {
			if (!$(this).hasClass("error"))
			{					  
         		$(this).addClass("active");
			}
    	});
		$('.fields .textfield').blur(function () {
			if (!$(this).hasClass("error"))
			{
         		$(this).removeClass("active");
			}
    	});
		$('.button')
			.hoverClass()
			.downClass()
			.touchClass()
		;
	
	}
	
	// GALLERY
	if (base.section == 'galleryPage'){
		$("#footerlists .anchor").click(function(){
			$("html:not(:animated), body:not(:animated)").animate({ scrollTop: 0}, 500, 'easeOutQuint');										 
		});
		
		//Get our elements for faster access and set overlay width
	    var div = $('div.sc_menu'),
	                 ul = $('ul.sc_menu'),
	                 // unordered list's left margin
	                 ulPadding = 15;

	    //Get menu width
	    var divWidth = div.width();
	    //Find last image container
	    var lastLi = ul.find('li:last-child');

		if(base.iPad){
			div.css({overflow: 'scroll'});
		}else{
			div.css({overflow: 'hidden'});
		}
		var half = divWidth/2;
	//	alert(half+'--'+divWidth);
	
		$("div.sc_menu").scrollTo('+=1200px', 1750,{easing:'easeOutQuint',onAfter:function(){
			//-----------------------------------
			
			//set new function
			div.mousemove(function(e){
		      //As images are loaded ul width increases,
		      //so we recalculate it each time
		      var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

		      var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
		      div.scrollLeft(left);
		    });
		
			//-----------------------------------
		}});
	}
	
	
	
	//NEWS
	if (base.section == 'newsPage'){
		/*******************************
	         Photo Viewer
		 *******************************/
		
		if($('#rightcolumn .photos').exists()) { 
			
			// Iterate through all slideshows to create relative pager links !IMPORTANT!
			$('#rightcolumn .photos div').each(function() {			
				// No way to relatively define pager reference, so pass in actual DOM element for pager
				var pagerDOM = $(this).next('ul');
				
				$(this).cycle({ 
					fx:     'fade', 
					speed:  800, 
					timeout: 8000, 
					pager:  pagerDOM, 
					pagerAnchorBuilder: function(idx, slide) { 
						return '<li><a href="#">1</a></li>'; 
					} 
				});
			});
			
		}
		
		var $more = $('.showmore');
		var $newsVideo = $('#leftcolumn .newsitem .newsexpanded');
			
		// set more button to loadnews
		$more.click(base.news.loadNews);
		// attach video events to news videos (recalled on ajax load)
		base.news.attachVideoEvents($newsVideo);
		// set zoom icon to click
		if ($(".newsimage .newszoom").exists()){
			$(".newsimage .newszoom").each(function(index) {
				var href = $(this).parent().find("a").attr("href");
				$(this).html("<a href='"+href+"'>Zoom</a>");
		  });
		}
		// setup zoom
		setupZoom();
	}
	
	// FAQ
	if (base.section == 'faqPage'){
		var $deptDropdown = $('#dept .dropdown-choices li a');
		var $sortDropdown = $('#sort .dropdown-choices li a');	
			/*$sortDropdown
				.click(function() {
					var show = $(this).parents("li").attr("id").replace('sort-','');
					if (show == "all"){
						$titleList.show();			 
					} 
					else {		 
						$titleList
							.hide()
							.filter('.'+show)
							.show();
					}
					base.padList($titleList, hbo.titleItemsPerRow);
				}
			);		*/
			$deptDropdown.click(function() {
				var dest = $(this).attr("href");
				var baseURL = $('base').attr("href");
				window.location = baseURL+dest;
				
			});
	}
	
	// ACCOUNTS
	if (base.section == 'accountPage'){
			
	}
	
	// HYDRO ANIMATE IN
	
	if (base.section == 'hydrofloPage'){
		$(".bigbottle").css("opacity","0").delay(500).animate({opacity:1},1000);

	}
	
	// FEEDBACK
	if (base.section == 'feedbackPage'){
		// highlight form fields on focus - unless they have ERROR class
		$('.fields .textfield').focus(function () {
			if (!$(this).hasClass("error"))
			{					  
         		$(this).addClass("active");
			}
    	});
		$('.fields .textfield').blur(function () {
			if (!$(this).hasClass("error"))
			{
         		$(this).removeClass("active");
			}
    	});
		$('.fields .textarea').focus(function () {
			if (!$(this).hasClass("error"))
			{					  
         		$(this).addClass("active");
			}
    	});
		
		$('.fields .textarea').blur(function () {
			if (!$(this).hasClass("error"))
			{
         		$(this).removeClass("active");
			}
    	});
		
		
		// make sure the form validates before it submits
		$("form").submit(function(){
			base.cleanupFeedbackErrors();
			
			if (base.validateFeedbackInfo()){
				return true;
			} else {
				return false;
			}
		});
		
		// make (?) bubbles show their text on the right
		// first function = hover, second func = out
		$("#feedbackPage .formgroup .help").hover(
			
			function(){
				var str 		= $(this).html()
				var chunks		= str.split("|");
				var helpTitle 	= chunks[0];
				var helpText 	= chunks[1];
				var $targ 		= $(this).parents(".formgroup").find(".status");
				
				$targ.find(".helper").html(helpTitle).css("display","block");
				$targ.find("p").html(helpText);
				if ($targ.hasClass("error")){
					$targ.removeClass("error");
				}
			},
			function(){
				var $targ = $(this).parents(".formgroup").find(".status");
				
				$targ.find(".helper").hide();
				$targ.find("p").html("");
			}
		);
	}
	
	
	
	
	// functionality for account details form
	if($("#accountinfo").exists()){
		
		
		
		// make sure the form validates before it submits
		$("form").submit(function(){

			base.cleanupAccountErrors();
			
			if (base.validateAccountInfo()){
				
				return true;
				
			} else {	
				return false;
			}
		});
		
		// make (?) bubbles show their text on the right
		// first function = hover, second func = out
		$("#accountinfo .formgroup .help").hover(
			
			function(){
				var str 		= $(this).html()
				var chunks		= str.split("|");
				var helpTitle 	= chunks[0];
				var helpText 	= chunks[1];
				var $targ 		= $(this).parents(".formgroup").find(".status");
				
				$targ.find(".helper").html(helpTitle).css("display","block");
				$targ.find("p").html(helpText);
				if ($targ.hasClass("error")){
					$targ.removeClass("error");
				}
			},
			function(){
				var $targ = $(this).parents(".formgroup").find(".status");
				
				$targ.find(".helper").hide();
				$targ.find("p").html("");
			}
		);
		
		// Uncheck Same As Billing Info and you get the form field inserted
		$("#billing_as_shipping").click(function(){
			if ($(this).attr("checked")){
				
				$("#shippingForm").slideUp();
				$("#accountinfo-three .helper").removeClass("error").html("").hide();
				$("#accountinfo-three p").html("");
				$("#accountinfo-three").removeClass("error");
			} else {
					
				$("#shippingForm").slideDown();
				
			}
		});
		
	}
	
	
	// any Accounts subpage with a form needs this functionality
	if($("#accountPage").exists()){
		// highlight form fields on focus - unless they have ERROR class
		$('.textfield').focus(function () {
			if ($(this).hasClass("error"))
			{					  
         		$(this).addClass("active");
				$(this).removeClass("error");
			} else {
				$(this).addClass("active");
			}
    	});
		$('.textfield').blur(function () {
			
         		$(this).removeClass("active");
			
    	});
		
		
	
	}
	// any Accounts subpage with a warning div needs this functionality
	if($("#accountPage #userwarning").exists()){
		$("#userwarning a.close").click(
			function()
			{
				// TODO: WRITE A COOKIE TO NOT SHOW THIS AGAIN
				$(this).parent().parent().slideUp();
				return false;
			}
		);
	}
	if ($("#accountPage.saved").exists()){
		$('.button')
			.hoverClass()
			.downClass()
			.touchClass()
		;	
		$('.button.remove').click(function(){
			base.removeSavedBottle($(this).find("a").attr("rel"));
			return false;
		});

	}
	if($("#accountPage.detail").exists()){
		// hovers
		$('.button')
			.hoverClass()
			.downClass()
			.touchClass()
		;
		
		// inline editing START
		$(".editable").live('click',function(){
			$(this).parent().find(".editable").hide();
			$(this).parent().find(".editfields").show().find(".textfield,.textarea").focus();
			return false;
		});
		// inline editing END
		$(".editfields .button.cancel").live('click',function(){
			var targ = $(this).find("a").attr("rel");
			$("#"+targ+"Hold").find(".editable").show();
			$("#"+targ+"Hold").find(".editfields").hide();
			return false;
		});
		
		// inline editing SAVE
		$(".editfields .button.save").live('click',function(){
			var targ = $(this).find("a").attr("rel");
			var newValue = "";
			var id = $("#"+targ+"Hold").data("id");	
			var type = $("#"+targ+"Hold").attr("class");

			base.renameSavedBottle(targ,id,type);
			
			
			return false;
		});
		// inline editing PRESS ENTER
		$("input.textfield.inlinedit").keydown(function(event){
			if (event.keyCode == '13') {
				var targ = $(this).attr("rel").replace("bottle","").toLowerCase();
				var newValue = "";
				var id = $("#"+targ+"Hold").data("id");	
				var type = $("#"+targ+"Hold").attr("class");
				
				base.renameSavedBottle(targ,id,type);
				
			 	event.preventDefault();
		   }
		});
		// REMOVE FILE button (from hi-res listings)
		$("table#file-list a.remove").live('click',function(){
			var id = $(this).attr("rel");
			var ok = confirm("This action can not be undone. Are you sure?");
			if (ok){

				$.getJSON("api/rest/?method=bottles.removeFile&format=json",{file_id: id},
				   function(data) {
						if(data["failed"] == false){
							// DO THIS ON THE CALLBACK ONCE THE METHOD EXISTS
							$("#row"+id).remove();
							// was this the final row?
							
							if ($("table#file-list tbody").children().length == 1){
								$("table#file-list tbody tr#welcome").show();	
							}
						} else {
							alert(base.errorFileDelete);
						}
						
				   });
			}
			return false;
		});
		
		// ADD TO CART BUTTON
		$(".button a.cart").parent().click(function(){
			var bottleID = $(this).find("a").attr("rel");
			
			base.addBottleToCart(bottleID,false);
			
			
			return false;
		});
		
		// APPROVE PDF BUTTON
		$(".button.approve").live('click',function(){
			base.approvePDF($("#bottleID").val());
			return false;
		});
		$(".button.approved").live('click',function(){
			alert(base.alreadyApproved);
			return false;
		});
		$(".button.change").live('click',function(){
			base.openPDFFeedbackModal();
			return false;
		});
		
		
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// BOTTLE DETAIL PAGE VIA ADMIN
		if ($("body").hasClass("admin")){
			
			// inline editing SAVE
			$("#pdfList .editfields .button.addpdf").live('click',function(){
				var targ = $(this).find("a").attr("rel");
				var bottle_id = $("#"+targ+"Hold").data("id");	
				var pdfComment = $("#note"+bottle_id).val();
					
				base.addPDFComment(bottle_id, pdfComment);
				
			
				return false;
			});
			
			// notify user of pdf proof
			$("#notify.button").click(function(){
				var bottleID = $(this).find("a").attr("rel");
				var userID = $("#userID").val();
				
				base.requestPDFApproval(bottleID, userID);
				
				return false;
			});
			
		}
		
			
	}
	
	// functionality for login form
	if($("#logininfo").exists()){
		// make sure the form validates before it submits
		$("form").submit(function(){
			base.cleanupLoginErrors();
			
			if (base.validateLoginInfo()){
				return true;
			} else {
				return false;
			}
		});
	}
	// functionality for retrieve info form
	if($("#retrieveinfo").exists()){
		// make sure the form validates before it submits
		$("form").submit(function(){
			base.cleanupRetrievalErrors();
			
			if (base.validateRetrievalInfo()){
				return true;
			} else {
				return false;
			}
		});
	}
	if($("#resetinfo").exists()){
		// make sure the form validates before it submits
		$("form").submit(function(){
			base.cleanupRetrievalErrors();
			
			if (base.validateResetInfo()){
				return true;
			} else {
				return false;
			}
		});
	}
	// disable account subnav clicks
	if ($("#accountselector.inactive").exists()){
		$("#accountselector.inactive ul li a").click(
			function(){
				return false;
			}
		);												  
	}
	if ($("#submitbutton").exists()){
			$('#submitbutton')
			.hoverClass()
			.downClass()
			.touchClass()
		;
	}
	
	
	// YOUR ARTWORK page
	if ($("ul.biglist").exists()){
		base.padList($("ul.biglist li"), base.artworkItemsPerRow, false);	
		base.heightenList($("ul.biglist li"));	
		
		
		$("ul.biglist li a.remove").click(
			function()
			{
				var confirmDelete = confirm(base.confirmDeleteMessage);
				if (confirmDelete){
					// TODO: NEED TO POST TO A SCRIPT HERE
					// remove listing
					$(this).parent('li').slideUp();
				} 
				return false;
			}
		);
	}
	
	
	// YOUR CART page
	if ($("#accountPage #cartform").exists()){
		$('.button')
			.hoverClass()
			.downClass()
			.touchClass()
		;
		
		
		// BIG REVIEW BUTTON
		$(".button.review a").parent().click(function(){
			var dest = $(this).find("a").attr("href");
			if ($("#amt-est-total").html() == "$0.00"){
				alert(base.addBottlesRequest);
			} else {
				// save the cart one last time
				base.finalizeSave(dest);
				
				//window.location.href=dest;
			}
		
			
			return false;
		});
		// EMPTY CART BUTTON
		$('.button.empty a').parent().click(function(){
			var confirmation = confirm(base.confirmDeleteMessage);
			if (confirmation){
				
				$.getJSON("api/rest/?method=orders.emptyCart&format=json",{},
				function(data){
					if(data["failed"] == false){
						var html = "<tr><td colspan='9'><div class='pagestatus warning'>" + $(".pagestatus").html() + "</div></td></tr>";
						$("#cartform tbody").children().remove();
						
						$("#cartform tbody").append(html);
						$("#cartform tbody .pagestatus").removeClass(".hidden");		
					} else {
						// failed
						alert(base.errorEmptyingCart);
					}
				});
				
			}
			return false;
		});
			
		
		// state tax selector
		/* nixed b/c their script requires state, city and zip
		$('#lbl-tax a')
			.click(function() {
				$('#lbl-tax')
					.find('.message')
						.hide()
						.end()
					.find('select')
						.show()
				;
				return false;
			})
		;
		$('#lbl-tax select')
			.bind('change', function() {
				var $selectedOption = $(this).find('option:selected'),
					selectedState = $selectedOption.html(),
					selectedStateValue = $selectedOption.val()
				;
				$('#lbl-tax')
					.find('select')
						.hide()
						.end()
					.find('.message')
						.find('.state')
							.html(selectedState)
							.end()
						.show()
				;
				// calculate tax rate
				
				// add to form
			})
		;*/
		$('#cartform .configuration')
			.delegate('select.bottle', 'change', function() {
				base.updateCartChoices($(this), base.findBottleCost);
			})
			.delegate('select.image-color, select.cap-type, input.quantity', 'change', function() {
				//base.findBottleCost($(this), $.proxy(base.tallyCart, $(this)));
				base.findBottleCost($(this), $.proxy(base.tallyCart));
			})
			.delegate('select.cap-color', 'change', function() {
				base.saveCart();
			})
		;
		$('#cartform .refresh.cart')
			.bind('click', base.saveCart)
		;
		// NEW remove (per colorway)
		$('#cartform td a.remove')
			.bind('click', function() {
				var $id = $(this).attr('rel'),
					$td = $(this).parents('td'),
					$tr = $td.parents('tr'),
					$rows = $('#cartform table tr'),
					$configID = $td.find(".id").val();
				
				var $firstcell = $("#configRow"+$id).find('td:first-child');
					position = $rows.index($tr),
					numrows = $firstcell.attr('rowspan');
				
				var confirmation = confirm(base.confirmDeleteMessage);
				if (confirmation){
					// need to do multiple checks
					// are there multiple styles for this bottle?
					if (numrows > 1){
						// is this the first row being removed?
						if ($tr.hasClass("first")){
							// first style in series
							// bit of trickery.. we remove the first cell, insert it into the next row
							var $nextRow = $('#cartform table tr').eq(position+1);
							$nextRow.prepend($firstcell).attr("id","configRow"+$id).addClass("first");
							$firstcell.attr('rowspan',numrows-1);
							$tr.remove();
							
						} else {
							// second style in series	
							$firstcell.attr('rowspan',numrows-1);
							$tr.remove();
						}
					} else {
						// singular row for this style
						// kill the row with the pertinent data AND the "add more styles" row
						$rows.each(function(i){
							if ($(this).attr("rel") == $id){
								$(this).remove();
							}
						});
						
					}
					
					// need to check again to see if the tbody is now empty.. if so, show user an empty cart message
					if($("#cartform tbody tr").length < 1){
						var html = "<tr><td colspan='9'><div class='pagestatus warning'>" + $(".pagestatus").html() + "</div></td></tr>";
						$("#cartform tbody").append(html);
						$("#cartform tbody .pagestatus").removeClass(".hidden");
					}
					
					// save it
					base.removeBottleFromCart($configID);
				} // end if
				return false;
			})
		;
		
		/*
		// old remove
		$('#cartform a.remove')
			.bind('click', function() {
				var $header = $(this).parents('td'),
					$firstRow = $header.parents('tr'),
					$rows = $('#cartform table tr'),
					startPosition = $rows.index($firstRow),
					endPosition = startPosition + $header.attr('rowspan') + 1
				;
				var confirmation = confirm(base.confirmDeleteMessage);	
				if (confirmation){
					$rows
						.slice(startPosition, endPosition)
							.remove()
					;
				}
				return false;
			})
		;
		*/
		$('td.addmore a.addit')
			.bind('click', function() {
				var $id = $(this).attr("rel");
				// need to tell the database to add this row
				base.addColorway($id, $("#order-id").val());
				
				/*var	$link = $(this),
					$form = $(this).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(0)
						.end()
					.insertAfter($lastRow)
				;
				$labelRow.attr('rowspan', numberConfigurations+1);
				$form.data('added', numberAdded + 1);*/
				
				return false;
			})
		;
		
		
		
		// inline editing START
		$(".editable").live('click',function(){
			$(this).parent().find(".editable").hide();
			$(this).parent().find(".editfields").show().find(".textfield").focus();
			return false;
		});
		// inline editing END
		$(".editfields .button.cancel").live('click',function(){
			var targ = $(this).find("a").attr("rel");
			$("#"+targ+"Hold").find(".editable").show();
			$("#"+targ+"Hold").find(".editfields").hide();
			return false;
		});
		
		// inline editing SAVE
		$(".editfields .button.save").live('click',function(){
			var targ = $(this).find("a").attr("rel");
			var newValue = "";
			var id = $("#"+targ+"Hold").data("id");	
			var type = $("#"+targ+"Hold").attr("class");

			base.renameCartOrder(targ,id,type);
			
			
			return false;
		});
		// inline editing PRESS ENTER
		$("input.textfield.inlinedit").keydown(function(event){
			if (event.keyCode == '13') {
				var targ = $(this).attr("rel").replace("bottle","").toLowerCase();
				var newValue = "";
				var id = $("#"+targ+"Hold").data("id");	
				var type = $("#"+targ+"Hold").attr("class");
				
				base.renameCartOrder(targ,id,type);
				
			 	event.preventDefault();
		   }
		});
		
		$("div.finalize").click(function(){
			base.finalizeOrder();
			return false;
		});
		
		$("div.completed").click(function(){
			base.adminCompleteOrder();
			return false;
		});
		
		
		$("tr.bordered .button.add").click(function(){
			//alert("Under Construction");
			
			base.openBottleAddModal();
			
			return false;
		});
		$(".modal.addbottles li a").click(function(){
			var bottleID = $(this).attr("rel");
			base.addBottleToCart(bottleID, true);
			
			
			return false;
		});
		
		base.tallyCart();
		
	
		
		$("#cartform div.title input.change").change(function(){
			var bottleID = $(this).attr("rel");
			var newTitle = $(this).val();
			base.quickBottleRename(bottleID, newTitle);
		
		});
		// FILE UNDER button for admin page
		$(".ordersort .button").click(function(){
			$orderStatus = $("#file-under option:selected").val();
			$orderID = $(this).find("a").attr("rel");
			
			base.updateOrderStatus($orderStatus, $orderID);
			
			return false;
		});
		
		
	}
	
	
	
	//
	
	
	// ADMIN PAGES
	if (base.section == 'ordersPage'){
		$('.button')
			.hoverClass()
			.downClass()
			.touchClass()
			.click(function(){
				var dest = $(this).find("a").attr("href");
				window.location.href =  dest;
		});
	}	
	
}; 

$(document).ready(base.readyEvent);
if(!($.browser.msie)){
	document.addEventListener("touchstart", function() {},false);
}

