/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                 //
//                                         ___           ___                                                       //
//                                        /__/\         /  /\         _____                                        //
//                                       _\_ \:\       /  /:/_       /  /::\                                       //
//                                      /__/\ \:\     /  /:/ /\     /  /:/\:\                                      //
//                                     _\_ \:\ \:\   /  /:/ /:/_   /  /:/~/::\                                     //
//                                    /__/\ \:\ \:\ /__/:/ /:/ /\ /__/:/ /:/\:|                                    //
//                                    \  \:\ \:\/:/ \  \:\/:/ /:/ \  \:\/:/~/:/                                    //
//                                     \  \:\ \::/   \  \::/ /:/   \  \::/ /:/                                     //
//                                      \  \:\/:/     \  \:\/:/     \  \:\/:/                                      //
//                                       \  \::/       \  \::/       \  \::/                                       //
//                                        \__\/         \__\/         \__\/                                        //
//        ___           ___                         ___                                   ___           ___        //
//       /  /\         /  /\                       /__/\          ___       ___          /  /\         /__/\       //
//      /  /:/_       /  /::\                      \  \:\        /  /\     /  /\        /  /::\        \  \:\      //
//     /  /:/ /\     /  /:/\:\    ___     ___       \  \:\      /  /:/    /  /:/       /  /:/\:\        \  \:\     //
//    /  /:/ /::\   /  /:/  \:\  /__/\   /  /\  ___  \  \:\    /  /:/    /__/::\      /  /:/  \:\   _____\__\:\    //
//   /__/:/ /:/\:\ /__/:/ \__\:\ \  \:\ /  /:/ /__/\  \__\:\  /  /::\    \__\/\:\__  /__/:/ \__\:\ /__/::::::::\   //
//   \  \:\/:/~/:/ \  \:\ /  /:/  \  \:\  /:/  \  \:\ /  /:/ /__/:/\:\      \  \:\/\ \  \:\ /  /:/ \  \:\~~\~~\/   //
//    \  \::/ /:/   \  \:\  /:/    \  \:\/:/    \  \:\  /:/  \__\/  \:\      \__\::/  \  \:\  /:/   \  \:\  ~~~    //
//     \__\/ /:/     \  \:\/:/      \  \::/      \  \:\/:/        \  \:\     /__/:/    \  \:\/:/     \  \:\        //
//       /__/:/       \  \::/        \__\/        \  \::/          \__\/     \__\/      \  \::/       \  \:\       //
//       \__\/         \__\/                       \__\/                                 \__\/         \__\/       //
//                           ___           ___           ___           ___           ___                           //
//                          /  /\         /__/\         /  /\         /  /\         /__/|                          //
//                         /  /:/_        \  \:\       /  /::\       /  /:/        |  |:|                          //
//                        /  /:/ /\        \__\:\     /  /:/\:\     /  /:/         |  |:|                          //
//                       /  /:/ /::\   ___ /  /::\   /  /:/~/::\   /  /:/  ___   __|  |:|                          //
//                      /__/:/ /:/\:\ /__/\  /:/\:\ /__/:/ /:/\:\ /__/:/  /  /\ /__/\_|:|____                      //
//                      \  \:\/:/~/:/ \  \:\/:/__\/ \  \:\/:/__\/ \  \:\ /  /:/ \  \:\/:::::/                      //
//                       \  \::/ /:/   \  \::/       \  \::/       \  \:\  /:/   \  \::/~~~~                       //
//                        \__\/ /:/     \  \:\        \  \:\        \  \:\/:/     \  \:\                           //
//                          /__/:/       \  \:\        \  \:\        \  \::/       \  \:\                          //
//                          \__\/         \__\/         \__\/         \__\/         \__\/                          //
//                                                                                                                 //
//                                                                                                                 //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                 //
//                                       W e b   S o l u t i o n   S h a c k                                       //
//                                                    Matt Rabe                                                    //
//                                                       '09                                                       //
//                                                                                                                 //
//                                             www.websolutionshack.com                                            //
//                                                                                                                 //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Initial Setup
////////////////////////////////////////////////////////////////////////////////////

// AJAX load current page ITIS
url = $(window).location.toString();
scriptname = url.split("/")[url.split("/").length - 1].split("#")[0].split(".")[0];
var loading = false;
var lastHash = '';
var hashobserver = null;
var contentdestroyed = [];
contentdestroyed['content'] = false;
contentdestroyed['subcontent'] = false;
var defaultLoadError = 'There was an error loading the requested page. Please try again.';
var ajaxaction = [];
var scripts = [];
var currentappcycle = '';

// Initialize AJAX Page loader
Event.observe(window, 'load', function()
{
	ajax_init();
});

// Initialize ajax_loadPageFromHash()
//ajax_loadPageFromHash();


// New AJAX method global vars
var service;
var view;
var nav;
var myBookListener;
var myBookPrimer;
var bookmark;
var ele;


////////////////////////////////////////////////////////////////////////////////////
// Core Functions
////////////////////////////////////////////////////////////////////////////////////

