var lastImageWidth = null;
var lastImageHeight = null;
var loadingTimer,
loadingFrame = 1;

$(document).ready(function() {
  
    $("body").fullscreen_background();
    
    $("body").navDropDown();
    
    if (!$("body").hasClass("home")) {
        
        $("#logo").css({
            "cursor": "pointer"
        }).click(function() {
            location.href = "/";
        });
    }
    
    if ($("body").hasClass("home")) {
        $("body").home();
    }
    
    if ($("body").hasClass("yoga")) {
        $("body").yoga();
    }

    if ($("body").hasClass("blog")) {
        $("body").blog();
    }
    if ($("body").hasClass("archive")) {
        $("body").blogArchive();
    }
    if ($("body").hasClass("gallery")) {
        $("body").gallery();
    }
    if ($("body").hasClass("events")) {
        $("body").events();
    }
    if ($("body").hasClass("schedule")) {
        $("body").schedule();
    }
    
    if ($("body").hasClass("shop")) {
        $("body").shop();
    }
    
    if ($("body").hasClass("testimonials")) {
        $("body").testimonials();
    }

    //subscription mailing list
    //on click, reveal mailing list
    $("#subscribe-mailing-list").click(function() {
        $("#facebook_panel").animate({
            "margin-top": 0
        });
      
        $("#subscribe").animate({
            "margin-top": -$("#subscribe").height() - $("footer").height()
        });
        return false;
    });
    //hide mailing list
    $(".close").click(function(event) {
        //console.log(event)
        var button = $(event.target);
        button.parent().animate({
            "margin-top": 0
        });
    });

    $("#email_fld").focus(function(event){
      if($("#email_fld").val() == "Your Email") {
        $("#email_fld").val("");
      }
    })
    
    $("#email_fld").blur(function(event){
      if($("#email_fld").val() == "") {
        $("#email_fld").val("Your Email");
      }
    })
    
    //submit email
    $("#subscriptions").submit(function(event) {
        var email = $("#email_fld").val();
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!filter.test(email)) {
            alert("Please enter a valid email address");
            return false;
        } else {
            $(this).fadeOut();
            var jqxhr = $.ajax({
                type: 'POST',
                url: "/blog/subscribe/",
                data: $(this).serialize(),
                success: function(data) {
                    $("#subscribe").find("p:first").html("Thanks.<br/>You have been subscribed!");
                    $("#email_fld").val("Your Email");
                    $("#subscribe").delay("1500").animate({
                        "margin-top": -$("footer").height()
                    });
                },
                dataType: 'json'
            });
        }
        return false;
    });

    $("#footer-facebook").click(function() {
        $("#subscribe").animate({
            "margin-top": 0
        });
      
        $("#facebook_panel").animate({
            "margin-top": -$("#facebook_panel").height() - $("footer").height()
        });
        return false;
    });

    if($("#audioplayer").size()) {
      $(".audioplayer").show();
      
      var playerObj = $("#audioplayer");
      var player = new MediaElementPlayer(playerObj, {
          // shows debug errors on screen
          enablePluginDebug: false,
          pluginPath: '/media/mediaelement/',
          plugins: ['flash'],
          audioWidth: 5,
          audioHeight: 5,
          features: [],
          startVolume: 0.1,
          //forcing the use of flash for all browsers
          //due to weird safari bug
          mode:'shim',
          success: function(mediaElement, domObject) {
              $(".btn_play_pause").click(function() {
                  if ($(this).hasClass('paused')) {
                        mediaElement.pause();
                        $(".audio_player .track-list li a").removeClass("playing");
                        $(".audio_player .track-list li a").addClass("paused");
                        $(this).removeClass('paused');
                        $(this).addClass('playing');
                        player.setSrc($(this).parent().attr("title"));
                        mediaElement.setVolume(.5);
                        mediaElement.play();
                  } else {
                      $(this).removeClass('playing');
                      $(this).addClass('paused');
                      mediaElement.pause();
                  }
              });

          },
          error: function() {}
      });
    }
    

    $("#like").click(function() {
        $(this).css({
            "background": "transparent",
            "margin-top": "10px",
            "height": "28px"
        })
        $(this).find("div:first").css({
            "opacity": 1
        });
    });

    function resizeHandler() {
        var newContentSize = $("#bg_image_wrapper").height();
        if (!$("body").hasClass("home")) {
            if (!$.browser.msie) {
                newContentSize -= (parseInt($("#content").css("padding-top")) + parseInt($("#content").css("padding-bottom")) + $("footer").height() + 10);
            }
            $("#content").css({
                "min-height": newContentSize
            });
            
            
        }

        if ($(window).width() < 1034) {
            $("header").css({
                "position": "fixed"
            });
            if (!$("body").hasClass("home")) {
                $("#content").css({
                    "min-height": newContentSize + 10
                });
            }
        } else {
            $("header").css({
                "position": "fixed"
            });
            if (!$("body").hasClass("home")) {
                $("#content").css({
                    "min-height": newContentSize
                });
            }
        }
    }


    $(window).resize(resizeHandler);
    resizeHandler();
});

