$(function(){
    
    $('a.remove-survey').click(function() {
    var confirmDelete = confirm("Are you sure you want to delete " + $(this).attr('title') + "?");
           
           if (!confirmDelete) {
               return false;
           } else {
               window.location.href = $(this).attr('href');
               return false;
           }
    });
    
        $('#add-multiple-choice-question').click(function() {
            var surveyId = $('form#update-survey-form').attr('action').match(/[0-9]+$/);
            
            $.ajax({
                url: '/admin/survey/generate-question/' + surveyId,
                async: false,
                success: function(resp) {
                    $('#question-fields').append(resp);
                }
            })
        });
        
        $('#remove-field').live('click', function() {
            var eleObj     = $(this);
            var questionId = String($(this).next('.question-field').
                                        attr('name').
                                        match(/\[[0-9]+\]$/));
                                    
            questionId = questionId.replace('[', '');
            questionId = questionId.replace(']', '');
            
            $.ajax({
                url: '/admin/survey/delete-question/' + questionId,
                type: 'GET',
                async: false,
                success: function(resp) {
                    eleObj.parent('.question-misc').remove();
                    eleObj.remove();
                }
            });
        });
        
        
        $('#add-choice').live('click', function() {
            var parentQuestionArrayKey = $(this).
                                            parent('.question-misc').
                                            find('input.question-field').
                                            attr('name').
                                            match(/[0-9]{1,2}/);
                                        
            var choiceField = '<div class="choice-misc">' + 
			      '<input type="text" class="choice-field" name="choices[new][' + parentQuestionArrayKey + '][]" style="margin-left:25px;float:left;" />' + 
                              '<div class="ui-icon ui-icon-minus" id="remove-choice-field" title="Delete Option"></div>' +
	                      '<div style="clear:both;"></div>' + 
		              '</div>';
	
                          
            $(this).parent('.question-misc').append(choiceField);
        });
        
        $('#remove-choice-field').live('click', function() {
            var eleObj     = $(this);
            var choiceId = String($(this).prev('.choice-field').
                                            attr('name').
                                            match(/\[[0-9]+\]$/));
                                    
            choiceId = choiceId.replace('[', '');
            choiceId = choiceId.replace(']', '');
            
            $.ajax({
                url: '/admin/survey/delete-answer/' + choiceId,
                type: 'GET',
                async: false,
                success: function(resp) {
                    eleObj.parent('.choice-misc').remove();
                    eleObj.remove();
                }
            });
        });

	$('#password').focus(function() {
		this.type = 'password';	
	});
     
        $('#email_template_switcher').change(function() {
            var selectedOption = $('#email_template_switcher option:selected');
            var selectedOptId  = $(selectedOption).val();

            if ($(this).hasClass('blank')) { // switcher on blank email page
		if (selectedOptId == 'Select a Template') {
		    $('#new_email_form').load('/admin/email/blank #new_email_form', function() {

		    tinyMCE.init({
                        mode : "specific_textareas",
                        plugins : "heading, paste",
                        elements : "message, content, ajaxfilemanager",
                        editor_selector : "content",
                        theme : "advanced",
                        theme_advanced_toolbar_location : "top",
                        theme_advanced_buttons1_add_before : "formatselect",
                        theme_advanced_buttons1 : "bold,italic,underline,h,pasteword",
                        theme_advanced_buttons3 : ""
                    });
                    });

		    return;
		}

                $('#new_email_form').load('/admin/email-templates/modify/' + selectedOptId + ' #modify-form', function() {
                    $('#new_email_form p:first').remove();
                    $('#new_email_form hr').remove();
                    
                    $('input[name="email_subject"]').attr('name', 'subject');
                    $('textarea[name="email_content"]').attr('name', 'email_message');

                    tinyMCE.init({
                        mode : "specific_textareas",
                        plugins : "heading, paste",
                        elements : "message, content, ajaxfilemanager",
                        editor_selector : "content",
                        theme : "advanced",
                        theme_advanced_toolbar_location : "top",
                        theme_advanced_buttons1_add_before : "formatselect",
                        theme_advanced_buttons1 : "bold,italic,underline,h,pasteword",
                        theme_advanced_buttons3 : ""
                    });
                });
            } else {
                $('.modify-email-template').load('/admin/email-templates/modify/' + selectedOptId + ' #modify-form', function() {
                    $('.modify-email-template p:first').remove();
                    $('.modify-email-template hr').remove();
				
                    tinyMCE.init({
                        mode : "specific_textareas",
                        plugins : "heading, paste",
                        elements : "message, content, ajaxfilemanager",
                        editor_selector : "content",
                        theme : "advanced",
                        theme_advanced_toolbar_location : "top",
                        theme_advanced_buttons1_add_before : "formatselect",
                        theme_advanced_buttons1 : "bold,italic,underline,h,pasteword",
                        theme_advanced_buttons3 : ""
                    });
                });
           }
        });
        
        $('a.remove-committee').click(function() {
           var confirmDelete = confirm("Are you sure you want to delete " + $(this).attr('title') + "?");
           
           if (!confirmDelete) {
               return false;
           } else {
               window.location.href = $(this).attr('href');
               return false;
           }            
        });
        
        $('a.delete-template').click(function() {
           var confirmDelete = confirm("Are you sure you want to delete " + $(this).attr('title') + "?");
           
           if (!confirmDelete) {
               return false;
           } else {
               window.location.href = $(this).attr('href');
               return false;
           }            
        });

        $('a.preview-committee-members').click(function() {
            var committeeMembers = new Array();
                       
	    var committeeId   = $(this).attr('id').replace('committee-', '');
	    var committeeName = $(this).attr('title');

            var response = false;
            
            jQuery.ajax({
                url: '/admin/committees/preview-members/' + committeeId,
                type: 'GET',
                dataType: 'html',
                async: false,
                success: function(data) {
                    jQuery.fancybox({
                    'width' : 500,
                    'title': 'Previewing Members of ' + committeeName + ' Committee',
                    'content' : data
                });
                }
            });            
           
            return false;
        });
    
        
        $('a#preview-recipients').click(function() {
            var recipientCommittees = new Array();
            
            $('input.committee-id-field:checked').each(function() {
                recipientCommittees.push($(this).val());
            });
            
            var recipCommitteesString = recipientCommittees.join('&');
            
            var response = false;
            
            jQuery.ajax({
                url: '/admin/committees/preview-recipients/' + recipCommitteesString,
                type: 'GET',
                dataType: 'html',
                async: false,
                success: function(data) {
                    jQuery.fancybox({
                    'width' : 500,
                    'title': 'Previewing Committee Recipients',
                    'content' : data
                });
                }
            });            
           
            return false;
        });

	$("div.video a.fancybox-youtube").click(function(){
		jQuery.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'title'			: this.title,
			'width'			: 640,
			'height'		: 390,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
				'wmode'		: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
		return false;
	});

	$('#search-cat-link').click(function(){
		$('.search-cat-dropdown').toggle();
	});

	$('.find-family').click(function(){
		$('#search-cat-link').text('Find Family');
		$('#search-form').attr("action", "/search/properties");
		$('.search-cat-dropdown').hide();

	});

	$('.find-member').click(function(){
		$('#search-cat-link').text('Find Member');
		$('#search-form').attr("action", "/search/members");
		$('.search-cat-dropdown').hide();
	});

	$('.cal-hover').hide();
	$('.active').hover(
		function(){
			$(this).find('.cal-hover').show();
		},
		function(){
			$(this).find('.cal-hover').hide();
		}
		);
	$("ul.dropdown li").hover(function(){
		$(this).addClass("hover");
		$('ul:first',this).css('visibility', 'visible');
	}, function(){
		$(this).removeClass("hover");
		$('ul:first',this).css('visibility', 'hidden');
	});
	$("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");

	$('#search input.search').focus(function(){
		if($(this).val() == 'Type name here') $(this).val('');
	}).blur(function(){
		if($(this).val() == '') $(this).val('Type name here');
	});

	$('img.coupon-small').click(function(){
		smallcoupon = $(this);
		$('img.coupon-large').fadeOut('linear',function(){
			$(this).attr('src',smallcoupon.attr('src'));
			$(this).fadeIn();
		});
	});

	if($('#thumbs').size()) {
		$('#thumbs').galleriffic({
			delay: 0,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading'
		});
	}

	// ##### FONT RESIZER #####
	// Reset Font Size
	var originalFontSize = $('html').css('font-size');
	$(".resetFont").click(function(){
		$('html').css('font-size', originalFontSize);
	});
	// Increase Font Size
	$(".increaseFont").click(function(){
		var currentFontSize = $('html').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum*1.2;
		$('html').css('font-size', newFontSize);
		return false;
	});
	// Decrease Font Size
	$(".decreaseFont").click(function(){
		var currentFontSize = $('html').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum*0.8;
		$('html').css('font-size', newFontSize);
		return false;
	});

});



