/* 

Author: Mr. Henry
Date: 2008-12-24

Fueled by jQuery

*/

// Note: No conflict function

// This function must be called after including the jQuery javascript file, but before including any other conflicting library, 
// and also before actually that other conflicting library gets used, in case jQuery is included last. noConflict can be called at 
// the end of the jQuery.js file to globally disable the $() jQuery alias. jQuery.noConflict returns a reference to jQuery, so it 
// can be used to override the $() alias of the jQuery object.
// Use jQuery via jQuery(...)
// jQuery.noConflict();

jQuery(document).ready(function(){
    
    $.localScroll();
    
    /* Newsletter
    -----------------------------------------------------*/
    var input_text_color    = "#3C3C3C";
    
    jQuery(".newsletter input[type=text]").focus(function(){
        jQuery(this).attr("value","").css({ 'color': input_text_color });
    });
    
    jQuery(".newsletter input[type=text]").blur(function(){
       if(jQuery(this).attr("value") == ""){
           jQuery(this).attr("value","your e-mail address goes here...");
       }
    });
    
    $(".newsletter button[type=submit]").click(function() {
        var post_url            = $(this).parents("form").attr("action");
        var cm_email            = $("#cm-email");
        var css_input_success   = {
            'color' : '#06B259'
        };
        var css_input_error     = {
            'color' : '#d92400',
            'borderColor' : '#d92400'
        };
        
        if (post_url == "undefined" || post_url == "") return false; // Check if form action is defined
        if (cm_email.val() == "") { // Check if email isn't empty
            cm_email.css(css_input_error);
            return false;
        }
        
        var data_string = "cm_email=" + cm_email.val();
        
        $.ajax({
            type: "POST",
            url: post_url,
            data: data_string,
            success: function(data) {
                if (data == "Success") {
                    cm_email.val("It was a success").css(css_input_success);
                } else {
                    cm_email.css(css_input_error);
                };
            }
        });
        
        return false;
        
    });
    
    
    /* Search
    -----------------------------------------------------*/
    jQuery(".search input[type=text]").focus(function(){
        jQuery(this).attr("value","");
    });
    
    jQuery(".search input[type=text]").blur(function(){
       if(jQuery(this).attr("value") == ""){
           jQuery(this).attr("value","What are you looking for?");
       }
    });
    
    
    /* Flickr badge
    -----------------------------------------------------*/
    $(".flickr a").eq(2).css("margin-right","0");
    
    
    /* Category filter
    -----------------------------------------------------*/
    jQuery(".filter-the-fuzz a").click(function(event){
        event.preventDefault();
        var status              = null;
        var cat_name            = jQuery(this).attr("class");
        var post_url            = template_url + "/test.php";
        
        if ($.cookie('mrhenry_blog_cats') == null) {
          mrhenry_blog_cats     = new Array("1","1","1","1","1","1");
        } else {
          mrhenry_blog_cats  = $.cookie('mrhenry_blog_cats').split(',');
        }
        
        if(jQuery(this).parent().attr("class") == "active" || jQuery(this).parent().attr("class") == "active even"){
            state = 0;
        } else {
            state = 1;
        }
        
        switch(cat_name){
            case "coding":
                mrhenry_blog_cats[0] = state;
                status = mrhenry_blog_cats.join(",");
                break;
            case "sexual-thrills":
                mrhenry_blog_cats[1] = state;
                status = mrhenry_blog_cats.join(",");
                break;
            case "internet":
                mrhenry_blog_cats[2] = state;
                status = mrhenry_blog_cats.join(",");
                break;
            case "sharing":
                mrhenry_blog_cats[3] = state;
                status = mrhenry_blog_cats.join(",");
                break;
            case "design":
                mrhenry_blog_cats[4] = state;
                status = mrhenry_blog_cats.join(",");
                break;
            case "mr-henry":
                mrhenry_blog_cats[5] = state;
                status = mrhenry_blog_cats.join(",");
                break;
        }
        
        $.cookie("mrhenry_blog_cats", status, {path: "/"});
        location.reload();
        //jQuery.post(post_url, { cat_name: cat_name, status: status } );
    });
    
    
    /* Slideshow
    -----------------------------------------------------*/
    var slideshowId = null;
    var length      = null;
    var imgWidth    = null;
    var prevId      = null;
    var posX        = imgWidth;
    var transTime   = 1000;
    
    initializeSlideshow();
    
    // Browse through slideshow by navigation
    jQuery(".slideshow-navigation li").click(function(){
        var container = jQuery(this).parent().prevAll(".slideshow-container");
        if (!(jQuery(this).hasClass("active"))){
            if (!(container.is(":animated"))){
                var currPicture = container.children(":visible");
                var currId      = currPicture.attr("id").charAt(currPicture.attr("id").length - 1);
                var nextId      = jQuery(this).html();
                var nextPicture = container.children(".slideshow", this).eq(nextId - 1);
                
                if (nextId == currId) { 
                  return false; 
                } else if (nextId > currId) {
                    posX    = imgWidth;
                } else {
                    posX    = -imgWidth;
                };
                
                slideTheShow(container, currPicture, nextPicture);
                setActiveButton(nextPicture);
            }
        }
    });
    
    // Browse through slideshow by clicking on the image
    jQuery(".entry img").click(function(){
        if (jQuery("body").attr("id") != "post") { 
            slideshowLinkToPost($(this)); 
            return false; 
        }
        var container = jQuery(this).parent(); 
        if (!(container.is(":animated")) && container.children().length > 1){
            var currPicture = container.children(":visible");
            var currId      = currPicture.attr("id").charAt(currPicture.attr("id").length - 1);
            var nextId      = parseInt(currId) + 1;
            
            if (nextId > container.children().length) {
                nextId  = 1;
                if (nextId == currId) {
                    return false;
                }
                posX    = -imgWidth;
            } else {
                posX    = imgWidth;
            }

            var nextPicture = container.children().eq(nextId - 1);
            
            slideTheShow(container, currPicture, nextPicture);
            setActiveButton(nextPicture);
        }
    });
    
    // Fly to a specific picture into a slideshow through a link
    jQuery("a.wpGallery").click(function(){
       console.log($(this).attr("href"));
       
       return false; 
    });
    
    function initializeSlideshow(){
        if (jQuery("body").attr("id") == "post") {
            jQuery("div.entry").each(function(){
              jQuery("p", this).each(function(){
                jQuery("img.slideshow", this).css({ 'border':'none', 'margin-left':'0' }).wrapAll('<div class="slideshow-container"></div>');
                cssObj      = {
                        'position'      : 'relative',
                        'border'        : '5px solid #272727',
                        'overflow'      : 'hidden',
                        'margin-left'   : '-5px',
                        'width'         : '490px',
                        'height'        : '340px'
                };

                jQuery(".slideshow-container").parent().css(cssObj);

                length      = jQuery("img.slideshow", this).length;
                imgWidth    = jQuery("img.slideshow:first").width();

                // Initialize navigation 
                if (length > 1) {
                    var navigation = '<ul class="slideshow-navigation">';
                    slideshowId = slideshowId + 1;
                    for (var i = 0; i < length; i++) {
                        if (i == 0) {
                            navigation = navigation + '<li class="active">' + (i + 1) + '</li>';
                        } else {
                            navigation = navigation + '<li>' + (i + 1) + '</li>';
                        }
                        jQuery("img.slideshow", this).eq(i).attr("id","slideshow-" + slideshowId + "-img-" + (i + 1)); // give every image an ID
                    }
                    navigation = navigation + '</ul>';
                    jQuery(".slideshow-container", this).parent().append(navigation);
                } else { 
                    jQuery("img.slideshow", this).css("cursor","default");
                };

                // Show first one, hide the others
                jQuery(".slideshow", this).css("display","none");
                jQuery(".slideshow:first", this).css("display","block");

                jQuery(".slideshow", this)
              });
            });
        } else {
            
        }
    }
    
    function setActiveButton(picture){
        activeId = picture.attr("id").charAt(picture.attr("id").length - 1);
        navContainer = picture.parents("p").find(".slideshow-navigation");
        navContainer.children().each(function(){
            if(jQuery(this).hasClass("active")){  
                jQuery(this).removeClass("active");
            }
        });
        navContainer.children().eq(activeId -1).addClass("active");
    }
    
    function slideTheShow(container, currPicture, nextPicture){
        cssObj      = {
          'display'   : 'block',
          'left'      : posX
        };
        nextPicture.css(cssObj);        
        container.animate({ left: -posX }, transTime, "easeOutExpo", function(){
            currPicture.css("display","none");
            nextPicture.css("left","0");
            container.css("left","0");
            currPicture = container.children("img:visible");
        });
    }
    
    function slideshowLinkToPost(el){
        window.location = el.parents(".post").children("h2").children("a[rel=bookmark]").attr("href");
    }
    
    
    /* Seconds alive
    ------------------------------------------------------
    ******************************************************
    Chit chat about Mr. Henry
    *****************************************************/
    var beginDate       = new Date(2006, 7, 1) //Month is 0-11 in JavaScript
    setTimeout(secondsRunning, 0);
    
    function secondsRunning() {
        var today		      = new Date();
        var milliseconds  = Math.round((today.getTime() - beginDate.getTime()));
    	var string		    = milliseconds + "";
        regex             = /(\d)(\d{3})(,|\.|$)/;
        
        var match;
        
        string = string.replace(regex,"$1,$2$3");
        string = string.replace(regex,"$1.$2$3");
        string = string.replace(regex,"$1.$2$3");
        string = string.replace(regex,"$1.$2$3");
        string = string.replace(regex,"$1.$2$3");
        while(true){
            match = string.replace(/(\d|\.|,)(\d|\.|$|,)/,"<span class='n$1'>$1</span>$2");
            match = match.replace("n.","npoint");
            match = match.replace("n,","ncomma");
            if (match == string) {
                break;
            } else {
                string = match;
            }
        }

    	jQuery(".seconds-alive big").html(string);

      setTimeout(secondsRunning, 200);
      
    };
    
    
    /* Tha dirty mode :)
    ------------------------------------------------------
    ******************************************************
    Credits to the jQuery crew for the Konami-code-cather.
    UP-UP-DOWN-DOWN-LEFT-RIGHT-LEFT-RIGHT-B-A
    *****************************************************/
    var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
    if ( window.addEventListener ) {
        window.addEventListener("keydown", function(e){
            kkeys.push( e.keyCode );
            if ( kkeys.toString().indexOf( konami ) >= 0 ){
                changeMode();
            }
        }, true);
        
    }
    
    function changeMode(){
        kkeys       = [];
        currMode    = $.cookie("mrhenry_blog_mode");
        
        if (currMode == "holy") {
            $.cookie("mrhenry_blog_mode", "dirty", {path: "/"});
            jQuery("body").addClass("dirty");
            jQuery("body").prepend('<div class="flash">DIRTY MODE</div>');
            jQuery("#sidebar .about p").html("Mr. Henry is an all-round internet-bureau broadcasting live from Antwerp, Belgium! We build steady relationships, hot-ass websites, kick-ass applications, yummy designs and we look good doing it! Come see our work, we love our clients! (and mommies too ofcourse!)");
        } else {
            $.cookie("mrhenry_blog_mode", "holy", {path: "/"});
            jQuery("body").removeClass("dirty");
            jQuery("body").prepend('<div class="flash">HOLY MODE</div>');
            jQuery("#sidebar .about p").html("Mr. Henry is an all-round internet-bureau broadcasting HORNY from Antwerp, Belgium! We build steamy relationships, hot-ass websites, kick-ass applications, yummy designs and we look good doing it! Cum see our work, we massage our clients! (and your milf’s too ofcourse!)");
        }
        jQuery(".flash").fadeOut("slow", function(){ jQuery(".flash").remove(); });
    }
    
    
    /* Mysteries!
    ------------------------------------------------------ */
    jQuery(".mysteries-solved").dblclick(function(){
        window.location = blog_url + "/category/mysteries/";
    });
        
    
    /* Blockquote
    ------------------------------------------------------ */ 
    $("blockquote").each(function(){
        var offset = $(this).offset();
        var bg_pos  = 'left ' + (0 - Math.round(offset.top)) + "px";
        $(this).css({ 'background-position': bg_pos });
    });
    
    
    /* The mommy arrow
    ------------------------------------------------------ */
    if ($('#post').length > 0) {
        var mommy           = $('.mommy');
        var mommy_target    = $('#sidebar .about');
        var mommy_arrow     = '<img src="' + blog_url + '/wp-content/themes/mrblog/images/general/img-mommy-arrow.png" alt="Respect your mommy" class="mommy-arrow"/>';
        mommy.hover(
            function(){
                if ($(this).find('img').length <= 0) {
                    mommy_target.prepend(mommy_arrow);
                }
            },
            function(){
                mommy_target.find('img').fadeOut(100, function(){
                    $(this).remove();
                });
        });
    }
    
});
