$(function(){
	strong = function() {
		$('p > strong', '#middle').each(function() {
			$(this).parent().css('marginTop', '-15px');
			$(this).parent().css('marginLeft', '15px');
			$(this).parent().css('paddingBottom', '0px');
			$('<strong class="foo" style="display:block;cursor:pointer"><span style="width:12px;float:left;">+</span> '+$(this).text()+'</strong>').insertBefore($(this).parent());
			$(this).remove();
		});
		hideallfoo = function() {
			$('strong.foo', '#middle').each(function(){
				$(this).next().slideUp();
				var txt = $(this).html();
				myval = txt.replace(new RegExp(/\-/),'+');
				$(this).html(myval);
			});
		}
		hideallfoo();
		$('strong.foo', '#middle').click(function() {
			if ($(this).next().is(":hidden")) {
				hideallfoo();
				var txt = $(this).html();
				myval = txt.replace(new RegExp(/\+/),'-');
				$(this).html(myval);
				$(this).next().slideToggle();
			}
			else {
				var txt = $(this).html();
				myval = txt.replace(new RegExp(/\-/),'+');
				$(this).html(myval);
				$(this).next().slideToggle();
			}
		
		});
	};
	strong();
	
	Site.fixHeight();
    Site.fixLeftColumn();

	Scene.loadFirstImage();

	Form.checkForms();

    $('#scene-toggle, #viewpictures').click(function(){
		if ($(this).hasClass('loaded')) {
			Scene.toggle();
		}
		else {
			// else load the images
			Scene.handleImages();
			Scene.toggle();
			$(this).addClass('loaded');
		}
			return false;
    });


    $(window).resize(function() {
        Site.fixLeftColumn();
    });

	if (window.location.hash) {
        var hash = window.location.hash;
        hash = hash.replace('#', '');
		$('ul.links li a, ul.footerlinks li a').each(function(){
			if ($(this).attr('href') == hash) {
				Site.getPage(this,hash);
			}
		});
		if (hash == '/forms/register') Site.getPage($('#right a.reglink'), hash);
	}


	$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
	Site.trackExternal();
	
	$('.magic.text').live('blur', function() {
		if ($(this).val() != "") $(this).addClass("active");
		else $(this).removeClass("active");
	});
	
	if ($('.socialed').length) $('.socialed a').hover(function() {
		$('.socialtext').html($(this).find('img').attr('alt'));
	},function() {
		$('.socialtext').html('');
	}).attr('title', '');
	
	$('.register h4').click(function() {
		var f = $(this).parent();
		if (f.hasClass('open')) f.animate({height: "25px"}, "slow", function() { $(this).removeClass("open"); Site.fixLeftColumn(); });
		else f.addClass("open").animate({height: "230px"}, "slow", function() { Site.fixLeftColumn(); });
	});
	
	$('.share .open').live('click', function(e) {
		e.preventDefault();
	
		if ($(this).hasClass("active"))
			$('.share').stop().animate({height: '20px'}, "fast", function() {
				Site.fixLeftColumn();
				$('.share .open').removeClass("active");
			});
		else
			$('.share').stop().animate({height: '70px'}, "fast", function() {
				Site.fixLeftColumn();
				$('.share .open').addClass("active");
			});
	});
	
	$('.share2 .open').live('click', function(e) {
		e.preventDefault();
		$('#middle').attr('style', '').removeAttr('style');
		$('.share2').stop().animate({height: '129px'}, "fast", function() {
			Site.fixLeftColumn();
		});
	});
	
	$('.share2 .close').live('click', function(e) {
		e.preventDefault();
		$('.share2').stop().animate({height: '21px'}, "fast", function() {
			Site.fixLeftColumn();
		});
	});
	
	$('#middle').attr("style", "").removeAttr("style");
});

