$(function(){
/*  -------------------------------------------------------------------
    Show funtionality that need Javascript enabled (faster like that) - */
    $(".needjs").show();
	
	
/*  -------------------------------------------------------------------
    Add / Remove selected class from the iphone screen selector ------- 	
	$(".thumbs li a").click(function() {
		if($(this).hasClass('selected')) {
			$(".thumbs > li > a").removeClass('selected');
			$(this).addClass('selected');
		}
		else {
			$(".thumbs > li > a").removeClass('selected');
			$(this).addClass('selected');
		}
    });*/
	
	/*
	/* Show default content within .carousel-content */
	$(".carousel-content").show();
	
	/* Set the first menu item as active. */
	$("#carousel-menu li:first").addClass('selected');
	
	/* If menu item is clicked, switch content properly. */
	$("#carousel-menu li.menu-item").click(function(){

		var altText = $(this).find('.carousel-content-image img').attr("alt");
		var imgSrc = $(this).find('a.carousel').attr("href");
		var imgDesc = $(this).find('.info').html();
		
		if ($(this).is(".selected")) {
		return false;
		} else {
			
		$(".carousel-content").animate({ opacity: 1 }, 250 , function() { /*0*/ 
		$(".carousel-content-info").html(imgDesc).animate({ opacity: 15, marginBottom: "0" }, 400 ); /*0.85*/
		$(".carousel-content-image img").attr({ src: imgSrc , alt: altText }).animate({ opacity: 1 }, 400 );
		$(".carousel-content").animate({ opacity: 1 }, 250 );
		});
	}
	
	$("#carousel-menu li").removeClass('selected');
	$(this).addClass('selected');
	return false;
	
	});
	
	/* Pause Rotation if Hovering #carousel-menu Item */
	carouselNext = false;
	$("#carousel-menu li").hover(
	function () {
	carouselNext = true;
	},
	function () {
	carouselNext = false;
	}
	);
	
	
	
	/* Rotate Carousel, Move from :last to :first if necessary. */
	var carouselNextClick = function(){
	if(!carouselNext) {
	
	var $nextElement = $(".selected").next("li.menu-item");
	
	if($("li.selected").hasClass("menu-last") ){
	$("#carousel-menu li:first").trigger("click");
	} else {
	$nextElement.trigger("click");
	}
	
	}
	};
	
	/* Pause between rotations in milliseconds. (3500 is 3.5 seconds) */
	setInterval(carouselNextClick, 4000); /*3500*/




/*  -------------------------------------------------------------------
    Archives Menu ----------------------------------------------------- */
    $(".b_yyyy").bind("click", function(){
        year = $(this).text();
        $(".b_yyyy").removeClass("selected");
        $(".list_months.open").hide();
        
        $(this).addClass("selected");
        $("#archives_"+year).show().addClass("open");
        return false;
    });


/*  -------------------------------------------------------------------
    External Link -----------------------------------------------------    */
    var allowedDomains = [location.hostname, "sixpixelsofseparation.com", "twistimage.com"];
    $("a[href^=http]")
    .filter(function(el){
        for ( var i=0; i < allowedDomains.length; i++ ) {
            if(this.href.indexOf(allowedDomains[i]) > -1) return false;
        }
        return true;
    })
    .bind("click", function(){ $(this).attr("target", "_blank"); });
    

/*  -------------------------------------------------------------------
    Share Post -------------------------------------------------------- */
    bubble = "";
    $("a.b_share", ".utilities")
    .bind("mouseenter", function(){
        window.clearTimeout(bubble);
        createShare($(this), "mouseenter");
        return false;
    })
    .bind("mouseleave", function(){
        obj    = $(this);
        bubble = window.setTimeout("createShare(obj,'mouseleave');",300);
        return false;
    })
    .bind("click", function(){
        return false;
    });
    
    $("a.b_twitter", ".utilities").bind("click", function(){
        postPermalink          = $(this).attr("rel");
        postPermalink_absolute = postPermalink.replace("http://" + location.hostname,"");
        postTitle              = $(this).attr("title");
        postTitle              = escape(postTitle.replace("Tweet This Post | ",""));
        openTwitter(postPermalink_absolute, postPermalink, postTitle, $(this), "");
        return false;
    });
    
    $("a.b_tweetthisvideo", "#p_1614").bind("click", function(){
        postPermalink          = $(this).attr("rel");
        postPermalink_absolute = postPermalink.replace("http://" + location.hostname,"");
        postTitle              = $(this).attr("title");
        postTitle              = escape(postTitle.replace("Tweet This | ",""));
        openTwitter(postPermalink_absolute, postPermalink, postTitle, $(this), "Check out");
        return false;                                                   
    });


/*  -------------------------------------------------------------------
    Search ------------------------------------------------------------ */
    $("#frm_search").submit(function(){
        if($("input#search", this).val()!=""){
            $("#frm_search").attr("action", "/search/" + $("input#search", "#frm_search").val());
        }else{
            return false;    
        }
    });    
    $("input#b_submit")
    .bind("mouseover focus", function(){ $(this).attr("src", "/spos/img/b_submit_o.gif"); })
    .bind("mouseout blur", function(){ $(this).attr("src", "/spos/img/b_submit.gif"); });


/*  -------------------------------------------------------------------
    Tags List --------------------------------------------------------- */
    $("li:lt(7)",".tags ul").css("display", "inline");
    $("li:last",".tags ul").after('<li class="tags_more"><a href="javascript:;" onclick="toggleTags(this);">view all</a></li>');

/*  -------------------------------------------------------------------
    Subscribe --------------------------------------------------------- 
    $("#frm_subscribeemail").submit(function(){
        if($("input#email", this).val()!=""){
            return true;
        }else{
            return false;        
        }
    });*/

/*  -------------------------------------------------------------------
    Print ------------------------------------------------------------- */
    url=location.href;
    if(url.indexOf("#print")>=0){
        printPage();    
    }
    
/*  -------------------------------------------------------------------
    Google Analytics Event Tracking ----------------------------------- */
    //Upcoming Appearances
    $(".gatrack_appearances").bind("click", function(){
        pageTracker._trackEvent("Upcoming Appearances", "Clicked External Link", this.href);
    });
    
    //Feature Post
    $(".gatracking_featuredposts a").bind("click", function(){
        pageTracker._trackEvent("Featured Posts", "Clicked Link", $(this).attr("href"));
    });
    
    //Feature Episodes
    $(".gatracking_featuredepisodes a").bind("click", function(){
        pageTracker._trackEvent("Featured Episodes", "Clicked Link", $(this).attr("href"));
    });

    //Related Posts right after entry text
    $(".gatracking_relatedposts a").bind("click", function(){
        pageTracker._trackEvent('CTA', 'Entry Body - Related Entries', $(this).attr("href"));
    });
    
    //Order Book
    $(".gatracking_orderbook a").bind("click", function(){
        if($(this).text()=="Chapters - Indigo"){ txt = "Indigo - Chapters";    }
        else{ txt = $(this).text(); }
        pageTracker._trackEvent("Order Book", "Clicked Link", txt);
    });
    
    //Related Posts right after entry text
    $("a.gatracking_commentsfeed").bind("click", function(){
        pageTracker._trackEvent('CTA', 'Entry Body - Subscribe to comments', $(this).attr("href"));
    });
    
    
/*  -------------------------------------------------------------------
    Press Page -------------------------------------------------------- */
    if($("body").attr("id")=="p_press"){
        $('.expanded').cleverExpander({
            slicePoint:       200,  // default is 100
            expandText:       'Expand', // default is 'Read more...'
            userCollapseText: 'Collapse'  // default is '[collapse expanded text]'
        });
    }
    
/*  -------------------------------------------------------------------
    Smooth Anchor Scroll ---------------------------------------------- */
    $.localScroll({ lazy:false } );
});

