/*

Interface 1.6

Copyright 2005-2006 Jimmy Morin, All Rights Reserved

This javascript may not be used without permission from Jimmy Morin (contact@jimmymorin.com)

*/

var infoWindowObj;
function infoWindow(url)
{
	infoWindowObj = window.open(url, 'infoWindow', 'width=550,height=250,location=no,toolbar=no,resize=auto,scrollbars=yes');
};

var imagePreviewWindow;
function imagePreview(image, frame)
{
	imagePreviewWindow = window.open('preview.php?image=' + image + '&frame=' + frame + '&paper=', 'imagePreviewWindow', 'location=no,toolbar=no,resize=auto');
};

function validateForm()
{
	var invalid = 0;

	$('#name').style.background = $('#surname').style.background = $('#street').style.background = $('#city').style.background = $('#zip').style.background = $('#phone').style.background = $('#ssn').style.background = $('#mail').style.background = $('#agreement').style.background = $('#name2').style.background = $('#street2').style.background =  $('#city2').style.background =  $('#zip2').style.background = $('#agreement_text').style.background = '';

	if ($('#name').val() == '')
	{
		$('#name').style.background = '#FFC93D';
		invalid++;
	}
	else if ($('#company').val() == '')
	{
		$('#company').style.background = '#FFC93D';
		invalid++;
	}


	if ($('#street').val() == '')
	{
		$('#street').style.background = '#FFC93D';
		invalid++;
	}

	if ($('#city').val() == '')
	{
		$('#city').style.background = '#FFC93D';
		invalid++;
	}

	if (!$('#zip').val().match(/^[0-9 ]+$/))
	{
		$('#zip').style.background = '#FFC93D';
		invalid++;
	}

	if (!$('#phone').val().match(/^[0-9\- ]+$/))
	{
		$('#phone').style.background = '#FFC93D';
		invalid++;
	}

	if (!$('#ssn').val().match(/^[0-9\- ]+$/))
	{
		$('#ssn').style.background = '#FFC93D';
		invalid++;
	}

	if (!$('#mail').val().match(/^[a-z0-9]{1}[a-z0-9\.\-_]+@[a-z0-9\-\.]+[a-z]{2,6}$/i))
	{
		$('#mail').style.background = '#FFC93D';
		invalid++;
	}

	if ($('#agreement').checked == false)
	{
		$('#agreement_text').style.background = '#FFC93D';
		invalid++;
	}

	if ($('#name2').val() != '' || $('#street2').val() != '' || $('#city2').val() != '' || $('#zip2').val() != '')
	{
		if ($('name2').val() == '')
		{
			$('#name').style.background = '#FFC93D';
			invalid++;
		}

		if ($('#street2').val() == '')
		{
			$('#street2').style.background = '#FFC93D';
			invalid++;
		}

		if ($('#city2').val() == '')
		{
			$('#city2').style.background = '#FFC93D';
			invalid++;
		}

		if (!$('#zip2').match(/^[0-9 ]+$/))
		{
			$('#zip2').style.background = '#FFC93D';
			invalid++;
		}
	}

	if (invalid)
	{
		alert('Fält markerade med orange är inte korrekt ifyllda, var snäll och kontrollera dessa och prova igen.');

		return false;
	}
	else
	{
		return true;
	}
};

Upload = function() {
	this.interval	= null;

	if (this.validate('#imageInput'))
	{
		if ($('#error'))
			$('#error').hide();

		$('#uploadForm').hide();
		$('#uploadStatus').show();

		var sid	= $('#sid').val();

		if (typeof sid != 'undefined')
		{
			this.interval = setInterval(function() {
				$.get('/uploadStatus.php?sid=' + sid, function(response)
				{
					if (response != '')
					{
						response = response.split(';');

						var uploadStatus		= response[1];
						var uploadPercent		= response[2];
						var uploadSpeed		= response[3];
						var uploadDuration	= response[4];
						var uploadRemaining	= response[5];

						switch (uploadStatus)
						{
							case '0':
								$('#uploadProgressBar').css('width', uploadPercent + '%');
								$('#uploadProgressInfo').html(uploadPercent + ' % (' + uploadSpeed + 'kb/s) ~ ' + uploadRemaining + ' sekund(er) kvar.');
							break;

							case '1':
								clearInterval(this.interval);
			
								$('#uploadProgressBar').css('width', '100%');
								$('#uploadProgressInfo').html('Uppladdning klar, bilden hanteras. Var snäll och dröj.');

								location.href = '/format.php?sid=' + $('#sid').val() + '&m=' + $('#member').val();
							break;

							case '2':
								clearInterval(this.interval);
			
								location.href = '/index.php?sid=' + $('#sid').val() + '&error=upload';
							break;
						}
					}
				});
			}, 2000);

			$('#uploadProgressInfo').html('Påbörjar uppladdning, var snäll och dröj.');
		}
		else
		{
			location.href = '/index.php?error=upload';
		}

		return true;
	}

	return false;
};

