/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype

(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" && 
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
            
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    Class.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
    
    return Class;
  };
})();

$.fn.extend({
insertAtCursor: function(myValue){
  this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
  }
});

var Ideadrop = Class.extend({
	SCRIPT_NAME: window.location.pathname,
	dialogVisible: false,
	user: null,
	privs: {},
	strings: {
		login:'Login',
		logout:'Logout'
	},
	init: function() {
		var self = this;
		$('a.external').each(function(i,e) {
			e.target='_blank';
		});	
	
		$('.autosubmit').change(function(e) {
			e.target.form.submit();
		});

		$('.confirm').click(function(e) {
			var msg = 'Are you sure?';
			if (!confirm(msg)) {
				e.preventDefault();
				return false;
			}
		});

		$(".id-calendar").datepicker({
		});

		$("input[type=checkbox].id-disable-previous").click(function(e) {
			var el = e.target;
			if (el.checked) {
				$(el).prev('input').val('').attr('disabled', el.checked);
			} else {
				$(el).prev('input').attr('disabled', el.checked);
			}
		});

		$(".sortable").sortable({
			update: function(event, ui) {
				var data = 'action=update_list&list_id='+this.id+'&data_id='+$(this).attr('data_id')+'&'+$(this).sortable('serialize');
				var reload = $(this).hasClass('reload');
				$.ajax({
					url:self.SCRIPT_NAME,
					type: 'post',
					dataType: 'json',
					data: data,
					success: function(data) {
						if (self.isError(data)) {
							alert(data.error_message);
						} else {
						    if (reload) {
						        window.location.reload();
						    }
						}
					},
					error: function(xml, status) {
						alert('Error saving order');
					}
				});
			}
		});

		$('#dialog_box').keyup(function(e) {
			if (e.keyCode==27) { //esc
				self.hideDialogBox();
			}
		});
		
		// login handler
		$('.nav_login').click(function(event) {
			if (self.loggedIn()) {
				$('#dialog_box').load(URL_BASE + 'login.php?ajax_form&action=logout', function() {
					self.updateUser();
					self.showDialogBox();
					$('#login_cancel').click(function(e) { self.hideDialogBox(e) });
					window.location.reload();
				});
			} else {
				var referrer = window.location.pathname;
				$('#dialog_box').load(URL_BASE + 'login.php?ajax_form&referrer=' + escape(referrer), function() {
					self.showDialogBox();
					$('#login_form').submit(function(e) { self.loginSubmit(e) });
					$('#login_cancel').click(function(e) { self.hideDialogBox(e) });
					$('#login_email')[0].focus();	
				});
			} 
			event.preventDefault();
		});

		// nav hover handler
		$('#mainNav>li').hover(function(event) {
			$(this).addClass('hover');
			$(this).children('ul').fadeIn('fast');
		}, function() {
			$(this).children('ul').fadeOut('fast');
			$(this).removeClass('hover');
		});
		
		$(this).bind('userUpdated', function() {
			$('#mainNav')[self.loggedIn()?'addClass':'removeClass']('loggedIn');
			if (self.loggedIn()) {
			} else {
				//clear out the admin list
				$('#admin_list').html('');
			}
		});

		$(this).bind('privsUpdated', function() {
			$('#admin_list').html('');
			$.each(self.privs, function(i, priv) {
				if (priv.url) {
					$('#admin_list').append('<li><a href="' + priv.url +'">'+priv.name+'</a></li>');
				}
			});
		});

		$(self).bind('privsUpdated', function() {
			if (self.hasPriv('content_admin')) {
				self.updateEditableContent();
			}
		});
		
		this.updateUser();
	},
	hasPriv: function(priv) {
		var r = false;
		$.each(this.privs, function(i,p) {
			if (p.priv==priv) {
				r = true;
				return false;
			}
		});
		return r;
	},
	updatePrivs: function() {
		var self = this;
		$.get(URL_BASE +'admin.php', {
			privs: ''
			}, function(data) {
				self.privs = data;
				$(self).triggerHandler('privsUpdated');
			},'json');
	},
	updateEditableContent: function() {
		var self = this;
		$('.upload_button').remove();
		$('.upload_element').each(function(i,element) {

			var re = $(element).attr('upload_id').match(/([a-z0-9]+)_(\d+|header)/);
			if (!re) { 
				alert('invalid id ' + $(element).attr('upload_id'));
				return;
			}
					
			$(element).attr('upload_id_base', re[1]).attr('upload_id_index', re[2]);
			var div = $('<div>').addClass('upload_button').css(
				{	'top':$(element).position().top,
					'left':$(element).position().left
				}
			);
			
			switch (element.nodeName)
			{
				case 'DIV':
					$(element).attr('upload_type','text');
					div.html('edit').css('left', $(element).position().left + $(element).width()-30);
					break;
				case 'IMG':
					$(element).attr('upload_type','image').attr('imageSrc', $(element).attr('src'));
					div.html('replace');
					break;
				default:
					return;
			}

			div[0].element = $(element);
			$(element).after(div);
		});

		$('.upload_button').click(function(e) {
			var el = e.target;
			var upload_type = el.element.attr('upload_type');
			var upload_id = el.element.attr('upload_id');
			if (!upload_type || !upload_id) {
				return;
			}
			e.preventDefault();
			$('#dialog_box').load(URL_BASE +'edit.php?upload_type=' + upload_type +'&upload_id='+ upload_id , function() {
				self.showDialogBox();
				$('#edit_cancel').click(self.hideDialogBox);
				$('#edit_add_image').click(function() {

					var index = 1;
					$('img.upload_element[upload_id^='+$(el.element).attr('upload_id_base')+']').each(function(i,e) {
						var idx = parseInt($(e).attr('upload_id_index'));
						if (!isNaN(idx) && idx>=index) {
							index = idx+1;
						}
					});
					
					var rendering_mode = $('#edit_text_form input:radio[name=rendering_mode]:checked').val();
					var image_id = $(el.element).attr('upload_id_base') +'_'+ index;
					var img = '';
					switch (rendering_mode)
					{
						case 'html':
							img = '<img src="images/upload/'+image_id+'.jpg" class="upload_element" upload_id="' + image_id +'">';
							break;
						case 'wiki':
							img = '[upload_image: '+ image_id+']';
							break;
					}
					$('#edit_text_text').insertAtCursor(img);
				});
				$('#edit_text_form').submit(function(e) {
					$.post(URL_BASE +'edit.php', {
						upload_type: upload_type,
						upload_id: upload_id,
						rendering_mode: $('#edit_text_form input:radio[name=rendering_mode]:checked').val(),
						edit_text: $('#edit_text_text').val()
					}, function(data) {
						if (self.isError(data)) {
							alert(data.error_message);
						} else {
							$(el.element).html(data);
							self.updateEditableContent();
							self.hideDialogBox();
						}
					}, 'json');
					e.preventDefault();
				});
				$('#upload_image_form').submit(function(e) {
					$('#uploadTarget').remove();

					$('<iframe src="about:blank" id="uploadTarget">').load(
						function(iframe) {
							var data = $(iframe.target).contents()[0].body.innerHTML;
							try {
								var result = eval("(" + data + ")");
								if (result.error_message) {
									$('#upload_result').html(result.error_message);
								} else {
									$('#upload_result').html('');
									var d = new Date();
									$(el.element).attr('src', $(el.element).attr('imageSrc')+'?t='+d.getTime());
									self.hideDialogBox();
									$('#uploadTarget').remove();
								}
							} catch(er) {
								if (data) {
									alert("Error: " + er);
								}
							}
						}
					).appendTo('#page');

					$('#upload_image_form').attr('target', 'uploadTarget');
					$('#upload_result').html('Uploading...');
				});
			});
				
		});
			
	},
	loggedIn: function() {
		return this.user ? this.user.userID : false;
	},
	setUser: function(user) {
		this.user = user;
		if (this.loggedIn()) {
			this.updatePrivs();
			$('.nav_login.nav_login_text').html(this.strings.logout);
		} else {
			this.privs = {};
			$('.nav_login.nav_login_text').html(this.strings.login);
			$('.upload_button').remove();
		}
		$(this).triggerHandler('userUpdated');
	},
	updateUser: function() {
		var self = this;
		$.get(URL_BASE +'login.php', {
			action: 'user'
			}, function(data) {
				self.setUser(data)
			},'json');
	},
	loginSubmit: function(event) {
		var self = this;
		var login_email = $('#login_email').val();
		var login_pword = $('#login_pword').val();
		if (login_email && login_pword) {
			$.post(URL_BASE +'login.php', {
				ajax_form: true, 
				login_email: login_email, 
				login_pword: login_pword,
				login_submit: true 
			}, 
			function(data) {
				if (self.isError(data)) {
					$('#login_messages').html(data.error_message);
				} else {
					self.updateUser();
					self.hideDialogBox();
				    window.location.reload();
				}
			}, 
			'json');
		}
		event.preventDefault();
	},
	showDialogBox: function() {
		scrollTo(0,0);
    	$('#dialog_box').css("left", Math.floor(($(window).width() - $('#dialog_box').outerWidth() ) / 2)+ $(window).scrollLeft() + "px");
		$('#dialog_box').fadeIn('fast');
		this.dialogVisible = true;
	},
	hideDialogBox: function() {
		$('#dialog_box').fadeOut('fast');
		this.dialogVisible = false;
	},
	isError: function(obj) {
		if (obj && 'object' == typeof obj) {
			if ('error_message' in obj) {
				return true;
			}
		}
		
		return false;
	}
});

var ideadrop;
$(document).ready(function(){
	ideadrop = new Ideadrop();
});

