var ft_subtypes = new Array();
ft_subtypes['website-templates'] = new Array();
ft_subtypes['website-templates']['xhtmlcss'] = 'Tableless XHTML/CSS';
ft_subtypes['website-templates']['html'] = 'Tables-based HTML';

$(function() {

	var __degrade6 = (jQuery.browser.msie && jQuery.browser.version <= 6);
	var __degrade7 = (jQuery.browser.msie && jQuery.browser.version <= 7);
	$('a.offsite').attr('target', '_blank');
	jQuery('#cartsize').each(function() { var t = jQuery(this), x, y; if ((x = af_getCookie('4t_scrc')) == null || (y = x.split('|')).length < 2) val = 0; else val = y[1]; t.text(' (' + val + ')'); });

	////////////////////////////////////////////////////////////////////////////////////////////////
	// colorbox
	////////////////////////////////////////////////////////////////////////////////////////////////

		jQuery.fn.ft_colorbox = function() {
			
			////////////////////////////////////////////////////////////////////////////////////////
			// initialize
			////////////////////////////////////////////////////////////////////////////////////////

				var t = $(this), o = t.find('option'), fieldName = t.attr('name');
				t.hide();

				if (__degrade7)
				{
					t.show();
				
					o.each(function() {
						var x = $(this), tmp, name, code;

						if (x.val() == '')
							return;

						tmp = $.trim(x.text());
						code = tmp.match(/#[a-fA-F0-9]{6}/i)[0];
						name = tmp.split(' ')[0];
						x
							.text(name)
							.css('background-color', code);
					});
					
					return;
				}

				// Build colors array
					var colors = new Array();
					o.each(function() {
						var x = $(this), tmp, name, code;
						
						if (x.val() == '')
							return;

						tmp = $.trim(x.text());
						code = tmp.match(/#[a-fA-F0-9]{6}/i)[0];
						name = tmp.split(' ')[0];
						
						colors[x.val()] = new Array(code, name);
					});

				// Get current color
					var activeColor = t.val();

					if (activeColor == '')
						activeColor = 'none';
				
				// Build cb
					var tmp = '<span class="opt opt_none first">&nbsp;<strong>none</strong></span>';
					
					count = 1;
					
					for (i in colors)
					{
						tmp = tmp + '<span class="opt opt_' + i + (count % 4 == 0 ? ' first' : '') + '">&nbsp;<strong>' + i + '</strong></span>';

						count++;

						if (count % 4 == 0)
							tmp = tmp + '<br />';
					}
				
					var cb = $(
						'<div class="colorbox">' + 
							'<span class="opt opt_' + activeColor + ' opener">&nbsp;<strong>' + activeColor + '</strong></span>' +
							'<input type="hidden" name="' + fieldName + '" value="' + activeColor + '" />' +
							'<div class="panel">' + 
								'<div class="inner">' +
									tmp + 
								'</div>' +
							'</div>' +
						'</div>'
					);
					
					cb.insertAfter(t);
					
					t.remove();

			////////////////////////////////////////////////////////////////////////////////////////
			// configure
			////////////////////////////////////////////////////////////////////////////////////////
				
				// input
					var input = cb.find('input');

				// opener
					var opener = cb.find('.opener');
					opener
						.disableSelection()
						.click(function(e) {
							e.stopPropagation();
							cb.trigger('togglePanel');
						});
				
				// panel
					var panel = cb.find('.panel');
					panel
						.disableSelection()
						.click(function(e) {
							e.stopPropagation();
						})
						.css('position', 'absolute')
						.css('z-index', 1)
						.css('left', opener.position().left + opener.outerWidth() - panel.outerWidth())
						.css('top', opener.position().top + opener.outerHeight())
						.hide();

					panel.find('.inner')
						.css('z-index', 1);

					// opts
						var opts = panel.find('.opt');
						opts
							.click(function(e) {
								e.stopPropagation();
								var v = $.trim($(this).find('strong').text());
								cb
									.trigger('changeColor', [v])
									.trigger('hidePanel');
							});

				// cb
					cb
						.disableSelection()
						.bind('togglePanel', function(e) {
							if (panel.is(':visible'))
								cb.trigger('hidePanel');
							else
								cb.trigger('showPanel');
						})
						.bind('hidePanel', function(e) {
							opener.removeClass('opener_active');
							panel.fadeOut(100);
						})
						.bind('showPanel', function(e) {
							$('.colorbox .panel').trigger('hidePanel');
							opener.addClass('opener_active');
							panel
								.css('left', opener.position().left + opener.outerWidth() - panel.outerWidth())
								.css('top', opener.position().top + opener.outerHeight())
								.fadeIn(200);
						})
						.bind('changeColor', function(e, key) {
							if (key == 'none')
								input.val('');
							else
								input.val(key);
							opener
								.removeClass('opt_' + activeColor)
								.addClass('opt_' + key)
								.find('strong')
									.text(key);
							activeColor = key;
							
						});
						
					cb.trigger('changeColor', [activeColor]);
					$('body').click(function(e) {
						cb.trigger('hidePanel');
					});
		};

	////////////////////////////////////////////////////////////////////////////////////////////////
	// xyz/n33
	////////////////////////////////////////////////////////////////////////////////////////////////

		jQuery.fn.xyz = function(options) {
			var settings = jQuery.extend({
				selectorParent:		jQuery(this)
			}, options);
			return jQuery.xyz(settings);
		}

		jQuery.xyz = function(options) {
			// Settings
				var settings = jQuery.extend({
					selectorParent: 	null,
					hotspotSelector:	null,
					contentSelector:	null,
					follow:				true,
					xpos:				'right',
					ypos:				'bottom',
					xpad:				15,
					ypad:				15,
					bottomLeftClass:	'bottom_left',
					bottomRightClass:	'bottom_right',
					bottomCenterClass:	'bottom_center',
					topLeftClass:		'top_left',
					topRightClass:		'top_right',
					topCenterClass:		'top_center',
					delay:				450
				}, options);

			settings.selectorParent.each(function() {
				// Vars
					var timeoutID, p = $(this), q = p.nextAll(settings.contentSelector), cy = settings.ypos, cx = settings.xpos;
				// Main
					function getLeft(offset)
					{
						switch (settings.xpos)
						{
							case 'center':
								cx = 'Center';
								if (offset <= q.outerWidth() + 5) {
									cx = 'Right';
									return Math.min(jQuery(window).width() - q.outerWidth(), offset + settings.xpad);
								}
								else if (offset >= jQuery(window).width() - q.outerWidth() - 5) {
									cx = 'Left';
									return Math.max(0, offset - q.outerWidth() - settings.xpad);
								}
								return Math.min(Math.max(0, offset - (q.outerWidth() / 2) + 1), jQuery(window).width() - q.outerWidth());
							case 'left':
								cx = 'Left';
								if (offset <= q.outerWidth() + 5) {
									cx = 'Right';
									return Math.min(jQuery(window).width() - q.outerWidth(), offset + settings.xpad);
								}
								return Math.max(0, offset - q.outerWidth() - settings.xpad);
							case 'right':
								cx = 'Right';
								if (offset >= jQuery(window).width() - q.outerWidth() - 5) {
									cx = 'Left';
									return Math.max(0, offset - q.outerWidth() - settings.xpad);
								}
								return Math.min(jQuery(window).width() - q.outerWidth(), offset + settings.xpad);
						}
								
						return offset;
					}
					
					function getTop(offset)
					{
						var n;
						switch (settings.ypos)
						{
							case 'top':
								n = offset - q.outerHeight() - settings.ypad;
								cy = 'top';
								if (n > 0)
									return n;
							case 'bottom':
								if (offset + q.outerHeight() >= jQuery(window).height() - settings.ypad) {
									cy = 'top';
									return offset - q.outerHeight() - settings.ypad;
								}
								cy = 'bottom';
								return Math.min(jQuery(window).height() - q.outerHeight(), offset + settings.ypad);
						}
						
						return offset;
					}
					
					var t;
					
					q.
						hide().
						css('position', 'fixed');
						//css('top', getTop(p.offset().top)).
						//css('left', getLeft(p.offset().left + (p.width() / 2)));
					p.
						bind('turnoff', function() {
							window.clearTimeout(timeoutID);
							q.hide();
						}).
						css('cursor', 'help').
						mousemove(function(event) {
							if (settings.follow) {
								eval('t = settings.' + cy + cx + 'Class;');
								if (t)
									q.removeClass(t);
								q.css('top', getTop(event.clientY)).css('left', getLeft(event.clientX, true));
								//alert(q.outerHeight());
								eval('t = settings.' + cy + cx + 'Class;');
								q.addClass(t);
								//alert(q.outerHeight());
							}
						}).
						mouseenter(function(event) {
							if (settings.delay == 0)
								q.show();
							else
								timeoutID = window.setTimeout(function() {
									q.show();
								}, settings.delay);
						}).
						mouseleave(function() {
							window.clearTimeout(timeoutID);
							q.hide();
						}).
						click(function() {
							window.clearTimeout(timeoutID);
							q.hide();
						});
			});
		}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// formerize/n33
	////////////////////////////////////////////////////////////////////////////////////////////////

		jQuery.fn.ft_formerize = function() {
			// password fields
			jQuery(this)
				.find('input[type=password]')
					.each(function() {
						var e = jQuery(this);
						var x = jQuery(jQuery('<div>').append(e.clone()).remove().html().replace(/type="password"/i, 'type="text"').replace(/type=password/i, 'type=text'));
						if (e.attr('id') != '')
							x.attr('id', e.attr('id') + '_fakeformerizefield');
						if (e.attr('name') != '')
							x.attr('name', e.attr('name') + '_fakeformerizefield');
						x.addClass('blank').val(x.attr('title')).insertAfter(e);
						if (e.val() == '')
							e.hide();
						else
							x.hide();
						e.blur(function(event) {
							event.preventDefault();
							var e = jQuery(this);
							var x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]');
							if (e.val() == '') {
								e.hide();
								x.show();
							}
						});
						x.focus(function(event) {
							event.preventDefault();
							var x = jQuery(this);
							var e = x.parent().find('input[name=' + x.attr('name').replace('_fakeformerizefield', '') + ']');
							x.hide();
							e.show().focus();
						});
						// just in case :P
						x.keypress(function(event) {
							event.preventDefault();
							x.val('');
						});
					});
			// text fields
			jQuery(this)
				.find('input[type=text],textarea')
					.each(function() {
						var e = jQuery(this);
						if (e.val() == '' || e.val() == e.attr('title')) {
							e.addClass('blank');
							e.val(e.attr('title'));
						}
					})
					.blur(function() {
						var e = jQuery(this);
						if (e.attr('name').match(/_fakeformerizefield$/))
							return;
						if (e.val() == '') {
							e.addClass('blank');
							e.val(e.attr('title'));
						}
					})
					.focus(function() {
						var e = jQuery(this);
						if (e.attr('name').match(/_fakeformerizefield$/))
							return;
						if (e.val() == e.attr('title')) {
							e.removeClass('blank');
							e.val('');
						}
					});
			// form events
			jQuery(this)
				// submit
				.submit(function() {
					jQuery(this)
						.find('input[type=text],textarea')
							.each(function(event) {
								var e = jQuery(this);
								if (e.attr('name').match(/_fakeformerizefield$/))
									e.attr('name', '');
								if (e.val() == e.attr('title')) {
									e.removeClass('blank');
									e.val('');
								}
							});
				})
				// reset
				.bind("reset", function(event) {
					event.preventDefault();
					// temporary: just set all SELECTs to their first options
					jQuery(this)
						.find('select')
							.val(jQuery('option:first').val());
					jQuery(this)
						.find('input,textarea')
							.each(function() {
								var e = jQuery(this);
								var x;
								e.removeClass('blank');
								switch (this.type) {
									case 'password':
										e.val(e.attr('defaultValue'));
										x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]');
										if (e.val() == '') {
											e.hide();
											x.show();
										}
										else {
											e.show();
											x.hide();
										}
										break;
									case 'checkbox':
									case 'radio':
										e.attr('checked', e.attr('defaultValue'));
										break;
									case 'text':
									case 'textarea':
										e.val(e.attr('defaultValue'));
										if (e.val() == '') {
											e.addClass('blank');
											e.val(e.attr('title'));
										}
										break;
									default:
										e.val(e.attr('defaultValue'));
										break;
								}
							});
				});
				
			return jQuery(this);
		};

	////////////////////////////////////////////////////////////////////////////////////////////////
	// list
	////////////////////////////////////////////////////////////////////////////////////////////////

		if ($('#layout_list').exists())
		{
			$('#layout_list .searchbar').each(function() {
				var sb = $(this), t = sb.find('#type'), st = sb.find('#subtype'), f = sb.find('form'), submit = sb.find('#submit'), search = sb.find('#search');
				var container = sb.find('.container'), shutter = sb.find('.shutter');

				var p = af_getPref('4t', 'searchbar_status');
				
				if (p == 'off')
					sb.addClass('searchbar_off');
				
				var searchSuggestions = new Array();
					searchSuggestions[0] = 'corporate glassy';
					searchSuggestions[1] = 'computers clean';
					searchSuggestions[2] = 'dark metallic';
					searchSuggestions[3] = 'bright distressed';
					searchSuggestions[4] = 'paper realistic';
					searchSuggestions[5] = 'jquery gallery';
					searchSuggestions[6] = 'music modern';

				search.attr('title', 'eg. ' + searchSuggestions[$.rand(0, searchSuggestions.length - 1)]);
				if (search.val().substring(0,3) == 'eg.')
					search.val('');
				f.ft_formerize();
				
				submit
					.click(function(e) {
						f.find('input, select').each(function () {
							var tmp = $(this);
							if (tmp.val() == '' || tmp.val() == tmp.attr('title'))
								tmp.attr('disabled', 'disabled');
						});
						f.submit();
						e.preventDefault();
						e.stopPropagation();
					});
				
				shutter
					.click(function() {
					
						if (container.is(':visible'))
						{
							af_setPref('4t', 'searchbar_status', 'off');
							f.fadeOut(200);
							container.slideUp(250, function() {
								sb.toggleClass('searchbar_off');
							});
						}
						else
						{
							af_setPref('4t', 'searchbar_status', 'on');
							f.fadeIn(300);
							container.slideDown(250, function() {
								sb.toggleClass('searchbar_off');
							});
						}
					
					});
					
				sb
					.bind('update', function(e, type, subtype) {
						var v = t.val();
						
						sb.find('form').attr('action', '/' + v + '/');
						
						if (ft_subtypes[v] != null)
						{
							var s = '<option value="">- Any -</option>';

							for (i in ft_subtypes[v])
								s = s + '<option value="' + i + '"' + (type == v && subtype == i ? ' selected' : '') + '>' + ft_subtypes[v][i] + '</option>';
								
							st.html(s);
							st.attr('disabled', false);
							st.fadeTo(0, 1);
						}
						else
						{
							st.html('');
							st.attr('disabled', true);
							st.fadeTo(0, 0.50);
						}

					})
				
				t.change(function() {
					sb.trigger('update');
				});
			});

			$('#layout_list .searchbar .color').each(function() {
				$(this).ft_colorbox();
			});

			$('#layout_list .ipp select')
				.change(function() {
					af_setPref('4t', 'list_ipp', $(this).val());
					var h = location.href, x = h.split('/'), y = x[x.length - 2];
					if (parseInt(y) == y) h = x.slice(0, x.length - 2).join('/') + '/';
					af_redirectAndReplace(h);
				});
			
		}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// view
	////////////////////////////////////////////////////////////////////////////////////////////////

		jQuery.fn.ft_view = function() {
			var active = 0;
			var t = $(this);
			
			var summary = t.find('.summary');
			var thumbviewer = t.find('.thumbviewer'), thumbviewer_items = thumbviewer.find('li'), thumbviewer_as = thumbviewer.find('li a');
			
			var preview = t.find('.preview');
			var preview_image = preview.find('.image');
			var img = preview.find('img');
			var loader = preview.find('.loader');
			
			var tmpimg = $('<img src="/site/images/spacer.gif" />');
			var count = thumbviewer_items.size();
			var isLocked = false;

			if (__degrade6)
			{
				t.find('strong.def').each(function() {
					var t = $(this), label = t.next('.xyzlabel');
					label.hide();
					t
						.html('<acronym title="' + label.text() + '">' + t.text() + '</acronym>')
						.css('cursor', 'pointer');
				});
			}
			else
			{
				t.find('strong.def').xyz({
					contentSelector: '.xyzlabel',
					follow: true,
					xpos: 'center',
					ypos: 'top',
					xpad: 0,
					ypad: 25,
					delay: 150
					//bottomLeftClass: 'label_bottom_left',
					//bottomRightClass: 'label_bottom_right',
					//bottomCenterClass: 'label_bottom_center',
					//topLeftClass: 'label_top_left',
					//topRightClass: 'label_top_right',
					//topCenterClass: 'label_top_center'
				});
			}

			tmpimg
				.load(function() {
					if (tmpimg.attr('src').search(/spacer.gif$/) != -1)
						return true;
				
					img
						.stop(true, true)
						.attr('src', tmpimg.attr('src'))
						.fadeTo(0, 1);

					tmpimg
						.attr('src', '/site/images/spacer.gif');

					loader
						.hide();
					
					ft_thumbviewer_layoutPreviewStatus[active] = 1;
					summary.text(ft_thumbviewer_layoutPreviewTitles[active] + ' ('  + (active + 1) + '/' + count + ')');
					isLocked = false;
				});
			
			preview
				.bind('switchTo', function (e, n) {

					if (isLocked)
						return;

					active = parseInt(n);

					thumbviewer_items.removeClass('active');
					thumbviewer_items.eq(n).addClass('active');

					var src = ft_thumbviewer_layoutPreviewURLs[ft_thumbviewer_layoutPreviewOrder[active]];

					if (parseInt(ft_thumbviewer_layoutPreviewStatus[n]) == 1)
					{
						img.attr('src', src);
						summary.text(ft_thumbviewer_layoutPreviewTitles[active] + ' ('  + (active + 1) + '/' + count + ')');
					}
					else
					{
						isLocked = true;

						tmpimg.attr('src', src);
						
						img.fadeTo(800, 0.65);
						loader.fadeTo(500, 1);
					}
				})
				.bind('next', function() {			
					var i = parseInt(active) + 1;

					if (i >= ft_thumbviewer_layoutPreviewOrder.length)
						i = 0;
				
					preview.trigger('switchTo', [i]);
				});
				
			preview_image
				.css('cursor', 'pointer')
				.click(function() {
					preview.trigger('next');
				});
			
			thumbviewer_items
				.disableSelection()
				.css('cursor', 'pointer')
				.click(function() {
					var i = $(this), n = i.attr('id').split('_')[1];
					preview.trigger('switchTo', n);
				});
		};

		if ($('#layout_view').exists())
			$('#layout_view').ft_view();

});
