/*
 * code for pulling in blog posts from blogger
 * based on the related posts code
 */
 
var BLOG_URL = 'http://blog.kuzakscloset.com/feeds/posts/summary/';
var BLOG_LABEL_URL = 'http://blog.kuzakscloset.com/search/label/';
var TWITTER_ENDPT = 'http://api.twitter.com/users/show.json';
var MAX_RESULTS = 6;
var SHOW_RESULTS = 3;
var IMGS_TO_SHOW = 7;
var MAX_FEED_LOAD = 10;
var TAGS = 'Organizing';
var THUMB_SZ = 's100-c';
var GALLERY_SZ = 's640';
var SLIDER_DIV = '#featured';


function contact() {
	if (verifySubmission()) {
		$('#contactform').attr("method", "POST");
		$('#contactform').attr("action", "http://www.kuzakscloset.com/contact.php");
		$('#contactform').submit();
	}
}

function verifySubmission() {
	name = jQuery.trim($('#contactform #contact-name').val());
	email = jQuery.trim($('#contactform #contact-email').val());
	message = jQuery.trim($('#contactform #contact-message').val());
	
	if (name.length > 0 && email.length > 0 && message.length > 0) {
		// allow submission
		return true;
	} else {
		return false;
	}
}

function getTweet() {
    $.ajax({url:TWITTER_ENDPT,
            data:{'include_entities':false,
                  'screen_name':'kuzakscloset',
                  'include_rts':0},
            success:processTweet,
            dataType:'jsonp',
            cache:true});
} 
 
function getPosts() {
 
				$.ajax({url:BLOG_URL
						,data:{'category':TAGS,'max-results':MAX_RESULTS,'alt':'json-in-script'}
						,success:processPosts
						,dataType:'jsonp'
						,cache:true });   
						
						
}

function getImagesForSplash() {
				$.ajax({url:BLOG_URL
						,data:{'max-results':MAX_FEED_LOAD,'alt':'json-in-script'}
						,success:processSlidesFeed
						,dataType:'jsonp'
						,cache:true });   
					
}

