//-----------------------------------------------------------
// Public JS
//-----------------------------------------------------------
var dil = {};

// function for drop down month/day/year ----------------[TN]
dil.setDays = function() {
	// Note, this function assumes the combo boxes for month/day have options Month/Day with values 00/00
	var y = document.getElementById('Year').options[document.getElementById('Year').selectedIndex].value;
	var m = document.getElementById('Month').options[document.getElementById('Month').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('Day').length) {
		for (i = document.getElementById('Day').length; i < days + 1; i++) {
			document.getElementById('Day').length = days + 1;
			document.getElementById('Day').options[i].text = i;
			document.getElementById('Day').options[i].value = i;
		}
	}
  
	// if (days in new month < current days) then we must delete the extra days
	if (days + 1 < document.getElementById('Day').length) {
		document.getElementById('Day').length = days + 1;
		if (document.getElementById('Day').selectedIndex == -1) 
			document.getElementById('Day').selectedIndex = days - 1;
	}

}
//------------------------------------------------------[TN]

// XHMessage - Generic XH Message Div ------------------[TN]
dil.XHMessage = function(parentClass, theMessage, cursorOffsetTop, whereDisplay, isSuccessful) {
	if( arguments[5] != null ? arguments[5] : true )
		$('.XHMessage').remove();

	$('.' + parentClass).append('<div class="XHMessage' + ( (isSuccessful == 1) ? ' Success' : ' Error') + '">' + theMessage + '</div>');
	$('.XHMessage').click(function(){ this.parentNode.removeChild(this)});

	if (whereDisplay == 'Event') {
		var parentWidth = $('.' + parentClass).css('width');
		parentWidth = parentWidth.split('px');
		parentWidth = parentWidth[0];

		var parentOffsetTop = $('.' + parentClass).get(0);
		parentOffsetTop		= parentOffsetTop.offsetTop;

		var msgTop	 = cursorOffsetTop - parentOffsetTop;
		var msgWidth = Number(parentWidth) - 22;

		$('.XHMessage').css({
			'width' : msgWidth,
			'top'	: msgTop,
			'left'	: 0		
		}) ;
	} else if (whereDisplay == 'DOM') {
		$('.XHMessage').css({
			'position'	: 'relative'
		});
	}
}
//------------------------------------------------------[TN]

// PostRating ------------------------------------------[TN]
dil.PostRating = function(event, ratingType, pkID, rating, theParent, columnParent) {
	if ( event.pageX == null && event.clientX != null ) {
	  var e = document.documentElement||{}, b = document.body||{};
	  event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft || 0) - (e.clientLeft || 0);
	  event.pageY = event.clientY + (e.scrollTop || b.scrollTop || 0) - (e.clientTop || 0);
	}
	var cursorTop = event.pageY;	

	$.post('/rating.process/', {
			'Type'		: ratingType,
			'Rating'	: rating,
			'pkID'		: pkID
		}, 
		function(data) {
			if(data['Msg'] == 'SUCCESS') {
				$(theParent).children().remove();

				// add images with rating
				if(rating >= 0)
					$(theParent).append('<img src="/img/v1/ico.thumb_up.gif" align="absmiddle" />');
				else
					$(theParent).append('<img src="/img/v1/ico.thumb_down.gif" align="absmiddle" />');

				if( data['Rating'] != null ) {
					var ratingSpan = '<span class="XHMessageRating">' + ( ( data['Rating'] <= 0 ) ? '' : '+' ) + data['Rating'] + '</span>';
					if( data['Type'] == 'comment' )
						$(theParent).prepend( ratingSpan );
					else
						$(theParent).append( ratingSpan );
				}
			}else{
				dil.XHMessage(columnParent, data['Msg'], cursorTop, 'Event', 0);
			}
		},
		'json'
	);
	return(false);
}
//------------------------------------------------------[TN]

// Flag Form -------------------------------------------[TN]
dil.Flag = function(event, flagType, pkID, linkID) {
	// remove previous form if exists
	dil.CloseFlagForm();

	// create the form
	$('body').append('<div class="FlagForm">Reason:<br /><textarea id="FlagReason" class="FlagReason"></textarea><div align="center"><input type="button" class="FlagButton" value="Flag" onclick="javascript: dil.SubmitFlagForm(\'' + flagType + '\',' + pkID + ',\'' + linkID + '\');" /> <input type="button" value="Cancel" onclick="javascript: dil.CloseFlagForm();" /></div></div>');

	// position the form
	var xOffset		= (arguments[4] != null) ? arguments[4] : 0;
	if ( event.pageX == null && event.clientX != null ) {
	  var e = document.documentElement||{}, b = document.body||{};
	  event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft || 0) - (e.clientLeft || 0);
	  event.pageY = event.clientY + (e.scrollTop || b.scrollTop || 0) - (e.clientTop || 0);
	}

	var cursorLeft	= event.pageX - xOffset;
	var cursorTop	= event.pageY;	

	$('.FlagForm').css({'top' : cursorTop, 'left' : cursorLeft});
	return(false);
}
//------------------------------------------------------[TN]

// Close Flag Form -------------------------------------[TN]
dil.CloseFlagForm = function() {
	$('.FlagForm').remove();
}
//------------------------------------------------------[TN]

// Post Flag -------------------------------------------[TN]
dil.SubmitFlagForm = function(flagType, pkID, linkID) {
	var theParent = $('#' + linkID).parent();
	var flagReason = jQuery.trim($('#FlagReason').val());

	$('.FlagForm .FlagError').remove();

	if( flagReason == ''){
		$('.FlagForm').append('<div class="FlagError">Please enter a reason for flagging this.</div>');
	}else{
		$.post('/flag.process/', 
			{
				'Type'		: flagType,
				'ID'		: pkID,
				'Reason'	: flagReason
			}, 
			function(data) {
				if(data['Msg'] == 'flagged') {
					dil.CloseFlagForm();
					$(theParent).children().remove();
					$(theParent).append('<span class="XHMessageFlag">' + data['Msg'] + '</span>');
				}else{
					$('.FlagForm').append('<div class="FlagError">' + data['Msg'] + '</div>');
				}
			},
			'json'
		);
	}
	return(false);
}
//------------------------------------------------------[TN]

