/* Global */

var oa = {
	logged_in_facebook: false,
	twitter_connected: false,
	ios_device: false
}

jQuery.fn.maxlength = function(){
	$("textarea[maxlength]").keypress(function(event){ 
		var key = event.which;
		if(key >= 33 || key == 13) {
			var maxLength = $(this).attr("maxlength");
			var length = this.value.length;
			if(length >= maxLength) {
				event.preventDefault();
			}
		}
	});
}

$.fn.emoji = function() {
	return this.each(function() {
		$(this).html(function(i, oldHtml) {
			return oldHtml.replace(/([\ue001-\ue537])/g, function(s, eChar) {
				return '<img style="display: inline; vertical-align: middle; height: 15px;" src="/images/emoji/' + eChar.charCodeAt(0).toString(16) + '.png" alt="" />';
			});
		});
	});
};

var Apple = {};  
Apple.UA = navigator.userAgent;  
Apple.Device = false;  
Apple.Types = ["iPhone", "iPod", "iPad"];  
for (var d = 0; d < Apple.Types.length; d++) {  
	var t = Apple.Types[d];  
	Apple[t] = !!Apple.UA.match(new RegExp(t, "i"));  
	Apple.Device = Apple.Device || Apple[t];  
}  
if (Apple.Device) {
	oa.ios_device = true;
} 

$(document).ready(function() {
    /**
     * toggle overlay visibility
     */
    if ($('a#btnToggleOverlay').length) {
        $('a#btnToggleOverlay').click(function(e) {
            e.preventDefault();
            var $ol = $('#filter-overlay'),
                $btn = $(this); 
            if (!$ol.is(':visible')) {
                $ol.slideDown('fast');
                $btn.addClass('active');
            } else {
                $ol.slideUp('fast');
                $btn.removeClass('active');
            }
        });
    }

    /**
     * toggle login/sign-up
     */
    if ($('a.btnToggleLogin').length) {
        $('a.btnToggleLogin').click(function(e) {
            e.preventDefault();
            var $login_view = $('#login'),
                $sign_up_view = $('#sign-up'),
                $btn = $(this); 

            if ($login_view.is(':visible')) {
                $login_view.hide();
                $sign_up_view.show();
            } else {
                $sign_up_view.hide();
                $login_view.show();
            }
        });
    }

    /**
     * toggle top advisor categories
     */
    if ($('a.btnToggleMerits').length) {
        $('a.btnToggleMerits').click(function(e) {
            e.preventDefault();
            var $ta = $('ul.top-advisor-list.all-ta-categories'),
                $btn = $(this);

            if ($ta.is(':visible')) {
                $ta.slideUp();
                $btn.attr('title', 'See More').html('See More');
            } else {
                $ta.slideDown();
                $btn.attr('title', 'See Less').html('See Less');
            }
        });
    }

    /**
     * switch text/password input types on focus/blur
     */
    if ($('form#login-box, form#sign-up-box').length) {
        (function($) {
            var $signup_password_text = $('#signup_password_text'),
                $signup_password = $('#signup_password'),
                $login_password_text = $('#login_password_text'),
                $login_password = $('#login_password'),
                color_placeholder = '#999',
                color_default = '#555';
          
            // reset bindings
            $signup_password_text.unbind('focus', 'blur');
            $login_password_text.unbind('focus', 'blur');
            
            // login password 
            $login_password_text.live('focus', function() {
                if ($login_password_text.val() == 'Password') {
                    $login_password_text.hide();
                    $login_password.css('color', color_default).show().focus();
                }
            });
            
            $login_password.live('blur', function() {
                if ($login_password.val() == '') {
                    $login_password.hide();
                    $login_password_text.css('color', color_placeholder).val('Password').show();
                }
            });

            // sign-up
            $signup_password_text.live('focus', function() {
                if ($signup_password_text.val() == 'Password') {
                    $signup_password_text.hide();
                    $signup_password.css('color', color_default).show().focus();
                }
            });
            
            $signup_password.live('blur', function() {
                if ($signup_password.val() == '') {
                    $signup_password.hide();
                    $signup_password_text.css('color', color_placeholder).val('Password').show();
                }
            });
        })(jQuery);
    }

    /**
     * clear input placeholders
     */
    if ($('form').length) {
        $('form').clearFocus();
    }

	/**
	 * birthdate widget
	 */
	if ($('#dob_widget').length) {
		$('#dob_widget').dobWidget();
	}

	/**
	 * in the news - highlights
	 */
	(function() {
		var count = $('#highlights-holder').find('a').length,
			timer = 5000,
			i = 1;
	
		$('#highlights-holder').find('a:first-child').show();

		var highlights = setInterval(function () {
			$('#highlights-holder').find('a').hide();

			if (i < count) { i += 1; } else { i = 1; }

			$('#highlights-holder').find('a[rel="' + i + '"]').fadeIn('slow');
		}, timer);
	}());

	// This does some cool stuff
	$().maxlength();
});