function processPosts(json, status) {

	var url = null;
	var thumb = null;
	var title = null;
	var added = 0;
	
	var html = "";
	
	
	if (json.feed.entry) {
	
		for(var i = 0; i < json.feed.entry.length && added < SHOW_RESULTS; i++) {
			var entry = json.feed.entry[i];
			
			// load the first url
			for (var k = 0; k < entry.link.length; k++) {
				if (entry.link[k].rel == 'alternate') {
					url = entry.link[k].href;
					break;
				}
			}
			
			if (entry.media$thumbnail == null) {
				continue;
			}
			
			title = entry.title.$t;
			thumb=entry.media$thumbnail.url;
			if (THUMB_SZ && THUMB_SZ != 's72-c') {
		   		 thumb = thumb.replace(/\/s72-c\//, '/' + THUMB_SZ + '/');
			}
			
			html += "<li><a class=\"tip\" href=\"" + url + "\" title=\"" + title + "\">"
			      + "<img src=\"" + thumb + "\" alt=\"" + title + "\"/></a>"
				  + "<div class=\"oblock\"><div class=\"block\"><a href=\"" + url + "\" title=\"" + title + "\">" + title + "</a></div></div></li>";			
			
			
			added += 1;
		}
		
		$('#blog-widget').append(html);
		$('#blog-widget a.tip').tipsy({gravity:'w'});
	}

}

/*
 * generates a set of links and images for the front gallery slider
 *
 */
function processSlidesFeed(json, status) {

	var url = null;
	var thumb = null; 
    var sliderImg = null;
	var title = null;
	var added = 0;
	
	var html = "";
    var captions = "";
    var commP = /(\d*) Comments/;
	
	
	if (json.feed.entry) {
	
		for(var i = 0; i < json.feed.entry.length && added < IMGS_TO_SHOW; i++) {
			var entry = json.feed.entry[i];
            var cat = "";
            var anchor = "";
            var comments = "";
			
            // we want image'd posts only
			if (entry.media$thumbnail == null) {
				continue;
			}
            
			// load the first url/# comments
			for (var k = 0; k < entry.link.length; k++) {
                if (entry.link[k].rel == 'replies') {
                    if (entry.link[k].title[0] != "0") {
                        comments = entry.link[k].title.match(commP)[1];
                    }
                }
				if (entry.link[k].rel == 'alternate') {
					url = entry.link[k].href;
					break;
				}
			}
            
            // load the first category
            if (entry.category.length > 0) {
                cat = entry.category[0].term;
            }
			
			title = entry.title.$t;
			thumb=entry.media$thumbnail.url;
            sliderImg = thumb.replace(/\/s72-c\//, '/' + GALLERY_SZ + '/');
			
            // anchor is shared in img and in caption
            anchor = "<a href=\"" + url + "\" title=\"" + title + "\" data-caption=\"#slidecap-" + i + "\">";
            html +=  anchor
                 + "<img src=\"" + sliderImg + "\" title=\"" + title + "\" alt=\"" + title + "\" "
                 + "data-caption=\"#slidecap-" + i + "\" "
                 + "\" width=\"620\" height=\"410\"/>"
                 + "</a>";
                 
            captions += "<span class=\"orbit-caption\" id=\"slidecap-" + i + "\">";
            if (cat != "") {
                captions += "<span class=\"orbit-caption-cat\">"
                         +  "<a href=\"" + BLOG_LABEL_URL + cat + "\" title=\"See other " + cat + "posts \">"
                         +  cat + "</a></span>";
            }
            captions += anchor + title + "</a>";
            
            // generate comments
            if (comments != "") {
                captions += "<span class=\"orbit-caption-comments\">" + comments + " comment";
                if (comments != "1") {
                    captions += "s";
                }
                captions += "</span>";
            }
            captions += "</span>";
			added += 1;
		}
		
		$(SLIDER_DIV).append(html);
        $(SLIDER_DIV).after(captions);
	}

  $(SLIDER_DIV).orbit({animation:'fade',animationSpeed:800,advanceSpeed:5000,bulletThumbs:false,bullets:true,captions:true,directionalNavFadeSpeed:100,timerDial:false});
}

function processTweet(json, status) {    
    var id = json.status.id_str;
    var tweet = json.status.text;
    
    $('#tweet').append(linkify(tweet));
}

function writeSocialButtons(pUrl, pImgUrl, pTitle) {

    document.write('<ul class="social-buttons">'
    + '<li class="social-gp">' + getGPlusButton(pUrl) + '</li>'
    + '<li class="soocial-t">' + getTweetButton(pUrl, pTitle) + '</li>'
    + '<li class="social-f">' + getLikeButton(pUrl) + '</li>'
    + '<li class="social-p">' + getPinButton(pUrl, pImgUrl, pTitle) + '</li>'
    + '</ul>');
}

function getPinButton(pinUrl, pinImgUrl, pinText) {
    return '<a href="http://pinterest.com/pin/create/button?'
    + $.param({url:pinUrl, media:pinImgUrl, description: pinText})
    + '" class="pin-it-button" count-layout="horizontal">Pin It</a>';
}

function getTweetButton(pUrl, pTitle) {
    return '<a class="twitter-share-button" data-count="horizontal" '
    + 'data-via="kuzakscloset" data-text="' + pTitle + '" '
    + 'data-url="' + pUrl + '" href="https://twitter.com/share">Tweet</a>'
    + '<script src="//platform.twitter.com/widgets.js" type="text/javascript"></script>';
}

function getGPlusButton(pUrl) {
    return '<g:plusone href="' + pUrl + '" size="medium"/>';
}

function getLikeButton(pUrl) {
    return '<div class="fb-like" data-font="arial" data-layout="button_count" data-send="false" '
    + 'data-show-faces="false" data-width="100" data-href="' + pUrl + '"/>';
}

function linkify(text) {
    text = text.replace(/(https?:\/\/\S+)/gi, function (s) {
        return '<a href="' + s + '">' + s + '</a>';
    });

    text = text.replace(/(^|)@(\w+)/gi, function (s) {
        return '<a href="http://twitter.com/' + s + '">' + s + '</a>';
    });

    text = text.replace(/(^|)#(\w+)/gi, function (s) {
        return '<a href="http://search.twitter.com/search?q=' + s.replace(/#/,'%23') + '">' + s + '</a>';
     });
    return text;
}
