// Photos
var photoProvider = new Flickr('photoProvider');
photoProvider.containerId = 'artist_photos';
photoProvider.thumbWidth = 75;
photoProvider.thumbHeight = 75;
photoProvider.maxPages = 1;
photoProvider.pagingHtml = '<a href="' + $('#flickrChannelURL').val() + '" target="_blank" class="channelLink"><img src="../img/flickrChannel.png" /><span>flickr</span></a><div id="flickrtext">Artist Gallery</div>';

// Videos
var videoProvider = new YouTube('videoProvider');	
videoProvider.containerId = 'artist_videos';
videoProvider.thumbWidth = 114;
videoProvider.thumbHeight = 75;
videoProvider.overlayImage = '/img/play.png';
videoProvider.pagingHtml = '<a href="' + $('#youTubeChannelURL').val() + '" target="_blank" class="channelLink"><img src="../img/ytChannel.png" /><span>youtube</span></a><div id="youtubetext">Artist Channel</div>';

// Artist Products
var ajaxPage = new AjaxPage('ajaxPage');
ajaxPage.pageURL = BASE + '/ajax/artistproducts';
ajaxPage.containerId = 'artist_products_box';
ajaxPage.pagingContainerId = 'artist_products_paging';
ajaxPage.numItemsPerPage = 8;

$(document).ready(function()
{
	// Artist products
	ajaxPage.totalElements = $('#totalProducts').html();
	var artistId = $('#artistId').html();
	
	ajaxPage.init(artistId);
	
	// Photos
	// This always returns up to 20 results because this is all the flick allows
	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=" + $('#flickr_tag').val() + "&lang=en-us&format=json&jsoncallback=?",
		function (data)
		{
			photoProvider.showFeed(data);
		});
});


function showMoreInfo(showId)
{
	var divId = '#ShowMoreInfo' + showId;
	var isVisible = !$(divId).hasClass('hidden');

	if (!isVisible)
	{
		$(divId).show('normal');
	}
	else
	{
		$(divId).hide('normal');
	}
	
	$(divId).toggleClass('hidden');
}

function showWaterfrontShare()
{
	$('#waterfront_share').slideToggle("fast");
}

function selectWaterfrontLink()
{	
	document.getElementById('waterfrontArtistShareLink').focus();
    document.getElementById('waterfrontArtistShareLink').select();
}

function cssUpload(uploadCssFieldName)
{
	var artistId = $("#artisthiddenId").val();
	var cssfile = $("#cssfile").val();
	
	if (cssfile != '')
	{
		$.ajaxFileUpload
		({
			url: BASE + '/ajax/customcssupload/?fileNameId=' + uploadCssFieldName
			  	+ '&artistId=' + artistId
				+ '&cssfile=' + cssfile,
			secureuri: false,
			fileElementId: uploadCssFieldName,
			dataType: 'json',
			success: function (msg)
			{
				window.location = BASE + "/artist/" + artistId;
			}
		});
	}
	else
	{
		alert("Please upload css file.");
	}
}

function sampleDownload()
{
	window.open(BASE + '/ajax/downloadcss', 'Download');
}

