$(document).ready(function(){
	$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
});

/**
 * 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) {
        var height = h || ($(document).height() + $(window).scrollTop());
        $('#left-column').height(height);
		$('#scene').height(height);
		$('#farright').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();
						$('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);
		$(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: pareseInt(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'}
			]),
	contactForm: '#contact-form-holder',

	checkForms : function() {
		$(this.forms).each(function(i,f){
			if ($('#'+f.id).length) {
				//alert(f.id);
				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();
				if (parseInt(Site.height) < height) {
					var newheight = parseInt(Site.height) + parseInt(height);
					//console.log("site.height: "+Site.height+" height: "+height+ "newheight: "+newheight);
					$('#middle, #middle .padding').animate({height:newheight},500);
				}
			}
		});
	},

	sendForm : function(formid, holder) {
		//alert("formid: "+formid+" holder: "+holder);
		var url = $(formid).attr('action');
		var data = $(formid).serialize();
		//alert("url: "+url);
		//alert(data);
		$.ajax({
			type: "POST",
			url: url,
			data: data,
			dataType: 'html',
			beforeSend: function(){$('#'+holder).fadeOut();},
			complete: function(){$('#'+holder).fadeIn();},
			success: function(html) {
				$('#'+holder).html(html);
			}
		});
	}
}

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;
                    }
                });
            }
        });
    },

    //hash : function(url){
        //window.location.hash ='#'+url;
    //}
};


/**

 handleImages : function() {
		// first preload the first image
		var first = $('#piclist li a:first').attr('href');
		Scene.preload(first, {loaded: function(img){

		var pl_size = $('#piclist li a').size();
		var i =0;
		$('#scene').css({opacity:'0'});
	    if (homepagerun == true) { $('#scene').css({opacity:'0'}); }
		var shownfirst = false;
		$('#piclist li a').each(function(j, el){
			var id = $(this).attr('id').split('piclink-')[1];
			// preload
			Scene.preload(this,{
				loaded: function(img) {
					i++;
					var image = img.obj;
					$(image).attr('id', 'pic-'+id);
					if (shownfirst == false) {
						shownfirst = true;
						$(el).addClass('sel');$(image).addClass('active');
						if (homepagerun == true) { $('#scene').animate({opacity:1.0},500);}
						else { $('#scene').css({opacity:1.0}); }
					}
					/*if (id == 1) {
						$(el).addClass('sel');$(image).addClass('active');
						if (homepagerun == true) { $('#scene').animate({opacity:1.0},500);}
						else { $('#scene').css({opacity:1.0}); }
					}*/
					/*
					$('#scene').append(image);
					percent = Math.round(i/pl_size*100);
					if (percent == 100) {
						$('#viewpictures span').text("VIEW PICTURES");
						$('#scene').animate({opacity:1.0},1000);
					}
					else {
						$('#viewpictures span').text("Loading: "+percent+'%');
					}
				}
			});
			}
			*/