tinyMCE.init({
	mode : "exact",
	elements : "contentEditor",
	theme : "advanced",
	width: '100%',
	height: '450px',
	theme_advanced_toolbar_location : "top",
	theme_advanced_blockformats : "p,h4",
	content_css : "/layout/css/screen.css?" + new Date().getTime(),
	plugins : "table"
});

var backup;
var BASE_DIR = '/';

$(document).ready(function() {
		
	$('a.lightbox').lightBox({
		txtImage: 'Kuva',
		txtOf: '/'		
	});
	
	$('a.deleteEventPic').click(function() {
		var row = $(this).parent();
		if(confirm('Haluatko varmasti poistaa kuvan tapahtumasta?')) {
			$.ajax({
				url: BASE_DIR + 'hallinta/deleteEventPic/',
				data: { imageID: $(this).attr('id').replace('eventpic_', '') },
				type: 'POST',
				success: function() {
					if(row.siblings().size() == 0) {
						row.parent().parent().remove();
					} else {
						row.remove();
					}
				}
			});					
		}
		return false;
	});
	
	$('a.addPicField').click(function() {
		var li = $(this).parent().prev().find('li:last');
		li.after(li.clone().val(''));
		return false;
	});
	
		
	$('ul#productCards li').each(function() {
		$(this).css('cursor', 'pointer');
			
		$(this).click(function() {
			window.location = $(this).find('a').attr('href');
		});
		
		$(this).hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
	});
	
	$('a.delete').click(function() {
		if($(this).hasClass('icon') && $(this).parents('table').size() == 0) {
			return confirm('Oletko varma että haluat poistaa rivin?');
		}
	});

	$('#attachments a.delete').unbind('click');	
	$('#attachments a.delete').click(function() {
		var link = $(this); 
		if($(this).hasClass('icon')) {
			if(confirm('Oletko varma että haluat poistaa rivin? Tätä toimintoa ei voi peruuttaa!')) {
				
				$.ajax({
					type: 'post',
					url: BASE_DIR+'hallinta/deleteFile/'+$(this).attr('id').replace('id_', '')+'/',
					success: function() {
						link.parents('li').remove();
						
						if($('ul#attachments').find('input[type=file]').size() > 0) {
							var file = $('ul#attachments').find('input[type=file]:last').attr('name').split('_');
							file = parseInt(file[1]) + 1;
						}
						else {
							var file = 1;
						}
						
						$('ul#attachments').append('<li><input type="file" class="file" name="file_'+file+'" /></li>');
					}
				});
			}
		}
		return false;
	});
	
	$('ul#selectedImages li').each(function() {
		$('ul.hallintaGallery a#'+$(this).attr('id')).addClass('selected');
	});
	
	$('div#galleryWrapper a.galleryNavigation').click(function() {
		var amount = $(this).attr('id') == 'galleryPrev' ? -1 : 1;
		var currentPage = parseInt($('div#galleryWrapper ul').attr('id').replace('page_', ''));
		var newPage = amount + currentPage;
		
		if(newPage > 0) {
			getGalleryPage(newPage)
		}
		return false;				
	});

function getGalleryPage(page) {
	$.ajax({
		type: 'get',
		url: BASE_DIR+'hallinta/getImagePage/'+page+'/',
		success: function(response) {
			if(response.trim().length > 0) {
				var newUL = $(response);
				$('div#galleryWrapper ul').fadeOut(function() {
					newUL.hide();
					
					$('ul#selectedImages li').each(function() {
						newUL.find('a#'+$(this).attr('id')).addClass('selected');
					});
					
					$(this).replaceWith(newUL);
					newUL.fadeIn();
					if(!$('div#galleryWrapper').hasClass('addImages')) {
						$('a.lightbox').lightBox({
							txtImage: 'Kuva',
							txtOf: '/'		
						});
					}
				});
			}
		}
	});
}

	$('input#deleteGalleryPics').change(function() {
		if($(this).is(':checked')) {
			$('div#galleryWrapper a.lightbox').each(function() {
				var clone = $(this).clone();
				clone.addClass('clone');
				$(this).hide();
				$(this).after(clone);
			});
			$('div#galleryWrapper a.clone').click(function() {
				var imageID = $(this).attr('id').replace('image_', '');
				var pageID = $(this).parents('ul').attr('id').replace('page_', '');
				if(confirm('Haluatko varmasti poistaa kuvan?')) {
					$.ajax({
						type: 'POST',
						url: BASE_DIR+'hallinta/deletePic/',
						data: 'imageID='+imageID,
						success: function(response) {
							getGalleryPage(pageID);
						}
					});
				}
				return false;
			});
		}
		else
		{
			$('div#galleryWrapper img.clone').remove();
			$('div#galleryWrapper img').show();
		}
		
	});
	
	if($('div#productGalleryWrapper')[0]) {
		var firstImage = $('div#productGalleryWrapper li:first a');
		
		
		var id = firstImage.attr('id');
		var caption = firstImage.attr('title');
		$('div.productInfo').prepend('<img src="'+BASE_DIR+'kuva/product/'+id+'/" title="'+caption+'" class="productImage" />');
		/*$('div.contentBlock h2').prev('img').reflect({ height: 0.3 });*/
		
	}
	
	$('#leftColumn form.productForm h4').not('.static').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
	});
	
	$('form#addEvent').submit(function() {
			
		var dates = $(this).find('input[name=date]').val().split('-');
		
		for(var i = 0; i < dates.length; i++) {
			var date = dates[i].split('.');
			var day = parseInt(date[0], 10);
			var month = parseInt(date[1], 10);
			var year = parseInt(date[2], 10);
			
			$(this).find('input').removeClass('error');
			$(this).find('p.errorDescription').remove();
			
			if(
				day < 1 || day > 31 || 
				month < 1 || month > 12 || 
				year < 2008 || year > 2030 || 
				isNaN(day) || isNaN(month) || isNaN(year) || 
				i == 2)
			{
				$(this).find('input[name=date]').addClass('error');
				$(this).find('input[name=date]').after('<p class="errorDescription">Päivämäärä tulee olla muodossa DD.MM.YYYY</p>');
			}
			else if(parseInt(year+""+month+""+day) < prevdate && prevdate > 0) {
				$(this).find('input[name=date]').addClass('error');
				$(this).find('input[name=date]').after('<p class="errorDescription">Lopetuspäivämäärä ei voi olla ennen aloituspäivämäärää.</p>');
			}
			
			var prevdate = parseInt(year+""+month+""+day);
		}
		
		if($(this).find('input[name=excerpt]').val().length == 0) {
			$(this).find('input[name=excerpt]').addClass('error');
			$(this).find('input[name=excerpt]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
		}
		
		if($(this).find('.error').size() > 0) {
			return false;
		}
		else
		{
			return true;
		}
		
			
	});
	
	$('#leftColumn form.productForm h4').not('.static').click(function() {
		var col = $(this).next('div.collapse');
		if(col.is(':visible')) {
			$(this).removeClass('open');
			col.hide();
		}
		else
		{
			$('div.collapse').hide();
			$('#leftColumn form.productForm h4').removeClass('open')
			col.show();
			$(this).addClass('open');
		}	
	});
	
	$('#leftColumn form.productForm h4').not('.static').eq(0).addClass('open');
	$('div.collapse').not('div.collapse:first').hide();
	
	
	$('div.addImages ul.hallintaGallery li a').livequery('click', function() {
		$(this).toggleClass('selected');
		if($(this).hasClass('selected')) {
			var image = $(this).html();
			$('ul#selectedImages').append('<li id="'+$(this).attr('id')+'">'+image+'</li>');
		}
		else
		{
			$('ul#selectedImages li#'+$(this).attr('id')).remove();
		}
		return false;
	});
	
	$('#leftColumn ul#selectedImages li img').livequery('click', function() {
		$('#leftColumn ul.hallintaGallery li a#'+$(this).parent().attr('id')).removeClass('selected');
		$(this).parent().remove();
	});
	
	$('#tapahtumat a.more').click(function() {
		if($(this).hasClass('icon')) {
			var desc = $(this).parents('ul').next('ul.eventDescription');
			
			if($(this).parents('ul').next('ul.eventDescription').is(':visible')) {
				desc.slideUp(300);
				desc.find('textarea').val(backup);
			}
			else
			{
				$('ul.eventDescription').slideUp(300);
				backup = desc.find('textarea').val();
				desc.slideDown(300);
			}
		}
		return false;
	});
	
	
	$('a.eventDescription_submit').click(function() {
		$(this).parents('form').submit();
		return false;
	});
	
	$('a.eventDescription_cancel').click(function() {
		$(this).parents('ul').prev('ul').find('a.more').click();
		return false;
	});
	
	
	var d=new Date();

	$.ajax({
		type: 'get',
		url: BASE_DIR+'calendar/main/'+d.getFullYear()+'/'+(d.getMonth()+1),
		timeout: 1000,
		success: function(response) {
			
			$('div#calendarHolder h5').after(response);
			$('table#calendar td a').tooltip({ 
				track: true, 
				delay: 0, 
				showURL: false, 
				fade: 250,
				left: -10,
				positionLeft: true,
				bodyHandler: function() {
					var html = $(this).find('span').html();
					var tooltipContent = '';
					$(html.split("|")).each(function() {
						tooltipContent = tooltipContent + '<p>'+$(this)[0]+'</p>';
					});
					return tooltipContent;
				}
			});
		}
	});
	
	$('a#calendar_next').click(function() {
		calendarChange(1);
		return false;
	});
	
	$('a#calendar_prev').click(function() {
		calendarChange(-1);
		return false;
	});
	
	$('#tapahtumat ul li span').editable();
	
	$('ul#ajankohtaista li').each(function() {
		$(this).css('cursor', 'pointer');
			
		$(this).click(function() {
			window.location = $(this).find('a').attr('href');
		});
		
		$(this).hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
	});
	
	if($('p#addProductAddress')[0]) {
		$('p#addProductAddress span#group').html($('select#group option:selected').html().toLowerCase());
		$('p#addProductAddress span#shortTitle').html($('input#shortTitle').val());
		
		$('select#group').change(function() {
			$('p#addProductAddress span#group').html($('select#group option:selected').html().toLowerCase());
		});
		
		$('input#shortTitle').keydown(function(e) {
			
			if(e.keyCode > 105 || e.keyCode == 32) {
				return false;
			}
			
		});
		
		$('input#shortTitle').keyup(function(e) {
			$('p#addProductAddress span#shortTitle').html($('input#shortTitle').val().toLowerCase());
		});
		
		$('input[name=shortTitle]').blur(function() {
			var input = $(this);
			$.get(BASE_DIR+'hallinta/osoitetarkastus/'+$(this).val()+'/'+$('input[name=productID]').val()+'/', '', function(response) {
				response = parseInt(response);
				if(response == 1) {
					input.addClass('error');
					input.next('p.errorDescription').remove();
					input.after('<p class="errorDescription">Osoite on jo olemassa. Valitse toinen.</p>');
				}
				else if(response == 0) {
					input.removeClass('error');
					input.next('p.errorDescription').remove();
				}				
			});
		});	
	}
	
	
	
	$('form#contactForm').submit(function() {
			
		$(this).find('.error').removeClass('error');
		$(this).find('p.errorDescription').remove();
	
		if($(this).find('input[name=name]').val().length == 0) {
			$(this).find('input[name=name]').addClass('error');
			$(this).find('input[name=name]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
		}
		
		if($(this).find('input[name=title]').val().length == 0) {
			$(this).find('input[name=title]').addClass('error');
			$(this).find('input[name=title]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
		}
		
		if($(this).find('input[name=email]').val().length == 0) {
			$(this).find('input[name=email]').addClass('error');
			$(this).find('input[name=email]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
		}
		
		if($(this).find('textarea[name=message]').val().length == 0) {
			$(this).find('textarea[name=message]').addClass('error');
			$(this).find('textarea[name=message]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
		}
		
		var error = false;
		$(this).find('input').each(function() {
			if($(this).hasClass('error')) error = true;
		});
		
		return error ? false : true;
	});
	
	$('form.productForm').submit(function() {

		if($(this).find('input[name=title]').val().length == 0) {
			if(!$(this).find('input[name=title]').hasClass('error')) {
				$(this).find('input[name=title]').addClass('error');
				$(this).find('input[name=title]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
			}
		}
		else
		{
			$(this).find('input[name=title]').removeClass('error');
			$(this).find('input[name=title]').next('p.errorDescription').remove();
		}	
		
		if($(this).find('input[name=shortTitle]').val().length == 0) {
			if(!$(this).find('input[name=shortTitle]').hasClass('error')) {
				$(this).find('input[name=shortTitle]').addClass('error');
				$(this).find('input[name=shortTitle]').after('<p class="errorDescription">Kenttä ei saa olla tyhjä.</p>');
			}
		}
		else
		{
			$(this).find('input[name=shortTitle]').removeClass('error');
			$(this).find('input[name=shortTitle]').next('p.errorDescription').remove();
		}
		
		var input = $(this).find('input[name=shortTitle]');
		$.ajax({
			url: BASE_DIR+'hallinta/osoitetarkastus/'+input.val()+'/0/',
			async: false,
			success: function(response) {
				response = parseInt(response);
				if(response == 1) {
					input.addClass('error');
					input.next('p.errorDescription').remove();
					input.after('<p class="errorDescription">Osoite on jo olemassa. Valitse toinen.</p>');
				}
				else if(response == 0) {
					input.removeClass('error');
					input.next('p.errorDescription').remove();
				}
			}				
		});

		var images = new Array;
		$('#selectedImages li').each(function() {
			images.push($(this).attr('id').replace('image_', ''));
		});
		$('#selectedImages').after('<input type="hidden" name="images" value="'+images.join(',')+'" />');
		
		var error = false;
		$(this).find('input').each(function() {
			if($(this).hasClass('error')) error = true;
		});
		return error ? false : true;
	});
	
	$('li.productButtons a.up').click(function() {
		var newRow = $(this).parents('ul').prev('ul');
		var oldRow = $(this).parents('ul');
		switchRows(oldRow, newRow);
		return false;
	});
	
	$('li.productButtons a.down').click(function() {
		var newRow = $(this).parents('ul').next('ul');
		var oldRow = $(this).parents('ul');
		switchRows(oldRow, newRow);
		return false;
	});
	
	$('table#banners a.up').click(function() {
		var newRow = $(this).parents('tr').prev('tr');
		var oldRow = $(this).parents('tr');
		switchRows(oldRow, newRow, 'banneri');
		return false;
	});
	
	$('table#banners a.down').click(function() {
		var newRow = $(this).parents('tr').next('tr');
		var oldRow = $(this).parents('tr');
		switchRows(oldRow, newRow, 'banneri');
		return false;
	});
	
	$('table#banners a.delete').click(function() {
			
		if(confirm('Haluatko varmasti poistaa tämän bannerin?')) {
			var id = $(this).parents('tr').attr('id').replace('id_', '');
			$.ajax({
				type: 'POST',
				url: BASE_DIR+'hallinta/deleteBanner/',
				data: 'id='+id,
				success: function(response) {
					$('tr#id_'+id).fadeOut(400, function() { $(this).remove(); } );
				}
			});
		}
		return false;
	});
		
});
	
function switchRows(oldRow, newRow, type) {	
	if(newRow.size() > 0 && !newRow.hasClass('titles')) {
		var newID = newRow.attr('id').replace('id_', '');
		var oldID = oldRow.attr('id').replace('id_', '');		
		var data = 'old='+oldID+'&new='+newID+'&type='+type;		
		$.ajax({
			type: 'POST',
			url: BASE_DIR+'hallinta/switchOrder/',
			data: data,
			success: function(r) {
				$('#id_'+oldID).swap('#id_'+newID);
				
				$('#id_'+oldID).attr('id', 'tempID');
				$('#id_'+newID).attr('id', 'id_'+oldID);
				$('#tempID').attr('id', 'id_'+newID);
			}
		});
	}
	
}

jQuery.fn.swap = function(b){
   b = jQuery(b)[0];
   var a = this[0];
   var t = a.parentNode.insertBefore(document.createTextNode(''), a);
   b.parentNode.insertBefore(a, b);
   t.parentNode.insertBefore(b, t);
   t.parentNode.removeChild(t);
   return this;
};

function calendarChange(dir) {
	var data = $('table#calendar').attr('class').split('_');
	
	var month = parseInt(data[1]) + dir;
	var year = parseInt(data[0]);
	
	if(month > 12) {
		month = 1;
		year = year + 1;
	}
	
	if(month < 1) {
		month = 12;
		year = year - 1;
	}
	
	$.ajax({
		type: 'get',
		url: BASE_DIR+'calendar/main/'+year+'/'+month,
		success: function(response) {
			$('table#calendar').replaceWith(response);
			$('table#calendar td a').tooltip({ 
				track: true, 
				delay: 0, 
				showURL: false, 
				fade: 250,
				left: -10,
				positionLeft: true,
				bodyHandler: function() {
					var html = $(this).find('span').html();
					var tooltipContent = '';
					$(html.split("|")).each(function() {
						tooltipContent = tooltipContent + '<p>'+$(this)[0]+'</p>';
					});
					return tooltipContent;
				}
			});
		},
		error: function() {
			alert("error");
		}
	});
	return false;
}

jQuery.fn.editable = function(options) {
	$(this).bind('click', function() {
		var theSpan = $(this);
		theSpan.hide();
		theSpan.after('<input type="text" class="editing '+$(this).attr('class')+'" value="'+$(this).text()+'" />');
		
		var theInput = $(this).next();
		theInput.focus();
		
		theInput.blur(function() {
			theInput.remove();
			theSpan.show();
		});
	
		theInput.keydown(function(e) {
			if(e.keyCode == 13) {
				theSpan.removeClass("editable");
				var defaultValue = theSpan.text();
				theSpan.html('<img src="img/loader.gif" />');
				
				if(theSpan.attr("class") == "amount" && (theInput.attr("value") <= 0 || !theInput.attr("value")))
				{
					var deleteThis = true;
					theSpan.addClass("editable");
				}
				else
				{
					var field = theSpan.attr('class');
					var value = theInput.val();
					var id = theSpan.parents('ul').attr('id').replace('event_', '');
					
					var querystring = 'id='+id+'&field='+field+'&value='+value.replace('+', '%2B');
					theInput.remove();
					theSpan.show();
					
					$.ajax({
						type: "POST",
						url: BASE_DIR+"hallinta/updateEventField/",
						cache: false,
						data: querystring,
						success: function(response) {
							if(response.trim().length == 0) {
								theSpan.html('&nbsp;');
							}
							else
							{
								theSpan.text(''+response.trim()+'');
								theSpan.html(theSpan.html(replace(/ /g, '&nbsp;')));
							}
							theSpan.addClass("editable");
						}
					});
				}
				theInput.blur();
				if(deleteThis) { deleteRow(theSpan); theSpan.text(defaultValue); }
			}
			else if(e.keyCode == 27) {
				theInput.blur();
			}					
		});
	});
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
