// 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;

var ajaxPageRecommended = new AjaxPage('ajaxPageRecommended');
ajaxPageRecommended.pageURL = BASE + '/ajax/recommendedproducts';
ajaxPageRecommended.containerId = 'artist_recommended';
ajaxPageRecommended.pagingContainerId = 'artist_recommended_paging';
ajaxPageRecommended.numItemsPerPage = 8;

var ajaxPageReview = new AjaxPage('ajaxPageReview');
ajaxPageReview.pageURL = BASE + '/ajax/productreviews';
ajaxPageReview.containerId = 'product_reviews_box';
ajaxPageReview.pagingContainerId = 'product_reviews_paging';
ajaxPageReview.numItemsPerPage = 2;

$(document).ready(function()
{
	// Artist products
	ajaxPage.totalElements = $('#totalProducts').val();
	var artistId = $('#artistId').val();
	ajaxPage.eliminateItemId = $('#productId').val();

	if(ajaxPage.totalElements > 0)
		ajaxPage.init(artistId);
	
	// Recommended products
	ajaxPageRecommended.totalElements = $('#totalRecommended').val();
	var productId = $('#productId').val();
	
	if(ajaxPageRecommended.totalElements > 0)
		ajaxPageRecommended.init(productId);
	
	// Product reviews
	ajaxPageReview.totalElements = $('#totalProductReviews').val();
	var productId = $('#productId').val();
	
	if(ajaxPageReview.totalElements > 0)
		ajaxPageReview.init(productId);
	
	// color box 
	$('.cBoxPopup').colorbox({
		scrolling: false,
		onComplete: function()
		{
			for (editorName in CKEDITOR.instances)
			{
				CKEDITOR.instances[editorName].destroy();
			}
			
			$('.productformtable textarea').each(function(i)
			{
				CKEDITOR.replace(this);
			});
			
			$.fn.colorbox.resize();
		}
	});
});

// This is called when the track player is clicked
function onTrackPlayerClick(trackPlayerId)
{
	$.each($('#trackListing object'), function()
	{
		if (this.id != trackPlayerId)
		{
			this.stop('stop');
		}
	});
}

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;
}

function uploadFile(uploadFieldName, fileNamePath)
{
	// Display loading animation
	$('#' + uploadFieldName + 'Loading').html('<img src="' + BASE + '/img/ajax.gif" style="padding-left: 5px;" />');
	
	$.ajaxFileUpload({
		url: BASE + '/ajax/' + fileNamePath + '/?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
					{
						$('#' + uploadFieldName + 'OrgName').val(data.file);
						$('#' + uploadFieldName + 'Hidden').val(data.msg);
						
						$('span:#' + uploadFieldName + 'File').hide();                   // File button span
						$('span:#' + uploadFieldName + 'Name').show();   				 // Filename span
						$('span:#' + uploadFieldName + 'Name').html(data.file);   		 // Filename span
						$('span:#' + uploadFieldName + 'DeleteTemp').show();             // Delete temp button span
						$('span:#' + uploadFieldName + "Delete").hide();                 // Delete button span
						
						// Colorbox resize 
						//$.fn.colorbox.resize();
					}
				}
			}
		}
	});
}

function deleteTempFile(uploadFieldName)
{
	$.ajax({
		type: 'POST',
		url: BASE + '/ajax/cms/deletetempfile',
		data: 'tempFile=' + $('#' + uploadFieldName + 'Hidden').val(),
		success: function()
		{
			$('#' + uploadFieldName + 'OrgName').val('');
			$('#' + uploadFieldName + 'Hidden').val('');
						
			$('span:#' + uploadFieldName + 'File').show();   		// File button span
			$('span:#' + uploadFieldName + 'Name').hide();   		// Filename span
			$('span:#' + uploadFieldName + 'DeleteTemp').hide();   	// Delete temp button span
		}
	});
}

