﻿$(document).ready( function () {
    var spItems = {}, spWidth, spCloseWidth = 50, spMargin = 10, spAutoClick, spCtr, spTimer, spTiming = 6000, spAutoClicked = false,
        components = $("#components");
    
    window.updateConvioLink = function(radio_opt)
    {
      jQuery(radio_opt).parents('.dContent').find('a.lnkConvioDonate').attr('href', radio_opt.value);
    }
    if(Modernizr.input['placeholder'] === false) {
        $('.placeholder').each(function() {
            var $label = $(this),
                $input = $label.next('input');
            $input.val($label.text());
            $input.bind('focus', function() {
                var $this = $(this);
                if($this.val() === $label.text()) {
                    $this.val('');
                }
            });
            $input.bind('blur', function() {
                var $this = $(this);
                if($this.val() === '') {
                    $this.val($label.text());
                }
            });
        });
    }
    
    $('#maincol h1').append($('#page-tools'));

    // build sliding panel functionality for home page
    $(".sliderPanel").each( function(index) {
        var sp = $(this);
        spItems[ sp.attr("id") ] = index * (spCloseWidth + spMargin) + "px";
        if (index === 0)
        {
            spWidth = sp.width();
        }

	var overlayDiv = sp.children("a.slideOverlay");
	var contentDiv = sp.children("div.slideContent");
	var link = sp.contents().find("a.moreLink");
		
	overlayDiv.attr("href", link.attr("href"));
	overlayDiv.width(228);
	overlayDiv.height(300);
	overlayDiv.css('position', 'absolute');
	overlayDiv.css('display', 'block');

        sp.click( function() {
            var sp = $(this), totalWidth = 0, sps = $(".sliderPanel");

            if (spAutoClicked) { spAutoClicked = false; }
            else if (spTimer) { clearInterval(spTimer); spTimer = false; }

            sps.removeClass("active");
            sp.addClass("active");
            sps.each( function(index) {
                closeSp = $(this);
                if (closeSp.attr("id") !== sp.attr("id") )
                {
                    closeSp.animate( { "width": spCloseWidth + "px", "left": totalWidth + "px" }, {"duration":"slow"} );
                    totalWidth += (spCloseWidth + spMargin);
                }
                else
                {
                    sp.animate( { "width": + spWidth + "px", "left": spItems[ sp.attr("id") ] }, {"duration":"slow"} );
                    totalWidth += (spWidth + spMargin);
                }

            });
        });
    });

    // begin autosliding for home page
    spAutoClicked = true;
    $("#sp1").click();
    spCtr = 1;
    spAutoClick = function () {
        var sps = $(".sliderPanel");
        spAutoClicked = true;
        $(sps.get(spCtr)).click();
        spCtr += 1;
        if ( spCtr >= sps.length ) { spCtr = 0; }
    };
    spTimer = setInterval( spAutoClick, spTiming );

    // setting up focus/blur functionality for search and email fields
    $("input.search").live("focus", function() {
        var fld = $(this);
        if (fld.val() === "Search") { fld.val(""); }
    }).live("blur", function() {
        var fld = $(this);
        if (fld.val() === "") { fld.val("Search"); }
    });
    $("input.email").live("focus", function() {
        var fld = $(this);
        if (fld.val() === "Email Address") { fld.val(""); }
    }).live("blur", function() {
        var fld = $(this);
        if (fld.val() === "") { fld.val("Email Address"); }
    });

    // yank components section from the page if it's really empty
    if ( components.html().toString().replace(/(\s)*/g, "") === "" ) { components.hide(); $("#main").addClass("fullPage"); }

    // get Twitter feed info if the page has a place for it
    if ( $("#tweet").length > 0 )
    {
        $.getJSON("http://twitter.com/status/user_timeline/feedingamerica.json?count=1&callback=?", function(data) {
            $("#tweet").html( tweetLink(data[0].text) );
            $("#tweetInfo").html( tweetLink( "@" + data[0].user.screen_name.toString().toUpperCase() ) );
            $("#tweetInfo a").append("<br/><span class=\"tweetTime\">" + twitter_relative_time( data[0].created_at.toString() ) + "</span>");
        });
    }
    if($('.rtFacebook').length > 0){
        
		$.getJSON("https://graph.facebook.com/FeedingAmerica/posts?access_token=" + $('.rtFacebook').data("token") + "&callback=?", function(posts) {
			var post = posts.data[0].message, 
				url = posts.data[0].link,
				iconUrl = posts.data[0].icon,
				type = posts.data[0].type,
				$container = $('.rtFacebook');
			post = post.replace(/(http:\/\/[^ ]+)/gi, "<a href='$1' target='_blank' >$1</a>");
			$container.append('<p class="post">' + post + '</p>');
			if(iconUrl != undefined) {
			    $container.append('<a href="'+ url + '" class="icon" target="_blank" ><img src="' + iconUrl + '" />'+ type + '</a>');			
			}
		});
	}
	if($('#rtBlog').length > 0){
		$.getJSON("http://blog.feedingamerica.org//?feed=json&jsonp=?", function(posts) {
			var post = posts[0].excerpt, 
				url = posts[0].permalink,
				title = posts[0].title,
				$container = $('#rtBlog');
			post = post.replace(/(http:\/\/[^ ]+)/gi, "<a href='$1' target='_blank' >$1</a>");
			$container.append('<a href="'+ url + '" class="icon" target="_blank" >' + title + '</a>');	
			$container.append('<p class="post">' + post + '</p>');
		});
	}
	if($('#blog-long').length > 0){
		$.getJSON("http://blog.feedingamerica.org//?feed=json&jsonp=?", function(posts) {
		    var url = "",
				title = "",
				$container = $('#blog-long'),
				$ul = $('<ul>');
		    for(i=0; i<3; i++) {
			    url = posts[i].permalink;
			    title = posts[i].title;
			    $ul.append('<li><a href="'+ url + '" class="icon" target="_blank" >' + title + '</a></li>');
			}
			$container.append($ul);
		});
	}
	
	if ($("#mapFrame")) {
		if (getQueryString() && getQueryString()["tab"] && getQueryString()["tab"] === "child") {
			$("#mapFrame").attr("src", "/SiteFiles/flashmap/child.html?v=2");
		}
	}

    // create panels
    panelize("#rtData");
    panelize("#fdData");
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() { panelize("#fdData"); });
    // create video scroller
    videoScroll("#mainVid");
    videoScroll("#compVid");

    // create secondary article viewer
    secondaryViewer();
  
});

