var lastFetchedNews = 0;
var lastNewsCategory;

/* IE PNG fix multiple filters */
(function ($) {
    if (!$) return;
    $.fn.extend({
        fixPNG: function(sizingMethod, forceBG) {
                if (!($.browser.msie)) return this;
                var emptyimg = "{{ MEDIA_URL}}css/images/blank.gif"; //Path to empty 1x1px GIF goes here
                sizingMethod = sizingMethod || "scale"; //sizingMethod, defaults to scale (matches image dimensions)
                this.each(function() {
                        var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
                                imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
                                src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
                        this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
                        if (isImg) this.src = emptyimg;
                        else this.style.backgroundImage = "url(" + emptyimg + ")";
                });
                return this;
        }
    });
})(jQuery);

function init_blink(el) {
    if(el.value == '') {
        el.value = el.title;
        $(el).removeClass('focus');
    }
    $(el).parents('form').submit(function(){
        if (el.value == el.title){
            el.value = '';
        }
    });
}

function clean_blink($selector) {
    $selector.each(function(){
        this.value = this.title
    }).removeClass('focus');
}

function bind_share(in_element) {
    $('.socials .ico-facebook', in_element).click(function(e){
        e.preventDefault();
        url = $(this).parent().data('url');
        title = $(this).parent().data('title');
        window.open('https://www.facebook.com/sharer.php?u='+url+'&t='+title,'sharer','toolbar=0,status=0,width=626,height=436')
    })

    $('.socials .ico-twitter', in_element).click(function(e){
        e.preventDefault();
        url = $(this).parent().data('url');
        title = $(this).parent().data('title');
        window.open('https://twitter.com/intent/tweet?text='+title+'&utl='+url,'sharer','toolbar=0,status=0,width=626,height=436')
    })

    $('.ico-print', in_element).click(function(e){
        e.preventDefault();
        var $to_print = $(this).parents('.print-item');
        if ($to_print.length){
            $to_print.jqprint();
        }
    })
}

function send_quiz(e){
    $('#quiz-form').ajaxSubmit(function(data, type, object, $form){
        $.colorbox({
            html: data,
            opacity: 0.5,
            onComplete: function(){
                bind_share($('.socials'));
                email_item($('.email-page-link'), $form)
            }
        });
    });
}

function email_item($selector) {
    $selector.click(function(e){
        e.preventDefault();
        $.colorbox({
            href: this.href,
            onComplete: function(){
                var $form = $('#email-page-form')
                $('input[name=link]', $form).val(location.href);
                $('.blink', $form).each(function(){ init_blink(this) });
                $form.ajaxForm({
                    dataType: 'json',
                    beforeSubmit: function(formData, $form, options){
                        $('.error', $form).remove();
                    },
                    success: function(data, type, object, $form) {
                        if (data.errors) {
                            for (key in data.errors){
                                var $block = $('input[name="'+key+'"]', $form)
                                $block.before("<p class='error'>"+data.errors[key]+"</p>")
                            }
                        } else {
                            $form.parent().html('<p class="success">Message was sent</p>');
                        }
                        $.colorbox.resize()
                    }
                })
            }
        });
    });
}

