;(function($) {

    function getFlashMovie(movieName) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? window[movieName] : document[movieName];
    }

    // Firefox returns css colors in the format, 'rgb(17, 17, 17)', instead of in
    // hexadecimal format. However IE actually returns the hex value. This function
    // is intended to detect the format of the passed in color and to convert it to
    // hexadecimal if necessary.
    function RGBtoHex(rgb) {
        var matches = rgb.match(/rgb\((\d+), (\d+), (\d+)\)/);
        if (matches) {
            var R = parseInt(matches[1]);
            var G = parseInt(matches[2]);
            var B = parseInt(matches[3]);
            return toHex(R)+toHex(G)+toHex(B);
        } else {
            matches = rgb.match(/^#([0-9a-f]+)$/);
            return matches[1];
        }
    }
    
    function toHex(N) {
        if (N==null) return "00";
        N=parseInt(N); if (N==0 || isNaN(N)) return "00";
        N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
        return "0123456789ABCDEF".charAt((N-N%16)/16)
            + "0123456789ABCDEF".charAt(N%16);
    }
    $(document).ready(function() {
    	if($('#tShirtViewer').length > 0) {
            $('#tShirtViewer').show().siblings().hide();
            $('#tShirtViewer').css('visibility', 'visible');

			  $('.product_viewer dd img').removeClass('currentPhoto');
            var logo_path = $('.colors a:first').parents('.colors').find('.logo-image').attr('src');

            // Get the swatch colors
            var primary_color = RGBtoHex($('.colors a:first').find('.primary-color').css('background-color'));
            var secondary_color;
            var json;
            if ($(this).find('.secondary-color').length > 0)
                secondary_color = RGBtoHex($('.colors a:first').find('.secondary-color').css('background-color'));
            else
                secondary_color = null;

            // Get the path of appropriate flash file for the given clothing style
            var shirt_flash = $('[name=clothing_style_flash]').val();

            // Calculate parameters to pass to the flash viewer
            if (secondary_color)
                json = '[{\"tshirtImage\": \"'+shirt_flash+'\", \"logoImage\": \"'+logo_path+'\", \"shirtColor\": \"'+primary_color+'\", \"shirtColor2\": \"'+secondary_color+'\"}]';
            else
                json = '[{\"tshirtImage\": \"'+shirt_flash+'\", \"logoImage\": \"'+logo_path+'\", \"shirtColor\": \"'+primary_color+'\"}]';

        var flashvars = false;
        
        var params = {
          menu: "false",
          wmode: "transparent",
          swliveconnect: 'true', 
          allowScriptAccess: 'sameDomain', 
          allowfullscreen: 'false'
        };
        var attributes = {
          name: ""
        };
        params.flashvars ='tempJSON=' + escape(json).toString();
        swfobject.embedSWF("/flash/products/tShirtViewerv2.swf", "tShirtViewer", "211", "256", "9.0.0","/expressInstall.swf", flashvars, params, attributes);
                       
        $('.colors a').click(function() {
        	$('.product_viewer dd img:first').removeClass('currentPhoto');
        	$('#tShirtViewer').css('visibility', 'visible');
        	$('#tShirtViewer').show().siblings().hide();
        	var self = this;
            // Find the shirt logo
            var logo_path = $(self).parents('.colors').find('.logo-image').attr('src');

            // Get the swatch colors
            var primary_color = RGBtoHex($(self).find('.primary-color').css('background-color'));
            var secondary_color;
            var json;
            if ($(this).find('.secondary-color').length > 0)
                secondary_color = RGBtoHex($(self).find('.secondary-color').css('background-color'));
            else
                secondary_color = null;

            // Get the path of appropriate flash file for the given clothing style
            var shirt_flash = $('[name=clothing_style_flash]').val();

            // Calculate parameters to pass to the flash viewer
            if (secondary_color)
                json = '[{"tshirtImage": "'+shirt_flash+'", "logoImage": "'+logo_path+'", "shirtColor": "'+primary_color+'", "shirtColor2": "'+secondary_color+'"}]';
            else
                json = '[{"tshirtImage": "'+shirt_flash+'", "logoImage": "'+logo_path+'", "shirtColor": "'+primary_color+'"}]';
            // Set variables on the embed tag and an associated params tag. Passing 
            // data via sendTextToFlash doesn't work correctly when the flash first
            // loads. But this method does.


           		//$('#tShirtViewer param[name=flashVars]').val('tempJSON='+json);
	           		try {
	            		getFlashMovie("tShirtViewer").sendTextToFlash(json);
	        		}
	        		catch(ex) {
	        			
	        		}

			
            // Swap product photos for the T-shirt viewer, if necessary
 
            // Send parameters to the flash via an external interface

            // Remove 'selected' class from any other color swatches
            $(self).parents('.colors').find('.selected').removeClass('selected');

            // Add 'selected' class to this swatch's containing list item
            $(self).parent().addClass('selected');

            // Click the underlying radio button, unclick all others
            $(self).parents(".colors").find("input").attr("disabled", true);
            $(self).find("input").attr("disabled", false);

            if (chooser = $('.product_info').data('chooser_obj')) chooser.update_details();


            return false;
        }).find('input').attr("disabled", true);
 
}        // If the T-shirt viewer is visible when the page first loads, then load up a preview right away
    });
        

})(jQuery);