function artistSignup(prevPage)
{
	var name = $("#name").val();
	var phone = $("#phone").val();
	var email = $("#email").val();
	var password = $("#newPassword").val();
	var confirmpassword = $("#confirmPassword").val();
	var reason = $("#reason").val();
	
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/artistusersignupprocess",
		data: "name=" + name
			+ "&phone=" + phone
			+ "&email=" + email
			+ "&newPassword=" + password
			+ "&confirmPassword=" + confirmpassword
			+ "&reason=" + reason
			+ "&prevpage=" + prevPage,
		success: function(msg)
		{
			if (msg == "OK")
			{
				close_form();
				alert ("Your details have been submitted. We'll e-mail you once they've been confirmed.");
				window.location = BASE + '/' + prevPage;
			}
			else
			{
				$("#artist_signup_form_box").html(msg);
				
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}

function artistUpdate(prevPage)
{
	var artistId = $("#currentArtistId").val();
	var userId = $("#userId").val();
	var reason = $("#reason").val();
	
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/artistuserupdateprocess",
		data: "artistId=" + artistId
			+ "&userId=" + userId
			+ "&reason=" + reason
			+ "&prevpage=" + prevPage,
		success: function(msg)
		{
			if (msg == "OK")
			{
				close_form();
				
				alert ("Your details have been submitted. We'll e-mail you once they've been confirmed.");
				window.location = BASE + '/' + prevPage;
			}
			else
			{
				$("#artist_signup_form_box").html(msg);
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}

var editor;

function displayRichTextBox(div, strLen)
{
	/*if (editor)
	{
		editor.destroy();
	}*/
	
	var description = $("#artist_description").html();
	
	$("#left_box .jScrollPaneContainer").remove();
	$("#description_message").hide();
	$("#edit_button").hide();
	
	$("#edit_artist_description").show();
	$("#edit_artist_description").html(description);
	
	editor = CKEDITOR.replace(div);
	$("#save_button").show();
}

function saveDescription(artistId)
{
	var content_text = editor.getData();

	content_text = escape(content_text);
	content_text = content_text.replace('+', '%2B');
	content_text = content_text.replace('/', '%2F');

	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistdescription/',
		data: "content_text=" + content_text
			+ "&artistId=" + artistId,
		success: function(msg)
		{
			if (msg == 'OK')
			{
				window.location = BASE + "/artist/" + artistId;
			}
		}
	});
}

function uploadImage(uploadFieldName)
{
	var artistId = $("#artistHiddenId").val();
	var artistImage = $("#artistDefaultImage").val();
	
	$.ajaxFileUpload({
		url: BASE + '/ajax/artistuploadimage/?fileInputId=' + uploadFieldName
			+ '&artistId=' + artistId
			+ '&artistImage=' + artistImage,
		secureuri: false,
		fileElementId: uploadFieldName,
		dataType: 'json',
		success: function (msg)
		{
			if (msg != '')
			{
				alert(msg);
			}
			else
			{
				window.location = BASE + "/artist/" + artistId;
			}
		}
	});
}

function deleteImage(formBoxId, filePath, boxId)
{
	var isConfirmed = confirm('Are you sure you want to delete the image?');
	
	// Construct the query string
	var queryString = '';
	queryString += getFormQueryString('#' + formBoxId + '  input');
	
	if (isConfirmed)
	{
		$.ajax({
			type: "POST",
			url: BASE + '/ajax/' + filePath,
			data: queryString,
			success: function()
			{
				$('#' + boxId).html('');
				
				// Colorbox resize
				$.fn.colorbox.resize();
			}
		});
	}
}

function removeShow(showId, artistId)
{
	var isConfirmed = confirm('Are you sure you want to delete the show?');
	
	if (isConfirmed)
	{
		$.ajax({
			type: "POST",
			url: BASE + '/ajax/artistremoveshow',
			data: "showId=" + showId,
			success: function()
			{
				window.location = BASE + "/artist/" + artistId;
			}
		});
	}
}

function addLink()
{
	var artistId = $("#artistHiddenId").val();
	var linkTitle = $("#linkTitle").val();
	var linkUrl = $("#linkUrl").val();
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistaddlink',
		data: "artistId=" + artistId
			+ "&linkTitle=" + linkTitle
			+ "&linkUrl=" + linkUrl,
		success: function(msg)
		{
			if (msg == "OK")
			{
				window.location = BASE + "/artist/" + artistId;
			}
			else
			{
				var title = $("#divLinkTitle").html();
				var url = $("#divLinkUrl").html();
				var icon = $("#iconDiv").html();
				
				// Colorbox resize after validation check
				$.fn.colorbox.resize();
				
				$("#link_form_box").html(msg);
				
				$("#iconDiv").html(icon);
				$("#divLinkTitle").html(title);
				$("#divLinkUrl").html(url);
			}
		}
	});
}