$(function() {
    email_item($('.email-page-link'));
    bind_share(document.body);

    $('#invite-event-link').click(function(e){
        e.preventDefault();
        $.colorbox({
            href: this.href,
            onComplete: function(){
                var $form = $('#invite-event-form');
                $('.blink', $form).each(function(){ init_blink(this) });
                $form.ajaxForm({
                    dataType: 'json',
                    beforeSubmit: function(formData, $form, options){
                        $('.error', $form).remove();
                    },
                    success: function(data, type, object, $form) {
                        if (data.errors) {
                            for (key in data.errors){
                                var $block = $('input[name="'+key+'"]', $form)
                                $block.before("<p class='error'>"+data.errors[key]+"</p>")
                            }
                        } else {
                            $form.parent().html('<p class="success">Invite was sent</p>');
                        }
                        $.colorbox.resize()
                    }
                })
            }
        });
    });
    
    $('a.sharethis').colorbox({
        inline:true, 
        href:".sharethis-window",
        innerWidth: 200,
        onOpen: function(){
            $(".sharethis-window").show();
        },
        onCleanup: function(){
            $(".sharethis-window").hide();
        }
    });
    
    $('#explore-send-story-link').click(function(e){
        e.preventDefault();
        $.colorbox({
            href: this.href,
            onComplete: function(){
                var $form = $('#explore-send-story-form');
                $('.blink', $form).each(function(){ init_blink(this) });
                $form.ajaxForm({
                    dataType: 'json',
                    beforeSubmit: function(formData, $form, options){
                        $('.error', $form).remove();
                    },
                    success: function(data, type, object, $form) {
                        if (data.errors) {
                            for (key in data.errors){
                                if (key == 'agree') {
                                    var $block = $('input[name=agree]', $form).parent().parent()
                                } else {
                                    var $block = $('input[name="'+key+'"]', $form)
                                }
                                $block.before('<p class="error">'+data.errors[key]+'</p>')
                            }
                        } else {
                            $form.parent().html('<p class="success">Story was sent</p>');
                        }
                        $.colorbox.resize()
                    }
                })
            }
        });
    });

    $('#quick-contact').ajaxForm({ 
        dataType: 'json', 
        beforeSubmit: function(formData, $form, options){
            $('.info', $form).empty()
        },
        success: function(data, type, object, $form) {
            $block = $('.info', $form);
            if (data.errors) {
                for (key in data.errors){
                    $block.append("<p class='error'>'"+key+"': "+data.errors[key]+"</p>")
                }
                $('.blink', $form).each(function(){ init_blink(this) });
            } else {
                $block.append('<p class="success">Thank you for contacting The Community Foundation of Middle Tennessee.<br /><br />Your message was successfully transmitted.</p>');
                //clean_blink($('input[type=text], textarea', $form))
                $('.form_body', $form).empty();
            }
        }
    });
    
    $('#attend-story-form').ajaxForm({ 
        dataType: 'json', 
        beforeSubmit: function(formData, $form, options){
            $('.error', $form).remove();
            $('.info', $form).empty()
        },
        success: function(data, type, object, $form) {
            if (data.errors) {
                for (key in data.errors){
                    var error = '<p class="error">'+data.errors[key]+'</p>';
                    if (key == 'agree') {
                        var $block = $('label.checklabel', $form);
                    } else {
                        var $block = $('input[name="'+key+'"]', $form);
                    }
                    $block.before(error)
                }
            } else {
                $('.info', $form).append('<p class="success">Story was sent</p>');
                clean_blink($('input[type=text], textarea', $form));
                $('input[type=checkbox]', $form).removeAttr('checked').trigger('change')
            }
        }
    });
    
    $('#attend-picture-form').ajaxForm({ 
        dataType: 'json', 
        beforeSubmit: function(formData, $form, options){
            $('.error', $form).remove();
            $('.info', $form).empty()
        },
        success: function(data, type, object, $form) {
            if (data.errors) {
                for (key in data.errors){
                    var error = '<p class="error">'+data.errors[key]+'</p>';
                    if (key == 'agree') {
                        var $block = $('label.checklabel', $form);
                    } else {
                        var $block = $('input[name="'+key+'"]', $form).parent();
                    }
                    $block.before(error);
                }
            } else {
                $('.info', $form).append('<p class="success">Photo was sent</p>');
                var $file = $('input[type=file]', $form);
                if ($.browser.msie) {
                    $file.replaceWith($file.clone());
                } else {
                    $file.val("");
                }
		        $file.parent().find('p').text('browse....');
                $('input[type=checkbox]', $form).removeAttr('checked').trigger('change')
            }
        }
    });
    
	$('.blink').live('focus', function() {
		if(this.value == this.title) {
			this.value = '';
			$(this).addClass('focus');
		}
	}).live('blur', function() {
		init_blink(this)
	}).each(function() {
        init_blink(this)
    });
	
	$('#header-signup .trigger').click(function() {
		$(this).parent().addClass('clicked').find('fieldset:eq(0)').fadeIn();
		return false;
	});
	
	$('body').click(function(e) {
		if($(e.target).parents('#header-signup').length == 0) {
			$('#header-signup').removeClass('clicked').find('fieldset:visible').fadeOut();
		};
		if($(e.target).parents('#nav-donate').length == 0) {
			$('#nav-donate').removeClass('open').find('.dd').slideUp();
		};
	});
	
	$('#nav ul.left li').hover(function() {
		$(this).addClass('hover').find('.dd').stop(true,true).slideDown();
	}, function() {
		$(this).find('.dd').stop(true,true).slideUp(function() {
			$(this).parent().removeClass('hover');
		});
	});
	
	$('#nav-donate .button').click(function() {
		$(this).parent().addClass('open').find('.dd').slideDown();
		return false;
	});
	
	$('#hero ul').jcarousel({
        visible: 1,
        scroll: 1,
        auto: 4,
        animation: 600,
        wrap: "circular",
        initCallback: hero_initCallback
	});
	
	$('.tab-links a').click(function() {
		if($(this).parent().hasClass('disabled') == false) {
			if($.browser.msie && $.browser.version < 8) {
				var tab = $(this).attr('hash');
			} else {
				var tab = $(this).attr('href');
			}
			$(this).parent().addClass('current').siblings('.current').removeClass('current');
			$(tab).addClass('current').siblings('.current').removeClass('current');
		}
		return false;
	});
	
	$('.quiz-box .checklabel').click(function() {
		$(this).addClass('selected').siblings('.selected').removeClass('selected');
	});
	
	$('.quiz-box .orange-button').click(function() {
		var idx = $('.questions .current').index() + 1;
		if( idx < $('.questions fieldset').length - 1 ) {
			$('.questions fieldset.current').hide(0, function() {
				$(this).removeClass('current').next().show(0, function() {
					$(this).addClass('current')
				});
			});
			$('.quiz-box .buttons .l-back').show();
			$('.quiz-box .buttons p span').text(idx+1);
		} if( idx == $('.questions fieldset').length - 1 ) {
			$('.questions fieldset.current').hide(0, function() {
				$(this).removeClass('current').next().show(0, function() {
					$(this).addClass('current')
				});
			});
			$('.quiz-box .buttons .l-back').show();
			$('.quiz-box .buttons p span').text(idx+1);
			$('.quiz-box .orange-button').text('Submit').attr('onclick', 'send_quiz(event)');
		}
		return false;
	});
    
	$('.quiz-box .l-back').click(function() {
		if($('.questions .current').is(':animated') == false) {
			var idx = $('.questions .current').index() + 1;
			if( idx > 2 ) {
				$('.questions fieldset.current').hide(0, function() {
					$(this).removeClass('current').prev().show(0, function() {
						$(this).addClass('current')
					});
				});
				$('.quiz-box .buttons .l-back').show();
				$('.quiz-box .buttons p span').text(idx-1);
				$('.quiz-box .orange-button').text('Next').removeAttr('onclick');
			} if( idx == 2 ) {
				$('.questions fieldset.current').hide(0, function() {
					$(this).removeClass('current').prev().show(0, function() {
						$(this).addClass('current')
					});
				});
				$('.quiz-box .buttons .l-back').hide();
				$('.quiz-box .buttons p span').text(idx-1);
			}
		}
		return false;
	});
	
	$('a[class*="cbox-vid"]').colorbox({
		iframe: true,
		innerWidth: 420,
		innerHeight: 270,
		opacity: 0.5,
		slideshow: false,
		fastIframe: false,
		onOpen: function() {
			$('#colorbox').addClass('video');
		},
		onClosed: function() {
			$('#colorbox').removeClass('video');
		}
	});

    $('a[class="cbox-audio"]').colorbox({
         iframe: true,
         innerWidth: 420,
	     innerHeight: 300,
	     slideshow: false,
		 fastIframe: false
         //href: url
    });
	
	$('.tt-link').live('mouseover', function() {
		$('.tooltip .arrow').show();
		if($('.tooltip').length == 0) {
			$('body').append('<div class="tooltip"><p></p><span class="arrow"></span></div>');
		}
		var txt = $(this).text();
		var offset = $(this).offset();
		$('.tooltip p').text(txt);
		var wid = '-' + (($('.tooltip p').width()/2) +6) + 'px';
		$('.tooltip p').css({
			left: wid
		}).parent().css({
			top: offset.top - 29,
			left: offset.left + 10
		}).show();
		
	}).live('mouseout', function() {
		$('.tooltip p').text('').parent().removeAttr('style').parent().find('.arrow').hide();
	}).live('click', function() {
		$('.tooltip p').text('').parent().removeAttr('style').parent().find('.arrow').hide();
    });
	
	$('.scroll-contact-link').click(function() {
		var scrt = $('#bottom').offset().top;
		$('html, body').animate({
			scrollTop: scrt
		}, 800);
		return false;
	});
	
	$('.font-l').click(function() {
		var current_size = parseInt($('.font-sizer').css('font-size'));
		if(current_size < 12) {
			$('.font-sizer').css('font-size', current_size+1);
		}
		return false;
	});
	
	$('.font-s').click(function() {
		var current_size = parseInt($('.font-sizer').css('font-size'));
		if(current_size > 8) {
			$('.font-sizer').css('font-size', current_size-1);
		}
		return false;
	});
	
	$('.event-gallery .slider ul').jcarousel({
		scroll: 1,
		wrap: "both"
	});
	
	$('#fund-tabs #media .thumbs ul').jcarousel({
		scroll: 1,
		wrap: "both"
	});
	
	$('.give-gallery .thumbs ul').jcarousel({
		scroll: 1,
		wrap: "both"
	});
	
	$('a[rel="event-gallery"]').colorbox({
		opacity: 0.5,
		slideshow: true,
		slideshowAuto: false,
		previous: "prev",
		next: "next"
	});
	
	$('.custom-upload').mousemove(function(e) {
		var pos_x = e.pageX;
		var offset = $(this).offset().left;
		var offset_l = pos_x - offset - 30;
		$(this).find('input').css('left', offset_l);
	});
	
	$('.custom-upload input').change(function() {
		var txt = $(this).val();
		$(this).parent().find('p').text(txt);
	});
	
	$('.custom-checkbox .checkbox').live('change', function() {
		if($(this).is(':checked')) {
			$(this).parent().addClass('checked');
		} else {
			$(this).parent().removeClass('checked');
		}
	});
	
	$('a[class*="colorbox"]').colorbox({
		opacity: 0.5
	});
	
	$('#donor-tabs .bar').click(function() {
		var el = $(this).parent().toggleClass('open').find('.list-section');
		if (el.length == 1) el.load('/explore/about/donors/get/?letter=' + $(this).html(), function() {el.slideToggle();});
		else el.slideToggle();
		$(this).parent().siblings('.open').removeClass('open').find('.list-section').slideUp();
		return false;
	});
	
	$('#fund-tabs #media .thumbs a').click(function() {
		var image_src = $(this).attr('href');
		
		$('#fund-tabs #media .full-image img').fadeOut(function() {
			$(this).attr('src', image_src).fadeIn();
		});
		
		return false;
	});
	
	$('.give-gallery .thumbs a').click(function() {
		var image_src = $(this).attr('href');
		
		$('.give-gallery .full-img img').fadeOut(function() {
			$(this).attr('src', image_src).fadeIn();
		});
		
		return false;
	});
	
	$('.questions a').click(function() {
		if($.browser.msie && $.browser.version < 8) {
			var targ = $(this).attr('hash');
		} else {
			var targ = $(this).attr('href');
		}
		
		$('html, body').animate({
			scrollTop: $(targ).offset().top
		});
		
		return false;
	});
	
	$('.answer .l-back').click(function() {
		$('html, body').animate({
			scrollTop: 0
		});
		return false;
	});
	
	$('.map-section area').hover(function() {
		var idx = parseInt($(this).attr('href').toString().replace('county', ''));
		$('.map-hover').css('background-position', '0px -' + ((idx * 400) - 400) + 'px');
	}, function() {
		$('.map-hover').removeAttr('style');
	}).click(function() {
		var idx = parseInt($(this).attr('href').toString().replace('county', ''));
		var cont = '#' + $(this).attr('href');
		$('.map-active').css('background-position', '0px -' + ((idx * 400) - 400) + 'px');
		$(cont).slideDown().siblings(':visible').slideUp();
		return false;
	});
	
	$('.funds-slider').jcarousel({
		wrap: "both",
		scroll: 1,
		initCallback: story_initCallback,
		itemFirstInCallback: story_itemFirstInCallback,
		buttonPrevHTML: '<a href="#" class="jcarousel-prev"><span class="icon"></span><span class="text"></span></a>',
		buttonNextHTML: '<a href="#" class="jcarousel-next"><span class="icon"></span><span class="text"></span></a>'
	});
	
	$('#news-tabs .teal-button').click(function() {
	    $(this).hide();
	    $(this).next('.loader_gif').show();
	    
	    category = $(this).attr('ref');
	    if (category != lastNewsCategory) {
	        lastNewsCategory = category;
	        lastFetchedNews = 5;
	        $('ul.older').empty();
	        if (!lastNewsCategory) {
	            $('a.teal-button').show();
	        }
	    } else {
	        lastFetchedNews = lastFetchedNews + 5;
	    }
	    
	    $.ajax({
	        url: '/explore/fetch-news/',
	        type: 'POST',
	        data: {'last_fetched_news': lastFetchedNews, 'last_news_category': lastNewsCategory},
	        success: function(html) {
	            $(".loader_gif").hide();
	            $("a.teal-button[ref=" + lastNewsCategory + "]").show();
	            $(".tab-entry[ref=" + lastNewsCategory + "]").find('ul.older').append(html);
	        }
	    });
		return false;
	});
});

