girl = 
{
	baseUrl	: '',
	rewrite : false,
	
	urlTo	: function(url)
	{
		if(!this.rewrite)
		{
			return this.baseUrl + '/index.php?' + url;
		}
		else
		{
			return this.baseUrl + url;
		}
	},
	
	urlToResource : function(url)
	{
		return this.baseUrl + url;
	}
};

girl.profilePicture	= 
{
	cropperSize 	: 180,
	offsetX			: null,
	offsetY			: null,
	show			: function(imageUrl)
	{
		var time = Number(new Date());
		
		var imageElement = $('<img src="' + imageUrl + '?' + time + '">');
		$('#dragBorder').append(imageElement);
		
		imageElement.load(function(){
			var imageElement = $(this);
			
			var dragBorder = $('#dragBorder');
			
			var left = 0;
			var top = 0;
			var axis = '';
			
			var borderWidth = imageElement.width();
			var borderHeight = imageElement.height();
			var borderLeft = 0;
			var borderTop = 0;
			
			if(imageElement.width() > imageElement.height())
			{
				left = Math.round(((imageElement.width() - girl.profilePicture.cropperSize) / 2) * -1) + (imageElement.width() - girl.profilePicture.cropperSize);
				borderWidth += (imageElement.width() - girl.profilePicture.cropperSize);
				borderLeft = (imageElement.width() - girl.profilePicture.cropperSize) * -1;
			}
			else if(imageElement.height() > imageElement.width())
			{
				top = Math.round(((imageElement.height() - girl.profilePicture.cropperSize) / 2) * -1) + (imageElement.height() - girl.profilePicture.cropperSize);
				borderHeight += (imageElement.height() - girl.profilePicture.cropperSize);
				borderTop = (imageElement.height() - girl.profilePicture.cropperSize) * -1;
			}
			
			dragBorder.css({
				'position'	: 'relative',
				'width'		: borderWidth + 'px',
				'height'	: borderHeight + 'px',
				'left'		: borderLeft + 'px',
				'top'		: borderTop + 'px'
			});
			
			position = {
				left	: left,
				top		: top
			};
			
			position.left -= ((dragBorder.width() - girl.profilePicture.cropperSize) / 2);
			position.top -= ((dragBorder.height() - girl.profilePicture.cropperSize) / 2);
			
			girl.profilePicture.offsetX = position.left;
			girl.profilePicture.offsetY = position.top;
			
			imageElement.css({
				'left'	: left,
				'top'	: top
			});
			
			imageElement.draggable({
				axis		: axis,
				cursor		: 'move',
				containment	: 'parent',
				drag		: function(event, ui)
				{
					var dragBorder = $('#dragBorder');
					var position = $('#dragBorder img').position();
					position.left -= ((dragBorder.width() - girl.profilePicture.cropperSize) / 2);
					position.top -= ((dragBorder.height() - girl.profilePicture.cropperSize) / 2);
					girl.profilePicture.offsetX = position.left;
					girl.profilePicture.offsetY = position.top;
				}
			});
		});
	},
	
	save		: function()
	{
		var url = girl.urlTo('/crop/' + this.offsetX + '/' + this.offsetY);
		$.get(url, function(response){
		});
	}
};

