//------------------------------------------------------[MJ]
// Public: JS
//------------------------------------------------------[MJ]

// On Load ---------------------------------------------[MJ]
$(document).ready(function() {
	// MTMHP Boo-Yea!---------------------------------------[LB]
	$('#MTMHP').click(function() {
		var title = 'RyanSeacrest.com';
		var url = window.location;

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url, '');
		} else if (window.external) { // IE Favorite
			window.external.AddFavorite( url, title); 
		}
		
		return false;
	});
	//------------------------------------------------------[LB]

	// Header Login Username Focus -------------------------[MJ]
	$('#Login_Username').focus(function(){
		if(jQuery.trim($(this).val()) == 'USERNAME' ) {
			$(this).css('color', '#555555').val('');
		}
	});	

	$('#Login_Username').blur(function(){
		if(jQuery.trim($(this).val()) == '' ) {
			$(this).css('color', '#AFAFAF').val('USERNAME');
		}
	});
	//------------------------------------------------------[MJ]

	// Header Login PW focus -------------------------------[MJ]
	$('#Login_Password').focus(function(){
		$('#LoginDropdown').css('background','#FFF8D1 url(\'/img/v1/header_loginbgYEL.gif\') no-repeat');
		$(this).css('color', '#555555');
	});

	$('#Login_Password').blur(function(){
		if(jQuery.trim($(this).val()) == '' ) {
			$('#LoginDropdown').css('background','#FFF8D1 url(\'/img/v1/header_loginbg_pwYEL.gif\') no-repeat');
			$(this).css('color', '#AFAFAF');
		}
	});
	//------------------------------------------------------[MJ]

	//In case browser autofills password ------------------[MJ]
	if ( $('#Login_Password').val() != '' ) {
		$('#LoginDropdown').css('background','#FFF8D1 url(\'/img/v1/header_loginbgYEL.gif\') no-repeat');
		$('#Login_Password').css('color', '#555555');
	}
	//------------------------------------------------------[MJ]
	
	// Share Email Form ------------------------------------[MJ]
	$('.STR_Email').click(function(e) {
		$('#ShareEmail').remove();
		var HTML = '	<div class="ShareEmail" id="ShareEmail">'+
					'		<div class="ShareText">SHARE THIS WITH A FRIEND</div>'+
					'		<a href="#" onclick="javascript: $(\'#ShareEmail\').fadeOut(\'normal\'); return false;" class="ShareEmailX">close</a>'+
					'		<br clear="all" />'+
					'		<div class="EmailFormContainer" id="EmailFormContainer">'+
					'			<div class="ShareEmailMsg" id="ShareEmailMsg"></div>'+
					'			<form name="ShareEmail" method="POST" id="Share_Email" onsubmit="EmailForm(event); return false;">'+
					'				<table cellpadding="4" cellspacing="0">'+
					'					<tr>'+
					'						<td align="right">Your Name:</td>'+
					'						<td><input type="text" name="YourName" id="Share_YourName" /></td>'+
					'					</tr>'+
					'					<tr>'+
					'						<td align="right">Friend\'s Email:</td>'+
					'						<td><input type="text" name="FriendEmail" id="Share_FriendEmail" /></td>'+
					'					</tr>'+
					'				</table>'+
					'				<input type="submit" name="Submit" value="Send" class="Button" id="Share_Message" />'+
					'			</form>'+
					'		</div>'+
					'		<br clear="all" />'+
					'</div>';
		$(this).parents('.EmailWrapper').append( HTML );
		$('#ShareEmail').css('top', (e.pageY-150)+'px');
		$('#ShareEmail').css('left', (e.pageX-20)+'px');
		$('#ShareEmail').fadeIn('normal');
	});
	//------------------------------------------------------[MJ]

	// Close Messages
	$('.MSG_Error').click(ClickToClose);
	$('.MSG_Success').click(ClickToClose);
});
//------------------------------------------------------[MJ]

// Set Days --------------------------------------------[MJ]
setDays = function() {
	// Note, this function assumes the combo boxes for month/day have options Month/Day with values 00/00
	var y = document.getElementById('Register_YearSel').options[document.getElementById('Register_YearSel').selectedIndex].value;
	var m = document.getElementById('Register_MonthSel').options[document.getElementById('Register_MonthSel').selectedIndex].value;
	var d;

	// find number of days in current month
	if ( (m == 4) || (m == 6) || (m == 9) || (m == 11) ) {
		days = 30;
	} else if (m == 2) {
		// check for leapyear - Any year divisible by 4, except those divisible by 100 (but NOT 400)
		if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
		  days = 29
		else
		  days = 28
	} else {
		days = 31;
	}

	// if (days in new month > current days) then we must add the extra days
	if (days + 1 > document.getElementById('Register_DaySel').length) {
		for (i = document.getElementById('Register_DaySel').length; i < days + 1; i++) {
			document.getElementById('Register_DaySel').length = days + 1;
			document.getElementById('Register_DaySel').options[i].text = i;
			document.getElementById('Register_DaySel').options[i].value = i;
		}
	}
  
	// if (days in new month < current days) then we must delete the extra days
	if (days + 1 < document.getElementById('Register_DaySel').length) {
		document.getElementById('Register_DaySel').length = days + 1;
		if (document.getElementById('Register_DaySel').selectedIndex == -1) 
			document.getElementById('Register_DaySel').selectedIndex = days - 1;
	}
}
//------------------------------------------------------[MJ]