function getQueryString() {
	var result = {}, queryString = parent.location.search.substring(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}

	return result;
}

// TWITTER functions
// convert plain text to linking html for tweet text content
function tweetLink(txt)
{
    return txt.toString().replace(/(http:\/\/[^ ]+)/gi, "<a href=\"$1\" target=\"_blank\">$1</a>" ).replace(/(@([_a-z0-9\-]+))/gi,"<a href=\"http://twitter.com/$2\" target=\"_blank\" title=\"Follow $2\" $target >$1</a>");
}

// parse twitter time value
function twitter_relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


// create moving panel functionality
function panelize( selector )
{
    var pHolder = $(selector), pFrame, pPanes, pWidth, pCtrls, pCount = 0;

    if (pHolder.length === 0) { return; }

    pWidth = pHolder.width();
    pCtrls = $("<p class=\"panelControls\">");
    pFrame = pHolder.children(".paneFrame");
    pPanes = pFrame.children(".pane");

    pPanes.each( function (index) {
        var pane = $(this), ctrl = $("<a href=\"#\" class=\"panelPager ir tpng\"></a>");

        pane.css( { "left": pWidth * index + "px" } );
        ctrl.click( function() {
            pCtrls.children(".panelPager").removeClass("active");
            $(this).addClass("active");
            pFrame.animate( { "left": -1 * index * pWidth + "px" }, { "duration":"slow" } );
            return false;
        });

        if (index === 0) { ctrl.addClass("active"); }

        pCtrls.append(ctrl);
        pCount += 1;
    });
    pCtrls.width(pCount * 21);
    pHolder.after(pCtrls);
}