girl.faces = 
{
	// Variables
	textDisplayDelay	: 8000,
	nextElement			: null,
	commentParent		: null,
	columns				: 0,
	rows				: 0,
	visibleColumns		: 0,
	visibleRows			: 0,
	timeSinceBigPicture	: 0,	
	list				: null,
	queues				: {
		small			: [],
		medium			: [],
		large			: []
	},
	comments			: [],
	columnData			: [],
	lastId				: 0,
	animationLeftFrom		: -50,
	animationLeftCurrent	: -50,
	animationRightFrom		: -150,
	animationRightCurrent	: -200,
	animationDelay			: 100,
	animationFade			: 6000,
	commentSpawnColumns		: [],
	
	// "Constants"
	ELEMENT_TYPE		: 
	{
		SMALL	: 1,
		MEDIUM	: 2,
		LARGE	: 3
	},
	
	COMMENT_POSITION	:
	{
		ABOVE	: 0,
		BELOW	: 1,
		RIGHT	: 2,
		LEFT	: 3
	},
	
	COMMENT_IDS		: 
	[
		'commentAbove',
		'commentBelow',
		'commentRight',
		'commentLeft'
	],
	
	// Populates the list with pictures and starts the animation
	init				: function()
	{
		this.list = $('#photoList');
		this.popup = $('#img-popup');
		
		// Find number of elements to insert
		this.calculateSize();
		var elements = this.columns * this.rows;
		
		// Load data
		this.populateQueue(girl.faces.ELEMENT_TYPE.SMALL, elements + 60);
		this.populateQueue(girl.faces.ELEMENT_TYPE.MEDIUM, 10);
		this.populateQueue(girl.faces.ELEMENT_TYPE.LARGE, 10);
		this.loadComments();
		
		// Insert element into the list
		for(var i = 0; i < elements; i++)
		{
			this.list.append(this.createListElement(this.getNextElement()));
		}
		
		girl.faces.insertNewElement();
		if(!(jQuery.browser.msie && jQuery.browser.version < 7))
		{
			setTimeout(function() { girl.faces.showComment(); }, 2000);
		}
	},
	
	// Shows/hides comments
	showComment			: function(index)
	{
		// Randomly select a column if no column is specified
		if(index == null)
		{
			var safe = false;
			var tries = 0;
			while(!safe && tries < 100)
			{
				tries += 1;
				index = this.commentSpawnColumns[Math.floor(Math.random() * this.commentSpawnColumns.length)];
				
				safe = this.checkForOverlay(index.index);
				
				if(safe)
				{
					if(this.columnData[index.index].type > 1)
					{
						safe = false;
					}
				}
			}
		}
		
		// Try to remove an existing comment
		$('.comment').remove();
		
		// Insert the comment
		if(this.commentParent)
		{
			this.commentParent.css('z-index', '');
		}
		var comment = $('<div class="comment"><div class="arrow"></div><strong>Visste du at...</strong>' + this.comments[Math.floor(Math.random() * this.comments.length)].fact + '</div>');
		comment.attr('id', this.COMMENT_IDS[index.type]);
		this.commentParent = $('#photoList > li:eq(' + index.index + ')');
		this.commentParent.css('z-index', '102');
		this.commentParent.append(comment);
		
		// Insert a new one
		setTimeout(function() { girl.faces.showComment(); }, this.textDisplayDelay);
	},
	
	loadComments		: function()
	{
		var url = girl.urlTo('/facts');
		$.ajax({
		    type: 'GET',
		    url: url,
		    dataType: 'json',
		    success: function(data) {
				girl.faces.comments = data;
			}
		});
	},
	
	// Inserts new element
	insertNewElement	: function()
	{	
		if (this.nextElement == null)
		{
			this.nextElement = this.createListElement(this.getNextElement());
		}
		this.list.prepend(this.nextElement);
		this.animate(true);
	
		this.nextElement.css('opacity', '0');
		this.nextElement.animate({opacity: 1}, this.animationFade);
		
		this.nextElement = this.createListElement(this.getNextElement());
		$("#photoList > li:last").remove();
		this.columnData.pop();
	},
	
	// Returns an element from one of the queues
	getNextElement		: function()
	{
		var type = girl.faces.ELEMENT_TYPE.SMALL;
		var bigImageThreshold = Math.round(this.columns * 3);
		
		if(this.timeSinceBigPicture > bigImageThreshold)
		{
			if (Math.floor(Math.random() * 10) < 3) {
				type = Math.round(Math.random()) + 2;
				
				if(type == 3 && $('.listStory').length == 4)
				{
					type = 2;
				}
			}
		}
		
		this.timeSinceBigPicture++;
		
		switch(type)
		{
			case girl.faces.ELEMENT_TYPE.SMALL:
				if(girl.faces.queues.small.length == 0)
				{
					this.populateQueue(type, 20);
				}
				
				var element = girl.faces.queues.small.pop();
				break;
			case girl.faces.ELEMENT_TYPE.MEDIUM:
				this.timeSinceBigPicture = 0;
				
				var used = true;
				while(used)
				{
					var celebrityId = Math.floor(Math.random() * girl.faces.queues.medium.length);
					if($('#storyId' + girl.faces.queues.medium[celebrityId].id).length == 0)
					{
						used = false;
					}
				}
				
				var element = girl.faces.queues.medium[celebrityId];
				break;
			case girl.faces.ELEMENT_TYPE.LARGE:
				this.timeSinceBigPicture = 0;
				
				var used = true;
				while(used)
				{
					var storyId = Math.floor(Math.random() * girl.faces.queues.large.length);
					if($('#storyId' + storyId).length == 0)
					{
						used = false;
					}
				}
				
				var element = girl.faces.queues.large[storyId];
				break;
		}
		this.columnData.push({type: element.type});
		return element;
	},
	
	animate			: function(start)
	{
		if(start)
		{
			this.animationLeftCurrent = this.animationLeftFrom;
			this.animationRightCurrent = this.animationRightFrom;
		}
		else
		{
			this.animationLeftCurrent++;
			this.animationRightCurrent--;
		}
		
		this.list.css({
			'margin-left'	: this.animationLeftCurrent + 'px',
			'margin-right'	: this.animationRightCurrent + 'px'
		});
		
		if(this.animationLeftCurrent == 0)
		{
			setTimeout(function() { girl.faces.insertNewElement(); }, this.animationDelay);
		}
		else
		{
			setTimeout(function() { girl.faces.animate(false); }, this.animationDelay);
		}
	},
	
	// Creates a list element
	createListElement	: function(data)
	{
		if(data.type == girl.faces.ELEMENT_TYPE.LARGE)
		{
			return $('<li id="storyId' + data.id + '" class="listStory"><a href="' + data.link + '"><img src="' + data.image + '" /></a></li>');
		}
		else if(data.type == girl.faces.ELEMENT_TYPE.MEDIUM)
		{
			return $('<li id="celebrity' + data.id + '"><img src="' + data.image + '" /></li>');
		}
		else
		{
			var image = 'http://plan-jentekampanjen.s3.amazonaws.com/' + data.id + '.jpg';
			if(data.nettby == 1)
			{
				return $('<li><img src="' + image + '" title="' + data.name + ' fra Nettby" /></li>');
			}
			else
			{
				return $('<li><img src="' + image + '" /></li>');
			}
		}
	},
	
	// Populate one of the queues with elements loaded from json
	populateQueue		: function(type, elements)
	{
		var url = girl.baseUrl + '/wall/' + elements + '/' + type + '/' + this.lastId;
		$.ajax({
		    type: 'GET',
		    url: url,
		    dataType: 'json',
		    success: function(data) { 
				switch(type)
				{
					case girl.faces.ELEMENT_TYPE.SMALL:
						for(i = 0; i < data.length; i++)
						{
							girl.faces.queues.small.unshift(data[i]);
							if(parseInt(data[i].id) > girl.faces.lastId)
							{
								girl.faces.lastId = data[i].id;
							}
						}
						break;
					case girl.faces.ELEMENT_TYPE.MEDIUM:
						girl.faces.queues.medium = data;
						break;
					case girl.faces.ELEMENT_TYPE.LARGE:
						girl.faces.queues.large = data;
						break;
				}
			},
		    data: {},
		    async: false
		});
	},
	
	// Sets the height of the wrapper div and calculates how many
	// columns and rows the current screen size can hold
	calculateSize		: function()
	{
		var wrapper = $('#photos');
		
		// Find the minimum height of the photo wrapper
		var minHeight = 150 + 550 + 150;
		var canvasHeight = $(window).height() - 43;
		
		wrapper.height(Math.max(minHeight, canvasHeight));
		
		// Calculate number of columns and rows
		var tempWidth = wrapper.width() + 200;
		
		$('#photos > ul').width(tempWidth + 50);
		
		this.animationRightFrom = 150;
		
		// Hide ribbon if screen is too small
		if($(window).width() <= 1024)
		{
			$('#ribbon_vgtv').hide();
		}
		
		// Calculate number of rows and columns
		this.columns = Math.ceil(tempWidth / 50);
		this.rows = Math.ceil(wrapper.height() / 50) + 1;
		
		this.visibleColumns = Math.ceil(wrapper.width() / 50);
		this.visibleRows = this.rows;
		
		// Find speed of animation based on size
		if(wrapper.width() < 1200)
		{
			this.animationDelay = 100;
		}
		else if(wrapper.width() < 1700)
		{
			this.animationDelay = 150;
		}
		else
		{
			this.animationDelay = 200;
		}
		
		// Find safe columns to spawn comments in
		this.commentSpawnColumns = [];
		$('.mark').remove();
		
		var maxIndex = this.columns * this.rows;
		for(i = 0; i < maxIndex; i++)
		{
			var row = Math.floor(i / this.columns);
			var column = i - (row * this.columns);
			
			// Element too far to the left
			if(column < 2)
			{
				continue;
			}
			
			// If above row 2, check for space below
			if(row < 2)
			{
				if(column >= 16 && column < (this.visibleColumns - 3))
				{
					this.insertCommentSpawn(i, this.COMMENT_POSITION.BELOW);
				}
				continue;
			}
			
			// Inside/around box
			if(column < 16 && (row > 2 && row < 15))
			{
				
				if(column >= 14 && column < 16)
				{
					this.insertCommentSpawn(i, this.COMMENT_POSITION.RIGHT);
				}
				else if(row > 12 && column > 1)
				{
					this.insertCommentSpawn(i, this.COMMENT_POSITION.BELOW);
				}
				
				continue;
			}
			
			// All the way to the right
			if(column >= (this.visibleColumns - 3))
			{
				if(column < (this.visibleColumns - 1) && row < (this.visibleRows - 2))
				{
					this.insertCommentSpawn(i, this.COMMENT_POSITION.LEFT);
				}
				
				continue;
			}
			
			// Do not display at bottom
			if(row == (this.rows - 1))
			{
				continue;
			}
			
			// Default with comment above
			this.insertCommentSpawn(i, this.COMMENT_POSITION.ABOVE);
		}
	},
	
	markColumn		: function(index, color)
	{
		var row = Math.floor(index / this.columns);
		var column = index - (row * this.columns);
		
		var top = ((row * 50) + 43);
		var left = (column * 50);
		
		var element = $('<div class="mark"></div>');
		element.css({
			'position'		: 'absolute',
			'top'			: top + 'px',
			'left'			: left + 'px',
			'width'			: '50px',
			'height'		: '50px',
			'background'	: color,
			'opacity'		: '0.5',
			'z-index'		: '101'
		});
		
		$('body').append(element);
	},
	
	insertCommentSpawn		: function(index, type)
	{
		this.commentSpawnColumns.push({
			index	: index,
			type	: type
		});
	},
	
	checkForOverlay			: function(index)
	{
		var mediumIndexes = [
		 	index + 1, 
		 	index + this.columns, 
		 	index + (this.columns + 1)
		 ];
		
		for(i = 0; i < mediumIndexes.length; i++)
		{
			if(mediumIndexes[i] < this.columnData.length)
			{
				if(this.columnData[mediumIndexes[i]].type >= 2)
				{
					return false;
				}
			}
		}
		
		var largeIndexes = [
		 	index +2,
		 	index + this.columns + 2,
		 	index + (this.columns * 2), 
		 	index + ((this.columns * 2) + 1),
		 	index + ((this.columns * 2) + 2)
		];
		
		for(i = 0; i < largeIndexes.length; i++)
		{
			if(largeIndexes[i] < this.columnData.length)
			{
				if(this.columnData[largeIndexes[i]].type == 3)
				{
					return false;
				}
			}
		}
		
		return true;
	},
	
	findRowAndColumn	: function(index)
	{
		var row = Math.floor(index / this.columns);
		var column = i - (row * this.columns);
	}
};

