/**
 * Deziro APP Wide Settings
 */

/**
 * Global Clicksports Namespace
 */
var CS = {};

$(function() {
	
	CS.createPlaceHolders();
	
	$('#content .tooltip').qtip({
		content: { text: false }
	});
	
	$('#navigation-main').superfish({
		delay: 750,
		dropShadows: false,
		autoArrows: false,
		hoverClass: 'hover'
	});
	
	// Show messages for 5 seconds
	setTimeout(function(){
		$('#content .message').hide('fast')
	}, CS.settings.default_fadeout);
});

/**
 * Create placeholder attributes for browsers that don`t support them
 */
CS.createPlaceHolders = function() {
	
	$('[placeholder]').focus(function() {
	
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
	
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
	
		var input = $(this);
		if(input.val() === '' || input.val() == input.attr('placeholder')) {
	
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur();
	
	$('[placeholder]').parents('form').submit(function() {
	
		$(this).find('[placeholder]').each(function() {
	
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				
				input.val('');
			}
		});
	});
}

/**
 * Create a category chain select
 * 
 * @param {Object} elm
 * @return {Object} elm
 */
CS.createCategorySelect = function(elm) {
	
	var elm = $(elm);
	var index = 0;

	var req = function(index) {
		
		var url = CS.settings.category_chain_url;
		if(index !== 0) url += '/' + index;
		
		$.ajax({
			url: url,
			cache: true,
			success: function(data) {
				
				var options = $.parseJSON(data);
				
				// Stop if we have an empty category
				if(options.length === 0) return;
				
				if(index === 0) opts = '<option value="0">Keine</option>';
				else {
					
					opts = '<option value="">Unterkategorie auswählen</option>';
					opts += '<option value="back">Zurück</option>';
				}
				
				for(opt in options) {
					
					opts += '<option value="' + opt + '">' + options[opt] + '</option>';
				}
				
				elm.html(opts);
				return index;
			}
		});
	}

	// Load base once
	elm.one('click', function(e) { index = req(index); });
	
	elm.change(function(e) {
		
		var val = $(this).val();
		if(val === 0 || val.length === 0) return;
		
		// If we should go back...
		if(val === 'back') val = 0;
		
		req(val);
	});
	
	return elm;
}

/**
 * Create tooltips for the sidebar
 * 
 * @return {Boolean}
 */
CS.createSidebarTooltips = function() {

	var lists = $('#wishlist-sidebar-listing li');
	$.each(lists, function() {
		
		var elm = $(this);
		var heading = elm.find('h4 a');
		var content = $(heading.attr('href'));
		
		heading
			.css('cursor', 'help')
			.click(function(e) {
				
				e.preventDefault();
			})
			.qtip({
				content: content.html(),
				position: {
					corner: {
						target: 'bottomMiddle',
						tooltip: 'topMiddle'
					}
				},
				hide: {
					fixed: true
				}
			});
	});
	
	return true;
}