////////////////////////////////////////////////////////////////////////
// wrapper for console.log
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

////////////////////////////////////////////////////////////////////////
// jQuery Template Engine
// https://github.com/trix/nano
(function($){
	$.templ = function(template, data) {
		return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
			var keys = key.split("."), value = data[keys.shift()];
			$.each(keys, function () {
				value = value[this];
			});
			return (value === null || value === undefined) ? "" : value;
		});
	};
})(jQuery);

////////////////////////////////////////////////////////////////////////
// wrapper for placeholder in input fields
// http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
$(function(){
	$('[placeholder]').focus(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
		var input = $(this);
		if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur();

	$('[placeholder]').parents('form').submit(function() {
		$(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
			}
		});
	});
});

////////////////////////////////////////////////////////////////////////
// ajax loader
function show_loader(id){
	if($('#loader-' + id).length) {
		$('#loader-' + id).attr('num', parseInt($('#loader-' + id).attr('num'))+1);
		return '';
	}
	return $('<div class="loader" num="1" id="loader-' + id + '"> </div>');
}
function hide_loader(id){
	var num = $('#loader-' + id).attr('num') - 1;
	if(num > 0)
		$('#loader-' + id).attr('num', num);
	else
		$('#loader-' + id).remove();
}

////////////////////////////////////////////////////////////////////////

