//On firefox, it seems like the code gets double-inited, so this solves that problem
var isInitialized = false;
var productsLoaded = false;
var lastPath = '';
var lastFile = '';
var superfluid;
var colors = [];
colors["0"] = '#BB0000';
colors["1"] = '#AA9900';
colors["2"] = '#00BB00';
colors["3"] = '#00BBBB';
colors["4"] = '#0000BB';
colors["5"] = '#990099';
colors["6"] = '#333333';
function initializeVisualizer() {
	var width = window.innerWidth;
	var height = window.innerHeight;
	var vizWidth = 640;
	var vizHeight = 480;
	if(width >= 1200 && height >= 700) {
		vizWidth = 800;
		vizHeight = 600;
	}
	superfluid = new SuperfluidFlash(vizWidth, vizHeight, this);
	superfluid.attach($('#superfluid'));
    var uploader = new qq.FileUploader({
        // pass the dom node (ex. $(selector)[0] for jQuery users)
        element: document.getElementById('file-uploader'),
        // path to server-side upload script
        action: '/visualizer/shared/upload/upload.php',
     // validation    
     // ex. ['jpg', 'jpeg', 'png', 'gif'] or []
     	allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],        
     // each file size limit in bytes
     // this option isn't supported in all browsers
     // set to true to output server response to console
     debug: false,
     // events     
     onComplete: function(id, fileName, responseJSON) {
    	 if(navigator.appName != 'Microsoft Internet Explorer') {
    		 $('#uploadImage').dialog("close");
    	 }
    	 else {
    		 $('#upload-image-sidebar').hide();
    		 $('#accordion-wrapper').show();
    	 }
    	var path = "/visualizer/shared/upload/" + responseJSON.fileName;
    	lastPath = path;
    	lastFile = responseJSON.fileName;
    	$('#photo-categories').val(t('My Photos'));
    	$('#visualizer').visualizer("loadPhoto", path);
     },
     messages: {
         // error messages, see qq.FileUploaderBasic for content            
     },
     showMessage: function(message){ alert(message); }
             
    });
    initializeHelp();
}

//Track the last product added
var lastProduct = null;