var Sendlink = {

	modal: function(bottle) {
        $.ajax({
            type: "POST",
            url: '/sendlink',
            data: "link="+bottle,
            dataType: 'html',
            success: function(html) {
            	$.snap({
            		html:'<div id="sendlink-holder">'+html+'</div>',
            		inputh: 510,
            		inputw: 300
                });
            }
        });
        return false;
    },
    
    submit : function(formid, holder){
        var url = $(formid).attr('action');
		var data = $(formid).serialize();
		$.ajax({
			type: "POST",
			url: url,
			data: data,
			dataType: 'html',
			success: function(data) {
                $('#'+holder).html(data);
			}
		});
        return false;
    }

};

var Unicode = {
	/* was C */
	lookupTable : {
		"\n": "\\n",
		"\r": "\\r",
		'"': '\\"',
		"\t": "\\t",
		"\b": "\\b",
		"\f": "\\f",
		"\\": "\\\\"
	},
	/* was D() */
	asciiToUnicode : function(str) {
		return this.lookupTable[str] || "\\u00" + Math.floor(str.charCodeAt() / 16).toString(16) + (str.charCodeAt() % 16).toString(16);
	}
};



/**
 * Site class:
 * General functions
 */
var Site = {
	height : '625',

	trackExternal : function() {
		$('a[href^="http://"]').click(function(){
			var url = $(this).attr('href');
   		if (typeof(pageTracker) == 'object') pageTracker._trackPageview('/external/'+url);
		});
		return true;
	},

	/*setHeight : function(h) {
		Site.height = h;
		$('#middle').height(Site.height);
	},*/

	/**
	* fixHeight
	* this function increases the size of the content box to match the background image.
	* 86 being the magic number here (i worked it out using math)
	*/
	fixHeight : function(h) {
		this.height = h || $('#middle').height();
		if (this.height % 86 != 0 && this.height >425) {
		//if (this.height % 86 != 0) {
			while(this.height % 86 != 0) {
				this.height++;
			}
		}
		if (this.height < 395) {this.height = 395;}
			//this.height += 4;
		$('#middle').height(this.height);
	},

	/**
 	* calcHeight
 	* Takes a new height and returns the height after calculating it based on the 86 increment
 	*/
	calcHeight : function(h) {
		if (h % 86 != 0 && h >425) {
			while(h % 86 != 0) {
				h++;
			}
		}
		return h;
	},

	fixLeftColumn : function() {
		$('#left-column,#scene,#scene div').height("auto");
  		var height = $(window).height();
  		if (height < $(document).height()) height = $(document).height();
		$('#left-column,#scene,#scene div').height(height);
	},

	getPage : function(t,url) {
		//data = '&url='+url;
		$.ajax({
			type: "POST",
			url: '/getjson'+url,
			dataType: 'json',
			beforeSend: function(){
				Scene.minishow();
			},
			complete: function(){},
			success: function(data) {

				$('#middle').slideUp(750, function(){
					// google tracker
					pageTracker._trackPageview(url);
			
					var title = data.title;
					var content = data.content;
					var scene = data.scene;
					if (data.editlink && $('#editlink')) { $('#editlink').attr('href', data.editlink); }
					if (data.m_title) { document.title = data.m_title; }
					window.location.hash = '#'+url;
			
					$('ul.links li a').removeClass('sel');
					$(t).addClass('sel');
			
					// put content into a dummy div to get the height
					$('body').append('<div style="width:340px;padding:10px 0;height:auto;display:0" id="dummy">'+content+'</div>');
					var height = $('#dummy').height();
					$('#dummy').remove();
					
					if (height < 384) height = 384;
					
					$('#middle').height(height).html(content);
					$('#piclist li a').removeClass('sel');
					var active = $('#scene div.active');
					if (active.length == 0) active = $('#scene div:last');
				
					var pic = $('#scene .last-active').css('background-image','url('+scene+')').removeClass('last-active');
					active.addClass('last-active');
				
				
					var fade = 1000;
					//var pic = '#pic-'+id;
					$(pic).css({opacity: 0.0})
						.addClass('active')
						.animate({opacity: 1.0}, fade, function() {
							active.removeClass('active');
							//Scene._show();
							$('#middle').slideDown(750, function() {
								Site.fixLeftColumn();
								$(this).attr("style", "").removeAttr("style");
							});
							strong();
							Form.checkForms();
							$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
							Site.trackExternal();
					});
				});
			}
		});
		return false;
	}
};