(function($) {
    $.fn.clearFocus = function() {
        var color_placeholder = '#999',
            color_default = '#555';

		$('input:text', $(this)).live('focus', function() {
			if (!$(this).hasClass('ignoreFocus')) {
				if (this.value == this.defaultValue) {
					$(this).val('').css('color', color_default);
				}
			}
		}).live('blur', function() {
			if (!$(this).hasClass('ignoreFocus')) {
				if (!this.value.length) {
					$(this).val(this.defaultValue).css('color', color_placeholder);
				}
			}
		});

		$('textarea', $(this)).live('focus', function() {
			if (this.value == $(this).attr('title')) {
				$(this).val('').css('color', color_default);
			}
		}).live('blur', function() {
			if (!this.value.length) {
				$(this).val($(this).attr('title')).css('color', color_placeholder);
			}
		});
        return this;
    };
})(jQuery);

(function($) { 
	$.fn.dobWidget = function() {
		// defaults
        var color_placeholder = '#999',
            color_default = '#555';

		var user_month_set = '',
			user_day_set = '',
			user_year_set = '';

		var $month = $('#dob_month'),
			$day = $('#dob_day'),
			$year = $('#dob_year');

		var default_values = {};
		if ($month.val() !== '') {
			default_values.month = $month.val();
		} else {
			default_values.month = 'MM';
		}

		if ($day.val() !== '') {
			default_values.day = $day.val();
		} else {
			default_values.day = 'DD';
		}

		if ($year.val() !== '') {
			default_values.year = $year.val();
		} else {
			default_values.year = 'YYYY';
		}

		var month_skips = ['2', '3', '4', '5', '6', '7', '8', '9'],
			day_skips = ['4', '5', '6', '7', '8', '9'];

		$month.val(default_values.month);
		$day.val(default_values.day);
		$year.val(default_values.year);

		// month events
		$month.live('focus', function() {
			if (this.value === default_values.month || this.value === user_month_set) {
				$(this).val('').css('color', color_default);
			}
		}).live('blur', function() {
			if (!this.value.length) {
				$(this).val(default_values.month).css('color', color_placeholder);
			}
		});

		$month.live('keyup', function() {
			if (isNaN($month.val())) {
				$month.val('');
			} else if (parseInt($month.val(), 10) > 12) {
				var cache_month = $month.val();

				$month.val('01'); 
				user_month_set = '01';
				$day.val(cache_month.substr(-1, 1)).css('color', color_default).focus();
				user_day_set = cache_month.substr(-1, 1);
			} else if ($.inArray($month.val(), month_skips) >= 0) {
				$month.val('0' + $month.val());
				user_month_set = $month.val();
				$day.focus().css('color', color_default);
			} else if ($month.val().length === 2) {
				$day.focus().css('color', color_default);
				user_month_set = $month.val();
			}
		});

		// day events
		$day.live('focus', function() {
			if (this.value === default_values.day || this.value === user_day_set) {
				$(this).val('').css('color', color_default);
			}
		}).live('blur', function() {
			if (!this.value.length) {
				$(this).val(default_values.day).css('color', color_placeholder);
			}
		});

		$day.live('keyup', function() {
			if (isNaN($day.val())) {
				$day.val('');
			} else if (parseInt($day.val(), 10) > 31) {
				var cache_day = $day.val();

				user_day_set = '0' + cache_day.substr(0, 1);
				$day.val('0' + cache_day.substr(0, 1));
				$year.val(cache_day.substr(-1, 1)).css('color', color_default).focus();
			} else if ($.inArray($day.val(), day_skips) >= 0) {
				$day.val('0' + $day.val());
				user_day_set = $day.val();
				$year.focus().css('color', color_default);
			} else if ($day.val().length === 2) {
				$year.focus().css('color', color_default);
				user_day_set = $day.val();
			}
		});
		
		// year events
		$year.live('focus', function() {
			if (this.value === default_values.year || this.value === user_year_set) {
				$(this).val('').css('color', color_default);
			}
		}).live('blur', function() {
			if (!this.value.length) {
				$(this).val(default_values.year).css('color', color_placeholder);
			}
		});

		$year.live('keyup', function() {
			if (isNaN($year.val())) {
				$year.val('');
				return;
			}
			
			// year can only begin with 1 or 2
			if ($year.val().substr(0, 1) > 2 || $year.val().substr(0, 1) < 1) {
				$year.val('');
				return;
			}
			
			// if 1, 1900s only
			if ($year.val().substr(0, 1) == 1) {
				if ($year.val().substr(1, 1) != 9) {
					$year.val($year.val().substr(0, 1));
					user_year_set = $year.val().substr(0, 1);
					return;
				}
			}

			// if 2, only current century	
			if ($year.val().substr(0, 1) == 2) {
				if ($year.val().substr(1, 1) != 0) {
					$year.val($year.val().substr(0, 1));
					user_year_set = $year.val().substr(0, 1);
					return;
				}
			}

			user_year_set = $year.val();
		});

		return this;
	};
})(jQuery);

