
// When DOM is loaded
jQuery(document).ready(function(){
	
	// Make automatically-generated links open in a new window
	/* jQuery("#footer-widgets a").attr("target","_blank"); */
	jQuery(".affiliates-home a").attr("target","_blank");
	
	// Add popups to Shop Pretty page
	jQuery("#affiliates").each(function(){          
		jQuery(".affiliate-item").each(function(){
			var th=jQuery(this);
			var tko=null;
			th.hover(
				function(){
					tko=window.setTimeout(function(){
					 var prv=th.find(".popup");
					 jQuery(".affiliate-item").css("z-index",5);
					 th.css("z-index",10);
					 th.find(".popup").show(200);
					},0)
				},
				function(){
					clearTimeout(tko);
					th.find(".popup").hide(100);
				}
			);
		});
	});
	
	// Build and control category drop-down menu on Shop Pretty
	jQuery("#affiliates .affiliate-group").each(function(){	
		var label = jQuery(this).find("h3").text();
		var id = jQuery(this).attr("id");
		jQuery('#affiliate_cat_select').append(jQuery('<option></option>').val(id).html(label));  // Populate list
	});	
	jQuery('#affiliate_cat_select').append(jQuery('<option></option>').val("all").html("All"));  // Add this last
	jQuery('#affiliate_cat_select').change(resort_cat);

	// Build and control brand name drop-down menu on Shop Pretty
	var old_label = "";  // This solves the problems of duplicates
	jQuery("#affiliate_full_list .affiliate-item").each(function(){	
		var label = jQuery(this).attr("name");
		if (label != old_label) {
			// Only unique names are added
			jQuery('#affiliate_name_select').append(jQuery('<option></option>').html(label));  // Populate list
		}
		old_label = label;
	});	
	jQuery('#affiliate_name_select').change(resort_name);


	
});


function resort_cat() {
	var cat_selected = jQuery('#affiliate_cat_select option:selected').val();
	if (cat_selected == "all") {
		jQuery("#affiliates .affiliate-group").hide(200).show(300);
	} else {
		jQuery("#affiliates .affiliate-group").hide(200);
		jQuery("#affiliates #" + cat_selected).show(300);
	}
	jQuery("#affiliate_full_list .affiliate-item").hide(200);	// Get rid of all brand items, if visible
}

function resort_name() {
	var name_selected = jQuery('#affiliate_name_select option:selected').html();
	jQuery("#affiliates .affiliate-group").hide(200);	// Get rid of all categories, if visible
	jQuery("#affiliate_full_list .affiliate-item").hide(200);
	
	// Calls by name instead of by id, so duplicates are all called
	jQuery('#affiliate_full_list .affiliate-item').each(function() {
		if (jQuery(this).attr("name") == name_selected) {
			jQuery(this).show(300);
		}
	});
}