function ajax_init()
{
	// Top-level AJAX requests
	service = new TiteSiteService("content.php", "historyElement");
	view = new ViewComponent("content");
	service.addEventListener("newcontent", view.serviceHandle);

	myBookListener = new BookmarkListener();
	myBookPrimer = new BookmarkPrimer(service, window.location.toString());
	service.addEventListener("request", myBookListener.serviceHandle);

	view.addEventListener("afterChange", function(elem)
	{
		if ($('loading'))
		{
			$('loading').fade({duration: .25, from: 1, to: 0});
		}

		ajax_initAjaxLinks();
		
		currentpage = service.dto.contentName.replace('.php', '');

		// Mark current subnav as selected, ITIS
		if ($('subnav_'+currentpage))
		{
			subnavs = $$('.subnav a');
			for (i = 0; i < subnavs.length; i++)
			{
				if (subnavs[i].id != 'subnav_'+currentpage)
				{
					subnavs[i].removeClassName('selected');
				}
			}
			$('subnav_'+currentpage).addClassName('selected');
		}

		// Mark current subsubnav as selected, ITIS
		if ($('subsubnav_'+currentpage))
		{
			subsubnavs = $$('.subsubnav a');
			for (i = 0; i < subsubnavs.length; i++)
			{
				if (subsubnavs[i].id != 'subsubnav_'+currentpage)
				{
					subsubnavs[i].removeClassName('selected');
				}
			}
			$('subsubnav_'+currentpage).addClassName('selected');

			if ($('appcyclelinks'))
			{
				cyclelinks = $$('span#appcyclelinks a');
				for (i = 0; i < cyclelinks.length; i++)
				{
					// Update the CycleLink to reflect the current subsubpage
					re = new RegExp("viewprofile.[a-z]*");

					$(cyclelinks[i]).href = $(cyclelinks[i]).href.replace(re, currentpage)
				}
			}
		}
		
		// Update Link Popup, ITIS
		if ($('linkpopup_inp'))
		{
			// Remove Refname & Refuri from the querystring, ITIS
			re1 = new RegExp("&refname=[A-Za-z0-9% ]*");
			re2 = new RegExp("&refuri=[A-Za-z0-9%:\.\,\_ ]*");
			re3 = new RegExp("view=[A-Za-z0-9]*");

			$('linkpopup_inp').value = (parent.location.href.indexOf('view=') > -1 ? parent.location.href.replace(re3, 'view='+currentpage) : parent.location.href+'&view='+currentpage) + '&cycle=' + currentappcycle;
			$('linkpopup_inp').value = $('linkpopup_inp').value.replace(re1, '');
			$('linkpopup_inp').value = $('linkpopup_inp').value.replace(re2, '');

		}
	});

	myBookListener.addEventListener("refresh", function(hash)
	{
		// Update the linklink whenever we move to a different page
		if ($('linklink'))
		{
			elem = $("linklink");

			elem.onclick = function()
			{
				if ($('linkpopup_wrapper'))
				{
		
					$('linkpopup_wrapper').setStyle('display: block;');
				}
				
				return false;
			};
		}
	});
	// Set the initial linklink value (based on parent url)
	if ($('linklink'))
	{
		elem = $("linklink");

		currentpage = parent.location;

		// Store current URL in linklink popup
		elem.setAttribute("href", currentpage);

		if ($('linkpopup_inp'))
		{
			// Remove Refname & Refuri from the querystring, ITIS
			re1 = new RegExp("&refname=[A-Za-z0-9% ]*");
			re2 = new RegExp("&refuri=[A-Za-z0-9%:\.\,\_ ]*");

			$('linkpopup_inp').value = currentpage;
			$('linkpopup_inp').value = $('linkpopup_inp').value.replace(re1, '');
			$('linkpopup_inp').value = $('linkpopup_inp').value.replace(re2, '');
		}

		elem.onclick = function()
		{
			if ($('linkpopup_wrapper'))
			{
				$('linkpopup_wrapper').setStyle('display: block;');
			}

			return false;
		};

		if ($('linklink_wrapper'))
		{
			$('linklink_wrapper').setStyle('display: inline;');
		}
	}

	ajax_initAjaxLinks();
}