function updateDiv(divId, val)
{
	$("#" + divId).html("<b>" + val + "</b>");
	
	if (divId == 'divLinkUrl')
	{
		$.ajax({
			type: "POST",
			url: BASE + '/ajax/artistaddlinkdisplayimage',
			data: "url=" + val,
			success: function(msg)
			{
				$("#iconDiv").html(msg);
			}
		});
	}
}

function removeLink(contentId, artistId)
{
	var isConfirmed = confirm('Are you sure you want to delete the link?');
	
	if (isConfirmed)
	{
		$.ajax({
			type: "POST",
			url: BASE + '/ajax/artistremovelink',
			data: "contentId=" + contentId,
			success: function()
			{
				window.location = BASE + "/artist/" + artistId;
			}
		});
	}
}

function artistShow()
{
	var artistId = $("#showArtistId").val();
	var showId = $("#showId").val();
	var tourId = $("#tourId").val();
	var showVenueName = $("#showVenueName").val();
	var showLocation = $("#showLocation").val();
	var showShowDate = $("#showShowDate").val();
	var showOnSaleDate = $("#showOnSaleDate").val();
	var showPreSaleDate = $("#showPreSaleDate").val();
	var showWebsite = $("#showWebsite").val();
	var showSupportArtists = $("#showSupportArtists").val();
	var showPlayingTimes = $("#showPlayingTimes").val();
	var showTicketCategoryId = $("#showTicketCategoryId").val();
	var showShowTypeId = $("#showShowTypeId").val();
	var isRedirectToPage = $("#isRedirectToPage").val();
	
	showVenueName = showVenueName.replace('&', '%26');
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistsaveshow',
		data: "showArtistId=" + artistId		
			+ "&showId=" + showId
			+ "&tourId=" + tourId
			+ "&showVenueName=" + showVenueName
			+ "&showLocation=" + showLocation
			+ "&showShowDate=" + showShowDate
			+ "&showOnSaleDate=" + showOnSaleDate
			+ "&showPreSaleDate=" + showPreSaleDate
			+ "&showWebsite=" + showWebsite
			+ "&showSupportArtists=" + showSupportArtists
			+ "&showPlayingTimes=" + showPlayingTimes
			+ "&showTicketCategoryId=" + showTicketCategoryId
			+ "&showShowTypeId=" + showShowTypeId
			+ "&isRedirectToPage=" + isRedirectToPage,
		success: function(msg)
		{
			if (msg == "OK")
			{
				if ($('#isRedirectToPage').val())
				{
					window.location = BASE + "/artist/" + artistId;
				}
				else
				{
					$('#show_form_box').html('<img src="' + BASE + '/img/template/ajax.gif" style="margin-left:300px; margin-top: 225px;" />');
					
					getManageTours(artistId);
				}
			}
			else
			{
				$("#show_form_box").html(msg);
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}

function initAutoComplete(id, ajaxHandler, maxLimit)
{
	var html = '';
	
	$('#' + id).autocomplete
	(
		BASE + '/ajax/' + ajaxHandler + '/',
		{
			minChars: 1,
			delay: 300,
			max: maxLimit,
			matchSubset: false,
			scrollHeight: 600,
			formatItem:function(item)
			{
				html = item.length > 1 ? "<img class=\"right\" src=\"" + item[1] + "\" alt=\"\"/>\n" : "";
				return html + item[0];
			}
		}
	);
}

function tourFormDisplay(action)
{
	var tourArtistId = $("#tourArtistId").val();
	var tourId = (action == 'edit') ? $("#tourId").val() : "";
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artisttourform',
		data: "tourId=" + tourId
			+ "&tourArtistId=" + tourArtistId,
		success: function(msg)
		{
			$("#tour_form_box").html(msg);
			
			// Colorbox resize 
			$.fn.colorbox.resize();
		}
	});
}

