$(document).ready(function() {
  $('#codefield').hide();
  $('#removeie6').click(function() {
  	$('#ie6div').remove();
  });
    var signupBox = $.cookie('CCSignupBox');
  $('#removesignup').click(function() {
  	$('#signupdiv').remove();
  	$.cookie('CCSignupBox', 'removed');
  	  });
  
  var signupBox = $.cookie('CCSignupBox');
     if (signupBox != 'removed') {
    $('#signupdiv').show();
  };
 
 
 $('#examplewrapper').scrollFollow( {
    speed: 1000,
    offset: 60,
    killSwitch: 'stopFollowingMe'
 });


$('#color1').ColorPicker({
	color: '#5c5c5c',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color1').val('#'+hex).css('backgroundColor', '#' + hex).css('color',intcolor);
		updateBorderColor();
		updateCode();
	}
});

$('#color2').ColorPicker({
	color: '#333333',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color2').val('#'+hex).css('backgroundColor', '#' + hex).css('color',intcolor);
		updateBackgroundType();
		updateCode();
	}
});

$('#color3').ColorPicker({
	color: '#accbf7',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color3').val('#'+hex).css('backgroundColor', '#' + hex).css('color',intcolor);
		updateTextColor('#'+hex);
		updateCode();
	}
});
$('#color4').ColorPicker({
	color: '#cccccc',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color4').val('#'+hex).css('backgroundColor', '#' + hex).css('color', intcolor);
		updateExampleWrapper('#'+hex);
	}
});
$('#color5').ColorPicker({
	color: '#999999',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color5').val('#'+hex).css('backgroundColor', '#' + hex).css('color',intcolor);
		updateEmailMarketingColor();
		updateCode();
	}
});

$('#color6').ColorPicker({
	color: '#ff0000',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		if(hsb.b > 50) { var intcolor = '#000'; } else { var intcolor = '#fff'; }
		$('#color6').val('#'+hex).css('backgroundColor', '#' + hex).css('color',intcolor);
		updateBackgroundType();
		updateCode();
	}
});


// Select dropdowns
$('#borderwidth').change(function() { updateBorderWidth(); updateWidthCalculator(); });
$('#borderstyle').change(function() { updateBorderStyle(); });
$('#borderradius').change(function() { updateBorderRadius($('borderradius').val()); });
$('#emailinputsize').change(function() { updateEmailSize($('#emailinputsize').val())});
$('#textfont,input[name="textweight"],#textsize').change(function() { updateTextStyle(); });
$('#gradheight').change(function() { updateBackgroundType(); });
$('#textalign').change(function() { updateTextAlign(); });
$('#textpadding').change(function() { updateTextPadding(); });
$('#presets').change(function() { updatePresets(); });
// $('#bordertype').change(function() { updateBorderType($('#bordertype').val()); updateBackgroundColor(); }); // Only solid for now.

// Radio Buttons
$('input[name=safesubscribe]').bind('click change', function() { updateSafeSubscribe(); });
$('input[name="emailmarketing"]').bind('click change', function() { updateEmailMarketing(); });
$('input[name="backgroundtype"]').bind('click change', function() { updateBackgroundStyle(); updateBackgroundType(); });

// Text inputs
$("#defaulttext").bind('change keyup', function() { updateEmailInput(); });
$("#uid").bind('change keyup', function() { updateUID(); });
$("#defaultformtext").bind('change keyup', function() { updateFormText($("#defaultformtext").val());});
$("#bgurl").bind('change keyup', function() { updateBackgroundURL($(this).val()); updateCode(); });

$("#defaultbuttontext,input[name=submitdisplay],input[name=submitposition]").bind('change keyup', function() { updateDefaultButton(); });

// Pattern
$("li#bgpattern ul li").click(function(){ $("li#bgpattern ul li").removeClass('selected'); $(this).addClass('selected'); var url = $(this).attr("title"); updateBackgroundURL(url); updateCode(); });

