$(document).ready(function() {
	$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
		  while(x<c.length){var m=r.exec(c.substr(x));
		    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
		    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
		    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
		URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
		  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
		  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
		});
	var create_embed_code = function(quote_id){
		var script_code = '<script src="http://media.quotd.com/js/quotd_widget.js" type="text/javascript"></script>';			
		var headline_embed = '#'+quote_id+'_embed_headline';
		var headline_embed_txt = '#'+quote_id+'_embed_headline_txt';
		var container_embed = '#'+quote_id+'_embed_container';
		var quote_info_embed = '#'+quote_id+'_embed_quote_info';
		var agrees_embed = '#'+quote_id+'_embed_agrees';

		var bg_embed = '#'+quote_id+'_bgcolor';
		var font_embed = '#'+quote_id+'_fontcolor';
		var border_embed = '#'+quote_id+'_bordercolor';
		var link_embed = '#'+quote_id+'_linkcolor';
			
		var width_link = '#'+quote_id+'_embed_holder .embed_control_size';
		var embed_width = $(width_link).filter(function(){
			var match = 'rgb(227, 116, 0)';
			return ( $(this).css('background-color') == match );				
		}).attr('rel');

		if (embed_width == '600'){
			embed_height = 220;
		}

		else if (embed_width == '600'){
			embed_height = 180;
		}

		else if (embed_width == '600'){
			embed_height = 165;
		}

		else {
			embed_height = embed_width * (22/60)
		};		

		if ($(headline_embed).is(':checked')){
			var headline_status = 'True'
		}
		else {
			var headline_status = 'False'
		};

		if ($(container_embed).is(':checked')){
			var container_status = 'True'				
		}
		else {
			var container_status = 'False'
		};

		if ($(quote_info_embed).is(':checked')){
			var quote_info_status = 'True'
		}
		else {
			var quote_info_status = 'False'
		};


		if ($(agrees_embed).is(':checked')){
			var agrees_status = 'True'
		}
		else {
			var agrees_status = 'False'
		};

		var data_key = "{'quote':'"+quote_id+"','s':'"+embed_width+"','h':'"+$.URLEncode($(headline_embed_txt).val())+"','hi':'"+headline_status+"','c':'"+container_status+"','i':'"+quote_info_status+"','a':'"+agrees_status+
							"','font':'"+$(font_embed).val()+"','bg':'"+$(bg_embed).val()+"','border':'"+$(border_embed).val()+"','link':'"+$(link_embed).val()+"'}"


		var quotd_embed_container = '<div class="quotd_quote_widget_container clearfix" data-key="'+data_key+
						'" style="margin: 15px 0px 15px 0px; width: '+embed_width+'px; height:'+embed_height+'px; background-color:'+$(bg_embed).val()+'; color: '+$(font_embed).val()+
						'; border: 1px solid '+$(border_embed).val()+';" rel="'+quote_id+'"></div><br />';


		return script_code + quotd_embed_container

	};
	var create_embed_question_code = function(question_id){
		var script_code = '<script src="http://media.quotd.com/js/quotd_question_embed.js" type="text/javascript" />'
		var embed_preview = '#'+question_id+'_embed_preview';

		var container_embed = '#'+question_id+'_embed_container';
		var description_embed = '#'+question_id+'_embed_description';
		var question_info_embed = '#'+question_id+'_embed_question_info';
		var quote_info_embed = '#'+question_id+'_embed_quote_info';
		var agrees_embed = '#'+question_id+'_embed_agrees';
		var collapse_embed = '#'+question_id+'_embed_collapsed';

		var embed_preview = '#'+question_id+'_embed_preview';
		var second_bg_embed = $(embed_preview).attr('data-second-bg-color');
		var third_bg_embed = $(embed_preview).attr('data-third-bg-color');

		var bg_embed = '#'+question_id+'_bgcolor';
		var font_embed = '#'+question_id+'_fontcolor';
		var border_embed = '#'+question_id+'_bordercolor';
		var link_embed = '#'+question_id+'_linkcolor';
		
		var quote_values = '[';
		var input_checked_selector = '#'+question_id+'_embed_question_answer_exclusion input:checked';
		$.each($(input_checked_selector), function() {
			quote_values = quote_values +'('+$(this).attr('rel')+',(';
			quote_inputs = '#'+$(this).attr('rel')+'_answer_quote_list input:checked';
			$.each($(quote_inputs), function() {
				quote_values=quote_values+$(this).attr('rel')+',';
			});
			quote_values=quote_values+')),';
		});
		var quote_values = quote_values + ']';
	
		var width_link = '#'+question_id+'_embed_holder .embed_control_question_size_selected';
		var embed_width = $(width_link).first().attr('rel');

		if (embed_width == '400'){
			if (embed_collapse == 'True'){
				var embed_height = '100';
			}
			else {
				var embed_height = '440';						
			}
			}

		else if (embed_width == '500'){
			if (embed_collapse == 'True'){
				var embed_height = '125';
			}
			else {
				var embed_height = '550';						
			}
			}

		else if (embed_width == '600'){
			if (embed_collapse == 'True'){
				var embed_height = '150';
			}
			else {
				var embed_height = '660';						
			}
		}

		else {
			if (embed_collapse == 'True'){
				var embed_height = embed_width * .25;
			}
			else {
				var embed_height = embed_width * (11/10);						
			}		
		};

		if ($(collapse_embed).is(':checked')){
			var embed_collapse = 'True';
		}
		else {
			var embed_collapse = 'False';
		};

		if ($(description_embed).is(':checked')){
			var embed_description = 'True';
		}
		else {
			var embed_description = 'False';
		};

		if ($(question_info_embed).is(':checked')){
			var question_info_status = 'True'
		}
		else {
			var question_info_status = 'False'
		};

		if ($(quote_info_embed).is(':checked')){
			var quote_info_status = 'True'
		}
		else {
			var quote_info_status = 'False'
		};

		if ($(agrees_embed).is(':checked')){
			var agrees_status = 'True'
		}
		else {
			var agrees_status = 'False'
		};

		var data_key = "{'question':"+question_id+",'s':'"+embed_width+"','qlist':'"+quote_values+"','col':'"+embed_collapse+"','desc':'"+embed_description+
								"','sbg':'"+second_bg_embed+"','tbg':'"+third_bg_embed+"','c':'"+container_embed+
								"','quotei':'"+quote_info_status+"','a':'"+agrees_status+"','questi':'"+question_info_status+
								"','font':'"+$(font_embed).val()+"','bg':'"+$(bg_embed).val()+"','border':'"+$(border_embed).val()+"','link':'"+$(link_embed).val()+"'}"

		var quotd_embed_container = '<div class="quotd_question_widget clearfix" data-key="'+data_key+
			'" style="width: '+embed_width+'px; height:'+embed_height+'px; margin: 0px 15px !important; padding: 5px !important; background-color:'+$(bg_embed).val()+'; color: '+$(font_embed).val()+
			'; border: 1px solid '+$(border_embed).val()+';" rel="'+question_id+'"></div><br />';

		return quotd_embed_container + script_code
	};
	var create_embed_story_code = function(story_id){
		var script_code = '<script src="http://media.quotd.com/js/quotd_story_embed.js" type="text/javascript" />'
		var embed_preview = '#'+story_id+'_embed_preview';

		var container_embed = '#'+story_id+'_embed_container';
		var description_embed = '#'+story_id+'_embed_description';
		var story_info_embed = '#'+story_id+'_embed_story_info';
		var quote_info_embed = '#'+story_id+'_embed_quote_info';
		var agrees_embed = '#'+story_id+'_embed_agrees';
		var collapse_embed = '#'+story_id+'_embed_collapsed';

		var embed_preview = '#'+story_id+'_embed_preview';
		var second_bg_embed = $(embed_preview).attr('data-second-bg-color');
		var third_bg_embed = $(embed_preview).attr('data-third-bg-color');

		var bg_embed = '#'+story_id+'_bgcolor';
		var font_embed = '#'+story_id+'_fontcolor';
		var border_embed = '#'+story_id+'_bordercolor';
		var link_embed = '#'+story_id+'_linkcolor';

		var quote_values = '(';
		var	quote_inputs = '#'+story_id+'_story_quote_list input:checked';
		$.each($(quote_inputs), function() {
			quote_values=quote_values+$(this).attr('rel')+',';
		});
					
		var quote_values = quote_values + ')';

	
		var width_link = '#'+story_id+'_embed_holder .embed_control_question_size_selected';
		var embed_width = $(width_link).first().attr('rel');

		if (embed_width == '400'){
			if (embed_collapse == 'True'){
				var embed_height = '100';
			}
			else {
				var embed_height = '440';						
			}
			}

		else if (embed_width == '500'){
			if (embed_collapse == 'True'){
				var embed_height = '125';
			}
			else {
				var embed_height = '550';						
			}
			}

		else if (embed_width == '600'){
			if (embed_collapse == 'True'){
				var embed_height = '150';
			}
			else {
				var embed_height = '660';						
			}
		}

		else {
			if (embed_collapse == 'True'){
				var embed_height = embed_width * .25;
			}
			else {
				var embed_height = embed_width * (11/10);						
			}		
		};

		if ($(collapse_embed).is(':checked')){
			var embed_collapse = 'True';
		}
		else {
			var embed_collapse = 'False';
		};

		if ($(description_embed).is(':checked')){
			var embed_description = 'True';
		}
		else {
			var embed_description = 'False';
		};

		if ($(story_info_embed).is(':checked')){
			var story_info_status = 'True'
		}
		else {
			var story_info_status = 'False'
		};

		if ($(quote_info_embed).is(':checked')){
			var quote_info_status = 'True'
		}
		else {
			var quote_info_status = 'False'
		};

		if ($(agrees_embed).is(':checked')){
			var agrees_status = 'True'
		}
		else {
			var agrees_status = 'False'
		};

		var data_key = "{'story':"+story_id+",'s':'"+embed_width+"','qlist':'"+quote_values+"','col':'"+embed_collapse+"','desc':'"+embed_description+
								"','sbg':'"+second_bg_embed+"','tbg':'"+third_bg_embed+"','c':'"+container_embed+
								"','quotei':'"+quote_info_status+"','a':'"+agrees_status+"','storyi':'"+story_info_status+
								"','font':'"+$(font_embed).val()+"','bg':'"+$(bg_embed).val()+"','border':'"+$(border_embed).val()+"','link':'"+$(link_embed).val()+"'}"

		var quotd_embed_container = '<div class="quotd_story_widget clearfix" data-key="'+data_key+
			'" style="width: '+embed_width+'px; height:'+embed_height+'px; margin: 0px 15px !important; padding: 5px !important; background-color:'+$(bg_embed).val()+'; color: '+$(font_embed).val()+
			'; border: 1px solid '+$(border_embed).val()+';" rel="'+story_id+'"></div><br />';

		return quotd_embed_container + script_code
	};
	$('.quotd_question_description embed, .quotd_question_description object').each(function(){
				$(this).attr('width','500').attr('height', $(this).height()*(500/$(this).width()));
	});
	$('.quotd_embed_question_description embed, .quotd_embed_question_description object, .quotd_embed_question_description img').each(function(){
				$(this).attr('width',$(this).attr('width')*.2).attr('height', $(this).height()*.2);
	});
	$('.quotd_question_description').jScrollPane();
	$('.quotd_question_answers_collection:visible').jScrollPane();
	$('.embed_tumblr_logo').click(function(){
		var new_url = $(this).attr('href')+'&s='+$.URLEncode($($(this).attr('rel')).val());
		window.open(new_url, '', 'width=450,height=450');
		return false;
	});
  	function formatCollection(row) {
      return row.title;
  	};
	var coll_url = "/json/jquery/collection_search/";
	$('.collection_name').each(function(){
		var autoelement = this;
		$(this).autocomplete({
			source: function(request, response){
				$.ajax({
					url: coll_url,
					dataType: 'jsonp',
					data: {q: request.term},
					success: function(data){
						response($.map( data.results, function(item){
							return {
								label: item.title,
								value: item.id,
								answers: item.answers,
								type: item.type
							}
						}))					
					},
				
				})
			},
			minLength: 2,
			focus: function(event, ui){
				$(autoelement).val(ui.item.label);
				return false;
			},
			select: function(event, ui){
				$(autoelement).val(ui.item.label);
	    		$(autoelement).siblings('.collection').attr('value', ui.item.value);
	    		$(autoelement).siblings('.tweet').slideUp('fast');
	    		$(autoelement).siblings('.answer').slideUp('fast');
	    		if (ui.item.type == 'question')
	        		{
	          			var i=0;
	          			$(autoelement).siblings('.answer').find('option').remove().end();
	          			var ans_list = ui.item.answers;
	          			for (i=0; i < ans_list.length; i++){
							var new_option = "<option value='"+ans_list[i].id+"'>"+ans_list[i].response+"</option>";
							$(autoelement).siblings('.answer').append(new_option);
					    }
		   				$(autoelement).siblings('.answer').slideDown('fast');
	       			};
	       		if (ui.item.type == 'feed'){          
	         		$(autoelement).siblings('.tweet').slideDown('fast');
				}

				return false;
			}
		});
	});
	$('.tweet').maxlength({slider: true, statusClass: "tweettext_status", maxCharacters: 120});
	$('.agree_selector').click(function(event){
		var self = $(this).children('.ratings_ctrl_holder').children('.rating_ctrls_item_anchor');
		var other = $(this).next().children('.ratings_ctrl_holder').children('.rating_ctrls_item_anchor');
		$.ajax({
			type: 'POST',
			dataType:'json',
			url: $(this).attr('rel'),
			success: function(json, status){
				var disagree_text = json.rating.disagree;
				var agree_text = json.rating.agree;
				$(self).text(agree_text);
				$(other).text(disagree_text);
			}
		});
		$(this).removeClass('agree_container').addClass('agree_container_selected');
		$(this).next().removeClass('disagree_container_selected').addClass('disagree_container');
	});
	$('.disagree_selector').click(function(event){
		var self = $(this).children('.ratings_ctrl_holder').children('.rating_ctrls_item_anchor');
		var other = $(this).prev().children('.ratings_ctrl_holder').children('.rating_ctrls_item_anchor');
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: $(this).attr('rel'),
			success: function(json, status){
				var agree_text = json.rating.agree;
				var disagree_text = json.rating.disagree;
				$(self).text(disagree_text);
				$(other).text(agree_text);
			}
		});
		$(this).removeClass('disagree_container').addClass('disagree_container_selected');		
		$(this).prev().removeClass('agree_container_selected').addClass('agree_container');
	});
	$('.connect_tool').submit(function () {
		var el = this;
		if ($(this).siblings('.tweet').val() == 'Add tweet text here'){
			$(this).siblings('.tweet').attr('value', '');
		}

    	var disableSubmit = function(val){
        	$('.connect_tool', this).attr('disabled', val);
    			};

		$.ajax({
			url: $(this).attr('action'),
			type: 'POST',
			contentType: "application/json; charset=utf-8",
			dataType: 'json',
			context: $(this),
			data: {	'collection': $('.collection', this).val(),
					'answer': $('.answer', this).val(),
					'tweet': $('.tweet', this).val()
			},
			success: function(json, status){
				var msg = json.msg;
				$('.connect_tool__message', this).removeClass().html(msg).fadeIn('slow');
				disableSubmit(false);
				$('.answer', this).slideUp('fast');
				$('.collection_name', this).slideUp('fast');
				$('.quotd__submit', this).slideUp('fast');
				if (json.type == 'success'){
					$(this).clearForm();
				}
			},
			error: function(xhr, textStatus, errorThrown){
				$('.connect_tool__message', this).hide();
				$('.connect_tool__message', this).removeClass().addClass('error').html(textStatus).fadeIn('slow');
			}
		});
		return false;
	});
	$('.collection_name').addClass("idleField");
    $('.collection_name').focus(function() {
	$(this).removeClass("idleField").addClass("focusField");
        if (this.value == this.defaultValue){
        	this.value = '';
    	}
        if(this.value != this.defaultValue){
	    	this.select();
        }
    });
    $('.collection_name').blur(function() {
    	$(this).removeClass("focusField").addClass("idleField");
        if ($.trim(this.value == '')){
        	this.value = (this.defaultValue ? this.defaultValue : '');
    	}
    });
	$('.connection_prompt').click(function(){
		$(this).siblings('.connection_holder').slideDown('fast');
		$(this).slideUp('fast');
	});
	$('.custom_embed').blur(function(){
		$(this).attr('rel', $(this).val());
	});
	$('.custom_embed').focus(function(){
		custom_quote_id = $(this).parent().attr('id').split('_')[0];
		$(this).bind('keyup', function (e) {
			$(this).attr('rel', $(this).val());
			var new_code = create_embed_code(custom_quote_id);
			$(textarea_embed).val(new_code);
		});
	});

	jQuery.copy=function(data){return jQuery.fn.copy.call({},data);};jQuery.fn.copy=function(delimiter){var self=this,flashcopier=(function(fid){return document.getElementById(fid)||(function(){var divnode=document.createElement('div');divnode.id=fid;document.body.appendChild(divnode);return divnode;})();})('_flash_copier'),data=jQuery.map(self,function(bit){return typeof bit==='object'? bit.value||bit.innerHTML.replace(/<.+>/g,''):'';}).join(delimiter||'').replace(/^\s+|\s+$/g,'')||delimiter,divinfo='<embed src="http://media.quotd.com/js/jquery.copy.swf"FlashVars="clipboard='+encodeURIComponent(data)+'"width="0"height="0"'+'type="application/x-shockwave-flash"></embed>';flashcopier.innerHTML=divinfo;return self;};	
	var HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if (s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} 
				else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
	};
	var RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			};
	var HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			};


	$('.connect_container').click(function(){
		connect_container = $(this).attr('rel');
		if ($(connect_container).is(":visible")){
			$(connect_container).slideUp('fast');
		}
		else {
			$(connect_container).slideDown('fast');
		}
	});
	$('.question_embed_prompt').click(function(){

			question_id = $(this).attr('rel');

			textarea_embed = '#'+question_id + '_question_embed_code';

			embed_code = create_embed_question_code(question_id);

			$(textarea_embed).val(embed_code);
			
			embed_code_wrapper = '#'+question_id+'_embed_holder'
			
			if ($(embed_code_wrapper).is(":visible")){
					$(embed_code_wrapper).slideUp('fast');
			}
			else {
					$(embed_code_wrapper).slideDown('fast');					
			}
	});

	$('.story_embed_prompt').click(function(){

			question_id = $(this).attr('rel');

			textarea_embed = '#'+question_id + '_question_embed_code';

			embed_code = create_embed_story_code(question_id);

			$(textarea_embed).val(embed_code);
			
			embed_code_wrapper = '#'+question_id+'_embed_holder'
			
			if ($(embed_code_wrapper).is(":visible")){
					$(embed_code_wrapper).slideUp('fast');
			}
			else {
					$(embed_code_wrapper).slideDown('fast');					
			}
	});



	$('.embed_prompt').click(function(){

			quote_id = $(this).attr('rel');

			textarea_embed = '#'+quote_id + '_embed_code';

			embed_code = create_embed_code(quote_id);

			$(textarea_embed).val(embed_code);
			if ($(this).parent().parent().parent().siblings('.embed_wrapper').is(":visible")){
					$(this).parent().parent().parent().siblings('.embed_wrapper').slideUp('fast');
			}
			else {
					$(this).parent().parent().parent().siblings('.embed_wrapper').slideDown('fast');					
			}
	});
	$('.embed_close_tool, .embed_question_close_tool').click(function(){
			$(this).parent().parent().slideUp('fast');
	});

	$('.close_tool').click(function(){
			$(this).parent().slideUp('fast');
	});

	$('.embed_collapsed').click(function(){
		var quest_id = $(this).attr('id').split('_')[0];
		var small_size_holder = '#'+quest_id+'_embed_size_small';
		var med_size_holder = '#'+quest_id+'_embed_size_med';
		var large_size_holder = '#'+quest_id+'_embed_size_large';
		var custom_size_holder = '#'+quest_id+'_embed_size_custom';

		var desc_arrow = '#'+quest_id+'_desc_arrow';
		var quotes_arrow = '#'+quest_id+'_quotes_arrow';

		$(small_size_holder).html('400x100');
		$(med_size_holder).html('500x125');
		$(large_size_holder).html('600x150');
		$(desc_arrow).attr('src', 'http://media.quotd.com/img/right_arrow.png')
		$(quotes_arrow).attr('src', 'http://media.quotd.com/img/right_arrow.png')
		
		var hide_list = $(this).attr('rel');
		$(hide_list).slideUp('fast');

		var quest_id = $(this).attr('id').split('_')[0];
		var collection_type = $('#'+quest_id+'_embed_holder').attr('data-collection-type');
		if (collection_type=='question'){
			var new_embed_code = create_embed_question_code(quest_id);
		};
		if (collection_type=='story'){
			var new_embed_code = create_embed_story_code(quest_id);
		};
		var textarea_embed = '#'+quest_id + '_question_embed_code';
		$(textarea_embed).val(new_embed_code);

		
	})
	$('.embed_expanded').click(function(){
		var quest_id = $(this).attr('id').split('_')[0];
		var small_size_holder = '#'+quest_id+'_embed_size_small';
		var med_size_holder = '#'+quest_id+'_embed_size_med';
		var large_size_holder = '#'+quest_id+'_embed_size_large';
		var custom_size_holder = '#'+quest_id+'_embed_size_custom';

		var desc_arrow = '#'+quest_id+'_desc_arrow';
		var quotes_arrow = '#'+quest_id+'_quotes_arrow';

		$(small_size_holder).html('400x440');
		$(med_size_holder).html('500x550');
		$(large_size_holder).html('600x660');
		$(desc_arrow).attr('src', 'http://media.quotd.com/img/down_arrow.png')
		$(quotes_arrow).attr('src', 'http://media.quotd.com/img/down_arrow.png')

		var show_list = $(this).attr('rel');
		$(show_list).slideDown('fast');

		var quest_id = $(this).attr('id').split('_')[0];
		var collection_type = $('#'+quest_id+'_embed_holder').attr('data-collection-type');
		if (collection_type=='question'){
			var new_embed_code = create_embed_question_code(quest_id);
		};
		if (collection_type=='story'){
			var new_embed_code = create_embed_story_code(quest_id);
		};
		var textarea_embed = '#'+quest_id + '_question_embed_code';
		$(textarea_embed).val(new_embed_code);
	})
	$('.embed_checkbox').click(function(){
			if ($(this).is(':checked')){
				headline_id = $(this).attr('rel');
				$(headline_id).show();
				if ($(this).hasClass('embed_headline')){
					$(this).siblings('.embed_headline_txt').removeAttr('disabled');
				}
				}
			else {
				headline_id = $(this).attr('rel');
				$(headline_id).hide();								
				if ($(this).hasClass('embed_headline')){
					$(this).siblings('.embed_headline_txt').attr('disabled', true);
				}
				}
			var quote_id = headline_id.split('_')[0].split('#')[1];
			var new_embed_code = create_embed_code(quote_id);
			var textarea_embed = '#'+quote_id + '_embed_code';
			$(textarea_embed).val(new_embed_code);	
	});
	$('.embed_question_checkbox').click(function(){
			if ($(this).is(':checked')){
				headline_id = $(this).attr('rel');
				$(headline_id).show();
				}
			else {
				headline_id = $(this).attr('rel');
				$(headline_id).hide();								
				}
			var quest_id = headline_id.split('_')[0].split('#')[1];
			var collection_type = $('#'+quest_id+'_embed_holder').attr('data-collection-type');
			if (collection_type=='question'){
				var new_embed_code = create_embed_question_code(quest_id);
			};
			if (collection_type=='story'){
				var new_embed_code = create_embed_story_code(quest_id);
			};
			var textarea_embed = '#'+quest_id + '_question_embed_code';
			$(textarea_embed).val(new_embed_code);	
	});

	$('.embed_control_size').click(function(){
			$('.embed_control_size').css('background-color', 'white')
			$(this).css('background-color', '#e37400');
			headline_el = $(this).parent().attr('id');
			var quote_id = headline_el.split('_')[0];
			var new_code = create_embed_code(quote_id);
			$(textarea_embed).val(new_code);
	});
	$('.embed_control_question_size').click(function(){
			$('.embed_control_question_size').css('background-color', 'white');
			$('.embed_control_input .embed_control_question_size_selected').removeClass('embed_control_question_size_selected');
			$(this).addClass('embed_control_question_size_selected');
			$(this).css('background-color', '#e37400');
			headline_el = $(this).parent().attr('id');
			var quest_id = headline_el.split('_')[0];
			var collection_type = $('#'+quest_id+'_embed_holder').attr('data-collection-type');
			if (collection_type=='question'){
				var new_embed_code = create_embed_question_code(quest_id);
			};
			if (collection_type=='story'){
				var new_embed_code = create_embed_story_code(quest_id);
			};
			var textarea_embed = '#'+quest_id + '_question_embed_code';
			$(textarea_embed).val(new_embed_code);
	});

	$('.quotd_embed_answer_headline_holder').click(function(){
		quest_id = $(this).parent().attr('rel');
		var preview_container = '#'+quest_id+'_embed_preview';
		bg_color = $(preview_container).attr('data-bg-color');
		second_bg_color = $(preview_container).attr('data-second-bg-color');
		
		ans_id = $(this).attr('rel');
		quote_id = $(this).parent().attr('rel');
		$(this).parent().find('.quotd_embed_answer_headline_holder').css('background-color', second_bg_color).css('border-bottom', '1px solid black').removeClass('.quotd_embed_answer_selected');
		$(this).css('background-color', bg_color).css('border-bottom', '1px solid '+bg_color).addClass('quotd_embed_answer_selected');
		answer_holder = '#'+quote_id+'_embed_answers_holder .quotd_embed_answers_collection';
		revealed_answers = '#'+ans_id+'_quotd_answer_container';
		$(answer_holder).slideUp('fast');
		$(revealed_answers).slideDown('fast');
	});

	$('.quotd_answer_exclusion_set').click(function(){
		ans_id = $(this).attr('rel');
		question_id = $(this).parent().parent().attr('rel');
		$(this).parent().find('.quotd_answer_exclusion_set').css('border-bottom', '');
		if ($(this).css('background-color')=='rgb(170, 170, 170)'){
			$(this).css('border-bottom', '1px solid #AAAAAA');
		}
		else {
			$(this).css('border-bottom', '1px solid white');
		}
		answer_holder = '#'+question_id+'_embed_question_quote_exclusion .quotd_answer_quote_exclusion';
		revealed_answers = '#'+ans_id+'_answer_quote_list';
		$(answer_holder).slideUp('fast');
		$(revealed_answers).slideDown('fast');
	});

	jQuery.extend(jQuery.expr[':'], {
		unchecked: function(element) {
			return ('checkbox' === element.type || 'radio' === element.type) && !element.checked;
		}
	});
	
	$('.quotd_quote_exclusion_input').click(function(){

		quote_id = $(this).attr('rel');
		embed_quote = '#'+quote_id+'_quotd_embed_quote_preview';
		
		quest_id = $(this).parent().attr('rel');
		var preview_container = '#'+quest_id+'_embed_preview';
		bg_color = $(preview_container).attr('data-bg-color');
		second_bg_color = $(preview_container).attr('data-second-bg-color');		
		

		if ($(this).is(':checked')){
			$(this).parent().parent().css('background-color', bg_color);
			if ($(embed_quote).attr('data-status-view')=='removed'){
				$(embed_quote).attr('style', 'display:block;').attr('data-status-view', 'included');
			}
		}		

		else {
			$(this).parent().parent().css('background-color', second_bg_color);
			if ($(embed_quote).attr('data-status-view')=='included'){
				$(embed_quote).attr('style', 'display:none;').attr('data-status-view', 'removed');
			}
		};

		var exclude_text = '';
		if ($('.quotd_answer_exclusion_input:unchecked').size()){
			var answers_excluded = $('.quotd_answer_exclusion_input:unchecked').size();
		}
		else {
			var answers_excluded = 0;
		};
		
		if ($('.quotd_quote_exclusion_input:unchecked').size()){
			var quotes_excluded = $('.quotd_quote_exclusion_input:unchecked').size();
		}
		
		else {
			var quotes_excluded = 0;
		}

		if (quotes_excluded > 1 && answers_excluded > 1){
			var exclude_text = answers_excluded +' answers and '+quotes_excluded + ' quotes excluded';
		}
		else if (quotes_excluded > 1 && answers_excluded==0){
			var exclude_text = quotes_excluded + ' quotes excluded';
		}

		else if (quotes_excluded > 1 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer and '+quotes_excluded + ' quotes excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded > 1){
			var exclude_text = answers_excluded +' answers and '+quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer and '+quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded==0){
			var exclude_text = quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 0 && answers_excluded>1){
			var exclude_text = answers_excluded +' answers excluded';
		}

		else if (quotes_excluded == 0 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer excluded';
		}		
		
		else {
			var exclude_text = 'No quotes or answers excluded yet';
		};
		
		quest_txt = '#'+quest_id + '_embed_checkbox_remove';
		$(quest_txt).html(exclude_text);		
	});
	$('.quotd_answer_quote_exclusion').sortable({
		stop: function(event, ui){
			var result = $(this).sortable('toArray');
			var item_array = new Array();
			var insert_item = '#'+result[0]+'_quotd_embed_quote_preview';
			item_array = $.grep(result, function(value){
				return value !=result[0];
			});
			$.each(item_array, function() {
				new_insert_item = '#'+this+'_quotd_embed_quote_preview';
				$(new_insert_item).insertAfter($(insert_item));
				insert_item=new_insert_item;
			});
		}
	});
	$('.quotd_answer_exclusion_holder').sortable({
		stop: function(event, ui){
			var result = $(this).sortable('toArray');
			var item_array = new Array();
			var insert_item = '#'+result[0].split('_')[0]+'_quotd_embed_answer_headline_holder';
			item_array = $.grep(result, function(value){
				return value !=result[0];
			});
			$.each(item_array, function() {
				new_insert_item = '#'+this.split('_')[0]+'_quotd_embed_answer_headline_holder';
				$(new_insert_item).insertAfter($(insert_item));
				insert_item=new_insert_item;
			});
		}
	});
	$('.quotd_answer_exclusion_input').click(function(){
		ans_id = $(this).attr('rel');
		ans_related_inputs = '#'+ans_id+'_answer_quote_list .quotd_quote_exclusion_input';
		embed_ans_related_input = '#'+ans_id+'_quotd_answer_container';
		embed_ans_header = '#'+ans_id+'_quotd_embed_answer_headline_holder';
		quest_id = $(this).parent().parent().parent().parent().attr('rel');
		var preview_container = '#'+quest_id+'_embed_preview';
		bg_color = $(preview_container).attr('data-bg-color');
		second_bg_color = $(preview_container).attr('data-second-bg-color');
		
		if ($(this).is(':checked')){
			new_bottom_color = '1px solid '+bg_color +' !important';
			$(this).parent().parent().parent().css('background-color', bg_color).css('border-bottom', new_bottom_color);
			$(ans_related_inputs).attr('checked', true).removeAttr('disabled').parent().parent().css('background-color', bg_color);
			$(embed_ans_related_input).attr('data-view-status','included');
			if ($(embed_ans_header).is(':hidden')){
				$(embed_ans_header).slideDown('fast');
			}
		}		
		else {
			new_bottom_color = '1px solid '+second_bg_color +' !important';			
			$(this).parent().parent().parent().css('background-color', second_bg_color).css('border-bottom', new_bottom_color);
			$(ans_related_inputs).attr('checked', false).attr('disabled', true).parent().parent().css('background-color', second_bg_color);			
			$(embed_ans_related_input).attr('data-view-status','removed').slideUp('fast');
			$(embed_ans_related_input).siblings("div[data-view-status='included'] div:hidden").first().slideDown('fast');
			if ($(embed_ans_header).is(':visible')){
				$(embed_ans_header).slideUp('fast');
			}
		};
		var exclude_text = '';
		if ($('.quotd_answer_exclusion_input:unchecked').size()){
			var answers_excluded = $('.quotd_answer_exclusion_input:unchecked').size();
		}
		else {
			var answers_excluded = 0;
		};
		
		if ($('.quotd_quote_exclusion_input:unchecked').size()){
			var quotes_excluded = $('.quotd_quote_exclusion_input:unchecked').size();
		}
		
		else {
			var quotes_excluded = 0;
		}

		if (quotes_excluded > 1 && answers_excluded > 1){
			var exclude_text = answers_excluded +' answers and '+quotes_excluded + ' quotes excluded';
		}
		else if (quotes_excluded > 1 && answers_excluded==0){
			var exclude_text = quotes_excluded + ' quotes excluded';
		}

		else if (quotes_excluded > 1 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer and '+quotes_excluded + ' quotes excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded > 1){
			var exclude_text = answers_excluded +' answers and '+quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer and '+quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 1 && answers_excluded==0){
			var exclude_text = quotes_excluded + ' quote excluded';
		}

		else if (quotes_excluded == 0 && answers_excluded>1){
			var exclude_text = answers_excluded +' answers excluded';
		}

		else if (quotes_excluded == 0 && answers_excluded==1){
			var exclude_text = answers_excluded +' answer excluded';
		}		
		
		else {
			var exclude_text = 'No quotes or answers excluded yet';
		};
		question_id = $(this).parent().parent().parent().parent().parent().attr('rel');
		quest_txt = '#'+question_id + '_embed_checkbox_remove';
		$(quest_txt).html(exclude_text);
	});
	$('.embed_color_input_question').ColorPicker({
			onSubmit: function(hsb, hex, rgb, el) {
				hex_value ='#'+hex;
				$(el).val(hex_value);
				$(el).siblings('.embed_color_preview').css('background-color', hex_value);

				color_type = $(el).siblings('.embed_color_name').html();
				var question_id = $(el).attr('id').split('_')[0];
				var preview_container = '#'+question_id+'_embed_preview';
				

				if (color_type =='BG'){
					second_hsb= {h:hsb.h, s:hsb.s, b:Math.round((hsb.b-0)/2)};
					var second_hex = HSBToHex(second_hsb);

					third_hsb= {h:hsb.h, s:hsb.s, b:Math.round((hsb.b-0)/3)};
					var third_hex = HSBToHex(third_hsb);

					$(preview_container).attr('data-third-bg-color', '#'+third_hex);
					$(preview_container).attr('data-second-bg-color', '#'+second_hex);
					$(preview_container).attr('data-bg-color', hex_value);

					bg_selector = preview_container + ' .question_preview';
					$(bg_selector).css('background-color', hex_value);
					$('.quotd_embed_answer_headline_holder').css('background-color', '#'+second_hex);
					$('.quotd_embed_answer_selected').css('background-color', hex_value).css('border-bottom', '1px solid '+hex_value);					
				};
				if (color_type =='Font'){
					font_selector = preview_container + ' .question_preview';
					om_fonts = preview_container + '.embed_om_name_quote, .embed_om_occ_quote';
					$(font_selector).css('color', hex_value);
					$(om_fonts).css('color', hex_value);
				};
				if (color_type =='Border'){
					border_selector = preview_container + ' .question_preview';
					border_def = '1px solid '+hex_value;
					$(border_selector).css('border-color', border_def);						
				};		
				if (color_type =='Link'){
					ctype_selector = preview_container + ' .question_preview a';
					$(ctype_selector).css('color', hex_value);									
				};		
				var collection_type = $('#'+question_id+'_embed_holder').attr('data-collection-type');
				if (collection_type=='question'){
					var new_embed_code = create_embed_question_code(question_id);
				};
				if (collection_type=='story'){
					var new_embed_code = create_embed_story_code(question_id);
				};
				var textarea_embed = '#'+question_id + '_question_embed_code';
				$(textarea_embed).val(new_embed_code);	

				$(el).ColorPickerHide();
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
			}
		}).bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
	});
	$('.embed_color_input').ColorPicker({
			onSubmit: function(hsb, hex, rgb, el) {
				hex_value ='#'+hex;
				$(el).val(hex_value);
				$(el).siblings('.embed_color_preview').css('background-color', hex_value);

				color_type = $(el).siblings('.embed_color_name').html();
				var quote_id = $(el).attr('id').split('_')[0];
				var preview_container = '#'+quote_id+'_embed_preview';
				

				if (color_type =='BG'){
					bg_selector = preview_container + ' .quote_preview';
					$(bg_selector).css('background-color', hex_value);
				};
				if (color_type =='Font'){
					font_selector = preview_container + ' .quote_preview';
					om_fonts = preview_container + '.embed_om_name_quote, '+preview_container+' .embed_om_occ_quote, '+preview_container+' .embed_container_title';
					$(font_selector).css('color', hex_value);
					$(om_fonts).css('color', hex_value);
				};
				if (color_type =='Border'){
					border_selector = preview_container + ' .quote_preview';
					border_def = '1px solid '+hex_value;
					$(border_selector).css('border', border_def);						
				};		
				if (color_type =='Link'){
					ctype_selector = preview_container + ' .quote_preview a';
					$(ctype_selector).css('color', hex_value);									
				};		
				var new_embed_code = create_embed_code(quote_id);
				var textarea_embed = '#'+quote_id + '_embed_code';
				$(textarea_embed).val(new_embed_code);	

				$(el).ColorPickerHide();
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
			}
		}).bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
	});
	$('.embed_headline_txt').focus(function(){
			headline_el = $(this).attr('rel');
			var quote_id = headline_el.split('_')[0].split('#')[1];
			var textarea_embed = '#'+quote_id + '_embed_code';			
			$(this).bind('keyup', function (e) {
				$(headline_el).find('a').html($(this).val());
				var new_code = create_embed_code(quote_id);
				$(textarea_embed).val(new_code);
			})
	});
	$('.embed_control_input textarea').click(function(){
		$.copy($(this).text());
	});
	$('.quotd_embed_desc_arrow').click(function(){
		if ($(this).attr('src')=='http://media.quotd.com/img/right_arrow.png'){
			$(this).attr('src', 'http://media.quotd.com/img/down_arrow.png');
			var desc_holder = $(this).attr('rel');
			$(desc_holder).slideDown('fast');
		}
		else {
			$(this).attr('src', 'http://media.quotd.com/img/right_arrow.png');
			var desc_holder = $(this).attr('rel');
			$(desc_holder).slideUp('fast');			
		}
	});
	$('.quotd_embed_quotes_arrow').click(function(){
		if ($(this).attr('src')=='http://media.quotd.com/img/right_arrow.png'){
			$(this).attr('src', 'http://media.quotd.com/img/down_arrow.png');
			var desc_holder = $(this).attr('rel');
			$(desc_holder).slideDown('fast');
		}
		else {
			$(this).attr('src', 'http://media.quotd.com/img/right_arrow.png');
			var desc_holder = $(this).attr('rel');
			$(desc_holder).slideUp('fast');			
		}
	});
	$('.embed_checkbox_remove_content').click(function(){
			if ($(this).parent().siblings('.embed_question_quote_exclusion').is(":visible")){
					$(this).parent().siblings('.embed_question_quote_exclusion').slideUp('fast');
			}
			else {
					$(this).parent().siblings('.embed_question_quote_exclusion').slideDown('fast');					
			}
		
	});
	$('.quotd_answer_exclusion_close').click(function(){
		question_id = $(this).attr('rel');
		textarea_embed = '#'+question_id + '_question_embed_code';
		var collection_type = $('#'+question_id+'_embed_holder').attr('data-collection-type');
		if (collection_type=='question'){
			var embed_code = create_embed_question_code(question_id);
		};
		if (collection_type=='story'){
			var embed_code = create_embed_story_code(question_id);
		};
		$(textarea_embed).val(embed_code);
		$(this).parent().slideUp('fast');
	})
});