$.widget("ui.visualizer", {
    // Constants
    activeObject: null,
    loadedSampleImages: false,
    productsLoaded: false,
    firstModelLoaded: false,
    // Collections
    products: {},
    activeProducts: {},
    textures: {},
    objectAttributes: {},
    /*
     * Widget Initialization
     */
    _init: function(){
    	if(isInitialized) {
    		return;
    	}
    	isInitialized = true;
        this.setupSliderPanel();
        this.setupVisualizerUIEventListeners();
        if (this.options.markerPath) {
            $("#getMarker a").attr("href", this.options.markerPath);
        }
        if (this.options.showAddToCartLink) {
            $("#addAllToCart").css("visibility", "visible");
            $("#viewCart").css("visibility", "visible");
        }
        this.getSampleImages();
    },
    getClientName: function() {
    	return this.options.client;
    },
    getVisualizerData: function(){
    	if(!productsLoaded) {
    		this.getProducts();
    		this.getTextures();
    		productsLoaded = true;
    		$('#accordion').accordion("activate", 1);
    	}
    	else {
    		if(!$.objectIsEmpty(this.activeProducts)) {
    			$('#accordion').accordion("activate", 2);
    		}
    		else {
    			$('#accordion').accordion("activate", 1);
    		}
    	}
    },
    /*
     * Visualizer Methods
     */
    createInactiveState: function() {
    	this.nothingSelected();
    	$("#texture-prompt").text("Load a product to see its available textures");
    	$(".introText").show();
        $('#accordion').accordion("activate", 1);
    },
    nothingSelected: function() {
    	$(".currentActiveProduct").removeClass("currentActiveProduct");
    	$("#texture-prompt").text(t('Select a product to see its available configuration options'));
    	$("#texture-prompt").show();
    	$('#additional-options').hide();
    	this.disableSliders();
    	this.removeTextures();
    	$("#info").html("");
    },
    saveScreenshot: function() {
    	simulateModal(t("Your screenshot is being taken. Note that for high-resolution screenshots, this may take 30 or 40 seconds to complete. Please Wait..."));
    	if($("input:radio[name=resolution]:checked").val() == 'high') {
    		uploadScreenshotToServer(superfluid.takeHiResPhoto(), 
        		$('#visualizer').visualizer("getClientName")); 
        }
        else {
        	uploadScreenshotToServer(superfluid.takeLowResPhoto(), 
        		$('#visualizer').visualizer("getClientName"));
        	
        }
    },
    setupVisualizerUIEventListeners: function(){
        var _this = this;
        if(_this.options.dealerLocatorURL) {
        	$('#search-dealers').click(function() {
        		insertDealerInfo($('#dealer-zipcode').val(), 
        				_this.getClientName());
        	});
        };
        $("#imgLoadPhotos").click(function(){
            _this.uploadPhoto();
            return false;
        });
        $('#more-help').click(function() {
        	var helpPath = _this.options.helpImagePath; 
        	if(!helpPath) {
        		helpPath = '/visualizer/img/helpscreen.png';
        	}
        	$('#help-image').attr("src", helpPath);
        	$('#help').dialog("open");
        	return false;
        });
        // Selects a Sample Image
        $("#samplePhotos ul li a").live("click", function() {
        	var selected = $("#photo-categories").val();
        	var newBg = '';
        	if(selected != t('My Photos')) {
        		newBg = _this.options.sampleImagesPath + $(this).attr("id");
        	}
        	else newBg = $(this).attr("id");
            _this.loadPhoto(newBg);
            return false;
        });
        // Selects a Product and loads into Visualizer
        $("#products ul#productList>li a").live("click", function(){
            var productID = $(this).attr("id");
            //Add the object and get its
            if(productID != 'plane') {
            	simulateModal("Loading your selected product into the Visualizer");
            }
            _this.loadObject(productID);
            return false;
        });
        //Removes an Active Product from Visualizer
        $("#activeProducts ul li a.remove").live("click", function(){
            var objectId = $(this).parent().attr("id").substring(14);
            _this.removeActiveProduct(objectId);
            $(this).parent().hide("slow").remove();
        });
        //Add Active Product to Cart Button
        $("#activeProducts ul li a.addtocart").live("click", function(){
            var cartId = $(this).attr("id");
            var sku = $(this).children('img').attr('alt');
            $(this).find("img").attr("src", "/visualizer/img/add_to_cart-green.png");
            _this.addProductToCart(cartId, sku);
            return false;
        });
        $("#activeProducts ul li").live("click", function() {
        	var objectId = $(this).attr("id").substring(14);
        	if(_this.activeProducts) {
        		var product = _this.products[_this.activeProducts[objectId]];
        	}
        	//This gets invoked when the red X is clicked since it also
        	//tries to select the object to make it active.
        	if(!product) {
        		return;
        	}
        	superfluid.selectObject(objectId);
        });
        //Add All Products to Cart Button
        $("#addAllToCart").click(function() {
            _this.addAllActiveProductsToCart();
            return false;
        });
        // Load Texture from Swatch
        $("#textures .texture img").live("click", function(){
            _this.selectTexture($(this).parents("ul").attr("id"), $(this).attr("name"));
            return false;
        })
        $("#textures .texture img").live("hover", function(){
        	$('#texture-name').text($(this).attr("title")); 
            return false;
        })
        // Activate Contact Modal
        $("#contactTrigger").click(function(){
            $("#contact").dialog("open");
            return false;
        });
        // Activate Product Description Modal
        $("#productDescriptionTrigger").live("click", function(){
        	$("#productDescription").dialog("open");
            return false;
        });
        $('#viewCart').attr('href', _this.options.viewCartLink);
        $("#rotateInput").change(function(){
            _this.updateRotationFromInput();
        });
        $("#heightInput").change(function(){
            _this.updateHeightFromInput();
        });
        $("#photo-categories").change(function() {
        	$('#samplePhotos ul li').remove();
        	var selected = $("#photo-categories").val();
        	var photos = _this.sampleImages[selected];
            for (var i = 0; i < photos.length; i++) {
                var image = photos[i];
                if(selected != t('My Photos')) {
                	$("#samplePhotos ul").append('<li><a href="#" id="' + image.path + '"><img src="/visualizer/images/background-thumbs/' + image.path + '" /></a></li>');
                }
                else {
                	$("#samplePhotos ul").append('<li><a href="#" id="' + image.path + '"><img src="' + image.path + '"/></a></li>');
                }
            }
        });
        $('#save-screenshot-button').click(function() {
        	if(navigator.appName != 'Microsoft Internet Explorer') {
        		$('#save-and-share').dialog('close');
        	}
			_this.saveScreenshot();
		});
		$("#product-categories").change(function() {
        	var selected = $("#product-categories").val();
        	_this.updateProductList(selected);
        });
		$('#webcam-enabled').change(function() {
			if(this.checked) {
				superfluid.startCameraFeed();
			}
			else superfluid.stopCameraFeed();
		});
    },
    /*
     * Photo Methods
     */
    loadPhoto: function(img) {
    	simulateModal("Loading photo and identifying the Target...<br />This may take a moment.");
    	superfluid.analyzeImage(img)
    },
    uploadPhoto: function() {
    	if(navigator.appName != 'Microsoft Internet Explorer') {
    		$('#uploadImage').dialog("open");
    	}
    	else {
    		$('#accordion-wrapper').hide();
    		$('#upload-image-sidebar').show();
    	}		
    },
    getSampleImages: function() {
    	var _this = this;
    	$.ajax({
            url: _this.options.sampleImagesFeed,
            dataType: 'json',
            success: function(data){
                _this.sampleImages = data.categories;
                $.ajax({
                    url: '/visualizer/shared/upload/my_photos.php?action=retrieve',
                    dataType: 'json',
                    success: function(data){
                        _this.sampleImages[t('My Photos')] = data.photos;
                        for(category in _this.sampleImages) {
                            $('#photo-categories').
                            append($("<option></option>").
                            attr("value", category).text(t(category))); 
                        }
                        $('#photo-categories').change();
                    },
                    error: function() {
                    	
                    }
                });
                $('#accordion').accordion('resize');
            },
            error: function() {
            	console.log("Couldn't load sample photos");
            }
        });
    },
    addSamplePhoto: function(img) {
    	var newPhoto = new Object();
    	newPhoto.path = img;
    	this.sampleImages[t('My Photos')].push(newPhoto);
    },
    /*
     * Product Methods
     */
    getProducts: function(){
    	var _this = this;
        $.ajax({
            url: _this.options.productsFeed,
            dataType: 'json',
            success: function(data){
                _this.products = data;
                _this.loadDefaultProducts();
            },
            error: function(data, textStatus, errorThrown){
                console.log(errorThrown);
            },
            complete: function(){
                _this.loadProducts();
                // Set that Products are loaded
                _this.productsLoaded = true;
            }
        });
    },
    loadProducts: function() {
    	//Calculate the available rooms.
    	var allRooms = new Array();
    	for(var key in this.products) {
    		if(!this.products.hasOwnProperty(key)) {
    			continue;
    		}
    		var product = this.products[key];
    		var rooms = product.rooms;
    		for(var roomKey in rooms) {
    			if(!rooms.hasOwnProperty(roomKey)) {
        			continue;
        		}
    			var room = rooms[roomKey];
    			if($.inArray(room, allRooms) == -1) {
    				allRooms.push(room);
    			}
    		}
    	}
    	$.each(allRooms, function(index, value) { 
            $('#product-categories').
            append($("<option></option>").
            attr("value", value).
            text(value)); 
        });
        $('#product-categories').append($("<option></option>").attr("value", "Tools").text("Tools"));
    	$('#product-categories').change();
    },
    updateProductList: function(room) {
    	$('#products ul#productList li').remove();
    	if(room == 'Tools') {
    		$('#products ul#productList').append('<li class="productListing"><a href="#" id="plane"><img src="/visualizer/images/products/floor-4x4.jpg" alt="Surface Tool" title="Build a Surface"/></a></li>');
    	}
    	else {
        	var listingTemplate = $.template('<li class="productListing"><a href="#" id="${productID}"><img src="${thumbnailPath}" alt="${alt}" title="${title}"/></a></li>');
        	for (var i in this.products) {
            	var product = this.products[i];
            	if($.inArray(room, product.rooms) != -1) {
            		product.productAttributes = new Array();
            		$("#products ul#productList").append(listingTemplate, {
            			thumbnailPath: product.imageSrc,
            			productID: i,
            			title: product.title,
            			alt: product.title,
            			price: '$' + product.price
            		});
            	}
        	}
       	}
        $(".productListing img").hover(
        	function() {
        		$('#product-photo').html('<p class="productTitle">' + this.alt + '</p><p class="productThumb"><img src="' + this.src + '"/></p>');
        	}
        );
    	var alt = $(".productListing img").first().attr("alt");
    	var src = $(".productListing img").first().attr("src");
    	$('#product-photo').html('<p class="productTitle">' + alt + '</p><p class="productThumb"><img src="' + src + '"/></p>');
    },
    loadDefaultProducts: function(){
        var _this = this;
        var defaultProductIds = $.getUrlVar(this.options.defaultProductParam);
        if (defaultProductIds) {
            var productArray = defaultProductIds.split(",");
            if (productArray.length) {
            	for(product in productArray) {
                    _this.loadObject(decodeURIComponent(productArray[product]));
                    
            	}
            }
        }
    },
    addActiveProduct: function(objectID, productID) {
    	if(this.activeProducts[objectID]) {
    		if (!$.objectIsEmpty(this.activeProducts)) {
            	$(".introText").hide();
            }
    		this.updateActiveObject(objectID);
    		return;
    	}
    	this.activeProducts[objectID] = productID;
    	this.objectAttributes[objectID] = {};
        var activeProductTemplate;
        if(productID == 'plane') {
        	var template = $('<li id="activeProduct_${objectID}" class="activeProduct"><span class=\"product-title\">Custom Surface</span></li>');
        	$("#activeProducts .maxHeightWrapper ul").append(template);
        }
        else {
        	var product = this.products[productID];
        	var removeProductLink = '<a class="remove" href="#" id="${objectID}"><img src="/visualizer/img/active-products-remove-red.jpg" title="Remove Product" alt="Remove Product"/></a>';
        	var productPageLink = (this.options.showProductPageLink) ? '<a href="${productLink}" target="_blank" ><img src="/visualizer/img/go-to-product-page.png" title="Go To Product Page" alt="Go To Product Page"/></a>' : '';
        	var priceInfo = (this.options.showProductInfoPrice) ? '<span class="product-price">' + this.options.currency + product.price + "</span>" : '';
        	var addToCartLink = (this.options.showAddToCartLink) ? '<a class="addtocart" href="#" id="${cartId}"><img src="/visualizer/img/add_to_cart.png" title="Add to Cart" alt="Add to Cart"/></a>' : ''; 
        	var activeProductTemplate = $.template('<li id="activeProduct_${objectID}" class="activeProduct">' + removeProductLink + '<span class=\"product-title\">${title}</span>' + productPageLink + addToCartLink + priceInfo + '</li>');
        	$("#activeProducts .maxHeightWrapper ul").append(activeProductTemplate, {
            	objectID: objectID,
            	title: product.title,
            	cartId: objectID,
            	productLink: 'http://www.bringithome3d.com/products/' + product.handle
        	});
        	if (!$.objectIsEmpty(this.activeProducts)) {
        		$(".introText").hide();
        	}
        	this.updateActiveObject(objectID);
        	$("#activeProducts .maxHeightWrapper li:last img").tooltip({
            	showURL: false,
            	track: true
        	});
        }
        $('#accordion').accordion("activate", 2); 
        endModal();
    },
    removeActiveProduct: function(objectID) {
    	superfluid.removeModel(objectID); 
        delete this.activeProducts[objectID];
        // Show default instructions if there are no products loaded
        if ($.objectIsEmpty(this.activeProducts)) {
            this.createInactiveState();
        }
    },
    updateProductInfo: function(productID) {
        var product = this.products[productID];
        var infoTemplate = $.template('<span class="title">${title}</span><table><tr class="price"><td class="key">Price:</td><td>${price}</td></tr><tr class="vendor"><td class="key">Vendor:</td><td>${vendor}</td></tr></table><p><a id="productDescriptionTrigger" href="#"><img src="/visualizer/img/view-product-description.jpg"></a>');
        
        $("#info").html(infoTemplate, {
            title: product.title,
            price: this.options.currency + product.price,
            vendor: product.vendor
        })        
        if (!this.options.showProductInfoTitle) {
            $("#info .title").hide();
        }
        if (!this.options.showProductInfoPrice) {
            $("#info .price").hide();
        }
        if (!this.options.showProductInfoVendor) {
            $("#info .vendor").hide();
        }
        if (!this.options.showProductInfoDescription) {
            $("#productDescriptionTrigger").hide();
        }
        else {
            $("#productDescription-content").html(product.description);
        }        
    },
    /*
     * Loaded Object Methods
     */
    loadObject: function(productID) {
    	if(productID == 'plane') {
    		lastProduct = 'plane';
    		superfluid.toggleTool('polygon_plane');
    		
    	}
    	else {
    		var product = this.products[productID];
        	lastProduct = productID;
        	superfluid.loadModel("http://" + window.location.hostname + product.modelFolder + product.modelName);
        }
    },
    updateActiveObject: function(objectID) {
        this.activeObject = objectID;
        this.updateTextures(this.activeProducts[objectID], objectID);
        $(".currentActiveProduct").removeClass("currentActiveProduct");
        $("#activeProduct_" + objectID).addClass("currentActiveProduct");
        this.enableSliders();
        //this.updateRotation(objectID);
        //this.updateHeight(objectID);
        this.updateProductInfo(this.activeProducts[objectID]);
    },
    /*
     * Texture Methods
     */
    getTextures: function(){
    	var visualizer = this;
        $.ajax({
            url: visualizer.options.texturesFeed,
            dataType: 'json',
            success: function(data){
                visualizer.textures = data.textures;
            },
            error: function(data, textStatus, errorThrown) { 
            	console.error(errorThrown);
            }
        });
        return false;
    },
    updateTextures: function(productID, objectID) {
    	this.removeTextures();
    	$('#additional-options').hide();
    	var product = this.products[productID];
    	if(product.productType == 'textures' || product.productType  =='both') {
    		var textureTemplate = $.template('<li class="texture"><img id="${largeSrc}" name="${textureID}" src="${thumbSrc}" title="${alt}" alt="${alt}"/></li>');
    		var texturesGroups = this.textures.mappings[productID];
            if (texturesGroups) {
            	for(textureGroupID in texturesGroups) {
            		var textureGroup = texturesGroups[textureGroupID];
            		for(var j = 0; j < this.textures['texture-groups'].length; j++) {
            			if(textureGroup == this.textures['texture-groups'][j].region) {
            				var textureTypes = this.textures['texture-groups'][j];
            				// Load Texture Swatches
            				var textures = textureTypes.options;
            				$("#textures .maxHeightWrapper").append('<div class="textureGroup"><h3>' + textureTypes.name + '</h3><ul id="' + j + '"></ul></div>');
            				for (var i = 0; i < textures.length; i++) {
            					var texture = textures[i];
            					$("ul#" + j).append(textureTemplate, {
            						largeSrc: this.options.textureLargePath + texture.imgPath,
            						thumbSrc: this.options.textureThumbPath + texture.imgPath,
            						alt: texture.title,
            						textureID: i
            					});
            				}
            			}
            		}
            	}
            }
            else {
            	// Load text if there are no texture swatches
            	$("#textures .maxHeightWrapper").append('<div class="textureGroup"><p>' + t('This Product has no textures') + '</p></div>');
            }
            $("#textureGroup").show();
    	}
    	if(product.productType == 'options' || product.productType == 'both') {
    		$('#texture-title').text('Options');
    		var options = product.options;
    		var options_defaults = product.options_defaults;
    		$('#additional-options').show();
    		$('#additional-options').children().each(function() { $(this).remove() });
    		$('#additional-options').text('');
    		var viz = this;
    		var counter = 0;
    		$.each(options, function(i, n) {
    			var optionName = i.replace(" ", "-");
    			$("#additional-options").append("<span class=\"option-text\">" + i  + "</span><a href=\"#\" id=\"" + optionName + "Trigger\"><img src=\"/visualizer/img/icon-help-tiny.png\"></a>");
    			$("#additional-options").append("<select class=\"product-option\" id=\"" + counter + "\"></select><br>");
    			for(var j = 0; j < n.length; j++) {
    				var option = "<option value=\"" + n[j] + "\"";
    				if(n[j] == options_defaults[i]) {
    					option += " selected=\"selected\"";
    				}
    				option += ">" + n[j] + "</option>";
    				$("#additional-options #" + counter).append(option);
    			}
    			if(viz.objectAttributes[objectID][counter]) {
    				$("#additional-options #" + counter).val(viz.objectAttributes[objectID][counter]);
    			}
    			$('#additional-options #' + optionName + 'Trigger').click(function() {
    				$('#attributeDescription-content').html(product.options_descriptions[optionName].description);
    				$('#attributeDescription-photo').html('<img src="' + product.options_descriptions[optionName].image + '">');
    				$('#attributeDescription-name').html(product.options_descriptions[optionName].name);
    				$("#attributeDescription").dialog("open");
    			});
    			counter++;
    		});
    		//Store the selected value whenever it is changed
    		$('#additional-options select').change(function() { 
    			viz.objectAttributes[objectID][parseInt($(this).attr("id"))] = $(this).children("option:selected").text();
    			var product = viz.products[productID];
    	        var queryString = "?product=" + encodeURIComponent(product.title) + "&fixture=" +
    	        	encodeURIComponent($('#0 option:selected').text()) +
    	        	"&height=" + encodeURIComponent($('#1 option:selected').text()) +
    	        	"&length=" + encodeURIComponent($('#2 option:selected').text()) +
    	        	"&quick_adjust=" + encodeURIComponent($('#3 option:selected').text()) +
    	        	"&ladder=" + encodeURIComponent($('#4 option:selected').text());
    			$.ajax({
    	        	url: '/visualizer/turnstangen/product_lookup.php' + queryString,
    	        	dataType: 'json',
    	        	success: function(data) {
    	        		if(data['model_folder']) {
    	        			simulateModal("Updating Model...");
    	        			ExecuteCommand("replaceFurniture'" + "http://" + window.location.hostname + data['model_folder'] + "'" + data['model_name'] + "'");
    	        			$('#activeProducts .currentActiveProduct img').attr('alt', data['sku']);
    	        			var product = viz.products[productID];
    	        			product.price = data['price'];
    	        			product.product_id = data['model_name'].substring(1, 3);
    	        			viz.updateProductInfo(productID);
    	        			$('.currentActiveProduct .product-price').text(viz.options.currency + product.price);
    	        		}
    	        	}
    			});
    		});
    	}
        //IE6 fix for layout
        $("#textures .maxHeightWrapper div:first").css("marginLeft", "0");
    },
    removeTextures: function(){
        $("#textures .textureGroup").remove();
    },
    selectTexture: function(region, textureID){
    	var realRegion = this.textures['texture-groups'][region]; 
    	var texture = realRegion.options[textureID];
    	superfluid.setTexture("http://" + window.location.hostname + texture.texturePath + texture.textureName, realRegion.region);
    },
    /*
     * Cart Methods
     */
    addProductToCart: function(objectID, sku) {
    	var visualizer = this;
    	var productID = this.activeProducts[objectID];
    	var product = this.products[productID];
    	$.ajax({
    		dataType : 'json',
    		url: '/visualizer/fb/add_to_cart.php?client=' + visualizer.getClientName() + "&sku=" +
    		sku + "&product_id=" + product.product_id,
        	success: function(data) {
            	if(navigator.appName != 'Microsoft Internet Explorer') {
            		$('#rightcol').append('<iframe width="0" src="' + data.url + '">');
            	}
            	else window.open(data.url);
        	},
        	error: function(data, textStatus, errorThrown) {
        		//alert("Error: " + errorThrown);
        	}
    	});
        //this.sendToCart(cartIds);
    },
    addAllActiveProductsToCart: function(){
        var visualizer = this;
        // Get All Active Product Cart Ids
        $("#activeProducts ul li a.addtocart").each(function(index, el) {
        	$(el).find("img").attr("src", "/visualizer/img/add_to_cart-green.png");
        	visualizer.addProductToCart($(el).attr("id"), $(el).attr("alt"));
        })
    },
    /*
     * Slider Methods
     */
    setupSliderPanel: function(){
        var visualizer = this;
        //Initialize Rotation Slider
        $("#rotate").slider({
            value: 0,
            min: 0,
            max: 359,
            slide: function(event, ui){
                visualizer.rotateObject(ui.value);
                $("#rotateInput").attr("value", ui.value);
            }
        });
        $("#height").slider({
            value: 0,
            min: -100,
            max: 100,
            slide: function(event, ui){
                visualizer.adjustHeight(ui.value);
                $("#heightInput").attr("value", ui.value);
            }
        });
        // Set Initial Sliders to disabled
        this.disableSliders();
    },
    resetSliders: function(){
    	/*$('#rotate').spinner("value", 0);
    	$("#height").spinner("value", 0);
    	*/
    	$("#rotate").slider('option', 'value', 0);
    	$("#height").slider('option', 'value', 0);
    },
    enableSliders: function() {
    	$("#rotateInput").removeAttr("disabled");
    	$("#heightInput").removeAttr("disabled");
    	$("#rotate").slider('enable');
        $("#height").slider('enable');
    },
    disableSliders: function() {
    	$("#rotateInput").attr("disabled", "disabled");
    	$("#heightInput").attr("disabled", "disabled");
        $("#rotate").slider('disable');
        $("#height").slider('disable');
    },
	rotateObject: function(val) {
    	 superfluid.rotateToAngle(val);
    },
    updateRotationFromInput: function() {
    	var rotationValue = $("#rotateInput").val();
    	$("#rotate").slider('option', 'value', rotationValue);
        this.rotateObject(rotationValue);
    },
	adjustHeight: function(val) {
    	superfluid.setHeight(val); 
    },
    updateHeightFromInput: function(){
        var heightValue = $("#heightInput").val();
        $("#height").slider('option', 'value', heightValue);
        this.adjustHeight(heightValue);
    }
});

