/**
 * builder.js
 * 
 * All of the js that's required to get the builder working!
 */

$(document).ready( function() {
	if (typeof jQuery.SelectBox !== 'undefined') {
		$('#category').selectbox();
	}
	
	if ( $('#builder_form [name=source]').val()=='submit' ) {
		$('#teaser').click();
	}
	
	// Handle form submissions
	var extra_form_data = {
		'submitted' : 1,
		'caller'    : 'builder.js'
	}
	if ( window.self !== window.top ) { // temporary 'Potter' category for Valentine's 2012 - this is for iframe submissions only
		extra_form_data['category'] = 15;
	}
	var options = {
		'beforeSubmit' : function( data, jqForm, options ) {
			// Before sending submit data
			$('#ok').attr('disabled','disabled');
			$('#results').html("<img src='http://cdn.lxdcdn.net/images/loading.gif' alt='Loading' />").fadeIn();
			setCookie(data['username'], data['location'], data['email']);
		},
		'success' :	function( data ) {
			$('#ok').removeAttr('disabled');
			
			try { 
				var json = $.parseJSON(data);
				
				$('#results').load("/preview.php", json);
				$('#story_link').focus();

				// Complete
				if( json.success ) {
					$('#builder_collapse').slideUp(500, function(){
						var resPos = $('#results').position();
						if ( parseInt( resPos.top ) > 0 )
						{
							$(window).scrollTo( parseInt( resPos.top ), 750 );
						}
					});
					$('#builder_buttons').hide();
					$('#submit_again').fadeIn();
				}
				
				if ( json.captcha ) {
					$('#captcha_info').hide();
					$('#solvemedia').slideUp();
					$('#solved_captcha').val('1');
				}
				else if ( $('#smc').exists() ) {
					ACPuzzle.reload('');
				}
			}
			catch ( err ) {
				console.log(data);
				console.log(err);
			}
		},
		'data'     : extra_form_data,
		'url'      : '/submit.php',
		'type'     : 'post'
	};
	$('#builder_form').ajaxForm(options);
	
	
});

$('#teaser').live('click', function() {
	$('#teaser').fadeOut();
	
	if ( $('#smc').exists() ) {
		var ACPuzzleOptions = { tabindex: 1 };
		ACPuzzle.create( $('#smc').val(), 'solvemedia', ACPuzzleOptions );
	}
	
	if ( $('#story_tab').find(':checked').length ) {
		$('.story_tab_icon_active').show();
		$('.story_tab_text_active').show();
		$('.story_tab_icon_inactive').hide();
		$('.story_tab_text_inactive').hide();
		
		$('.upload_tab_icon_active').hide();
		$('.upload_tab_text_active').hide();
		$('.upload_tab_icon_inactive').show();
		$('.upload_tab_text_inactive').show();
	}
	else if ( $('#upload_tab').find(':checked').length ) {
		$('.story_tab_icon_active').hide();
		$('.story_tab_text_active').hide();
		$('.story_tab_icon_inactive').show();
		$('.story_tab_text_inactive').show();
		
		$('.upload_tab_icon_active').show();
		$('.upload_tab_text_active').show();
		$('.upload_tab_icon_inactive').hide();
		$('.upload_tab_text_inactive').hide();
	}
	
	restoreFromCookie();
	$('#builder').slideDown(); 
	$('#content').focus();

	var sp = $('#sp').val();
	$('#background').val($('#template').css('background-image'));
	$('.template_icon').each( function(index, item) {
		var image_src = sp + '/images/builder/templates/' + $(this).attr('id') + '.png';
		$(this).css('background-image', 'url("'+image_src+'")');
		$(this).css('background-position', '-5px -5px');
	});
});

$('#content').live('keydown keyup', function () {
	textCounter(this, 'counter', $(this).attr('maxlength'), 12);
});

$('.template_icon').live('click', function() {
	$('#template').css('background-image', $(this).css('background-image'));
	$('#background').val($('#template').css('background-image'));
});

$('.template_icon').live('mouseover', function() {
	$('#template').css('background-image', $(this).css('background-image'));
});


$('#carousel').live('mouseleave', function() {
	$('#template').css('background-image', $('#background').val());
});

/*
$('#carousel_bottom').live('click', function () {
	$('.concealed').toggle();
	$(this).toggleClass('up down');
	$('#carousel').height(Math.max($('#carousel ul').height()+2, 34));
});
*/

$('.minimize').live('click', function() {
	$('#content').blur();
	$('#builder').slideUp();
	$('#teaser').fadeIn();
	
	if ( $(this).attr('id')=='min' ) {
		custom_clear_form();
	}
});

