/* color: set to the first visible color when the popup is loaded
* if user clicks a swatch to change the background color, the color is updated.
* color is used to set the dropdown menu option for "background color" when user
* chooses a graphic
* persBGHeight: the height of each background color in all-colors-2c.png
* 
* COMPRESSION: GO TO
* - http://www.javascriptobfuscator.com/Default.aspx
* - encode strings
* - encode numbers
* - replace names
*/



function changeBG( multiplier, color, fontColor, shape ) {
	changeBGImage( '', shape );
} /* function changeBG( multiplier, color, shape ) {*/
function setNames() {
	jQuery(".fashioncraft-content .names").html( jQuery(".fashioncraft-content #name").val() );
}
function setDates() {
	jQuery(".fashioncraft-content .dates").html( jQuery(".fashioncraft-content #date").val() );
}
function in_array( what, where ){
	/* this returns true or false ONLY*/
	var a=false;
	for(var i=0;i<where.length;i++){
		if(what == where[i]){
			a=true;
			break;
		}
	}
	return a;
}  /*function in_array( what, where ){*/
function updateFontColor( fileName ){
	/* background has changed. make sure font color is correct */
	var darkBackgrounds = new Array(); /* these all need a white font*/
	darkBackgrounds[0] = "peacock.png";
	darkBackgrounds[1] = "hot-pink.png";
	darkBackgrounds[2] = "garden-green.png";
	darkBackgrounds[3] = "plum.png";
	darkBackgrounds[4] = "marine.png";
	darkBackgrounds[5] = "apricot.png";
	darkBackgrounds[6] = "mocha.png";
	darkBackgrounds[7] = "brick.png";
	darkBackgrounds[8] = "midnight.png";
	darkBackgrounds[9] = "golden-jewel.png";
	var fontColor = in_array( fileName, darkBackgrounds ) ? "#fff" : "#000";
	jQuery(".fashioncraft-content .names").css({ 'color' : fontColor });
	jQuery(".fashioncraft-content .dates").css({ 'color' : fontColor });
}
function changeBGImage( href, shape ) {
	/* change the background image to whatever was clicked
	* this is the new, cool way
	* first figure out what was clicked*/
	if ( !shape ) {
		var fileName = href.split( "\/" );
		fileName = fileName[fileName.length-1];
		/*get the current shape and text settings*/
		var shape = jQuery(".fashioncraft-content #varHolders p.currentShape").html() ? jQuery(".fashioncraft-content #varHolders p.currentShape").html().toLowerCase() : "circle";
		var text = jQuery(".fashioncraft-content #varHolders p.showTextInput").html() ? "noText" : "text";
		var path = jQuery(".fashioncraft-content #varHolders p.advanced").html() ? "//" + document.domain + "/fashioncraft-jars/backgrounds/" : "//www.fashioncraft.com/images/personalized/backgrounds/";
		path += shape + "/" + text + "/" + fileName;
		/*//jQuery("body").append("<br>filename = " + path);*/
		jQuery('.fashioncraft-content #bgColorPrint,.fashioncraft-content .currentColor').html( capWords(fileName.replace( /-/g, " " ).replace( /\.png/, "" )) );
		if ( jQuery(".fashioncraft-content #varHolders p.showTextInput").html() ) {
			/* make sure font color is accurate*/
			updateFontColor( fileName );
		}
	} else {
		var path = jQuery('.fashioncraft-content .personalizedGraphic').css('background-image');
		/*//jQuery("body").append("<br>changing shape to " + shape + "<br>Path = " + path);*/
		if ( shape == "circle" && jQuery(".fashioncraft-content #varHolders p.currentShape").html() != "circle" ) {
			path = path.replace( "diamond", "circle" );
			jQuery('.fashioncraft-content #currentShape, .fashioncraft-content #varHolders p.currentShape').html("Circle");
			// replace the path in each .personalizedGraphic from /diamond/ to /circle/
			jQuery(".fashioncraft-content .personalizedGraphic a img").each(function(){
				jQuery(this).attr({
					"src": jQuery(this).attr("src").replace( /\/diamond\//g, "/circle/" )
				});
			});
			//jQuery(".personalizedGraphic").css({ "margin" : "23px" });
		} else if ( shape == "diamond" && jQuery(".fashioncraft-content #varHolders p.currentShape").html() != "diamond" ) {
			path = path.replace( "circle", "diamond" );
			jQuery('.fashioncraft-content #currentShape,.fashioncraft-content #varHolders p.currentShape').html("Diamond");
			jQuery(".fashioncraft-content .personalizedGraphic a img").each(function(){
				jQuery(this).attr({
					"src": jQuery(this).attr("src").replace( /\/circle\//g, "/diamond/" )
				});
			});
			//jQuery(".personalizedGraphic").css({ "margin" : "0px" });
		}
		path = path.replace( "(", "" ).replace( ")", "" ).replace( "url", "" );
		/*//jQuery("body").append("<br>filename = " + path);*/
	}
	jQuery('.fashioncraft-content .personalizedGraphic').css({
		'background-image' : 'url(' + path + ')'
	});
}

function chooseColorShapeGraphic( color, shape, graphic, colorID, shapeID, graphicID, nameID, dateID ) {
	/* this is used for tags and jars, meaning shapeID may or may not exist
	* test for that before trying to set the value */
	 //jQuery("body").append("<br>choosing...");
	jQuery("#" + graphicID + " option").each(function(i){
		if ( cleanText(jQuery(this).html()) == cleanText(graphic) ) {
			jQuery(this).attr( "selected", "selected" ); /* select the right option*/
		} else {
			jQuery(this).removeAttr( "selected" ); /* deselect the current option*/
		}
	});
	 //jQuery("body").append("<br>chose graphic...");

	/* color*/
	jQuery("#" + colorID + " option").each(function(i){
		/*alert( "val: " + jQuery(this).val() + "\r\nhtml: " + jQuery(this).html() );*/
		if ( cleanText(jQuery(this).html()) == cleanText(color) ) {
			jQuery(this).attr( "selected", "selected" ); /* select the right option*/
			/*jQuery("#graphic").val( jQuery(this).val() ); // this works too*/
		} else {
			jQuery(this).removeAttr( "selected" ); /* deselect the current option*/
		}
	});
	 //jQuery("body").append("<br>chose color...");
	
	/* shape*/
	if ( jQuery("#" + shapeID).length ) {
		//jQuery("body").append("<br>choosing shape");
		jQuery("#" + shapeID + " option").each(function(i){
			/*alert( "val: " + jQuery(this).val() + "\r\nhtml: " + jQuery(this).html() );*/
			if ( cleanText(jQuery(this).html()) == cleanText(shape) ) {
				jQuery(this).attr( "selected", "selected" ); /* select the right option*/
				/*jQuery("#graphic").val( jQuery(this).val() ); // this works too*/
			} else {
				jQuery(this).removeAttr( "selected" ); /* deselect the current option*/
			}
		});
	}
	//jQuery("body").append("<br>chose shape...");

	/* name and date*/
	if ( nameID ) {
		// in the future we may allow names and dates to be entered as well
		if ( jQuery("#" + nameID).length ) {
			jQuery("#" + nameID).val( jQuery("#name").val() );
			jQuery("#" + dateID).val( jQuery("#date").val() );
		}
	}
	
	/* close the popup*/
	if ( typeof tb_remove == "function" ) {
		tb_remove(); 
	}
	//jQuery("body").append("<br>done choosing");
} /*function chooseColorShapeGraphic( color, shape, graphic, colorID, shapeID, graphicID ) {*/


function runCSS(){
	var path = document.domain == "www.fashioncraft.com" ? "//www.fashioncraft.com/images/personalized/" : "//" + document.domain + "/fashioncraft-jars/";
	jQuery(".fashioncraft-content a").css({ "background" : "none" });
	jQuery(".fashioncraft-content, .fashioncraft-content p").css({
		"margin" : "0px",
		"padding" : "0px"
	});
	jQuery(".fashioncraft-content .names,.fashioncraft-content .dates").css({
		"font-size" : "12px",
		"height" : "12px",
		"overflow" : "hidden",
		"text-align" : "center",
		"font-family" : "Arial, Helvetica, sans-serif",
		"position" : "absolute",
		"width" : "154px",
		"left" : "0px"
	}); /* we have to put the left value cause IE sucks */
	jQuery(".fashioncraft-content .names").css({ "top" : "88px" });
	jQuery(".fashioncraft-content .dates").css({ "top" : "101px" }); /* names + line height(12) + 1 (buffer) */
	jQuery(".fashioncraft-content .personalizedGraphic").css({ "position" : "relative" });
	jQuery(".fashioncraft-content #varHolders").css({ 	"display" : "none", "float" : "right" });
	jQuery('.fashioncraft-content p > a > img').css({
		'border' : 'none',
		'padding-left' : '2px',
		'padding-right' : '2px',
		'border-left' : '1px dotted #000000',
		'margin-bottom' : '4px'
	});
	jQuery('.fashioncraft-content p#swatches > a > img:first,.fashioncraft-content p.showShapes > a > img:first').css({
		'border-left' : 'none'
	});
	/*
	* can't use this cause IE 6 and 7 suck
	jQuery('a + a > img').css({
		'border-left' : '1px dotted #000000',
	});
	*/

	var text = jQuery(".fashioncraft-content #varHolders p.showTextInput").html() ? "noText" : "text";
	var shape = jQuery(".fashioncraft-content #varHolders p.currentShape").html() ? jQuery(".fashioncraft-content #varHolders p.currentShape").html().toLowerCase() : "circle";
	var color = jQuery(".fashioncraft-content #varHolders p.currentColor").html() ? jQuery(".fashioncraft-content #varHolders p.currentColor").html().toLowerCase().replace( / /g, "-" ) : "baby-blue";
	jQuery('.fashioncraft-content .personalizedGraphic').css({
		'background-image' : 'url(' + path + 'backgrounds/' + shape + '/' + text + '/' + color + '.png)',
		'background-position' : 'center',
		'background-repeat' : 'no-repeat',
		'float' : 'left',
		'border' : '1px solid #CEEBF9',
		'margin' : '3px'
	});
	jQuery(".fashioncraft-content .personalizedGraphic").css({
		"height" : "166px",
		"width" : "166px"
	});
	jQuery('.fashioncraft-content .personalizedGraphic a img').css({
							/*'height' : '110px',
							'width' : '110px',*/
							'height' : '57px', /* -53 / 2 = 26 / 27*/
							'width' : '84px', /* -26 / 2 = 13 */
							/*'margin' : '8px 21px 50px 21px'*/
							/*'margin' : '28px 0px 0px 28px',*/
							/*'margin' : '35px 0px 0px 41px',*/
							'padding' : '35px 41px 55px 41px'
	});
	jQuery('.fashioncraft-content .personalizedGraphic a img').css({ 'border' : 'none' });
} /*function runCSS(){*/

function preloadBackgrounds() {
	jQuery(".fashioncraft-content #swatches a").each(function(){
		jQuery("<img>").attr("src", jQuery(this).attr("href"));
	});
}

function preloadBackground( href ) {
	/* href will always point to the circle image
	* but maybe they switched to diamond
	* if so we need to change the 'circle' to 'diamond'
	* figure it out and do it */
	if ( jQuery(".fashioncraft-content #varHolders p.currentShape").html().toLowerCase() == "diamond" ) {
		href = href.replace( /circle/, "diamond" );
	}
	jQuery("<img>").attr("src", href );
}

function capWords(str){
	/* modified from the handy code at
	* http://www.java2s.com/Code/JavaScript/Language-Basics/CapitalizingtheFirstLetterinEachWordofaString.htm
	* now returns the value instead of printing it */
	var words = str.split(" "); 
	for (var i=0 ; i < words.length ; i++){ 
		words[i] = words[i].substr(0,1).toUpperCase() + words[i].substr(1, words[i].length-1); 
	}
	return words.join(" ");
}

function cleanText( text ) {
	return text.replace( / /g, "" ).replace( /-/g, "" ).replace( /%20/g, "" ).toLowerCase();	
}

function handleGraphicClick(element){
	//jQuery("body").append("<br>handling graphic click");
	var imageName = jQuery(element).html().split( ".png", 2 )[0].split( "graphics/", 2 )[1]; /*pull name from file name*/
	var graphic = imageName;
	imageName = imageName.replace(/\-/g, " " ); /*replace dashes with spaces to make it look nicer*/
	var color = String( jQuery(".fashioncraft-content #varHolders p.currentColor").html() );
	var shape = String( jQuery(".fashioncraft-content #varHolders p.currentShape").html() );
	var popupType = String( jQuery(".fashioncraft-content #varHolders p.popupType").html() );
	var advanced = jQuery(".fashioncraft-content #varHolders p.advanced").html();
	var embed = jQuery(".fashioncraft-content #varHolders p.embed").html();
	if ( advanced && embed ) {
		// ... we are embedded! do nothing because this will never happen!
	} else if ( advanced ) {
		/*not embedded but still advanced mode (via site owner's server instead of link)*/
		//jQuery("body").append("<br>advanced mode choosing options");
		chooseColorShapeGraphic( color, shape, graphic, "color", "tagShape", "graphic" );
		//jQuery("body").append("<br>advanced mode done choosing options");
	} else {
		/*not embedded or advanced, just display which graphic was clicked*/
		jQuery('.fashioncraft-content #currentGraphic').html( capWords(imageName).replace( /Circle\//g, "").replace( /Diamond\//g, "" ) );
	} /*if ( advanced && embed ) {*/	
	
} // function handleGraphicClick(element){
	
function makeTabs(){
	jQuery(".fashioncraft-content #fashioncraftGraphics").tabs({
		cache: true,
		spinner: 'Loading...',
		load: function(event, ui) {
			runCSS();
			if ( jQuery(".fashioncraft-content #varHolders p.showTextInput").html() ) {
				setNames();
				setDates();
				updateFontColor( jQuery('.fashioncraft-content #varHolders p.currentColor').html().toLowerCase().replace( / /g, "-" ) + ".png" );
			}
		}
	});
	jQuery(".fashioncraft-content .ui-tabs-panel").css({ 'height' : '325px', 'overflow' : 'scroll', 'position' : 'relative' });
	
}
jQuery(document).ready(function(){
	/*************** CSS **************************************/
	runCSS();
	/************ END CSS **************************************/
	//jQuery("body").append("<br>ran css");
	
	var showTextInput = jQuery(".fashioncraft-content #varHolders p.showTextInput").html();
	var advanced = jQuery(".fashioncraft-content #varHolders p.advanced").html();
	var embed = jQuery(".fashioncraft-content #varHolders p.embed").html();
	var showDebug = jQuery(".fashioncraft-content #varHolders p.showDebug").html();
	
	if ( showTextInput != "null" && showTextInput != "undefined" && showTextInput != "0" && showTextInput != "" ) {
		showTextInput = 1;
	} else {
		showTextInput = 0;
	}
	if ( showTextInput ) {
		jQuery(".fashioncraft-content #name").keyup( setNames ); /* it doesn't fire on 'change' event until mouse moves out of box.. autofill menus NEVER fire..*/
		jQuery(".fashioncraft-content #date").change( setDates );
		jQuery(".fashioncraft-content #date").datepicker({
			dateFormat: 'mm-dd-y'
		});
		jQuery(".fashioncraft-content #ui-datepicker_div, .fashioncraft-content .ui-datepicker").css( "z-index", "9999" );
	}
	//jQuery("body").append("<br>done handling text inputs");
	/* 
	* JQUI stylesheet must be included when:
	* - in advanced mode and we're showing text inputs and it is NOT already loaded
	* loading the stylesheet at other times will break the datepicker in IE7
	*/
	var color="Baby Blue";
	var persBGHeight = 166;
	var offsetCirclewSample = 21;
	var offsetCirclenSample = -113;
	var offsetDiamondwSample = -270;
	var offsetDiamondnSample = -436;
	jQuery(".fashioncraft-content #varHolders p.persBGHeight").html( persBGHeight );
	jQuery(".fashioncraft-content #varHolders p.offsetCirclewSample").html( offsetCirclewSample );
	jQuery(".fashioncraft-content #varHolders p.offsetCirclenSample").html( offsetCirclenSample );
	jQuery(".fashioncraft-content #varHolders p.offsetDiamondwSample").html( offsetDiamondwSample );
	jQuery(".fashioncraft-content #varHolders p.offsetDiamondnSample").html( offsetDiamondnSample );
	var offset = showTextInput ? offsetCirclenSample : offsetCirclewSample;
	jQuery(".fashioncraft-content #varHolders p.offset").html( offset );
	//jQuery("body").append("<br>done reviewing offsets");
	
	jQuery(".fashioncraft-content #swatches a").click(function(event){
		event.preventDefault();
		changeBGImage( jQuery(this).attr("href") );
		return false;
	});
	//jQuery("body").append("<br>going to load jqui soon");
	jQuery(document).ready(function() {
		var JQVersion = Number(jQuery().jquery.replace( /\./g, "" ) );
		var JQ132 = Number("1.3.2".replace( /\./g, "" ) );
		if ( jQuery(".fashioncraft-content #fashioncraftGraphics").length ) {
			//alert("making tabs");
			if ( !jQuery().tabs ) {
				// JQUI isn't loaded. figure out what version of jquery we're on, then load the appropriate jqui
				if ( JQVersion < JQ132 ) {
					// load old version
					//jQuery("body").append("<br>loading old jqui, jquery version = " + jQuery().jquery);
					jQuery.getScript( "//ajax.googleapis.com/ajax/libs/jqueryui/1.6/jquery-ui.min.js",function(){
						jQuery("head").append( "<link type='text/css' rel='stylesheet' href='/fashioncraft-notepads/css/ui.all.css'>");
						jQuery(document).ready(function(){ makeTabs(); });
					});
				} else {
					// load new version
					//jQuery("body").append("<br>loading new jqui, jquery version = " + jQuery().jquery);
					jQuery.getScript( "//ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" );
					jQuery("head").append( "<link type='text/css' rel='stylesheet' href='//ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css'>");
					jQuery(document).ready(function(){ makeTabs(); });
				}
			} else {
				// it's loaded. just redo the tabs
				//jQuery("head").append( "<link type='text/css' rel='stylesheet' href='//ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css'>");
				//jQuery("head").append("<link href='css/redmond/ui.all.css' rel='stylesheet' type='text/css'>");
				//jQuery("body").append("<br>jqui is loaded already. making tabs");
				makeTabs();
			}
			//jQuery("head").append( "<link type='text/css' rel='stylesheet' href='//ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css'>");
			//makeTabs();

			//jQuery(".ui-tabs-panel").css({ 'height' : '325px', 'overflow' : 'scroll', 'position' : 'relative' });
			//alert("done making tabs");
		}
		if ( JQVersion < JQ132 ) {

				//jQuery("body").append("<br>got livequery plugin");
				jQuery(".fashioncraft-content .personalizedGraphic a").livequery( "click", function(event){
					//jQuery("body").append("<br>livequery, jquery is less than 132");
					event.preventDefault();
					handleGraphicClick(this);
					return false;
				});
				//jQuery("body").append("<br>done setting up graphic click handling");
		} else { // if ( JQVersion < JQ132 ) {
			//jQuery("body").append("<br>JQ greater than 132, setting up graphic click handling");
			jQuery(".fashioncraft-content .personalizedGraphic a").live( "click", function(event){
				//jQuery("body").append("<br>live, jquery is 132");
				event.preventDefault();
				handleGraphicClick(this);
				return false;
			});
		} // if ( JQVersion < JQ132 ) {
	});

	/* for some reason, no code after this hover event will run
	* so that's why it's at the end */
	jQuery(".fashioncraft-content p#swatches a").hover(function(event){
		//jQuery("body").append("<br>preloading backgrounds on swatch hover");
		preloadBackground( jQuery(this).attr("href") );
		//jQuery("body").append("<br>done preloading backgrounds on swatch hover");
	});

	/*
	* //jQuery("body").append("<br>" + jQuery("ul .ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").css( "padding" ) );
	* //jQuery("body").append("<br>" + jQuery("ul .ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").css({ "padding" : "4em" }) );
	* //jQuery("body").append("<br>" + jQuery("#fashioncraftGraphics").css({ "padding" : "4em" }) );*/
});