// NotifyConfirm ---------------------------------------[TN]
dil.NotifyConfirm = function(event, theID, notificationType) {
	if(confirm('Are you sure you want to be emailed whenever a comment is posted to this ' + notificationType + '?')) {
		if ( event.pageX == null && event.clientX != null ) {
		  var e = document.documentElement||{}, b = document.body||{};
		  event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft || 0) - (e.clientLeft || 0);
		  event.pageY = event.clientY + (e.scrollTop || b.scrollTop || 0) - (e.clientTop || 0);
		}
		var cursorTop = event.pageY;	

		$.post('/notification.process/',
			{
				'TheID' : theID,
				'Type'	: notificationType,
				'Action': 'Add'

			},
			function(data) {
				if(data['Msg'] == 'success') {
					$('.NotificationLabel').children().remove();
					$('.NotificationLabel').html('Subscribed');
				}else{
					dil.XHMessage('Col_A', data['Msg'], cursorTop, 'Event', 0);
				}
			},
			'json'
		);
	} else {
		return(false);
	}
}
//------------------------------------------------------[TN]

// StopNotification ------------------------------------[TN]
dil.StopNotification = function(event, notificationID, page) {
	if(confirm('Are you sure you want to stop receiving notifications for this?')) {
		if ( event.pageX == null && event.clientX != null ) {
		  var e = document.documentElement||{}, b = document.body||{};
		  event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft || 0) - (e.clientLeft || 0);
		  event.pageY = event.clientY + (e.scrollTop || b.scrollTop || 0) - (e.clientTop || 0);
		}
		var cursorTop = event.pageY;	

		$.post('/notification.process/',
			{
				'NID'	: notificationID,
				'Action': 'Remove'
			},
			function(data) {
				if(data['Msg'] == 'success') {
					$( '#ACT_Section_Notifications .ACT_SectionContent' ).load( '/my_account.my_notifications.list/', {'Page':page} );					
				}else{
					dil.XHMessage('Content', data['Msg'], cursorTop, 'Event', 0);
				}
			},			
			'json'
		);
	}else{
		return(false);
	}
}
//------------------------------------------------------[TN]

//------------------------------------------------------[MN]
var DilbertSearch = function( ObjName ){ 
	var This = {
		ObjName: ObjName,
		CharIDs: [],

		Char_Toggle: function( CharID ){
			var CharIDs	= [];
			if( typeof( CharID ) == 'number' )
				CharIDs.push( CharID );
			else
				CharIDs = CharID;

			for( var i = 0; i < CharIDs.length; i++ ){

				var LI_Char	= $( '.CHR_CharID_'+ CharIDs[i] ).parent();
				var Action	= LI_Char.hasClass( 'CHR_Selected' ) ? 'DeSelect' : 'Select';

				switch( Action ){
					case 'Select':
						LI_Char.addClass( 'CHR_Selected' );
						this.CharIDs.push( CharIDs[i] );
					break;

					case 'DeSelect':
						LI_Char.removeClass( 'CHR_Selected' );
						this.CharIDs.splice( $.inArray( CharIDs[i], this.CharIDs ), 1 );
					break;
				}
			}

			$( '#SCH_CharIDs' ).val( this.CharIDs.join( ',' ) );
			$( '.CHR_CharCount' ).html( this.CharIDs.length );
		},
		Clear_Advanced: function () {
			$( '#AnyCharacter' ).attr( 'checked', 'checked' );
			$( '.CHR_Selected' ).removeClass( 'CHR_Selected ');
			$( '#SCH_CharIDs' ).val( '' );
			$( '#Author' ).val( '' );
			$( '#Types' ).get(0).selectedIndex = 0;
		},
		Reset_Date_Picker: function () {
			 $('#SpanDateAfter').html('');
			 $('#SpanDateBefore').html('');
			 $('#DateAfter').val('');
			 $('#DateBefore').val('');
			 $('.SCH_Range_Hyphen').remove();
			 $('.SCH_Calendar').datepicker( "setDate", new Date() );
			 $('.SCH_LinkReset').remove();
		}
	};

	return This; 
};
//------------------------------------------------------[MN]

