var timeouts = {};
var searchWait = 300;

$(document).ready(function()
{
	// Site Wide Misc
	$('.autogrow').autoGrowInput();
	$('.autoresize').autoResize({});
	$('.fancybox').fancybox();
	$('.fancyframe').fancybox({type: 'iframe'});
	$('.uploadify').uploadify({
		'uploader'  : '/uploadify/uploadify.swf',
		'script'    : '/ajax/media/upload',
		'scriptData': {
	    	phpSessionId	: $('#phpSessionId').val(),
	    	token			: $('#token').val(),
	    	limit			: $('#limit').val(),
	    	process			: 'upload'
		},
	    'buttonImg' : '/images/changepic.png',
	    'cancelImg' : '/uploadify/cancel.png',
	    'auto'      : true,
	    'multi'		: true,
	    'width'		: '100%',
	    'onComplete': showUploadPreview
	});
	$('.date-field').datepicker({
		timeFormat: 'h:mm'
	});
	$('.date-picker').datepicker({
	});
	
	$('.auto-value').live('focus', removeTitle);
	$('.auto-value').live('blur', addTitle);
        
	$('#blackout').live('click', deBlackoutClick);
	
	$('.auto-next').each(function() {
		$(this).attr('oldValue', $(this).val());
	});
	$('.auto-next').live('keyup', checkForNext);
	
	$('a.close-msg').live('click', closeMessage);
	
	$('.ck-basic').ckeditor({
		'toolbar': [
			['Cut','Copy','Paste', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','TextColor','BGColor','-','Maximize'],
			['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', '-', 'Undo','Redo','-','Find','Replace','-','SelectAll', 'Image','Table','HorizontalRule','SpecialChar'],
                        ['Source']
		]
	});
	
	$('.search-tabs').live('click', changeTab);
        
        // Package stuff
        $('#create-package').live('click', createPackage);
        $('.edit_package').live('click', editPackage);
        $('.toggle-featured').live('change', toggleFeaturedOptions);
        $('.toggle-leads').live('change', toggleLeadsOptions);
        $('.toggle-start-date').live('change', toggleStartDateField);
        $('.toggle-recurring').live('change', toggleRecurringField);
        
        $('.toggle-featured').each(toggleFeaturedOptions);
        $('.toggle-leads').each(toggleLeadsOptions);
        $('.toggle-start-date').each(toggleStartDateField);
        $('.toggle-recurring').each(toggleRecurringField);
});

function createPackage()
{
    $('#create-package-form').show();
    $('#create-package').hide();
}

function editPackage()
{
    var id = $(this).attr('data-id');
    $('.edit-package-form[data-id=' + id + ']').show();
    return false;
}


function toggleFeaturedLeadsOptions(id)
{
    if($('.toggle-featured[data-id=' + id + ']').is(':checked') && $('.toggle-leads[data-id=' + id + ']').is(':checked')) {
        $('.require-featured-leads[data-id=' + id + ']').show();
    } else {
        $('.require-featured-leads[data-id=' + id + ']').hide();
    }
}

function toggleFeaturedOptions()
{
    var id = $(this).attr('data-id');
    if($('.toggle-featured[data-id=' + id + ']').is(':checked')) {
        $('.require-featured[data-id=' + id + ']').show();
    } else {
        $('.require-featured[data-id=' + id + ']').hide();
    }
    
    toggleFeaturedLeadsOptions(id);
}

function toggleLeadsOptions()
{
    var id = $(this).attr('data-id');
    if($('.toggle-leads[data-id=' + id + ']').is(':checked')) {
        $('.require-leads[data-id=' + id + ']').show();
    } else {
        $('.require-leads[data-id=' + id + ']').hide();
    }
    
    toggleFeaturedLeadsOptions(id);
}

function toggleStartDateField()
{
    var id = $(this).attr('data-id');
    if($('.toggle-start-date[data-id=' + id + ']').is(':checked')) {
        $('.require-start-date[data-id=' + id + ']').show();
    } else {
        $('.require-start-date[data-id=' + id + ']').hide();
    }
}

function toggleRecurringField()
{
    var id = $(this).attr('data-id');
    if($('.toggle-recurring[data-id=' + id + ']').is(':checked')) {
        $('.require-non-recurring[data-id=' + id + ']').hide();
    } else {
        $('.require-non-recurring[data-id=' + id + ']').show();
    }
}

function changeTab()
{
	var target = $(this).attr('data-target');
	
	$('.search-tabs').find('.color').removeClass('color');
	$(this).find('span').addClass('color');
	$('.on').removeClass('on').addClass('color-bg');
	$(this).parent().addClass('on');
	
	$('.target').val(0);
        $('#' + target).val(1);
	
	return false;
}

function checkForNext()
{
	var text = $(this).val();
	var maxlength = $(this).attr('maxlength');
	var group = $(this).attr('data-autoGroup');
	var old = $(this).attr('oldValue');
	
	if (old == text)
		return false;
	$(this).attr('oldValue', text);
	if(text.length == maxlength) $(this).next('[data-autoGroup=' + group + ']').focus();
}

function removeTitle()
{
	var val = $(this).val();
	var defaultValue = $(this).attr('default');
	if(val == defaultValue) $(this).val('');
}

function addTitle()
{
	var val = $(this).val();
	var defaultValue = $(this).attr('default');
	if(!val) $(this).val(defaultValue);
}

function blackout(above, sticky)
{
	$('#blackout').show();
	if(above) above.addClass('aboveBlackout').addClass(sticky ? 'sticky' : '');
}

function deBlackoutClick()
{
    deBlackout();
}

function deBlackout(unstick)
{
    if(!$('.aboveBlackout').hasClass('sticky') || unstick)
    {
	$('#blackout').hide();
	$('.aboveBlackout').removeClass('aboveBlackout');
    }
}

function log(text)
{
	if(typeof console === "undefined") {
	    return;
	}
	console.log(text);
}

function parseAnchor()
{
	var hash = window.location.hash.split('#')[1];
	var data = {};
	var tmp;

	while(hash)
	{
		tmp = hash.split(';')[0].split('=');
		data[tmp[0]] = tmp[1];
		hash = hash.split(';')[1];
	}

	return data;
}

function showUploadPreview(event, ID, fileObj, response, data)
{
	response = $.parseJSON(response);
	if(!response.error)
	{
		var template = $('#upload-previews').find('#template').clone();
		if(response.limit && ($('#upload-previews').children('.upload-thumb').length >= response.limit))
		{
			$('#upload-previews').children('.upload-thumb:first').remove();
		}
		template.attr('id', '');
		template.addClass('upload-thumb');
		template.find('img').attr('src', response.file);
		template.find('input').val(response.name);
		template.appendTo('#upload-previews').show();
	}
}

function searchTimeout(id, functionName)
{
	clearTimeout(timeouts[id]);
	timeouts[id] = setTimeout(functionName, searchWait);
}

function closeMessage()
{
	$(this).parents('.error-msg').fadeOut(500, function() { $(this).remove(); });
	$(this).parents('.warning-msg').fadeOut(500, function() { $(this).remove(); });
	$(this).parents('.success-msg').fadeOut(500, function() { $(this).remove(); });
	$(this).parents('.info-msg').fadeOut(500, function() { $(this).remove(); });
	return false;
}