girl.stories = 
{
	activeTab		: 'mina',
	changeTab		: function(tab)
	{
		if(tab != this.activeTab)
		{
			$('#' + this.activeTab + ' > a').removeClass('active');
			$('#' + tab + ' > a').addClass('active');
			$('#about_view').attr('className', 'about_view_' + tab);
			$('#storyContent').load(girl.urlTo('/story/' + tab));
			this.activeTab = tab;
		}
	},
	init			: function()
	{
		var anchor = window.location.href.split("#");
		if(anchor.length == 2)
		{
			this.changeTab(anchor[1]);
		}
	},
	
	share			: 
	{
		twitter		: function()
		{
			girl.popup.show('/twitter/action/shareStory/' + girl.stories.activeTab, 800, 400);
		},
		
		facebook	: function()
		{
			FB.Connect.showShareDialog (girl.urlTo('/spre-ordet#' + girl.stories.activeTab), function() {
			});
		},
		
		nettby		: function()
		{
			var name = girl.stories.activeTab;
			var url = girl.urlTo('/spre-ordet#' + name);
			name = name.substr(0, 1).toUpperCase() + name.substr(1);
			var description = $('#storyContent > .intro').text();
			name = name + ' sin utrolige historie';
			
			url = escape(url);
			name = escape(name);
			description = escape(description);
			
			window.open('http://www.nettby.no/user/edit_link.php?name='+name+'&url='+url+'&description='+description,'edit_link','scrollbars=no,width=450,height=430');
		}
	}
};