// Header Login ----------------------------------------[TN]
var DilbertLogin = {
	ShowLoginForm : function( ParentNode ) {
		$('.HDR_SignupForm').css('display','none');
		$(ParentNode).append(
			'<div class="HDR_LoginForm">' +
			'	<div class="LOG_LogInBox">' +
			'		<a href="#" onclick="javascript: DilbertLogin.HideLoginForm(); return(false);" class="HDR_BtmLoginFormClose">close</a>' +
			'		<form class="LOG_LogInForm" name="LogInForm" method="POST" action="/login.process/" onsubmit="DilbertLogin.SubmitLogin(); return(false);">' +
			'			<table width="" cellpadding="2" cellspacing="0">' +
			'				<tr>' +
			'					<td>Username</td>' +
			'					<td><input tabindex="1" class="LOG_TextInput MSC_StyledInput" id="HDR_Username" type="text" name="Username" value="" /></td>' +
			'				</tr>' +
			'				<tr>' +
			'					<td>Password</td>' +
			'					<td><input tabindex="2" class="LOG_TextInput MSC_StyledInput" id="HDR_Password" type="password" name="Password" value="" /></td>' +
			'				</tr>' +
			'				<tr>' +
			'					<td nowrap>Remember Me</td>' +
			'					<td><input tabindex="3" type="checkbox"  id="HDR_RememberMe" name="RememberMe" /></td>' +
			'				</tr>' +
			'				<tr id="HDR_LoginRow">' +
			'					<td align="center"><div class="HDR_Progress"><img src="' + PATH.IMG + '/ico.progress.gif" /></a></td>' +
			'					<td><input tabindex="4" type="image" src="/img/v1/btn.login.gif" value="Log In" /></td>' +
			'				</tr>' +
			'				<tr>' +
			'					<td colspan="2">' +
			'					Your username is not necessarily your email address.<br /><br />' +
			'					Forgot <a href="/forgot_password/" title="Forgot username/password">username/password</a>?<br /><br />' +
			'					Not a member yet? please <a href="/register/" title="Register">register</a>!<br />' +
			'					<a href="/privacy/" title="Privacy Policy">Privacy Policy</a>' +
			'					</td>' +
			'				</tr>' +
			'			</table>' +
			'		</form>' +
			'	</div>' +
			'</div>'
		);
	},
	HideLoginForm : function( ) {
		$('.HDR_SignupForm').css('display','inline');
		$('.HDR_LoginForm').remove();
	},
	SubmitLogin : function() {
		$('.HDR_LoginError').remove();
		$('.HDR_Progress').css('display', 'block');
		var LoginVars = {
			Username	: $('#HDR_Username').val(),
			Password	: $('#HDR_Password').val(),
			RememberMe	: ( ($('#HDR_RememberMe:checked').length == 1 ) ? 'Yes' : 'No' )
		};
		$.post( '/ajax.login.process/', 
			LoginVars , 
			function( LoginReturn ) { 
				if ( LoginReturn['Msg'] == 'SUCCESS' )	{
					window.location.reload();
				} else {
					$('.HDR_Progress').css('display', 'none');
					$('#HDR_LoginRow').after( '<tr><td class="HDR_LoginError" colspan="2">' + LoginReturn['Msg'] + '</td></tr>');
				}
			}, 'json'
		);
		return(false);
	}
};
//------------------------------------------------------[TN]

// Send To Friend Functionality ------------------------[SK]
dil.SendToFriend = function(Event, FormElm, LinkURL, EmailsList, FromName, Callback) {
	
	$('.PAG_EmailAction', $(FormElm).parent().parent()).hide();
	$('.PAG_EmailFriendStatus div', $(FormElm).parent().parent()).remove();
	$('.PAG_EmailFriendStatus', $(FormElm).parent().parent()).append('<div class="PAG_AJAXProcess">...sending</div>');
	
	var FormElm = FormElm;
	var Callback = Callback;
	
	$.getJSON('/send_to_friend.process/', 
		{
		Event: Event,
		LinkURL: LinkURL,
		EmailsList: EmailsList,
		FromName: FromName
		},
		function(Data, TextStatus){
			var jForm = $(FormElm).parent().parent();
//			alert(jForm.html());
			$('.PAG_EmailFriendStatus .PAG_AJAXProcess', jForm).remove();
			if(TextStatus == 'success' && Data['Status'] != 'Error'){
				$('.PAG_EmailFriendStatus', jForm).append('<div class="PAG_AJAXSuccess">'+Data['Msg']+'</div>');
				$('.PAG_EmailClose', jForm).show();
				jForm.css('background-image', 'url("/img/v1/blog/bg.send_form.success.gif")');
			}else{
				$('.PAG_EmailAction', jForm).show();
				if($('.PAG_EmailFriendStatus .PAG_AJAXError', jForm).length){
					$('.PAG_EmailFriendStatus .PAG_AJAXError', jForm).html(Data['Msg']);
				}else{
					$('.PAG_EmailFriendStatus', jForm).append('<div class="PAG_AJAXError">'+Data['Msg']+'</div>');
				}
				jForm.css('background-image', 'url("/img/v1/blog/bg.send_form.error.gif")');
				if(jQuery.isFunction(Callback)){
					Callback();
				}
			}
		}
	)
};
	
dil.CloseSendForm = function(jForm){
	var jForm = jForm;
	var CloseCallBack = function(){
		$('.PAG_EmailFriendStatus div', jForm).remove();
		$('.PAG_EmailAction', jForm).show();
		$('.PAG_EmailClose', jForm).hide();
		jForm.css('background-image', 'url("/img/v1/blog/bg.send_form.gif")');
	};
	if(jQuery.browser.msie && Number(jQuery.browser.version) < 7){
		jForm.toggle();
		CloseCallBack();
	}else{
		jForm.slideToggle('fast', CloseCallBack);
	}
};
	
dil.ToggleSendForm = function(jForm){
	if(jForm.css('display') == 'none'){
		if(jQuery.browser.msie && Number(jQuery.browser.version) < 7){
			jForm.toggle();
		}else{
			jForm.slideToggle('fast');
		}
	}else{
		dil.CloseSendForm(jForm);
	}
};

dil.ClickToClose = function(Event) {
	var Parent = $(this).parent();
	$(this).remove();
	if (!Parent.children().length)
		Parent.remove();
};

dil.Toggle = function(jContainer){
	if(jQuery.browser.msie && Number(jQuery.browser.version) < 7){
		jContainer.toggle();
	}else{
		jContainer.slideToggle('fast');
	}
}

//------------------------------------------------------[SK]

