var TinyGrab = (function(){
	
	if (window.jQuery === undefined) {
		return false;
	}
	
	function makeDraggable(elem) {
		/* Mousemoving stufff */
		var down = false,
			x = 0, y = 0;
		
		elem.mousedown(function(e){
			down = true;
			x = e.pageX + elem.scrollLeft();
			y = e.pageY + elem.scrollTop();
			elem.css('cursor', 'url(/site/resources/images/closedhand.cur), pointer');
			return false;
		});
		
		elem.css('cursor', 'url(/site/resources/images/openhand.cur), pointer');
		
		$(document)
			.mousemove(function(e){
				if (down) {
					elem.scrollLeft(
						x - e.pageX
					);
					elem.scrollTop(
						y - e.pageY
					);
					return false;
				}
			})
			.mouseup(function(){
				elem.css('cursor', 'url(/site/resources/images/openhand.cur), pointer');
				down = false;
			});
	}
	
	function findSize(img) {
		return;
	}
	
	function preload(arr) {
		$.each(arr, function(i, item){
			(new Image()).src = item;
		});
	}
	
	preload([
		'/site/resources/images/load.gif',
		'/site/resources/images/openhand.cur',
		'/site/resources/images/closedhand.cur'
	]);
	
	return {
		all: function(){},
		register: function() {
			
			$('input:text')
				.focus(function(){
					if (this.value === this.defaultValue) {
						this.value = '';
					}
				})
				.blur(function(){
					if (/^\s*?$/.test(this.value)) {
						this.value = this.defaultValue;
					}
				});
			
		},
		panel: function() {
			
			var getLarge = function(src){
					return src.replace('/thumbs','');
				},
				zSettings = {
					width: 100,
					height: 100,
					mousewheelZoom: !$.browser.msie,
					zoomerOverlay: {
						radialOpacity: 0.2,
						shadowWidth: 5
					}
				};
			
			$('table.norm img')
				.css({
					cursor: 'pointer'
				})
				.click(function(){
					
					var self = this;
					
					$(document).unbind('mousemove.zoomer');
					$('#preview-pane').remove();
					
					var imgContainer = $('<div/>').css({
						overflow: 'hidden',
						height: 200,
						width: 450,
						margin: '0 0 10px 0',
						border: '1px solid #CCC'
					});
					
					var img = $('<img src="' + getLarge(self.src) + '" />').hide();
					imgContainer.append(img);
					
					img.load(function(){
						
						img.show();
						previewPane.css({'background': ''});
						
						var height = this.naturalHeight || this.height || $(this).height();
						$('div', previewPane).height( Math.min(height, 200) );
						
					});
					
					var previewPane = $('<div id="preview-pane" />').append(
						$('<h2>Preview</h2>').append(
							$('<a href="#"> (CLOSE)</a>').click(function(){
								img.add(document).unbind('.zoomer');
								previewPane.hide();
							})
						).add(imgContainer)
					);
					previewPane.css({background: 'url(/site/resources/images/load.gif) no-repeat center center'}).prependTo('#rightcol');
					
					makeDraggable(imgContainer);
				});
			
			
			/* Scrolling (fixed) */
			var rightcol = $('#rightcol'),
				leftcol = $('#leftcol'),
				rcLeft = rightcol.offset().left,
				width = rightcol.width(),
				top = rightcol.offset().top + 20;
			
			$(window).scroll(function(){
				var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
				if (scrollTop > top) {
					rightcol.css({
						position: 'fixed',
						left: rcLeft,
						top: 20,
						width: width
					});
					
					/* Check if it's reached the footer */
					var difference = (rightcol.offset().top + rightcol.height()) - (leftcol.offset().top + leftcol.height());
					if (difference > 0) {
					    rightcol.css('top', -difference);
					}
					
				} else {
					rightcol.css({
						position: 'static'
					});
				}
			});
			
			$(window).resize(function(){
				rightcol.css('position','static');
				rcLeft = rightcol.offset().left;
			});
			
			
			(function(){
				/* /edit/previewer... */
				var href = $('tr:eq(2)').find('a').attr('href');
				var pathname = window.location.pathname;
				if (href && (pathname.search("/go/panel/grabs") >= 0 || pathname.search("/go/panel/edit") >= 0)) {
					var row = $('<tr/>').hide().append('<td>Preview</td><td><div><img src="' + href + '"/></div></td>');
					var contain = row.find('div').css({
						width: $('tr:eq(1) > td:eq(1)').outerWidth(),
						overflow: 'hidden',
						height: 0
					});
					row.find('img').load(function(){
						contain.height( Math.min(120, this.naturalHeight || this.height || $(this).height()) );
						row.css('display', '');
						contain.width( contain.parent().width() );
						makeDraggable(contain);
					});
					row.insertAfter('tr:eq(0)');
				}
			})();
				
		}
	};
	
})();

