/* Global.js */
var monthsAbbr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

// remove IE6 image flickering
try {document.execCommand('BackgroundImageCache', false, true);}
catch(e) {}

var isValidEmail = function(str) {
	var at = str.lastIndexOf("@");
	var dot = str.lastIndexOf(".");
	return (at > 0 && dot > 0 && dot > at);
};
//Navigation drop-downs
(function($) {
	$.fn.initNav = function(){
		return this.each(function(){
			var $this = $(this);
			$this.find("li").bind("mouseover", function(){
				$(this).addClass("active");
			}).bind("mouseout", function(){
				$(this).removeClass("active");
			});
			$this.find("li ul").show();
			$this.find("li:has(ul)").bind("mouseover", function(){
				$(this).removeClass("active");
				$(this).addClass("selected");
				$(this).find("ul").css("left", "0");
				var overhang = $(this).offset().left + 200 - $("body").width();
				if (overhang > 0) {
					$(this).find("ul").css("left", (-overhang-5) + "px");
				}
			}).bind("mouseout", function(){
				$(this).removeClass("selected");
				$(this).find("ul").css("left", "-999em");
			}).each(function() {
				$(this).css("z-index", 5000 - $(this).prevAll("li").length);
			});
			$this.find("a").bind("focus", function(){
				$(this).parents("li").find("ul").css("left", "0");
			}).bind("blur", function(){
				$(this).parents("li").find("ul").css("left", "-999em");
			});
		});
	};
})(jQuery);
//convert add-this link lists to form
function convertRSSList1() {
	if ($(".getRSS .getRSSList a").length > 0) {
		var str = "";
		$(".getRSS .getRSSList a").each(function() {
			str += "<option value='" + $(this).attr("href") + "'>" + $(this).text() + "</option>";
		});
		$(".getRSS .getRSSList").after("<form target='_top' action='#' method='post'><table cellspacing='10' summary=''><tr><td><label for='reader'>Add All You to:</label></td><td><select name='reader' id='reader'>" + str + "</select></td><td><input type='image' src='http://img4.allyou.com/static/i/btn_add.gif' alt='Add' /></td></tr></table></form>");
		$(".getRSS form").bind("submit", function(){
			$(this).attr("action", $(this).find("option:selected").val());
		});
		$(".getRSS .getRSSList").remove();
	}
}
function convertRSSList2() {
	if ($(".addTo .getRSSList a").length > 0) {
		var str = "";
		$(".addTo .getRSSList a").each(function() {
			str += "<option value='" + $(this).attr("href") + "'>" + $(this).text() + "</option>";
		});
		$(".addTo .getRSSList").after("<form target='_top' action='#' method='post'><table cellspacing='4' summary=''><tr><td><label for='reader'>Add All You to:</label></td><td><select name='reader' id='reader'>" + str + "</select></td><td><input type='image' src='http://img4.allyou.com/static/i/btn_add.gif' alt='Add' /></td></tr></table></form>");
		$(".addTo form").bind("submit", function(){
			$(this).attr("action", $(this).find("option:selected").val());
		});
		$(".addTo .getRSSList").remove();
	}
}

//Textbox Default Text
(function($) {
	$.fn.textboxDefault = function(options){
		var defaults = {blurClass:"blur"};  
		var options = $.extend(defaults, options);
		
		return this.each(function(){
			var $this = $(this);
			$this.data("defaultText", $this.val()).addClass(options.blurClass).focus(function(){
				if ($this.val() == $this.data("defaultText")) {
					$this.removeClass(options.blurClass).val("");
				}
			}).blur(function(){
				if ($this.val() == "") {
					$this.addClass(options.blurClass).val($this.data("defaultText"));
				}
			});
		});
	};
})(jQuery);

//Validate and submit the free newsletter form
(function($) {
	$.fn.freeNewsletterValidate = function(){
		return this.each(function(){
			var $this = $(this);
			$this.find("form").submit(function(){
				var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
				if (!emailPattern.test($this.find("input[name=email]").val())) {
					var errorMsg = $('<div></div>').attr('style', 'color:#c00').text('Please enter a valid email address.');
					if ($this.find('.dek').text().indexOf('Please enter a valid email address.') == -1) {
						$this.find('.dek').append(errorMsg);
					}
					return false;
				} else {
					omniNewsProxy($this.find("input[name=sub]").val());
					return true;
				}
			});
		});
	};
})(jQuery);