// Account Editing -------------------------------------[MN]
var DIL_Account = function( ObjName ){ 
	var This = {
		ObjName: ObjName,
		AvatarID: 0,
		Avatars: null,

		Avatars_Load: function( Page ){
			var PerPage		= 10;
			var LastPage	= Math.ceil( this.Avatars.length / PerPage );
			var HTML		= '<div class="ACT_AvatarList_Top"></div><div class="ACT_AvatarList_Body"><div class="ACT_AvatarChoices">';
			for( var i = ( ( Page - 1 ) * PerPage ); i < ( Page * PerPage ); i++ ){
				if( this.Avatars[i] )
					HTML += '<div class="ACT_AvatarChoice'+ ( this.Avatars[i].AvatarID == this.AvatarID ? ' ACT_Selected' : '' ) +'"><img class="ACT_Avatar" onclick="javascript: '+ ObjName +'.Avatars_Select( '+ this.Avatars[i].AvatarID +', this.src );" src="'+ this.Avatars[i].ImagePath +'" /></div>';
			}

			HTML += '<div class="ACT_AvatarPaging">';
			if( Page != 1 )
				HTML += '<a href="#" class="ACT_PagingButton" onclick="javascript: '+ ObjName +'.Avatars_Load( '+ ( Page - 1 ) +' ); return false;"><img src="'+ PATH.IMG +'/btn.previous.gif" alt="Previous" border="0" /></a>';
			if( Page != LastPage )
				HTML += '<a href="#" class="ACT_PagingButton" onclick="javascript: '+ ObjName +'.Avatars_Load( '+ ( Page + 1 ) +' ); return false;"><img src="'+ PATH.IMG +'/btn.next.gif" alt="Next" border="0" /></a>';
			HTML += '</div></div></div><div class="ACT_AvatarList_Bottom"></div>';

			$( '.ACT_AvatarList' ).html( HTML );
		},

		Avatars_Select: function( AvatarID, Src ){
			this.AvatarID = AvatarID;
			$( '.ACT_CurrentAvatar' ).attr( 'src', Src );
			this.Avatars_Toggle();
			$.post( PATH.Public +'/my_account.avatar.edit.process/', { AvatarID: AvatarID } );
		},

		Avatars_Toggle: function(){
			var Div_AvatarList	= $( '.ACT_AvatarList' );
			var Action			= Div_AvatarList.hasClass( 'ACT_Open' ) ? 'Close' : 'Open';

			switch( Action ){
				case 'Open':
					Div_AvatarList.addClass( 'ACT_Open' );
					this.Avatars_Load( 1 );
				break;

				case 'Close':
					Div_AvatarList.removeClass( 'ACT_Open' );
				break;
			}
		},

		Input_ToggleEdit: function( Event ){
			var MyInput = $( Event.target );

			var Action		= Event.data.Action;
			var PostPage	= (Event.data.PostPage) ? Event.data.PostPage : 'my_account.profile.edit.process';
			var ItemID		= (Event.data.ItemID) ? Event.data.ItemID : 0;

			switch( Action ){
				case 'Edit':
					MyInput.addClass( 'ACT_FieldEdit' );
				break;

				case 'Save':
					MyInput.removeClass( 'ACT_FieldEdit' );
					$.post( PATH.Public + '/' + PostPage + '/', { Field: MyInput.attr( 'name' ), Value: MyInput.val(), ItemID: ItemID }, This.Save_Callback, 'json' );
				break;
			}
		},

		Profile_CheckKey: function( Event ){
			if ( 13 == ( Event.keyCode || Event.which ) ){
				$( Event.target ).blur();
			}
		},

		Profile_Save_Callback: function( Response ) {
			$( '.XHMessage' ).remove();

			for( i in Response.Messages )
				dil.XHMessage( 'ACT_ProfileMessages', Response.Messages[i], 0, 'DOM', Response.Success, false );
//				dil.XHMessage( 'ACT_Section_Profile', Response.Messages[i], 500, 'Event', Response.Success, false );
/*
			if( Response.Success ) {
				$( '.ACT_FieldInput' ).removeClass( 'ACT_FieldEdit' );
				$( '.ACT_FieldInput_Country' ).css( 'display', 'none' );
				$( '.ACT_FieldValue_Country' ).html( $( '.ACT_FieldInput_Country option[value='+ Response.CountryID +']' ).html() ).css( 'display', 'inline' );
				$( '.ACT_FieldInput_Password' ).css( 'display', 'none' );
				$( '.ACT_FieldValue_Password' ).css( 'display', 'inline' );

				$( '.ACT_RefreshLink' ) .css( 'display', 'none' );
				var ToggleLink = $( '.ACT_EditLink' );
					$(ToggleLink).children('img').attr('alt', 'EDIT');
					$(ToggleLink).children('img').attr('src', '/img/v1/btn.edit.gif');

					ToggleLink.removeClass( 'ACT_LinkDisabled' )
			}
*/
		},

		Profile_Refresh: function(){
			This.Section_Toggle( 'ACT_Section_Profile', 'Close' );
			$( '.ACT_Section_Profile .ACT_SectionContent' ).html( '' );
			This.Section_Toggle( 'ACT_Section_Profile', 'Open' );
		},

		Profile_ToggleEdit: function(){
			var ToggleLink = $( '.ACT_EditLink' );

			if( ToggleLink.hasClass( 'ACT_LinkDisabled' ) )
				return false;

			switch( $(ToggleLink).children('img').attr('alt') ) {
				case 'EDIT':
					$( '.ACT_RefreshLink' ) .css( 'display', 'inline' );
					$( '.ACT_FieldInput' ).addClass( 'ACT_FieldEdit' );
					$( '.ACT_FieldInput_Country' ).css( 'display', 'inline' );
					$( '.ACT_FieldValue_Country' ).css( 'display', 'none' );
					$( '.ACT_FieldInput_Password' ).css( 'display', 'inline' ).val( '' );
					$( '.ACT_FieldValue_Password' ).css( 'display', 'none' );
					$(ToggleLink).children('img').attr('alt', 'SAVE');
					$(ToggleLink).children('img').attr('src', '/img/v1/btn.save_edits.gif');
				break;

				case 'SAVE EDITS':
//					ToggleLink.addClass( 'ACT_LinkDisabled' );

					var ProfileForm = ToggleLink.parents( '.ACT_ProfileForm' );
					$.post(
						PATH.Public +'/'+ ProfileForm.attr( 'action' ) +'/',
						ProfileForm.serialize(),
						This.Profile_Save_Callback,
						'json'
					);
				break;
			}
		},

		Section_Toggle: function( Section ){
			var Div_Section	= $( '.'+ Section );
			var Action		= arguments[1] != null ? arguments[1] : ( Div_Section.hasClass( 'ACT_Open' ) ? 'Close' : 'Open' );
			var Div_Content	= Div_Section.children( '.ACT_SectionContent' );

			switch( Action ){
				case 'Close':
					Div_Section.removeClass( 'ACT_Open' );
					$('.XHMessage').remove();
				break;

				case 'Open':
					if( !Div_Section.hasClass( 'ACT_Open' ) )
						Div_Section.addClass( 'ACT_Open' );

					if( !Div_Content.html() ){
						switch( Div_Section.attr( 'id' ) ){
							case 'ACT_Section_MyFavorites':		var URL = '/my_account.my_favorites.list/';			break;
							case 'ACT_Section_MyLists':			var URL = '/my_account.my_lists.list/';				break;
							case 'ACT_Section_MySubscriptions':	var URL = '/my_account.my_subscriptions.list/';		break;
							case 'ACT_Section_News':			var URL = '/my_account.latest_news/';				break;
							case 'ACT_Section_Notifications':	var URL = '/my_account.my_notifications.list/';		break;
							case 'ACT_Section_Profile':			var URL = '/my_account.profile/';					break;
							case 'ACT_Section_MyMashups':		var URL = '/my_account.my_mashups.list/';			break;
						}

						Div_Content.load( PATH.Public + URL, {}, function(){
							switch( Div_Section.attr( 'id' ) ){
								case 'ACT_Section_MyLists':
									$( '.ACT_Section_MyLists .ACT_FieldInput' ).each(function(){
										$( this ).bind('focus', { Action: 'Edit' }, This.Input_ToggleEdit ).bind( 'blur', { Action: 'Save', PostPage: 'user.list.process', ItemID: $( this ).attr( 'id' ).replace( 'ACT_ListID_', '' ) }, This.Input_ToggleEdit ).bind( 'keydown', This.Profile_CheckKey ); 
									} );

									$( '.ACT_Section_MyLists .LinkDeleteList' ).each(function(){
										$( this ).bind( 'click', { 'Action'	: 'Delete', 'ItemID' : $( this ).attr( 'id' ).replace( 'ACT_DelListID_', '' ) }, This.Profile_DeleteList );
									});
								break;
/*
								default:
									$( '.ACT_FieldInput' ).bind( 'focus', { Action: 'Edit' }, This.Profile_ToggleEdit ).bind( 'blur', { Action: 'Save' }, This.Profile_ToggleEdit ).bind( 'keydown', This.Profile_CheckKey );
								break;
*/
							}							
						} );
					}
				break;
			}
		},

		Profile_DeleteList: function( Event ) {
			if ( confirm( 'Are you sure you want to delete this list? \nNote: this action cannot be undone.' ) ) {
				$.post( '/user.list.process/', 
					Event.data, 
					function(data) {
						if(data['Msg'] == 'success') {
							$( '#ACT_DelListID_' + Event.data.ItemID ).parents( '.ACT_ListRow' ).html('<td colspan="3">Deleted</td>');
						}else{
							dil.XHMessage('ACT_Messages', data.Msg, 350, 'DOM');
						}					
					},			
					'json'
				);
			}
			return (false);
		},

		UpdateSubscriptions: function() {
			$('.XHMessage').remove();
			var Subscriptions = [];
			$.post( PATH.Public + '/my_account.my_subscriptions.process/', 
				$('.ACT_Subscriptions').serialize(), 
				function( data ) {
					dil.XHMessage( 'ACT_SubscriptionMessages', data.Msg, 0, 'DOM', ((data.Status == 'UPDATED') ? 1 : 0 ), true );
				}, 
				'json'
			);
		},

		RemoveFavorite: function(Container, StripID, Callback) {
			$.post( PATH.Public + '/my_account.my_favorites.process/', { StripID: StripID }, Callback);
		},

		DeleteMashup: function(Container, StripID, Callback) {
			$.post( PATH.Public + '/my_account.my_mashups.process/', { StripID: StripID }, Callback);
		}
	};

	return This; 
};
//------------------------------------------------------[MN]