$('#story_tab').live('click', function() {
	if ( !$('#story_tab').hasClass('active') ) {
		$('#results').hide();
		
		$('#upload_tab').removeClass('active');
		$('#story_tab').addClass('active');
		
		if ( $('.story_tab_icon_active').length ) { $('.story_tab_icon_active').show(); }
		$('.story_tab_text_active').show();
		if ( $('.story_tab_icon_inactive').length ) { $('.story_tab_icon_inactive').hide(); }
		$('.story_tab_text_inactive').hide();
		
		if ( $('.upload_tab_icon_active').length ) { $('.upload_tab_icon_active').hide(); }
		$('.upload_tab_text_active').hide();
		if ( $('.upload_tab_icon_inactive').length ) { $('.upload_tab_icon_inactive').show(); }
		$('.upload_tab_text_inactive').show();
		
		$('input[name=submit_type]:eq(0)').prop('checked', true);
		$('#upload_content').hide();

		var tmp = $('#upload_content').html();
		$('#upload_content').html($('#submit_info').html());
		$('#submit_info').html(tmp);
		$('#tips').show();
		
		$('#counter_container').show();
		$('#carousel').show();
		if ( $('#carousel_top').exists() ) { $('#carousel_top').show(); }
		if ( $('#carousel_bottom').exists() ) { $('#carousel_bottom').show(); }
		
		$('#story_content').show();
		$('#story_submit').val('1');
		
		if ( $('#smc').exists() ) { ACPuzzle.reload(''); }
	}
});

$('#upload_tab').live('click', function() {
	if ( !$('#upload_tab').hasClass('active') ) {
		$('#results').hide();
		
		$('#story_tab').removeClass('active');
		$('#upload_tab').addClass('active');
		
		if ( $('.story_tab_icon_active').length ) { $('.story_tab_icon_active').hide(); }
		$('.story_tab_text_active').hide();
		if ( $('.story_tab_icon_inactive').length ) { $('.story_tab_icon_inactive').show(); }
		$('.story_tab_text_inactive').show();
		
		if ( $('.upload_tab_icon_active') ) { $('.upload_tab_icon_active').show(); }
		$('.upload_tab_text_active').show();
		if ( $('.upload_tab_icon_inactive').length ) { $('.upload_tab_icon_inactive').hide(); }
		$('.upload_tab_text_inactive').hide();
		
		$('input[name=submit_type]:eq(1)').prop('checked', true);
		$('#story_content').hide();
		$('#carousel').hide();
		if ( $('#carousel_top').exists() ) { $('#carousel_top').hide(); }
		if ( $('#carousel_bottom').exists() ) { $('#carousel_bottom').hide(); }
		$('#counter_container').hide();
		
		$('#tips').hide();
		var tmp = $('#submit_info').html();
		$('#submit_info').html($('#upload_content').html());
		$('#upload_content').html(tmp);

		$('#upload_content').show();
		$('#upload_submit').val('1');
		
		if ( $('#smc').exists() ) { ACPuzzle.reload(''); }
	}
});

$('#again').live('click', function(e) {
	e.preventDefault();
	custom_clear_form();
	$('#builder_collapse').slideDown();
	$('#builder_buttons').show();
	$('#results').hide();
	$('#submit_again').hide();
});

$('#upload_button').live('click', function() {
	$('#upload_file').click();
});

$('#upload_file').live('change', function() {
	$('#upload_dest').html($('#upload_file').val());
});

$('#story_text, #story_link, #embed_code').live('click', function() {
	//select_text($(this).attr('id'));
});

$('#send').live('click', function() {
	// add a loading gif in the interim
	$('#loader').fadeIn('fast');
	$('#share_top_right').fadeOut('fast');
	
	var form_data = {
		'from' : $('#from').val(),
		'to'   : $('#to').val(),
		'link' : $('#story_link').val()
	};
	
	$.ajax({
		'url'      : 'email_form.php',
		'data'     : form_data,
		'dataType' : 'html',
		'success'  : function(data) {
			try {
				var json = $.parseJSON(data);
				
				if ( json.success ) {
					$('#share_top_right .error').html('');
					$('#share_top_right .error').parent().hide();
					$('#share_top_right .success').html('Email Sent!');
					$('#share_top_right .success').parent().show();
					$('#to').parent().parent().hide();
					$('#send').hide();
				}
				else {
					$('#share_top_right .error').html('<b>Error</b><br>'+json.message);
					$('#share_top_right .error').parent().show();
				}
			}
			catch (err) {
				$('#share_top_right .error').html('There was an error sending the email');
				$('#share_top_right .error').parent().show();
			}
			
			$('#share_top_right').fadeIn('fast');
			$('#loader').fadeOut('fast');
		}
	});
});

function custom_clear_form() {
	$('#content').val('');
	$('#counter').html('350');
	$("#category option[selected]").removeAttr('selected');
	$("#category option[value='0']").attr('selected', 'selected');
	$('#category_input').val('Category (required)');
	$('#upload_file').val('');
	$('#upload_url').val('http://');
	$('#upload_dest').html('');
	$('#headline').val('Title');
	$('#story_tab').click();
	
	if ( $('#smc').exists() ) {
		$('#captcha_info').show();
		$('#solvemedia').show();
		$('#solved_captcha').val('0');
		
		var ACPuzzleOptions = { tabindex: 1 };
		ACPuzzle.create( $('#smc').val(), 'solvemedia', ACPuzzleOptions );
	}
}

