$.noConflict(true)(function($)
{
	// Define some variables
	var ftd = $(document),
		currentTab,
		currentTemplate = $('#partlist_current > li'),
		previewTemplate = $('#partlist_preview > li'),
		pointsDisplay = $('span[name="pointsdisplay"]'),
		previewImage = $('#signatureimage'),
		previewImageFull = $('#signatureimage_full'),
		sigBBCode = $('#sigbbcode'),
		regions = $('[name^="region["]'),
		fonts = $('[name^="font["]');
	
	if (typeof vBSignatures.current != 'undefined')
	{
		var tmpSrc = previewImage.attr('src');
		var tmpPos = tmpSrc.indexOf('?');
		if (tmpPos >= 0)
		{
			tmpSrc = tmpSrc.substr(0, tmpPos);
		}
		previewImage.attr('src', tmpSrc + '?v=' + (Math.random() * 99999999999999));
				
		var tmpSrc = previewImageFull.attr('src');
		var tmpPos = tmpSrc.indexOf('?');
		if (tmpPos >= 0)
		{
			tmpSrc = tmpSrc.substr(0, tmpPos);
		}
		previewImageFull.attr('src', tmpSrc + '?v=' + (Math.random() * 99999999999999));
				
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Shorthand
			var thisElem = $('a[name="partname"][data-partid="' + vBSignatures.current[i] + '"]');
			
			// Override
			$('#partlist_current').append('<li>' + currentTemplate.html()
				.replace(/%folder%/igm, 	i)
				.replace(/%styleid%/igm, 	thisElem.attr('data-styleid'))				
				.replace(/%partname%/igm, 	thisElem.text())
			+ '</li>');
			
			if (i == '')
			{
				// Base, ensure we can't delete that 
				$('img[name="deletepart"][data-command="current"][data-folder="' + i + '"]').hide();
			}
		}
	}
	
	$('input[name="purchase"]').on('click', function(e)
	{
		var thisButton = $(this),
			partName = $('a[name="partname"][data-partid="' + thisButton.attr('data-partid') + '"]'),
			points = parseInt(vBSignatures.points),
			price = parseInt(thisButton.attr('data-price'));
		
		if (confirm(vbphrase['dbtech_vbsignatures_are_you_sure_purchase']))
		{
			if (price > points)
			{
				// Can't afford
				return false;
			}
			
			// Update remaining points
			vBSignatures.points = (points - price);
			pointsDisplay.text(vBSignatures.points);
			
			// Update this button
			thisButton.attr('disabled', 'disabled').css('cursor', 'default').val(vbphrase['dbtech_vbsignatures_already_owned']);
			
			$('input[name="purchase"]').each(function(index, element)
			{
				var loopButton = $(this);
				if (!loopButton.is(':disabled') && vBSignatures.points < parseInt(loopButton.attr('data-price')))
				{
					// Update this button
					loopButton.attr('disabled', 'disabled').css('cursor', 'default').val(vbphrase['dbtech_vbsignatures_insufficient_funds']);
				}
			});
			
			ajaxCall('purchase', {'partid' : thisButton.attr('data-partid')});
		}
	});	
	
	$('input[name="preview"]').on('click', function(e)
	{
		var thisButton = $(this),
			partName = $('a[name="partname"][data-partid="' + thisButton.attr('data-partid') + '"]'),
			styleId = thisButton.attr('data-styleid');
		
		// Set the preview list
		vBSignatures.preview[thisButton.attr('data-folder')] = thisButton.attr('data-partid');
		
		if ($('img[name="deletepart"][data-command="preview"][data-folder="' + thisButton.attr('data-folder') + '"]').length)
		{
			// Update the name
			$('span[name="deletepartname"][data-command="preview"][data-folder="' + thisButton.attr('data-folder') + '"]').text(partName.text());
		}
		else
		{
			$('#partlist_preview').append('<li>' + previewTemplate.html()
				.replace(/%folder%/igm, 	thisButton.attr('data-folder'))
				.replace(/%styleid%/igm, 	styleId)
				.replace(/%partname%/igm, 	partName.text())
			+ '</li>');
		}
		
		var extraParams = {
			'parts' : {},
			'usepreview' : vBSignatures.usePreview,
			'signaturestyleid' : styleId
		};
		
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.current[i];
		}
		
		for (var i in vBSignatures.preview)
		{
			if (vBSignatures.preview[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.preview[i];
		}
		
		ajaxCall('updatepreview', extraParams);
	});
	
	$('input[name="setsignature"]').on('click', function(e)
	{
		// Remove this button
		$(this).remove();
		ajaxCall('setsignature', {'signaturestyleid' : $(this).attr('data-styleid')});
	});
	
	$('input[name="previewsignature"]').on('click', function(e)
	{
		var extraParams = {
			'parts' : {},
			'usepreview' : '1',
			'signaturestyleid' : $(this).attr('data-styleid')
		};
		
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.current[i];
		}
		
		for (var i in vBSignatures.preview)
		{
			if (vBSignatures.preview[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.preview[i];
		}
		
		if (typeof vBSignatures.current[''] == 'undefined')
		{
			// We didn't have a base
			return false;
		}
		
		// Finally save the signature
		ajaxCall('updatepreview', extraParams);
	});	
	
	$('input[name="savesignature"]').on('click', function(e)
	{
		var thisButton = $(this);
		
		var extraParams = {
			'parts' : {},
			'signaturestyleid' : thisButton.attr('data-styleid')
		};
		
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.current[i];
		}
		
		for (var i in vBSignatures.preview)
		{
			if (vBSignatures.preview[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.preview[i];
			
			vBSignatures.current[i] = vBSignatures.preview[i];
			vBSignatures.preview[i] = '';
		}
		
		if (typeof vBSignatures.current[''] == 'undefined')
		{
			// We didn't have a base
			return false;
		}
		
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// This has been deleted
				continue;
			}
			
			if ($('img[name="deletepart"][data-command="current"][data-folder="' + i + '"]').length == 0)
			{
				// We have a new part for the Current list
				$('#partlist_current').append('<li>' + currentTemplate.html()
					.replace(/%folder%/igm, 	i)
					.replace(/%styleid%/igm, 	thisButton.attr('data-styleid'))					
					.replace(/%partname%/igm, 	$('a[name="partname"][data-partid="' + vBSignatures.current[i] + '"]').text())
				+ '</li>');
				
				if (i == '')
				{
					// Base, ensure we can't delete that 
					$('img[name="deletepart"][data-command="current"][data-folder="' + i + '"]').hide();
				}
			}
			else if ($('span[name="deletepartname"][data-command="preview"][data-folder="' + i + '"]').length > 0)
			{
				// Update the text
				$('span[name="deletepartname"][data-command="current"][data-folder="' + i + '"]').text($('span[name="deletepartname"][data-command="preview"][data-folder="' + i + '"]').text());
			}
			
			// Delete this part from the Preview list
			$('img[name="deletepart"][data-command="preview"][data-folder="' + i + '"]').parent().remove();
		}
		
		// Finally save the signature
		ajaxCall('savesignature', extraParams);
	});	
	
	ftd.on('click', 'img[name="deletepart"]', function(e)
	{
		var thisButton = $(this),
			cmd = thisButton.attr('data-command');
		
		// Set the preview list
		vBSignatures[cmd][thisButton.attr('data-folder')] = '';

		$('img[name="deletepart"][data-command="' + cmd + '"][data-folder="' + thisButton.attr('data-folder') + '"]').parent().remove();
		
		var extraParams = {
			'parts' : {},
			'signaturestyleid' : thisButton.attr('data-styleid')
		};
		
		for (var i in vBSignatures.current)
		{
			if (vBSignatures.current[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.current[i];
		}
		
		for (var i in vBSignatures.preview)
		{
			if (vBSignatures.preview[i].length == 0)
			{
				// Skip this
				continue;
			}
			
			// Override
			extraParams.parts[i] = vBSignatures.preview[i];
		}
		
		ajaxCall('updatepreview', extraParams);
	});
	
	// Tab changes
	$('a[name="signaturetab"]').on('click', function(e)
	{
		// Ensure the anchor doesn't add
		e.preventDefault();
		
		var thisTab = $(this),
			tabList = thisTab.parent().parent().children('dd'),
			currentTab;
		
		tabList.each(function(index, element)
		{
			if ($(element).hasClass('selected'))
			{
				// Set current tab
				currentTab = $(element).children('a').attr('data-tabid');
				return true;
			}
		});
		
		if (thisTab.attr('data-tabid') == currentTab)
		{
			// No need to do anything
			return true;
		}
		
		// Clean up old tab / view
		$('a[name="signaturetab"][data-tabid="' + currentTab + '"]').parent().removeClass('selected');
		$('div[name="signatureview"][data-tabid="' + currentTab + '"]').fadeOut('fast')
		
		// Update current tab storage
		currentTab = thisTab.attr('data-tabid');
		
		// Set selected on new tab
		thisTab.parent().addClass('selected');
		$('div[name="signatureview"][data-tabid="' + currentTab + '"]').fadeIn('fast');
	});
	
	$('span[name="partloader"]').hover(function(e)
	{
		$('div[name="partpopup"][data-partid="' + $(this).attr('data-partid') + '"]').show();
		
	}, function()
	{
		$('div[name="partpopup"][data-partid="' + $(this).attr('data-partid') + '"]').hide();
		
	}).mousemove(function(e)
	{
		$('div[name="partpopup"][data-partid="' + $(this).attr('data-partid') + '"]').css({
			'top' : e.pageY + 10,
			'left' : e.pageX - 150
		});
	});
	
	$('div[name="previewloader"]').hover(function(e)
	{
		$('div[name="previewpopup"]').show();
		
	}, function()
	{
		$('div[name="previewpopup"]').hide();
		
	}).mousemove(function(e)
	{
		$('div[name="previewpopup"]').css({
			'top' : e.pageY + 15,
			'left' : e.pageX - 15
		});
	});
	
	
	// #########################################################################
	// Shorthand for an ajax call
	function ajaxCall(varname, extraParams, type)
	{
		paused = true;
		
		if (typeof type == 'undefined')
		{
			// Ensure we're setting this correctly
			type = 'POST';
			extraParams['securitytoken'] = SECURITYTOKEN;
		}
		
		// Set additional global params
		extraParams['do'] = 'ajax';
		extraParams['action'] = varname;
		
		extraParams['region'] = {};
		regions.each(function(index, element)
		{
			var thisElem = $(this);
			
			// Set the param
			extraParams['region'][thisElem.attr('data-regionid')] = thisElem.val();
		});
		
		extraParams['font'] = {};
		fonts.each(function(index, element)
		{
			var thisElem = $(this);
			
			// Set the param
			extraParams['font'][thisElem.attr('data-regionid')] = thisElem.val();
		});

		// Add random garble to avoid IE bug
		extraParams['v'] = Math.random() * 99999999999999;
		
		$.ajax({
			type: type,
			url: 'vbsignatures.php',
			data: (SESSIONURL ? SESSIONURL + '&' : '') + $.param(extraParams)
		})
		.done(function(data)
		{
			if (!data)
			{
				// Empty response
				return false;
			}			
			
			try
			{
				// Parse the data
				data = $.parseJSON(data);
			}
			catch (e)
			{
				var errmsg = data;
				data = {'error' : data};
			}
			
			if (data.error)
			{
				// Log the error to the console
				console.error(timeStamp() + "AJAX Error: %s", data.error);
				
				return true;		
			}
						
			if (typeof data.dosave != 'undefined')
			{
				// Emulate a click of the save button
				$('input[name="savesignature"]').trigger('click');
			}
						
			if (typeof data.imgpath != 'undefined')
			{
				// Emulate a click of the save button
				sigBBCode.val(data.imgpath);
			}
						
			if (typeof data.preview != 'undefined')
			{
				if (data.preview == true)
				{
					if (previewImage.attr('src').match(/_preview.png/gi) == null)
					{
						// Stuff the preview url in there
						previewImage.attr('src', previewImage.attr('src').replace('.png', '_preview.png'));
					}
					if (previewImageFull.attr('src').match(/_preview.png/gi) == null)
					{
						// Stuff the preview url in there
						previewImageFull.attr('src', previewImageFull.attr('src').replace('.png', '_preview.png'));
					}
				}
				else
				{
					if (previewImage.attr('src').match(/_preview.png/gi) != null)
					{
						// Stuff the preview url in there
						previewImage.attr('src', previewImage.attr('src').replace('_preview.png', '.png'));
					}
					if (previewImageFull.attr('src').match(/_preview.png/gi) != null)
					{
						// Stuff the preview url in there
						previewImageFull.attr('src', previewImageFull.attr('src').replace('_preview.png', '.png'));
					}
				}
				
				var src = previewImage.attr('src');
				var pos = src.indexOf('?');
				if (pos >= 0)
				{
					src = src.substr(0, pos);
				}
				previewImage.attr('src', src + '?v=' + (Math.random() * 99999999999999));
				
				var src = previewImageFull.attr('src');
				var pos = src.indexOf('?');
				if (pos >= 0)
				{
					src = src.substr(0, pos);
				}
				previewImageFull.attr('src', src + '?v=' + (Math.random() * 99999999999999));
			}			
		})
		.fail(function(data, textStatus)
		{
			try
			{
				if (data.statusText == 'communication failure' || data.statusText == 'transaction aborted' || data.status == 0)
				{
					// Ignore this error
					return false;
				}
				
				// Log the error to the console
				console.error(timeStamp() + "AJAX Error: Status = %s: %s", data.status, data.statusText);
			}
			catch (e)
			{
				// Log the error to the console
				console.error(timeStamp() + "AJAX Error: %s", data.responseText);
			}
		});
	};
	
	// #########################################################################
	// Debugging function, generates a timestamp of when something occurred
	function timeStamp()
	{
		var d = new Date();
		
		return '[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] ';
	};	
});

YAHOO.util.Event.onDOMReady(function()
{
	var scroll_offset = YAHOO.util.Dom.get('usercp_nav').offsetTop;
	//YAHOO.util.Dom.setStyle('usercp_nav', 'width', YAHOO.util.Dom.getSignaturestyle('usercp_nav_container', 'width'));

	YAHOO.util.Event.addListener(window, 'scroll', function()
	{	
		var scroll_top = YAHOO.util.Dom.getDocumentScrollTop();
		if (scroll_top + YAHOO.util.Dom.get('usercp_nav').offsetHeight < YAHOO.util.Dom.get('content').offsetHeight && scroll_top > scroll_offset)
		{
			YAHOO.util.Dom.setStyle('usercp_nav', 'position', 'fixed');
			YAHOO.util.Dom.setStyle('usercp_nav', 'marginTop', '-' + (scroll_offset - 10) + 'px');
		}
		else if (scroll_top > scroll_offset)
		{
			YAHOO.util.Dom.setStyle('usercp_nav', 'position', '');
			YAHOO.util.Dom.setStyle('usercp_nav', 'marginTop', ((YAHOO.util.Dom.get('content').offsetHeight - YAHOO.util.Dom.get('usercp_nav').offsetHeight) > 0 ? (YAHOO.util.Dom.get('content').offsetHeight - YAHOO.util.Dom.get('usercp_nav').offsetHeight) : 0) + 'px');
		}
		else if (scroll_top < scroll_offset)
		{
			YAHOO.util.Dom.setStyle('usercp_nav', 'position', '');
			YAHOO.util.Dom.setStyle('usercp_nav', 'marginTop', '5px');
		}
	});
});