var console;
var files = Array();
var inDialog = false;
var initLength = -1;
var maxLengthOnPage = -1;
var fullFileList = "";
var myProspectus = true;

$().ready(function () {
					
	function checkAttachment () {
		$("#fileAttachments .attachmentDownload_pdf a").each(function () {
			var fileId = $(this).attr('href').match(/[0-9]+$/);
			var fieldName = $(this).html();
			
			if(fileId === null || fieldName.indexOf('.') == 0) {
				return;
			}
			fileId = fileId[0];
			log(fileId);
			var linkText = '<a title="page-link-' + fileId + '" href="#">';
			if(files.indexOf(fileId) != -1) {
				linkText += '(Remove from my prospectus)';
			} else {
				linkText += '(Add to my prospectus)';
			}
			linkText += '</a>';
			$(this)
				.append(" - download")
				.after($(linkText).addClass('my-prospectus-link').click(function (e) {
																			e.preventDefault();
																			if(files.indexOf(fileId) != -1) {
																				removeFile(fileId);	
																				$(this).text('(Add to my prospectus)');
																			} else {
																				addFile(fileId);
																				$(this).text('(Remove from my prospectus)');
																			}
																	   }));
		});
	}
	
	function showBar() {
		log('show bar');
		log($("#my-prospectus-bar").length);
		if($("#my-prospectus-bar").length == 0) {
			$("body").addClass("my-prospectus-body");
			$("body").prepend('<div id="my-prospectus-bar"></div>');
			$('#my-prospectus-bar').append('<a href="#" id="my-prospectus-add-remove-button">add/remove pages <span id="fileCount">(' + files.length + ' page' + (files.length > 1? 's' : '') + ')</span></a>');
			$('#my-prospectus-bar').append('<a href="#" id="my-prospectus-create-button">create my prospectus</a>');
			$('#my-prospectus-bar').append('');
			$('#my-prospectus-bar').append('');
			$('#my-prospectus-bar').append('');
			$('#my-prospectus-add-remove-button').click(function (e) {
				e.preventDefault();
				showDialog("Your Prospectus");
			});
			$('#my-prospectus-create-button').click(function (e) {
				e.preventDefault();
				showDialog("Create Your Prospectus");
			});
			if($('#secureBar').length > 0) {
				$('#secureBar').css('top', ($('#my-prospectus-bar').height() + parseInt($('#my-prospectus-bar').css("borderBottomWidth"))) + "px");
			}
		} else {
			$('#fileCount').html('(' + files.length + ' page' + (files.length > 1? 's' : '') + ')');
		}
	}
	
	function addFile(id) {
		files.push(id);
		maxLengthOnPage += 1;
		$.cookie('myProspectus', files, {path:'/', expires:1});
		if(files.length > 0) {
			showBar();
		}
		if(files.length == 1 && files.length > initLength && maxLengthOnPage == 1 && $('#admin_dialogBox').length == 0) {
			showDialog("welcome");
		} else if($('#admin_dialogBox').length == 0) {
			showBubble(true);	
		}
	}
	
	function removeFile(id) {
		if(files.indexOf(id) != -1) {
			files.splice(files.indexOf(id), 1);
			$.cookie('myProspectus', files, {path:'/', expires:1});
			showBar();
		}
		if(files.length == 0) {
			$('#my-prospectus-bar').remove();
			$("body").removeClass("my-prospectus-body");
			$.cookie('myProspectus', null, {});
			if($('#secureBar').length > 0) {
				$('#secureBar').css('top', 0 + "px");
			}
		} else if(!inDialog) {
			showBubble(false);	
		}
		$('.my-prospectus-link').each(function () {
												if($(this).attr('title') == 'page-link-' + id) {$(this).text('(Add to my prospectus)');}
												});
	}
	
	function showBubble(bool) {
			$('#my-prospectus-bar #fileCount').qtip({
				content: {
					text: (bool ? 'The file has been added to your prospectus' : 'A file has been removed from your prospectus')
				},
				show: { when: false, ready: true, solo:true},
				hide: { when: { event: 'unfocus' }, delay: 20000},
				target: $('body'),
				style: {
					tip:'topMiddle',
					border: {
						radius: 4,
						width: 0.1,
						color: '#CCCCCC'
					}
				},
				position: {
					corner: {
						target:'bottomMiddle',
						tooltip:'topMiddle'
					}
				},
				textAlign: 'center',
				width: 80
		});
	}
	
	function showDialog(type) {
		inDialog = true;
		if(type == "welcome") {
			$('body').e4eDialog({
				diagTitle:type,
				content:'<p>Welcome to the prospectus builder, using this tool you can add the pages you want to read. At the top of the screen you will see two links, "add/remove pages" and "create my prospectus".</p><h2 class="my-prospectus-builder-full-width-title">Adding and Removing Pages</h2><p>To add pages to your prospectus you can either navigate around the website adding pages whereever you see the "(add to my prospectus)" link. Alternatively if you click on "add/remove pages" you can see a full list of pages from throughout the website that you can add to your prospectus. Within the box that appears you can either click on the <img src="/_includes/prospectus-builder/images/icons/add.png" alt="add icon" /> button next to the file which will add it to the bottom of your prospectus, or drag the item using the <img src="/_includes/prospectus-builder/images/icons/moveAll.png" alt="move" /> icon to place the file where you would like it in the list.</p><p>Once an item is in the list you can change its position by either dragging it up or down using the <img src="/_includes/prospectus-builder/images/icons/move.png" alt="move up and down" /> icon.</p><p>To remove a page from your prospectus click on the "add/remove pages" link and then in the column with the title "Your Files" remove a page by clicking on the <img src="/_includes/prospectus-builder/images/icons/remove.png" alt="remove" /> icon.</p><h2 class="my-prospectus-builder-full-width-title">Creating your prospectus</h2><p></p>When you have added and ordered all the files you wish into your prospectus click on the "create my prospectus" link. In the screen that follows you will have the option of emailing yourself a copy of the prospectus you have created or alternatively you can wait for the prospectus to be created and it will then be shown automatically when it has been completed.',
				close: function () {inDialog = false;}
			});
		} else if(type == "Your Prospectus") {
			$('body').e4eDialog({
				diagTitle:type,
				close: function () {inDialog = false;}
			});
			if(fullFileList != '') {
				loadList();
			} else {
				$.getJSON('/_includes/prospectus-builder/code/attachment_list.asp?pid=' + pageList, function (data, textStatus) {
						log(data);
						fullFileList = data;
						loadList();
					});
			}
		} else if(type == 'Create Your Prospectus') {
			$('body').e4eDialog({
				diagTitle:type,
				content:'<div id="prospectus-builder-list-create"></div><div id="prospectus-builder-create-options"></div>',
				height:300,
				close: function () {inDialog = false;},
				buttons: ['create'],
				buttonFunctions: [submitCreateForm]
			});
			if(fullFileList != '') {
				for(var i=0; i<files.length; i++){
						if(!isNaN(parseInt(files[i]))) {
							var li = $('<li title="' + getFileName(files[i]) + '" class="prospectus-builder-create-pdf-li"><p>' + getFileName(files[i]) + '</p></li>');
					  		$('#prospectus-builder-list-create').append(li);
						}
				}
			} else {
				$.getJSON('/_includes/prospectus-builder/code/attachment_list.asp?pid=' + pageList, function (data, textStatus) {
					log(data);
					log(textStatus);
					fullFileList = data;
					for(var i=0; i<files.length; i++){
						if(!isNaN(parseInt(files[i]))) {
							var li = $('<li title="' + files[i] + '" class="prospectus-builder-create-pdf-li"><p>' + getFileName(files[i]) + '</p></li>');
							$('#prospectus-builder-list-create').append(li);
						}
					}
				 });
			}
			$('#prospectus-builder-create-options').append('<p>Your current prospectus is show to the left. To edit this further please close this box and select the\'add/remove pages\' link from the top of the screen.</p><p>To recieve your prospectus via email please fill in the box below.</p><p><form id="prospectus-builder-form"><label for="prospectus-builder-email-field">Email:</label> <input id="prospectus-builder-email-field"/></p><p>When you are ready click on create to produce your customised prospectus.</form></p>');
		}
	}
	var jobID;
	function submitCreateForm() {
		var fileListString = "";
		for(var i=0; i<files.length; i++){
			if(!isNaN(parseInt(files[i]))) fileListString += files[i];
			if(i != files.length - 1) fileListString += ",";
		}
		log(fileListString);
		if($("#prospectus-builder-form").length > 0) {
			log('form submitted');
			$('#admin_button_create').css('display', 'none');
			$.post('/_includes/prospectus-builder/code/prospectus-builder-start.asp', {pages:fileListString, email:$('#prospectus-builder-email-field').val()}, function(data) {
				if(data.status == 'ok') {
					jobID = data.jobID
					$('#admin_dialog_content').children().remove();
					$('#admin_dialog_content').append('<div id="prospectus-builder-create-status"><p>your file has been added to the queue to be created</p></div>');
					
					createStatus(data);
				}
				
			},'json');
		}
	}
	
	function createStatus(data) {
		$.getJSON('/_includes/prospectus-builder/code/prospectus-builder-status.asp?jobID=' + jobID, function (data) {
			log(data.status);
			if (data.status == 'Finished processing') {
				$('#prospectus-builder-create-status').children().remove()
				$('#prospectus-builder-create-status').append('<p>Your prospectus has been created successfully. Please <a target="_blank" href="' + data.statusDetails.link + '">click here</a> to view it.</p>');
				$('#prospectus-builder-create-status').css('background', 'transparent url(/_includes/prospectus-builder/images/accept.png) left center no-repeat');
				$('#prospectus-builder-create-status').css('marginLeft', '117px');
				$('#prospectus-builder-create-status').css('paddingLeft', '25px');
				$('#prospectus-builder-create-status').css('paddingTop', '0px');
				log(data.statusDetails.link);
			} else {
				setTimeout(createStatus,1000);
				if(data.status != 'error') {
					$('#prospectus-builder-create-status').children().remove();
					if(data.statusDetails != undefined && data.statusDetails.status != undefined) {
						$('#prospectus-builder-create-status').append('<p>' + data.statusDetails.status + '</p>');
					} else {
						$('#prospectus-builder-create-status').append('<p>' + data.status + '</p>');
					}
				}
			}
		});
	}
	
	function getFileName(id) {
		for(var i=0; i<fullFileList.length; i++){
			if(parseInt(fullFileList[i]['id']) == id) {
				return fullFileList[i]['name'];
			}
		}
	}
	
	function loadList() {
		if($('#admin_dialog_content').length > 0) {
			$('#admin_dialog_content').html('<div id="prospectus-builder-list-intro">This is the intro for the prospectus builder, the left shows all available files whilst the right shows your current prospectus and the files you have added to it.</div><h2>All Files</h2><h2>Your Files</h2><ul id="prospectus-builder-list-full"></ul><ul id="prospectus-builder-list-current"></ul>')
			if($('#admin_dialog_content').length > 0) {
				var pageTitle = "";
				$('#prospectus-builder-list-full').children().remove();
				log(fullFileList);
				for(var i=0; i<fullFileList.length; i++){
					if(fullFileList[i]['pageTitle'] != pageTitle) {
						pageTitle = fullFileList[i]['pageTitle'];
						log(pageTitle);
						var heading = $('<li class="prospectus-builder-page-heading">' + pageTitle + '</li>');
						$('#prospectus-builder-list-full').append(heading);
					}
					var page = $('<li title="' + fullFileList[i]['id'] + '" class="prospectus-builder-page-li' + (files.indexOf(fullFileList[i]['id']) == -1 ? "" : " prospectus-builder-page-li-selected") + '"><span class="handle"><span>move</span></span><p>' + fullFileList[i]['name'] + '</p></li>');
					var add = $('<a href="#" title="' + fullFileList[i]['name'] + '" class="prospectus-builder-add-button"><span>add</span></a>');
					page.append(add);
					$('#prospectus-builder-list-full').append(page);
					$(add).click(function () {
						$(this).parent().slideUp(300, function(e) {
							$(this).addClass('prospectus-builder-page-li-selected');
							var fileName = getFileName($(this).attr("title"));
							var newNode = $('<li title="' + $(this).attr("title") + '" class="prospectus-builder-pdf-li"><span class="handle"><span>move</span></span><p>' + fileName + '</p></li>');
							var remove = $('<a href="#" title="' + fileName + '" class="prospectus-builder-remove-button"><span>remove</span></a>');
							$(remove).click(nodeRemoved);
							$(newNode).append(remove);
							$('#prospectus-builder-list-current').append(newNode);
							$(newNode).slideDown(300);
							log($(newNode).parent());
							addFile($(this).attr("title"));
						});
					});
				}
				
				$('#prospectus-builder-list-current').children().remove();
				for(var i=0; i<files.length; i++){
						if(!isNaN(parseInt(files[i]))) {
							var fileName = getFileName(files[i]);
							var li = $('<li title="' + files[i] + '" class="prospectus-builder-pdf-li"><span class="handle"><span>move</span></span><p>' + fileName + '</p></li>');
							var remove = $('<a href="#" title="' + fileName + '" class="prospectus-builder-remove-button"><span>remove</span></a>');
					  		$('#prospectus-builder-list-current').append(li);
							$(li).append(remove);
							$(remove).click(nodeRemoved);
						}
				}
				$("#prospectus-builder-list-current").sortable({
					axis:'y',
					handle:'.handle',
					placeholder: 'ui-state-highlight',
					beforeStop: function (event, ui) {
						if($(ui.helper).hasClass('prospectus-builder-page-li')) {
							$('#prospectus-builder-list-full').children().each(function () {
								if($(this).attr("title") == $(ui.helper).attr('title')) {
									$(this).slideUp(300, function(e) {$(this).addClass('prospectus-builder-page-li-selected');});
								}
							});
							var fileName = getFileName($(ui.helper).attr("title"));
							var newNode = $('<li title="' + $(ui.helper).attr("title") + '" class="prospectus-builder-pdf-li"><span class="handle"><span>move</span></span><p>' + fileName + '</p></li>');
							var remove = $('<a href="#" title="' + fileName + '" class="prospectus-builder-remove-button"><span>remove</span></a>');
							$(remove).click(nodeRemoved);
							$(newNode).append(remove);
							$(ui.placeholder).after(newNode);
							$(newNode).slideDown(300);
							addFile($(ui.helper).attr("title"));
						}
					},
					stop: function(event, ui) {
							files = [];
							$('#prospectus-builder-list-current .prospectus-builder-page-li').each(function () {log($(this).remove());});
							$("#prospectus-builder-list-current li").each(function () {
																					files.push($(this).attr('title'));
																					});
							$.cookie('myProspectus', files, {path:'/', expires:1});
							
							
					}
				}).disableSelection();
				$('#prospectus-builder-list-full li').draggable({
					handle:'.handle',
					connectToSortable: '#prospectus-builder-list-current',
					opacity:0.7,
					helper:'clone',
					containment: '#admin_dialog_content'
				}).disableSelection();
			}	
		}
	}
	
	function nodeRemoved() {
		$(this).parent().slideUp(300, function() {
			removeFile($(this).attr('title'));
			$(this).remove();
			var fileId = $(this).attr('title');
			$('#prospectus-builder-list-full').children().each(function () {
				if($(this).attr("title") == fileId) {
					$(this).slideDown(300);
					$(this).removeClass('prospectus-builder-page-li-selected');
				}
			})
		});
	}
	
	function log(str, type) {
		if(console) {
			if(type == "warning") {
				console.warn(str);
			} else if(type == "error") {
				console.error(str);
			} else if(type == "info") {
				console.info(str);
			} else if(type == "debug") {
				console.debug(str);
			} else {
				console.log(str);	
			}
		}
	}			
	
	if(!Array.indexOf){
      Array.prototype.indexOf = function(obj){
          for(var i=0; i<this.length; i++){
              if(this[i]==obj){
                  return i;
              }
          }
          return -1;
      }
  }
					
	//log("document ready");
	if(myProspectus) {
		//log("check for attachment");
		files = $.cookie('myProspectus') === null ? [] : $.cookie('myProspectus').split(',');
		if(!files.push) {
			files = [];
		}
		//log(files.length);
		maxLengthOnPage = initLength = files.length;
		checkAttachment();
		if(files.length > 0) {showBar();}
	} else {
		//log("do not change page");
	}
	

});