// create video panel functionality
function videoScroll( selector )
{
    var vHolder = $(selector), vFrame, vImgs, vWidth, vL, vR, vBtnCheck, vProxy, vPlayBtn;

    if (vHolder.length === 0) { return; }

    vWidth = vHolder.width();
    vFrame = vHolder.children(".vidFrame");
    vImgs = vFrame.children(".vidImg");
    vL = vHolder.children(".vidLeft");
    vR = vHolder.children(".vidRight");
    vPlayBtn = vHolder.children(".vidIndicator");

    vImgs.each( function (index) { $(this).css( { "left": vWidth * index + "px" } ); });

    vBtnCheck = function ()
    {
        if ( parseInt(vFrame.css("left"),10) === 0  ) { vL.addClass("off"); } else { vL.removeClass("off"); }
        if ( ( parseInt(vFrame.css("left"),10) + vWidth*vImgs.length ) <= vWidth ) { vR.addClass("off"); } else { vR.removeClass("off"); }

        vL.click( function() {
            if ( parseInt(vFrame.css("left"),10) < 0  )
            {
                vL.unbind("click"); vL.click( function() { return false; } );
                vR.unbind("click"); vR.click( function() { return false; } );
                vFrame.animate( {"left":"+=" + vWidth}, { "duration":"slow", "complete":vBtnCheck } );
            }
            return false;
        });
        vR.click( function() {
            if ( ( parseInt(vFrame.css("left"),10) + vWidth*vImgs.length ) > vWidth )
            {
                vL.unbind("click"); vL.click( function() { return false; } );
                vR.unbind("click"); vR.click( function() { return false; } );
                vFrame.animate( {"left":"-=" + vWidth}, { "duration":"slow", "complete":vBtnCheck } );
            }
            return false;
        });
    };

    vBtnCheck();

    vProxy = function() {
        var index = -1 * Math.floor( parseInt(vFrame.css("left"),10) / vWidth );
        document.location = vImgs.children("a").get(index);
    };

    vPlayBtn.click( vProxy );
    vImgs.children(".vidDesc").click( vProxy );

}

// create secondary landing viewer
function secondaryViewer()
{
    var sv = $(".secondaryOverview"), sdx = 0, svP, svNext, svPrev, svGallery, svGalFrame, sImgs, sThumbs, sDescs, thumbW, thumbH, offThumbW, offThumbH, offThumbPL, offThumbPT, goL, goR, goLeft, goRight;

    if (sv.length === 0) { return; }

    sImgs = sv.find(".secondaryImage");
    sThumbs = sv.find(".secondaryGalItem");
    sDescs = sv.children(".secondaryDesc");
    svP = sv.find(".secondaryPointer");
    svNext = sv.find(".vidRight");
    svPrev = sv.find(".vidLeft");
    svGallery = sv.find(".secondaryGallery");
    svGalFrame = sv.find(".secondaryGalleryFrame");
    goL = svGalFrame.find(".vidLeft");
    goR = svGalFrame.find(".vidRight");

    // initialize
    sImgs.hide();
    $(sImgs.get(0)).show();
    sDescs.hide();
    $(sDescs.get(0)).show();
    sThumbs.each( function (index) {
        var gal = $(this);

        if (index === 0)
        {
            thumbW = gal.width();
            thumbH = gal.height();
            offThumbW = gal.width() - 20;
            offThumbH = gal.height() - 17;
            offThumbPL = 10; offThumbPT = 8;
            svGallery.width(thumbW*sThumbs.length);
            svGallery.height(thumbH);

            secActivate(0);
        }

        gal.css( { "left":index*thumbW } );
        gal.click( function () { secActivate(index); } );
    });


    // left / right scroller buttons
   
    //function pauseScrollButtons() { goL.unbind("click"); goR.unbind("click"); }
    if ( svGallery.width() > svGalFrame.width() )
    {
        svNext.show();
        svPrev.show();
    }

    // set up previous & next buttons
    svNext.click( function () {
        if ( sdx < (sThumbs.length - 1) ) { 
			sdx += 1; 
			secActivate(sdx); 
			adjustViewToIndex(sdx); 
		} else {
		}
        return false;
    });
    svPrev.click( function () {
        if ( sdx > 0 ) { 
			sdx -= 1; 
			secActivate(sdx); 
			adjustViewToIndex(sdx); 
		}
        return false;
    });

    // move between sections
    function secActivate(idx)
    {
        sThumbs.each( function (index) {
            var thumb = $( sThumbs.get(index) );
            if (index !== idx)
            {
                $( sImgs.get(index) ).slideUp(); //hide();
                $( sDescs.get(index) ).fadeOut(); //hide();
                if ( thumb.width() != offThumbW ) { thumb.children(".sGalFrame").animate( { "width":offThumbW, "height":offThumbH, "margin-left":offThumbPL, "margin-right":offThumbPL, "margin-top":offThumbPT }, { "duration":"fast" } ); }
            }
            else
            {
                sdx = idx;
                $( sImgs.get(index) ).slideDown(); //show();
                $( sDescs.get(index) ).fadeIn(); //show();
                $( sThumbs.get(index) ).children(".sGalFrame").animate( { "width":thumbW, "height":thumbH, "margin-left":"0", "margin-right":"0", "margin-top":"0" }, { "duration":"fast" } );
                svP.css( { "left": index*thumbW } );
            }
        });
    }

    // make sure selected index is in viewport
    function adjustViewToIndex(idx)
    {
        var rightTarget = svGalFrame.width() - thumbW,
			currentLocation = (idx*thumbW) + parseInt(svGallery.position().left,10);
        if ( currentLocation > rightTarget ) { 
			svGallery.animate( {"left":(svGalFrame.width() - thumbW - idx*thumbW)},
							   {"complete":function() { } } 
			); 
		}
        else if ( currentLocation < 0 ) { 
			svGallery.animate( {"left":"-" + idx*thumbW},
							   {"complete":function() { } }
			); 
		}
    }

}