function artistTour(action)
{
	var artistId = $("#tourArtistId").val();
	var tourId = (action == 'edit') ? $("#tourId").val() : "";
	var tourEventStatusId = $("#tourEventStatusId").val();
	var tourName = $("#tourName").val();	
	var tourStatusComment = $("#tourStatusComment").val();
	var tourArtistName = $("#tourArtistName").val();
	var tourOnSaleDate = $("#tourOnSaleDate").val();
	var tourPreSaleDate = $("#tourPreSaleDate").val();
	var tourArchiveDate = $("#tourArchiveDate").val();
	
	tourArtistName = tourArtistName.replace('&', '%26');
	tourName = tourName.replace('&', '%26');
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistsavetour',
		data: "tourArtistId=" + artistId
			+ "&tourId=" + tourId
			+ "&tourEventStatusId=" + tourEventStatusId
			+ "&tourName=" + tourName
			+ "&tourStatusComment=" + tourStatusComment
			+ "&tourArtistName=" + tourArtistName
			+ "&tourOnSaleDate=" + tourOnSaleDate
			+ "&tourPreSaleDate=" + tourPreSaleDate
			+ "&tourArchiveDate=" + tourArchiveDate,
		success: function(msg)
		{
			if (msg == "OK")
			{
				$('#tour_form_box').html('<img src="' + BASE + '/img/template/ajax.gif" style="margin-left:300px; margin-top:100px;" />');
				
				getManageTours(artistId);
			}
			else
			{
				$("#tour_form_box").html(msg);
				
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}

function showInfo(external, showId)
{
	var tourArtistId = $("#tourArtistId").val();
	var tourId = $("#tourId").val();
	
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/artistshow",
		data: "showArtistId=" + tourArtistId
			+ "&tourId=" + tourId
			+ "&showId=" + showId,
		success: function(msg)
		{
			$("#tour_form_box").html(msg);
			
			// Colorbox resize
			$.fn.colorbox.resize();
		}
	});	
}


function showGotoPage(external, page)
{
	$('#showsInfo').html('<img src="' + BASE + '/img/template/ajax.gif" style="margin-left:300px; margin-top:150px;" />');
	
	var tourId = $("#tourId").val();
	
	$.ajax({
		type: 'POST',
		url: BASE + "/ajax/getshows",
		data: 'page=' + page
			+ "&tourId=" + tourId,
		success: function(msg)
		{
			$('#showsInfo').html(msg);
		}
	});
}
	
function getShowsList()
{
	var tourId = ($("#tourId").val() ? $("#tourId").val() : '');
	$('#editTourButton').focus();
	
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/getshows",
		data: 'tourId=' + tourId,
		success: function(msg)
		{
			$("#showsInfo").html(msg);
			
			// Colorbox resize
			$.fn.colorbox.resize();
		}
	});	
}

function getManageTours(artistId)
{
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/artisttour",
		data: 'tourArtistId=' + artistId,
		success: function(msg)
		{
			$("#tour_form_box").html(msg);
			
			// Colorbox resize
			$.fn.colorbox.resize();
		}
	});	
}

/* -------------------------------------------------------------------------------------------------------- */
/* Manage Products
/* -------------------------------------------------------------------------------------------------------- */

function getProductForm(action, divId)
{
	var artistId = $("#artistId").val();
	var productId = (action == 'edit') ? $("#productId").val() : "";
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/productform',
		data: "productId=" + productId
			+ "&artistId=" + artistId,
		beforeSend: function()
		{
			for (editorName in CKEDITOR.instances)
			{
				CKEDITOR.instances[editorName].destroy();
			}
		},
		success: function(msg)
		{
			$("#productFormBox").html(msg);
			
			$('#productFormBox textarea').each(function(i)
			{
				CKEDITOR.replace(this);
			});
			
			// Colorbox resize 
			$.fn.colorbox.resize();
		}
	});
}

