(function($){
	$.fn.FrontviewAdmin = function(options) {
		options = options || {};
		// set default values for required options
		options = $.extend({
			requestUrl  : "admin3/frontview_admin.php",
			minWidth    : null,
			hint		: 'Doubleclick to edit',
			onError     : function() {
				// starts if the request-script returns the string "false"
				alert('An error occurred.');
			},
			onSuccess   : function() {
				// starts if the request-script returns NOT the string "false"
			}
		}, options);
		this.each(function(){
			new jQuery.FrontviewAdmin(this,options);
		});
		return this;
	};
	

	$.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            }
            style = window.getComputedStyle(dom, null);
            for(var i=0;i<style.length;i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                if (camel.substr(0,3)=='Moz') continue;
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            }
            return returns;
        }
        if(dom.currentStyle){
            style = dom.currentStyle;
            for(var prop in style){
                returns[prop] = style[prop];
            }
            return returns;
        }
        return this.css();
    }

	jQuery.FrontviewAdmin = function(actual, options) {
		var changing = false;

		function save(content,elem) {
			if (content!="") {
				postData = options.postData || {};
				postData = $.extend({
				'content' : content,
				'action':'save'
				}, options.postData);
				// post postData and get new content from options.requestURL
				$.post(options.requestUrl,postData,function(data, status){
					if (data.result){
						$(elem).html(data.val);
						options.onSuccess();
					}else{
						options.onError();
					}
				},"json");
			}
			changing = false;
			return false;
		}

		var w = $(actual).width() + 1;
		$(actual)
			.wrap('<span style="position:relative" class="frontview_wrapper"><div class="frontview_current" style="width:'+w+'px"></div></span>')
			.parent().after('<div style="width:'+w+'px;position:relative"><input style="right:0px" class="frontview_button frontview_edit" type="button" value="edit" /></div>')
			.closest('.frontview_current').css({'border':'1px dotted #888888'});
		
		var $all = $(actual).closest('.frontview_wrapper');
		$all.append('<div class="frontview_editor" style="display:none;width:'+w+'px"></div><div style="position:relative;display:none;width:'+w+'px;"><input class="frontview_button frontview_save" type="button" value="save" style="right:55px" /><input class="frontview_button frontview_cancel" type="button" value="cancel" /></div>');
		
		$all.find('.frontview_edit').click(function(){
			if(!changing){
				
				options = $.extend({
				postData:{
					'modul':$(actual).attr('modul'),
					'field':$(actual).attr('field'),
					'record':$(actual).attr('record')
					}
				}, options);
						
				width  = ($(actual).width() < options.minWidth)?options.minWidth:$(actual).width()+5;

				var textarea = document.createElement('textarea');
				
				$(actual).closest('.frontview_current').removeClass('frontviewadmin_hover')
				$(textarea).css($(actual).getStyleObject());

				$(textarea).css({
				'width'  : width+'px',
				'height' : $(actual).height()+'px'
				});
				$(textarea).focus(function(){
					$(this).css({'border':'1px dotted #B2ED00'});
				}).blur(function(){
					$(this).css({'border':'1px dotted #888888'});
				});
				
				$(textarea).keyup(function(){
					if ($(this).scrollTop()>0) {
						$(this).css({'height':($(this).height()+$(this).scrollTop())});
						h = ($(this).height()-15) * -1;
						$all.find('.frontview_editor').css('bottom',h+'px');
					}
				});
				
				$.post(options.requestUrl,options.postData,function(data, status){
					val = data.val;
					val = val.replace(/\n/g,"").replace(/\r/g,"").replace(/<br\s*\/?>/img,"\n");
					$(textarea).html(val).focus();

					if ($(textarea).scrollTop()>0) {
						$(textarea).css({'height':($(textarea).height()+$(textarea).scrollTop())});
						h = ($(textarea).height()-15) * -1;
						$all.find('.frontview_editor').css('bottom',h+'px');
					}
				},"json");

				//$(textarea).html($(actual).html().replace(/<br\s*\/?>/img,"\n"));
				
				//$all.find('.frontview_current').next().andSelf().css('display','none');
				//$all.find('.frontview_editor').html(textarea).next().andSelf().css('display','block');
				
				$all.find('.frontview_editor').html(textarea);
				$all.find('.frontview_current').next().fadeOut(300,function(){
					$all.find('.frontview_current').css('display','none');
					$all.find('.frontview_editor').css('display','block').next().fadeIn(300,function(){
						/*
						while($(textarea).get(0).scrollHeight>$(textarea).height()){
							$(textarea).height($(textarea).height()+1);
						}
						*/
					});
				});
			

				$all.find('.frontview_cancel').click(function(){
					//$all.find('.frontview_current').next().andSelf().css('display','block');
					//$all.find('.frontview_editor').html(textarea).next().andSelf().css('display','none');
					
					$all.find('.frontview_editor').next().fadeOut(300,function(){
						$all.find('.frontview_editor').css('display','none');
						$all.find('.frontview_current').css('display','block').next().fadeIn(300);
					});
					
					changing = false;
				});
				$all.find('.frontview_save').click(function(){
					save($all.find('.frontview_editor>textarea').val(),$all.find('.frontview_current').find('.frontviewadmin'));
					$all.find('.frontview_editor').next().fadeOut(300,function(){
						$all.find('.frontview_editor').css('display','none');
						$all.find('.frontview_current').css('display','block').next().fadeIn(300);
					});
					changing = false;
				});

				changing = true;
			}
		}).hover(function(event){
			if(!changing){
				$(actual).closest('.frontview_current').addClass('frontviewadmin_hover');
			}
		},function(){
			if(!changing){
				$(actual).closest('.frontview_current').removeClass('frontviewadmin_hover');
			}
		}).find('.frontview_current').css({'border':'1px dotted #888888'});
					
					
	}
})(jQuery);
