(function () {
	var $html = $('html'),
		fontFaceClass;

	$html.addClass('js');

	// Allow custom styles for users with narrower screens.
	if (screen.availWidth < 1110) {
		$html.addClass('narrow');
	}

	// If Firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
	if (document.documentElement.style.MozTransform === '') { // gecko 1.9.1 inference
		fontFaceClass = 'hide-custom-font-face';
		$html.addClass(fontFaceClass);
		setTimeout(function () {
			$html.removeClass(fontFaceClass);
		}, 500);
	}
}( ));

// GOOD written functions that have global reach go here
Date.prototype.lastSunday = function () {
	var dateOnSundayWithTime = new Date(this.getTime() - (this.getDay() * 24 * 60 * 60 * 1000 ));
	return new Date(dateOnSundayWithTime.getFullYear(), dateOnSundayWithTime.getMonth(), dateOnSundayWithTime.getDate() );
};

Date.prototype.dateOnlyString = function () {
	return (this.getMonth() + 1 ) + "/" + this.getDate() + "/" + this.getFullYear();
};


function JSKitCommentsCountFilter(count) {
   if (count > 0)
      return count;
   else
      return '+';
}



var analytics = {
  
  updateVisit: function() {
    var visitCookie = this.getVisitCookie();
    if( visitCookie[1] != (new Date() ).dateOnlyString() )
    {
      this.updateVisitCookie( visitCookie );
    }

  },
	updateLoyalty: function () {
		var loyaltyCookie = this.getLoyaltyCookie();
		if (loyaltyCookie[(new Date()).getDay()] == 0) {
			loyaltyCookie = this.flipDayBit(loyaltyCookie);
		}
		return true;
	},

  getVisitCookie: function() {
    var currentVisitCookieValue = GOOD.readCookie( 'visit_cookie' );
	  var lastSunday = (new Date()).lastSunday();
    var yesterday = new Date( new Date() - (1000*60*60*24) );
    var defaultCookieValue = lastSunday.dateOnlyString() + "," + yesterday.dateOnlyString();
    
    if( !currentVisitCookieValue ) 
    {
      currentVisitCookieValue = defaultCookieValue;
    }

    return this.parseCookie( currentVisitCookieValue );
  },
	getLoyaltyCookie: function () {
		var currentCookieValue = GOOD.readCookie( 'loyalty_cookie'),
			lastSunday = (new Date()).lastSunday(),
			defaultCookieValue = '0,0,0,0,0,0,0,' + lastSunday.dateOnlyString(),
			loyaltyArray;

		if (!currentCookieValue) {
			currentCookieValue = defaultCookieValue;
		}

		loyaltyArray = this.parseCookie(currentCookieValue);

		if (this.getSundayDate(loyaltyArray) !== lastSunday.dateOnlyString()) {
			loyaltyArray = this.parseCookie(defaultCookieValue);
		}

		return loyaltyArray;
	},

	parseCookie: function (cookie_string) {
		var toReturn = cookie_string.split(',');
        return toReturn;
	},

  updateVisitCookie: function( visit_cookie) {
    visit_cookie[1] = ( new Date() ).dateOnlyString();
    GOOD.writeCookie( 'visit_cookie', visit_cookie[0] + "," + visit_cookie[1] );
    this.notifyGoogleAnalyticsOfVisit( visit_cookie[0] );
  },
  notifyGoogleAnalyticsOfVisit: function( join_week ) {
    _gaq.push(['_setCustomVar',
               1,
               'cohort_visit', 
               join_week,  
               1                
              ]);
		return this;    
  },
	updateLoyaltyCookie: function (loyalty_cookie) {
		GOOD.writeCookie('loyalty_cookie', this.serializeLoyaltyArray(loyalty_cookie));
	},

	serializeLoyaltyArray: function (loyalty_cookie) {
		var toReturn =  '',
			i;
		for (i = 0; i < 7; i++) {
			toReturn += loyalty_cookie[ i ] + ",";
		}
		toReturn += loyalty_cookie[7];
		return toReturn;
	},

	flipDayBit: function (loyaly_cookie) {
		loyaly_cookie[(new Date()).getDay() ] = 1;
		this.updateLoyaltyCookie(loyaly_cookie);
		this.notifyGoogleAnalyticsOfCount(loyaly_cookie);
	},

	countNumberOfVisits: function (loyalty_cookie) {
		var sum = 0,
			i;
		for (i = 0; i < 7; i++) {
			sum += parseInt(loyalty_cookie[i], 10);
		}
		return sum;
	},

	notifyGoogleAnalyticsOfCount: function (loyalty_cookie) {  
    _gaq.push(['_setCustomVar',
               2,
               this.getSundayDate(loyalty_cookie).replace(/\//g, '_') + '_Weekly_Visits', 
               this.countNumberOfVisits(loyalty_cookie),  
               1                
              ]);
		return this;
	},

	getSundayDate : function (loyalty_cookie) {
		return loyalty_cookie[7];
	}
};

function resetText (id,text) {
    if ($(id).val() === '') {
		$(id).val(text);
    }
}

function clearForm (id, value) {
   if ($(id).val() === value) {
        $(id).val('');
   }
}

//////////////////////////
// Create the GOOD namespace
//////////////////////////

var GOOD = {
    cache_buster: 0,

	// A flag for testing DOM-readiness
	domReady: (function () { $(function () { GOOD.domReady = true; }); return false; })( ),

	// Returns a new copy of an object (not a reference)
	beget: function (o) {
		var F = function () {};
		F.prototype = o;
		return new F();
	},

	reloadAllAdsOnPage: function () {
		var self = this;
		$('iframe.vendor_ad').each(function () {
			var original_source = $(this).attr("src");
			original_source = original_source.replace( /&cache_buster=[0-9]*/i, '' ) + "&cache_buster=" + self.cache_buster;
			self.cache_buster += 1;
			$(this).attr({
				src: original_source
			});
		});
		return false;
	},

	writeCookie: function (name, value, days, path) {
		var date = new Date(),
			expiry;

		expiry = (days) ? date.setTime(date.getTime() + days * 8.64e7).toGMTString() : '';
		path = path || '/';
		document.cookie = [name + '=' + value, 'expires=' + expiry, 'path=' + path].join('; ');
		return this.readCookie(name);
	},

	readCookie: function (name) {
		var nameEQ = name + "=",
			ca = document.cookie.split(';'),
			c;

		for (var i=0; i<ca.length; i++) {
			c = ca[i];

			if (c.charAt(0) === ' ') {
				c = c.substring(1,c.length);
			}

			if (c.indexOf(nameEQ) === 0) {
				return unescape(c.substring(nameEQ.length,c.length));
			}
		}

		return null;
	},

	deleteCookie: function (name) {
		return this.writeCookie(name, '', -1);
	},

	user: function() {
		var cookie = this.readCookie('CakeCookie[good_cookies]'),
			user;

		if (cookie) {
			cookie = cookie.split('|');
			user = {
				link: '/community/' + cookie[0],
				name: cookie[1] && cookie[1].replace('+',' '),
				image: cookie[2] || 'http://resource.cloudfront.goodinc.com/v11/images/defaults/avatar30.jpg',
				fb: cookie[3] > 0,
				access: cookie[4] && cookie[4] === '1'
			};
		} else {
			user = false;
		}

		return user;
	},

	// Helper method for calling ui.dialog and referencing already-open dialogs
	// The options parameter can be used to override default UI dialog options.
	// Additionally, options can accept the following non-UI properties:
	//	url: Sets the url for the $.load request (default: event's target.href)
	//	html: The selector that queries or creates the $dialog jQuery object (default: '<div/>')
	dialog: function (selector, options) {
		var $dialog = $(options && options.html || '<div/>');

		function open(url, config) {
			if (url) {
				$.ajax({
					url: url,
					success: function (html) {
						var $html = $(html);
						$(function () {
							GOOD.form.animateAndReplace($dialog.children(), $html, {
								hide: ($.support.opacity) ? ['puff', { percent:100 }, 200] : ['slide', {}, 0] ,
								show: ['slide', { direction:'up' }, 200],
								after: function ($old, $new) {
									var $dialogContainer = GOOD.form.getAncestor($new, '.ui-dialog');
									$dialogContainer.animate(
										{ top:($(document).scrollTop() + ($(window).height() - $dialogContainer.outerHeight()) / 2) },
										{
											duration: 100,
											complete: function () {
												$dialog.dialog('option', 'position', 'center');
											}
										}
									);
								}
							});
						});
					}
				});
				$dialog.html('<div class="loading"/>');
			}

			$dialog
				.bind('dialogclose', function () {
					$(this).dialog('destroy').remove();
				})
				.dialog(config)
				// Add a title attribute to the close button for added accessibilty
				.parent()
					.find('.ui-dialog-titlebar-close')
						.attr('title', 'Click here to close this box')
						.end()
					.end()
				.dialog('open');
		}

		// Extend dialog defaults with any specified options
		options = $.extend({
			autoOpen: false,
			bgiframe: true,
			iframe: false,
			modal: true,
			resizable: false,
			closeText: '',
			closeOnEscape: true,
			width: 600
		}, options);

		if (selector) {
			$(selector).each(function (i) {
				options.title = options.title || this.title;
				$(this).unbind().click(function (e) {
					e.preventDefault();
					open(options.url || this.href, options);
				});
			});
		} else {
			open(options.url, options);
		}

		return $dialog;
	},

	// Helper funciton for calling a login dialog and handling any interrupted actions
	login: function (postId) {
		GOOD.dialog(null, {
			url:'/login' + ('/' + postId || ''),
			title:'Sign in to GOOD'
		});
	},

	// Checks for an existing association b/w Facebook and GOOD user account
	facebookLogin: function () {

		$.ajax({
			url: "/users/facebook_login",
			success: function (userIsNew) {

				if (userIsNew === '1') {
					var $openDialogs = $('.ui-dialog-content').filter(function () {
							return $(this).dialog('isOpen');
						});

					GOOD.dialog(null, {
						title: 'Facebook',
						url: '/users/facebook_account',
						width: 900,
						open: function () {
							$openDialogs.dialog('close');
						},
						close: function () {
							GOOD.refresh();
						}
					});

				} else {
					GOOD.refresh();
				}
			}
		});
	},

	// Populate profileArea	(called within page)
	populateProfile: function ($profile) {
		var user = this.user(),
			$loggedInBox = $('\
				<div class="you">\
					<a class="profile-link polaroid"><img class="profile-image" /></a>\
					<ul>\
						<li><a class="profile-link">Profile</a></li>\
						<li><a href="/users/edit">Edit Settings</a></li>\
						<li class="signout"><a href="/logout">Signout</a></li>\
					</ul>\
				</div>');
		
		if (user && user.access) {
			$loggedInBox
				.find('li')
				.eq(1)
				.after('\
					<li><a href="/madisonboomadmin/posts/edit">Create a Post</a></li>\
					<li><a href="/madisonboomadmin/posts/new_job">New Job Listing</a></li>\
					<li><a href="/madisonboomadmin/posts/new_press">New Press Release</a></li>\
					<li><a href="/madisonboomadmin/posts">Admin</a></li>\
				');
		}

		if (user) {
			$profile.empty();

			$loggedInBox
				.find('.profile-link')
					.attr('href', user.link)
					.end()
				.find('.profile-image')
					.attr({
						'src': user.image,
						'alt': user.name,
						'title': user.name
					});

			if (user.fb) {
				$loggedInBox
					.find('[href=/logout]').click(
					function (e) {
						e.preventDefault();
						FB.Connect.logout(function () {
							window.location='/logout';
						});
					}
				);
			}


			$profile
				.append($loggedInBox)
				.removeClass('not-logged-in')
				.addClass('logged-in');

		} else {

//			GOOD.dialog($profile.find('a[href=/login], a[href=/users/signup]'));

		}

		$profile.show();
	}

};

