	window.youtubeVisible = false;
	window.currentLayout = 0;
	// Function to change color
	// Takes hex and which color to change (i.e bg, pri, sec, acc, txt)
	function changeColor(hex, sender) {
		// Save sender and holder
		var $sender = $("#" + sender);
		var $holder = $("#" + sender + "_holder");
		// Set colorpicker
		$sender.ColorPickerSetColor(hex);
		// Set bgcolor or picker
		$sender.css('background-color', '#' + hex);
		// Set title of picker and value of hidden input
		$sender.attr({title: hex});
		$holder.attr({value: hex});
		// Set css properties based on sender
		
		$('.'+$sender.attr("id")+'_bgco').css('background-color', '#' + hex);
		$('.'+$sender.attr("id")+'_bgco_ho:hover').css('background-color', '#' + hex);
  		$('.'+$sender.attr("id")+'_boco').css('border-color', '#' + hex);
  		$('.'+$sender.attr("id")+'_co').css('color', '#' + hex);
		$('.'+$sender.attr("id")+'_co_ho:hover').css('color', '#' + hex);
		
		initScrollPane('colors');
	};
	
	// Swtich layouts changes css href attribute
	// and makes other specific changes for each layout via js
    function switchLayout(sender,init,youtube) {
    	var palettesLeft = $("#palettes-tab").css("left");
    	var layoutID = "css/layout" + sender + ".css";
    	window.currentLayout = sender;
    	if (($("#layout-css").attr("href") != layoutID) || (init) || (youtube != "ignore")) {
    		$("#top-navigation").animate({height: "2000px"}, 1200, "easeInSine", function () {
    			if (youtube == "ignore") { $("#layout-changer ul li a").removeClass(); }
    			
    			$("#"+sender).addClass("active");
    			$("body").removeClass();
				$("body").addClass("layout"+sender).addClass('bg_bgco');
				toggleYoutube(youtube,sender);
				$("#layout-css").attr("href", layoutID);
				$("#layout_holder").attr("value", sender);
				
				// Special javascript instructions for each layout
    			switch (sender)
				{
				case "1":
					if (!init) {
						$("#info").css({"width" : "475px"}).parent().css({"width" : "505px","height":"278px"});
					} break;
  					
  				case "2":
  					if (!init) {
  						$("#info").css({"width" : "475px"}).parent().css({"width" : "505px","height":"278px"});
  					} break;
  				
  				case "3":
  					if (!init) {
  						$("#info").css({"width" : "475px"}).parent().css({"width" : "505px","height":"278px"});
  					} break;
  				
  				case "4":
  					if (!init) {
  						$("#info").css({"width" : "377px"}).parent().css({"width" : "407px","height":"278px"});
  					} break;
  					
  				case "5":
  					if (!init) {
  						$("#info").css({"width" : "470px"}).parent().css({"width" : "505px","height":"313px"});
  					} break;
  				}
  				
  				var showTimer = setTimeout('initScrollPane()', 1800);
    			return false;	
  			});
  		}
  	}
	
	function showCreator() {
		$("#top-navigation").animate({height: "100px"}, 1200, "easeInSine");
	}
	
	// Initialize scroll pane for css reloads    
    function initScrollPane(action) {
    	if (typeof action == "undefined") {
    		action = 'both';
  		}
    	if (action == 'js' || action == 'both') {
    		$("#info").jScrollPane();
    	}
    	if (action == 'colors' || action == 'both') {
  			$('#wrapper .jScrollPaneDrag').css('background-color', '#' + $("#sec_holder").attr("value"));
  			$('#wrapper .jScrollPaneTrack').css('background-color', '#' + $("#acc_holder").attr("value"));
  			if ($('#layout_holder').val() != "5") {
  				$('#wrapper .jScrollPaneContainer').css('border-color', '#' + $("#acc_holder").attr("value"));
  				$('#wrapper .jScrollPaneContainer').css('background-color', 'transparent');
  			} else {
  				$('#wrapper .jScrollPaneContainer').css('border-color', '#' + $("#acc_holder").attr("value"));
  				$('#wrapper .jScrollPaneContainer').css('background-color', '#' + $("#acc_holder").attr("value"));
  				$('.acc_bgco5').css('background-color', '#' + $("#acc_holder").attr("value"));
  			}
  		}
  		if (action == 'both') {
  			showCreator();
  		}
  		return false;
    }
    
    function toggleYoutube(toggle,sender) {
    	if (toggle == "off") {
    	    window.youtubeVisible = false;
    	    imageRotators(sender);	
    	} else if (toggle == "on") {
    	    window.youtubeVisible = true;
    	    $('#a-youtube span').text('Remove');
    	    $('#rotator1').css('height','0px');
		    $('#youtube').css('display','block');
		    $('#slider-list').css('display','none');	
    	} else if (toggle == "ignore" && !window.youtubeVisible) {
    		imageRotators(sender);
    	}
    	return false;
    }
    
    function imageRotators(sender) {
    	$('#a-youtube span').text('Add');
    	$('#youtube').css('display','none');
    	if (sender != "5") {
    		$('#slider-list').empty().css('display','none');
    		$('#rotator1').cycle({
	    	    fx:      'fade',
	    	    timeout: 5000,
	    	    pause:	  1,
	    	    speed:   1000,
	    	    easing:	 'easeOutQuart'
			});
    	} else {
    		$('#slider-list').empty().css('display','block');
    		$('.layout5 #rotator1').cycle({		
	    	    fx:      'scrollHorz',
	    	    timeout: 5000,
	    	    pause:	  1,
	    	    speed:   1000,
	    	    easing:	 'easeOutQuart',
	    	    pager:	 '#slider-list'   				
			});
			$(".layout5  #slider-list a").wrapAll(document.createElement("ul"));
			$(".layout5 #slider-list a").wrap(document.createElement("li"));
    	}
   	}
    
    
    // Switch tabs between picker and palettes
    function switchTabs($sender) {
    	if ($sender.hasClass("active") != true) {
			var tabID = "#" + $sender.attr("id") + "-tab";
			$("#color-menu li a.active").removeClass();
			$sender.addClass("active");
			if (tabID == "#palettes-tab") {
				$("#picker-tab").css("top", "120px");
				$("#color-changer .jScrollPaneContainer").css("top", "-44px");
				$("#color-changer-header").html("Choose a Color Palette");
				$("#add-color").animate({left: "-106px"}, 400, "easeInSine");
			} else {
				$("#picker-tab").css("top", "6px");
				$("#color-changer .jScrollPaneContainer").css("top", "120px");
				$("#color-changer-header").html("Customize Your Colors");
				$("#add-color").animate({left: "0px"}, 400, "easeInSine");
			}
		}
    };
    
    // Take each palette and take the colors out of html and set color and title
    // Also bind click event and set hidden input
    function createPalette(sender) {
    	var paletteString = "";
    	var $palette = $("#" + sender);
    	var $eachPaletteColor = $("#" + sender + " div");
    	$eachPaletteColor.each(function (i) {
			var color = $(this).html();
			var delimeter = ":";
			paletteString = paletteString + (color + delimeter);
			var $currentColor = $(this);
    		$currentColor.attr("title", color);
    		$currentColor.css("background-color", "#" + color);
    		$currentColor.html("");
		});	
		
		// Bind click event to each palette
		$palette.bind("click", function(e) {
			$eachColor = $("#" + $(this).attr("id") + " div");
			$eachColor.each(function (i) {
				changeColor($(this).attr("title"), $(this).attr("class"));
			});
    	});
    	
    	// Creates palettes string to hold all palettes
    	paletteString += "pal";
    	currentPalettes = $("#palettes_holder").attr("value") + paletteString;
    	$("#palettes_holder").attr("value", currentPalettes);
    };
    
    // Reinitializes palette scroller each time one is added
    function getPaletteWidth(newPalette) {
    	var palettes = $("#palettes-tab li").length;
    	var $palettesTab = $("#palettes-tab");
    	var width = (palettes * 55) - 3;
    	$("#palettes-ul").css("width", width);
    	$("#palettes-ul li.last").removeClass("last");
    	$("#palettes-ul li:last").addClass("last");
    	$palettesTab.jScrollHorizontalPane({scrollbarHeight:6, scrollbarMargin:0, reset:true, showArrows:true, arrowSize:27});
    	
    	
    	// Cache and bind arrows to function
    	$leftArrow = $("#color-changer a.jScrollArrowLeft");
    	$rightArrow = $("#color-changer a.jScrollArrowRight");
    	
    	$leftArrow.bind('mousedown', function(e) {
    		scrollPalettes('left', $palettesTab.css("left"), $palettesTab);
    	});
    	$rightArrow.bind('mousedown', function(e) {
    		scrollPalettes('right', $palettesTab.css("left"), $palettesTab);
    	});
    	
    	// If new palette was created, scroll to it	
    	if (newPalette) {
    		switchTabs($("#palettes"));
    		$("#palettes-tab")[0].scrollTo("#palettes-ul li:last");
    		$("#palettes-ul li:last").css("opacity", "0").animate({opacity: "1"}, 2500);
    	}
    };
    
    // Scroll palettes when arrow is clicked
    function scrollPalettes(direction, startingLeft, $scroller) {
    	if (direction == 'left') {
    		newLeft = parseInt(startingLeft) + 55;
    		if (newLeft > 0) {
    			newLeft = 0;
    		}
    	} else {
    		newLeft = parseInt(startingLeft) - 55;
    		rightEdge = ((parseInt($scroller.children().css("width")) - 271 -1) * -1);
    		if (newLeft < rightEdge) {
    			newLeft = rightEdge;
    		}
    	}
    	$scroller.animate({left: newLeft+"px"}, 200);
    };
    
    
    // Takes current colors and creates a palette
    function addPalette(bg, pri, sec, acc, txt) {
    	var currentPaletteNum = $("#palettes-tab li").length + 1;
    	var currentPalette = "palette" + currentPaletteNum;
    	$("#palettes-ul").append('<li><a id="'+currentPalette+'"><div class="bg">'+bg+'</div><div class="pri">'+pri+'</div><div class="sec">'+sec+'</div><div class="acc">'+acc+'</div><div class="txt">'+txt+'</div></a></li>');
    	createPalette(currentPalette);
    	getPaletteWidth(true);
    };