girl.share = {
	show	: function(parent, tab)
	{
		if ($('#' + parent + ' .content .' + tab + ':hidden').length > 0) 
		{
			$('#' + parent + ' .content:visible').slideUp('fast');
			
			$('#' + parent + ' .content > *').hide();
			$('#' + parent + ' .content .' + tab).show();
			
			$('#' + parent + ' .content').slideDown('normal');
		}
	},
	
	email :
	{
		contacts	: null,
		selected	: null,
		
		getContacts	: function(parent)
		{
			data = {
				provider : $('#' + parent + ' .content .email .provider').val(),
				username : $('#' + parent + ' .content .email .username').val(),
				password : $('#' + parent + ' .content .email .password').val()
			};
			
			$.post(girl.urlTo('/invite/getContacts'), data, function(response)
			{
				var container = $('$#' + parent + ' .content .email .contactsContainer');
				$('$#' + parent + ' .content .email .contactsContainer *').remove();
				if (response.length > 0)
				{
					girl.share.email.contacts = response;
					
					var table = $('<table cellpadding="0" cellspacing="0" width="100%"></table>');
					for (i = 0; i < girl.share.email.contacts.length; i++)
					{
						var row = $('<tr></tr>');
						if ((i + 1) % 2 == 0) {
							row.addClass('dark');
						}
						
						row.attr('id', 'contact-' + i);
						
						row.click(function()
						{
							$(this).toggleClass('selected');
						});
						
						row.append('<td>' + girl.share.email.contacts[i].name + '</td><td>' + girl.share.email.contacts[i].email + '</td>');
						table.append(row);
					}
					
					container.append(table);
				}
				else
				{
					container.append('<p>Fant ingen kontakter</p>');	
				}
				
				container.show();
				
			}, 'json');
		}
	}
};