//------------------------------------------------------[TN]
dil.setDateRange = function( date ) {
	$('#DateAfter').val('');
	$('#DateBefore').val('');
	$('#SpanDateAfter').html('');
	$('#SpanDateBefore').html('');
	$('.SCH_Range_Hyphen').remove();
	$('.SCH_LinkReset').remove();
	var dateRange = date.split('-');
	if ( dateRange[0] != null ) {
		$('#DateAfter').val( jQuery.trim( $.datepicker.formatDate('mm/dd/yy', new Date(dateRange[0])) ) );
		$('#SpanDateAfter').html( jQuery.trim( $.datepicker.formatDate('mm/dd/yy', new Date(dateRange[0])) ) );
	}

	if ( dateRange[1] != null ) {
		$('#DateBefore').val( jQuery.trim( $.datepicker.formatDate('mm/dd/yy', new Date(dateRange[1])) ) );
		if ( jQuery.trim( dateRange[0] ) != jQuery.trim( dateRange[1] ) )
			$('#SpanDateBefore').html( jQuery.trim( $.datepicker.formatDate('mm/dd/yy', new Date(dateRange[1])) ) );
	}

	if ( dateRange[0] != null && dateRange[1] != null && jQuery.trim( dateRange[0] ) != jQuery.trim( dateRange[1] ) )
		if ( $('#DateAfter').attr('type') == 'text' )
			$('#DateAfter').after( '<span class="SCH_Range_Hyphen"> - </span>' );
		else
			$('#SpanDateAfter').after( '<span class="SCH_Range_Hyphen"> - </span>' );


	if ( $('#DateAfter').attr('type') == 'hidden' )
		$('.SCH_Date_Ranges').append('<div class="SCH_LinkReset"><a href="#" onclick="javascript: SCH.Reset_Date_Picker(); return(false);">reset<a/></div>');

}
//------------------------------------------------------[TN]