$(document).ready(function() {


	
	// Set up color pickers for each changer
	$('#bg').ColorPicker({onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
		onHide: function (colpkr) {$(colpkr).fadeOut(500);return false;},
		onChange: function (hsb, hex, rgb) {changeColor(hex, "bg");}});
	
	$('#pri').ColorPicker({onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
		onHide: function (colpkr) {$(colpkr).fadeOut(500);return false;},
		onChange: function (hsb, hex, rgb) {changeColor(hex, "pri");}});
		
	$('#sec').ColorPicker({onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
		onHide: function (colpkr) {$(colpkr).fadeOut(500);return false;},
		onChange: function (hsb, hex, rgb) {changeColor(hex, "sec");}});
		
	$('#acc').ColorPicker({onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
		onHide: function (colpkr) {$(colpkr).fadeOut(500);return false;},
		onChange: function (hsb, hex, rgb) {changeColor(hex, "acc");}});
		
	$('#txt').ColorPicker({onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
		onHide: function (colpkr) {$(colpkr).fadeOut(500);return false;},
		onChange: function (hsb, hex, rgb) {changeColor(hex, "txt");}});
	    
    // Change layout by replacing layout css link in head
    $("#layout-changer ul a").click(function () {
    	switchLayout($(this).attr("id"),false,"ignore");
    });
    
    $('#a-youtube').click(function() {
    	if (window.youtubeVisible) {
    		switchLayout(window.currentLayout,false,"off");
    	} else {
    		switchLayout(window.currentLayout,false,"on");
    	}	
    });
    
    // Switch tabs
    $("#palettes, #picker").click(function () {
    	switchTabs($(this));
    });

    // Adds current colors to palette using the values of the holders
    // Tried to make this function as smart as possible so it would only check
    // for duplicate palettes as far as it needed to
    $("#add-color").click(function () {
    	var paletteCreated = false;
    	// Goes through each palette
    	for (i=1;i<=$("#palettes-tab li").length;i++) {
    		// Init variables
    		sameColorCount = 0;
    		j = 1;
    		sameColor = true;
			do {
				if ($("#palette"+i+" div:nth-child("+j+")").attr("title") == $("#color-holder input:nth-child("+j+")").attr("value")) {
    				// If the color is the same 
    				// Add 1 to sameColorCount
    				// Keep checking
    				sameColorCount++;
    			} else {
    				// This palette is different
    				// Check next palette
    				sameColor = false;
    				if (i == $("#palettes-tab li").length) {
    				
    					// If palette is different and its the last palette, then add it
    					addPalette(	$("#bg_holder").attr("value"),$("#pri_holder").attr("value"),
    								$("#sec_holder").attr("value"),$("#acc_holder").attr("value"),$("#txt_holder").attr("value"));
    					paletteCreated = true;
    					break;
    				}
    			}
    			j++;
			} while ((j<=5) && (sameColor == true)) // Keep checking if same color is true
			
			// Dont check anymore li elements since current palette is the same as an existing palette
    		if ((sameColorCount == 5) && (!paletteCreated)) {
    			$("#palette-error").css("opacity", "1").html("This palette already exists.").animate({opacity: "0"}, 5000);
    			break;
    		}
    	}
    });
	
	// Populates hidden data fields when the save/buy dialog window is called
	var populateData = function(hash) {
		$("#hidden_fields input").each(function(i) {
			$current = $(this);
			var $sendTo = $("#saveForm #" + $current.attr("id") + "_form");
			$sendTo.attr("value", $current.attr("value"));
		});
		if (window.buyIsTrue) {
			$("#saveForm #save_button").css("display", "none");
			$("#saveForm h2").html("Buy Your Design");
		} else {
			var buttonText = $("#button_text_holder").attr("value");
			$("#saveForm h2").html(buttonText + " Your Design");
			$("#saveForm #save_button").attr("value", buttonText);
		}
		
	};
	
	// Save/update button
	$('#submit_design').click(function() {
		window.buyIsTrue = false;
		$('#save_dialog').jqmShow();
	});
	
	// Buy Button
	$('#buy_design').click(function() {
		window.buyIsTrue = true;
		$('#save_dialog').jqmShow();
	});
	
	function initialize() {
		
		// Create palettes from HTML
		$("#palettes-ul a").each(function (i) {
    		createPalette($(this).attr("id"));
    	});
		
		// get total width of palettes, false indicates this is on intitialization
		getPaletteWidth(false);
		
		// Initialize starting tab (#palettes or #picker)
		switchTabs($("#palettes"));
		
		// Switch to current layout set by hidden input
		switchLayout($("#layout_holder").attr("value"),true,"ignore");
		
		// Set colors according to hidden input values
		$("#color-holder input").each(function (i) {
			var currentColor = $(this).attr("value");
			var currentSender = $(this).attr("class");
			changeColor(currentColor, currentSender);
		});
		
		// Initialize save dialog for later
		$('#save_dialog').jqm({ajax:'save.php', modal:true, overlay: 80, onLoad:populateData});
	};
	
	initialize();
});