function setVoteImageOrientation() {
	var newImg = new Image();
	newImg.src = $('div.question-vote img.q').attr('src');
	if (newImg.width > newImg.height) {
		$('div.question-vote .question-photo').addClass('landscape');
	} else { 
		$('div.question-vote .question-photo').removeClass('landscape');
	}
}

function showVoteQuestionShare() {
	// Tracking
	_gaq.push(['_trackEvent', 'Count', 'Question Referals']);

	$('#question-refer-body').html($('#question-text').html());
	image_url = $('#question-small-image').html();
	$('#question-refer-image').attr('src', image_url);
	$('#refer-overlay').show();
	//FB.getLoginStatus(function(response) {
		//if (response.session) {
			//$('#refer-question-fb-unlinked').hide();
			//$('#refer-question-fb-linked').show();
			//loadFacebookFriends();
		//} else {
			//$('#refer-question-fb-linked').hide();
			//$('#refer-question-fb-unlinked').show();
		//}
	//});
	FB.getLoginStatus(function(response) {
		if (response.authResponse && response.status === 'connected') {
			$('#refer-question-fb-unlinked').hide();
			$('#refer-question-fb-linked').show();
			loadFacebookFriends();
		} else {
			$('#refer-question-fb-linked').hide();
			$('#refer-question-fb-unlinked').show();
		}
	});
}

function showFlagQuestion(is_friend_stream) {
	if (typeof(is_friend_stream) == 'undefined') { is_friend_stream = false; }

	$('#flag-overlay').show();

	if (!is_friend_stream) {
		// Tracking
		_gaq.push(['_trackEvent', 'Count', 'Question Flags', 'Public']);
	} else {
		// Tracking
		_gaq.push(['_trackEvent', 'Count', 'Question Flags', 'Friend']);
	}
}

function hideFlagQuestion() {
	// Reset form
	selects = $('.flagging-content form select');
	$.each(selects, function(index, select) {
		$(select).find('option:first').attr('selected', 'selected');
	});

	// Clear errors
	$('div[id$="-error"]').hide();

	// Hide overlay
	$('#flag-overlay').hide();
}

function showFlagUser() {
	$('#flag-overlay').show();

	// Tracking
	_gaq.push(['_trackEvent', 'Count', 'Profile Flags']);
}

function hideFlagUser() {
	// Reset form
	$('#flag-user-comment').val('');

	// Clear errors
	$('div[id$="-error"]').hide();

	// Hide overlay
	$('#flag-overlay').hide();
}

