$(document).ready(function(){
	if ($('.hideme').length) do_hideme();

	Site.fixHeight();

	$(window).resize(function() {
        Site.fixHeight();
    });

	Scene.loadFirstImage();
	Form.checkForms();

	$('#scene-toggle').click(function() {
		$('#middle').slideToggle();
		$('#footer').slideToggle();
		if ($('#middle').is(":hidden")) {
			$(Scene.sceneToggleHolder).css('background','#000');
			$(Scene.sceneToggle).css('background-image', 'url(/images/middle-arrow-red.png)');
		} else {
			$(Scene.sceneToggleHolder).css('background','#fff');
			$(Scene.sceneToggle).css('background-image', 'url(/images/middle-arrow-white.png)');
		}
		return false;
	});
	$('#l-gallery').click(function() {
		what = $('#l-gallery');
		$('ul.links li a, ul.blinks li a, ul.sndlinks li a').removeClass('sel');
		if (!$(what).hasClass('clicked')) {
			$('#scene-toggle-holder').toggle();
			Scene._hide();
			var li = $(what).parent();
			$(what).addClass('sel');
			//$('<a id="g-prev">').append(li);
			$(li).append('<span id="leftright">&nbsp;</span>');
			$('#leftright').css({opacity:0}).append('<a id="g-prev" href="#"></a>').append('<a id="g-next" href="#"></a>').animate({opacity:1},500);
			$(what).addClass('clicked');
		}
		else {
			$(what).removeClass('clicked');
			$('#scene-toggle-holder').toggle();
			Scene._show();
			$('#leftright').animate({opacity:0}, 500, function() {
				$('#leftright').remove();
			});
		}
		return false;
	});

	$('#g-prev').live('click',function() {
		scene--;
		if (scene == -1) { scene = len; }
		var next = scenes[scene];
		Scene.changeImage(next);
		return false;
	});

	$('#g-next').live('click',function() {
		scene++;
		if (scene == len) { scene = 0; }
		var next = scenes[scene];
		Scene.changeImage(next);
		return false;
	});

	if (window.location.hash) {
        var hash = window.location.hash;
        hash = hash.replace('#', '');
		$('ul.links li a, ul.sndlinks li a, ul.blinks li a').each(function(){
			if ($(this).attr('href') == hash) {
				Site.getPage(this,hash);
			}
		});
	}

	$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
	
	$('.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.fixHeight();
				});
		}
		else
		{
			f.addClass("open").animate({
				height: "230px"
				}, "slow", function() {
					Site.fixHeight();
				});
		}
	});
	
	$('.share2 .open').live('click', function(e) {
		e.preventDefault();
		$('#middle .padding, #middle').attr('style', '').removeAttr('style');
		$('.share2').stop().animate({height: '129px'}, "fast", function() {
			Site.fixHeight();
		});
	});
	
	$('.share2 .close').live('click', function(e) {
		e.preventDefault();
		$('.share2').stop().animate({height: '21px'}, "fast", function() {
			Site.fixHeight();
		});
	});
	$('#middle .padding, #middle').attr('style', '').removeAttr('style');
	
});

function do_hideme() {
	$('.hideme h2').each(function(i,v) {
	
		var c = [];
	
		$(this).nextAll().each(function() {
		
			if ($(this).is("h2")) return false;
			else {
				c.push($(this));
				//$(this).remove();
			}
		
		});
	
		$(this).after('<div class="dohideme"></div>');
		
		var d = $(this).next();
		
		$.each(c, function() {
			d.append($(this));
		});
	
	});

	$('.dohideme').each(function() {
	    var h = $(this).prev();
	    
	    h.click(function() {
	    	if ($(this).next().is(':hidden')) {
	    		$('.dohideme').not(':hidden').slideUp(500, function() {
	    			$(this).prev().find('.control').text('+');
	    		});
	    		$(this).next().slideDown(500);
	    		$(this).find('.control').text('-');
	    	}
	    	else {
	    		$(this).next().slideUp(500);
	    		$(this).find('.control').text('+');
	    	}
	    }).prepend('<span class="control">+</span>').addClass('controlled');
	    
	    $(this).slideUp();
	});
}

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;
    }

};

/**
 * Site class:
 * General functions
 */