$.extend($.ui.visualizer, {
    defaults: {
		client: null,
        defaultProductParam: 'sku',
        encryptVisualizer: true,
        showProductPageLink: false,
        showAddToCartLink: false,
        markerPath: null,
        sampleImagesPath: null,
        sampleImagesFeed: null,
        productsFeed: null,
        texturesFeed: null,
        textureLargePath: null,
        textureThumbPath: null,
        cartPath: null,
        contactEmail: null,
        contactForm: false,
        showHelpIcon: true,
        showProductInfoTitle: true,
        showProductInfoPrice: true,
        showProductInfoVendor: true,
        showProductInfoDescription: true
    }
})
/*
 * Utilities
 */
$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        if (window.location.href.indexOf('?') != -1) {
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    },
    objectIsEmpty: function(obj){
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                return false;
            }
        }
        return true;
    }
});

function simulateModal(text) {
	if(navigator.appName == 'Microsoft Internet Explorer') {
		$('#page-wrapper').block({centerY: 0, css: {top: '570px', width: '320px', backgroundColor: '#ddd', padding: '10px'}, message: '<div id="overlay"><div id="overlay-left"><span id="overlay-text">' + t(text) + 
			'</span></div></div>'});
	}
	else {
		document.getElementById('superfluid').style.top = "-1000px";
		$('#page-wrapper').block({css: {width: '320px', backgroundColor: '#ddd', padding: '10px'}, message: '<div id="overlay"><div id="overlay-left"><span id="overlay-text">' + t(text) + 
		'</span></div></div>'});
	}
}