var JSHTML = {
    config : {
        flag : '',
        delimiters : ['{{','}}'],
        fragmentCallback : function(){},
        template : {}
    },
    parse : function() {
        var config = this.config,
            flagRegex = new RegExp('\\s*?' + config.flag + '\\s*?' + config.delimiters[0] + '(.+)' + config.delimiters[1] + ''),
            context = arguments[0] || document.documentElement,
            nodes = context.childNodes,
            nLen = nodes.length,
            current, match,
            makeFrag = function(str) {
                var tempDiv = document.createElement('div'),
                    frag = document.createDocumentFragment(),
                    replacement = function($0, $1) {
                        return config.template[$1] || $0;
                    },
                    node;
                tempDiv.innerHTML = str.replace(/^\s+|\s+$/g,'').replace(/\{(.+?)\}/g, replacement);
                while ( (node = tempDiv.firstChild) ) {
                    frag.appendChild(node);
                }
                try { config.fragmentCallback.call(frag); }
                catch(e) {
                    setTimeout(function(){ throw new Error(e); }, 0);
                }
                return frag;
            };
        while (nLen--) {
            current = nodes[nLen];
            if (current.nodeType !== 8) {
                arguments.callee.call(this, current);
                continue;
            }
            match = flagRegex.exec(current.data.replace(/[\n\r]/g,''));
            if (!match) { continue; }
            current.parentNode.replaceChild(makeFrag(match[1]), current);
        }
    }
};

jQuery(document).ready(function($){
	
	TinyGrab.all();
	
	var sec = window.location.href.match(/go\/(.+?)(\/|$)/);
	
	
	if (sec) {
		if ( TinyGrab[sec[1]] ) {
			TinyGrab[sec[1]]();
		}
	}
	
	JSHTML.parse( document.body );
	
});





/*


var TinyGrab = (function(){
	
	if (window.jQuery === undefined) {
		return false;
	}
	
	function findSize(img) {
		
	}
	
	return {
		panel: function() {
			
			var getLarge = function(src){
					return src.replace('/thumbs','');
				},
				zSettings = {
					width: 100,
					height: 100,
					mousewheelZoom: !$.browser.msie,
					zoomerOverlay: {
						radialOpacity: 0.2,
						shadowWidth: 5
					}
				};
			
			$('table.norm img')
				.css({
					cursor: 'pointer'
				})
				.click(function(){
					
					var self = this;
					
					$(document).unbind('mousemove.zoomer');
					$('#preview-pane').remove();
					
					var img = $('<div/>').append('<img src="' + getLarge(self.src) + '" />');
					img.css({
						width: 450,
						display: 'none'
					});
					
					var previewPane = $('<div id="preview-pane" />').append(
						$('<h2>Preview</h2>').append(
							$('<a href="#"> (CLOSE)</a>').click(function(){
								img.add(document).unbind('.zoomer');
								previewPane.hide();
							})
						).add(img)
					);
					previewPane
						.css({
							background: 'url(/site/resources/images/load.gif) no-repeat center center',
							height: 300
						})
						.prependTo('#rightcol');
					
					img.load(function(){
						var size = findSize(this);
						//if (size.height < )
						previewPane.css('height','auto');
						img.show();
						setTimeout(function(){
							img.zoomer(zSettings);
						}, 300);
					});
				});
				
		}
	};
	
})();


*/