$(window).load(function() {
	if($('.hoverable').length) {
		$('.hoverable').each(function() {
			$(this).append('<span class="overlay" />');
			var wid = $(this).find('img').width();
			var hei = $(this).find('img').height();
			$(this).find('.overlay').css({width: wid-6, height: hei-6});
		});
	}
	if($('#county-map').length) {
		$('.map-section').removeClass('loading');
		$('#map-image, .map-hover, .map-active, .map-section h3').fadeIn();
	}
});

function pageLoaded() {
	if($('.tab-box').length) {
		$('.tab-links li[class!="disabled"]:first, .tab-box .tab-entry:first').addClass('current');
		$('.tab-links li:last').addClass('last');
	}
	if($('.quiz-box').length) {
		$('.quiz-box fieldset:first').addClass('current');
		$('.quiz-box .l-back').hide();
	}
	if($('#sub-nav').length) {
		$('.main-m').css('padding-top', 40);
	}
	if($('#page-head').length) {
		$('#breadcrumb').css({'padding-top': 5, 'border-radius': '0px 0px 5px 5px'});
	}
	if($('.box-expense').length) {
		$('.box-expense').each(function() {
			$(this).find('ul li:odd').addClass('odd');
		});
	}
	if($('.box-review').length) {
		$('.box-review').each(function() {
			$(this).find('ul li:odd').addClass('odd');
		});
	}
	if($('.box-toolkit').length) {
		$('.box-toolkit').each(function() {
			if($(this).find('em.icon').length) {
				$(this).find('li').each(function() {
					$(this).addClass('has-icon');
				});
			}
		});
	}
	if($('.wide-buttons').length) {
		$('.wide-buttons').each(function() {
			if($(this).find('em.icon').length) {
				$(this).find('li').each(function() {
					$(this).addClass('has-icon');
				});
			}
		});
	}
	if($('#county-map').length) {
		$('.map-section').addClass('loading');
        $('#map-image').pngFix();
		$('#map-image, .map-hover, .map-active, .map-section h3').hide();
	}
	if($('ol').length) {
		$('ol').each(function() {
			$(this).find('li').each(function() {
				$(this).wrapInner('<span />');
			});
		});
	}
}

function hero_initCallback(carousel) {
	$('.jcarousel-prev, .jcarousel-next').live('click', function() {
		carousel.stopAuto();
	});
}

function story_initCallback(carousel) {
	$('.jcarousel-next').live('click', function() {
		carousel.next();
		return false;
	});
	$('.jcarousel-prev').live('click', function() {
		carousel.prev();
		return false;
	});
}

function story_itemFirstInCallback(carousel, item, idx, state) {
	
	if(idx == 1) {
		$('.jcarousel-prev .text').text($('.funds-slider li:last h5 strong').text());
		$('.jcarousel-next .text').text($('.funds-slider li:eq(1) h5 strong').text());
	}
	else {
		if(idx == $('.funds-slider li').length) {
			$('.jcarousel-prev .text').text($('.funds-slider li:eq(' + (parseInt(idx)-2) + ') h5 strong').text());
			$('.jcarousel-next .text').text($('.funds-slider li:eq(0) h5 strong').text());
		} else {
			$('.jcarousel-prev .text').text($('.funds-slider li:eq(' + (parseInt(idx)-2) + ') h5 strong').text());
			$('.jcarousel-next .text').text($('.funds-slider li:eq(' + idx + ') h5 strong').text());
		}
	}
}