$("#paddingwidth,.input input[name=widthtype],#width").bind('change keyup', function(e) { 
	if(eventKeys(e) || e.keyCode == 46 || e.keyCode == 8) { 
		// If it's not an arrow, tab, etc. and not delete or backspace, process the sucker!
		updateBoxWidthandPadding(); updateWidthCalculator(); updateCode(); 
	}
});
$('input[name=widthtype]').click(function() { updateBoxWidthandPadding(); updateWidthCalculator(); updateCode();  });
	
	
	function updatePresets(preset) {
		if(!preset) {
			var preset = $('#presets').val();
		}
		switch(preset) {
				
			case 'Army':
				updateTextColor('#f2d99f','#000000');
				updateBorderColor('#400f0f','#FFFFFF');
				updateBorderRadius(6);
				updateBorderStyle('solid');
				updateBackgroundStyle('gradient');
				updateBackgroundType('#498a2f','#472c0b', '#000000', '#FFFFFF');
				updateEmailMarketingColor('#ffffcc', '#000000');
				updateSafeSubscribe('white');
				updateFormText("Receive our newsletter.\n<br />That&rsquo;s an order!");
				updateTextStyle('courier', '24', 'bold');
				updateEmailInput('soldier@yourdivision.com');
				updateDefaultButton('Enlist');
				break;
			
			case 'Jazz':
				updateTextStyle('palatino', '20', 'normal');
				updateTextColor('#cfd1b3', '#000000');
				updateBorderColor('#FFFFFF','#000000');
				updateBorderRadius(9);
				updateBorderStyle('solid');
				updateBackgroundStyle('gradient');
				updateBackgroundType('#595187','#000000', '#000000', '#FFFFFF');
				updateFormText('Scratch below to catch our newsletter,&nbsp;daddy-o.');
				updateEmailInput('jazzlover@npr.org');
				updateDefaultButton('Yeah');
				break;
				
			case 'Impact':
				updateTextStyle('impact', '30', 'normal');
				updateTextColor('#e61010', '#000000');
				updateBorderColor('#FFFFFF','#000000');
				updateBorderRadius(3);
				updateBorderStyle('solid');
				updateBackgroundStyle('gradient');
				updateBackgroundType('#707070','#000000', '#FFFFFF', '#FFFFFF');
				updateFormText('DO YOU want our newsletter?');
				updateEmailInput('uknowuwanna@signup.com');
				updateDefaultButton('ADD ME');
				break;
				
			case 'Barbie':
				updateTextStyle('comicsans', '24', 'bold');
				updateTextColor('#12748c', '#000000');
				updateBorderColor('#f5f7b4','#000000');
				updateBorderRadius(20);
				updateBorderStyle('solid');
				updateEmailMarketingColor('#5c4444', '#ffffff');
				updateBackgroundStyle('gradient');
				updateBackgroundType('#d911d9','#d7cde6', '#000000', '#000000');
				updateFormText('Like, do you want updates?');
				updateEmailInput('have@fun.com');
				updateSafeSubscribe('white');
				updateDefaultButton('Totally!');
				break;
			
			case 'NYC':
				updateTextStyle('georgia', '24', 'normal');
				updateTextColor('#000000', '#ffffff');
				updateBorderColor('#000000','#ffffff');
				updateBorderRadius(15);
				updateBorderWidth(6);
				updateBorderStyle('dashed');
				updateEmailMarketingColor('#000000', '#ffffff');
				updateBackgroundStyle('gradient');
				updateBackgroundType('#ffffff','#f2fa05','#000000', '#000000');
				updateFormText('Hey, ye gonna sign up or wat?');
				updateEmailInput('take@thexpressway.com');
				updateSafeSubscribe('black');
				updateDefaultButton('Beep!');
				break;
				
			default:
				updateTextStyle('helvetica', 16, 'normal');
				updateTextColor('#accbf7', '#000000');
				updateBorderColor('#000000','#FFFFFF');
				updateBorderRadius(14);
				updateEmailMarketingColor('#999999', '#ffffff');
				updateBackgroundType('#ad0c0c','#000001', '#000000', '#FFFFFF');
				updateFormText('Sign up for Email Newsletters');
				updateEmailInput('signmeup@example.com');
				updateSafeSubscribe('gray');
				updateDefaultButton('Go');
				break;
		}
		
		updateBackgroundType();
	}
	
	function eventKeys(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 37 || code == 38 || code == 39 || code == 40 || code == 46 || code == 8 || code == 16) {
			return false;
		}else {
			return true;
		}
	}
	
	function setDefaults() {
		$('#examplewrapper .emailmarketing, #examplewrapper .emailmarketing a').css('padding','0').css('margin','0').css('line-height','1');
		$('#examplewrapper .emailmarketing').css('display','block').css('margin-top','4px').css('text-align', $('#textalign').val());
	}
	
	function updateUID() {
		$('#m').val($('#uid').val());
	}
	function updateFeed() {
	
		
		
		var attrLink = '<a id="codeSwapLink" href="http://www.constantcontact.com/index.jsp?pn=katzwebdesign"  title="Go to Constant Contact" target="_blank" style="text-align:center; clear:both; display:block; font-weight:normal!important; font-size:10px;">Email newsletters by Constant Contact</a>';
    	
    	if($('input[name="givethanks"]:checked').val() == 'yes') {
    		$("#ccoptin .rss-item,#ccoptin #cc-attr").remove();
			var existingStr = $('#attributioncode').val();
			
			if($("#ccoptin #cc-attr").length == 0) {
				if($('#corners').length > 0) { 
					$('#corners').after(attrLink);
				} else {
					$('#kwd-constant-contact').after(attrLink);
				}
			}
		} else {
			var existingStr = '';
			$(".rss-item").remove();
		}
		return existingStr;
	}
	
	function updateCode() {
		$('#codeSwapLink').remove();
		var fullStr = $('#examplewrapper .grabber').html().replace(/\n/g,'') + updateFeed();
		//alert(fullStr);
    	$('#bloggercode').val(fullStr).submit();
    	$('#codefield').val(fullStr);
    	validateForm();
	}

	function updateBoxWidthandPadding() {
		var rawpaddingwidth = $('#paddingwidth').val();
		var paddingwidth = $('#paddingwidth').val() + 'px';
		
		var widthtype = $('input[name=widthtype]:checked').val();
		if(widthtype == 'per') {
			//if(($('#width').val() * 1) > 100) { $('#width').val('100'); }
			widthunit = '%';
		} else {
			widthunit = 'px';
		}
		if($('#width').val() != '') { 
			var width = $('#width').val() + widthunit; 
			var rawwidth = $('#width').val();
		} else {
			var width = '100' + widthunit;
			var rawwidth = '100';
		}
		
		$("#corners").css("width", width);
		
		$('#kwd-constant-contact')
			.css('padding', paddingwidth)
			.css("float", 'none')
			.css('width', '100%')
		;

		var ccwidth = $('#kwd-constant-contact').width();
		
		if(widthunit == 'px') {
			$('#kwd-constant-contact').css('width',ccwidth+'px');
			$('#corners').width($('#corners').width() + rawpaddingwidth * 2);
			if($('#width').val() != '') { $('#width').val($('#corners').width() - rawpaddingwidth * 2);}
		} else {
			$('#kwd-constant-contact').css("width", 'auto');
			$('#corners').css("width", width);
		}
		$('#corners').css('margin', '0 auto');
	}
	
	function updateWidthCalculator() {
		if($('input[name=widthtype]:checked').val() == 'px') {
		var realwidth = $('#corners').width() + +$('#borderwidth').val() * 2;
			$('#actualwidth').html('<small style="display:block; border:1px solid #ccc; clear:both; float:left; width:95%; background:#fcfcfc; padding:4px 2%; margin-top:6px;"><strong>Real width is '+ realwidth + 'px.</strong><br /> Width: '+ $('#width').val()+ 'px + <br />Padding: '+$('#paddingwidth').val() + 'px'+' * 2 +<br />Border Width: '+$('#borderwidth').val() + 'px * 2</small>');
		} else {
			$('#actualwidth').html('');
		}
	}
	
	function updateFormText(defaultformtext) {
		if(defaultformtext != $("#defaultformtext").val()) {
			$("#defaultformtext").val(defaultformtext);
			updateFormText(defaultformtext);
		}
		else if(defaultformtext == '') {
			$('form#ccoptin label.ccHead').remove();
		} else {
			if($('form#ccoptin label.ccHead').length > 0) {
				$('form#ccoptin label.ccHead').html(defaultformtext);
			} else {
				$('form#ccoptin').prepend('<label class="ccHead">'+defaultformtext+'</label>');
			}
			$('label.ccHead')
			.css("line-height", "1")
			.css("margin", "0")
			.css("padding", "0");
		}
		updateTextPadding();
	}
	
	function updateDefaultButton(defaultbuttontext,submitstyle,submitposition) {
		if(!defaultbuttontext) { var defaultbuttontext = $("#defaultbuttontext").val();} else {$("#defaultbuttontext").val(defaultbuttontext) }
		if(!submitstyle) { var submitstyle = $('input[name=submitdisplay]:checked').val(); } else { $('input[name=submitdisplay][value='+submitstyle+']').attr('checked','checked'); }
		if(!submitposition) { var submitposition = $('input[name=submitposition]:checked').val(); } else { $('input[name=submitposition][value='+submitposition+']').attr('checked','checked'); }
		if(submitstyle == 'inline') {
			$('#go').addClass('submitWrap');
			$('div.submitWrap').replaceWith($('#go'));
		} else {
			$('#go:not("div.submitWrap #go")').removeClass('submitWrap').wrap('<div class="submitWrap"></div>');
		}
		
		if(submitposition == 'after') {
			$('.submitWrap').remove().insertAfter('#ea');
		} else {
			$('.submitWrap').remove().insertBefore('#ea');
		}
		
		$('#go').val(defaultbuttontext);
		//css('padding','1px 4px');//.removeClass('inline').removeClass('block').addClass(submitstyle);
		
	}
	
	function updateEmailInput(defaulttext) {
		if(!defaulttext) {
			var defaulttext = $("#defaulttext").val();
		}
		$('#ea').val(defaulttext).attr('defaultValue', defaulttext);
		$('#defaulttext').val(defaulttext);
	}

	function updateTextStyle(textfont,textsize,fontweight,textpadding) {
		if(!textfont) {
			var textfont = $('#textfont').val();
		} else {
			var textfont = $('select[name="textfont"] option[id="'+textfont+'"]').val();
			$('select[name="textfont"] option[value="'+textfont+'"]').attr('selected','selected');
		}
		if(!textsize) {
			var textsize = $('#textsize').val();
		} else {
			$('select#textsize option[value="'+textsize+'"]').attr('selected','selected');
		}
		if(!fontweight){
			var fontweight = $('input[name="textweight"]:checked').val();
		} else {
			$('input[name="textweight"][value="'+fontweight+'"]').attr('checked','checked');
		}
		if($('#textfont option:selected:contains("*")').length > 0) { 
			$("#textoptions .asterix").show();
		} else {
			$("#textoptions .asterix").hide();
		}
		$('#examplewrapper .emailmarketing, #examplewrapper .emailmarketing a,#kwd-constant-contact label.ccHead').css("font-family",textfont)
		if($('input[name="emailmarketing"]:checked').val() == 'yes') { 
			$('#kwd-constant-contact .emailmarketing').css("font-family",textfont); 
		}
		$('label.ccHead')
			.css("font-size", textsize +'px')
			.css("font-weight", fontweight)
			.css("line-height", "1")
			.css("margin", "0");
		if(!textpadding) {
			updateTextPadding();			
		} else {
			updateTextPadding(textpadding);			
		}
	}
	
	function updateEmailSize(emailinputsize) {
		if(emailinputsize != 0) {
			$('#defaulttext, label[for=defaulttext], li.defaulttext').show();
			if($('#kwd-constant-contact #ea').length > 0) {
				$('#kwd-constant-contact #ea').attr('size',emailinputsize);
				if($('#kwd-constant-contact #ea').attr('size') != emailinputsize) {
					// processStyle(); 
				}
			} else {
				$('#kwd-constant-contact #p').after('<input type="text" name="ea" id="ea" size="'+emailinputsize+'" value="signmeup@example.com" onfocus="if (this.value == this.defaultValue) {this.value = \'\';}" onblur="if (this.value == \'\') {this.value = this.defaultValue;}" />');
			}
		} else {
			$('#defaulttext, label[for=defaulttext], li.defaulttext').hide();
			$('#kwd-constant-contact #ea').remove();
		}
	}
	
	function updateBorderStyle(borderstyle) {
		if(!borderstyle || borderstyle == '') {
			var borderstyle =  $('#borderstyle option:selected').val();
		} else {
			 $('#borderstyle option[value='+borderstyle+']').attr('selected','selected');
		}
		
		$('#kwd-constant-contact').css('background-clip','border-box').css("border-style", borderstyle);
	}
	function updateBorderWidth(borderwidth) {
		if(!borderwidth) {
			var borderwidth =  $('#borderwidth').val() + 'px';
		} else {
			borderwidth =  borderwidth + 'px';
		}
		if(borderwidth == '0' || borderwidth == 'none') {
			$('#borderwidth option[value="0"]').attr('selected','selected');
			$('#kwd-constant-contact').css("border-width", '0');
		} else {
			$('#kwd-constant-contact').css("border-width", borderwidth);
		}
	}

	function updateBackgroundColor(color1, color2,textcolor1,textcolor2) {
		if(!color1) {
			var color1 = $('#color6').val().replace(/#/g,'');	
		} else {
			$('#color6').val(color1).css('background-color',color1).ColorPickerSetColor(color1);
		}
		if(!color2) {
			var color2 = $('#color2').val().replace(/#/g,'');	
		} else {
			$('#color2').val(color2).css('background-color',color2).ColorPickerSetColor(color2);
		}
		if(textcolor1) {
			$('#color6').css('color',textcolor1);
		}
		if(textcolor2) {
			$('#color2').css('color',textcolor2);
		}
		if($("input[name=backgroundtype]:checked").val() == 'gradient') {
			$('#safesubscribelightimg,#safesubscribedarkimg,#safesubscribeblackimg').css("background-color", color2).css("background-image", 'none');
		} else {
			$('#kwd-constant-contact').css("background-image", 'none').css("background", $('#color2').val());
			$('#safesubscribelightimg,#safesubscribedarkimg,#safesubscribeblackimg').css("background-color", color2).css("background-image", 'none');
		}
	}
	function updateBackgroundStyle(style) {
		if(style) {
			$('input[name=backgroundtype][value='+style+']').attr('checked','checked');
		}
		else { return; }
	}
	function updateBackgroundType(color1,color2,textcolor1,textcolor2,url){
		var selection = $("input[name=backgroundtype]:checked").val();
		if(selection == 'gradient') {
			$("li#bgtop,li#gradheightli").show();
			$("li#bgpattern,li#bgurl").hide();
			$("li#bgbottom label").text('Background Top Color:');
			updateBackgroundColor(color1,color2,textcolor1,textcolor2);
			updateGradient(color1,color2,textcolor1,textcolor2);
		} else if(selection == 'solid') {
			updateBackgroundColor(color1,color2,textcolor1,textcolor2);
			$("li#bgtop,li#gradheightli,li#bgpattern,li#bgurl").hide();
			$("li#bgbottom").show();
			$("li#bgbottom label").text('Background Color:');
		} else if(selection == 'pattern') {
			$("li#bgpattern").show('normal');
			$("li#bgtop,li#gradheightli,li#bgbottom,li#bgurl").hide();
			
			if($("li#bgpattern ul li.selected").length) { var bgTitle = $("li#bgpattern ul li.selected").attr('title'); } 
			else { var bgTitle = $("li#bgpattern ul li:first").attr('title'); }
			updateBackgroundURL(bgTitle);
		} else if(selection == 'url') {
			$("li#bgtop,li#gradheightli,li#bgpattern").hide();
			$("li#bgurl,li#bgbottom").show();
			$("li#bgbottom label").text('Background Color:');
			updateBackgroundURL(url,color1);
		}
		// alert('c1: '+typeof(color1) + ', c2: '+typeof(color2) + ', tc1: '+typeof(textcolor1) + ', tc2: '+typeof(textcolor2));
	}
	
	
	function updateBackgroundURL(url, color, repeat) {
		if(!url || url == 'http://') { var url = ''; } else { url = 'url('+url+')'; }
		if(!color) { var color = 'transparent'}
		$('#kwd-constant-contact').css("background", color+' '+url+' left top repeat');
	}
	function updateGradient(color1,color2,textcolor1,textcolor2) {
			if(!color1) {
				var color1 = $('#color6').val().replace(/#/g,'');	
			} else {
				$('#color6').val(color1).css('background-color',color1).ColorPickerSetColor(color1);
			}
			if(!color2) {
				var color2 = $('#color2').val().replace(/#/g,'');	
			} else {
				$('#color2').val(color2).css('background-color',color2).ColorPickerSetColor(color2);
			}
			if(textcolor1) {
				$('#color6').css('color',textcolor1);
			}
			if(textcolor2) {
				$('#color2').css('color',textcolor2);
			}
			
			var gradheight = $('#gradheight').val();
			
			var getImage = 'http://katzwebservices.com/constant-contact/gradients/gradient-image.php';
			
			// alert('start='+color1+'&end='+color2+'&height='+gradheight);
			$.ajax({
			  type: "GET",
			  url: getImage,
			  dataType: "script",
			  data: 'start='+color1+'&end='+color2+'&height='+gradheight,
			  async: true,
			  success: function(msg){
			     var getImage = msg;
			     var bgRule = '#'+color2+' url(gradients/'+getImage+') left top repeat-x';
			     //alert(bgRule);
				$('#kwd-constant-contact').css('background', bgRule);
				updateCode();
			   },
			   error: function() {
			   	return false;
			   }
			});
	}
	function updateSafeSubscribe(safesubscribe) {
		if(!safesubscribe) {
			var safesubscribe = $('input[name="safesubscribe"]:checked').val();
		} else {
			$('input[name="safesubscribe"][value='+safesubscribe+']').attr('checked', 'checked');
		}
		var safecodelight = $("#safesubscribelightcode").html();
		var safecodedark = $("#safesubscribedarkcode").html();
		var safecodeblack = $("#safesubscribeblackcode").html();
		var emailmarketingcolor = $('#color5').val();
		
		$('#kwd-constant-contact .safesubscribe').remove();
		if(safesubscribe == 'gray' || safesubscribe == 'grey') { 
			$('#kwd-constant-contact form').append('<a href="http://snurl.com/as4c4" target="_blank" class="safesubscribe" style="padding:5px 0 0 0; text-decoration:none; display:block; border:none;" id="safecodedark"><img src="http://katzwebdesign.files.wordpress.com/2009/06/safesubscribe-light.gif" style="border:0;" width="168" height="14" alt="SafeSubscribe"  style="border:0;padding:0; margin:0;" /></a>'); 
			if(emailmarketingcolor == '#999999' || emailmarketingcolor == '#ffffff' || emailmarketingcolor == '#000000') { 
				$('#emailmarketingcode p, #emailmarketingcode a').css('color', "#999999");
				$('#color5').val('#999999').css('background-color','#999999').css('color','#ffffff'); 
			}
		}
		if(safesubscribe == 'white') { 
			$('#kwd-constant-contact form').append('<a href="http://snurl.com/as4c4" target="_blank" class="safesubscribe" style="padding:5px 0 0 0; text-decoration:none; display:block; border:none;" id="safecodelight"><img src="http://katzwebdesign.files.wordpress.com/2009/06/safesubscribe-dark.gif" style="border:0;" width="168" height="14" alt="SafeSubscribe"  style="border:0;padding:0; margin:0;" /></a>'); 
			if(emailmarketingcolor == '#999999' || emailmarketingcolor == '#ffffff' || emailmarketingcolor == '#000000') {  
				$('#emailmarketingcode p, #emailmarketingcode a').css('color', "white");
				$('#color5').val('#ffffff').css('background-color','#ffffff').css('color','#000000');
			}
		}
		if(safesubscribe == 'black') { 
			$('#kwd-constant-contact form').append('<a href="http://snurl.com/as4c4" target="_blank" class="safesubscribe" style="padding:5px 0 0 0; text-decoration:none; display:block; border:none;" id="safecodeblack"><img src="http://katzwebdesign.wordpress.com/files/2009/06/safesubscribe-black.gif" style="border:0;" width="168" height="14" alt="SafeSubscribe"  style="border:0;padding:0; margin:0;" /></a>'); 
			if(emailmarketingcolor == '#999999' || emailmarketingcolor == '#ffffff' || emailmarketingcolor == '#000000') { 
				$('#emailmarketingcode p, #emailmarketingcode a').css('color', "black").css('font-weight','normal'); 
				$('#color5').val('#000000').css('background-color','#000000').css('color','#ffffff'); 
			}
		}
		updateEmailMarketingColor();
	}
	
	function updateEmailMarketing() {
		$('#kwd-constant-contact .emailmarketing').remove();
		if($('input[name="emailmarketing"]:checked').val() == 'yes') { 
			$('#kwd-constant-contact .submit').after('<p style="padding:6px 0 0 0; margin:0; font-size:11px!important; font-weight:normal!important;" class="emailmarketing"><a href="http://snurl.com/as4af" style="text-decoration:none; font-size:11px;" target="_blank">For Email Marketing you can trust</a>');
		}
		updateTextStyle();
		updateEmailMarketingColor();
	}
	
	function updateExampleWrapper(examplebgcolor){ 
		$('#examplewrapper').css('background-color', examplebgcolor);
	}
	
	function updateEmailMarketingColor(color) {
		if(!color) {
			var color = $('#color5').val();	
		} else {
			$('#color5').val(color).css('background-color',color).ColorPickerSetColor(color);
		}
		$('#examplewrapper .emailmarketing, #examplewrapper .emailmarketing a').css('color', color);
	}
	
	function updateTextAlign() {
		$('#corners *:not("input[type=text]")').css("text-align",$('#textalign').val());
	}
	
	function updateTextPadding(val) {
		if(val) {
			$('label.ccHead').css("padding-bottom",val+'px');
			return;
		}
		var rawtextpaddingwidth = $('#textpadding').val(); 
		var textpaddingwidth = $('#textpadding').val() + 'px'; 
		
		$('label.ccHead').css("padding-bottom",textpaddingwidth);
	}
	
	function updateTextColor(color,textcolor) {
		if(!color) {
			var color = $('#color3').val();	
		} else {
			$('#color3').val(color).css('background-color',color).ColorPickerSetColor(color);
		}
		if(textcolor) {
			$('#color3').css('color',textcolor);
		}
   		$('#corners,#kwd-constant-contact').css("color", color);
	}
    function updateBorderRadius(borderradius) {
    	if(!borderradius) {
    		var borderradius = $("#borderradius").val() + 'px';
    	}
    	$('#kwd-constant-contact').css('border-radius',borderradius).css('-webkit-border-radius',borderradius).css('-moz-border-radius',borderradius);
    }
	function updateBorderColor(bordercolor,textcolor) {
		if(!bordercolor) {
			var bordercolor = $('#color1').val();	
		} else {
			$('#color1').val(bordercolor).css('background-color',bordercolor).ColorPickerSetColor(bordercolor);
		}
		if(textcolor) {
			$('#color1').css('color',textcolor);
		}
		$('#kwd-constant-contact').css("border-color",bordercolor);
	};
	
	function updateBorderType(bordertype) {
		if($('#corners').length == 0){
			$("#kwd-constant-contact").wrap("<div id='corners'></div>");
		}
		$('#corners')
			.css("background-color", 'transparent')
			.css("text-align",textalign);
			
		$('#kwd-constant-contact').css('display', 'block');
			
		if($("input#givethanksyes").is(':checked')) {
			$('#corners').css('margin-bottom','.5em');
		}			
	}
	

function updateAll() {
	setDefaults();
	updateTextColor();
	updateTextStyle();
	updateEmailSize($('#emailinputsize').val());
	updateBackgroundColor();
//	updateBackgroundType();
	updateBorderWidth();
	updateBorderRadius();
	updateBorderColor();
	updateBorderStyle();
	updateExampleWrapper($('#color4').val());
	updateEmailMarketing();
	updateEmailMarketingColor();
	updateSafeSubscribe();
	updateBoxWidthandPadding();
	updateTextAlign();
	updateTextPadding();
	updateDefaultButton();
//	updatePresets();
	updateUID();
	updateCode();
}
updatePresets();
updateAll();

	$("#settings").bind('change', function() { updateCode(); });



$('#settings').validate({
rules: {
	uid: {
		required: true,
		number: true,
		minlength: 8,
		maxlength: 13,
		rangelength: [8, 13]
	}
},
	messages: {
		uid: {
			required: jQuery.format("Your CC ID is required for the form to work."), 
			number: jQuery.format("Constant Contact IDs contain only numbers."),
			rangelength: jQuery.format("Constant Contact IDs are at least {0} characters, normally 13."),
			minlength: jQuery.format("Constant Contact IDs are at least {0} characters, normally 13."),
			maxlength: jQuery.format("Constant Contact unique IDs are no longer than {0} characters.")
		}
	}
});

  // processStyle();
$('form label.error').hide();
  
$('#settings').submit(function() {
	if($(this).valid()) {
		showCode();
	}
	return false;});
   function validateForm() {
   	var valid = $("#uid").valid();
   	if(valid){
   		$('#getwidget, #getcode').removeAttr("disabled").css('cursor', 'pointer');
   		$('#buttons .alert').hide('slow').animate({ color: "#ffffff" }, 1000);;
   	} else {
   		$('#buttons .alert').remove();
   		$("#installoptions").after('<p class="alert">You must enter a valid <a href="#">Unique ID</a> before your form will function properly.</p>').css('color',"black");
   		$('#getwidget, #getcode').attr('disabled', true).css('cursor', 'default');   	}
   	var uidlength = $('#uid').val();
   	uidlength = uidlength.length;
   	if(uidlength < 13 && uidlength > 7) {
   		$('#uid').addClass('warning');
   		$('#useroptions label.warning').remove();
   		$('#useroptions').append('<label for="uid" generated="true" class="warning" style="display:block;">Constant Contact IDs are normally 13 characters.</label>');
   	} else {
   		$('#uid').removeClass('warning');
   		$('#useroptions label.warning').remove();
   	}
   }
   
	$('#buttons .alert a').click(function() {
		$('input#uid').focus();
		$('#instructions').is(':hidden').show('slow');
		return false;
	});
        
   $('form[name!=ccoptin], form[name!=ccoptin] input, form[name!=ccoptin] select').change(function() {
   	//processStyle();
   }).keyup(function() {
	 	//processStyle();
	 });
	 
   $('label img').click(function(){
		$(this).closest('input[type=radio]').click();
   });
   $('input[type=radio]').click(function() { 
   	//processStyle();
   });
   
   
  
   
   function processStyle() {
		var borderwidth = $('#borderwidth').val() + 'px';
		var rawpaddingwidth = $('#paddingwidth').val();
		var paddingwidth = $('#paddingwidth').val() + 'px';
		
		var rawtextpaddingwidth = $('#textpadding').val(); 
		var textpaddingwidth = $('#textpadding').val() + 'px'; 
		
		var widthtype = $('input[name=widthtype]:checked').val();
		if(widthtype == 'per') {
			if(($('#width').val() * 1) > 100) { $('#width').val('100'); }
			widthunit = '%';
		} else {
			widthunit = 'px';
		}
		if($('#width').val() != '') { 
			var width = $('#width').val() + widthunit; 
			var rawwidth = $('#width').val();
		} else {
			var width = '100' + widthunit;
			var rawwidth = '100';
		}
		
		var examplebgcolor = $('#color4').val();
		
		var emailmarketingcolor = $('#color5').val();
		
		$('#examplewrapper .emailmarketing, #examplewrapper .emailmarketing a').css('padding','0').css('margin','0').css('line-height','1');
		$('#examplewrapper .emailmarketing').css('display','block').css('margin-top','4px').css('text-align', textalign);
		
		var textsize = $('#textsize').val() + 'px';
		var textweight = $('input[name="textweight"]:checked').val();
		var safesubscribe = $('input[name="safesubscribe"]:checked').val();
		var safecodelight = $("#safesubscribelightcode").html();
		var safecodedark = $("#safesubscribedarkcode").html();
		var safecodeblack = $("#safesubscribeblackcode").html();
		var defaulttext = $("#defaulttext").val();
		var defaultformtext = $("#defaultformtext").html();
		var emailinputsize = $('#emailinputsize').val();
		var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
      var defaultformtext = defaultformtext
      			/*
.replace(/"/g,"&quot;")
                  .replace(/</g,"&lt;")
                  .replace(/>/g,"&gt;")
                  .replace(/&/g,"&amp;")
                  
*/.replace(regexp,"");    
		
		
	
		
		
		$('.safesubscribe').css('display','block').css('margin','4px 0 0 0').css('padding','0').css('line-height','1');
		$('.safesubscribe img').css('display','inline');
		
		$('#kwd-constant-contact label.ccHead')
			.css("font-size",textsize)
			.css("font-weight", textweight)
			.css("line-height", "1")
			.css("margin", "0")
			.css("padding", "0.3em 0")
		;
		
		
	
		
		
		
		$('#ea').val(defaulttext).attr('defaultValue', defaulttext).css('padding','2px 4px');
		$('#go').val(defaultbuttontext).css('padding','1px 4px');
		
		$('form#ccoptin').css('margin','0').css('padding','0');
		
		$('#m').val($('#uid').val());
		
		

		$(".rss-item").remove();
		var htmlStr = $('#examplewrapper .grabber').html().replace(/\n/g,'');
		
    	if($('input[name="givethanks"]:checked').val() == 'yes') {
			var existingStr = $('#attributioncode').val();
		} else {
			var existingStr = '';
			$(".rss-item").remove();
		}
		
		var fullStr = htmlStr + existingStr;
    	$('#bloggercode').val(fullStr).submit();
    	

    	$('#codefield').val(fullStr);
    	
    	$('.grabber').hAlign();
    	
    	validateForm();
    	
    	return false;    
   }
   
   
   
   $('#getcode').click(function() {
	 	validateForm();
	 	// processStyle();
		showCode();
    	return false;
   });
   
   $('a.textdirections').click(function() { $('div.textdirections').slideToggle("slow").select(); });
   
   function showCode() {
   	$('#codefield').slideToggle("slow").select();
    	if($('#getcode').val() == "View Code") { 
    		$('#getcode').val("Hide Code");
    	} else { 
	      	$('#getcode').val("View Code");
    	}
   }
   
   $('#viewinstructions').click(function() {
		$('#instructions').slideToggle("slow");
    	if($(this).html() == "(View instructions)") { 
    		$(this).html("(Hide instructions)");
    	} else { 
	      	$(this).html("(View instructions)");
    	}
    	return false;
   });
   $('#codefield').click(function() {
   	$(this).select();
   });
   $('#getwidget').click(function() {
		//processStyle();
    	
   });
      
/*
   $("#blogger").click(function() {
   		$("#uid").valid(); 
   		$(this).submit();
   });
*/
   
	
   	
});

	$.fn.clearText = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
		});
	};
	
	$.fn.processColor = function(black, sat) {
	if(sat > 40) { black = black - 10;}
	
	if(black < 25) {
		$(this).css('color', 'white');
	} else if(black < 50) {
		$(this).css('color', '#cccccc');
	} else if(black < 60) {
		$(this).css('color', '#333333');
	} else {
		$(this).css('color', 'black');
	}
	
	};
	
	(function ($) {
		
		$.fn.vAlign = function() {
			return this.each(function(i){
			var ah = $(this).height();
			var ph = $(this).parent().height();
			var mh = (ph - ah) / 2;
			$(this).css('margin-top', mh);
			});
		};
	})(jQuery);
	
	(function ($) {
		
		$.fn.hAlign = function() {
			return this.each(function(i){
			var ah = $(this).width();
			var ph = $(this).parent().width();
			var mh = (ph - ah) / 2;
			$(this).css('padding-left', mh);
			});
		};
	})(jQuery);
	
	(function($) {
  $.fn.stripHtml = function() {
      var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
      this.each(function() {
          $(this).html(
              $(this).html().replace(regexp,"")
          );
      });
      return $(this);
  }
})(jQuery);