/*  -------------------------------------------------------------------
    Tag Cloud --------------------------------------------------------- */    
    function tagcloudSplit(){ /*Damn MT*/
        $("li.rank3:first", "ul.tagcloud").prepend('<li class="ranksection_title">Sometimes he also writes about</li>');
        $("li.rank4:first", "ul.tagcloud").prepend('<li class="ranksection_title">And occasionally he mentions</li>');
    }


/*  -------------------------------------------------------------------
    Print Page -------------------------------------------------------- */    
    function printPage(){
        url = location.href;
        url = url.replace("#print","");
        url = url.replace("http://" + location.hostname,"");
        pageTracker._trackEvent("Print This", "Page", url);
        window.print();
    }
    

/*  -------------------------------------------------------------------
    Podcast Player ---------------------------------------------------- */    
    var newWindow = "";    
    function openPlayer(mp3){
        var url = "/podcast/player/?mp3=" + mp3;
        if (!newWindow.closed && newWindow.location) {
            newWindow.location.href = url;
        }else{
            newWindow = window.open(url,'Player','height=81,width=440');
            if(!newWindow.opener){ newWindow.opener=self; }
        }
        if(window.focus){ newWindow.focus(); }
    }


/*  -------------------------------------------------------------------
    Share Post -------------------------------------------------------- */
    var postPermalink;
    var postTitle;
    function createShare(obj, mouseevent){
        if(mouseevent=="mouseleave"){
            $(obj).children(".pi_share, .pi_stf").animate({"bottom": "45px", "opacity": 0}, 200, function(){ $(this).hide(); });
        }else{
            if($(obj).children(".pi_share").is("div")){
                $(obj).children(".pi_share").show();
                $(obj).children(".pi_share").animate({"bottom": "15px", "opacity": 1}, 200);
            }else{                
                postPermalink          = $(obj).attr("href");
                postPermalink_absolute = postPermalink.replace("http://" + location.hostname,"");
                postTitle              = $(obj).attr("title");
                postTitle              = escape(postTitle.replace("Share this post | ",""));

                /*Facebook*/
                popFBLink       = "http://www.facebook.com/sharer.php?u=" + postPermalink;
                popFBWinName    = "pop_fb";
                popFBFeatures   = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
                
                /*Delicious*/
                popDelLink      = "http://del.icio.us/post?v=4&noui&jump=close&tags=twistimage&url="+ postPermalink +"&title="+ postTitle + " - Six Pixels of Separation - Twist Image";
                popDelWinName   = "pop_delicious";
                popDelFeatures  = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
                
                /*Twitter*/
                popTwitterLink  = "http://twitter.com/home?status=" + postTitle + " " + postPermalink + " (via @mitchjoel)";
                
                /*Digg*/
                popDiggLink     = "http://digg.com/submit?phase=2&amp;url="+ postPermalink +"&title="+ postTitle + " - Six Pixels of Separation - Twist Image";
                popDiggWinName  = "pop_digg";
                popDiggFeatures = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
                
                /*Google Bookmarks*/
                popGBLink       = "http://www.google.com/bookmarks/mark?op=add&bkmk="+ postPermalink +"&title="+ postTitle + " - Six Pixels of Separation - Twist Image";
                popGBWinName    = "pop_GB";
                popGBFeatures   = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
                
                popShare =  '<div class="pi pi_style1color2 pi_share">';
                popShare += '    <div class="pi_content">';
                popShare += '        <ul>';
                popShare += '            <li><a href="javascript:;" onclick="openSTF(\''+postPermalink_absolute+'\', \''+postPermalink+'\',\''+postTitle+'\', this);return false;" class="i_stf">Send to a Friend</a></li>';
                popShare += '            <li><a href="'+ popFBLink +'" onclick="pageTracker._trackEvent(\'Share This\', \'Facebook\', \''+postPermalink_absolute+'\'); window.open(\''+popFBLink+'\',\''+ popFBWinName +'\',\''+ popFBFeatures +'\'); return false;" class="i_facebook">Share on Facebook</a></li>';
                popShare += '            <li><a href="'+ popDelLink +'" onclick="pageTracker._trackEvent(\'Share This\', \'Delicious\', \''+postPermalink_absolute+'\'); window.open(\''+popDelLink+'\',\''+ popDelWinName +'\',\''+ popDelFeatures +'\'); return false;" class="i_delicious">Add to Delicious</a></li>';
                popShare += '            <li><a href="'+ popGBLink +'" onclick="pageTracker._trackEvent(\'Share This\', \'Google Bookmarks\', \''+postPermalink_absolute+'\'); window.open(\''+popGBLink+'\',\''+ popGBWinName +'\',\''+ popGBFeatures +'\'); return false;" class="i_google">Add to Google</a></li>';
                popShare += '            <li><a href="'+ popDiggLink +'" onclick="pageTracker._trackEvent(\'Share This\', \'Digg\', \''+postPermalink_absolute+'\'); window.open(\''+popDiggLink+'\',\''+ popDiggWinName +'\',\''+ popDiggFeatures +'\'); return false;" class="i_digg">Digg This</a></li>';
                popShare += '            <li><a href="'+ popTwitterLink +'" onclick="openTwitter(\''+postPermalink_absolute+'\', \''+postPermalink+'\', \''+postTitle+'\', $(this)); return false;" class="i_twitter_blue">Tweet This</a></li>';
                popShare += '        </ul>';
                popShare += '    </div>';
                popShare += '    <div class="pi_bottom"></div>';
                popShare += '</div>';                
                
                $(obj).append(popShare);
                $(obj).children(".pi_share").animate({"bottom": "15px", "opacity": 1}, 200);
            };
        };
        return false;
    };


    function openTwitter(postPermalink_absolute, postPermalink, postTitle, obj, txt){
        oldclass = $(obj).attr("class");
        newclass = oldclass.replace("twitter", "loading");
        $(obj).attr("class", newclass);
        
        popTwitterLink      = $(obj).attr("href");
        popTwitterWinName   = "pop_twitter";
        popTwitterFeatures  = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
        $.ajax({
            type    : "GET",
            url     : "/spos/functions/trimURL.php",
            async   : false,
            data    : "url=" + postPermalink,
            success : function(shortPermalink){
                if(shortPermalink.indexOf("http://")==0){
                    if(txt=="Check out"){
                        popTwitterLink = "http://twitter.com/home?status=Check out @mitchjoel on " + postTitle + " " + shortPermalink;    
                    }else{
                        popTwitterLink = "http://twitter.com/home?status=" + postTitle + ": " + shortPermalink + " (via @mitchjoel)";
                    }
                }
            }
        });
        pageTracker._trackEvent("Share This", "Twitter", postPermalink_absolute);
        window.open(popTwitterLink, popTwitterWinName, popTwitterFeatures);
        $(obj).attr("class", oldclass);
    }


