/**
 * Holds the mains set of commands for FDCA. Modification History ID WHO DATE
 * COMMENTS ------- -------------- -------------
 * ---------------------------------- rr001 Rod 03/04/2011 Added LoginPage as
 * global function. rr002 Rod 05/04/2011 Added forgot pwd functionality.
 * 2011/04/13 - Dipesh update menus to used ID hash tag instead of location in
 * list.
 */
$(document).ready(function()
{
	/**
	 * Handle when menu/submenu is loaded.
	 */
	var onMenuLoad = function()
	{
		// Clean anchors.
		$('a').each(function()
		{
			var name = $(this).attr('name');
			name = name.replace(/\\"/g, '');
			// console.log(name);
			$(this).attr('name', name);
		});

		setTimeout(function()
		{
			// Parse URL for anchor
			// http://www.akrostaging.com.au/FDCA2/index.php/main/Family%20Day%20Care%20Matters#S301&anchor=testlink
			var Anchor = location.hash.match(/&anchor=[^&]*&?/);
			
			//console.log(Anchor);

			if (Anchor != null)
			{
				var name = Anchor[0].replace('&anchor=', '').replace('&', '');

				var $a = $('a').filter('[name="' + name + '"]');

				//console.log($a);

				$('body').scrollTo($a, 800);
				
				//window.a = $a;
				//console.log($a.scrollTop());
				
				/**
				$('html,body,document').animate(
				{
					scrollTop : $a.offset().top
				}, 'slow');
				**/
			}
		}, 500);
	}

	/**
	 * Handle url change event.
	 */
	$(window.location).bind('change', function()
	{
		var MenuNumber = location.hash.match(/^#(M|S)\d[^&]*&?/);
		if (MenuNumber == null)
		{
			window.location.href = $('.CurrentMenu').find('a').attr('href');
			return;
		}

		MenuNumber = MenuNumber[0].replace('#', '').replace('&', '');

		if (MenuNumber.substring(0, 1) == 'M')
		{
			Core.LoadMenuPage(MenuNumber.replace('M', ''), "maincontent", "Menu", onMenuLoad);
		}
		else if (MenuNumber.substring(0, 1) == 'S')
		{
			Core.LoadMenuPage(MenuNumber.replace('S', ''), "maincontent", "Submenu", onMenuLoad)
		}

		/**
		 * var MenuNumber = location.hash.match(/^#[^&]*&?/); if
		 * (!isNaN(MenuNumber) && MenuNumber != '' && MenuNumber != '0' &&
		 * $('.Submenu').children().length != 0) { var script =
		 * $($('.Submenu').find('a').get(parseInt(MenuNumber) -
		 * 1)).attr('href').replace('javascript:', ''); //
		 * console.log(MenuNumber); // var script =
		 * $($('.Submenu').find('a').get(parseInt(MenuNumber) - // 1)); //
		 * console.log(script); } else { var script =
		 * $('.CurrentMenu').find('a').attr('href'); if (script != undefined) {
		 * script.replace('javascript:', ''); } else { script = ''; } }
		 * eval(script);
		 */
	});

	// Inital url load content.
	$(window.location).trigger('change');

	/**
	 * // If not home page, load the first menu's page. if
	 * ($('.HomeMenu').length == 0) { // Exceute the script related to the
	 * module. var script =
	 * $('.CurrentMenu').find('a').attr('href').replace('javascript:', '');
	 * eval(script); }
	 */

	// Load the page elements if they exist.
	// NOTE: Load page will only retrieve if the given page element actually
	// exists hence not bandwidth wasted.
	Core.LoadPage('1', 'Advertisements');
	Core.LoadPage('2', 'FileManager');
	Core.LoadPage('3', 'PartnersModule');
	Core.LoadPage('4', 'HomePageBlurb');
	Core.LoadPage('5', 'NewsPreview');
	Core.LoadPage('6', 'ImageSliderContainer');

	// Login button.
	$('.LoginButton').bind('click', function()
	{
		LoginPage();
		/**
		 * $('.LoginContainer').dialog( { modal : true, height : '500', width :
		 * '500' });
		 */
	});

	// rr002 - Forgot password
	// $('#forgotpwd').click(function(){ FGPWD(); return false;});
	$('#forgotpwd').click(function()
	{
		$('#resendpwd').show();
		return false;
	});

	$('#submitresendpwd').click(function()
	{

		// $('#resendpwd').hide();
		$('#submitresendpwd').hide();
		$('#resendpwdtext').hide();
		$('#resendpwdfield').hide();
		$('#resendpwdmsg').show();
		FGPWD();

		// return false;
	});

	/**
	 * Restricted Menu Check
	 */
	// Bind live event to <a> links to capture direct references to a page and
	// show them as a standalone page.
	$('a').live('click', function(element)
	{
		if ($(this).hasClass('IsRestricted'))
		{
			var URL = $(element.currentTarget).attr('href');

			$.ajax(
			{
				url : Core.Base(),
				type : 'post',
				data : (
				{
					'option' : 'IsRestrictedCheck',
					'URL' : URL
				}),
				success : function(data)
				{
					if (data == 'True')
					{
						location.href = URL;
					}
					else if (data == 'Login')
					{
						LoginPage(URL);
					}
					else
					{
						// alert(data);
						alert('You do not have access to the page you requested.');
					}
				}
			});
			return false;
		}
	});

	/**
	 * Standalone pages.
	 */
	$('body').append('<div class="standalone_page_container_dialog_box"><div class="content"></div></div>');
	var $container = $('.standalone_page_container_dialog_box');
	$container.dialog(
	{
		autoOpen : false,
		modal : true,
		width : 800,
		position : 'top'
	});

	// Bind live event to <a> links to capture direct references to a page and
	// show them as a standalone page.
	$('a').live('click', function(element)
	{
		if ($(element.currentTarget).parent().hasClass('fc-event'))
		{
			return true;
		}

		// Get the url.
		var url = $(element.currentTarget).attr('href');

		// Check if matches the standalone page url schema.
		if (url.match('index.php/p/') == null)
		{
			return true;
		}

		/**
		 * // Check if the standalone container exists, if not create it. if
		 * ($('.standalone_page_container_dialog_box').length == 0) {
		 * $('body').append('<div class="standalone_page_container_dialog_box"><div
		 * class="content"></div></div>'); } // Get the standalone contianer.
		 * var $container = $('.standalone_page_container_dialog_box');
		 * 
		 * $container.dialog( { autoOpen : true, modal : true, width : 800,
		 * position : 'top' });
		 */

		// Load page contents and put in container.
		$.ajax(
		{
			url : url,
			type : 'get',
			success : function(data)
			{
				$container.find('.content').html(data);
				$container.dialog('open');

				// Online Print Centre agreement.
				var $AcceptCheckbox = $container.find('.accept-checkbox');
				var $AcceptDummy = $container.find('.accept-dummy');
				var $AcceptButton = $container.find('.accept-button');

				$AcceptCheckbox.bind('change', function()
				{
					if ($(this).is(':checked'))
					{
						$AcceptDummy.hide();
						$AcceptButton.show();
					}
					else
					{
						$AcceptDummy.show();
						$AcceptButton.hide();
					}

				}).trigger('change');

				$container.find('.close-dialog').bind('click', function()
				{
					$container.dialog('close');
					return $(this).hasClass('accept-button');
					// return false;
				});
			}
		});

		return false;
	});
});

/**
 * rr001 Login Page should be global to all.
 */
function LoginPage(AccessURL)
{
	var $AccessURL = $('.AccessURL');
	$('.LoginContainer').dialog(
	{
		modal : true,
		height : '500',
		width : '500',
		open : function()
		{
			if (AccessURL != undefined)
			{
				$AccessURL.val(AccessURL);
			}
			else
			{
				$AccessURL.val('');
			}
		},
		close : function()
		{
			$AccessURL.val('');
		}
	});
} // LoginPage

/**
 * Login Login Logs in the user.
 */
function Login()
{
	var Username = $('.username').val();
	var Password = $('.password').val();
	var AccessURL = $('.AccessURL').val();

	$.ajax(
	{
		url : Core.Base() + 'Login',
		type : 'post',
		data : (
		{
			'option' : 'CheckLogin',
			'URL' : AccessURL,
			'Username' : Username,
			'Password' : Password
		}),
		success : function(data)
		{
			if (data == 'True')
			{
				if (AccessURL == '')
				{
					location.reload();
				}
				else
				{
					location.href = AccessURL;
					location.reload();
				}
			}
			else if (data == 'Access')
			{
				$('.LoginError').hide();
				$('.AccessError').show();
			}
			else
			{
				$('.LoginError').show();
				$('.AccessError').hide();
			}
		}
	});
}

/**
 * rr002 - Forgot Password
 */
function FGPWD()
{
	var Username = $('#resendpwdfield').val();
	$.ajax(
	{
		url : Core.Base() + 'resetpassword',
		type : 'post',
		data : (
		{
			'option' : 'reset',
			'username' : Username
		}),
		success : function(data)
		{
			if (data != 'true')
			{
				$('#submitresendpwd').show();
				$('#resendpwdtext').show();
				$('#resendpwdfield').show();
				$('#resendpwdmsg').html('Invalid Email: Please double check.');
			}
			else
			{
				$('#resendpwdmsg').html('Your password will be sent to your email shortly.');
			}

			// Reload the page.
			// location.reload();
		}
	});

}

/**
 * ClearText Shows default value of field.
 * 
 * @param field
 * @return void
 */
function ClearText(field)
{
	if (field.defaultValue == field.value)
	{
		field.value = '';
	}
	else if (field.value == '')
	{
		field.value = field.defaultValue;
	}
}

/**
 * Contact Us
 */
function ContactUs()
{
	var fdcaname = $('#fdca_company').val();
	var password = 'testing';
	alert('Name: ' + fdcaname);
	$.ajax(
	{
		url : Core.Base() + 'contactus',
		type : 'post',
		data : (
		{
			'option' : 'CheckLogin',
			'name' : fdcaname,
			'Password' : Password
		}),
		success : function(data)
		{
			if (data != 'True')
			{
				$('.LoginError').show();
				return;
			}

			// Reload the page.
			location.reload();
		}
	});
}