// client side include:
// every element classed "incPH" loads as url the html content
// of the element and replaces it in the DOM, recursively
// running the operation on loaded include
//function csiInclude(domObj)
//{
//    (domObj).find(".csinclude").each( function() {

//        var placeholder = $(this), includeHtml, include;

//        placeholder.load( placeholder.attr("id"), function () {

//            // loaded html with leading whitespace stripped
//            includeHtml = placeholder.html().replace(/^(\s)*/g, "");
//            
//            // if this content doesn't start with a tag, wrap it in a tag
//            // (otherwise may lose text sitting outside of tags)
//            if (includeHtml[0] !== "<") includeHtml = "<span>" + includeHtml + "</span>";

//            // jquery object for this html
//            include = $( includeHtml );

//            // place loaded content and remove placeholder
//            placeholder.after( include );
//            placeholder.remove();

//            // now recursively do replacements in the new content
//            csiInclude( include );
//        });
//    });
//}


(function($) {
	$.fn.hoverNav = function() {
		var $this = $(this),
			$top_level = $this.find('>ul>li>a');
			$top_level.parent('li').each(function() {
				var $this = $(this),
					$sub = $this.find('li');
				$sub.width($this.find('ul').width() - 2);
				
			});
		$top_level.bind('mouseenter', function() {
			$(this).parent('li').addClass('hover');
		});
		$top_level.parent('li').bind('mouseleave', function() {
			$(this).removeClass('hover');
		});
	};
	$.fn.partnersRotate = function(options) {
		var opts = $.extend({interval: 5000}, options),
			$container = $(this),
			$scroller = $container.find('.partners'),
			$items = $scroller.find('li'),
			width = $items.width(),
			p = 1,
			c = $items.length,
			interval = c > 1 ? setInterval(function() {
				if(p>c) {
					$scroller.animate({left: '-' + (p*width)}, 500).animate({left: '-' + (width)}, 0);
					p = 1;
				} else {
					$scroller.animate({left: '-' + (p*width)}, 500);
				}
				p += 1;
			}, 
			opts.interval) : '';
		$items.filter(':first').clone().addClass('clone').appendTo($scroller);
		$items.filter(':last').clone().addClass('clone').prependTo($scroller);
		$scroller.animate({left: '-' + (p*width)}, 0);
	};
	
	$.fn.tabs = function(options) {
	    $(this).each(function() {
	        var opts = $.extend({}, $.fn.tabs.defaults, options),
	            $this = $(this),
	            $tabs = $this.find('.tlTab'),
	            $panels = $this.find('.tlPage');
	            
	        $tabs.filter(':first').addClass('on');
	        $panels.hide().filter(':first').show();
	        if(window.location.hash.slice(1) != '') {
	            $tabs.removeClass('on').filter(':eq('+window.location.hash.slice(1)+')').addClass('on');
	            $panels.hide().filter(':eq('+window.location.hash.slice(1)+')').show();
	        }
	        $tabs.bind('click', function() {
	            var index = $(this).index();
	            $panels.hide().filter(':eq('+index+')').show();
	            $tabs.removeClass('on').filter(':eq('+index+')').addClass('on');
	            window.location.hash = index;
	        });
	    });
	};
	$.fn.tabs.defaults = {}
	
})(jQuery);
$(function() {
	$('#headerNav .fl').hoverNav();
	$('.tabbedList').tabs();
	$('.leftSubInfo .container').partnersRotate();
	$('.linkTabs').each(function() {
	    var $this = $(this),
	        $tabs = $this.find('.tlTab'),
	        year = $this.find('.yearFilter:first').data("year");
	    $tabs.filter('.' + year).addClass('on');
	});
	$('#quote').each(function() {
	    var $this = $(this),
	        $first = $('.articleSection p:first');
	    $first.after($this.show());
	});
});

