// JavaScript Document
var bookPlateWizard = {
	initialized: false,
	cartItems: [],
	bookplates: [],
	mode: null,
	
	init: function(e){
		
		this.modalContents = this.createModContents();
		
		
		this.modalContents.modal({
			  closeHTML: ('<input id="modalCloseBtn" type="button" class="button modalClose" style="width:150px;" value="Return To Cart"></button>'),
			  onClose: this.warningMsg,
			  position: ["5%",],
			  overlayCss: {
				backgroundColor: '#efefef',
				cursor: 'wait'
			  },
			  containerCss: {
				height: 530,
				width: 650
			}
		});
		
		if (this.initialized == false)
			{
				this.bookplates = g_bookplates;
				if (typeof(g_mode) == "undefined")
					{this.mode = null;}
				else
					{this.mode = g_mode;
					 
					}
				
				this.readCart();
				
				
				this.initialized = true;
			}
		this.resolveWithCart();
		this.populateBookPlateList();
		this.stylePicker();
		if (this.mode != null)
			{
				this.initDisplay();
			}
	},
	warningMsg: function(){
		
		var self = this;
		var answer = confirm("Your Bookplates were not saved.  You must 'save' your bookplate(s) before checkout to ensure they are submitted. \n\n Click 'OK' To return to the cart without saving. \n\n Click 'CANCEL' to proceed with saving your Bookplate(s). ")
		if (answer)
			{
			$.modal.close();
			}
		else
			{
				var closeBtn = $('#modalCloseBtn');
				closeBtn.unbind('click');
				closeBtn.click(function(){bookPlateWizard.warningMsg()});
			}
	},
	initDisplay: function(){
		$('.wizardForm').hide();
		$('.previewArea').hide();
		$('.wizardAutoData').hide();
		$('.wizardOptions').hide();
		switch (this.mode)
					{
						case 0:
								$('.wizardAutoData').show();
								this.loadAutoFormFromPlate();
								$('#booktitleheading').html("All Donated Items");
							break;
						case 1:
								$('.wizardForm').show();
								$('.picker').hide();
								this.loadFormFromPlate(0);
								$('#booktitleheading').html("All Donated Items");
							break;
						case 2:
								$('.wizardForm').show();
								$('.picker').show();
								var bookplate = this.getNextPlate();
								if (bookplate != null)
									{
										this.loadFormFromPlate(this.getBookIndexByKey(bookplate.key));
									}
								else
									{
										this.loadFormFromPlate(0);
									}
							break;
					}
	},
	resolveWithCart: function(){
		//delete any itmes in bookplates not in cart
		for (var i=0; i < this.bookplates.length; i++)
		{
			var incart = false;
			for (b in this.cartItems)
			{
				if (this.bookplates[i].key == this.cartItems[b].key)
					{incart=true;}
			}
			if (incart == false)
				{this.bookplates.splice(i, 1)}
		}
		//save new items that are in cart but not in bookplates
		for (b in this.cartItems)
		{
			if ( this.getBookIndexByKey(this.cartItems[b].key) == null )
				{
					this.saveBookPlate(this.cartItems[b].key, false, this.cartItems[b].title, this.cartItems[b].author, null, null, null, null, null)
				}
		}
			
		
	},
	
	
	readCart: function(){
		$( ".book" ).each( 
			function(i){
				var key = $(this).attr('registry_item_id') ;
				var title = unescape($(this).attr('booktitle')); ;
				var author = $(this).attr('author') ;
				
				var author2 = eval(unescape(author));
				var astring = "";
		
		for (var i=0; i<author2.length;i++)
			{
				for (var j=author2[i].length -1; j>=0; j--)
					{
						astring += author2[i][j] + " ";
					}
				if (i < author2.length-1){astring += " and "};
			}
				bookPlateWizard.cartItems[bookPlateWizard.cartItems.length] = {key: key, title: title, author: astring};
			}
		)
	},
	
	createModContents: function(){
		var modDiv = $("<div id='modalData' class='modalData'></div>")
		var mTop = $("<div class='mTop'></div>");
		modDiv.append(mTop);
		
		var mContents = $("<div class='mContents'><div class='wizardTitle'>Book Plate Wizard</div></div>")
		mContents.append(this.createOptionsContent());
		mContents.append(this.createWizardAutoForm());
		mContents.append(this.createWizardForm());
		mContents.append(this.createPreviewArea());
		
		modDiv.append(mContents);
		var mBottom = $("<div class='mBottom'></div>");
		modDiv.append(mBottom);
		this.modalCreated = true;
		return modDiv;
	},
	createOptionsContent: function(){
		var wOptions = $('<div id="wizardOptions" class="wizardOptions"><div id="heading" class="heading">By using this bookplate wizard, you can choose to create a custom bookplate for each item in your shopping cart or have one created for you.  You will be able to preview each bookplate as you proceed.  Please make sure to preview and save your bookplates before returning to the cart to checkout.</div></div>')
		var tOptions = $('<table id="options" class="options">');
		
		var r1 = $('<tr><td valign="top"><input name="wizardMode" id="modeAllSame" type="radio" checked></td><td valign="top">Personalize cart- Create a personalized bookplate and re-use it for each title in your donation.</td></tr>');
		var r2 = $('<tr><td valign="top"><input name="wizardMode" id="modeAllDifferent" type="radio"></td><td valign="top">Personalize each item - Create a different personalized bookplate for each title in your donation.</td></tr>');
		var r3 = $('<tr><td valign="top"><input name="wizardMode" id="modeAuto" type="radio"></td><td valign="top">Autogenerate - Enter Your Name or "Anonymous" and a standard bookplate will be used for each title in your donation.</td></tr>');
		tOptions.append(r1);
		tOptions.append(r2);
		tOptions.append(r3);
		wOptions.append(tOptions);
		var footer = $('<div id="footer" class="footer"></div>');
		
		var btn = $('<input type="button" class="button" value="Continue To Next Step >> ">');
		btn.click(function(){bookPlateWizard.setMode();})
		footer.append(btn);
		wOptions.append(footer);
		return wOptions;
	},
	createWizardAutoForm: function(){
		var autoForm = $('<div class="wizardAutoData">Auto Generated - Enter Your Name or leave blank for "Anonymous" and a standard bookplate will be used for each title in your donation.<br><br></div>');
		var autoT = $('<table>');
		var r1 = $('<tr><td>Your Name: </td><td><input id="autoSignature" type="text" size="40"></td></tr>');
		var r2 = $('<tr><td colspan="2">leave it blank to sign your bookplate(s) "Anonymous"</td></tr>');
		autoT.append(r1);
		autoT.append(r2);
		autoForm.append(autoT);
		var footer = $('<div id="footer" class="footer"></div>');
		var btn2 = $('<input id="autoLbutton" type="button" class="button" value="<< Back To Options">');
		
		btn2.click(function(){bookPlateWizard.goToOptions();})
		footer.append(btn2);
		
		var btn = $('<input id="autoRbutton" type="button" class="button" value="Preview Bookplate >> ">');
		
		btn.click(function(){bookPlateWizard.generatePreview();})
		footer.append(btn);
		autoForm.append(footer);
		return autoForm;
	},
	stylePicker: function(){
		var sel = document.getElementById('bookplatelist');
		for (var i=0; i < sel.options.length;i++)
			{	
				$(sel.options[i]).removeClass('complete');
				$(sel.options[i]).removeClass('incomplete');
				if (this.bookplates[i].completed)
					{
						$(sel.options[i]).addClass('complete');
					}
				else
					{
						$(sel.options[i]).addClass('incomplete');
					}
			}
	},
	clearForm:function(key){
		$('#bookplateid').val(key);
		var sel = document.getElementById('f_salutation');
		sel.options[0].selected = true;
		$('#f_dedicatee').val("");
		$('#f_msg').val("");
		sel = document.getElementById('f_closingLabel');
		sel.options[0].selected = true;
		$('#f_closingSignature').val("");
	},
	loadAutoFormFromPlate: function(){
		$('#autoSignature').val(this.bookplates[0].signature);
	},
	loadFormFromPlate: function(index){
		
		var bookplate = this.bookplates[index];
		$('#booktitleheading').html(unescape(bookplate.title));
		$('#bookplateid').val(bookplate.key);
		
		
		var sel = document.getElementById('f_salutation');
		sel.options[0].selected = true;
		for (var i=0; i < sel.options.length;i++)
			{
				if (sel.options[i].value == bookplate.salutation)
					{sel.options[i].selected = true;}
				else
					{sel.options[i].selected = false;}
			}
		
		if (bookplate.dedicatee != null)
			{
				$('#f_dedicatee').val(bookplate.dedicatee);
			}
		else
			{
				$('#f_dedicatee').val("");
			}
		
		if (bookplate.msg != null)
			{
				$('#f_msg').val(bookplate.msg);
			}
		else
			{
				$('#f_msg').val("");
			}
		
		sel = document.getElementById('f_closingLabel');
		sel.options[0].selected = true;
		for (var i=0; i < sel.options.length;i++)
			{
				if (sel.options[i].value == bookplate.closing)
					{sel.options[i].selected = true;}
				else
					{sel.options[i].selected = false;}
			}
		if (bookplate.signature != null)
			{
				$('#f_closingSignature').val(bookplate.signature);
			}
		else
			{
				$('#f_closingSignature').val("");
			}
		
	},
	populateBookPlateList: function()
	{
		var bselect = $('#bookplatelist');
		for (var i = 0; i < this.bookplates.length; i++)
			{
				var oclass;
				if (this.bookplates[i].completed)
					{
						oclass="complete";
					}
				else
					{
						oclass="incomplete";
					}
				var title = this.bookplates[i].title;
				if (title.length > 50)
					{
						title = title.substr(0,47) + "...";
					}
				var opt = $('<option class="' + oclass + '" value="' + i + '">' + unescape(title) + '</option>');
				bselect.append(opt);
			}
	},
	createWizardForm: function(){
		var wForm = $('<div class="wizardForm"></div>');
		
		var wHeading = $('<div class="formHeading">Create A Custom Bookplate For: <span class="bookTitle" id="booktitleheading">Book Title</span></div>');
		wForm.append(wHeading);
		var item = $('<input type="hidden" id="bookplateid">');
		wForm.append(item);
		var wT = $('<table cellpadding="2"></table>');
		var r1 = $('<tr><td valign="top">Salutation: </td><td><select id="f_salutation"><option value="Dedicated To">Dedicated To</option><option value="In Honor Of">In Honor Of</option><option value="In Memory Of">In Memory Of</option><option value="For">For</option></select></td></tr>');
		var r2 = $('<tr><td valign="top">Dedicatee:</td><td><input type="text" name="dedicatee" id="f_dedicatee"></td></tr>');
		var r3 = $('<tr></tr>')
		var r3t1 = $('<td valign="top" width="120">Personal Message<br><span class="count">(80 character limit)</span></td>');
		r3.append(r3t1);
		var r3t2 =$('<td></td>');
		var r3t3txt = $('<textarea name="msg" class="msg" rows="2" maxlength="80" id="f_msg"></textarea>');
		r3t3txt.keypress(function(event){  
			 var key = event.which;  
	   
			 //all keys including return.  
			 if(key >= 33 || key == 13) {  
				 var maxLength = $(this).attr("maxlength");  
				 var length = this.value.length;  
				 var count = maxLength - this.value.length;
				 $('.count').html('(' + count + ' remaining)')
				 if(length >= maxLength) {  
	   
					 event.preventDefault();  
				 }  
			 }  
		 });  
		r3t2.append(r3t3txt);
		r3.append(r3t2);
		var r4 = $('<tr><td valign="top">Closing: </td><td><select id="f_closingLabel"><option value="Donated By">Donated By</option><option value="From">From</option><option value="Warm Regards">Warm Regards</option><option value="With Love">With Love</option><option value="Thank You">Thank You</option></select></td></tr>');
		var r5 = $('<tr><td valign="top">Signature:</td><td><input type="text" id="f_closingSignature"></td></tr>');
		wT.append(r1);
		wT.append(r2);
		wT.append(r3);
		wT.append(r4);
		wT.append(r5);
		wForm.append(wT);
		var footer = $('<div id="footer" class="footer"></div>');
		
		
		
		
		
		var btn2 = $('<input id="formLbutton" type="button" class="button" value="<< Back To Options">');
		
		btn2.click(function(){bookPlateWizard.goToOptions();})
		footer.append(btn2);
		
		var btn = $('<input id="formRbutton" type="button" class="button" value="Preview this Bookplate >> ">');
		btn.click(function(){bookPlateWizard.generatePreview();})
		
		
		footer.append(btn);
		wForm.append(footer);
		
		
		
		var picker = $('<table style="padding-top:50px;" class="picker"></table>');
		var tr1 = $('<tr><td colspan="3">To edit a previously created bookplate use the drop down below.</td></tr>');
		picker.append(tr1);
		var ptr = $('<tr><td>Edit Bookplate:</td></tr>');
		var td2 = $('<td></td>');
		var bselect = $('<select id="bookplatelist" class="bookplatelist"></select>');
		
		td2.append(bselect);
		//td2.append('<br><img src="/bookplate/check-mark-tiny.gif"> = complete');
		var td3 = $('<td></td>');
		var tdbtn = $('<input type="button" class="button" style="width:80px;" value="View/Edit">');
		tdbtn.click(function(){
							 bookPlateWizard.loadFormFromPlate($('.bookplatelist').val())
							 });
		td3.append(tdbtn);
		ptr.append(td2);
		ptr.append(td3);
		picker.append(ptr);
		wForm.append(picker);
		
		return wForm;
	},
	saveAll: function(){
		 var jsonStr = '{"mode":' + this.mode + ', "bookplates":'+ JSON.stringify(this.bookplates) + '}';  
		 $.ajax({  
           type: "POST",  
           url: "testajax.htm",  
           contentType: "application/json; charset=utf-8",  
           dataType: "json",  
           data: jsonStr,  
           success: function(contents){  
             	window.location.href = 'checkout';
           },  
           error: function(xhr, msg){  
            	window.location.href = 'checkout';
           }  
         });  
	},
	saveCallback: function(data)
	{
		alert('saved');
	},
	createPreviewArea: function(){
		var preview = $('<div class="previewArea"><div class="previewheading" id="previewheading"></div>');
		var bookplate = $('<div class="previewBookplate"><div class="previewBookplate"><div id="prevbooktitle" class="bookTitle"></div><div id="prevbookauthor" class="bookAuthor"><span></span> <span id="author"></span></div><div class="salutation"><span id="salutationLabel" class="salutationLabel"></span> <span id="salutationText" class="salutationText"></span></div><div id="prevmsg" class="msg"></div><div class="closing"><span class="closingText"></span> <span class="closingSignature"></span></div><div class="donateDate"></div></div>');
		preview.append(bookplate);
		var btndiv = $('<div class="previewfooter"></div>');
		
		
		var btn2 = $('<input id="lbutton" type="button" class="button" value="<< Edit Bookplate">');
		btn2.click(function(){bookPlateWizard.backToForm();})
		btndiv.append(btn2);
		var btn = $('<input id="rbutton" type="button" class="button" value="Next Bookplate >>">');
		btn.click(function(){bookPlateWizard.nextTitle();})
		btndiv.append(btn);
		
		var btn3 =  $('<input id="fbutton" type="button" class="button" value="Save and Checkout >>">');
		btn3.click(function(){bookPlateWizard.saveAll();});
		btndiv.append(btn3);
		preview.append(btndiv);
		return preview;
	},
	nextTitle:function(){
		this.stylePicker();
		var bookplate = this.getNextPlate();
		this.clearForm();
		$('#booktitleheading').html(unescape(bookplate.title));
		$('#bookplateid').val(bookplate.key);
		$('.previewArea').hide();
		$('.wizardForm').fadeIn("slow");
	},
	generatePreview: function(){
		var key = $('#bookplateid').val();
		var salutation = $('#f_salutation :selected').text();
		var dedicatee = $('#f_dedicatee').val();
		var msg = $('#f_msg').val();
		var closing = $('#f_closingLabel :selected').text();
		var signature = $('#f_closingSignature').val();
		switch(this.mode)
			{
				case 0: //auto
					var val = $('#autoSignature').val();
					if (val == "")
						{
							this.saveAllBookPlates("", "", "", "Donated By", "Anonymous");
						}
					else
						{
							this.saveAllBookPlates("", "", "", "Donated By", val);
						}
					
					this.populatePreview(this.bookplates[0]);
					$('#previewheading').html('This is a preview of your bookplate(s) using the first title in your donation as the example');
					$('#previewheading').html();
					$('.wizardAutoData').hide();
				break;
				case 1:  //all same
					this.saveAllBookPlates(salutation, dedicatee, msg, closing, signature);
					this.populatePreview(this.bookplates[0]);
					$('#previewheading').html('This is a preview of your bookplate(s) using the first title in your donation as the example');
					$('.wizardForm').hide();
				break;
				case 2: //all diff
					var bindex = this.getBookIndexByKey(key);
					this.saveBookPlate(key, true, this.bookplates[bindex].title, this.bookplates[bindex].author, salutation, dedicatee, msg, closing, signature )
					this.populatePreview(this.bookplates[bindex]);
					$('#previewheading').html('This is a preview of your bookplate.');
					$('.wizardForm').hide();
					var bookplate = this.getNextPlate();
					if (bookplate == null)
						{
							$('#fbutton').show();
							$('#rbutton').hide();
						}
					else
						{
							$('#fbutton').hide();
							$('#rbutton').show();
						}
				break;
			}
		
		
		$('.previewArea').fadeIn("slow");
	},
	populatePreview: function(bookplate){
		$('#prevbooktitle').html(unescape(bookplate.title));
		
		$('#prevbookauthor').html("By: " + bookplate.author);
		$('#salutationLabel').html(bookplate.salutation);
		$('#salutationText').html(bookplate.dedicatee);
		$('#prevmsg').html(bookplate.msg);
		$('.closingText').html(bookplate.closing);
		$('.closingSignature').html(bookplate.signature);
		$('.donateDate').html(bookplate.bdate);
	},
	saveAllBookPlates: function(sal, ded, msg, clos, sig)
	{
		for (b in this.bookplates)
			{
				this.saveBookPlate(this.bookplates[b].key, true, this.bookplates[b].title, this.bookplates[b].author, sal, ded, msg, clos, sig);
			}
	},
	saveBookPlate: function(key, complete, tit, auth, sal, ded, msg, clos, sig){
		
		var d = new Date();var curr_date = d.getDate(); var curr_month = d.getMonth() + 1 ;var curr_year = d.getFullYear();
		var bdate = curr_month + "/" + curr_date + "/" + curr_year;
		var b = this.getBookIndexByKey(key)
		if (b == null)
			{
				this.bookplates[this.bookplates.length] = {key: key, completed: complete, title: tit, author: auth, salutation: sal, dedicatee: ded, msg: msg, closing: clos, signature: sig, bdate: bdate}
			}
		else
			{
				this.bookplates[b] = {key: key, completed: complete, title: tit, author: auth, salutation: sal, dedicatee: ded, msg: msg, closing: clos, signature: sig, bdate: bdate}
			}
		
	},
	goToOptions: function(){
		$('.wizardAutoData').hide();
		$('.wizardForm').hide();
		$('.previewArea').hide();
		$('.wizardOptions').fadeIn("slow");
	},
	backToForm: function(){
		$('.previewArea').hide();
		switch (this.mode)
			{
				case 0:
					$('.wizardAutoData').fadeIn("slow");
					break;
				
				case 1:
					$('.wizardForm').fadeIn("slow");
					$('.picker').hide();
					break;
				case 2:
					$('.wizardForm').fadeIn("slow");
					this.stylePicker();
					$('.picker').show();
					break;
			}
	},
	setMode: function(){
		if ($('#modeAuto')[0].checked)
			{
				this.mode = 0;
				$('.wizardOptions').hide();
				$('.wizardAutoData').fadeIn("slow");
				$('.picker').hide();
				$('#rbutton').hide();
				$('#fbutton').show();
			}
		if( $('#modeAllSame')[0].checked)
			{
				this.mode = 1;
				$('.wizardOptions').hide();
				$('.wizardForm').fadeIn("slow");
				$('#bookplateid').val("all");
				$('.picker').hide();
				$('#booktitleheading').html('All Donated Items');
				$('#rbutton').hide();
				$('#fbutton').show();
				
			}
		if( $('#modeAllDifferent')[0].checked)
			{
				this.mode = 2;
				$('.wizardOptions').hide();
				$('.wizardForm').fadeIn("slow");
				$('.picker').show();
				this.stylePicker();
				
				var bookplate = this.getNextPlate();
				if (bookplate == null)
					{
						bookplate = this.bookplates[0];
					}
				
				$('#bookplateid').val(bookplate.key);
				$('#booktitleheading').html(unescape(bookplate.title));
				$('#fbutton').hide();
				$('#rbutton').show();
			}
			
		
	},
	
	getNextPlate: function(){
		var bookplate = null;
		for (b in this.bookplates)
			{
				if (this.bookplates[b].completed == false)
					{
						bookplate = this.bookplates[b];
						break
					}
			}
		return bookplate;
	},
	
	getBookIndexByKey: function(key){
		var index = null;
		for (var i =0; i <this.bookplates.length; i++)
			{
				if (this.bookplates[i].key == key)
					{index =i;}
			}
		return index;
	}

}