function ajax_initAjaxLinks()
{
	// Add parent to subsubnav links, ITIS
	if ($$('.subnav a.ajax').length > 0)
	{
		parentname = $$('.subnav a.ajax')[0].href.split('?view=')[1].split('.')[0] + '.';
		subsubnavs = $$('.subsubnav a.ajax');
		for (i = 0; i < subsubnavs.length; i++)
		{
			if (subsubnavs[i].href.indexOf('view=' + parentname) < 0)
			{
				subsubnavs[i].href = subsubnavs[i].href.replace('view=', 'view=' + parentname);
			}
		}
	}

	ajaxlinks = $$('a.ajax');
	for (i = 0; i < ajaxlinks.length; i++)
	{
		$(ajaxlinks[i]).stopObserving('click');

		ajaxlinks[i].onclick = function() { return false; };

		Event.observe($(ajaxlinks[i]), 'click', function()
		{
			if ($(this).href.split('?view=').length > 0)
			{
				request = $(this).href.split('?view=')[1].split('&')[0] + '.php';
				parts = $(this).href.split('?view=')[1].split('&');
				for (i = 1; i < parts.length; i++)
				{
					request = request + '&' + parts[i];
				}
			}else{
				request = $(this).href;
			}

			ajax_loadPage(request, true);
		});
	}

	// Add onclick event for App Cycle Links, ITIS (View Profile Header)
	cyclelinks = $$('span#appcyclelinks a');
	for (i = 0; i < cyclelinks.length; i++)
	{
		Event.observe($(cyclelinks[i]), 'click', function()
		{
			id = $(this).id.replace('cyclelink_', '');

			cyclelinks = $$('span#appcyclelinks a');
			for (i = 0; i < cyclelinks.length; i++)
			{
				if (cyclelinks[i].id != id)
				{
					cyclelinks[i].removeClassName('disabled');
				}
			}
			$('cyclelink_'+id).addClassName('disabled');

			// Update the Applications and Demographics subsubnav links to reflect the current App Cycle ID
			re = new RegExp("&cycle=[0-9]*");
			
			$('subsubnav_viewprofile.applications').href = $('subsubnav_viewprofile.applications').href.replace(re, '&cycle='+$(this).href.split('&cycle=')[1])
			$('subsubnav_viewprofile.demographics').href = $('subsubnav_viewprofile.demographics').href.replace(re, '&cycle='+$(this).href.split('&cycle=')[1])
		
			currentappcycle = $(this).href.split('&cycle=')[1];
		});
	}
}

function ajax_loadPage(request, reloadads)
{
	reloadads = (reloadads == false ? false : true);

	if (!loading)
	{
		// Show loading indicator
		if ($('loading'))
		{
			$('loading').appear({duration: .75});
		}

		// Hide the ajax_error div
		if ($('ajax_error')) $('ajax_error').hide();

		if (request.indexOf('viewprofile') > -1 && request != 'myprofile.viewprofile.php')
		{
			var dto = { containerid : 'subcontent', contentName : request.replace('myprofile.', '') };
			service.retrieveContent(dto);
		}else{
			var dto = { containerid : 'content', contentName : request };
			service.retrieveContent(dto);
		}
	}
}

function ajax_showError(error, fadeout)
{
	error = (error != null && error.replace(/^\s+|\s+$/g,"") != '' ? error : defaultLoadError);
	fadeout = (fadeout == true ? true : false);
	
	if ($$('#ajax_error p').length > 0)
	{
		$$('#ajax_error p')[0].innerHTML = error;
	}

	// Hide all response divs
	ajax_hideAllResponses();
	
	// Show the Div
	if ($('ajax_error'))
	{
		$('ajax_error').show();
	}

	// Hide the loading indicator
	if ($('loading'))
	{
		$('loading').fade({duration: .25, from: 1, to: 0});

		if (fadeout) window.setTimeout('$(\'ajax_error\').fade({duration: 1, from: 1, to: 0});', 5000);
	}
	
	if ($('ajax_messages').viewportOffset().slice(',')[1] <= -45) $('ajax_messages').scrollTo();
}

function ajax_showSuccess(success, fadeout)
{
	success = (success != null && success.replace(/^\s+|\s+$/g,"") != '' ? success : '');
	fadeout = (fadeout == false ? false : true);
	
	if ($$('#ajax_success p').length > 0)
	{
		$$('#ajax_success p')[0].innerHTML = success;
	}

	// Hide all response divs
	ajax_hideAllResponses();

	// Show the Div
	if ($('ajax_success'))
	{
		$('ajax_success').show();

		if (fadeout) window.setTimeout('$(\'ajax_success\').fade({duration: 1, from: 1, to: 0});', 5000);
	}

	if ($('ajax_messages').viewportOffset().slice(',')[1] <= -45) $('ajax_messages').scrollTo();
}

function ajax_showNotice(notice, fadeout)
{
	notice = (notice != null && notice.replace(/^\s+|\s+$/g,"") != '' ? notice : '');
	fadeout = (fadeout == false ? false : true);
	
	if ($$('#ajax_notice p').length > 0)
	{
		$$('#ajax_notice p')[0].innerHTML = notice;
	}

	// Hide all response divs
	ajax_hideAllResponses();

	// Show the Div
	if ($('ajax_notice'))
	{
		$('ajax_notice').show();

		if (fadeout) window.setTimeout('$(\'ajax_notice\').fade({duration: 1, from: 1, to: 0});', 5000);
	}

	if ($('ajax_notice').viewportOffset().slice(',')[1] <= -20) $('ajax_messages').scrollTo();
}

function ajax_hideAllResponses()
{
	// Hide/remove all response divs
	if ($('ajax_error')) $('ajax_error').hide();
	if ($('ajax_success')) $('ajax_success').hide();
	if ($('ajax_notice')) $('ajax_notice').hide();
	responsedivs = $$('div.response');
	for (i = 0; i < responsedivs.length; i++)
	{
		responsedivs[i].remove();
	}
}