function uploadProductImage(uploadFieldName)
{
	// Display loading animation
	$('#' + uploadFieldName + 'Loading').html('<img src="' + BASE + '/img/ajax.gif" style="padding:2px 0 0 25px; float:left;" />');
	
	$.ajaxFileUpload({
		url: BASE + '/ajax/uploadproductimage/?fileInputId=' + uploadFieldName,
		secureuri: false,
		fileElementId: uploadFieldName,
		dataType: 'json',
		success: function (data, status)
		{
			// Hide loading animation
			$('#' + uploadFieldName + 'Loading').html('');
				
			if (data)
			{
				data = eval('(' + data + ')');
				if (typeof(data.error) != 'undefined')
				{
					if (data.error != '')
					{
						alert(data.error);
					}
					else
					{
						$('#productImageName').val(data.file);
						$('#productImageNameHidden').val(data.msg);
						
						$('span:#' + uploadFieldName + 'File').hide();                   // File button span
						$('span:#' + uploadFieldName + 'Name').html(data.file).show();   // Filename span
						$('span:#' + uploadFieldName + 'DeleteTemp').show();             // Delete temp button span
						$('span:#' + uploadFieldName + "Delete").hide();                 // Delete button span
					}
				}
			}
		}
	});
}

function deleteTempFile(uploadFieldName)
{
	$.ajax({
		type: 'POST',
		url: BASE + '/ajax/cms/deletetempfile',
		data: 'tempFile=' + $('#productImageNameHidden').val(),
		success: function()
		{
			$('#productImageName').val('');
			$('#productImageNameHidden').val('');
						
			$('span:#' + uploadFieldName + 'File').show();   		// File button span
			$('span:#' + uploadFieldName + 'Name').hide();   		// Filename span
			$('span:#' + uploadFieldName + 'DeleteTemp').hide();   	// Delete temp button span
		}
	});
}
	
function artistProduct(action)
{
	// Construct the query string
	var queryString = '';
	queryString += getFormQueryString('#productFormBox input, #productFormBox select, #productFormBox textarea');
		
	var artistId = $("#artistId").val();
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistsaveproduct',
		data: queryString,
		success: function(msg)
		{
			if (msg == "OK")
			{
				window.location = BASE + "/artist/" + artistId;
			}
			else
			{
				// Destroy RTE
				for (editorName in CKEDITOR.instances)
				{
					CKEDITOR.instances[editorName].destroy();
				}
			
				$("#productFormBox").html(msg);
				
				// Load RTE
				$('#productFormBox textarea').each(function(i)
				{
					CKEDITOR.replace(this);
				});
			
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}

function manageProducts(artistId)
{
	$.ajax({
		type: "POST",
		url: BASE + "/ajax/artistproduct",
		data: 'artistId=' + artistId,
		success: function(msg)
		{
			$("#productFormBox").html(msg);
			
			// Colorbox resize
			$.fn.colorbox.resize();
		}
	});	
}

/* -------------------------------------------------------------------------------------------------------- */

function getFormFields(expression)
{
	var formFields = [];
	
	$(expression).each(function(i)
	{
		var current = $(this);
		
		if (current.attr('name').length > 0)
		{
			if (current.is('textarea'))
			{
				var contentText = '';

				//contentText = current.val();
				
				contentText = CKEDITOR.instances[current.attr('name')].getData();
						
				// Escape special characters.
				contentText = escape(contentText);
				contentText = contentText.replace('+', '%2B');
				contentText = contentText.replace('/', '%2F');
				contentText = contentText.replace('&', '%26');

				formFields[current.attr('name')] = contentText;
			}
			else if (current.is(':text') || current.is(':hidden') || current.is('select'))
			{
				var fieldValue = '';
				fieldValue = current.val();				
				fieldValue = fieldValue.replace('&', '%26');
				
				formFields[current.attr('name')] = fieldValue;
			}
		}
	});
	
	return formFields;
}

function getFormQueryString(expression)
{
	var queryString = '';
	var formFields = getFormFields(expression);
	var i;
	for (i in formFields)
	{
		queryString += '&' + i + '=' + formFields[i];
	}
	
	return queryString;
}
