$(document).ready(function(){
	
	$("#save").click(function(){
		ajaxSave( tinyMCE.get('content') );
	});
	
	$("#intro").fadeIn();

	var da = new Date;
	var rand_no = Math.ceil(100*Math.random()) + da.getTime();
	$("#id").val( rand_no );
		
	$(".user,.pass").clearOnFocus();

	$("#regBtn").click(function(){
		$("#intro").fadeOut();
		$("#regBox").fadeIn();
	});
	
	$("#cancelReg").click(function(){
		$("#regBox").fadeOut();
	});
	
	var images = new Array('pdf','logo','image1','image2','image3');
	
	$.each( images, function(){
		var id = this;
		new AjaxUpload('#'+ id, {
			autoSubmit: true,
			action: 'register.php',
			data: { 'id' : rand_no },
			name: id,
			onSubmit: function() { $("#"+ id +"Li span").html('<img src="images/ajax.gif" alt="" style="margin: 0 7px 0 7px;" />Uploading...'); },
			onComplete: function(file,response){
						if( response == 'success' ) {
							$("#"+ id +"Li span").html('<img src="images/tick.png" alt="" style="margin: 0 7px 0 7px;" />Uploaded');
						} else {
							//alert(response);
							$("#regBox").append(response);
							$("#"+ id +"Li span").html('<img src="images/x.png" alt="" style="margin: 0 7px 0 7px;" />Error');
						}
			}
		});	
	});
	
	//update images
	
	var uImages = new Array('pdf','logo','image1','image2','image3');
	
	$.each( uImages, function(){
		var id = this;
		new AjaxUpload('#u'+ id, {
			autoSubmit: true,
			action: 'doUpdate.php',
			name: id,
			onSubmit: function() { $("#u"+ id +"Li span").html('<img src="images/ajax.gif" alt="" style="margin: 0 7px 0 7px;" />Uploading...'); },
			onComplete: function(file,response){
						if( response == 'success' ) {
							$("#u"+ id +"Li span").html('<img src="images/tick.png" alt="" style="margin: 0 7px 0 7px;" />Uploaded');
						} else {
							//alert(response);
							$("#updateBox").append(response);
							$("#u"+ id +"Li span").html('<img src="images/x.png" alt="" style="margin: 0 7px 0 7px;" />Error');
						}
			}
		});	
	});
	
		
	$("#goRegister").click(function(){
			if( $("#regForm").valid() )
			{
				$.ajax({
				url: 'register.php',
				data: $('#regBox form').serialize(),
				type: 'post',
				cache: false,
				dataType: 'html',
				complete: function (xhr) {
					if( xhr.responseText == 'success' )
					{
						$('#regBox').animate( { 'height' : '50px' } ).html('<p style="margin: 2px 0 0 auto; color:#383939;text-align:center;line-height: 32px;font-size: 14px;height:32px;"><img src="images/tick32.png" alt="" style="padding-right:8px;position: relative; bottom: -10px" />Registration Successful, you may now login above. Once logged in, click the edit page button, which will appear above.</p>');
						setTimeout(function(){
							$('#regBox').fadeOut();
							$('#regBtn').fadeOut();
						},5000);
					}
					else
					{
						alert( xhr.responseText );
					}
				}
			});
		}
	});
	
	$("#regForm").validate({
		rules : {
			name: { required: true },
			email: { required: true, email: true },
			password: { required: true, minlength: 5 },
			confirm: { required: true, equalTo: "#password" },
			city:	{ required: true },
			country: { required: true },
			captcha: { required: true, equalTo: "#cid" }
		},
		messages : {
			captcha: {
				equalTo : 'Please enter the numbers from the box below'
			}
		}
	});
	
	
	
	$("#goUpdate").click(function(){
			if( true )
			{
				$.ajax({
				url: 'doUpdate.php',
				data: $('#updateBox form').serialize(),
				type: 'post',
				cache: false,
				dataType: 'html',
				complete: function (xhr) {
					if( xhr.responseText == 'success' )
					{
						var oldHtml = $('#updateBox').html();
						var oldHeight = $('#updateBox').css('height');
						$('#updateBox').animate( { 'height' : '50px' } ).html('<p style="margin: 2px 0 0 auto; color:#383939;text-align:center;line-height: 32px;font-size: 14px;height:32px;"><img src="images/tick32.png" alt="" style="padding-right:8px;position: relative; bottom: -10px" />Thank you, your details have been ammended.</p>');
						setTimeout(function(){
							$('#updateBox').fadeOut();
							setTimeout(function(){
								$('#updateBox').html(oldHtml);
								$('#updateBox').css('height',oldHeight);
							},900);
						},5000);
					}
					else
					{
						alert( xhr.responseText );
					}
				}
			});
		}

	});
	
	$("#updateForm").validate({
		rules : {
			name: { required: true },
			email: { required: true, email: true },
			city:	{ required: true },
			country: { required: true },
		}
	});
	
	
	
	
	$("#loginBtn").click(function(){
		$.ajax({
			url: 'login.php',
			data: $('#loginForm').serialize(),
			type: 'post',
			cache: false,
			dataType: 'html',
			complete: function (xhr) {
				var resp = xhr.responseText.split('|');
				if( resp[0] == 'success' )
				{
					$("#menu").html('<p style="float: left;">Logged In as: <strong>'+resp[1]+'</strong>'
									+'<div  id="editBtn" class="link">Edit Page</div>'
									+'<div id="updateBtn" class="link">Update Info</div>');
					$("#editBtn").click(function(){
						$.ajax({
							url: 'getpage.php',
							data: 'edit=true',
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								tinyMCE.activeEditor.setContent(xhr.responseText);
								$('#editPage').fadeIn();
							}
						});
					});
					
					$("#updateBtn").click(function(){
						$.getJSON("getupdate.php",{ajax: '1'}, function(j){
							$('#uOrganisation').val( j.organisation );
							$('#uName').val( j.name );
							$('#uEmail').val( j.email );
							$('#uTelephone').val( j.telephone );
							$('#uHouseno').val( j.houseno );
							$('#uStreet').val( j.street );
							$('#uCity').val( j.city );
							$('#uCountry').val( j.country );
							$('#uPostcode').val( j.postcode );
						});
					});
                                                $("#updateBtn").click(function(){
                                                    $("#updateBox").fadeIn();
                                        	});

				}
				else
				{
					$("#menuRight").html('Login Failed');
				}
			}
		});
	});
	
	
	setTimeout(function(){
		$.get('getCap.php', 
			function(data){
				$("#cid").val( data );
			}
		);
	}, 4000 );

});


