$(document).ready(function(){
	$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
    Site.trackExternal();
});

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() {
        //var height = $(window).height() - 132;
        //var height = ($(document).height() + $(window).scrollTop() - 132);
        //var height = $(document).height() - $('body').offset().top;
        var height = $(document.body).height() - 132;
        //var height = ($(document).height() + $(window).scrollTop());
        if (height < this.height) {
            height = this.height+40;
        }
        $('#left-column').height(height);
    },

	getPage : function(t,url) {
		//data = '&url='+url;
		$.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').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 (url == '/parents/') { height = 730; }
				if (url == '/further-info/frequent-questions/'){height = 650;}
				if (url == '/further-info/terms-and-conditions/'){height = 1000;}

				Site.fixHeight(height);

				$('#middle').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')
					.stop().animate({opacity: 1.0}, fade, function() {
						active.removeClass('active');
						Scene._show();
						strong();
                        Form.checkForms();
                        Site.fixLeftColumn();
						$('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();
                //if (console) console.log("site.height:"+Site.height+" height: "+height+"#middle.padding:"+$('#middle .padding').height());
				/*if (parseInt(Site.height) < height) {
					var newheight = parseInt(Site.height) + parseInt(height);
                    newheight = Site.calcHeight(newheight);
					$('#middle').animate({height:newheight},500);
				}*/
                //var newheight = parseInt(Site.height) + parseInt($('#middle').height()) - height;
                var newheight = 516;
                //console.log("newheight: "+newheight);
                newheight = Site.calcHeight(newheight);
				$('#middle').animate({height:newheight},500);
                //newheight = parseInt(Site.height + height - 250);
				//$('#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);
			}
		});
	}
}


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 : "0",

    contentArea : '#middle .padding, #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 = 500; }
        $(this.contentArea).css('display','block').animate({height:Site.height,opacity:1}, 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'});
    },

    /**
     * _hide
     * hides content box
     */
    _hide : function(speed) {
		if (!speed) { speed = 500; }
        $(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 {
			$(this.contentArea).animate({height:0,opacity:0}, speed, function() {
				$(this.contentArea).css({display:'none'});
			});
			$(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:Site.height,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+')" 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);
					}
				}
			});
		}
	}

}