function endModal() {
	$('#page-wrapper').unblock();
	if(navigator.appName != 'Microsoft Internet Explorer') {
		document.getElementById('superfluid').style.top  = "0px";
	}
	window.focus();
}

function surfacesChanged(surfaces) {
	endModal();
	//Check if this is actually a new file upload, or just an ID for an existing photo
	if($('#photo-categories').val() == t('My Photos') && lastFile != '') {
    	$.ajax({
            url: '/visualizer/shared/upload/my_photos.php?action=store&filename=' + 
            	encodeURIComponent(lastFile) + '&path=' + encodeURIComponent(lastPath),
            dataType: 'json'
    	});
    	$('#visualizer').visualizer('addSamplePhoto', lastPath);
    	lastFile = '';
	}
	//Trigger the change event to rebuild the photo list
	$('#photo-categories').change();
	$('#visualizer').visualizer("getVisualizerData");
	$('.picker').remove();
	for(var i = 0; i < surfaces.length; i++) {
		var picker = $('<div class="picker"/>'); 
		picker.css("background-color", colors[surfaces[i]]);
		picker.attr("id", surfaces[i]);
		picker.click(function() {
			superfluid.activateSurface($(this).attr("id"));
		});
		$('#plane-picker').append(picker);
    }
}

function photoRecognitionFailed() {
	endModal();
	$('#failed-id').dialog("open");	
}