function deleteFile(formBoxId, uploadFieldName, fileNamePath, boxId, fileTypeText)
{
	//var trackId = $("#trackId").val();
	//var trackFile = $("#fileNameHidden").val();
	
	var isConfirmed = confirm('Are you sure you want to delete the ' + fileTypeText + '?');
	
	if (isConfirmed)
	{
		
		// Display loading animation
		$('#delete' + uploadFieldName + 'Loading').html('<img src="' + BASE + '/img/ajax.gif" style="padding-left: 15px; margin-top: 14px;" />');
	
		// Construct the query string
		var queryString = '';
		queryString += getFormQueryString('#' + formBoxId + '  input');
	
		$.ajax({
			type: 'POST',
			url: BASE + '/ajax/' + fileNamePath,
			data: queryString,
			/*data: 'tempFile=' + trackFile
				+ '&trackId=' + trackId,
				*/
			success: function()
			{
				$('#' + uploadFieldName + 'OrgName').val('');
				$('#' + uploadFieldName + 'Hidden').val('');
				
				$('#delete' + uploadFieldName + 'Loading').html('');
				
				//$('span:#' + uploadFieldName + 'File').show();   		// File button span
				//$('span:#' + uploadFieldName + 'Name').hide();   		// Filename span
				//$('span:#' + uploadFieldName + 'DeleteTemp').hide();   	// Delete temp button span
				//$('span:#' + uploadFieldName + "Delete").hide();        // Delete button span
				
				$('#' + boxId).html('');
				
				// Destroy RTE
				for (editorName in CKEDITOR.instances)
				{
					CKEDITOR.instances[editorName].destroy();
				}
			
				// Load RTE
				$('#' + formBoxId + ' textarea').each(function(i)
				{
					CKEDITOR.replace(this);
				});
				
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		});
	}
}
/* -------------------------------------------------------------------------------------------------------- */
/* Manage Products
/* -------------------------------------------------------------------------------------------------------- */

function uploadImage()
{
	// Construct the query string
	var queryString = '';
	queryString += getFormQueryString('#productImageFormBox input');
	
	var productId = $("#productId").val();
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/productimage',
		data: queryString,
		success: function (msg)
		{
			if (msg == "OK")
			{
				window.location = BASE + "/product/" + productId;
			}
		}
	});
}

/*
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 getProductForm(action)
{
	var artistId = $("#artistId").val();
	var productId = (action == 'edit') ? $("#productId").val() : "";
	var currentProductId = $("#currentProductId").val();
	
	$('#' + action + 'Product').html('<img src="' + BASE + '/img/template/ajax.gif" style="margin-left: 10px; height: 20px; width: 20px; vertical-align: middle; " />');
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/productform',
		data: "productId=" + productId
			+ "&artistId=" + artistId
			+ "&currentProductId=" + currentProductId,
		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 artistProduct(action)
{
	// Construct the query string
	var queryString = '';
	queryString += getFormQueryString('#productFormBox input, #productFormBox select, #productFormBox textarea');
		
	var productId = ($("#productId").val() ? $("#productId").val() : $("#currentProductId").val());
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/artistsaveproduct',
		data: queryString,
		success: function(msg)
		{
			if (msg == "OK")
			{
				window.location = BASE + "/product/" + productId;
			}
			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 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];
			}
		}
	);
}

/* -------------------------------------------------------------------------------------------------------- */
/* Manage Tracks
/* -------------------------------------------------------------------------------------------------------- */

function deleteTrack(trackName, trackId, productId)
{
	var isConfirmed = confirm('Are you sure you want to delete "' + trackName + '" track?');
	
	if (isConfirmed)
	{
		$.ajax({
			type: "POST",
			url: BASE + '/ajax/deletetrack',
			data: "trackId=" + trackId,
			success: function()
			{
				window.location = BASE + "/product/" + productId;
			}
		});
	}
}

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 saveTrack()
{
	// Construct the query string
	var queryString = '';
	queryString += getFormQueryString('#trackFormBox input');
		
	var productId = $("#productId").val();
	
	$.ajax({
		type: "POST",
		url: BASE + '/ajax/savetrack',
		data: queryString,
		success: function(msg)
		{
			if (msg == "OK")
			{
				window.location = BASE + "/product/" + productId;
			}
			else
			{
				$("#trackFormBox").html(msg);
				
				// Colorbox resize 
				$.fn.colorbox.resize();
			}
		}
	});
}