girl.dialog =
{
	show	: function(page, width, height, title)
	{
		var dialog = $('<div id="dialog"></div>');
		
		$('body').append(dialog);
		
		dialog.dialog({
			width		: width,
			height		: height,
			modal		: true,
			title		: title
		});
		
		$('.ui-widget-overlay').css('opacity', 0.5);
		
		dialog.load(girl.urlTo(page));
	}
};

girl.popup =
{
	window 	: null,
	show	: function(page, width, height)
	{
		var url = girl.urlTo(page);
		this.window = window.open(url, 'popupWindow',
			'location=1,width=' + width + ',height=' + height
		);
		
		var screenWidth = screen.width;
		var screenHeight = screen.height;
		
		var xPos = Math.round((screenWidth / 2) - (width / 2));
		var yPos = Math.round((screenHeight / 2) - (height / 2));
		
		this.window.moveTo(xPos, yPos);
	}
};

girl.inspire =
{
	twitter		: function()
	{
		girl.popup.show('/twitter/action/setStatus/' + Base64.encode(this.getStatus()), 800, 400);
	},
	
	facebook	: function()
	{
		FB.Connect.showPermissionDialog('status_update', function() {
			var sequencer = new FB.BatchSequencer();
			var pendingResult = FB.Facebook.apiClient.users_setStatus(girl.inspire.getStatus(), false, true, sequencer);
			
			sequencer.execute(function() {
			    if(pendingResult.result)
			    {
			    	$('#inspire > .box > .bottom').append('<div id="inspireFeedback">Statusen din ble endret.</div>');
			    	$('#inspireFeedback').animate({opacity : 0}, 1500, function() { $('#inspireFeedback').remove(); });
			    }
			    else
			    {
			    	$('#inspire > .box > .bottom').append('<div id="inspireFeedback">Det oppstod en feil, statusen ble ikke endret.</div>');
			    	$('#inspireFeedback').animate({opacity : 0}, 1500, function() { $('#inspireFeedback').remove(); });
			    }
			});
		});
	},
	
	msn			: function()
	{
		$('#msnInspireLink').attr('href', 'aim:setstatus?' + this.getStatus().replace(/ /g, '+'));
	},
	
	getStatus	: function()
	{
		return $('#statusMessage').val();
	}
};