var Site = {
    height : '625',

    trackExternal : function() {
        $('a[href^="http://"]').click(function(){
        //$('a.occam').click(function(){
            var url = $(this).attr('href');
           if (typeof(pageTracker) == 'object') pageTracker._trackPageview('/external/'+url);
        });
        return false;
    },

	setHeight : function(h) {
		this.height = h;
		$('#middle, #middle .padding').height(this.height);
	},

	fixHeight : function(h) {
		//											content height 				offset from top					footer
		var height = h || $('#middle').height() + $('#middle').offset().top + 80;
		height = ($('#farright').height() > height) ? $('#farright').height() : height;	// set to farright if taller than what we got
		height = ($(window).height() > height) ? $(window).height() : height;
		$('#scene').height(height);
	},

	getPage : function(t,url) {
		//data = '&url='+url;
		if ($('#leftright') && url != '/gallery/') {
			$('#scene-toggle-holder').show();
			$('#l-gallery').removeClass('clicked');
			$('#leftright').animate({opacity:0}, 500, function() {
				$('#leftright').remove();
			});
		}
		if (url == '/gallery/') { return false;}
		$.ajax({
			type: "POST",
			url: '/getjson'+url,
			dataType: 'json',
			beforeSend: function(){
				Scene._hide();
			},
			complete: function(){},
			success: function(data) {
                // 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, ul.blinks li a, ul.sndlinks li a').removeClass('sel');
				$(t).addClass('sel');
				//alert("title: "+title+" scene: "+scene);v

				// put content into a dummy div to get the height
				$('#wire').append('<div style="width:535px;padding: 5px 20px 0px 15px;margin-bottom:8px;height:auto;background:#000" id="dummy">'+content+'</div>');
				var height = $('#dummy').height() + 50;
				$('#dummy').remove();

				// hacks for the faq's
				if (url == '/further-info/faqs/') { height = 460; }
				if (url == '/further-info/terms-and-conditions/') { height = 1230; }
				Site.setHeight(height);

				$('#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')
					.stop().animate({opacity: 1.0}, fade, function() {
						active.removeClass('active');
						$('#middle').html(content);
						Scene._show();
						Form.checkForms();
						//strong();
						if ($('.hideme').length) do_hideme();
						$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
						if ((height + 260 > ($(window).height() + $(window).scrollTop()))) { Site.fixHeight(Site.height + 290); }
						else { Site.fixHeight(); }
                        Site.trackExternal();
				});
			}
		});
		return false;
	}
};

/**
 * Scene class:
 * Controls the background image slideshow
 */
