var currentCartPage = 0;

$(document).ready(function() {
	
	initCart(1);
	
	//Save a change to 'My Default Location', probably re-display the map as well, should the map have 'nearby communities' and link to them?
	$(".loc-save").click(function(){
		var newLoc = $("#myLocation").val();
		alert("Currently non-functional");
		//we probably need to geocode/google the provided text, then turn it into state/city/etc for saving
		//$.post('/ajax/aptcart/editinfo.php', {});
	});
	
	//Save a change to the First/Last name of this user
	$(".name-save").click(function(){
		var newFirst = $("#firstName").val();
		var newLast = $("#lastName").val();
		$.post('/ajax/aptcart/editinfo.php', {'firstName':newFirst,'lastName':newLast}, function(data){ 
			alert(data);
		});
	
		return false;
	});
	
	//Save a change to the password for this user
	$(".changepass-save").click(function(){
		var changepass_old = $("#changepass_old").val();
		var changepass_new = $("#changepass_new").val();
		var changepass_new2 = $("#changepass_new2").val();
		var email = $("#email").val();
		$.post('/ajax/aptcart/editinfo.php', {'changepass_old':changepass_old,'changepass_new':changepass_new,'changepass_new2':changepass_new2, 'pass_email':email}, function(data){ 
			alert(data);
		});
	
		return false;
	});
	
	//Save a change to their contact information/preferences
	$(".contact-save").click(function(){
		var newEmail = $("#email").val();
		var newPhone = $("#phone").val();
		var newPref = $("input[name=prefcontact]:checked").val();
		var newTime = $("#updatefreq option:selected").val();

		$.post('/ajax/aptcart/editinfo.php', {'email':newEmail,'phone':newPhone,'prefcontact':newPref,'updatefreq':newTime }, function(data){ 
			alert(data);
		});
		
		return false;
	});
	
	//Checkbox clicks to show or hide the inline 'Sign Up!' form bits
	$("#show-signup").click(function(){
		$("#hide-signup").toggle();	
	});
	
	$("div.clear_history").click(function() {
		var remID=[];
		$("li.unit-container").each(function() {
			remID.push($(this).attr("id"));
		});
		$.get('/ajax/aptcart/delete.php', {'item[]':remID, 'type':'history'});
		
	});

	//form validation for the last step of AptCart
	$("#sendcartform").keydown(function(){
	}).validate({ 
		     rules: { 
			 firstName: "required", 
			 lastName: "required", 
			 register_user: { 
			     required: false, 
			     minlength: 2,
			     remote: "/ajax/usercheck.php" 
			 }, 
			 register_pass: { 
			     required: false, 
			     minlength: 5 
			 }, 
			 register_passagain: { 
			     required: false, 
			     minlength: 5, 
			     equalTo: "#register_pass" 
			 }, 
			 email: { 
			     //required: true, 
			     email: true
			     //remote: "/ajax/usercheck.php" 
			 }, 
			 phone: {
			     //required: false,
			     minlength: 7
			 },
			 keystring: {
			     required: true,
			     remote: "/ajax/usercheck.php"
			 },
			 terms: "required" 
		     }, 
		     onkeyup: false,		
		     messages: { 
			 firstName: "Enter your first name.", 
			 lastName: "Enter your last name.", 
			 register_user: { 
			     required: "Enter a username", 
			     minlength: jQuery.format("Enter at least {0} characters"), 
			     remote: jQuery.format("Username is already in use") 
			 }, 
			 password: { 
			     required: "Provide a password", 
			     rangelength: jQuery.format("Enter at least {0} characters") 
			 }, 
			 phone: {
			     minlength: "Please enter a valid phone number."
			 },
			 keystring: {
			     required: "Please enter a verification code.",
			     remote: "Please enter the correct code."
			 },
			 register_passagain: { 
			     required: "Repeat your password", 
			     minlength: jQuery.format("Enter at least {0} characters"), 
			     equalTo: "Enter the same password as above" 
			 }, 
			 email: { 
			     required: "Please enter a valid email address", 
			     minlength: "Please enter a valid email address", 
			     remote: jQuery.format("Email Address is already in use") 
			 }, 
			 terms: " " 
		     },
			     success: function(label) {
				     // set &nbsp; as text for IE
				     label.html("&nbsp;").addClass("checked");
			     }
	     
		     });
		 
			$("input").change(function() {
			switch($("input[@name='prefcontact']:checked").val()) {
				case 'email':
					$("#email").addClass('required email');
					$("#phone").removeClass('required phone');
				break;
				case 'phone':
					$("#phone").addClass('required phone');
					$("#email").removeClass('required email');
				break;
				case 'both':
					$("#email").addClass('required email');
					$("#phone").addClass('required phone');
				break;
			}
	    
			});
		
	
	
	// set up my location map
	
	if (typeof(myLocation) == 'object') {
		map = new GMap2(document.getElementById("location_map"));
		var lat = parseFloat(myLocation[0]);
		var lng = parseFloat(myLocation[1]);
		map.setCenter(new GLatLng(lat,lng),12);
	}
});