girl.upload = 
{
	uploaded			: false,
	start				: function()
	{
		$('#content').hide();
		$('#miniContent').show();
	},
	transferComplete	: function(uid)
	{
		var url = girl.urlToResource('/www/people/' + uid + '/cropper.jpg');
		girl.profilePicture.show(url);
		
		
		this.uploaded = true;
	},
	complete			: function()
	{
		return this.uploaded;
	},
	error				: function(code)
	{
		alert(code);
	}
};

function toggleHelpText(element, value)
{
	if(element.value == value)
	{
		element.value = '';
	}
	else if(element.value == '')
	{
		element.value = value;
	}
}

function openWindow(url, width, height)
{
	window.open(url, 'openWindow', 'width=' + width + ',height=' + height + '');
}

function getMousePos(event)
{
	if(event.pageX || event.pageY){
		return {x:event.pageX, y:event.pageY};
	}
	return {
		x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:event.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

Base64 = 
	{
	 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	 
		// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
	 
		// public method for decoding
	decode : function (input) {
			var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
	 
		// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
	 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
	 
		// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
};

$(document).ready(function(){
	var _speed = 100;
	var check_speed = 15000;
	var _numb, n_numb;
	var _step = 23;
	var _hold = $('#counter');
	var _f = false;
	if(_hold.length){
		_hold.html('<div></div><div></div><div></div><div></div><div></div><div></div>');
		var _list = _hold.children();
		
		$.ajax({
			url: girl.urlTo('/counter/init'),
			dataType: 'text',
			success: function(_val){
				_numb = parseInt(_val);
				if(!isNaN(_numb)){
					for(var i = 0; i < _list.length; i++){
						_list.get(i)._n = _numb%10*3;
						_numb = Math.floor(_numb/10);
						_list.eq(i).css('top', -_list.get(i)._n*_step);
					}
					_numb = _val;
					_f = true;
					setTimeout(function(){
						updateNumb();
					}, check_speed);
				}
			}
		});
	}
	
	function updateNumb(){
		$.ajax({
			url: girl.urlTo('/counter/update'),
			dataType: 'text',
			success: function(_val){
				n_numb = parseInt(_val);
				if(n_numb != _numb && !isNaN(n_numb)){
					if(_f){
						_f = false;
						moveFirst();
					}
				}
				setTimeout(function(){
					updateNumb();
				}, check_speed);
			}
		});
	}
	
	function moveFirst(){
		setTimeout(function(){
			if(_list.get(0)._n < 29) _list.get(0)._n++;
			else{
				_list.get(0)._n = 0;
				moveSecond(1);
			}
			_list.eq(0).css('top', -_list.get(0)._n*_step);
			setTimeout(function(){
				if(_list.get(0)._n < 29) _list.get(0)._n++;
				else{
					_list.get(0)._n = 0;
					moveSecond(1);
				}
				_list.eq(0).css('top', -_list.get(0)._n*_step);
				setTimeout(function(){
					if(_list.get(0)._n < 29) _list.get(0)._n++;
					else{
						_list.get(0)._n = 0;
						moveSecond(1);
					}
					_list.eq(0).css('top', -_list.get(0)._n*_step);
					_numb++;
					if(_numb < n_numb) moveFirst();
					else _f = true;
				}, _speed);
			}, _speed);
		}, _speed);
	}
	function moveSecond(_i){
		setTimeout(function(){
			if(_list.get(_i)._n < 29) _list.get(_i)._n++;
			else{
				_list.get(_i)._n = 0;
				if(_i < 5) moveSecond(_i + 1);
			}
			_list.eq(_i).css('top', -_list.get(_i)._n*_step);
			setTimeout(function(){
				if(_list.get(_i)._n < 29) _list.get(_i)._n++;
				else{
					_list.get(_i)._n = 0;
					if(_i < 5) moveSecond(_i + 1);
				}
				_list.eq(_i).css('top', -_list.get(_i)._n*_step);
				setTimeout(function(){
					if(_list.get(_i)._n < 29) _list.get(_i)._n++;
					else{
						_list.get(_i)._n = 0;
						if(_i < 5) moveSecond(_i + 1);
					}
					_list.eq(_i).css('top', -_list.get(_i)._n*_step);
				}, _speed);
			}, _speed);
		}, _speed);
	}
});