jQuery.fn.identify = function(prefix)
{
	var i = 0;
	return this.each(function() {
		if($(this).attr('id')) return;
		do {
			i++;
			var id = prefix + '_' + i;
		} while($('#' + id).length > 0);
		$(this).attr('id', id);
	});
};

$(document).ready(function()
{
	initSWFIR();
	initFancyImages();
	initEasySlider();
	initSearchText();
	initFavsDelete();
	initMarkSold();
	initCloseRequest();
	initModalPageLinks();
	initImageUploader();
	initCategoryChange();
	initDefaultFieldForms();
	initDateTimePickers();
	initInputMasking();
	initDeleteLinks();
	initWYSIWYG();
	initCountryDDL();
});

function initCountryDDL()
{
	if ($('select#PaypalCountry').length)
	{
		$('select#PaypalCountry').change(function(e){
			var code = $.trim($(this).val().toLowerCase());

			$('.country_field_info, .country_item').hide();

			if (code != '')
			{
				if ($('.country_item.country_item_' + code).length)
				{
					$('.country_field_info, .country_item_' + code).show();
				}

				else
				{
					$('.country_field_info, .country_item_rest').show();
				}
			}
		});

		$('select#PaypalCountry').change();
	}
}

// Initialize the delete links
function initDeleteLinks()
{
	// Remove any preexisting click functions.
	$('a.dlink').unbind('click');

	// Setup the click function to confirm the user wants to delete the selected item
	$('a.dlink').click(function(e)
	{
		var tempLink = $(this);
		var tempTitle = new String(tempLink.attr('title'));

		// If they don't confirm then stop the event.
		if (!confirm('Are you sure you want to ' + tempTitle.toLowerCase() + '?' + '\nAll related data will be permanently lost.'))
		{
			e.stopPropagation();
			return false;
		}

		return true;
	});
}

// WYSIWYG Editors
function initWYSIWYG()
{
	var wigs = $('textarea.wysiwyg_replace');

	if (wigs.length > 0)
	{
		var config = {
			toolbar:
			[
				['Format', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'SpecialChar', 'Maximize']
			],
			disableNativeSpellChecker:false,
			toolbarCanCollapse:false,
			removePlugins:'elementspath',
			//ignoreEmptyParagraph:true,
			forcePasteAsPlainText:true,
			entities:false,
			resize_enabled:false
		};

		// Initialize the editor.
		// Callback function can be passed and executed after full instance creation.

		for (var i = 0; i < wigs.length; i++)
		{
			var field = $(wigs[i]);
			var tempWidth = field.width();
			tempWidth += parseInt(field.css("padding-left"), 10) + parseInt(field.css("padding-right"), 10);
			tempWidth += parseInt(field.css("borderLeftWidth"), 10) + parseInt(field.css("borderRightWidth"), 10);

			config.width = tempWidth;

			field.wrap('<div class="wysiwyg_wrap" />');
			field.ckeditor(config);
		}
	}
}

function initInputMasking()
{
	$('input.numeric').numeric();
}

function initFancyImages()
{
	$("a.fancy_image").fancybox
	({
		titleShow: false,
		overlayOpacity: 0.7,
		overlayColor: '#000'
	});
}

function initDateTimePickers()
{
	var fields = $('input.datetime');

	if (fields.length > 0)
	{
		fields.datetimepicker
		({
			dateFormat: 'yy-mm-dd',
			timeFormat: 'hh:mm:ss',
			showSecond: false,
			stepHour: 1,
			stepMinute: 5,
			hour: 17,
			minute: 0
		});
	}

	var fields2 = $('input.date');

	if (fields2.length > 0)
	{
		fields2.datepicker
		({
			dateFormat: 'yy-mm-dd'
		});
	}
}

function initDefaultFieldForms()
{
	// Remove any preexisting click functions.
	$('a#request_post_back').unbind('click');

	// Link to add supply items
	$('a#request_post_back').click(function(e)
	{
		e.stopPropagation();

		$(this).parents('form').find('div.next_step input').val('');
		$(this).parents('form').submit();

		return false;
	});

	$('form.default_field_form').submit(function(){
		// Loop through the fields and remove the default field values

		$('div.default_val').each(function(){
			var field = $(this).parents('.default_field').find('input');

			focusDefaultField(field);
		});

		return true;
	});

	$('div.default_val').each(function(){
		var field = $(this).parents('.default_field').find('input');

		field.focus(function(e){
			focusDefaultField($(this));
		});

		field.blur(function(e){
			blurDefaultField($(this));
		});

		blurDefaultField(field);
	});
}

function focusDefaultField(field)
{
	var defaultVal = jQuery.trim(field.parents('.default_field').find('div.default_val').text());
	var curVal = jQuery.trim(field.val());

	if (curVal.toLowerCase() == defaultVal.toLowerCase())
	{
		field.val('');
	}
}

function blurDefaultField(field)
{
	var defaultVal = jQuery.trim(field.parents('.default_field').find('div.default_val').text());
	var curVal = jQuery.trim(field.val());

	if (curVal.toLowerCase() == '' || curVal.toLowerCase() == defaultVal.toLowerCase())
	{
		field.val(defaultVal);
	}
}