var Form = {
	forms : ([
				{'id': 'register-form-holder',  'url': '/user/register/'}
			]),

	checkForms : function() {
		$(this.forms).each(function(i,f){
			if ($('#'+f.id).length) {
				Form.getForm(f.id, f.url);
			}
		});
	},

	getForm : function(id, url) {
		$.ajax({
			type: "POST",
			url: url,
			dataType: 'html',
			beforeSend: function(){$('#'+id).hide();},
			complete: function(){$('#'+id).fadeIn(500);},
			success: function(html) {
				$('#'+id).html(html);
				// sort out height
				var height = $('#'+id).height();
				var newheight = 516;
				newheight = Site.calcHeight(newheight);
				$('#middle').animate({height:newheight},500);
			}
		});
	},

	sendForm : function(formid, holder) {
		var url = $(formid).attr('action');
		var data = $(formid).serialize();
		$.ajax({
			type: "POST",
			url: url,
			data: data,
			dataType: 'html',
			beforeSend: function(){$('#'+holder).fadeOut();},
			complete: function(){$('#'+holder).fadeIn();},
			success: function(html) {
				$('#'+holder).html(html);
				// sort out height
				var height = $('#'+holder).height();
				var newheight = parseInt(50) + parseInt(height);
				newheight = Site.calcHeight(newheight);
				$('#middle').animate({height:newheight},500);
			}
		});
	},
	
	staffLogin : function() {
	
		var form = $('#login-right');
		
		// http://stackoverflow.com/questions/979024/changing-the-action-of-a-form-with-javascript-jquery
		form.get(0).setAttribute('action', '/user/login');
		
		form.submit(function() {
			return Login.submit(this);
		});

		form.parent().find('h3').html('Login to this site');
		
		form.find('input[name=is_site]').val('true');
		
		form.find('input[name=user]').focus();

		return false;
	}
};


var Login = {
	holder : '.login-holder',

	submit : function(form) {
		var data = $(form).serialize();
		var url = $(form).attr('action');
		data += '&ajax=1';		// add ajax handling via javascript

		// setup redirect if necessary
		if (window.location.hash) {
			var hash = window.location.hash;
			hash = hash.replace('#', '');
			data += '&redirect='+hash;
		}
		var height = $(form).height();
		$(form).remove();
		$(Login.holder).append('<div class="login-loading" style="height:'+height+'px;"><h1>LOGGING IN</h1></div>');

		$.ajax({
			type: "POST",
			url: url,
			data: data,
			dataType: 'json',
			beforeSend: function(){},
			complete: function(){},
			success: function(data) {
				if (data.success == 1) {
					$('.login-loading h1', Login.holder).text('SUCCESS!');
					$('.login-loading',Login.holder).animate({opacity:0},500, function() {
						$('#login-header').remove();
						$(Login.holder).css('opacity',0).append(data.html).animate({opacity:1},500);
						$(this).remove();
						if (data.redirect) { window.location = data.redirect;}
					});
				} else {
					$('.login-loading h1', Login.holder).text('INCORRECT USERNAME/PASSWORD');
					$('.login-loading',Login.holder).animate({opacity:0},500, function() {
						$('#login-header').remove();
						$(Login.holder).css('opacity',0).append(data.html).animate({opacity:1},500);
						$(this).remove();
					});
				}
			}
		});
		
		return false;
	},

	addRedirect : function(form) {
		if (window.location.hash) {
			var hash = window.location.hash;
			hash = hash.replace('#', '');
			$(form).append('<input type="hidden" name="redirect" value="'+hash+'" />');
			data = $(form).serialize();
			alert(data);
		}
		return false;
	}
};

/**
 * Scene class:
 * Controls the background image slideshow
 */