//hide popunders from certain sites
var dref = document.referrer.toLowerCase();
if (dref.indexOf("google") > -1 || dref.indexOf("yahoo") > -1 || dref.indexOf("facebook") > -1 || dref.indexOf("primosearch") > -1 || dref.indexOf("righthealth") > -1 || dref.indexOf("alot") > -1 || dref.indexOf("digg") > -1 || dref.indexOf("reddit") > -1 || dref.indexOf("twitter") > -1 || dref.indexOf("stumbleupon") > -1 || dref.indexOf("cnn") > -1 || dref.indexOf("msn") > -1 || dref.indexOf("huffingtonpost") > -1) {
	adConfig.setPopups(false);
}


// initialize the calendar thumbnail module (flex module js copied from MHI)
function initCalTN(calFile) {
	var monthsAbbr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	var now = new Date();
	$(".calTN2:not(:has(.date))").prepend("<div class='date'><div class='month'>" + monthsAbbr[now.getMonth()] + "</div><div class='day'>" + now.getDate() + "</div></div>");
	$.ajax({
		type: "GET",
		url: calFile,
		dataType: "xml",
		success: function(data){
			var currentDay = $(data).find("day").eq(now.getDate() - 1);
			var calLink = $(data).find("month").attr("url");
			$(".calTN:not(:has(a)) h3").prepend($(data).find("title").eq(0).text() + " ");
			$(".calTN2:not(:has(a))").find("p").remove().end().append("<a href='" + calLink + "' class='title'>" + $(currentDay).find("title").text() + "</a><p>" + $(currentDay).find("short-deck").text() + " <a href='" + calLink + "' class='more'>&raquo; See Full Calendar</a></p>");
		}
	});
}