var Scene = {
	oldHeight : "0",

	images : [],

    contentArea : '#middle .padding, #middle',
	footer : '#footer',
    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+')');
    },

	sceneToggle : function() {
		if ($(this.contentArea).is(":hidden")) {
			$(this.sceneToggleHolder).css('background','#000');
			$(this.sceneToggle).css('background-image', 'url(/images/middle-arrow-red.png)');
		} else {
			$(this.sceneToggleHolder).css('background','#fff');
			$(this.sceneToggle).css('background-image', 'url(/images/middle-arrow-white.png)');
		}
	},

    /**
     * _show
     * Displays the content box again and resets styling to default
     */
    _show : function() {
        $(this.contentArea).css('display','block').animate({height:Site.height,opacity:1}, 1000, function() {
        	$(this).css('filter', 'none');
        	$('#middle .padding, #middle').attr('style', '').removeAttr('style');
        });
		$(this.footer).slideDown(500);
        $(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'});
		//alert("_show(): contentArea.css('display'): "+$(this.contentArea).css('display'));
    },

    /**
     * _hide
     * hides content box
     */
    _hide : function() {
        $(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);
			//alert("_hide(): contentArea.css('display'): "+$(this.contentArea).css('display'));
		}
		else {
			$(this.contentArea).animate({height:0,opacity:0}, 1000, function() {
				$(this.contentArea).css({display:'none'});
				//alert("_hide(): contentArea.css('display'): "+$(this.contentArea).css('display'));
			});
			$(this.pictureList).css({opacity:0,display:'block'}).animate({opacity:0.7},2000);
		}
		$(this.footer).slideUp(500);
        $(this.sceneToggleHolder).css('background','#fff');
        $(this.sceneToggle).css('background-image', 'url(/images/middle-arrow-white.png)');
        $(this.viewPictures).addClass('active');
    },

	loadFirstImage : function() {
		if (!scenes) { return false;}
		var first = scenes[scene];
		var image = $('<div>').addClass('active').css('background','url('+first+') no-repeat 0 0').css({opacity:'0'});
		var last = $('<div>').addClass('last-active');
		$('#scene').append(image).append(last);
		$('#scene .active').animate({opacity:1.0},1000);
		return false;
	},

	changeImage : function(href) {
		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 = 750;
		//var pic = '#pic-'+id;
		$(pic).css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, fade, function() {
				active.removeClass('active');
		});
	},


	/**
	 * 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)){
			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);
					}
				}
			});
		}
	}

};

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();
					});
				} 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;
	}
};

var Form = {
	forms : ([
				{'id': 'contact-form-holder', 	'url': '/form/contactForm'},
				{id: 'feedback-form-holder', url: '/form/feedbackForm'},
				{id: 'maintenance-form-holder', url: '/form/maintenanceForm'}
			]),

	checkForms : function() {
		$(this.forms).each(function(i,f){
			if ($('#'+f.id).length) {
				//alert(f.id);
				Form.getForm(f.id, f.url, i);
			}
		});
		if ($('#gmap').length) Googlemap.init();
	},

	getForm : function(id, url, index) {
		$.ajax({
			type: "POST",
			url: url,
			dataType: 'html',
			beforeSend: function(){$('#'+id).hide();},
			complete: function(){$('#'+id).fadeIn(500);},
			success: function(html) {
				var container = $('#'+id);
			
				container.html(html);
            	$('.contact-form textarea').each(function() {
					var tehtitle = $(this).attr('title');
					$(this).focus(function() {
						if ($(this).val() == tehtitle) $(this).val('');
					}).blur(function() {
						if ($(this).val() == "") $(this).val(tehtitle);
					});
				});
               
				if (container.hasClass('cpageexp')) $('.cpageexp h2').click(function() { //note that the map is not fetched by javascript but the feedback form is. this will activate both dropdowns now
					var t = $(this).parent();
						
					if (t.hasClass('open')) t.animate({height:26},"fast",function() { t.removeClass('open'); Site.fixHeight(); });
					else t.animate({height:376},"fast",function() { t.addClass('open'); Site.fixHeight(); });
				});
			}
		});
	},

	sendForm : function(formid, holder) {

		var doublecheck = true;
		if (holder == "maintenance-form-holder") doublecheck = confirm("You should not use this form if a fault requires immediate attention or is an emergency, e.g. water leaks, power cuts etc. In case of emergency, please call 01522 525 757 for an immediate response. Do you wish to continue?");
		
		if (doublecheck) {
			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);
				}
			});
		}
	},
	
	staffLogin : function() {
		$('html, body').animate({scrollTop:0}, 'slow');

		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 Googlemap = {

   init: function() {
       var damap = new google.maps.Map(document.getElementById("gmap"), {
           zoom: 14,
           center: new google.maps.LatLng(53.228126, -0.554140),
           mapTypeId: google.maps.MapTypeId.HYBRID
       });

       var mr = new google.maps.Marker({
           position: new google.maps.LatLng(53.228126, -0.554140),
           map: damap,
           title: "DIGS The Pavilions",
           icon: new google.maps.MarkerImage("/images/map-pin.png", new google.maps.Size(106, 49))
       });
   }
};

var Digs = {
    ajaxloader : '<div id="ajax-loader">Loading<br /><img src="/images/ajax_loader.gif" alt="Loading..." width="62" height="13" longdesc="Loading content..." /></div>',
    ajaxloaderexists : 0,

	loading : function(what) {
		if (!what) {
			$('body').loadAnimation();
		} else {
			$(what).loadAnimation();
		}
	},

	stoploading  : function() {
		$.loadAnimation.end();
	},

    /**
     * loader toggles the fast loader
     */
    loader : function(method) {
        // first check if #ajax-loader exists
        if (Digs.ajaxloaderexists == 0) {
            if ($('#ajax-loader').length < 1) {
                // create it
                $('body').append(Digs.ajaxloader);
                Digs.ajaxloaderexists = 1;
            } else Digs.ajaxloaderexists = 1;
        }

        // otherwise toggle
        if (method !== undefined) { if (method == 'on') $('#ajax-loader').css('display','block'); else $('#ajax-loader').fadeOut(250); return}

        if ($('#ajax-loader').is(':hidden')) $('#ajax-loader').css('display','block');
        else $('#ajax-loader').fadeOut(250);
    },

	redirect : function(where){
		//window.location.replace(where);
		window.location = where;
	},

	notify : function(title, message, icon) {
		switch(icon) {
			case 'add'		: image = '/images/add-icon.png'; break;
			case 'save'		: image = '/images/save-icon.png';break;
			case 'delete'	: image = '/images/delete-icon.png';break;
			case 'error'	: image = '/images/error-icon.png'; break;
			default			: image = '/images/info-icon.png';break;
		}
		$.gritter.add({
			title: title,
			text: message,
			image: image,
			sticky: false,
			time: '2000'
		});

	},

    info : function(id, type, message) {
        $(id).html('<span class="'+type+'">'+message+'</span>');
        return (type == 'error') ? false : true;
    },

    init : function() {
        $.address.init(function(e) {
            //if (e.path.substr(0,10) == '/my-place/') {
            var path = $.address.pathNames();
            if (path[0] == 'my-place' && path[1] != 'your-offers') {
                Album.load(e.path);
                pageTracker._trackPageview(e.path);
            } else if (path.length > 0) {
                var done = false;
                $('ul.links li a, ul.sndlinks li a, ul.blinks li a').each(function(){
                    if ($(this).attr('href') == e.path && done == false) {
                        Site.getPage(this,e.path);
                        done = true;
                    }
                });
            }
        });
    }

};

function popup(url) {
	var width  = 495;
	var height = 375;
	doPopup(url, width, height);
}

function popupBig(url) {
	var width  = 680;
	var height = 450;
	doPopup(url, width, height);
}

function doPopup(url, width, height) {
	var left   = (screen.width  - width)/2;
	var top	= (screen.height - height)/2;
	var params = 'width='+width+', height='+height+', top='+top+', left='+left+', directories=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, toolbar=no';
	newwin=window.open(url,'panorama', params);
	if (window.focus) {newwin.focus()}
	return false;
}

//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);