/*  -------------------------------------------------------------------
    Send To Friend ---------------------------------------------------- */
    function openSTF(postPermalink_absolute, postPermalink, postTitle, obj){
        popSTF     = '<div class="pi pi_style1color1 pi_stf">';
        popSTF += '    <div class="pi_content">';

        popSTF += '        <form id="frm_stf" method="post">';
        popSTF += '            <ol>';
        popSTF += '                <li>';
        popSTF += '                    <label for="stf_name">Your name <span>*</span></label>';
        popSTF += '                    <input id="stf_name" name="name" maxlength="200" class="v-mandatory" type="text" />';
        popSTF += '                </li>';
        popSTF += '                <li>';
        popSTF += '                    <label for="stf_email">Your email address <span>*</span></label>';
        popSTF += '                    <input id="stf_email" name="email" maxlength="200" class="v-mandatory v-email" type="text" />';
        popSTF += '                </li>';
        popSTF += '                <li>';
        popSTF += '                    <label for="stf_friend_name">Your friend\'s name <span>*</span></label>';
        popSTF += '                    <input id="stf_friend_name" name="friendname" maxlength="200" class="v-mandatory" type="text" />';
        popSTF += '                </li>';
        popSTF += '                <li>';
        popSTF += '                    <label for="stf_friend_email">Your friend\'s email address <span>*</span></label>';
        popSTF += '                    <input id="stf_friend_email" name="friendemail" maxlength="200" class="v-mandatory v-email" type="text" />';
        popSTF += '                </li>';
        popSTF += '            </ol>';
        popSTF += '            <div class="clearfix">';
        popSTF += '                <input value="Send" class="b_send" type="button" onclick="validateSTF()" />';
        popSTF += '                <a href="javascript:;" onclick="closeStf(this);" class="b_cancel">Cancel</a>';
        popSTF += '            </div>';
        popSTF += '        </form>';
        
        popSTF += '    </div>';
        popSTF += '    <div class="pi_bottom"></div>';
        popSTF += '</div>';
        
        //Append STF popin
        $(obj).parents(".pi_share:first").parent("a").append(popSTF);
    
        
        //Remove Mouseleave and ClearTimeout
        $(obj).parents(".b_share:first").unbind("mouseleave");
        window.clearTimeout(bubble);
    }
    
    
    function validateSTF(){        
        error=0;
        $(".v-mandatory", "#frm_stf").each(function(){
            if($(this).val()==""){ error++; }
        });
        $(".v-email", "#frm_stf").each(function(){
            if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,5})+$/.test($(this).val())){ error++; }
        });
        
        if(error==0){
            $.ajax({
                type: "GET",
                url: "/spos/functions/sendtoafriend.php",
                data: "stf_name="+ escape($("#stf_name").val()) +"&stf_email="+ escape($("#stf_email").val()) +"&stf_friend_name="+ escape($("#stf_friend_name").val()) +"&stf_friend_email=" + escape($("#stf_friend_email").val()) +"&postPermalink=" + postPermalink +"&postTitle=" + postTitle,
                success: function(msg){
                    popSTFsucess = '<div class="pi_stfsuccess">';
                    popSTFsucess += '        <p>'+ msg +'</p>';
                    popSTFsucess += '</div>';
                    popSTFsucess += '<div class="clearfix" style="clear:both;"><a href="javascript:;" onclick="closeStf(this);" class="b_cancel">Close</a></div>';

                    $("#frm_stf").html(popSTFsucess);
                    pageTracker._trackEvent('Share This', 'Send to a Friend', postPermalink_absolute);
                }
            });
        }else{
            if(!$("#stf_error").is("div")){
                $("ol", "#frm_stf").after("<div id='stf_error'>Please fill or correct all the fields above. Then click 'Send'.</div>");
            }
            return false;
        }
    }
    
    function closeStf(obj){
        $(obj).parents(".pi_stf:first").siblings(".pi_share").animate({"bottom": "45px", "opacity": 0}, 200, function(){ $(this).hide(); });
        $(obj).parents(".pi_stf:first").animate({"bottom": "45px", "opacity": 0}, 200, function(){ $(this).remove(); });    
    
        $(obj).parents(".b_share:first")
        .bind("mouseleave", function(){
            btn    = $(this);
            bubble = window.setTimeout("createShare(btn,'mouseleave');",300);
            return false;
        });
    }