var Scene = {
	oldHeight : null,

	contentArea : '#middle .padding, #middle',
	contentContent : '#middle .padding',
	contentMain : '#middle',
	sceneToggleHolder : '#scene-toggle-holder',
	sceneToggle : '#scene-toggle',
	scene : '#scene',

	viewPictures : '#viewpictures',
	pictureList : '#picturelist',


	/**
 	* toggle
 	* Toggles the content area
 	*/
	toggle : function() {
		if ($(this.contentArea).is(":hidden")) {
			this._show();
		} else {
			this._hide();
		}
	},

	changeScene : function(pic) {
		$(this.scene).css('background-image','url('+pic+')');
	},


	/**
 	* _show
 	* Displays the content box again and resets styling to default
 	*/
	_show : function(speed) {
		if (!speed) { speed = 750; }
		//$(this.contentArea).css('display','block').animate({height:Site.oldHeight+"px",opacity:1}, speed).height(Site.oldHeight);
		$(this.contentMain).slideDown(speed);
		$(this.sceneToggleHolder).css('background','#000');
		$(this.sceneToggle).css('background-image', 'url(/images/middle-arrow-red.png)');
		$(this.viewPictures).removeClass('active');
		$(this.pictureList).css({display:'none'});
	},

	minishow : function() {
		$(this.sceneToggleHolder).css('background','#000');
		$(this.viewPictures).removeClass('active');
		$(this.pictureList).css({display:'none'});
	},

	/**
 	* _hide
 	* hides content box
 	*/
	_hide : function(speed) {
		if (!speed) { speed = 750; }
        //$(this.contentArea).css({display:'none'});
		// fix for ie6
		if (jQuery.browser.msie == true && jQuery.browser.version.substr(0,3) == '6.0') {
			$(this.contentArea).css({display:'none'});
			$(this.pictureList).css({opacity:0,display:'block'}).animate({opacity:0.7},speed);
		}
		else {
			//Scene.oldHeight = $(this.contentContent).height();
			/*$(this.contentArea).animate({height:0,opacity:0}, speed, function() {
				$(this.contentArea).css({display:'none'});
			});*/
			$(this.contentMain).slideUp(speed);
			$(this.pictureList).css({opacity:0,display:'block'}).animate({opacity:0.7},2000);
		}
        $(this.sceneToggleHolder).css('background','#fff');
        $(this.sceneToggle).css('background-image', 'url(/images/middle-arrow-white.png)');
        $(this.viewPictures).addClass('active');
    },


	/*_hideContent : function(speed) {
		if (!speed) { speed = 500; }
		$(this.contentArea).css('display','block').animate({height:Site.height,opacity:1}, 1000);
		$(this.contentArea).css({display:'none'});
		// fix for ie6
		if (jQuery.browser.msie == true && jQuery.browser.version.substr(0,3) == '6.0') {
			$(this.contentArea).css({display:'none'});
			$(this.pictureList).css({opacity:0,display:'block'}).animate({opacity:0.7},1000);
		}
		else {
			$(this.contentArea).animate({height:0,opacity:0}, 1000, function() {
				$(this.contentArea).css({display:'none'});
			});
		}
	},

	_showContent : function(speed) {
		if (!speed) { speed = 500; }
		$(this.contentArea).css('display','block').animate({height:"100%",opacity:1}, 1000);
	},*/

	loadFirstImage : function() {
		$('#scene').css({opacity:'0'});
		var first = $('#piclist li a:first').attr('href');
		var id = $('#piclist li a:first').attr('id').split('piclink-')[1];;
		var active = $('<div style="background:url('+first+');height:'+$('#scene').height()+'px" class="active"></div>');
		var spawn = $('<div class="last-active"></div>');
		$('#piclist li a:first').addClass('sel');
		$('#scene').animate({opacity:1.0},500);
		$('#scene').append(active).append(spawn);
	},

	/** handleImages
	 * Code to handle the scene preloading and animation
	 */
	handleImages : function() {
		var pl_size = $('#piclist li a').size();
		var i =0;
		$('#piclist li a').each(function(j, el){
			var id = $(this).attr('id').split('piclink-')[1];
			var href = $(this).attr('href');

			$(this).click(function() {
				var href = $(this).attr('href');

				$('#piclist li a').removeClass('sel');
				var active = $('#scene div.active');
				if ( active.length == 0) active = $('#scene div:last');

				var pic = $('#scene .last-active').css('background-image','url('+href+')').removeClass('last-active');
				active.addClass('last-active');


				var fade = 1000;
				//var pic = '#pic-'+id;
				$(pic).css({opacity: 0.0})
					.addClass('active')
					.stop().animate({opacity: 1.0}, fade, function() {
						active.removeClass('active');
				});

				$(this).addClass('sel');
				return false;
			});
		});
	 },

	/**
	 * preload
	 * Preloads images (mainly)
	 */
	preload : function(wut, handler) {
		if ((typeof wut).toLowerCase() == 'string') {
			src = wut;
		}
		else {
			src = $(wut).attr('href');
			try {
				opts = eval('({'+$(wut).attr('rel')+'})');
			}catch(e){}
		}
		// test if it is an image, otherwise we'll use ajax
		if (src.match(/.jpg$|.jpeg$|.png$|.gif$|.bmp$|.tif$|.tiff$|.gi$/i) && 'a' == 'b'){
			var img = new Image();
			if (handler) {
				if (handler.loaded && typeof handler.loaded == 'function') {
					img.onload = function() {
						response = {
							width: img.width,
							height: img.height,
							src: img.src,
							obj: $('<img>').attr('src', img.src)
						};
						handler.loaded(response);
					};
				}
				if (handler.loaded && typeof handler.error == 'function') {
					img.onerror = function(err) { handler.error(err); }
				}
			}
			img.src = src;
		}
		// ajax
		else {
			$.get(src, function(html){
				if (handler) {
					if (handler.loaded && typeof handler.loaded == 'function') {
						var content = $('<div>').html(html);
						response = {
							width: parseInt(content.children(0).css('width')),
							height: parseInt(content.children(0).css('height')),
							src: src,
							obj: content,
							data: html
						};
						handler.loaded(response);
					}
				}
			});
		}
	}

};


