/* 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) {}

//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 Southern Accents to:</label></td><td><select name='reader' id='reader'>" + str + "</select></td><td><input type='image' src='http://img4.southernaccents.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 Southern Accents to:</label></td><td><select name='reader' id='reader'>" + str + "</select></td><td><input type='image' src='http://img4.southernaccents.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();
	}
}

$(document).ready(function(){
	//text resizer
	$("#txtResizer span").eq(0).css("color", "#666");
	$("#txtResizer span").bind("click", function(){
		var newSize = $(this).prevAll("span").length;
		$("#txtResizer span").css("color", "#369").eq(newSize).css("color", "#666");
		$("#txtResizeArea").css("font-size", (newSize*0.2+1)+"em");
	});

	//initialize popup links
	$("a.popup").addClass("pop").attr("title", "[Opens in new window]").bind("click", function(){
		var popup = window.open($(this).attr("href"), "_blank", "height=500,width=600,scrollbars=yes");
		popup.focus();
		return false;
	});
	$("a.popup2").attr("title", "[Opens in new window]").bind("click", function(){
		var popup = window.open($(this).attr("href"), "_blank", "height=500,width=600,scrollbars=yes");
		popup.focus();
		return false;
	});

	//don't submit search form with blank query
	$("#sitesearch").submit(function(){
		return ($.trim($("#searchbox").val()) != "");
	});

	//prints the pages url on screen used on print pages
	$("#linkLocation").html(location.href);

	//convert add-this link lists to form
	convertRSSList1();
	convertRSSList2();
});

//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() + ' &raquo; <a href="' + calLink + '">more</a></div>');
		}
	});
}

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.southernaccents.com" || hostname === "search.southernaccents.com") {
	google_adtest = "off"; //PROD
}
else {
	google_adtest = "on";
}

/* 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 */