function sortByName(a, b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function loadFacebookFriends() {
	$('#refer-question-fb-unlinked').hide();
	$('#refer-question-fb-linked').show();
	$('#overlay-loader').show();
	$('#overlay-loader .text').html('Loading friends...');
	FB.api('/me/friends', function(response) {
		$('#overlay-loader').hide();
		friends = response.data.sort(sortByName);
		$.each(friends, function(index, friend) { 
			$('#facebook-friend-refer').tmpl(friend).appendTo($('#fb-friend-list-refer'));
		});
	});
}

function resetLoader() {
	$('#overlay-loader').hide();
	$('#overlay-loader #loading-image').show();
	$('#overlay-loader #ok-button').hide();
}

function promptLogin(track_vote) {
	$('#overlay.login-overlay').show();
	if (typeof track_vote != 'undefined') {
		_gaq.push(['_trackEvent', 'Count', 'Unregistered Votes']);
	}
}

function checkLoginForm() {
	if ($('#login-email').val() == 'Email') {
		$('#login-email').val('')
	}
}

function checkRegisterForm() {
	if ($('#signup-first-name').val() == 'First Name') {
		$('#signup-first-name').val('')
	}
	if ($('#signup-last-name').val() == 'Last Name') {
		$('#signup-last-name').val('')
	}
	if ($('#signup-email').val() == 'Email') {
		$('#signup-email').val('')
	}
}

function checkReplyForm() {
	if ($('#reply').val() == 'Enter your reply here') {
		$('#reply').val('')
	}
}

function toggleAskPublic() {
	if (!$('#is_public').attr('checked')) {
		$('#share_facebook').attr('disabled', 'disabled');
		$('#share_facebook').attr('checked', false);
		$('#share_twitter').attr('disabled', 'disabled');
		$('#share_twitter').attr('checked', false);
		$('.target-age input.chk').attr('disabled', 'disabled');
		$('.target-age input.chk').attr('checked', false);
		$('.target-gender input.chk').attr('disabled', 'disabled');
		$('.target-gender input.chk').attr('checked', false);
	} else {
		$('#share_facebook').removeAttr('disabled');
		$('#share_twitter').removeAttr('disabled');
		$('.target-age input.chk').removeAttr('disabled');
		$('.target-age input.chk').attr('checked', true);
		$('.target-gender input.chk').removeAttr('disabled');
		$('.target-gender input.chk').attr('checked', true);
	}
}

function calculateTime (timestamp) {
	currentTimeMS = new Date().getTime();
	currentTimeS = currentTimeMS/1000;
	seconds = Math.round(currentTimeS - timestamp);
	minutes = Math.round(seconds/60);
	hours = Math.round(minutes/60);
	days = Math.round(hours/24);
	weeks = Math.round(days/7);
	months = Math.round(days/31);
	years = Math.round(days/365);

	if (minutes < 60) {
		if (minutes < 6) {
			return 'just now';
		}
		return minutes + ' min. ago';
	} else if (hours < 24) {
		if (hours == 1) {
			return hours + ' hour ago';
		} else {
			return hours + ' hours ago';
		}
	} else if (days < 7) {
		if (days == 1) {
			return days + ' day ago';
		} else {
			return days + ' days ago';
		}
	} else if (days < 31) {
		if (weeks == 1) {
			return weeks + ' week ago';
		} else {
			return weeks + ' weeks ago';
		}
	} else if (days < 365) {
		if (months == 1) {
			return months + ' month ago';
		} else {
			return months + ' months ago';
		}
	} else {
		if (years == 1) {
			return years + ' year ago';
		} else {
			return years + ' years ago';
		}
	}
}

Object.size = function(obj) {
	var size = 0, key;
	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

/*
if (typeof console == 'undefined' && typeof console.log == 'undefined') {
	console.log = function() {};
}
*/

function sendEvents(events) {
	for (category in events) {
		if (events.hasOwnProperty(category)) {
			if (Object.size(events[category]) > 0) {
				for (action in events[category]) {
					if (events[category].hasOwnProperty(action)) {
						if (typeof events[category][action] != 'string') {
							if (Object.size(events[category][action]) > 0) {
								for (label in events[category][action]) {
									if (events[category][action].hasOwnProperty(label)) {
										_gaq.push(['_trackEvent', category, action, events[category][action][label]]);
										//console.log(category + ' - ' + action + ' - ' + events[category][action][label]);
									}
								}
							}
						} else {
							_gaq.push(['_trackEvent', category, events[category][action]]);
							//console.log(category + ' - ' + events[category][action]);
						}
					}
				}
			}
		}
	}
}