// remap jQuery to $
 (function($) {

    // Global ====================================================
    $.fn.fullscreen_background = function() {

        function init() {
          
            resize_image_wrapper();
          
            $(".bg_image").one('load', function() {
              resize_bg();              
            }).each(function() {
              if(this.complete) $(this).load();
            });
            
            $(window).resize(function() {
                resize_bg();
            })

        }
        
        function resize_image_wrapper() {
          
          var minWidth = parseInt($("#container").css("min-width"));
          
          if ($("body").hasClass("home")) {
              var doc_width = $(window).width();
          } else {
              var doc_width = Math.max(($(window).width() - $("#content").outerWidth()), minWidth - $("#content").outerWidth());
          }
          
          var doc_height = $(window).height();
          
          $("#bg_image_wrapper").width(doc_width);
          $("#bg_image_wrapper").height(doc_height - parseInt($("#bg_image_wrapper").css("top")));
          
          
        }

        function resize_bg() {
            var minWidth = parseInt($("#container").css("min-width"));

            $(".bg_image").css("left", "0");
            if ($("body").hasClass("home")) {
                var doc_width = $(window).width();
            } else {
                var doc_width = Math.max(($(window).width() - $("#content").outerWidth()), minWidth - $("#content").outerWidth());
            }
            
            

            var doc_height = $(window).height();
                        
            if($("#tabs").size()) {
              var image_width = $("#tabs-1 .bg_image").width();
              var image_height = $("#tabs-1 .bg_image").height();
            } else {
              var image_width = $(".bg_image").width();
              var image_height = $(".bg_image").height();
            }
            
            if(image_width == 0) {
              image_width = lastImageWidth
            
            }
            
            if(image_height == 0) {
              image_height = lastImageHeight;
            }
             
            var image_ratio = image_width / image_height;
            
            var new_width = doc_width;
            var new_height = Math.round(new_width / image_ratio);
            
            if (new_height < doc_height) {
                new_height = doc_height;
                new_width = Math.round(new_height * image_ratio);
                var width_offset = Math.round((new_width - doc_width) / 2);

                $(".bg_image").css("left", "-" + width_offset + "px");
            }

            $("#bg_image_wrapper").width(doc_width);
            $("#bg_image_wrapper").height(doc_height - parseInt($("#bg_image_wrapper").css("top")));

            $(".bg_image").each(function(idx, item) {
              $(item).width(new_width);
              $(item).height(new_height);
              // $(item).css({"display": "none", "margin-left": 0});
              $(item).fadeIn(500);
            });

            var newContentSize = $("#bg_image_wrapper").height();
            if (!$("body").hasClass("home")) {
                if (!$.browser.msie) {
                    newContentSize -= (parseInt($("#content").css("padding-top")) + parseInt($("#content").css("padding-bottom")) + $("footer").height() + 10);
                }
                $("#content").css({
                    "min-height": newContentSize
                });
            } else {
                $("#content").css({
                    "top": newContentSize - $("#content").height() - 32,
                    "padding-top": 0
                });
            }
            
            //console.log("new_width "+new_width)
            lastImageWidth = new_width;
            lastImageHeight = new_height;
        }

        if ($(this).size() > 0) {
            init();
        }
    };

    $.fn.navDropDown = function() {
        // Nav drop down menu
        //cache nav
        var nav = $("nav");
        //add indicators and hovers to submenu parents
        nav.find("li").each(function() {
            if ($(this).find("div.submenu").length > 0) {
                //show subnav on hover
                $(this).mouseenter(function() {
                    //expand header
                    if($(this).hasClass("nav-item-audioplayer")) {
                      $("header").stop(true, true).animate({
                          height: 90
                      },
                      250);
                    } else {
                      if ($(this).find("li").length > 2) {
                          $("header").stop(true, true).delay(200).animate({
                              height: 140
                          },
                          250);
                      } else {
                          $("header").stop(true, true).delay(200).animate({
                              height: 125
                          },
                          250);
                      }
                    }
                    
                    if ($("html").hasClass("ie6") || $("html").hasClass("ie7") || $("html").hasClass("ie8")) {
                        $(this).find("div.submenu").stop(true, true).delay(300).show();
                    } else {
                        $(this).find("div.submenu").stop(true, true).delay(300).fadeIn(250);
                    }
                });

                //hide submenus on exit
                $(this).mouseleave(function(event) {
                    //contract header
                    $("header").delay(400).animate({
                        height: 90
                    },
                    250);
                    
                    if ($("html").hasClass("ie6") || $("html").hasClass("ie7") || $("html").hasClass("ie8") || $("html").hasClass("ie8")) {
                        $(this).find("div.submenu").stop(true, true).hide();
                    } else {
                        $(this).find("div.submenu").stop(true, true).fadeOut(250);
                    }
                });
            }
        });
        
        //audio player launcher
        var audio_player_link = $("#launch-audio-player a").click(function(event){
          event.preventDefault();
          window.open("/audio_player/",'iamyou_audio_player',"menubar=0,resizable=0,scrollbars=1,width=340,height=274");
        });

    }
    

    function animate_loading() {
        if ($('body').find('div.loading').length < 1) {
            clearInterval(loadingTimer);
            return;
        }
        $('div.loading').css('background-position', '0 ' + (loadingFrame * -40) + 'px');

        loadingFrame = (loadingFrame + 1) % 12;
    };

    function showLoader() {
        if ($('body').find('div.loading').length < 1) {
            $("<div class='loading'></div>").hide().appendTo("#content").fadeIn('fast');
            loadingTimer = setInterval(animate_loading, 66);
        }
    }

    function hideLoader() {
        $('div.loading').fadeOut('fast',
        function() {
            $(this).remove();
        });
    }

    // Home =====================================================
    $.fn.home = function() {

        function init() {
            $('#tabs').tabs({ fx: { opacity: 'toggle', duration: 1000, easing: 'easeInOutCubic' } });
            //$('#tabs').tabs();
            $('#tabs').tabs("rotate", 5000);
        }

        if ($(this).size() > 0) {
            init();
        }
    };

    // Yoga =====================================================
    $.fn.yoga = function() {

        function init() {
            $("#page_menu").find("a").each(function() {
                $(this).click(function() {

                    var href = $(this).attr('href');
                    showLoader();

                    $(this).parent().addClass("selected").siblings("li.selected").removeClass("selected");

                    $.getJSON(href + "/json",
                    function(data) {

                        hideLoader();
                        //replace content
                        $("#page-content").fadeOut("fast",
                        function() {
                            $(this).html("<h1>" + data.title + "</h1>" + data.content);
                            $(this).fadeIn();
                        });
                        if (data.background_image != null && data.background_image != '') {

                            $(".bg_image").fadeOut("fast",
                            function() {
                                $(this).attr({
                                    "src": "/images/pages/" + data.background_image
                                });
                                $(this).fadeIn();
                            });
                        }
                    });
                    return false;
                });
            });
        }

        if ($(this).size() > 0) {
            //init();
        }
    };

    // Nourishment ===============================================
    $.fn.nourishment = function() {

        function init() {}

        if ($(this).size() > 0) {
            init();
        }
    };

    // Music =====================================================
    $.fn.music = function() {

        function init() {}

        if ($(this).size() > 0) {
            init();
        }
    };

    // Schedule ==================================================
    $.fn.schedule = function() {

        function init() {

            $(".cal_nav").find("a").each(function() {
                $(this).click(function() {

                    showLoader();

                    var href = $(this).attr('href');

                    $.getJSON(href + "/json",
                    function(data) {
                        $("#class-list").fadeOut('fast',
                        function() {
                            hideLoader();
                            $(this).empty();
                            $.each(data.classes,
                            function(i, classes) {
                                var li = '<li><div class="class-details"><span class="class-day">' + classes.day + " "+classes.date+ '</span><span class="class-time">' + classes.time.replace(":00", "") + '</span>';
                                if (classes.description != '') {
                                    li += '<span class="class-status">' + classes.description + '</span>';
                                }
                                li += '</div>';
                                if(classes.status != "no_rsvp"){
	                                li += '<a class="rsvp button" href="mailto:rsvp@iamyoustudio.com?subject=I.AM.YOU. Studio | RSVP ' + escape(classes.date) + '">RSVP</a></li>';
                                }
                                $("#class-list").append(li);
                            });

                            $('.current').html(data.context.current.label);
                            $('.prev a').html(data.context.prev.label).attr({
                                'href': '/schedule/week/' + data.context.prev.link
                            });
                            $('.next a').html(data.context.next.label).attr({
                                'href': '/schedule/week/' + data.context.next.link
                            });
                            if ($.browser.msie) {
                                $(this).show();
                            } else {

                                $(this).fadeIn();
                            }
                        });

                    });

                    return false;
                });
            });
        }

        if ($(this).size() > 0) {
            init();
        }
    };

    // Event Schedule ==================================================
    $.fn.events = function() {

        function init_nav() {
            $(".cal_nav").find("a").each(function() {

                $(this).click(function() {

                    showLoader();

                    var href = $(this).attr('href');
                    $.getJSON(href + "/json",
                    function(data) {
                        // $(this).fadeIn();
                        $(".calendar").stop(true, true).fadeOut('fast',
                        function() {

                            var col = 0;
                            var row = 1;
                            var tableData = "<tr>";

                            //if this month does not start on a Sunday, add empty cells
                            if (data.context.startsOn != 7) {
                                for (col = 0; col < data.context.startsOn; col++) {
                                    tableData += "<td></td>";
                                }
                            }

                            //write this months dates
                            for (var i = 1; i < data.context.totalDays + 1; i++) {

                                if (data.calendar_data[i]) {
                                    var cal_event = data.calendar_data[i];
                                    tableData += "<td><div class=\"content\"><div class=\"cal_event\" title=\"" + cal_event.id + "\" style=\"";
                                    if (cal_event.calendar_image != "") {
                                        tableData += "background-image:url('/images/events/" + cal_event.calendar_image + "');";
                                    }
                                    tableData += "\"><img src=\"/media/spacer.gif\" class=\"overlay\" /><p>" + cal_event.title + "</p></div><p class=\"date\">" + i + "</p></div></td>";
                                } else {
                                    tableData += "<td><p class=\"date\">" + i + "</p></td>";
                                }

                                //adjust cell position
                                col++;
                                if (col > 6 && i != data.context.totalDays) {
                                    tableData += "</tr><tr>";
                                    col = 0;
                                    row++;
                                }
                            }

                            //close it up
                            if (col != 0) {
                                for (col; col < 7; col++) {
                                    tableData += "<td></td>";
                                }
                            }

                            tableData += "</tr>";
                            $("table.calendar tbody").html(tableData);

                            //update sidebar
                            $("#events_list").empty();
                            var lastId = 0;
                            var unique_events_count = 0;
                            $.each(data.calendar_data,
                            function(i, events) {
                                if (events.id != lastId) {
                                    lastId = events.id;
                                    unique_events_count++;
                                    var li = '<li class="content" title="' + events.id + '" style="display:none;"><span class="event_date">' + events.date + '</span><h3>' + events.title + '</h3><div class="event_details">' + events.description + '</div></li>';
                                    $(li).appendTo("#events_list").hide();
                                }
                            });
                            
                            $.each(data.upcoming_data,
                             function(i, events) {
                                 if (events.id != lastId) {
                                    if(unique_events_count+(i+1) > data.max_events_count) {
                                      return;
                                    }
                                    
                                     lastId = events.id;
                                     var li = '<li class="content upcoming_event" title="' + events.id + '" style="display:none;"><span class="event_date">Coming Up - ' + events.date + '</span><h3>' + events.title + '</h3><div class="event_details">' + events.description + '</div></li>';
                                     $(li).appendTo("#events_list").hide();
                                 }
                             });

                            $('.current').html(data.context.current.label);
                            $('.prev a').html(data.context.prev.label).attr({
                                'href': '/events/cal/' + data.context.prev.link
                            });
                            $('.next a').html(data.context.next.label).attr({
                                'href': '/events/cal/' + data.context.next.link
                            });

                            $(".calendar").fadeIn('slow', init);


                            hideLoader();
                        });

                    });

                    return false;
                });
            });
        }

        function selectEvent(id) {
            $(".calendar").find(".selected_cal_event").removeClass('selected_cal_event');
            $(".calendar").find(".cal_event[title='" + id + "']").parent().addClass('selected_cal_event');
        }

        function init() {

            $("#main").find(".content").each(function(i) {

                $(this).click(function(i) {
                    var selected = null;
                    var eventId = 0;
                    if ($(this).find(".event_details").length) {
                        eventId = $(this).attr('title');
                        selected = $(this);
                    } else {
                        eventId = $(this).find('.cal_event').attr('title');
                        selected = $("#events_list").children("li[title='" + eventId + "']");
                    }
                    if (!selected.hasClass('selected')) {
                        selectEvent(eventId);
                        selected.addClass('selected').find(".event_details").slideToggle().parent().siblings("li.selected").removeClass("selected").find(".event_details").slideToggle();
                    } else {

                        $(".calendar").find(".selected_cal_event").removeClass('selected_cal_event');
                        selected.removeClass("selected").find(".event_details").slideToggle();
                    }
                });
            });

            $("table.calendar tbody").find(".content").each(function(i) {
                $(this).hide().delay(i * 66).fadeTo("fast", ".1",
                function() {
                    $(this).find(".cal_event").find("p:first").each(function() {
                        if ($(this).height() > 0) {
                            $(this).css({
                                "margin-top": 80 - parseInt($(this).height())
                            });
                        }
                    });
                    $(this).fadeTo("slow", 1);
                });
            });

            $("#events_list").find(".content").each(function(i) {
                if ($.browser.msie) {
                    $(this).show();
                } else {
                    $(this).hide().delay(i * 66).fadeIn();
                }
            });

            var urlArray = (location.href).split("/");
            if (urlArray[urlArray.length - 2] == "id") {
                $("#main").find(".cal_event[title='" + urlArray[urlArray.length - 1] + "']").parent().trigger("click");
            }
        }

        if ($(this).size() > 0) {
            init();
            init_nav();
        }
    };

    // Blog =====================================================
    var blogLoadCount = 1;
    $.fn.blog = function() {
        function loadposts() {

            var href = "/blog/posts/" + blogLoadCount + "/5";

            showLoader();

            blogLoadCount++;
            $.getJSON(href + "/json",
            function(data) {

                if (data.hasOwnProperty('posts')) {

                    hideLoader();
                    $.each(data.posts,
                    function(i, post) {

                        var newDate = new Date();
                        newDate.setTime(post['unix-timestamp'] * 1000);
                        var month = "January";
                        switch (newDate.getUTCMonth()) {
                        case 1:
                            month = "February";
                            break;
                        case 2:
                            month = "March";
                            break;
                        case 3:
                            month = "April";
                            break;
                        case 4:
                            month = "May";
                            break;
                        case 5:
                            month = "June";
                            break;
                        case 6:
                            month = "July";
                            break;
                        case 7:
                            month = "August";
                            break;
                        case 8:
                            month = "September";
                            break;
                        case 9:
                            month = "October";
                            break;
                        case 10:
                            month = "November";
                            break;
                        case 11:
                            month = "December";
                            break;
                        }
                        var suffix = "th";
                        var day = newDate.getUTCDate();
                        var lastDigit = day < 10 ? day.toString().substr(1, day.toString().length - 1) : day;
                        switch (lastDigit) {
                        case 1:
                            suffix = 'st';
                            break;
                        case 2:
                            suffix = 'nd';
                            break;
                        case 3:
                            suffix = 'rd';
                            break;
                        }
                        var dateString = month + " " + newDate.getUTCDate() + suffix + ", " + newDate.getUTCFullYear();

                        var li = '<li class="post"><span class="post_date">' + dateString + '</span><span class="post_type">' + post['type'] + '</span>';
                        li += '<div class="post_body">';
                        //create post body based on content type
                        switch (post['type']) {
                        case "link":
                            li += '<a href="' + post['link-url'] + '">' + post['link-text'] + '</a>';
                            li += '<div>' + post['link-description'] + '</div>';
                            break;
                        case "photo":
                            li += '<img src="' + post['photo-url-500'] + '" />';
                            li += '<div>' + post['photo-caption'] + '</div>';
                            break;
                        case "audio":
                            li += '<div>' + post['audio-player'] + '</div>';
                            li += '<div>' + post['audio-caption'] + '</div>';
                            break;
                        case "video":
                            li += '<iframe class="youtube-player" type="text/html" width="500" height="311" src="' + (post['video-source']).replace("watch?v=", "embed/") + '" frameborder="0"></iframe>';
                            li += '<div class="post_caption">' + post['video-caption'] + '</div>';
                            break;
                        default:
                            li += '<h3>' + post['regular-title'] + '</h3><div>' + post['regular-body'] + '</div>';
                            break;
                        }
                        li += '</div>';
                        //add tags
                        li += '<ul class="post_tags">';
                        $.each(post.tags,
                        function(i, tag) {
                            li += '<li><a href="blog/tagged/' + tag + '">' + tag + '</a></li>';
                        });
                        li += '</ul><span class="clear"></span></li>';

                        $(li).appendTo('#blog_posts').fadeIn();
                    });

                }
            });
        }

        function init() {


            }

        if ($(this).size() > 0) {

            if (!$("body").hasClass("archive")) {
                init();
                $(window).scroll(function() {
                    if (blogLoadCount < 6) {
                        var prevY = $('#blog_posts').offset().top + $('#blog_posts').height() - $(this).scrollTop();
                        if (prevY < $(window).height()) {
                            loadposts();
                        }
                    } else {
                        $(document).unbind("scroll");

                    }
                })


                $('<div class="clear"><a href="/blog/archive/" class="prev">MORE</a></div>').appendTo(".col-right").click(function() {
                    loadposts();
                    return false;
                });
            }
        }
    };

    //archive has a diff layout, so lazyload accordingly
    $.fn.blogArchive = function() {

        function initNav() {
            //init prev button
            $('.prev').click(function() {

                $(this).hide();
                showLoader();

                var href = $(this).attr('href') + "/" + ($("#blog_archive").find('li.post').length - 1);

                $.getJSON(href + "/json",
                function(data) {

                    if (data.posts.length < 1) {
                        location.href = href;
                    } else {

                        hideLoader();
                        $("#blog_archive").append('<li class="post-month post-more"><h3>' + data.context.current.label + '</h3></li>');


                        $.each(data.posts,
                        function(i, post) {
                            var li = '<li class="post"><div class="post_wrapper"><a href="/blog/post/' + post.id + '/' + post.slug + '" class="post_link">';
                            switch (post.type) {
                            case "link":
                                li += '<div><h3><a href="' + post['link-url'] + '">' + post['link-text'] + '</a></h3>' + post['link-description'] + '</div>';
                                break;
                            case "photo":
                                li += '<div class="thumb_wrapper"><img src=' + post['photo-url-250'] + ' class="thumb" /></div>';
                                break;
                            case "video":
                                var videoThumb = String(post['video-source']).split('=');
                                li += '<div class="thumb_wrapper"><img src="http://img.youtube.com/vi/' + videoThumb[1] + '/0.jpg" class="thumb" /></div>';
                                break;
                            default:
                                li += '<div>' + post['regular-body'] + '</div>';
                                break;
                            }
                            li += '</div>';
                            var date = post['date'].split(" ");
                            var suffix = "th";
                            switch (date[1]) {
                            case 1,
                                11,
                                21,
                                31:
                                suffix = "st";
                                break;
                            case 2,
                                12,
                                22:
                                suffix = "nd";
                                break;
                            case 3,
                                13,
                                23:
                                suffix = "rd";
                                break;
                            default:
                                suffix = "th";
                                break;
                            }
                            li += '<div class="caption"><div class="post_date">' + date[2] + ' ' + date[1] + '</div>';
                            li += '</div><img src="/media/spacer.gif" class="overlay" /></a></li>'
                            $(li).appendTo("#blog_archive").fadeIn();

                        });

                        init();
                        $('.prev').attr({
                            'href': '/blog/archive/' + data.context.prev.link
                        }).show();
                    }
                });

                return false;
            });
        }

        //add event listeners to thumbs
        function initThumbs() {
            $("#main").find("a.post_link").each(function() {
                $(this).mouseover(function() {
                    $(this).find(".caption").fadeIn();
                }).mouseout(function() {
                    $(this).find(".caption").fadeOut();
                })
            });


        }

        if ($(this).size() > 0) {
            initThumbs();
            initNav();
            $(window).scroll(function() {
                var prevY = $('.prev').offset().top - $(this).scrollTop();
                if (prevY < $(window).height()) {
                    $('.prev:visible').trigger('click');
                }
            })
        }
    };

    // Gallery =====================================================
    $.fn.gallery = function() {

        function initFancyBox() {
            $("a[rel=photoset]").fancybox({
                'width': 880,
                'autoScale': true,
                'modal': false,
                'padding': 0,
                'margin': 130,
                'cyclic': true,
                'overlayOpacity': .92,
                'overlayColor': '#000',
                'centerOnScroll': false,
                'onStart': function() {},
                'onComplete': function(links, index) {
                    if (index != 0) {
                        $("#fancybox-right").css({
                            "margin-left": "72px"
                        });
                    } else {
                        $("#fancybox-right").css({
                            "margin-left": 0
                        });
                    }
                }
            });
            
            //update all youtube urls for modal
             $("a[rel=videoset]").each(function(index, item){
               var href = $(item).attr("href");
               var modal_href = href.replace(new RegExp("watch\\?v=", "i"), 'v/');               
               $(item).attr("href", modal_href);
             })
            
            $("a[rel=videoset]").fancybox({
                'width'   : 640,
                'height'    : 390,
                'modal': false,
                'autoScale'   : false,
                'transitionIn' : 'none',
                'transitionOut'  : 'none',
                'padding': 0,
                'margin': 130,
                'cyclic': true,
                'overlayOpacity': .92,
                'overlayColor': '#000',
                'centerOnScroll': false,
                'href'      : this.href,
                'type': 'swf',
                'swf' : {
                  'wmode'    : 'transparent',
                  'allowfullscreen' : 'true'
                },
                'showTitle': true,
                'titlePosition': 'outside',
                'onStart': function(currentArray,currentIndex,currentOpts) {
                  var obj = currentArray[ currentIndex ]; 
                  this.title = "<h2>"+$(obj).attr("title")+"</h2>";
                  this.title += "<h3 class=\"view\">"+$(obj).attr("data-date")+" - "+$(obj).attr("data-views")+" views</h3>";
                  if($(obj).attr("data-desc") != "") {
                    this.title += "<p class=\"desc\">"+$(obj).attr("data-desc")+"</p>";
                  }
                }
            });

        }

        function getGalleryStream(href) {
            if ($('body').hasClass('overview')) {
                $('body').removeClass('overview');
            }

            $("#photo_wrapper").empty();
            $("#gallery_list").empty();
            showLoader();
            $.getJSON(href + "/json",
            function(data) {

                $.each(data.photos,
                function(i, photo) {
                    var li = '<li class="thumb"><a rel="photoset" href="' + photo['photo_link']['source'] + '">';
                    li += '<img src="' + photo['photo']['source'] + '" alt="' + photo['title'] + '" /></a></li>';
                    $(li).appendTo("#photo_wrapper").hide().fadeIn();
                });

                $('<li><a href="/gallery">overview</a></li>').appendTo("#gallery_list");
                $.each(data.sets.photoset,
                function(i, photoSet) {

                    li = '<li><a href="/gallery/set/' + photoSet['id'] + '/' + escape(photoSet['title']) + '">' + photoSet['title'] + '</a></li>';
                    if (data.set_title == photoSet['title']) {
                        $(li).addClass('selected').click(function() {
                            return false;
                        }).appendTo("#gallery_list");

                    } else {
                        $(li).click(function() {
                            var href = $(this).find("a").attr('href') + "/json";
                            getGalleryStream(href)
                            return false;
                        }).appendTo("#gallery_list");
                    }
                });

                hideLoader();
                initFancyBox();
            });
        }


        function init() {
            if ($("body").hasClass("overview") || $("body").hasClass("videos")) {
                $("#main").find(".thumb a").each(function() {
                    $(this).mouseenter(function() {
                        $(this).find(".caption").fadeIn();
                    }).mouseleave(function() {
                        $(this).find(".caption").fadeOut();
                    });
                });
            }
        }

        if ($(this).size() > 0) {
            init();
            initFancyBox();
        }
    };

    // About =====================================================
    $.fn.about = function() {

        function init() {

            }

        if ($(this).size() > 0) {
            init();

        }
    };

    // Testimonials =====================================================
    $.fn.testimonials = function() {
      //alert("test!")
      $("#testimonial_list").accordion(
        {
          header: '.header',
          collapsible: true,
          active: false,
          autoHeight: false,
          changestart: function(event, ui) {
            ui.newHeader.find("a.btn_toggle").fadeOut('fast',
            function() {
                $(this).text("Close");
                $(this).fadeIn('fast');
            });
            
            ui.oldHeader.find("a.btn_toggle").fadeOut('fast',
            function() {
                $(this).text("More");
                $(this).fadeIn('fast');
            });            
          }
        }
        
        );
    }
    
    // Shop ==============================================================
    $.fn.shop = function() {
      //alert("test!")
      $("#shop-list").accordion(
        {
          header: '.btn_toggle',
          collapsible: true,
          active: false,
          autoHeight: false,
          changestart: function(event, ui) {
            ui.newHeader.fadeOut('fast',
            function() {
                $(this).text("Close");
                $(this).fadeIn('fast');
            });
            
            ui.oldHeader.fadeOut('fast',
            function() {
                $(this).text("More");
                $(this).fadeIn('fast');
            });            
          }
        }
        
        );
    }


})(this.jQuery);