var MSH_Help = {
	LeaveOpen : false,
	HelpText : {
		Punch: '"Punch Line" is a really cool application that enables you to replace Scott\'s punch line (the final frame of the strip) with your own. Once you write your incredibly witty final frame, it will be posted on Dilbert.com for the world to vote and comment upon. You can also send it to gazillions of friends, share it on services like Digg, print it, etc. So close this box and click on the big PUNCH ONE NOW! button to prove your comic genius!',
		Group: 'Like being social? "Group Mash" combines your comic genius with OTHER PEOPLE\'S comic genius to create SUPER COMIC GENIUS! Here\'s how it works: we remove the text from all 3 frames of a Dilbert strip. You write the text for the first frame, which is then posted on Dilbert.com and - if you\'d like - sent to your friends. Someone else writes the second frame, which is now posted on Dilbert.com and - if they\'d like - sent to their friends... and then it happens all over again for the final frame. The completed comic is then posted on Dilbert.com for everyone to vote and comment upon.',
		Theme: 'Anyone can write anything they\'d like in a Group Mash (no profanity, please), but reading different perspectives on a single theme can be REALLY FUNNY. Many of the themes will be office-related (human resources, anyone?), but non-office themes such as dating or current events will also appear.',
		Tab:   'Group Mashes enable you to start your own, continue or even finish those mashes started by others. (We HIGHLY ENCOURAGE you to do both, many, many times.) The tabs enable you to easily choose among starting your own, adding the second frame, adding the third frame, or simply reading the completed strips and and then voting or commenting on each to your heart\'s content.'
	},
	ShowHelp : function( ParentNode, HelpText, LeaveOpen ) {
		$('.MSH_HelpContainer').remove();
		$('.' + ParentNode).append('<div class="MSH_HelpContainer' + ((arguments[3] == null) ? '' : ' ' + arguments[3]) + '"><div class="MSH_HelpContainerInner">' + this.HelpText[HelpText] + ' <a href="#" onclick="javascript: $(\'.MSH_HelpContainer\').remove(); MSH_Help.LeaveOpen=false; return(false);" style="float: right;">close</a><br style="clear: right;" /></div></div>');
		$('.MSH_HelpContainerInner').corner("round 8px").parent().css('padding', '2px').corner("round 10px");

		if ( LeaveOpen == true )
			this.LeaveOpen = true;
	}
};


var DIL_API = {
	EmailMashupPostPixelData : function( JSONData ) {
		for(i=0; i<JSONData.length; i++)
			alert(JSONData[i]);
	}
};

// Event Delegation ------------------------------------[TN]
jQuery.delegate = function(Rules) {
	return function(e) {
		var Target = $(e.target);
		for (var Selector in Rules)
			if (Target.is(Selector)) return Rules[Selector].apply(this, $.makeArray(arguments));
	}
}
//------------------------------------------------------[TN]