jQuery(document).ready(function() {

	function confirmDelete() {
		return confirm('Are you sure you want to delete this page?');
	}

	jQuery('#updatePage').click(function() {

		// If remove page isn't checked, don't do anything.
		if (jQuery('input[name="remove"]').is(':checked')==false) {
			return;
		}

		if (confirmDelete()) {
			var pageId    = jQuery('input[name="id"]').val();
			var deleteUrl ='/admin/delete/page/' + pageId;

			jQuery('input[name="remove"]').closest('form').attr('action', deleteUrl);
		} else {
			return false;
		}

	});


});

jQuery(document).ready(function() {

	function ajaxfilemanager(field_name, url, type, win) {
		var ajaxfilemanagerurl = "/js/tinymce/jscripts/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php";
		var view = 'detail';
		switch (type) {
			case "image":
				view = 'thumbnail';
				break;
			case "media":
				break;
			case "flash":
				break;
			case "file":
				break;
			default:
				return false;
		}
		tinyMCE.activeEditor.windowManager.open({
			url: "/js/tinymce/jscripts/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php?view=" + view,
			width: 782,
			height: 440,
			inline : "yes",
			close_previous : "no"
		},{
			window : win,
			input : field_name
		});
	}



	tinyMCE.init({
		mode : "specific_textareas",
		plugins : "heading, paste",
		elements : "message, content, ajaxfilemanager",
		editor_selector : "content",
		theme : "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_buttons1_add_before : "formatselect",
		theme_advanced_buttons1 : "bold,italic,underline,h,pasteword",
		theme_advanced_buttons3 : "",
		file_browser_callback : ajaxfilemanager
	});



});

jQuery(document).ready(function() {
	// Remove those auto -generated span styles from tinyMCE on heading tags.
	jQuery('h1 > span,h2 > span,h3 > span').each(function() {
		if (jQuery(this).attr('style') == 'font-size: 12px;') {
			jQuery(this).attr('style', '');
		}

	});
	
	//ie7 fix
	jQuery('#helloMember').css('position', 'absolute');
	jQuery('div#container div#bodyArea > div#search').css('position', 'relative');
	
	//Profile page hover message (NOTE: 164x136)
	$("#editPhoto").mouseover(function(){
		$("#uploadStatus").text('Dimension: 164 x 136 pixels');
	});
});

function are_you_sure(){
	return confirm("Are you sure?")
}

