$('html').addClass('js');

// 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() + "/" + this.getDate() + "/" + this.getFullYear();
}


var analytics = function() 
{
        var self = this;

        return {        
           updateLoyalty: function() {
              var loyaltyCookie = this.getLoyaltyCookie();
              if( loyaltyCookie[ (new Date() ).getDay() ] == 0 )
              {
                 loyaltyCookie = this.flipDayBit( loyaltyCookie );
              }

              return true;
           },

           getLoyaltyCookie: function()
           {

              var currentCookieValue = GOOD.readCookie( 'loyalty_cookie' ) ;
              var lastSunday = (new Date() ).lastSunday();
              var defaultCookieValue = '0,0,0,0,0,0,0,' + lastSunday.dateOnlyString();     
              if( !currentCookieValue)
              {
                currentCookieValue = defaultCookieValue;
              }
              var 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;
           },

           updateLoyaltyCookie: function( loyalty_cookie )
           {
              GOOD.writeCookie( 'loyalty_cookie', this.serializeLoyaltyArray( loyalty_cookie ) );
           },
           
           serializeLoyaltyArray: function( loyalty_cookie )
           {
              var toReturn =  '';
              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;                  
             for( i = 0; i < 7; i++ )
             {
                sum += parseInt(loyalty_cookie[i]);
             }
             return sum;
           },
           
           notifyGoogleAnalyticsOfCount: function( loyalty_cookie ) 
           {
             pageTracker._setCustomVar( 1, 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('');
   }
}

function validateEmail(email) {

    $(".error").hide();

    var hasError = false;
    var emailReg = /^([\w\-\.]+@([\w\-]+\.)+[\w\-]{2,4})?$/;

    if( (email == '') || (email == 'your email address')) {
        $("#newsLetterBtn").after('<div class="error">You forgot to enter the email address.</span>');
        hasError = true;
    } else if(!emailReg.test(email)) {
        $("#newsLetterBtn").after('<div class="error">Please enter a valid email address</span>');
        hasError = true;
    }
    return false;
}

function loginOverlay(headerText, url, xwidth, yheight) {
	if(!headerText) {
		headerText = 'Sign in to GOOD';
	}
	if(!url) {
		url = '/login';
	}
	if(!xwidth) {
		xwidth = 550;
	}
	if(!yheight) {
		yheight = 430;
	}

	// Changed dialog options to match GOOD.dialog more closely
	$('<div id=\'overBox\'></div>')
		.html('Form is loading . . .')
		.dialog({
			autoOpen: false,
			bgiframe: true,
			modal: true,
			resizable: false,
			closeText: '',
			closeOnEscape: true,
			height: yheight,
			width: xwidth,
			title: headerText
		})
		.load(url).dialog('open');
}

//////////////////////////
// Create the GOOD namespace
//////////////////////////

var GOOD = {

	// 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();
	},

	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
			};
		} else {
			user = false;
		}

		return user;
	},

	access: function() {
		var cookie = this.readCookie('CakeCookie[good_nav]');
		return cookie;
	},

	// 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 = GOOD.user(),
			admin = /^\/goodadmin\//.test(window.location.pathname),
			postLink = ((admin) ? '/goodadmin' : '') + '/posts/edit',
			$loggedInBox = $('\
				<li class="you">\
					<h3><a class="profile-link"><img class="profile-image" /></a>You<span class="overlay"></span></h3>\
					<ul>\
						<li><a class="profile-link">Profile</a></li>\
						<li><a href="/users/edit">Edit Settings</a></li>\
						<li><a href="/logout">Signout</a></li>\
					</ul>\
				</li>');

		if (GOOD.access() == 1) {
			$loggedInBox
				.find('li')
				.eq(1)
				.after('\
					<li><a href="' + postLink + '">Create a Post</a></li>\
					<li><a href="/posts/edit_static_page">Create a Page</a></li>\
				');
		}

		if (user) {
			$profile.remove();

			$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';
						});
					}
				);
			}

			$loggedInBox.appendTo('.site.navigation');

		} else {

//			GOOD.dialog($profile.find('a[href=/login], a[href=/users/signup]'));

		}

		$profile.show();
	}

};