// Strip Viewer ----------------------------------------[TN]
var StripViewer = function( ){ 
	var This = {
		GoToStripDate : function(date){
			// date picker go to strip for that date
			window.location.href = '/strips/comic/' + $.datepicker.formatDate('yy-mm-dd', new Date(date)) + '/';
		},
		OpenShareLinks : function(e){
			// open share panel
			This.CloseAllPanels(e);
			if ( $(e.target).parents('.STR_Container').children().children('.STR_ShareLinks').css('display') == 'none' )
				$(e.target).parents('.STR_Container').children().children('.STR_ShareLinks').show('fast');
		},
		CloseShareLinks : function(e){
			// close share panel
			$(e.target).parents('.STR_Container').children().children('.STR_ShareLinks').hide('normal');
		},
		OpenEmailPanel : function(e){
			// open email panel
			This.CloseAllPanels(e);
			if ( $(e.target).parents('.STR_Container').children().children('.STR_EmailPanel').css('display') == 'none' )
				$(e.target).parents('.STR_Container').children().children('.STR_EmailPanel').animate( { bottom: '0px' }, 500 ).fadeIn('fast');
		},
		CloseEmailPanel : function(e){
			// close email panel
			if ( $(e.target).parents('.STR_Container').children().children('.STR_EmailPanel').css( 'bottom' ) == '0px' )
				$(e.target).parents('.STR_Container').children().children('.STR_EmailPanel').animate( { bottom: '-307px' }, 500 ).fadeOut('normal');;
		},
		EmailSend : function(e){
			// ajax send email
			$(e.target).parent('.STR_EmailInputs').css('display', 'none');
			$(e.target).parents('.STR_EmailPanel').append('<div class="STR_Working">Sending message...<br /><br /><img src="/img/v1/ico.progress.gif" /></div>');

			$.post(PATH.Public + '/api/email.process/', 
				{
					StripID		: $(e.target).parents('.STR_Container').attr('rel'), 
					FromName	: $(e.target).siblings('input[@name=FromName]').val(),
					Emails		: $(e.target).siblings('input[@name=Emails]').val(),
					Message		: $(e.target).siblings('textarea[@name=Message]').val(),
					Type		: 'Strip'
				}, 
				function(data){
					if ( data.Success == 'true' ) {
						$(e.target).parents('.STR_EmailPanel').children('.STR_Working').html(data.Message + '<div class="STR_EmailReturn"><a href="#" onclick="return(false);" class="STR_EmailMore STR_EmailShowForm"><span>MORE, MORE!</span></a><a href="#" onclick="return(false);" class="STR_EmailClose STR_EmailDone"><span>I\'M DONE</span></a></div>');
					} else {
						$(e.target).parents('.STR_EmailPanel').children('.STR_Working').html(data.Message + '<br /><a href="#" onclick="return(false);" class="STR_EmailBack STR_EmailShowForm"><span>BACK</span></a>');
					}
				}, 
				'json'
			);
		},
		ShowEmailForm : function(e) {
			// show email form, after submit, takes user back to form panel (back button)
			$(e.target).parents('.STR_EmailPanel').children('.STR_EmailInputs').css('display', '');
			$(e.target).parents('.STR_EmailPanel').children('.STR_Working').remove();
		},
		OpenSavePanel : function(e){
			// open save panel
			This.CloseAllPanels(e);
			if ( $(e.target).parents('.STR_Container').children().children('.STR_SavePanel').css( 'display' ) == 'none' )
				$(e.target).parents('.STR_Container').children().children('.STR_SavePanel').animate( { bottom: '0px' }, 400 ).fadeIn('fast');;
		},
		CloseSavePanel : function(e){
			// close save panel
			if ( $(e.target).parents('.STR_Container').children().children('.STR_SavePanel').css( 'bottom' ) == '0px' )
				$(e.target).parents('.STR_Container').children().children('.STR_SavePanel').animate( { bottom: '-168px' }, 400 ).fadeOut('normal');;
		},
		AddToList : function(e) {
			$(e.target).parents('.STR_SavePanel').children().children('.STR_XHMessage').html('');
			if ( VPI.IsLoggedIn ) {
				$(e.target).parents('.STR_SavePanel').children('.STR_SaveOptions').fadeOut('fast');
				$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').fadeIn('slow');
				STR.GetLists(e);
			} else {
				$(e.target).siblings('.STR_XHMessage').html('You must be logged in to add to lists.');
			}
		},
		SaveListBack : function(e) {
			$(e.target).parents('.STR_SavePanel').children().children('.STR_XHMessage').html('');
			$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').fadeOut('fast');
			$(e.target).parents('.STR_SavePanel').children('.STR_SaveOptions').fadeIn('slow');
		},
		AddToFaves : function(e) {
			// ajax add to favorites
			$(e.target).siblings('.STR_XHMessage').html('');
			$.post(PATH.Public + '/api/save_favorite.process/', 
				{ StripID : $(e.target).parents('.STR_Container').attr('rel'), Fav : 1 },
				function( data ){
					$(e.target).siblings('.STR_XHMessage').html(data.Message);
				},
				'json'
			);
		},
		GetLists : function(e) {
			// ajax get user's list for select combo box
			$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').children('.STR_FavesList').empty();

			$.get(PATH.Public + "/xml/lists/",
				null,
				function(data) {
					$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').children('.STR_FavesList').append('<option value="-1">select a list</option>');
					$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').children('.STR_FavesList').append('<option value="0">New List</option>');
					$.each( 
						$(data).find("List"), 
						function(i, n) {
							$(e.target).parents('.STR_SavePanel').children('.STR_SaveList').children('.STR_FavesList').append('<option value="' + $(n).find('ListID').text() + '">' + $(n).find('Title').text() + '</option>');
						}
					);
				},
				'xml'	
			);
		},
		ListSelect : function(TheNode) {
			// onchange of list select combo box
			$(TheNode).siblings('.STR_XHMessage').html('');

			var ListID = $(TheNode).children('option:selected').val();
			if ( ListID == 0 ) {
				$(TheNode).siblings('.STR_ListInputs').children('.STR_ListTitle').css({'float' : 'left', 'display' : ''});
				$(TheNode).siblings('.STR_ListInputs').children('.STR_ListGo').css({'float' : 'left', 'marginLeft' : '5px', 'marginTop' : '2px'});
				$(TheNode).siblings('.STR_ListInputs').fadeIn('fast');
			} else if ( ListID > 0 ) {
				$(TheNode).siblings('.STR_ListInputs').children('.STR_ListTitle').css('display','none');
				$(TheNode).siblings('.STR_ListInputs').children('.STR_ListGo').css({'float' : 'none', 'margin' : '2px auto'});
				$(TheNode).siblings('.STR_ListInputs').fadeIn('fast');
			} else {
				$(TheNode).siblings('.STR_XHMessage').html('Please select a list or add a new one.');
			}
		},
		ListGo : function(e) {
			// ajax add to list
			$(e.target).siblings('.STR_XHMessage').html('');
			$.post(PATH.Public + '/api/save_favorite.process/', 
				{ StripID : $(e.target).parents('.STR_Container').attr('rel'), ListID : $(e.target).parents('.STR_SaveList').children('select option:selected').val(),  ListTitle : $(e.target).siblings('input[@name=ListTitle]').val() },
				function( data ){
					$(e.target).parents('.STR_SaveList').children('.STR_XHMessage').html(data.Message);
				},
				'json'
			);
		},
		PrintStrip : function(e) {
			// print button
			var ImgPath = $(e.target).parents('.STR_Container').children('input[@name=PrintPath]').val();
			$($('#PrintFrame').get(0).contentWindow.document.body).html('<img src="' + ImgPath + '" />');
			$('#PrintFrame' ).get( 0 ).contentWindow.focus(); 
			$( '#PrintFrame' ).get( 0 ).contentWindow.print();
		},
		OpenEmbedPanel : function(e) {
			// open embed panel
			This.CloseAllPanels(e);
			if ( $(e.target).parents('.STR_Container').children().children('.STR_EmbedPanel').css( 'display' ) == 'none' )
				$(e.target).parents('.STR_Container').children().children('.STR_EmbedPanel').animate( { bottom: '0px' }, 300 ).fadeIn('fast');
		},
		CloseEmbedPanel : function(e) {
			// close embed panel
			if ( $(e.target).parents('.STR_Container').children().children('.STR_EmbedPanel').css( 'bottom' ) == '0px' )
				$(e.target).parents('.STR_Container').children().children('.STR_EmbedPanel').animate( { bottom: '-115px' }, 300 ).fadeOut('normal');
		},
		OpenMashPanel : function(e) {
			// open mash me panel
			This.CloseAllPanels(e);
			if ( $(e.target).parents('.STR_Container').children().children('.STR_MashPanel').css('display') == 'none' )
				$(e.target).parents('.STR_Container').children().children('.STR_MashPanel').animate( { bottom: '0px' }, 300 ).fadeIn('fast');;
		},
		CloseMashPanel : function(e) {
			// close mash me panel
			if ( $(e.target).parents('.STR_Container').children().children('.STR_MashPanel').css( 'bottom' ) == '0px' )
				$(e.target).parents('.STR_Container').children().children('.STR_MashPanel').animate( { bottom: '-127px' }, 300 ).fadeOut('normal');;
		},
		CloseAllPanels : function(e) {
			// close all panels
			This.CloseShareLinks(e);
			This.CloseEmailPanel(e);
			This.CloseSavePanel(e);
			This.CloseEmbedPanel(e);
			This.CloseMashPanel(e);
		},
		Vote : function(e) {
			This.CloseShareLinks(e);
			// ajax voting/rating
			$('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/blank.gif")'});

			$.post(PATH.Public + '/api/rating.process/', 
				{ Type : 'strip', ItemID : $(e.target).parents('.STR_Container').attr('rel'), Rating : $(e.target).attr('rel') },
				function( data ) {
					if ( data.Success == 'true' ) {
						$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_thanks.gif")'});
						var StripID = $(e.target).parents('.STR_Container').attr('rel');
						$('.STR_Container').each( function() {
							if ( $(this).attr('rel') == StripID ) {
								$(this).children('.STR_Footer').children().children('.STR_VoteCount').html( $(this).children('.STR_Footer').children().children('.STR_VoteCount').html() * 1 + 1 );
								$(this).children('.STR_Footer').children().children('.STR_Stars').rating('',{maxvalue:5,increment:.5, curvalue:$(e.target).attr('rel')});
							}
						})
					} else {
						switch ( data.Message ) {
							case 'This strip is invalid.':
								$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_invalidtype.gif")'});
							break;

							case 'Invalid rating value.':
								$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_invalidvalue.gif")'});
							break;

							case 'Invalid strip ID':
								$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_invalidstrip.gif")'});
							break;

							case 'You have already rated this strip.':
								$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_alreadyvoted.gif")'});
							break;

							default:
								if ( data.Message.substr(0,21) == 'You must be logged in' )
									$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_mustbeloggedin.gif")'});
								else
									$(e.target).parents('.STR_Container').children().children('.STR_Dogbert').css({'background-image' : 'url("' + PATH.IMG + '/rating/dogbert_error.gif")'});
							break;
						}
					}
				},
				'json'
			);
			return(false);
		}
	}
	return This;
}