Upload.prototype = {
	validate : function(item)
	{
		var file = $(item).val();

		if (file == '')
		{
			alert('Du har glömt välja vilken bild du vill ladda upp.');
			return false;
		}

		if (!file.match(/.+\.(jpg|jpeg|png|bmp|tif|tiff)/i))
		{
			alert('Filen du försöker ladda upp har fel filformat\n\nVar snäll och välj en annan fil och försök igen.\n\nAccepterade filformat:\njpg, png, bmp och tiff');
			return false;
		}

		return true;
	}
};

var cart;
Cart = function() {
	$('#cartContents').load('/cart.php?cmd=count', function() {
		cart.icon();
	});
};
Cart.prototype = {
	add: function(itemId)
	{
		$('#cartContents').load('/cart.php?cmd=add&id=' + itemId, function() {
			cart.icon();
		});
	},

	icon: function()
	{
		var items = $('#cartItems').html();

		if (items == '')
			$('#cartIcon').attr('src', '/templates/images/icons/cart_empty.png');
		else if (items == '1')
			$('#cartIcon').attr('src', '/templates/images/icons/cart_one.png');
		else if (items == '2')
			$('#cartIcon').attr('src', '/templates/images/icons/cart_two.png');
		else if (items == '3')
			$('#cartIcon').attr('src', '/templates/images/icons/cart_three.png');
		else
			$('#cartIcon').attr('src', '/templates/images/icons/cart_more.png');
	}
};

var print;
Print = function() {
	this.id				= null;
	this.cost				= 0;
	this.paper				= 0;
	this.sizeX				= 0;
	this.sizeY				= 0;
	this.sizeArea			= 0;
	this.sizeCircumference		= 0;
	this.frame				= 'empty';
	this.border				= 0;
	this.mode				= '';

	this.picturePrice			= 0;
	this.printPrice			= 0;
	this.paperPrice			= 0;
	this.sizePrice			= 0;
	this.framingPrice			= 0;
	this.framePrice			= 0;

	this.imageWidth			= $('#printImageSource').width();
	this.imageHeight			= $('#printImageSource').height();

	if ($('#id'))
		this.id = $('#id').val();

	if ($('#mode').val() != '')
		this.mode = $('#mode').val();

	if ($('#price').val() != '')
		this.picturePrice = parseInt($('#price').val());
};
Print.prototype = {
	setPaper : function(obj, paper, paperPrice, printPrice, framingPrice, border)
	{
		if (obj && paper)
		{
			$('#printPapers div').attr('class', '');

			obj.className = 'set';

			this.paper			= paper;
			this.paperPrice		= paperPrice;
			this.printPrice		= printPrice;
			this.framingPrice 	= framingPrice;

			if (border)
			{
				this.border = 1;

				$('#printImageSource').css('border', '30px solid #FFF');

				imageHeight	= Math.round((this.imageHeight / 100) * (((this.imageWidth - 60) / this.imageWidth) * 100));
				imageWidth	= this.imageWidth - 60;

				$('#printImageSource').attr('width', imageWidth);
				$('#printImageSource').attr('height', imageHeight);
			}
			else
			{
				this.border = 0;

				$('#printImageSource').css('border', 'none');

				$('#printImageSource').attr('width', this.imageWidth);
				$('#printImageSource').attr('height', this.imageHeight);
			}

			if ($('#printHelp')[0].offsetHeight > 15)
				$('#printHelp').fadeOut(300, function() {
					if ($('#printSizes')[0].offsetHeight < 15)
						$('#printSizes').fadeIn(500);
				});


			this.updatePrice();
			this.updateFrame();
		}
	},

	setSize : function(obj, sizeX, sizeY)
	{
		if (sizeX != '' && sizeY != '')
		{
			$('#printSizes div').attr('class', '');

			obj.className = 'set';

			this.sizeX = parseInt(sizeX);
			this.sizeY = parseInt(sizeY);

			this.sizeArea = (this.sizeX * this.sizeY) / 10000;
			this.sizeCircumference = ((this.sizeX + this.sizeY) * 2 / 100);

			this.updateFrame();
			this.updatePrice();

			if ($('#printFrames')[0].offsetHeight < 15)
				$('#printFrames').fadeIn(600);
		}
	},

	setFrame : function(obj, frame, framePrice)
	{
		if (frame && framePrice)
		{
			$('#printFrames div').attr('class', '');

			obj.className = 'set';

			this.frame = frame;
			this.framePrice = parseInt(framePrice);

			if ($('#printCosts')[0].offsetHeight < 15)
				$('#printCosts').fadeIn(500);

			this.updateFrame();
			this.updatePrice();
		}
	},

	updateFrame : function()
	{
		$('#printImage div').each(function () {
			switch ($(this).attr('class').toLowerCase())
			{
				case 'tl':
				case 'tr':
				case 'bl':
				case 'br':
					var imageArea = print.sizeX * print.sizeY;

					if (imageArea < 2500)
						$(this).css('background-image', 'url(/templates/images/frames/large/' + print.frame + '.png)');
					else if (imageArea > 2500 && imageArea < 6500)
						$(this).css('background-image', 'url(/templates/images/frames/medium/' + print.frame + '.png)');
					else if (imageArea > 6500)
						$(this).css('background-image', 'url(/templates/images/frames/small/' + print.frame + '.png)');
					break;
			}
		});
	},

	updatePrice : function()
	{
		var cost = this.picturePrice;

		cost += this.printPrice;

		cost += (this.sizeArea * this.paperPrice);

		if (this.frame != 'empty')
			cost += this.framingPrice;

		cost += this.sizeCircumference * this.framePrice;

		this.cost = Math.round(cost);

		$('#printCost').html(this.cost);
	}
};