//initialize the calendar thumbnail module
function initCal150(calFile) {
	var now = new Date();
	$(".cal150").empty().prepend("<div class='date'>" + monthsAbbr[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear() + "</div>");
	$.ajax({
		type: "GET",
		url: calFile,
		dataType: "xml",
		success: function(data){
			var currentDay = $(data).find("day").eq(now.getDate() - 1);
			var calLink = $(data).find("month").attr("url");
			var monthTitle = $(data).find("month > title").text();
			var image = $(currentDay).find("img[width=150]");
			if (image.length == 0) {
				image = $(currentDay).find("img");
			}
			$(".cal150").append('<h3><a href="' + calLink + '">' + monthTitle + '</a></h3><div class="img"><a href="' + calLink + '"><img src="' + image.attr("url") + '" width="150" height="150" alt="' + image.attr("alt") + '" /></a></div><h4><a href="' + calLink + '">' + $(currentDay).find("title").text() + '</a></h4><div class="deck">' + $(currentDay).find("short-deck").text() + ' <a href="' + calLink + '" class="teaserLink">more</a></div>');
		}
	});
}

//grocery server for search results page
function initSearchGS() {
	if (typeof searchString === "string") {
		gsapi.cid = "c15277771f0e7969577ca89681f09816";
		function myHandlerFunction(response) {
			$(response.promotionCount ? "div.gsPromo" : "div.recipeRes").show();
		}
		function myZIPHandlerFunction(zipCode) {
			var requestObject = s3.json.parse("{zipCode: '" + zipCode + "', ingredientNames: ['" + searchString + "']}");
			gsapi.grocery.getPromotionCount(requestObject, myHandlerFunction);
		}
		function processZipCode() {
			gsapi.grocery.getZipCode(myZIPHandlerFunction);
		}
		processZipCode();
	}
}

//Toggle List: Show More/Show Less
(function($) {
	$.fn.toggleList = function(){		
		return this.each(function(){
			var $this = $(this);
			$this.find("li:eq(3)").before("<li class='showLink'><a>Show More</a></li>");
			$this.find("li:gt(3)").hide();
			$this.find("li.showLink a").click(function(){
				$(this).parent("li").toggleClass("less").nextAll().toggle();
				$(this).text($(this).text()=="Show More" ? "Show Less" : "Show More");
			});
		});
	};
})(jQuery);

function initRssPartners(data){
	var html = '<div class="box" id="rssPartners">';
	html += '<div class="head"><h6>NEW <span>on the</span> WEB</h6></div>';
	html += '<div class="cont_out"><div class="cont_in">';
	html += '<div class="dek">Stories from our Partners</div> <ul>';
	for (var i=0; data.value.items[i]; i++) {
		var link = data.value.items[i].link;
		link += (link.indexOf("?")>0 ? "&" : "?") + "xid=ay";
		var title = data.value.items[i].title;
		var desc = data.value.items[i].description;
		if (desc.length > 90) {
			desc = desc.substring(0,90) + "...";
		}
		var source = link.replace("http://", "").split("/")[0].split(".").slice(-2).join(".");
		html += '<li class="clr"><div class="tout">';
		if (data.value.items[i].thumbnail1) {
			html += '<div class="img"><a href="' + link + '" target="_blank"><img src="' + data.value.items[i].thumbnail1 + '" alt="' + title + '" height="50" width="50"></a></div>';
		}
		else if (data.value.items[i].thumbnail2) {
			html += '<div class="img"><a href="' + link + '" target="_blank"><img src="' + data.value.items[i].thumbnail2 + '" alt="' + title + '" height="50" width="50"></a></div>';
		}
		html += '<div class="txt"><a href="' + link + '" target="_blank">' + title + '</a> ' + desc + ' <span class="url">(' + source + ')</span></div>';
		html += '</div></li>';
	}
	html += '</ul></div></div></div>';
	if (data.value.items[0]) {
		$("#rssPartnerFeeds").html(html);
	}
}


/* cookie functions */
function getCookie(name) {
	var ca = document.cookie.split(';');
	for (var i=0; ca[i]; i++) {
		ca[i] = $.trim(ca[i]);
		if (ca[i].indexOf(name + "=") == 0) {
			return ca[i].substring(name.length + 1);
		}
	}
	return null;
}
function setCookie(name, value, days) {
	var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/; domain=allyou.com";
    return (getCookie(name) == value);
}
function deleteCookie(name){
	if (getCookie(name)) {
		document.cookie = name + "=; path=/; domain=allyou.com";
	}
}


var google_num_ads = 0;
var google_last_ad_type = '';

// This function is required by Google and is used to display the ads that are returned from the JavaScript request.
// You should modify the document.write commands so that the HTML they write out fits with your desired ad layout.
function google_ad_request_done(google_ads) {
	var s;
	
	// Verify that there are actually ads to display.
	if (google_ads.length == 0) {
		return;
	}
	
	google_num_ads += google_ads.length;
	google_last_ad_type = google_ads[0].type;
	
	s = '<div class="ad_wrapper">';
	s += '<div class="ad_attribution"><a href="' + google_info.feedback_url + '" target="_blank">Ads by Google</a></div>';
	if (google_last_ad_type === "text") {
		for (var i = 0; i < google_ads.length; i++) {
			s += '<div class="ad_inner">';
			s += '<div class="ad_title"><a href="' + google_ads[i].url + '" target="_blank">' + google_ads[i].line1 + '</a></div>';
			s += '<div class="ad_text">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</div>';
			s += '<div class="ad_url"><a href="' + google_ads[i].url + '" target="_blank">' + google_ads[i].visible_url + '</a></div>';
			s += '</div>';
		}
	}
	else if (google_last_ad_type === "image") {
		//not used
	}
	else if (google_last_ad_type === "flash") {
		//not used
	}
	else if (google_last_ad_type === "html") {
		//not used
	}
	s += "</div>";
	document.write(s);
	return;
}

google_ad_output = "js";
google_max_num_ads = "3";
google_ad_type = "text";
google_safe = "high";
google_encoding = "utf8";
google_language = "en";

var hostname = window.location.hostname;
if (hostname === "www.allyou.com" || hostname === "search.allyou.com") {
	google_adtest = "off"; //PROD
}
else {
	google_adtest = "on";
}

/* local offer network */

var env = "http://search.allyou.com/";
if (window.location.hostname.indexOf("tmpldev") > -1) {
	env = "http://dev-esearch.allyou.com/";
}
else if (window.location.hostname.indexOf("tmplqa") > -1) {
	env = "http://qa-esearch.allyou.com/";
}

var initLonPicks = function() {
	if (window.citiesLON) {
		var len = citiesLON.length, cols = 3;
		for (var i = 0; i < cols; i++) {
			var numInColumn = Math.floor(len/cols) + (len%cols > i ? 1 : 0);
			var $list = $('<ul class="picks ' + (i===0 ? "first" : "") + '"></ul>');
			for (var j = 0; j < numInColumn; j++) {
				$('<a href="' + env + citiesLON[0].city_id.replace(/_/g, "-") + '/ay-deals.html">' + citiesLON[0].city_name + '</a>').data("city_id", citiesLON[0].city_id).appendTo($list).wrap("<li></li>");
				citiesLON.shift();
			}
			$("#lonPicks").append($list);
		}
	}
	$("#lonPicks").find("a").click(function(){
		setCookie("lonCityId", $(this).data("city_id"), 14);
	});
};

var initLonSelect = function(id) {
	var cityDropdown = document.getElementById(id)
	if (window.citiesLON && cityDropdown) {
		for (var i = 0; i < citiesLON.length; i++) {
			var opt = document.createElement('option');
			opt.setAttribute("value", citiesLON[i].city_id);
			opt.innerHTML = citiesLON[i].city_name;
			cityDropdown.appendChild(opt);
		}
	}
};

var validateLONForm = function(form, cityInputId, cityErrorId, emailInputId, emailErrorId) {
	var isValid = true, city = document.getElementById(cityInputId), email = document.getElementById(emailInputId);
	if (city && city.value === "") {
		$("#" + cityErrorId).html("Please select a city");
		isValid = false;
	}
	else if (city) {
		setCookie("lonCityId", city.value);
		$("#" + cityErrorId).empty();
	}
	if (email && !isValidEmail(email.value)) {
		$("#" + emailErrorId).html("Please enter a valid email");
		isValid = false;
	}
	else if (email) {
		$("#" + emailErrorId).empty();
	}
	return isValid;
}

var getLONCityName = function(cityId) {
	if (window.citiesLON && cityId) {
		for (var i = 0; i < citiesLON.length; i++) {
			if (citiesLON[i].city_id === cityId) {
				return citiesLON[i].city_name;
			}
		}
	}
	return null;
}

var getLONDealCount = function(cityId) {
	if (window.citiesLON && cityId) {
		for (var i = 0; i < citiesLON.length; i++) {
			if (citiesLON[i].city_id === cityId) {
				return citiesLON[i].deal_count;
			}
		}
	}
	return null;
}

var initLonHome = function() {
	var cityName, cityId = getCookie("lonCityId");
	if (window.citiesLON) {
		if (cityId) {
			cityName = getLONCityName(cityId);
			$(".lon-banner:last").show().find(".num").html(getLONDealCount(cityId) + " Deals").next(".location").html("in " + cityName).end();
			$(".lon-banner:last .results a").click(function(){
				window.location.href = $(this).attr("href").replace("cityId", cityId).replace(/_/g,'-');
				return false;
			});
		}
		else {
			initLonSelect("dd-city-1");
			$("#lon-city-form").submit(function(){
				if (validateLONForm(this, "dd-city-1", "dd-error-city", null, null)) {
					window.location.href = $(this).attr("action").replace("cityId", $(this).find(":selected").val()).replace(/_/g,'-');
				}
				return false;
			});
			$(".lon-banner:first").show();
		}
	}
	else {
		$(".lon-banner").remove();
	}
};

var initLonNewsletter = function() {
	var cityName, cityId = getCookie("lonCityId");
	if (window.citiesLON) {
		$("#dd-email-rr-1").val("Enter Your Email Address").textboxDefault();
		initLonSelect("dd-city-rr-1");
		if (cityId) {
			$(".lon-newsletter-tout").find("select").val(cityId).end().find("p.dek").html('Sign up to receive Daily Deals alerts for<br /><span class="location">' + getLONCityName(cityId) + ' | <a href="#">Update location</a></span>').find("a").click(function(){
				$(".lon-newsletter-tout").find("select").show().end().find("p.dek").html('Sign up to receive Daily Deals alerts');
				return false;
			});
		}
		else {
			$(".lon-newsletter-tout").find("select").show();
		}
		$("#dd-form-rr").submit(function(){
			if (validateLONForm(this, "dd-city-rr-1", "dd-error-city-rr-1", "dd-email-rr-1", "dd-error-email-rr-1")) {
				$(".lon-newsletter-tout").find("p.dek").html('Thank you for signing up!');
				return true;
			}
			return false;
		});
	}
	else {
		$(".lon-newsletter-tout").remove();
	}
};
$(document).ready(function(){
    $("#topnav").initNav();
});

/* BEGIN SPC jQuery Plugin
 * Contains code for:
 * - Social Sidebar initialization
 */
(function($) {

    var async_load = function(src_url) {
        var s = document.createElement("script");
            s.type = "text/javascript";
            s.async = true;
            s.src = src_url;
            var x = document.getElementsByTagName("script")[0];
            x.parentNode.insertBefore(s, x);
    },
    google_plusone_init = function(options) {
        async_load("https://apis.google.com/js/plusone.js");
        return this;
    },

    facebook_like_init = function(options) {

    /*
        jquery.fbjlike.js - http://socialmediaautomat.com/jquery-fbjlike-js.php
        based on: jQuery OneFBLike v1.1 - http://onerutter.com/open-source/jquery-facebook-like-plugin.html
        Copyright (c) 2010 Jake Rutter modified 2011 by Stephan Helbig
        This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
    */
      //Set the default values, use comma to separate the settings
      var defaults = {
        appID: '',
        userID: '',
        siteTitle: '',
        siteName: '',
        siteImage: '',
        href:false,
        mode: 'insert',
        buttonWidth: 450,
        buttonHeight: 60,
        showfaces: true,
        font: 'lucida grande',
        layout: 'normal',	//box_count|button_count|standard
        action: 'like',		// like|recommend
        send:false,
        comments:false,
        numPosts:10,
        colorscheme: 'light',
        lang: 'en_US',
        hideafterlike:false,
        googleanalytics:false,	//true|false
        googleanalytics_obj: 'pageTracker',	//pageTracker|_gaq
        onlike: function(){return true;},
        onunlike: function(){return true;}
    }

    var options =  $.extend(defaults, options);

      return this.each(function() {
      var o = options;
      var obj = $(this);
      if(!o.href)
        var dynUrl = document.location;
      else
        var dynUrl = o.href;
      var dynTitle = document.title;

      // Add #fb-root div - mandatory - do not remove
      $('body').append('<div id="fb-root"></div>');
      $('#fb-like iframe').css('height','35px !important');

      (function() {
        var e = document.createElement('script');
        e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/'+o.lang+'/all.js';
        $('#fb-root').append(e);
      }());

      // setup FB Developers App Link - do not touch
      window.fbAsyncInit = function() {
        FB.init({appId: o.appID, status: true, cookie: true, xfbml: true});
        FB.Event.subscribe('edge.create', function(response) {
              if(o.hideafterlike)$(obj).hide();
              if(o.googleanalytics){
                    if(o.googleanalytics_obj!='_gaq'){
                        pageTracker._trackEvent('facebook', 'liked', dynTitle);
                    } else {
                    _gaq.push(['_trackEvent','facebook', 'liked', dynTitle]);
                }
              }
              o.onlike.call(response);
            });
        FB.Event.subscribe('edge.remove', function(response) {
              if(o.googleanalytics){
                    if(o.googleanalytics_obj!='_gaq'){
                        pageTracker._trackEvent('facebook', 'unliked', dynTitle);
                    } else {
                    _gaq.push(['_trackEvent','facebook', 'unliked', dynTitle]);
                }
              }
              o.onunlike.call(response);
            });
      };
      var tSend = '';
      if(o.send)tSend = ' send="true"';
      var thtml = '<fb:like xmlns:fb="http://ogp.me/ns/fb#" ref="fb-like" href="'+dynUrl+'" width="'+o.buttonWidth+'" height="'+o.buttonHeight+'" show_faces="'+o.showfaces+'" font="'+o.font+'" layout="'+o.layout+'" action="'+o.action+'" colorscheme="'+o.colorscheme+'"'+tSend+'/>';

        if(o.comments){
        thtml += '<'+'div style="clear:both;"></div><fb:comments xmlns:fb="http://ogp.me/ns/fb#" href="'+dynUrl+'" num_posts="'+o.numPosts+'" width="'+o.buttonWidth+'"></fb:comments>';
      }
      if(o.mode=='append')$(obj).append(thtml);
      else $(obj).html(thtml);

      });
    },

    twitter_init = function(options) {
    /*
        jquery.twitterbutton.js - http://socialmediaautomat.com/jquery-twitterbutton-js.php
        Copyright (c) 2011 Stephan Helbig
        This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
    */

      //Set the default values, use comma to separate the settings
      var defaults = {
            user: false,
            user_description: false,
            url: false,
            count_url: false,
            title: false,
            mode: 'insert',
            layout: 'vertical', //vertical|horizontal|none
            action: 'tweet',		//tweet|follow
            lang: 'en',					//en|de|ja|fr|es
            hideafterlike:false,
            googleanalytics:false,							//true|false
            googleanalytics_obj: 'pageTracker',	//pageTracker|_gaq
            ontweet: function(){return true;},
            onretweet: function(){return true;},
            onfollow: function(){return true;}
        }

      var options =  $.extend(defaults, options);
      var script_loaded = false;
      return this.each(function() {
          var o = options;
          var obj = $(this);
          if(!o.url) var dynUrl = document.location;
          else var dynUrl = o.url;
          if(!o.title)var dynTitle = document.title;
          else var dynTitle = o.title;

            if(!o.count_url)o.count_url=dynUrl;

            if(!script_loaded){
                var e = document.createElement('script'); e.type="text/javascript"; e.async = true;
                e.src = 'http://platform.twitter.com/widgets.js';
                (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(e);

                $(e).load(function() {
                    function clickEvent(intent_event) {
                      if (intent_event) {
                            var label = intent_event.region;
                          if(o.googleanalytics){
                                if(o.googleanalytics_obj!='_gaq'){
                                    _gaq.push(['_trackEvent', 'twitter_web_intents', intent_event.type, label]);
                                } else {
                                    pageTracker._trackEvent('twitter_web_intents', intent_event.type, label);
                                }
                            }
                      };
                    }
                    function tweetIntent(intent_event) {
                      if (intent_event) {
                            var label = intent_event.data.tweet_id;
                          if(o.googleanalytics){
                                if(o.googleanalytics_obj!='_gaq'){
                                    _gaq.push(['_trackEvent', 'twitter_web_intents', intent_event.type, label]);
                                } else {
                                    pageTracker._trackEvent('twitter_web_intents', intent_event.type, label);
                                }
                            }
                            o.ontweet.call(intent_event);
                        if(o.hideafterlike)$(obj).hide();
                      };
                    }
                    function favIntent(intent_event) {
                        tweetIntent(intent_event);
                    }
                    function retweetIntent(intent_event) {
                      if (intent_event) {
                            var label = intent_event.data.source_tweet_id;
                          if(o.googleanalytics){
                                if(o.googleanalytics_obj!='_gaq'){
                                    _gaq.push(['_trackEvent', 'twitter_web_intents', intent_event.type, label]);
                                } else {
                                    pageTracker._trackEvent('twitter_web_intents', intent_event.type, label);
                                }
                            }
                            o.onretweet.call(intent_event);
                        if(o.hideafterlike)$(obj).hide();
                      };
                    }
                    function followIntent(intent_event) {
                      if (intent_event) {
                            var label = intent_event.data.user_id + " (" + intent_event.data.screen_name + ")";
                          if(o.googleanalytics){
                                if(o.googleanalytics_obj!='_gaq'){
                                    _gaq.push(['_trackEvent', 'twitter_web_intents', intent_event.type, label]);
                                } else {
                                    pageTracker._trackEvent('twitter_web_intents', intent_event.type, label);
                                }
                            }
                            o.onfollow.call(intent_event);
                        if(o.hideafterlike)$(obj).hide();
                      };
                    }
                    twttr.events.bind('click',    clickEvent);
                    twttr.events.bind('tweet',    tweetIntent);
                    twttr.events.bind('retweet',  retweetIntent);
                    twttr.events.bind('favorite', favIntent);
                    twttr.events.bind('follow',   followIntent);
                    script_loaded = true;
                });
            }


              if(o.action=='tweet'){
                var via = '';
                var related = '';
                if(o.user!=false){
                    via = 'data-via="'+o.user+'" ';
                    if(o.user_description!=false){
                        related = 'data-related="'+o.user+':'+o.user_description+'" ';
                    }
                }
                var counturl = '';
                if(o.count_url!=dynUrl)counturl = 'data-counturl="'+o.count_url+'" ';
                var thtml = '<div><a href="http://twitter.com/share" class="twitter-share-button" data-url="'+dynUrl+'" '+counturl+''+via+'data-text="'+dynTitle+'" data-lang="'+o.lang+'" '+related+'data-count="'+o.layout+'"></a></div>';
              } else {
                    thtml = '<div><a href="http://twitter.com/'+o.user+'" class="twitter-follow-button">Follow</a></div>';
              }
             if(o.mode=='append')$(obj).append(thtml);
             else $(obj).html(thtml);

      });
    },


    pinterest_init = function(params) {
        var defaults = {
                url: '',
                media: '',
                description: ''
            },

            init = function() {
                window.PinIt = window.PinIt || { loaded:false };
                if (window.PinIt.loaded) return;
                window.PinIt.loaded = true;
                function async_load(){
                    var s = document.createElement("script");
                    s.type = "text/javascript";
                    s.async = true;
                    s.src = "http://assets.pinterest.com/js/pinit.js";
                    var x = document.getElementsByTagName("script")[0];
                    x.parentNode.insertBefore(s, x);
                }
                if (window.attachEvent)
                    window.attachEvent("onload", async_load);
                else
                    window.addEventListener("load", async_load, false);
            };

		params =  $.extend(defaults, params);
        this.each(function() {
            var pinit_href = 'http://pinterest.com/pin/create/button/?' + $.param(params),
                pinit_html = ['<a href="', pinit_href, '" class="pin-it-button" count-layout="none"></a>'].join('');

            $(this).html(pinit_html);
        });
        init();
        return this;
    },

/*
 * MyRecipes.com jQuery plugins for mr-core namespace
 *
 * Attach plugin methods here and invoke via syntax:
 *
 * $(<selector>).spc_core(<method name>, <args>...);
 */
	social_sidebar_init = function(options) {
		var defaults = {
				tab_class:'tab',
				auto_close_delay: 5000,
				toggle_speed: 500,
				y_start: 200,
				y_docked: 20,
				collapse_trigger: 1050,
                collapse_width: 74,
				docked_class: 'docked',
				closed_class: 'closed',
                narrowed_class: 'narrowed',
				collapse_on: 'click',
				expand_on: 'click',
				share_buttons: {},
                badges: {},
                omniture: {},
                messages: {}
			},
			o = $.extend(true, defaults, options || {} ),
			docked_trigger = o.y_start - o.y_docked,
			$bar = this,
			$tab = $bar.find('.' + o.tab_class),
			check_docked = function() {
				var is_bar_docked = $bar.hasClass(o.docked_class),
		        	is_dockable  = $(document).scrollTop() > docked_trigger;
		        if ((!is_bar_docked &&  is_dockable) ||
		            ( is_bar_docked && !is_dockable))   {
		        		$bar.toggleClass(o.docked_class);
		        }
			},
			check_closed = function() {
				var is_bar_collapsed = $bar.hasClass(o.closed_class),
				 	is_window_narrow = $(window).width() < o.collapse_trigger,
				 	bar_should_collapse = is_window_narrow && !is_bar_collapsed,
				 	bar_should_expand = !is_window_narrow && is_bar_collapsed;

				if (bar_should_collapse) {
					collapse_bar();
				} else if (bar_should_expand) {
					expand_bar();
				} else {
					return;
				}
			},
			expand_bar = function() {
				if ($bar.hasClass(o.closed_class)) {
					$bar.stop().animate({left: '0'}, o.toggle_speed, function() {
						$bar.removeClass(o.closed_class);
			            $tab.fadeOut();
			            setTimeout(function(){
			                check_closed();
			            }, o.auto_close_delay);
			        });
				}

			},
			collapse_bar = function() {
				if (!$bar.hasClass(o.closed_class)) {
					$bar.stop().animate({left: '-' + o.collapse_width}, o.toggle_speed, function() {
						$bar.addClass(o.closed_class);
			            $tab.fadeIn();
			        })
				}
			},
            get_og_data = function() {
                var og_props = 'og:title og:type og:image og:url og:site_name og:description fb:app_id'.split(' '),
                    i,
                    og_data = {},
                    prop = '';

                for (i = 0; i < og_props.length; i += 1) {
                    prop = og_props[i];
                    og_data[prop] = $('meta[property="' + prop + '"]').attr('content');
                }

                get_og_data = function() {return og_data;};
                return get_og_data();
            },
            og_data = get_og_data(),
            badges = o.badges,
            badge_names = {
                facebook_like: 'facebook_like',
                google_plusone: 'google_plusone',
                twitter: 'twitter',
                pinterest: 'pinterest',
                stumbleupon: 'stumbleupon'
            },
            get_pinterest_img_url= function(og_url) {
            	var is_thumb = /-s.jpg$/;
            	if (is_thumb.test(og_url)) {
            		return og_url.replace(is_thumb, '-l.jpg');
            	} else {
            		return og_url;
            	}
            };
			/* END init var */

        $bar.hide();
        if (o.collapse_on && o.expand_on) {
            if (o.collapse_on === o.expand_on === 'click') {
                $bar.toggle(
                    function() {collapse_bar();},
                    function() {expand_bar();}
                )
            } else {
                $bar.bind(o.collapse_on, function() {
                    collapse_bar();
                });
                $bar.bind(o.expand_on, function() {
                    expand_bar();
                });
            }
        }

        /* Add docking and closing to window event handlers */
	    $(window).scroll(function() {
	        check_docked();
	    }).resize(function() {
	    	check_closed();
	    });

        var $badge = $bar.find('#badge-twitter'),
            service_count = 1;

        $badge = $bar.find('#badge-twitter');
        if (badges[badge_names.twitter]) {
             $badge.spc_core('twitter_init', {
                        url: 		og_data['og:url'],
                        title: 		o.messages.twitter || og_data['og:title'],
                        ontweet:	o.omniture.twitter
            });
            service_count += 1;
        } else {
            $badge.remove();
        }
        $badge = $bar.find('#badge-facebook-like')
        if (badges[badge_names.facebook_like]) {
            $badge.spc_core('facebook_like_init', {
                        layout: 'box_count',
                        buttonWidth: 75,
                        font: 'arial',
                        showfaces: false,
                        href:      og_data['og:url'],
                        siteTitle: og_data['og:title'],
                        siteName:  og_data['og:site_name'],
                        siteImage: og_data['og:image'],
                        appID:     og_data['fb:app_id'],
                        onlike:    o.omniture.facebook_like
             });
             service_count += 1;
        } else {
            $badge.remove();
        }


        $badge = $bar.find('#badge-google-plusone');
        if (badges[badge_names.google_plusone]){
            if (o.omniture.google_plusone) {
                window.ssb_omniture_gplusone = o.omniture.google_plusone;
            }
            /* Library now called inline on SSi include file */
            $badge.spc_core('google_plusone_init', {
                        href: og_data['og:url'],
                        size: 'tall'
            });
            service_count += 1;
        } else {
            $badge.remove();
        }

        $badge = $bar.find('#badge-pinterest');
        if (badges[badge_names.pinterest]) {
             $badge.spc_core('pinterest_init', {
                        url: og_data['og:url'],
                        media: get_pinterest_img_url(og_data['og:image']),
                        description: og_data['og:title']
            });
            service_count += 1;
        } else {
            $badge.remove();
        }

        if (service_count) {
            $bar.show();
            check_docked();
            setTimeout(function(){
                check_closed();
            }, o.auto_close_delay);
        }
	    /* END init */
	},

    /*
     * spc_core plugin map
     */
	spc_core_plugins = {
			social_sidebar_init: social_sidebar_init,
            facebook_like_init: facebook_like_init,
            google_plusone_init: google_plusone_init,
            pinterest_init: pinterest_init,
            twitter_init: twitter_init
	};
	/* END main var */

	/*
     * jQuery plug-in invocation function adapted from http://docs.jquery.com/Plugins/Authoring
     */
    $.fn.spc_core = function(method) {

    	var slice = Array.prototype.slice;
        /* Method calling logic */
        if (spc_core_plugins[method]) {
          return spc_core_plugins[method].apply(this, slice.call( arguments, 1 ));
        } else {
          $.error('Method ' + method + ' does not exist on in the jQuery spc_core namespace');
        }

    };
})(jQuery);
/* END SPC jQuery plugin */