function hideCalendar() {
	$("div.calendar-holder").hide();
	$(document).unbind('click', hideCalendar);
}

// update the "In Your Cart" section
function updateCartSummary() {
	var commCount = $(".unit-container:not(.community)").length;
	var flooorplanCount = $(".unit-container.community").length;
	var unitCount = $("ul.specific-units li").length;
	
	$("#count_comm").text(commCount);
	$("#count_fp").text(floorplanCount);
	$("#count_unit").text(unitCount);	
}

function clickCartPage(page) {
	currentCartPage = page;
	$.get('/ajax/aptcart/view.php', {pg: page+1}, function(data) {
		$("div.aptcart-tab-area").html(data);
		initCart(page+1);
	});
}

function initCart(curPage) {
	
	var numItems = currentItemCount['c'];
	
	var pageOptions = {click: clickCartPage, initialPage: curPage, numItems: numItems, textButtons: false, ajaxLoad: true};
	
	$(".aptcart-pager ul").paginate(pageOptions);
	
	
	//the appointment date calendar, displayed inline, but hidden - popup just displays its container
	$('div.calendar-box').datePicker({inline:true,selectMultiple:true});
	
	for (var comm in appointmentDates) {
		var calObj = $("#" + comm + " div.calendar-box");
		for (var d in appointmentDates[comm]) {
			calObj.dpSetSelected(appointmentDates[comm][d], true, false);
		}
	}
	
	$("textarea.ghost-text").click(function() {
		$(this).removeClass('ghost-text').val('').unbind('click');
	});
	
	//saves the calendar/message information from the 'popup' into the Cart session variable via add.php
	$("input.saveDate").click(function(){
		var parent = $(this).parent();
		var commID = parent.find("textarea").attr("id");
		var apptDates = parent.find(".calendar-box").dpGetSelected();
		var apptNotes = parent.find("textarea").val();
		
		var dateObj;
		var month;
		var day;
		var strApptDates = [];
		
		for (var d in apptDates) {
			dateObj = new Date(apptDates[d]);
			month = dateObj.getMonth() + 1;
			day = dateObj.getDate();
			if (month < 10) month = '0' + month;
			if (day < 10) day = '0' + day;
			strApptDates[d] = dateObj.getFullYear() + '-' + month + '-' + day;
		}
		if (!strApptDates.length) {
			strApptDates.push('remove');
			var dateText = 'No Date Set (click here)';
		} else {
			var dateText = 'Date Set (click to view)';
		}
		
		$.post('/ajax/aptcart/add.php', {'msg[]': apptNotes,'apptdate[]': strApptDates, 'id[]': commID});
		
		$("#" + commID).find("div.date-set a").text(dateText);
		
		$("div.calendar-holder").hide();
		return false;
	});
	
	//the close button on the 'popup' for the calendar
	$("div.close-button a").click(function(){
		$("div.calendar-holder").hide();
		return false;
	});
	
	//the text/icon 'Appointment Date' on the AptCart view
	$("div.appointment-date").click(function(){
		$(this).children("div.calendar-holder").show();
		$(document).click(hideCalendar);
		return false;
	});
	
	//Check: All
	$("a.checkAll").click(function(){
		$(".input-checkbox").attr("checked",true);
		var thisPage = $(this).prev().attr("id"); //the span with 'Select', its ID set to the current page # (parent could be easier)
		//this each loop doesn't work yet, could use the c-# or f-#,u-# for ^= selectors
		//would be more optimal(?) to use the below input-checkbox function?
			$.each($(this).children("li"), function(){
				alert( this.tagName );
			});
		//TODO - clear this page's communities out of 'notsend'
	});
	
	//Check: None
	$("a.checkNone").click(function(){
		$(".input-checkbox").attr("checked",false);
		var thisPage = "pg"+$(this).prev().prev().attr("id"); //the span with 'Select', its ID set to the current page #
		$.each($(this).children("li"), function(){
			alert( this.tagName );
		});
	});
	
	//A single-click on any of the checkboxes in the AptCart, sets children to same checked state, and modifies 'notsend' session array
	$("input.input-checkbox").click(function(){
		var parentType = $(this).parent().attr("id").substr(0,1);
		var act = '';
		thisID = $(this).parent().attr("id");
		var chngTo = this.checked;
		var addList = '';
		var remList = '';
		switch(parentType){
			case 'c': //community
				//add-remove the community from the list
				if(this.checked == true){
					remList  = remList + thisID+"|";
				} else {
					addList = addList + thisID+"|";
				}
				//add-remove the floorplans from the list
				$.each($(this).parent().siblings().children(), function(){
					if(this.tagName == "INPUT"){
						var fID = $(this).parent().attr("id");
						this.checked = chngTo;
						if(this.checked == true){
							remList  = remList + fID+"|";
						} else {
							addList = addList + fID+"|";
						}
					}
				});
				//add-remove the units from the list
				$.each($(this).parent().siblings().children("ul").children().children(), function(){
					if(this.tagName == "INPUT"){
						var uID = $(this).parent().attr("id");
						this.checked = chngTo; 
						if(this.checked == true){ remList  = remList + uID+"|"; } else { addList = addList + uID+"|"; }
					}
				});
			break;
			case 'f': //floorplan
				//add-remove the floorplan from the list
				if(this.checked == true){ remList  = remList + thisID+"|"; } else { addList = addList + thisID+"|"; }
				//add-remove the units from the list
				$.each($(this).parent().children("ul").children().children(), function(){
					var uID = $(this).parent("li").attr("id");
					if(this.tagName == "INPUT"){
						this.checked = chngTo;
						if(this.checked == true){
							remList  = remList + uID+"|";
						} else {
							addList = addList + uID+"|";
						}					
					}
				});
			break;
			case 'u': //unit
					//add-remove the unit from the list
					var uID = $(this).parent().attr("id"); 
					if(this.checked == true){ remList  = remList + uID+"|"; } else { addList = addList + uID+"|"; }
			break;
		}
		/*
		if( addList.length > 2){ //if the 'addList' isn't empty, we send it - otherwise 'remList'
		$.get('/ajax/aptcart/tosend.php', {'change':addList,'do':'a'});
		} else {
		$.get('/ajax/aptcart/tosend.php', {'change':remList,'do':'d'});
		}
		*/
		return false;
	});
	
	//REMOVE: Floorplan or Unit, different nesting of items - different 'children' relations than Comm, from Cart entirely
	$("a.remove").click(function(){
		var container = $(this).parents("li.unit-container");
		var remID = container.attr("id");
		
		container.slideUp();

		//ajax call to remove item		
		if($(this).hasClass("hist")){
			$.get('/ajax/aptcart/delete.php', {'item[]':remID, 'type':'history'});
		} else {
			$.get('/ajax/aptcart/delete.php', {'item[]':remID}, function(data){
				currentItemCount = data;
				$(".numCartItems").text(data['t']);
				$("span.cartItems").text('My AptCart (' + data['t'] + ')');
				clickCartPage(currentCartPage);
			}, 'json');
		}
		return false;
	});
	
	//REMOVE: Community only, from cart
	$("a.c-remove").click(function(){
		var container = $(this).parents("li.unit-container");
		
		var remID = container.attr("id");
		
		container.siblings().hide();	// remove shadow
		container.slideUp();
		
		//ajax call to remove item
		if($(this).hasClass("hist")){
			$.get('/ajax/aptcart/delete.php', {'item[]':remID, 'type':'history'}, function(data) {
				currentCartItems = data;
				$("#count_comm").text($("#count_comm").text() - 1);
			});
		} else {
			$.get('/ajax/aptcart/delete.php', {'item[]':remID}, function(data){
				currentItemCount = data;
				$("#count_comm").text($("#count_comm").text() - 1);
				$(".numCartItems").text(data['t']);
				$("span.cartItems").text('My AptCart (' + data['t'] + ')');
				if (data['t'] == '0') {
					$("div.button-aptcart").hide();	// hide checkout button if no items	
				}
				if ($("a.c-remove").length == 1 && currentCartPage) currentCartPage--;		// go to previous page if deleting the only community
				currentItemCount(currentCartPage);
				
			}, 'json');
		}
		return false;
	});

	//the link-button on the last step of AptCart, need to test this out yet
	$("a.cartbutton").click(function(){
		$("#sendcartform").get(0).submit();
		return false;
	});
}