(function($, undefined) {
	$.fn.galleryNav = function(options) {
	    $(this).each( function() {
		    var opts = $.extend({}, $.fn.galleryNav.defaults, options),
			    $container = $(this),
			    $galleryMask = $container.find('.gallery-mask'),
			    $gallery = $container.find('ul.gallery'),
			    $items = $gallery.find('.item'),
			    $stage = $container.find('.mainMedia'),
			    $empty = $('<ul>', {"class":'slider-ul'}),
			    $listItem = $('<li>', {"class":'page clearfix'}),
			    $pages = $(),
			    pageWidth = $gallery.width(),
			    pageCount = 0,
			    $pagination = undefined,
			    currentPage = 0,
			    $next = {},
			    $prev = {},
			    id = $stage.find('.media').data('id'),
			    $selected = $gallery.find('[data-id="' + id + '"]').addClass('selected');
		    $gallery.empty();
		    //Sort gallery items
		    $items.each(function(index) {
			    if(index % 10 === 0 && index !== 0) {
				    $empty = $empty.appendTo($listItem).clone().empty();
				    $listItem.appendTo($gallery);
				    $listItem = $('<li>', {"class":'page clearfix'});
			    }
			    $(this).appendTo($empty);
		    });
		    $gallery.append($listItem.append($empty));
		    $pages = $gallery.find('.page');
		    pageCount = $pages.length;
		    $gallery.css({position: "absolute",width: pageCount * pageWidth});
		    $galleryMask.height($gallery.height()).css({position: 'relative'});
    		
    		
		    if(pageCount > 1) {
			    $pagination = pagination(pageCount);
			    $galleryMask.after($pagination);
			    currentPage = $selected.parent().parent().index();
			    slideTo(currentPage);
		    }
    		
    					
		    // Setup Stage Links 
		    function setStage($stage) {
			    $('.inner .more').each(function() {
				    var $this = $(this),
					    $inner = $(this).parent('.inner'),
					    startHeight = $inner.height(),
					    endHeight = $inner.find('.full').height() + 10;
				    $this.bind('click', function(e) {
					    var $inner = $(this).parent('.inner');
					    e.preventDefault();
					    if($inner.hasClass('open')) {
						    $inner.animate({height: startHeight}).removeClass('open');
					    } else {
						    $inner.animate({height: endHeight}).addClass('open');
					    }
				    });
			    });
			    $stage.find('.prev, .next').bind('click', function(e) {
				    e.preventDefault();
				    $stage.find('iframe').hide();
				    $stage.animate({opacity: 0}, opts.fade/2);
				    $.get(this.href, loadMain);
				});
		    }
		    // Bind Gallery items
		    if(opts.ajaxGallery) {
			    $items.find('a').bind('click', function(e) {
				    e.preventDefault();
				    $stage.find('iframe').hide();
				    $stage.animate({opacity: 0}, opts.fade/2);
				    $.get(this.href, loadMain);
				    $items.removeClass('selected');
				    $(this).parent().addClass('selected');
			    });
			    setStage($stage);
		    }
    		
		    // Load Stage
		    function loadMain(data) {
			    var $this = $(data).find('.mainMedia>*'),
				    id = $this.filter('.media').data('id'),
				    $iframe = $this.find('iframe').hide(),
				    $item = $gallery.find('[data-id="' + id + '"]');
			    $items.removeClass('selected');
			    $item.addClass('selected');
			    if(pageCount > 1) {
				    currentPage = $item.parent().parent().index();
				    slideTo(currentPage);
			    }
			    $stage.empty().append($this)
			    .delay(opts.delay)
			    .animate({opacity: 1}, opts.fade/2, function() {
				    $iframe.show();
			    });
			    setStage($stage);
		    };
    		
    		
		    //Create pagination
		    function pagination(pages) {
			    var $pagination = $('<div>', {"class":"tlPagination clearfix"}),
				    $elipsis = $('<div>', {'class':"tlElp fl",html: '&hellip;'}).hide(),
				    $page = $('<a>',{'class':"tlPNum fl", href:"#"}),
				    i = 1;
    			
			    $next = $('<a class="tlPNext ir tpng fl" href="#">Next</a>');
			    $prev = $('<a class="tlPPrev ir tpng fl" href="#">Previous</a>');
			    $pagination.append($prev).append($page.clone().html(i)).append($elipsis.clone());
			    for(i;i<pages - 1;i++) {
				    $pagination.append($page.clone().html(i + 1));
			    }
			    $pagination.append($elipsis.clone()).append($page.clone().html("Last")).append($next);
    			
			    $pagination.find('.tlPNum').bind('click', function(e) {
				    e.preventDefault();
				    var $this = $(this)
				    currentPage = $this.parent().children().not('.tlElp').index($this) - 1;
				    slideTo(currentPage);
				    updatePagination(currentPage);
			    });
			    $prev.addClass('off').bind('click', dissabled);
			    $next.bind('click', nextPage);
			    if(pages > opts.pagesShown + 1) {
				    $pagination.find('.tlPNum').slice(opts.pagesShown).hide();
				    $pagination.find('.tlPNum:last').show();
				    $pagination.find('.tlElp').filter(':last').show();
			    }
			    return $pagination;	
		    }
		    function updatePagination(page) {
			    var $pages = $pagination.find('.tlPNum'),
				    pagePad = (Math.floor(opts.pagesShown/2)),
				    $elipses = $pagination.find('.tlElp');
			    $pages.removeClass('on').eq(page).addClass('on');
			    if(page >= pagePad + 1) {
				    $pages.hide().slice((page - pagePad), page + pagePad + 1).show();
				    if(page > pagePad + 1) {
					    $elipses.filter(':first').show();
				    } else {
					    $elipses.filter(':first').hide();
				    }
			    } 
			    if((page + pagePad + 2) >= $pages.length) {
				    $pages.hide().slice(-1 * opts.pagesShown).show(); 
				    $elipses.filter(':last').hide();
			    } else {
				    $elipses.filter(':last').show();
			    }
			    //show first and last
			    $pages.filter(':first').show();
			    $pages.filter(':last').show();
			    //check buttons
			    if($next.hasClass('off')) {
				    $next.unbind('click').bind('click', nextPage).removeClass('off');
			    } else if($prev.hasClass('off')) {
				    $prev.unbind('click').bind('click', previousPage).removeClass('off');
			    }
			    if(page === 0) {
				    $prev.unbind('click').bind('click', dissabled).addClass('off');
			    } else if(page === pageCount - 1) {
				    $next.unbind('click').bind('click', dissabled).addClass('off');
			    }
    			
		    };
		    function previousPage(e) {
			    e.preventDefault();
			    currentPage -= 1;
			    slideTo(currentPage);
			    updatePagination(currentPage);
		    };
		    function nextPage(e) {
			    e.preventDefault();
			    currentPage += 1;
			    slideTo(currentPage);
			    updatePagination(currentPage);
		    };
		    function dissabled(e) {
			    e.preventDefault();
		    };
    		
		    //slide to page 
		    function slideTo(page) {
			    $gallery.animate({left: "-" + (page * pageWidth)}, 1000);
			    if(pageCount > 1) {
				    updatePagination(page);
			    };
		    }
		});
	};
	$.fn.galleryNav.defaults = {
		pagesShown : 5,
		ajaxGallery : true,
		fade: 500,
		delay: 0
	};
	$(function() {
		$('#media_page').galleryNav();
		$('#real_page').galleryNav();
		$('#TW07_page').galleryNav({ajaxGallery: false});
	});
})(jQuery);