var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function logout()
{
	$.get('logout.php');
}

function deletePage( userId )
{
	var ans = confirm('Are you sure you want to delete this user?');
	if( ans ) 
	{
		$.ajax({
			url: 'deletepage.php',
			data: 'del=true&userId='+userId,
			type: 'post',
			cache: false,
			dataType: 'html',
			complete: function (xhr) {
				$("#uk1").animate({ 'height' : '50px' }).html('<p style="margin: 2px 0 0 auto; color:#383939;text-align:center;line-height: 32px;font-size: 14px;height:32px;"><img src="images/tick32.png" alt="" style="padding-right:8px;position: relative; bottom: -10px" />Page Deleted.</p>');
				setTimeout(function(){
					$("#uk1").fadeOut();
				},1000 );
				
			}
		});
	}
}

function editPage( userId )
{

	$.ajax({
		url: '/2010/getpage.php',
		data: 'edit=true&userId='+userId,
		type: 'post',
		cache: false,
		dataType: 'html',
		complete: function (xhr) {
			tinyMCE.activeEditor.setContent(xhr.responseText);
			$('#editPage').fadeIn();
		}
	});
				
}

function encode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	
	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);
		
		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;
		
		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}
		
		output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
		keyStr.charAt(enc3) + keyStr.charAt(enc4);
	} while (i < input.length);
	
	return output;
}


function ajaxSave(ed) {
	//var ed = tinyMCE.get('content');
	ed.setProgressState(1); // Show progress
	postPage( ed.getContent(), ed );
}

function postPage(body, ed) {
	var poststr = encodeURIComponent( body );
	$.ajax({
		url: '/2010/savepage.php',
		data: 'body='+poststr,
		type: 'post',
		cache: false,
		dataType: 'html',
		complete: function (xhr) {
			ed.setProgressState(0); // Hide progress
			$("#editPage").fadeOut();
		}
	});
}

	tinyMCE.init({
		 mode : "textareas",
		 elements : "page_edit",
		 theme : "advanced",
		 skin : "o2k7",
		 skin_variant : "silver",
		 plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",
		 width: '650px',
		 height: '492px',
		 
		 // Theme options
		 theme_advanced_buttons1 : "save,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect",
		 theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,hr,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		 theme_advanced_toolbar_location : "top",
		 theme_advanced_toolbar_align : "left",
		 theme_advanced_statusbar_location : "bottom",
		 theme_advanced_resizing : true
	});  