function error(error) {
	console.log(error);
}

function modelLoaded(id) {
	$('#visualizer').visualizer("addActiveProduct", id, lastProduct);
}

function rotationAngleChanged(angle) {
	$("#rotate").slider("option", "value", Math.round(parseFloat(arguments[0])));
	$("#rotateInput").attr("value", Math.round(parseFloat(arguments[0])));
}

function heightChanged(height) {
	$("#height").slider("option", "value", Math.round(parseFloat(arguments[0])));
	$("#heightInput").attr("value", Math.round(parseFloat(arguments[0])));
}

function objectSelected(id) {
	$("#visualizer").visualizer("updateActiveObject", id);
}

function nothingPicked() {
	$("#visualizer").visualizer("nothingSelected");
}

function visualizerMessage(msg) {
	alert(msg);
}
(function($){
    /**
     * Extend JQuery UI dialog to show or hide visualizer when opening.
     **/
    $.fn.extend($.ui.dialog.prototype, {
        _original_open: $.ui.dialog.prototype.open,
        _original_close: $.ui.dialog.prototype.close,
        open: function(){
            this._original_open();
            document.getElementById('superfluid').style.top = "-10000px";
        },
        close: function(){
            this._original_close();
            document.getElementById('superfluid').style.top = "0px";
        }
    });
})(jQuery);