function reportImage(userId, imageId)
{
	var question =	'Är du säker på att du vill rapportera den här bilden?\n\n' +
				'OBS!!\n' + 
				'Rapportera endast bilder som ej följer reglerna för Fotokonst.se\n' + 
				'reglerna finner du i menyn om du går till "Om Fotokonst" och sedan\n' +
				'klickar på "Medlemsvillkor"';

	if (confirm(question))
	{
		$.get('view_report.php?id=' + imageId, function(response) {
			if (response == '1')
				alert('Din rapportering för den här bilden har mottagits, tack.');

			if (response == '2')
				alert('Din rapportering ignorerades då du redan rapporterat den här bilden en gång.');
		});
	}
}

function textCounter(textObj, counterId, maxLength)
{
	if (typeof textObj == 'object')
	{
		textLength = $(textObj).val().length;

		if (textLength > maxLength)
		{
			$(textObj).val($(textObj).val().substr(0, maxLength));

			if (document.selection)
			{
				var range = textObj.createTextRange();

				range.moveStart = maxLength;
				range.moveEnd = maxLength;

				range.select();
			}
			else if (textObj.selectionStart)
			{
				textObj.focus()

				//textObj.setSelectionRange(maxLength, maxLength);
				textObj.selectionStart = maxLength;
				textObj.selectionEnd = maxLength;
			}

			$(counterId).val(maxLength);
		}
		else
		{
			$(counterId).val(textLength);
		}
	}
}

$('document').ready(function() {
	if ($.browser.msie)
	{
		$('#menu li').each(function() {
			$(this).hover(
				function() { $('ul', this).addClass('hover'); },
				function() { $('ul', this).removeClass('hover'); }
			);;
		});
	}

	$('.box').prepend('<div class="btl">&nbsp;</div><div class="btr">&nbsp;</div><div class="bbl">&nbsp;</div><div class="bbr">&nbsp;</div>');

	$('.shadow').each(function() {
		var w = parseInt($('img', this).width());

		html	= '	<div class="shadowBox" style="width:' + (w + 40) + 'px">' +
					'<div class="tl" style="width:' + (w + 20) + 'px">' +
						'<div class="tr">' +
							$(this).html() + 
							'<div class="bl">' +
								'<div class="br">&nbsp;</div>' +
							'</div>' +
						'</div>' +
					'</div>' +
				'</div>';

		$(this).html(html);
	});

	print = new Print();
	cart = new Cart();

	$('#categories ul').css('display', 'none');

	$('#categories li a').each(function() {
		$(this).bind('click', function() {
			if ($(this).siblings('ul').length)
			{
				$('#categories ul').filter(':visible').slideUp();
				//$('ul', this.parentNode)[0].css('display', 'block');

				$('ul', this.parentNode).slideDown();

				return false;
			}
		});
	});
});