function initModalPageLinks()
{
	var links = $('a.modal_page').fancybox({
		titleShow: false,
		scrolling: 'no',
		overlayOpacity: 0.7,
		width: 100,
		height: 100,
		type: 'iframe',
		overlayColor: '#000',
		padding: 10
	});
}

function hideAcceptBidButtons(id)
{
	if ($('ol.bid_list li').length > 0)
	{
		$('ol.bid_list li a.accept_bid').remove();
		$('<p><strong>*** ACCEPTED BID ***</strong></p>').insertAfter('li#bid_request_' + id + ' span.bid_amount');
	}
}

function initCloseRequest()
{
	// Remove any preexisting click functions.
	$('a.close_request').unbind('click');

	// Link to add supply items
	$('a.close_request').click(function(e)
	{
		e.stopPropagation();

		var curLink = $(this);

		if (confirm('Are you sure you want to close this request?\nBy doing so it will no longer appear on the site.'))
		{
			curLink.hide();

			$.getJSON(curLink.attr('href'), null, function (data)
			{
				// If there was an error
				if (typeof(data.code) == 'undefined' || data.code == '0')
				{
					curLink.show();

					if (typeof(data.msg) != 'undefined')
					{
						alert(data.msg);
					}

					else
					{
						alert('There was an error while trying to mark this item as sold.\nPlease try again later.');
					}
				}

				else
				{
					curLink.parents('li').find('span.vendor_bid').replaceWith('<span class="sold">closed</span>');
					curLink.remove();
				}
			});
		}

		return false;
	});
}

function initMarkSold()
{
	// Remove any preexisting click functions.
	$('a.mark_sold').unbind('click');

	// Link to add supply items
	$('a.mark_sold').click(function(e)
	{
		e.stopPropagation();

		var curLink = $(this);

		if (confirm('Are you sure you want to mark this item as sold?\nBy doing so it will no longer appear on the site.'))
		{
			curLink.hide();

			$.getJSON(curLink.attr('href'), null, function (data)
			{
				// If there was an error
				if (typeof(data.code) == 'undefined' || data.code == '0')
				{
					curLink.show();

					if (typeof(data.msg) != 'undefined')
					{
						alert(data.msg);
					}

					else
					{
						alert('There was an error while trying to mark this item as sold.\nPlease try again later.');
					}
				}

				else
				{
					curLink.parents('li').find('span.sellers_price').replaceWith('<span class="sold">sold</span>');
					curLink.remove();
				}
			});
		}

		return false;
	});
}

function initFavsDelete()
{
	// Remove any preexisting click functions.
	$('a.remove_fav').unbind('click');

	// Link to add supply items
	$('a.remove_fav').click(function(e)
	{
		e.stopPropagation();

		var curLink = $(this);
		curLink.hide();

		$.getJSON(curLink.attr('href'), null, function (data)
		{
			// If there was an error
			if (typeof(data.code) == 'undefined' || data.code == '0')
			{
				curLink.show();

				if (typeof(data.msg) != 'undefined')
				{
					alert(data.msg);
				}

				else
				{
					alert('There was an error while trying to remove this item from your favorites.\nPlease try again later.');
				}
			}

			else
			{
				curLink.parents('li').slideUp("slow", function()
				{
					var list = curLink.parents('ul');

					$(this).remove();

					if (list.find('li').length > 0)
					{
						list.find('li').removeClass('odd');
						list.find('li:even').addClass('odd');
					}

					else
					{
						list.replaceWith('<div>You currently do not have any favorite items selected.</div>');
					}
				});
			}
		});

		return false;
	});
}

function initSearchText()
{
	if ($('input#main_search').length > 0)
	{
		$('input#main_search').unbind('focus');
		$('input#main_search').focus(function(e){
			var tempVal = jQuery.trim($(this).val());

			if (tempVal.toLowerCase() == 'what are you looking for?')
			{
				$(this).val('');
			}
		});

		$('input#main_search').unbind('blur');
		$('input#main_search').blur(function(e){
			var tempVal = jQuery.trim($(this).val());

			if (tempVal == '' || tempVal == 'what are you looking for?')
			{
				$(this).val('What are you looking for?');
			}
		});
	}
}

function initSWFIR()
{
	if (typeof(swfir) != 'undefined' && typeof(swfir) != null)
	{
		var tilted = new swfir();
		tilted.specify("shadow-blur", "15");
		tilted.specify('rotate', '-5');
		tilted.specify("border-width", "10");
		tilted.specify("border-color", "fff");
		tilted.specify('shadow-color', '999');
		tilted.specify('src', '/assets/js/swfir.swf');
		tilted.swap("#this_week_pic img");
	}
}

function initEasySlider()
{
	if ($('#slider').length > 0)
	{
		$("#slider").easySlider({
			auto: false,
			continuous: true,
			controlsShow: false,
			nextId: "nextBtn",
			prevId: "prevBtn"
		});
	}
}

function initCategoryChange()
{
	$("select#CategoryId").change(function(e)
	{
		$(this).parents('.category_selector').find("div.children").hide();
		$(this).parents('.category_selector').find("div.children input").attr('checked', false);
		$(this).parents('.category_selector').find("div#children-" + $(this).val()).show();

		if ($(this).val() == '')
		{
			$(this).attr('name', 'data[Category][checkbox][0]');
		}

		else
		{
			$(this).attr('name', 'data[Category][checkbox][' + $(this).val() + ']');
		}
	});
}