/*  -------------------------------------------------------------------
    Comment Success Popin --------------------------------------------- */
    function openCommentSuccess(){
        page_url = location.href;
        page_url = page_url.replace("http://" + location.hostname,"");
        hash     = location.hash.slice(1).replace("#", "");
        
        pi =  '<div class="pi pi_style2color1 pi_commentsuccess">';
        pi += '    <div class="pi_content clearfix">';
        pi += '        <h4>Congratulations!</h4>';
        pi += '        <p>You passed the spam filter test that protects the Six Pixels of Separation blog from malicious comment-making robots, and your comment is now a part of the conversation.</p>';
        
            pi += '        <p class="cta_commentsfeed">';
            pi += '            <a href="comments.xml" onclick="pageTracker._trackEvent(\'CTA\', \'Comment Success - Subscribe to comments\', \''+ page_url +'\');" class="i_rss">';
            pi += '                Comments Feed';
            pi += '                <span>Subscribe to all comments for this post.</span>';
            pi += '            </a>';
            pi += '        </p>';

        pi += '        <a href="javascript:;" class="b" onclick="javascript:$(this).parents(\'.pi_commentsuccess:first\').animate({\'left\': \'-450px\', \'opacity\': 0}, 500);">Close</a>';    
        pi += '    </div>';
        pi += '    <div class="pi_bottom"></div>';
        pi += '</div>';        
        
        $("#"+hash).append(pi);
        $(".pi_commentsuccess").animate({"left": "-337px", "opacity": 1}, 500);
    }


/*  -------------------------------------------------------------------
    Tags -------------------------------------------------------------- */    
    function toggleTags(obj){
        if($(obj).text()=="view all"){
            $(obj).text('view less');
            $("li:gt(6):not(:last)", ".tags ul").css("display", "inline");
        }else{
            $(obj).text('view all');
            $("li:gt(6)", ".tags ul").hide();
        }
    }
	
/*  -------------------------------------------------------------------
    Tags --------------------------------------------------------------  	

	function switch_product_img(divName, totalImgs) {
	  for (var i=1; i<=totalImgs; i++) {
		  var showDivName = 'photo_' + i;
		  var showObj = document.getElementById(showDivName);
		  if (showDivName == divName){
			  showObj.style.display = 'block';
			 //$("#"+i).addClass("selected");
		  }else
			  showObj.style.display = 'none';
			 // $("#"+i).removeClass("selected");
		  }
	  }
	  */