var STR = new StripViewer();

$(document).ready( function() {
	// Strip Viewer ----------------------------------------[TN]
	$('.STR_Container').click( $.delegate({
		'.STR_BtnShare' : function(e) {
			STR.OpenShareLinks(e);
		},
		'.STR_ShareClose' : function(e) {
			STR.CloseShareLinks(e);
		},
		'.STR_BtnEmail' : function(e) {
			STR.OpenEmailPanel(e);
		},
		'.STR_EmailClose' : function(e) {
			STR.CloseEmailPanel(e);
		},
		'.STR_EmailSend' : function(e) {
			STR.EmailSend(e);
		},
		'.STR_EmailShowForm' : function(e) {
			STR.ShowEmailForm(e);	
		},
		'.STR_BtnSave' : function(e) {
			STR.OpenSavePanel(e);
		},
		'.STR_SaveClose' : function(e) {
			STR.CloseSavePanel(e);
		},
		'.STR_AddToFaves' : function(e) {
			STR.AddToFaves(e);
		},
		'.STR_AddToList' : function(e) {
			STR.AddToList(e);
		},
		'.STR_SaveListBack' : function(e) {
			STR.SaveListBack(e);
		},
		'.STR_ListGo' : function(e) {
			STR.ListGo(e);
		},
		'.STR_BtnPrint' : function(e) {
			STR.PrintStrip(e);
		},
		'.STR_BtnEmbed' : function(e) {
			STR.OpenEmbedPanel(e);
		},
		'.STR_EmbedClose' : function(e) {
			STR.CloseEmbedPanel(e);
		},
		'.STR_CopyEmbed' : function(e) {
			$.copy($(e.target).siblings('textarea[@name=EmbedCode]').val());
		},
		'.STR_BtnMash' : function(e) {
			STR.OpenMashPanel(e);
		},
		'.STR_MashClose' : function(e) {
			STR.CloseMashPanel(e);
		},
		'.STR_RatingStar' : function(e) {
			STR.Vote(e);
		}
	}));

	$('.STR_FavesList').change( function() {
		STR.ListSelect(this);
	});
	//------------------------------------------------------[TN]
});
//------------------------------------------------------[TN]