//snap version 1 (tweaked slightly to not set width of controls)
(function($){var methods={close:function(c){if($.browser.msie){$('#snap').remove();if(typeof c=='function')c();}else $('#snap').fadeOut("fast",function(){$(this).remove();if(typeof c=='function')c();});},open:function(o){var s=$.extend({callback:null,html:"",inputh:0,inputw:0},o);if($('#snap').length==0){$('body').append('<div id="snap"><div id="snap-back"></div><div id="snap-box"><div class="contents"><div class="controls"><a class="close" href="#"></a></div><div class="message"></div></div></div></div>');$('#snap, #snap-back').width($(window).width()).height($(window).height());$(window).resize(function(){$('#snap, #snap-back').width($(window).width()).height($(window).height());});$('#snap .close').click(function(e){e.preventDefault();$.snap("close",s.callback);});$(document).keyup(function(e){if(e.keyCode==27)$.snap("close",s.callback);});}var md=$('#snap .message');var cd=$('#snap .contents');var sd=$('#snap');md.html(s.html).css({display:'inline-block'});sd.css({position:'absolute',visibility:'hidden',display:'block'});if(s.inputw>0)md.width(s.inputw);if(s.inputh>0)md.height(s.inputh);var ih=md.height();var iw=md.width();if(iw<190)iw=190;else{var mw=$(window).width()-40;if(iw>=mw)iw=mw;}fw=iw+10;if(ih<184)ih=184;else{var mh=$(window).height()-40;if(ih>=mh)ih=mh;}var ih=ih+16;cd.height(ih).width(fw).css('margin-top',0-(ih/2));md.attr("style","").removeAttr("style");sd.attr("style","").removeAttr("style");md.width(fw).height(ih-31);if($.browser.msie)sd.show();else sd.fadeIn();}};$.snap=function(method){if(methods[method])return methods[method].apply(this,Array.prototype.slice.call(arguments,1));else if(typeof method==='object'||!method)return methods.open(method);else $.error('Method '+method+' does not exist fool!');return $(this);};})(jQuery);
