/**********************************************************
* TFE MODULE
* Package : TFE_WRITENOTE
* Version: 1.0
* Dependcies: JQuery, Flowplayer:tools
* copyright 2009 Derek Lee Bronston/theConspiracy
* Author : Derek Lee Bronston dereklee@theconspiracy5.com
***********************************************************/

var TFE_WRITENOTE = {
	
	revertObject:'',
	outlookObject :'',
	contactRemove:new Array(),
	thankNow:new Array(),
	excelData: '',
	macData: '',
	thankGroup:new Array(),
	extraGifts:new Array(),
	
	/**
	* This method Passing the event type selection via ajax to the system
	*
	*/
	SelectEventType:function()
	{
		$(document).ready(function(){
			//alert('1');
			//clear any residual data from date pick
			$("#post_date").html('');
			var eventType = $("#event_type").val();
			//$("#datepicker_"+eventType).val('');
			var eventTypes = new Array();
			eventTypes[0] = 'tfebaby';
			eventTypes[1] = 'tfewedding';
			eventTypes[2] = 'tfebridal';
			for(i=0;i<eventTypes.length;i++)
			{
				if(eventTypes[i] == $("#event_type").val())
				{
					$("#event_questions_"+$("#event_type").val()).show('slow');
				}
				else
				{
					$("#event_questions_"+eventTypes[i]).hide();
				}
			}
			$("#datepicker_"+$("#event_type").val()).datepicker({
				width: '300',
				//dateFormat: 'MM d, yy',
				//altFormat: 'yy-mm-dd',
				onSelect: function(dateText, inst) { 
					var oldDate = dateText.split('/');
					var newDate = oldDate[0]+'-'+oldDate[1]+'-'+oldDate[2];
			 		TFE_WRITENOTE.GetEventProfileQuestions(newDate,$("#event_type").val());
				}
			});
		});
		
		return true;
	},
	
	/**
	* This method will communicate with controller 
	* to get the question for the data
	*
	*/
	GetEventProfileQuestions:function(theDate,eventType)
	{
		var updateDiv = 'post_date';
		$.get('/writenote/stepone/eventprofilequestionspostdate/'+theDate+'/'+eventType+'/1',function(returned_data){
			$("#"+updateDiv).html(returned_data,function(data){
			});
		});
		return true;
	},
	
	GetEventProfileQuestionsRedo:function(theDate,eventType)
	{
		var updateDiv = 'post_date';
		$.get('/writenote/stepone/eventprofilequestionspostdate/'+theDate+'/'+eventType+'/0',function(returned_data){
			$("#"+updateDiv).html(returned_data,function(data){
			});
		});
		return true;
	},
	
	

	/**
	* This method handles the selection of design elements, send data to PHP controller for processing
	*
	* @param JSON OBJECT, ElementType, Name, ID
	*/
	SelectDesignElements:function(elemType,elemId)
	{
		//alert(elemType+' - '+elemId);
		if ($("#" + elemType).val() != '') {
			$.get('/writenote/stepone/selectdesignelement/' + elemType + '/' + elemId, function(returned_data){
				//alert(returned_data);
				$("#" + elemType + "_done").attr({
					src: "images/MAIL_THANK_NOW_ON.gif"
				});
			});
		}
		else//unset the display
		{
			$.get('/writenote/stepone/unselectdesignelement/' + elemType, function(returned_data){
				$("#" + elemType + "_done").attr({
					src: "images/MAIL_THANK_NOW_OFF.gif"
				});
			});
		}
	},
	
	
	ShowSample:function(div,im)
	{
		////$("#sample_image").html('');
		$('#'+div).toggle("fast",function callback() {
			if(im!='false')
			{
				$("#sample_image").html('<table width="600" height="480"><tr><td align="center" valign="middle"><img src="../../images/ajax-loader.gif"/></td></tr></table>');
				$.get('/writenote/steptwo/sampleimage/'+im,function(data){
					$("#sample_image").html(data);
				});
			}
		});
	},
	
	ShowScreen:function()
	{
		$("a[rel]").overlay({
			expose: 'white',
			effect: 'apple',
			onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getContent().find("div.wrap");

				// load only for the first time it is opened
				//if (wrap.is(":empty")) {
				wrap.load(this.getTrigger().attr("href"));
				//}
			}
		});
	},
	
	CheckDesignChoices:function(isLoggedIn){
		var url = '/writenote/steptwo/recipients/import';
		$.get('/writenote/stepone/DesignIsChosen',function(returned_data){
			if(returned_data == 'true')
			{
				window.location = url;
			}
			else
			{
				alert('Sorry you need to complete making your design choices before you can move on.');
			}
		});
	},
	
	ExcelHelper:function()
	{
		alert('excel');
		TFE_WRITENOTE.SubmitPostData('excel_helper');
		//alert()
	},
	
	SubmitPostData:function(formName)
	{
		$(document).ready(function() 
		{ 	//SUBMIT POST DATA
      	 	$("#"+formName).ajaxSubmit(function(success) 
      	 	{ 	//CLEAR FORM 
          		$('#'+formName).clearForm();
          		return true;
          		//UPDDATE SUBVIEW
               // TFE_BABY.GetSubView(updateDiv);
            }); 
       }); 
	},
	
	/**
	* Method handles detecing whether the user currently hasa session started and redirects to the appropriate place
	*
	*
	**/
	SessionExists:function()
	{
		$.get('/writenote/stepone/sessionexists',function(returned_data){
			window.location = '/writenote/stepone/clearnote';
		});
	},
	
	Autocomplete:function(phpData,div)
	{	
		//alert(1);
		$(document).ready(function(){
			var dataText = '';
			for(i=0;i<phpData.length;i++)
			{
				dataText  += phpData[i].text+',';
			}
   			var data = dataText.split(",");
			$("#"+div).autocomplete(data);
  		});
	},
	
	OrderFormCheck:function()
	{
		//console.log('hello'); return false;
		var isValid = true;
		var coupon = false;
		var hasCC = true;
		//CHECK FOR COUPON
		if($('#promo_code').val() != '')
		{
			coupon = true;
		}
		
		if($('#billing_firstname').val() == '')
		{
			isValid = false;
		}
		if($('#billing_lastname').val() == '')
		{
			isValid = false;
		}
		if($('#billing_address').val() == '')
		{
			isValid = false;
		}
		if($('#billing_city').val() == '')
		{
			isValid = false;
		}
		if($('#billing_state').val() == '')
		{
			isValid = false;
		}
		if($('#billing_postal').val() == '')
		{
			isValid = false;
		}
		
		if($('#terms').val() == '')
		{
			isValid = false;
		}

		if(!coupon)
		{
			if($('#card_num').val() == '')
			{
				isValid = false;
				hasCC = false;
			}
			
			var reg = new RegExp(" ");
			if (reg.test($('#card_num').val())) {
				isValid = false;
				hasCC = false;
			}
			if ($('#cc_exp_month').val() == '') {
				isValid = false;
				hasCC = false;
			}
			if ($('#cc_exp_year').val() == '') {
				isValid = false;
				hasCC = false;
			}
			if ($('#cc_security').val() == '') {
				isValid = false;
				hasCC = false;
			}
		}
		if(!isValid)
		{
			alert('Please complete the order form, you must agree to the terms of use. NOTE your credit card number CANNOT CONTAIN SPACES OR DASHES!');
		} 
		else
		{	
			if(!$('#shipping').attr('checked'))
			{	
				var api = $("div.overlay").overlay({
					oneInstance: false, 
					api: true,
					expose: 'white',
					effect: 'apple',
					top: '1%',
					onBeforeLoad: function() 
					{ 
						var wrap = this.getContent().find("div.wrap"); 
                		wrap.load('/writenote/stepthree/shippingaddressform');  
           	 		},
            		onClose:function()
            		{
            	
					}
				}); 
				api.load(); 
			}
			else
			{
				$('#shipping_firstname').val($('#billing_firstname').val());
				$('#shipping_lastname').val($('#billing_lastname').val());
				$('#shipping_address').val($('#billing_address').val());
				$('#shipping_address2').val($('#billing_address2').val());
				$('#shipping_city').val($('#billing_city').val());
				$('#shipping_state').val($('#billing_state').val());
				$('#shipping_country').val($('#billing_country').val());
				$('#shipping_postal').val($('#billing_postal').val());
				
				//CHECK FOR PROMO
				if($('#promo_code').val() != '')
				{
					var pcode = $('#promo_code').val();
					$.post('/writenote/stepthree/check_promo_code',{"promo_code":pcode},function(data){
						if(data > 0)
						{
							
							if($('#card_num').val() == '')
							{
								isValid = false;
								hasCC = false;
							}
			
							var reg = new RegExp(" ");
							if (reg.test($('#card_num').val())) {
								isValid = false;
								hasCC = false;
							}
							if ($('#cc_exp_month').val() == '') {
								isValid = false;
								hasCC = false;
							}
							if ($('#cc_exp_year').val() == '') {
								isValid = false;
								hasCC = false;
							}
							if ($('#cc_security').val() == '') {
								isValid = false;
								hasCC = false;
							}
							
							
							if(data == 2 && !hasCC)
							{
								alert('Please complete the order form, you must agree to the terms of use. NOTE your credit card number CANNOT CONTAIN SPACES OR DASHES!');
							}
							else
							{
								document.tfeorder.submit();
							}
						}
						else
						{
							alert('Please check your promo code there appears to be an error.');
						}
					});
				}
				else
				{
					document.tfeorder.submit();	
				}
			}
		}
	},
	
	/**
	* This method handles deleting a recipient from an order
	* @params in recipientId
	**/
	DeleteRecipient:function(recipientId)
	{
		//alert(recipientId);
		var conf = confirm('?Are you sure you want to delete this recipient, you cannot undo this');
		if(conf)
		{
			$.get('/writenote/steptwo/deleterecipient/'+recipientId,function(returned_data){
				$('#r-'+recipientId).toggle("slow",function callback() {
					$('#r-'+recipientId).remove();
				});
			});
		}
	},
	
	EditRecipient:function(recipientId)
	{
		$("#rec_title").html("Edit Recipient");
		//CLEAR RESIDUAL DATA 
		//$("#first_name").val('');
		//$("#last_name").val('');
		$("#full_name").val('');
		//$("#address").val('');
		$("#full_address").val('');
		//$("#address2").val('');
		//$("#city").val('');
		//$("#state").val('');
		//$("#country").val('');
		//$("#postal").val('');
		$("#id").val('');
		
		//SHOW EDIT TABLES
		$('#recipient').toggle("fast",function callback() {
			//ONLY GET DATA ON THE BLOCK DISPLAY 
			if(document.getElementById('recipient').style.display == 'block'){
				//LOADER
				document.getElementById('loader').innerHTML = '<img src="../../images/ajax-loader-horizontal.gif"/>';
				//GET DATA
				$.getJSON('/writenote/steptwo/editrecipient/'+recipientId,function(returned_data){
					//EXIT LOADER
					$("#loader").html('')
					//DISPLAY DATA IN FORM
					//$("#first_name").val(returned_data.first_name);
					//$("#last_name").val(returned_data.last_name);
					$("#full_name").val(returned_data.full_name);
					//$("#address").val(returned_data.address);
					$("#full_address").val(returned_data.full_address);
					//$("#address2").val(returned_data.address2);
					//$("#city").val(returned_data.city);
					//$("#state").val(returned_data.state);
					//$("#country").val(returned_data.country);
					//$("#postal").val(returned_data.postal);
					$("#id").val(returned_data.id);
				});
			}
		});
	},
	
	ModifyRecipient:function()
	{
		//MAKE SURE THIS IS NOT AN ADD
		if($("#id").val()!='')
		{
			$(document).ready(function(){
      	 		dataString = $("#edit_me").serialize();
				$.ajax({
					type: "POST",
					url: "/writenote/steptwo/modifyrecipient",
					data: dataString,
					dataType: "json",
					success: function(data) {
						alert('here');
						$("#id").val('');
            		} 
       			}); 
       			$('#recipient').toggle("slow");
	       	}); 
		}
		else // ADD NEW
		{
			var error = false;
			// ERROR CHECK 
			if($("#full_address").val() == '' && $("#delivery_type").val()!=3)
			{
				alert('Sorry you must include the recipient\'s address');
				error = true;
			}
			if(!error)
			{
      	 		dataString = $("#edit_me").serialize();
      	 		$.ajax({
				type: "POST",
				url: "/writenote/steptwo/importcontact",
				data: dataString,
				dataType: "post",
            	success:function(data)
            	{
            		$("#recipient").hide('fast');
            		$.get('/writenote/steptwo/append_recipients_table/'+data,function(data){
            			$("#additional_recipients").html(data);
            		})
            	}
			});
			}
		}
	},
	
	ModifyAllRecipients:function()
	{
		dataString = $("#recipientstable").serialize();
      	$.ajax({
			type: "POST",
			url: "/writenote/steptwo/editrecipients",
			data: dataString,
			dataType: "post",
            success:function(data)
            {
 				//alert('Update is complete');
 				//location.reload();
 				//document.confirm_order.submit();
 				$("#update_order").submit();
            }
		});
	},
	
	AddRecipient:function()
	{
		//alert($("#recipient").attr('display'));
		//CLEAR FORM
		$("#first_name").val('');
		$("#last_name").val('');
		$("#full_name").val('');
		$("#address").val('');
		$("#full_address").val('');
		$("#address2").val('');
		$("#city").val('');
		$("#state").val('');
		$("#country").val('');
		$("#postal").val('');
		$("#id").val('');
		$("#rec_title").html("Add Recipient");
		if(document.getElementById('recipient').style.display == 'none'){
			$('#recipient').show("fast",function callback() {
			});
		}
	},
	
	RecipientSample:function(recipientId)
	{
		$('#sample').toggle("slow");
	},
	
	RevertRecipient:function(recipientId,reciepientIndiceId)
	{
		//alert(reciepientIndiceId);
		//SHORTEN FORM DEFINITION FOR EASY ACCESS LATER
		var theForm = document.recipientstable;
		
		//LOOP THROUGH STORED OBJECT
		for(i=0;i<TFE_WRITENOTE.revertObject.length;i++)
		{
			//ISOLATE THE ARRAY BASED ON MATHCING RECIPIENT ID's
			//alert()
			if(recipientId == TFE_WRITENOTE.revertObject[i].id)
			{	
				/*
				LOOP THROUGH EDIT FORM TO GET ELEMENTS, 
				THIS MIGHT SEEM A BIT COMPLICATED BUT THE FORM ELEMENTS 
				ARE SET UP LIKE first_name[] etc.. 
				AND JAVASCRIPT DOESN'T LIKE ACCESSING AND 
				RESETTING THE FORM ELEMS WITH [] IN THE NAME
				*/
				var counter = 0;
				for(z=0;z<theForm.elements.length;z++)
				{
					if(counter == i)
					{
						switch(theForm.elements[z].name)
						{
							case 'salutation[]':
								if(TFE_WRITENOTE.revertObject[i].salutation=="")
								{
									theForm.elements[z].value = "Dear";
								}
								else
								{
									theForm.elements[z].value = TFE_WRITENOTE.revertObject[i].salutation;
								}
							break;
							
							case 'display_name[]':
							theForm.elements[z].value = TFE_WRITENOTE.revertObject[i].display_name;
							break;
							
							case 'gift[]':
							theForm.elements[z].value = TFE_WRITENOTE.revertObject[i].gift;
							break;
							
							case 'relationship[]':
							theForm.elements[z].value = TFE_WRITENOTE.revertObject[i].relationship;
							break;
							
							case 'valediction[]':
								if(TFE_WRITENOTE.revertObject[i].valediction == '')
								{
									theForm.elements[z].value  = "Love";
								}
								else
								{
									theForm.elements[z].value = TFE_WRITENOTE.revertObject[i].valediction;	
								}
							break;
						}
					}
					
					//INCREMENT COUNTER
					if(theForm.elements[z].name == 'id[]')
					{
						counter++;
					}
				}
			}
		}
	},
	
	SetRevertObject:function(revertObj)
	{
		//alert(revertObj);
		TFE_WRITENOTE.revertObject = revertObj;
	},
	
	ImportGmail:function()
	{
		$(document).ready(function(){
      	 	dataString = $("#gmail_form").serialize();
			$.ajax({
				type: "POST",
				url: "/external_lib/gmail.php",
				data: dataString,
				dataType: "json",
				beforeSend: function() {
					var api = $("div.overlay").overlay({
						oneInstance: false, 
						api: true,
						expose: 'white',
						effect: 'apple',
						top: '1%',
						onBeforeLoad: function() 
						{ 
							var wrap = this.getContent().find("div.wrap"); 
                			wrap.load('/writenote/steptwo/importview/');  
           				}
					}); 
				api.load(); 
            	},
            	success:function(data){
					//ERROR CHECK
					var isError = false;
					if(data.error)
					{
						alert("Sorry there was a problem loading your google contacts. Please check your username and password");
						isError = true;
						$("#loader").html('<span style="color:red">Please close and try it again!</span>');
						
						
					}
					
					
					
					if(!isError)
					{
            			st = 0;
            			str = '<input type="hidden" name="google_form" value="1"/>';
            			$.each(data, function(key, value){
  							if(value.name!='')
  							{
  								str += '<div id="c-'+st+'">';
  								str += '<table class="content"></td>';
  								str += '<tr><td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleContactRemove('+st+');"><img src="images/MAIL_DELETE_OFF.gif" border="0" id="del'+st+'" /></a></td>';
  								str += '<td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleThankNow('+st+');"><img src="images/MAIL_THANK_NOW_OFF.gif" border="0" id="thankNow'+st+'" /></a></td>';
  								str += '<td valign="top"><input type="text" name="full_name[]" value="'+value.name+'" class="ui-state-default ui-corner-all"/></td>';
  								str += '<td><textarea rows="3" cols="50" name="full_address[]" id="ta'+st+'" class="ui-state-default ui-corner-all" size="50">'+value.address+'</textarea><td/></tr>';
  								str += '<input type="hidden" name="delete[]" id="delete'+st+'">';
  								str += '<input type="hidden" name="thank_now[]" id="thank_now'+st+'">';
  								str += '</table>';
  								str += '</div>';
								st++;
  							}
						});
						document.getElementById('loader').innerHTML = '';
						document.getElementById('contacts').innerHTML = str;
						document.getElementById('button').innerHTML = '<img src="images/next_button.jpg" border="0" onClick="TFE_WRITENOTE.SubmitContacts();">';//'<input type="button" onClick="TFE_WRITENOTE.SubmitContacts();" name="submit_me" value="add contacts" class="ui-state-default ui-corner-all"/>';
            		}
				}
       		}); 
       }); 
	},
	
	
	ImportYahoo:function()
	{
		$(document).ready(function(){
      	 	dataString = $("#gmail_form").serialize();
			$.ajax({
				type: "POST",
				url: "/writenote/steptwo/loadyahoo",
				data: dataString,
				dataType: "json",
				beforeSend: function() 
				{
					var api = $("div.overlay").overlay(
					{
						oneInstance: false, 
						api: true,
						expose: 'white',
						effect: 'apple',
						top: '1%',
						onBeforeLoad: function() 
						{ 
							var wrap = this.getContent().find("div.wrap"); 
                			wrap.load('/writenote/steptwo/importview/');  
           				}
					}); 
				api.load(); 
            	},
            	success:function(data)
				{
					//alert('success');
            		st = 0;
            		str = '<input type="hidden" name="google_form" value="1"/>';
					var error = false;
            		$.each(data, function(key, value)
					{
						//ERROR CHECK
						if(key == 'error')
						{
							error = true;
						}
            			st++;
  						str += '<div id="c-'+st+'">';
  						str += '<table class="content"></td>';
  						str += '<tr><td  valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleContactRemove('+st+');"><img src="images/MAIL_DELETE_OFF.gif" border="0" id="del'+st+'" /></a></td>';
  						str += '<td  valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleThankNow('+st+');"><img src="images/MAIL_THANK_NOW_OFF.gif" border="0" id="thankNow'+st+'" /></a></td>';
  						str += '<td  valign="top"><input type="text" name="full_name[]" value="'+value.full_name+'" class="ui-state-default ui-corner-all"/></td>';
  						str += '<td  valign="top"><textarea rows="3" cols="50" name="full_address[]" class="ui-state-default ui-corner-all" size="50" id="ta'+st+'">'+value.full_address+'</textarea><td/></tr>';
  						str += '<input type="hidden" name="delete[]" id="delete'+st+'">';
  						str += '<input type="hidden" name="thank_now[]" id="thank_now'+st+'">';
  						str += '</table>';
  						str += '</div>';
					});
					
					//ERROR CHECK
					if (error) {
						alert('There appears to be an error with your Yahoo data. Please close this and try again');
						$("#loader").html('<span style="color:red">Please close and try it again!</span>');
					}
					else 
					{
						document.getElementById('loader').innerHTML = '';
						document.getElementById('contacts').innerHTML = str;
						document.getElementById('button').innerHTML = '<img src="images/next_button.jpg" border="0" onClick="TFE_WRITENOTE.SubmitContacts();">';//'<input type="button" onClick="TFE_WRITENOTE.SubmitContacts();" name="submit_me" value="add contacts" class="ui-state-default ui-corner-all"/>';
					}
				}
       		}); 
       }); 
	},
	
	SetOutlookObject:function(outlookObj)
	{
		TFE_WRITENOTE.outlookObject = outlookObj;
	},
	
	
	/**
	*	This method handles the submission of contacts from an upload
	*/
	SubmitContacts:function()
	{
		//LETS MAKE SURE THEY HAVE THEIR SHIT TOGETHER
		var conf = confirm('Are you sure you want to continue?');
		if(conf)
		{
			//NOW LETS MAKE SURE ALL THE ADDRESSES AND NAMES ARE THERE
			var error = false;
			var isThankNow = false;
			var hasThankNow = false;
			var idNum = 0;
			var address = '';
			var delivery_type = $("#delivery_type").val();
			$(':input', "#contacts_form").each(function() {
				if (this.name == 'thank_now[]') 
				{
					if(this.value > 0 )
					{
						isThankNow = true;
						hasThankNow = true;
						//RIP THE ID NUM OUT OF THE THANK NOW ID
						idNum = this.id.substr(9,this.id.length);
					}	
					else
					{
						isThankNow = false;
					}
				}
				
				//we only care about the address being a requirement if its going into the recipients table
				if ($("#ta"+idNum).val()=='' && isThankNow && delivery_type!=3) ///this is a work around for Firefox, it wasn't understanding this.value
				{
					error = true;
					hasThankNow = false;
					alert('OOPS!, you cannot submit contacts that do not have a name and an address');
					return false;
				}
			});
			
			//make sure there are Thank Nows
			if(!hasThankNow && !error)
			{
				error = true;
				alert('OOPS!, you cannot get past this point without choosing at least one person to Thank Now');
				return false;
			}
			
			if(!error)
			{
				$("#loader").html('<table width="600" height="480"><tr><td align="center" valign="middle"><img src="../../images/ajax-loader.gif"/></td></tr></table>');
				$(document).ready(function(){
					//SUBMIT THE FORM
      	 			dataString = $("#contacts_form").serialize();
      	 			//alert(dataString);
					$.ajax({
						type: "POST",
						url: "/writenote/steptwo/importview",
						data: dataString,
						dataType: "POST",
            			success:function(data) // GRAB THE EDIT RECIPIENT TABLE 
            			{
            				$.get('/writenote/steptwo/editrecipientstable/',function(data)
            				{
            					$("#view").html(data,function(){
            						$("#loader").html('');
            					});
            				});
            			}
            		});
				});
			}
		}
	},
	
	/**
	* Handles the toggleling of the remove values/images
	* @param int: the value 
	*/
	ToggleContactRemove:function(indice)
	{
		//is this indice already in the remove array?
		var isInArray = $.inArray(indice,TFE_WRITENOTE.contactRemove);
		//alert(isInArray);
		if(isInArray <0)
		{
			TFE_WRITENOTE.contactRemove.push(indice);
			//alert('here');
			$("#del"+indice).attr({src:"images/MAIL_DELETE_ON.gif"});	
			//SET VALUE IN THE FORM
			$("#delete"+indice).val(1);
			
			//DO WE NEED TO TOGGLE THE thnkaNow Image/Array
			isThankNow = $.inArray(indice,TFE_WRITENOTE.thankNow);
			//alert(isThankNow);
			if(isThankNow>=0)
			{
				TFE_WRITENOTE.thankNow.splice(isThankNow,1);
				$("#thankNow"+indice).attr({src:"images/MAIL_THANK_NOW_OFF.gif"});
			}
		}
		else // REMVE FROM ARRAY AND UNTOGGLE DELETE GIF
		{
			TFE_WRITENOTE.contactRemove.splice(isInArray,1)
			$("#del"+indice).attr({src:"images/MAIL_DELETE_OFF.gif"});
		}
	},
	
	/**
	* Handles the toggleling of the thank now values/images
	*
	*/
	ToggleThankNow:function(indice)
	{
		var isInArray= $.inArray(indice,TFE_WRITENOTE.thankNow);
		//alert(isInArray);
		if(isInArray <0)
		{
			TFE_WRITENOTE.thankNow.push(indice);
			//alert('here');
			$("#thankNow"+indice).attr({src:"images/MAIL_THANK_NOW_ON.gif"});	
			//DO WE NEED TO TOGGLE THE thnkaNow Image/Array
			isRemove = $.inArray(indice,TFE_WRITENOTE.contactRemove);
			$("#thank_now"+indice).val(1);
			//alert(isRemove);
			if(isRemove>=0)
			{
				TFE_WRITENOTE.contactRemove.splice(isRemove,1);
				$("#del"+indice).attr({src:"images/MAIL_DELETE_OFF.gif"});
			}
		}
		else // REMVE FROM ARRAY AND UNTOGGLE DELETE GIF
		{
			TFE_WRITENOTE.thankNow.splice(isInArray,1);
			//alert('REMOVE');
			$("#thank_now"+indice).val(0);
			$("#thankNow"+indice).attr({src:"images/MAIL_THANK_NOW_OFF.gif"});
		}
	},
	
	/**
	* Removes div from view
	* 
	*/
	RemoveMe:function(div)
	{
		$("#"+div).remove();
	},
	
	/**
	* This method handles the prcoessing of  the imported EXCEL data and couples 
	* it for display with users chosen format options
	*/
	ImportExcel:function()
	{
		$(document).ready(function(){
			$("#loader").show();
			var fullName = '';
            var fullAddress = '';
			var currentIndice = 0;
      	 	var excelFormat = $("#excel_helper").serializeArray();
      	 	//GET FORMAT DETAILS, SET UP ARRAY OF DATA FOR LATER USE
      	 	var excelIndices = new Array();
      	 	$.each(excelFormat, function(k, val){
      	 		excelIndices[''+val.value+''] = k;
				//alert(val.value + ': '+k);
      	 	});
      	 	$.get('/writenote/steptwo/importview/',function(data)
            {
            	$("#view").html(data);
            	$("#loader").hide();
            	st = 0;
            	str = '<input type="hidden" name="google_form" value="1"/>';
            	$.each(TFE_WRITENOTE.excelData, function(key, value)
            	{
            		//break up data set
            		dataSet = value.data;
					//alert(value.data[0]);
					//fullName = ''; 
					//fullName = dataSet[excelIndices['title']] + ' '+ dataSet[excelIndices['first_name']] + ' '+ dataSet[excelIndices['last_name']];
            		(typeof dataSet[excelIndices['title']]=='undefined')?fullName += dataSet[excelIndices['first_name']] + ' '+ dataSet[excelIndices['last_name']] :fullName+= dataSet[excelIndices['title']] + ' '+ dataSet[excelIndices['first_name']] + ' '+ dataSet[excelIndices['last_name']];
					(typeof dataSet[excelIndices['address']]=='undefined')?fullAddress += '' :fullAddress +="\n"+dataSet[excelIndices['address']];
            		(typeof dataSet[excelIndices['address2']]=='undefined' || dataSet[excelIndices['address2']].length<1)?fullAddress += '' :fullAddress +="\n"+dataSet[excelIndices['address2']];
            		(typeof dataSet[excelIndices['city']]=='undefined')?fullAddress += '' :fullAddress +="\n"+dataSet[excelIndices['city']];
            		(typeof dataSet[excelIndices['state']]=='undefined')?fullAddress += '' :fullAddress +=', '+dataSet[excelIndices['state']];
            		(typeof dataSet[excelIndices['postal']]=='undefined')?fullAddress += '' :fullAddress +=" "+dataSet[excelIndices['postal']];
            		(typeof dataSet[excelIndices['country']]=='undefined')?fullAddress += '' :fullAddress +=' '+dataSet[excelIndices['country']];
					
					//alert(typeof dataSet[excelIndices['address2']]);
            		//MAKE SURE THRE"S NOTHING UNDEFINED
            		
            		//SET UP HTML
            		str += '<div id="c-'+st+'">';
  					str += '<table class="content"></td>';
  					str += '<tr><td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleContactRemove('+st+');"><img src="images/MAIL_DELETE_OFF.gif" border="0" id="del'+st+'" /></a></td>';
  					str += '<td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleThankNow('+st+');"><img src="images/MAIL_THANK_NOW_OFF.gif" border="0" id="thankNow'+st+'" /></a></td>';
  					str += '<td valign="top"><input type="text" name="full_name[]" value="'+fullName+'" class="ui-state-default ui-corner-all" size="50"/></td>';
  					str += '<td valign="top"><textarea rows="3" cols="50" name="full_address[]" class="ui-state-default ui-corner-all" id="ta'+st+'">'+fullAddress+'</textarea><td/></tr>';
  					str += '<input type="hidden" name="delete[]" id="delete'+st+'">';
  					str += '<input type="hidden" name="thank_now[]" id="thank_now'+st+'">';
  					str += '</table>';
  					str += '</div>';
  					
  					//CLEAR THE STRINGS
  					fullName = '';
  					fullAddress = '';
  					//INCREMENT
  					st++;
				});
				//DISPLAY HTML
				$("#contacts").html(str);
				$("#button").html('<input type="button" onClick="TFE_WRITENOTE.SubmitContacts();" name="submit_me" value="add contacts" class="ui-state-default ui-corner-all"/>');
            }); 
       });
	},
	
	/**
	* This Methodhandles the initial EXCEL FILE file import. 
	* Data is stored in the TFE_WRITENOTE.excelData object for later use
	*/
	LoadExcel:function()
	{
		$(document).ready(function(){
			var api = $("div.overlay").overlay({
		    	oneInstance: false, 
				api: true,
				expose: 'white',
				effect: 'apple',
				top: '1%',
				onBeforeLoad: function() 
				{ 
					var wrap = this.getContent().find("div.wrap"); 
                	wrap.load('/writenote/steptwo/excelhelper');  
           		},
           		onLoad:function()
           		{
           			$.ajaxFileUpload
					(
						{
							url:'/writenote/steptwo/loadexcel', 
							secureuri:false,
							fileElementId:'addressbook',
							dataType: 'json',
							success: function (data, status)
							{
								//STORE DATA
								$("#loader").hide();
								TFE_WRITENOTE.excelData = data;
							},
							error: function (data, status, e)
							{
								alert('Sorry there was an issue with your Excel file. Please make sure it was saved as a TXT or TSV document.');
							}
						}
					)
					return false;
           		}
			});
           	
           	api.load(); 
		}); 
	},
	
	/**
	* This Method handles the importing the OSX contacts
	*/
	ImportMacContacts:function()
	{
		$(document).ready(function(){
			var api = $("div.overlay").overlay({
		    	oneInstance: false, 
				api: true,
				expose: 'white',
				effect: 'apple',
				top: '1%',
				onBeforeLoad: function() 
				{ 
					var wrap = this.getContent().find("div.wrap"); 
                	wrap.load('/writenote/steptwo/importview');  
           		},
           		onLoad:function()
           		{
					var error = false;
					var addy = '';
           			$.ajaxFileUpload
					(
						{
							url:'/writenote/steptwo/loadmaccontacts', 
							secureuri:false,
							fileElementId:'addressbook',
							dataType: 'json',
							success: function (data, status)
							{
								
								//STORE DATA
								//$("#loader").hide();
								TFE_WRITENOTE.macData = data;
            					str = '<input type="hidden" name="google_form" value="1"/>';
								st = 0;
            					$.each(data, function(key, value){
								//ERROR CHECK
								if(key == 'error')
								{
									error = true;
								}
            					st++;
  								if(value.fname!='')
  								{
									if(value.addresses == null)
									{
										addy = '';
									}
									else
									{
										addy = value.addresses;
									}
  									str += '<div id="c-'+st+'">';
  									str += '<table class="content"></td>';
  									str += '<tr><td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleContactRemove('+st+');"><img src="images/MAIL_DELETE_OFF.gif" border="0" id="del'+st+'" /></a></td>';
  									str += '<td valign="top"><a href="javascript:TFE_WRITENOTE.DoNothing();" onclick="TFE_WRITENOTE.ToggleThankNow('+st+');"><img src="images/MAIL_THANK_NOW_OFF.gif" border="0" id="thankNow'+st+'" /></a></td>';
  									str += '<td valign="top"><input type="text" name="full_name[]" value="'+value.fname+'" class="ui-state-default ui-corner-all"/></td>';
  									str += '<td valign="top"><textarea rows="3" cols="50" name="full_address[]" class="ui-state-default ui-corner-all" id="ta'+st+'">'+addy+'</textarea><td/></tr>';
  									str += '<input type="hidden" name="delete[]" id="delete'+st+'">';
  									str += '<input type="hidden" name="thank_now[]" id="thank_now'+st+'">';
  									str += '</table>';
  									str += '</div>';
  								}
							});
								//ERROR CHECK
								if (error) {
									alert('There appears to be an error with your vCard data. Please close this and try again');
									$("#loader").html('<span style="color:red">Please close and try it again!</span>');
								}
								else 
								{
									document.getElementById('loader').innerHTML = '';
									document.getElementById('contacts').innerHTML = str;
									document.getElementById('button').innerHTML = '<img src="images/next_button.jpg" border="0" onClick="TFE_WRITENOTE.SubmitContacts();">';//'<input type="button" onClick="TFE_WRITENOTE.SubmitContacts();" name="submit_me" value="add contacts" class="ui-state-default ui-corner-all"/>';
								}
							},
							error: function (data, status, e)
							{
								//alert(e);
							}
						}
					)
					return false;
           		}
			});
           	api.load(); 
		}); 
	},
	
	ImportContact:function()
	{
		$("#messaging").html('Adding now your contact now...');
		var error = false;
		//DO ERROR CHECK
		$(':input', "#byhand_form").each(function() {
			if(this.type == 'text')
			{
				if(this.value == '')
				{
					//address2 is not required
					if(this.name !='address2')
					{
						error = true;
					}
				}
			}
		});
		if(!error)
		{
			$("#loader").show();
			dataString = $("#byhand_form").serialize();
      		$.ajax({
				type: "POST",
				url: "/writenote/steptwo/importcontact",
				data: dataString,
				dataType: "post",
            	success:function()
            	{
					$("#messaging").html('Your contact has been added');
            		$("#loader").hide();
            		//clear from fields
					$(':input', "#byhand_form").each(function() {
						if(this.type == 'text')
						{
							this.value = '';
						}
					});
            	}
			});
			$("#faddress").val('');
		}
		else
		{
			$("#messaging").html('');
			alert('Please complete all required fields');
		}
	},
	
	RecipientsTable:function()
	{
		$("#loader").show();
		$.get('/writenote/steptwo/editrecipientstable/',function(data)
          {
          	//MAKE SURE THERE ARE RECIPENTS
          	//alert(data);
          	if(data != 'NONE')
          	{
            	$("#view").html(data,function(){
            		$("#loader").html('');
            	});
          	}
          	else
          	{
          		$("#loader").html('');
          		alert('Sorry you cannot load the recipients table with no recipients. ');
          	}
       	});
	},
	
	DoNothing:function()
	{
		
	},
	ToggleMe:function(div)
	{
		$("#"+div).toggle("fast");
	},
	ToggleInstructions:function(which)
	{
		var instructions = new Array();
		instructions[0] = 'instructions_salutation';
		instructions[1] = 'instructions_gift';
		instructions[2] = 'instructions_relationship';
		instructions[3] = 'instructions_valediction';
		for(i=0;i<instructions.length;i++)
		{
			if(which != instructions[i])
			{
				$("#"+instructions[i]).hide('fast');	
			}
		}
		$("#"+which).toggle('fast');
	},
	MyName:function(theForm)
	{
		var myForm = 'my first name<br>';
		myForm += '<input type="text" class="textbox" name="my_name">';
		
		var myPartnerForm = 'my first name<br>';
		myPartnerForm += '<input type="text" class="textbox" name="my_name">';
		myPartnerForm += 'my partner\'s first name<br>';
		myPartnerForm += '<input type="text" class="textbox" name="my_partner_name">';
		
		$("#my_partner_form").html('');
		if(theForm == 'my_form')
		{
			$("#my_partner_form").html(myForm);
		}
		else
		{
			$("#my_partner_form").html(myPartnerForm);
		}
	},
	
	/**
	 * This method handles the display for the baby names. The HTML is stored in divs on the 
	 * subview tfebbay_stepone_event_postdate.php
	 */
	HowManyBabies:function()
	{
		//GET THE NUMBER OF BABIES 
		var howMany = $("#number_of_babies").val();
		
		//CLEAR DIV
		$("#baby_name_form").html('');
		
		//PRINT CORRECT LAYOUT
		if(howMany == 2)
		{
			$("#baby_name_form").html($("#twinsLayout").html());
		}
		if(howMany == 3)
		{
			$("#baby_name_form").html($("#tripletsLayout").html());
		}
		if(howMany != 3 && howMany != 2)
		{
			$("#baby_name_form").html($("#onebabyLayout").html());
		}
		
		
	},
	
	OpenOverlay:function(url)
	{
		var api = $("div.overlay").overlay({ 
			oneInstance: true,
			api: true,
			expose: 'white',
			effect: 'apple',
			top: '1%',
			onBeforeLoad: function() 
			{ 	
				var wrap = this.getContent().find("div.wrap"); 
                wrap.load(url);  
           	}
           
		});
		//api.bind("onClose MyName");
		api.load(); 
	},
	
	CloseOverlay:function()
	{
		alert(1);
		var api = $("div.overlay").overlay({oneInstance: true});
			
		api.close();
		//api.unbind("onClose MyName");
	},
	CheckStepOne:function()
	{
		var error = false;
		$(':input', "#stepone_form").each(function() {
			if(this.type == 'text')
			{
				//alert(this.value);
				if(this.value == '')
				{
					error = true;
					return false;
				}
			}
		});
		if(error)
		{
			alert('Please complete the form');
			return false;
		}
	},
	
	/**
	* This method handles the login during the note writing process. 
	*/
	StepOneLogin:function()
	{
		dataString = $("#step_one_login").serialize();
      	 	$.ajax({
			type: "POST",
			url: "/writenote/stepone/login",
			data: dataString,
			dataType: "post",
            success:function(data)
            {
            	if(data == 'NO')
            	{
            		alert('Sorry that login is incorrect please try again.');
            	}
            	else
            	{
            		window.location = '/writenote/steptwo/recipients/import';
            	}
            }
		});
	},
	
	RegisterUser: function()
	{
		var email = $("#email").val();
		var pass = $("#pass").val();
		var passed = true;
		if(pass.length<6 || email.length<5)
		{
			alert('Please complete teh form. Your password must be 6 or more characters');
			passed = false;
		}
		
		if(passed)
		{
			dataString = $("#step_one_register").serialize();
      	 		$.ajax({
				type: "POST",
				url: "/writenote/stepone/register",
				data: dataString,
				dataType: "post",
            	success:function(data)
           		{
            		if(data == 'NO')
            		{
            			alert('Sorry that username is taken. Please try another');
            		}
            		else
            		{
            			window.location = '/writenote/steptwo/recipients/import';
            		}
            	}
			});
		}
	},
	
	ConfirmEditTable:function()
	{
		var error = false;
		$(':input', "#recipientstable").each(function() {
			//alert(this.type);
			if(this.type == 'text')
			{
				//ONLY 1 GIFT IS REQUIRED
				if(this.value == '' 
				
				&& this.name!='gift1[]'
				&& this.name!='gift2[]'
				&& this.name!='gift3[]'
				&& this.name!='gift4[]'
				&& this.name!='gift5[]')
				{
					//alert(this.name);
					error = true;
					return false;
				}
			}
			if(this.type == 'select-one')
			{
				if(this.value == 'choose')
				{
					error = true;
					return false;
				}
			}
		});
		if(error)
		{
			alert('Please complete the form');
			return false;
		}
		else
		{
			return true;
		}
	},
	
	DisplayContactsUi:function(which)
	{
		if(which == 'groups')
		{
			$("#groups").show('fast',function(){
				$("#people").hide('fast');
			});
		}
		else
		{
			$("#people").show('fast',function(){
				$("#groups").hide('fast');
			});
		}
	},
	
	/**
	* Handles the toggleling of the thank group values/images
	*
	*/
	ToggleGroup:function(indice)
	{
		isInArray= $.inArray(indice,TFE_WRITENOTE.thankGroup);
		if(isInArray<0)
		{
			TFE_WRITENOTE.thankGroup.push(indice);
			//alert('here');
			$("#thankGroup"+indice).attr({src:"images/MAIL_THANK_NOW_ON.gif"});	
			//DO WE NEED TO TOGGLE THE thnkaNow Image/Array
			$("#thank_group"+indice).val(1);
		}
		else // REMVE FROM ARRAY AND UNTOGGLE DELETE GIF
		{
			TFE_WRITENOTE.thankGroup.splice(isInArray,1)
			$("#thankGroup"+indice).attr({src:"images/MAIL_THANK_NOW_OFF.gif"});
		}
	},
	
	/**
	 * This method handles the mock radio group. It stores the BOOLEAN values dynamically in view defined array.
	 * This is primarily a visual method, generally it;s used in conjunction with methods for writing value to a
	 * field.
	 * 
	 * @param (object)params
	 */
	ToggleRadioGroup:function(params)
	{
		//required parameters
		var indice = params.indice;
		var radioGroup = params.radioGroup; 
		//optional
		var element = params.element; 
		var value = params.value;
		
		theArray = eval(radioGroup);
		var i = 0;
		$.each(theArray, function() {
      		if(i==indice)
			{
				//alert(indice);
				if (this == 0) {
					theArray[i] = 1;
					$("#" + radioGroup + "" + indice).attr({
						src: "images/MAIL_THANK_NOW_ON.gif"
					});
					if (element)//set value
					{
						TFE_WRITENOTE.SetValue(value, element);
					}
					//IF THERE'S A CALL TO Method PASSED AT THIS POInt CALL It
					if (params.callTo) //optional
					{
						/*
						 * loop through the parameter array passed by the
						 * object to set up cars to be passed to the callTo method.
						 */
						var paramString = "";
						//are there params
						if(params.callTo.param)
						{
							$.each(params.callTo.param, function(){
								paramString += "'" + this + "',";
							});
						}
						var pString = paramString.substr(0, paramString.length - 1);
						var func = "TFE_WRITENOTE." + params.callTo.method + "(" + pString + ")";
						eval(func);
					}
				}
				else {
					if (!params.isRadio) { // IF isRadio == YES then we can not use extended function of turning check off
						theArray[i] = 0;
						$("#" + radioGroup + "" + indice).attr({
							src: "images/MAIL_THANK_NOW_OFF.gif"
						});
						if (element) //unset value
						{
							TFE_WRITENOTE.SetValue("", element);
						}
						//IF THERE'S A CALL TO Method PASSED AT THIS POInt CALL It
						if (params.callTo) //optional
						{
							/*
							 * loop through the parameter array passed by the
						 	* object to set up cars to be passed to the callTo method.
			 				*/
							var paramString2 = "";
							if(params.callTo.param)
							{
								$.each(params.callTo.param, function(){
									paramString2 += "'" + this + "',";
								});
							}
							var pString2 = paramString2.substr(0, paramString2.length - 1);
							var func2 = "TFE_WRITENOTE." + params.callTo.method + "(" + pString2 + ")";
							eval(func2);
						}
					}
				}
			}
			else//unset any set value not equaling current indice
			{
				theArray[i] = 0;
				$("#" + radioGroup + "" + i).attr({
					src: "images/MAIL_THANK_NOW_OFF.gif"
				});
			}
			i++;
   		 });
	},
	
	/**
	 * This method handles setting any ind of value that has an ID, intended for hidden form 
	 * fields, but has many potential uses.
	 * 
	 * @param {Object} value
	 * @param {Object} elementID
	 */
	SetValue: function(value,elementID)
	{
		//alert(elementID);
		$("#"+elementID).val(value);
	},
	
	
	ShowEditTable:function()
	{
		$.get('/writenote/steptwo/editrecipientstable/',function(data)
        {
          $("#view").html(data,function(){
            $("#loader").html('');
           });
        });
	},
	
	SubmitFaux:function(url)
	{
		window.location = url;
	},
	/**
	 *  This is kinda of complicated, and is addition towards the end of teh project. This method handles showing the 
	 *  display of multiple 
	 * @param {Object} indice
	 */
	AddGift:function(indice)
	{
		//only 5 max gifts
		if(TFE_WRITENOTE.extraGifts[indice]<5)
		{
			TFE_WRITENOTE.extraGifts[indice] = TFE_WRITENOTE.extraGifts[indice] + 1;
			$("#extra_gift" + indice + "-" + TFE_WRITENOTE.extraGifts[indice]).show('fast');
		}
		else
		{
			alert('Sorry you can only add 5 gifts max per recipient.');
		}
	},
	
	ContactTFE:function()
	{
		$(document).ready(function(){
				$("#msg").html('<img src="/images/ajax-loader.gif">');
      	 		dataString = $("#contact_form").serialize();
				$.ajax({
					type: "POST",
					url: "/writenote/steptwo/contact_tfe",
					data: dataString,
					dataType: "json",
					success: function(data) 
					{
						$('#msg').html("Thanks, your message has been sent");
						$('#email').val('');
						$('#subject').val('');
						$('#message').val('');
            		} 
       			}); 
       			//$('#recipient').toggle("slow");
	       	}); 
	},
	
	/**
	 *  This method handles the submission of TFE Address book values for recipient import
	 */
	SubmitTFEAddressBook:function()
	{
		var hasGroups = false;
		var hasError = false;
		//HAS THIS USER SELECTED A GROUP TO SUBMIT?
		for(i=0; TFE_WRITENOTE.thankGroup.length;i++)
		{
			if(typeof TFE_WRITENOTE.thankGroup[i] !='undefined')
			{
				hasGroups = true;
				$.get('/writenote/steptwo/AddGroupToRecipients/'+$("#group"+i).val(),function(data){
					if(data == 'error')
					{
						hasError = true;
						alert('At least one of your recipients in this group is missing an addresss.');
					}
					else
					{
						if(!hasError)
						{
							$("#loader").show();
							$.get('/writenote/steptwo/editrecipientstable/', function(data){
									$("#view").html(data, function(){
									$("#loader").html('');
								});
							});
						}
					}
				});
			}
			else // IF THIS LOOP RUNS INTO ANY UNDEFINED VALUES BREAK THE LOOP TO PREVENT ERROR
			{
				break;	
			}
		}
		if(!hasGroups)//A REGULAR SUBMIT
		{
			TFE_WRITENOTE.SubmitContacts();
		}
		else // DEAL WITH GROUPS
		{
			//alert(hasError);
			
		}
	}
}