// Show Login ------------------------------------------[MJ]
function ShowLogin() {
	if($('#LoginDropdown').css('display') == 'block')
		$('#LoginDropdown').slideUp('normal');
	else
		$('#LoginDropdown').slideDown('normal');
}
//------------------------------------------------------[MJ]

// Share Email Stuff -----------------------------------[MJ]
function Bind() {
	$('.STR_Email').click(function(e) {
		$('#EmailFormContainer').css('display','block');
		$('#Share_Email').get(0).reset();
		$('#ShareEmailMsg').removeClass('ShareSuccess');
		$('#ShareEmailMsg').removeClass('ShareError');
		$('#ShareEmailMsg').html('');
		$('#ShareEmail').css('display', 'none');
		$('#ShareEmail').css('top', (e.pageY-300)+'px');
		$('#ShareEmail').css('left', (e.pageX-0)+'px');
		$('#ShareEmail').fadeIn('normal');
	});
}
//------------------------------------------------------[MJ]

// Share With A Friend ---------------------------------[MJ]
function EmailForm(e) {
var Data = eval( '(' + $('#ShareEmail').parents('.EmailWrapper').attr('rel') + ')' );
	var myVars = {
		'YourName'		: $('#Share_YourName').val(),
		'FriendEmail'	: $('#Share_FriendEmail').val(),
		'Type'			: Data['Type'],
		'TypeID'		: Data['TypeID']
	};

	$.post('/shareemail.process/', myVars, EmailFormCallback, 'json');
	return false;
}

function EmailFormCallback(myReturn) {
	if(myReturn['Status'] == 'Success') {
		// tell them it was successful
		$('#ShareEmailMsg').addClass('ShareSuccess');
		$('#ShareEmailMsg').html(myReturn['ErrorMsg']);

		// Reset the form
		$('#Share_YourName').val('');
		$('#Share_FriendEmail').val('');
	} else {
		// Error
		$('#ShareEmailMsg').removeClass('ShareSuccess');
		$('#ShareEmailMsg').removeClass('ShareError');
		$('#ShareEmailMsg').addClass('ShareError');
		$('#ShareEmailMsg').html(myReturn['ErrorMsg']);
	}
}
//------------------------------------------------------[MJ]

// Poll --------------------------------------------[MJ][LB]
function PollLoaded() {
	$('.PollSubmit').click(PollSubmit);
	$('.PollResult').click(PollResult);
}

function PollSubmit() {
	var FormID = '#' + $(this).parent().parent().attr('id');

	if($(FormID + ' input:checked').length == 0) {
		alert('Please choose a poll option.');
		return false;
	}

	var	PollData = {
		'PollID'	: $(FormID + ' .PollID').val(),
		'ChoiceID'	: $(FormID + ' .PollChoice:checked').val()
	};

	$.post('/poll.process/', PollData, function(){
		PollResult(PollData.PollID);
	});

	return false;
}

function PollResult(PollID) {
	if (!parseInt(PollID)) {
		PollID = $(this).parent().parent().parent().find('.PollID').val();
	}

	$('#Poll_' + PollID).load('/poll.result/?PollID=' + PollID);

	return false;
}
// -------------------------------------------------[MJ][LB]

// Login User ------------------------------------------[MJ]
function HeaderLoginForm() {
	var myVars = {
		'Username'		: $('#Login_Username').val(),
		'Password'		: $('#Login_Password').val(),		
		'RememberMe'	: ($('#Login_RememberMe').attr('checked') ? 'Yes' : 'No')
	};

	$.post('/ajx.login.process/', myVars, LoginFormCallback, 'json');
}

function LoginFormCallback(myReturn) {
	if(myReturn['Status'] == 'Success') {
		// Do something if no errors
		window.location.reload();
	} else {
		// Error
		$('#LoginError').css('display','block');

		var HTML = '';
		for(i = 0; i < myReturn['ErrorMsg'].length; i++) {
			HTML += myReturn['ErrorMsg'][i] + '<br />';
		}

		$('#LoginError').html(HTML);
	}
	return false;
}
//------------------------------------------------------[MJ]

//------------------------------------------------------[MJ]
function ClickToClose(Event) {
	var Parent = $(this).parent();
	$(this).remove();
	if(!Parent.children().length)
		Parent.remove();
}
//------------------------------------------------------[MJ]

// Spider-Safe Email -----------------------------------[MJ]
function jsWriteEmail(address, domain) {
	return document.write('<a href="mailto: ' + address + '@' + domain + '">' + address + '@' + domain + '</a>');
}
//------------------------------------------------------[MJ]

function ResetVoteCount(e) {
	if(confirm('Really reset vote count?')) {
		var myVars = {
			'PollID' : $('#ThePollID').val()	
		};

		$.post('/admin/resetvotecount/', myVars, ResetVoteCountCallback, 'json');
	}
}
function ResetVoteCountCallback(myReturn) {
	if(myReturn['Status'] == 'Success')
		window.location.reload(true);
	else
		alert('you got a problem, yo');
}

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
/*-----------------------------------------------------------*/