/**
 * @author Neil Lunn
 */
function list (variables, values, scope) {
	for (var i = 0; i < variables.length && i < values.length; i++) {
		(scope || this)[variables[i]] = values[i];
	}
}

// Extentions
(function($){
	var svTitle = "";
	$.fn.extend({
		SetTitle: function(){
			var pref = $(this).parent().parent().attr("title") + " - ";
			var cnt = $(this).text().toString().match(/\((\d+)\)/);
			var suff = " items found";
			if (parseInt(cnt[1]) == 1) {
				suff = " item found";
			}
			$(this).attr("title", pref + $(this).text() + suff);
		},
		HoverState: function(){
			$(this).hover(function(){
				$(this).toggleClass('sfHover');
				$(this).parent().toggleClass('sfHover');
				// Hide ul title so it does not display in IE/Webkit
				svTitle = $(this).parent().parent().attr("title");
				$(this).parent().parent().attr("title", "");
			}, function(){
				$(this).toggleClass('sfHover');
				$(this).parent().toggleClass('sfHover');
				// Save the ul title back 
				$(this).parent().parent().attr("title", svTitle);
			})
		}
		
	});
})(jQuery);

$(document).ready(function(){

	// Style Buttons
	$("#selection-crumbs a").each(function(){
		$(this).addClass('fg-button ui-state-default fg-button-icon-right ui-corner-all');
		$(this).prepend($("<span />").addClass('ui-icon ui-icon-circle-close'));
		$(this).tooltip({
			showURL: false,
			track: true,
			fixPNG: true,
			delay: 0,
			bodyHandler: function(){
				if ($(this).hasClass('remove-all')) {
					return $('<p />').html('<b>' + $(this).text() + '</b> from Selection');
				} else {
					return $('<p />').html('Remove <b>' + $(this).text() + '</b> from Selection');
				}		
			}
		});
	});
	
	$("#selection-crumbs").show();
	
	//all hover and click logic for buttons
	$(".fg-button:not(.ui-state-disabled)").hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	);
	
    // Size Nav - Horizontal
    $("#size-nav a").each(function(){
        var text = $(this).text();
        $(this).SetTitle();
        $(this).text(text.replace(/\s\(\w+\)/, ""));
        $(this).parent().css({
            "float": "left",
            "padding-right": "3px"
        });
        $(this).HoverState();
        $(this).tooltip({
            showURL: false,
            track: true,
			showBody: " - ",
			fixPNG: true,
            delay: 0,
			bodyHandler: function(){
				var $content = $("<div />");
				var parts = this.tooltipText.split($.data(this, "tooltip").showBody);
				$content.append($("<b />").text(parts[0]));
				$content.append($("<p />").text(parts[1]));
				return $content;
			}
        });
        
    });


    // Initiate Color Nav Styling with a callback on background image load.
    $(new Image()).load(function(){
        
		// Set up colours
		var xpos = 0;
        var colnames = [		// Set up colours used here
			"aqua", "black", "blue", "brown", "gray", "green", "orange",
			"pink", "purple", "red", "white", "yellow", "nude"
		];
        
        var colOffset = {};
        
        for (var n = 0; n <= colnames.length; n++) {
            colOffset[colnames[n]] = xpos;
            xpos -= 12;			// Current offset is 12px for each colour square
        }
        
		// Assign code to objects
        $("#color-nav a").each(function(){
            var clName = $(this).attr("class");
	        var hldOffset = (colOffset[clName]) ? colOffset[clName] : 0;
            $(this).css({
                "background-image": "url(http://images.trixanbody.com.au/pacnettrx/static/images/colours.jpg)",
                "background-position": hldOffset + "px 0px"
            });
            $(this).SetTitle();
            $(this).text("");
            $(this).HoverState();
            $(this).tooltip({
                showURL: false,
                track: true,
				showBody: " - ",
				fixPNG: true,
                delay: 0,
				bodyHandler: function(){
					var $content = $("<div />");
					var parts = this.tooltipText.split($.data(this, "tooltip").showBody);
					$content.append($("<b />").text(parts[0]));
					$content.append($("<p />").text(parts[1]));
					return $content;
				}				
            });
        });
    }).attr("src", "http://images.trixanbody.com.au/pacnettrx/static/images/colours.jpg");
	
    // Style Navigation
    $("#style-nav a").each(function(){
	list(['iName', 'cName'],$(this).attr("class").toString().replace(/sfHover/,"").split(' '));

	iName += ".png";

	var imgName = '/static/images/styles/';

	if (typeof(cName) != 'undefined' ) {

		imgName +=  cName + '/' + iName;

	} else {

		imgName += iName;

	}

	//var imgName = "/static/images/styles/" + $(this).attr("class").toString().split(' ')[0] + ".png";
        $(this).SetTitle();
        $(this).HoverState();
		$(this).tooltip({
			showURL: false,
			track: true,
			showBody: " - ",
			delay: 0,
			extraClass: 'large',
			fixPNG: true,
			bodyHandler: function(){
				var $content = $("<div />");
				$content.append($("<span />").css({
					"background-image": "url(" + imgName + ")"
				}));
				if ($.browser.msie && $.browser.version <= 6.0) { // Fix IE PNG Problem
					$content.find("span").css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + imgName + "')"
					});
				}
				var parts = this.tooltipText.split($.data(this, "tooltip").showBody);
				$content.append($("<b />").text(parts[0]));
				$content.append($("<p />").text(parts[1]));
				return $content;
			}
		});
    });

	// Preload those images
	$("#style-nav a").each(function(){
		var imgName = "/static/images/styles/" + $(this).attr("class").toString().split(' ')[0] + ".png";
		$(new Image()).load().attr("src", imgName);
	});

	// Basic Tooltip the basic items
	
	$("#menu-inner ul.normal a").each(function(){
		$(this).SetTitle();
		$(this).HoverState();
		$(this).tooltip({
	        showURL: false,
	        track: true,
			showBody: " - ",
			fixPNG: true,
	        delay: 0,
			bodyHandler: function(){
				var $content = $("<div />");
				var parts = this.tooltipText.split($.data(this, "tooltip").showBody);
				$content.append($("<b />").text(parts[0]));
				$content.append($("<p />").text(parts[1]));
				return $content;
			}				
		});
		
	});

    // Slider - Price Form Submit
    $("#price-slider").slider({
        range: true,
        min: parseInt($("#min-range").val()),
        max: parseInt($("#max-range").val()),
        values: [parseInt($("#min-price").val()), parseInt($("#max-price").val())],
        step: 5,
        slide: function(event, ui){
			$("#max-price").val(ui.values[1]);
			$("#max-price").change();
			$("#min-price").val(ui.values[0]);
			$("#min-price").change();
        }
    });

	$("#price-slider").tooltip();	
	$("#min-price").val($("#price-slider").slider("values",0));
	$("#max-price").val($("#price-slider").slider("values",1));
	
	$("#min-price").change(function(){
		if (parseInt($(this).val()) > parseInt($("#max-price").val())) {
			$(this).val(parseInt($("#max-price").val()));
		}
		else if (parseInt($(this).val()) < parseInt($("#min-range").val())) {
			$(this).val(parseInt($("#min-range").val()));
		} else if (parseInt($(this).val()) != $(this).val()) {
			$(this).val(parseInt($("#min-range").val()));
		} else if (parseInt($(this).val()) == parseInt($("#max-price").val())) {
			$(this).val(parseInt($("#max-price").val()) - parseInt($("#price-slider").slider("option","step")));
			if (parseInt($(this).val()) < parseInt($("#min-range").val())){
				$(this).val(parseInt($("#min-range").val()));
				$("#max-price").val(parseInt($(this).val()) + parseInt($("#price-slider").slider("option","step")));
			} 
		}
		$("#price-slider").slider("values",0,parseInt($(this).val()));
	});
	
	$("#max-price").change(function(){
		if (parseInt($(this).val()) < parseInt($("#min-price").val())) {
			$(this).val($("#min-price").val());
		} else if (parseInt($(this).val()) > parseInt($("#max-range").val())) {
			$(this).val(parseInt($("#max-range").val()));
		} else if (parseInt($(this).val()) != $(this).val()) {
			$(this).val(parseInt($("#max-range").val()));
		} else if (parseInt($(this).val() == parseInt($("#min-price").val()))) {
			$(this).val(parseInt($("#min-price").val()) + parseInt($("#price-slider").slider("option","step")));
		}
		$("#price-slider").slider("values",1,parseInt($(this).val()))
	});

	$("#max-price").numeric();
	$("#min-price").numeric();
	
	// Alternate Form selector - Prints
	$("#print :checkbox").click(function(){
		var $form = $(this).parent();
		// Strip out any existing style from URL
		var docUrl = $form.find(":last-child").val().replace(/\/print\/\w+/g,"");
		var holdUrl = docUrl;
		var count = 0; 
		$form.children(":checked").each(function(){
			docUrl += '/print/' + $(this).attr("name");
			count++; 
		});
		if (count < 3) {
			document.location = docUrl;	
		} else {
			document.location = holdUrl;
		}
		
	});
	

	// Cat page style hack
	$(".prod-price :first-child").filter("br").each(function(){
		$(this).remove();
	});
	
	// Category Page
    $("#thumbnails .colors img").each(function(){
    
        // Click Handler
        $(this).click(function(){
            var src = $(this).attr("src").toString().replace(/\.jpg/, "") + "/image1med.jpg";
            var id = $(this).attr("id").toString();
            // Replace the src on the img child of div.prod-thumb above this clicked swatch
            $(this).parent().siblings().eq(0).children().eq(0).children().eq(0).attr("src", src);
            // Change the href on the link child of div.prod-thumb above this clicked swatch
            var href = $(this).parent().siblings().eq(0).children().eq(0).attr("href").toString().replace(/#\w+/, "") + "#" + id;
            $(this).parent().siblings().eq(0).children().eq(0).attr("href", href);
            // Toggle Selected
            $(this).addClass('select');
            $(this).siblings().each(function(){
                $(this).removeClass('select');
            });
        });
        
        // Mouse over/out for older browsers
        $(this).hover(function(){ // Mouse Over
            $(this).addClass('sfHover');
			$(this).css({ 'cursor' : 'pointer'});
        }, function(){ // Mouse Out
            $(this).removeClass('sfHover');
        });
    });

	$("#menu-inner").children().show();

});
