$(document).ready(function() {
	SPSSW.Ready();
});

$(window).load(function () {
	SPSSW.Loaded();
});


var SPSSW = {
	siteOpenDelay: 300, 	//Delay in milliseconds before the site billboards open on hover.

	//Caled when everything is done loading.
	Loaded: function () {
		SPSSW.SetupNews();
	},

	//Called when the DOM is ready.
	Ready: function () {
		//Show the "excellence for everyone" photo when on the homepage.
		if (location.href.indexOf('SearchString=') == -1) {
			var taglinePhoto = $('#sps_footer_tagline_photo span');
			if (taglinePhoto != null && taglinePhoto.length > 0) {
				taglinePhoto.css('display', 'block');
			}
		}

		SPSSW.SetupPageTitle();
		SPSSW.SetupSchoolNews();
		SPSSW.SetupContact();
		SPSSW.SetupSites();

		//
		//Signin Page
		//
		var signInUser = document.getElementById('swsignin-txt-username');
		if (signInUser != null) {
			signInUser.focus();
		}

		var forgotPassword = $('a[href^="http://www.spokaneschools.org/site/Default.aspx?PageType=9"]');
		if (forgotPassword.length > 0) {
			forgotPassword.attr('href', 'https://www2.spokaneschools.org/Account/');
		}

		//Setup the photo scrolling.
		PhotoScroll.Load();

		//Setup the search box.
		var searchBox = $('#sps_channel_searchbox');
		searchBox.focus(SPSSW.SearchFocus);
		searchBox.keyup(SPSSW.SearchKeyup);

		//Prevent links from opening a new tab.
		$('a[target="_blank"]').attr('target', '');
	},

	//Load the page title, on a subpage.
	SetupPageTitle: function () {
		var pageTitle = document.getElementById('sps_content_pagetitle');
		var printTitle = document.getElementById('sps_header_print_title');

		if (pageTitle == null) {
			//If we are on a directory page, fill in the print title.
			var dirTitle = $('.sw-directory-title');
			
			if (dirTitle.length > 0 && printTitle != null) {
				printTitle.innerHTML = dirTitle.text();
				return;
			}
		}

		if (pageTitle != null && printTitle != null) {
			//Don't touch the page title div if this is a custom application.
			var siteID = document.getElementById('sps_siteid');
			if (siteID != null && siteID.innerHTML == "custom") {
				return;
			}

			//Don't display the page title on a staff directory page.
			var staffDirectoryExists = (document.getElementById('ctl00_PageContent_searchResults') != null);
			if (staffDirectoryExists) {
				pageTitle.style.display = 'none';
				return;
			}

			/*
			Four ways to identify the current page:
				url:		http://www.spokaneschools.org/[sitename]
				url:		http://www.spokaneschools.org/Page/[pageID]
				url:		http://www.spokaneschools.org/domain/[domainID]
				form field:	hid-pageid
			*/
			var pageID = document.getElementById('hid-pageid');

			if (pageID != null) {
				if (pageID.value == "0") {
					//If we are viewing the default section page, get it's ID.
					if (location.href.toLowerCase().indexOf('/domain/') != -1) {
						var domainID = location.href.substring(location.href.lastIndexOf('/') + 1);

						SPSTools.Call("Content.aspx", "Title", { did: domainID }, function (data) {
							pageTitle.innerHTML = data;
							printTitle.innerHTML = data;
						});
					}

					return;
				}
				else {
					SPSTools.Call("Content.aspx", "Title", { pid: pageID.value }, function (data) {
						pageTitle.innerHTML = data;
						printTitle.innerHTML = data;
					});

					return;
				}
			}

			pageTitle.style.display = 'none';
		}
	},

	//Setup the school contact list.
	SetupContact: function () {
		var contactsDiv = document.getElementById('sps_content_contacts');

		if (contactsDiv != null) {
			var site = $('#sps_sitename').text();
			var numRand = Math.floor(Math.random() * 10001);

			$.ajax({
				'type': 'GET',
				'data': { sn: site, r: numRand },
				'url': '/StaffDirectory/Contact.aspx',
				'dataType': 'text',
				'success': function (data) {
					contactsDiv.innerHTML = data;
					Contact.Security();
				},
				'error': function (http, status, error) { }
			});
		}
	},

	SetupSchoolNews: function () {
		var schoolNewsDiv = document.getElementById('sps_content_districtnews');

		if (schoolNewsDiv != null) {
			SPSTools.Call("Content.aspx", "NewsForSchools", {}, function (data) {
				if (data != "") {
					schoolNewsDiv.innerHTML = data;
					schoolNewsDiv.style.display = 'block';
				}
			});
		}
	},

	//Detects if there is too much content in the Welcome/News section next to the scrolling pictures and 
	//adds a "More" link to expand that section to show all the contents.
	SetupNews: function () {
		var topNews = $('#sps_content_top_news');

		if (topNews == null || topNews.length == 0) {
			return;
		}

		var topNewsDiv = $('#sps_content_top_news > div.region');
		var contentH = topNewsDiv.height();
		var viewportH = topNews.height();
		var clicked = false;

		if (contentH > viewportH) {
			var more = $('<div class="content_more"></div>').appendTo(topNews);

			more.click(function () {
				if (!clicked) {
					$('<div class="content_less"></div>').appendTo(topNewsDiv).click(function () {
						topNews.css('position', 'relative');
						topNewsDiv.removeClass('content_expand');
						more.show();
					});
				}

				more.hide();
				topNews.css('position', 'static');
				topNewsDiv.addClass('content_expand');
				clicked = true;
			});
		}
	},

	siteLinks: null,
	siteName: '',

	//Setup the site billboards.
	SetupSites: function () {
		SPSSW.siteName = $('#sps_sitename').text();
		SPSSW.siteLinks = $('#sps_header_sites_list a');

		//Set the hilite on the current site, then remove the temporary styles.
		SPSSW.SiteHilite(SPSSW.siteName);
		$('#sps_header_sites_' + SPSSW.siteName).css('background', '').css('color', '');

		//Pre-load the images.
		SPSSW.ImagePreload();

		//Setup the subsite links hover for the billboard display.
		SPSSW.siteLinks.hover(
			function () {
				var hoverSite = this.innerHTML.toLowerCase();
				hoverSite = (hoverSite == 'home' ? 'sps' : hoverSite);
				SPSSW.SiteHilite(hoverSite);

				if (hoverSite != SPSSW.siteName)
					SPSSW.SiteOpen(hoverSite);
				else
					SPSSW.SiteCloseNow();
			},
			function () { SPSSW.SiteClose(100); }
		);

		//Setup the hover on the billboard itself, to prevent premature closure.
		$('#sps_header_sites_billboard').hover(
			function () { clearTimeout(SPSSW.siteCloseTimer); },
			function () { SPSSW.SiteCloseNow(); }
		);

		//Close billboard if mouse enters another section (for cases when the hover above fails to work).
		$('#sps_content_bottom,#sps_header_links').mouseenter(function () { SPSSW.SiteCloseNow(); });
	},

	ImagePreload: function () {
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/billboard_sps.jpg';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/billboard_parents.jpg';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/billboard_students.jpg';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/billboard_community.jpg';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/billboard_staff.jpg';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/header_sites_hover.gif';
		$('<img/>')[0].src = '/SchoolwiresFiles/Images/header_sites_hoverlite.gif';
	},

	siteHoverCache: null,

	SiteOpen: function (hoverSite) {
		//Clear previous attempts to close/open.
		clearTimeout(SPSSW.siteCloseTimer);
		clearTimeout(SPSSW.siteOpenTimer);

		this.siteHoverCache = null;

		//Pre-load the data.
		SPSTools.Call('Content.aspx', 'Billboard', { 'site': hoverSite },
			function (data) {
				SPSSW.siteHoverCache = data;
			}
		);

		//Add a delay to avoid premature opening.
		SPSSW.siteOpenTimer = setTimeout(function () { SPSSW.SiteLoad(); }, SPSSW.siteOpenDelay);
	},

	SiteLoad: function () {
		//Loop until the request to the server for the data has completed.
		if (this.siteHoverCache == null) {
			setTimeout(function () { SPSSW.SiteLoad(); }, 100);
		}

		$('#sps_header_sites_billboard_content').html(this.siteHoverCache);
		$('#sps_header_sites_billboard').show();
		$('#sps_whitespace').animate({ backgroundColor: '#F2F2F2' }, 300);
	},

	SiteClose: function (delay) {
		//Add a delay to avoid premature closing.
		SPSSW.siteCloseTimer = setTimeout(function () { SPSSW.SiteCloseNow(); }, delay);
	},

	SiteCloseNow: function () {
		clearTimeout(SPSSW.siteOpenTimer);
		clearTimeout(SPSSW.siteCloseTimer);
		SPSSW.SiteHide();
		SPSSW.SiteHilite(SPSSW.siteName);
	},

	SiteHide: function () {
		$('#sps_whitespace').animate({ backgroundColor: '#FFFFFF' }, 50);
		$('#sps_header_sites_billboard').hide(); //.html('');
	},

	SiteHilite: function (selectedSiteName) {
		SPSSW.siteLinks.each(function () {
			var site = this.innerHTML.toLowerCase();
			site = (site == 'home' ? 'sps' : site);

			if (site == SPSSW.siteName) {
				if (selectedSiteName == site) {
					if (site == 'sps')
						SPSSW.SiteHide();

					this.className = 'sps_header_sites_list_a_selected';
				}
				else
					this.className = 'sps_header_sites_list_a_hoverlite';
			}
			else if (site == selectedSiteName) {
				this.className = 'sps_header_sites_list_a_hover';
			}
			else {
				this.className = '';
			}
		});
	},

	Search: function () {
		var searchFor = $('#sps_channel_searchbox').val();

		if (searchFor.length == 0) {
			alert('Please enter something to search for.');
			return;
		}

		window.location.href = "http://www.spokaneschools.org/site/Default.aspx?PageType=6&SiteID=1&SearchString=" + searchFor;
	},

	SearchFocus: function () {
		if (this.value == 'SEARCH') {
			this.value = '';
		}
	},

	SearchKeyup: function (event) {
		if (event.keyCode == '13') {
			event.preventDefault();
			SPSSW.Search();
		}
	},

	SelectLanguage: function () {

	}
}

var SPSTools = {
	//Example:  Call('Stuff.aspx', 'edit', {id:90, text:'howdy'}, function() { alert('success!'); })
	Call: function (page, mode, ajaxParams, OnSuccess) {
		ajaxParams.m = mode;
		
		$.ajax({
			type: "POST",
			url: "/Schoolwires/" + page,
			data: ajaxParams,
			dataType: "text",
			success: OnSuccess,
			error: function (http, status, error) { }
		});
	}
}


//Google Analytics Tracking Code
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-9687036-1']);
_gaq.push(['_setDomainName', 'spokaneschools.org']);
_gaq.push(['_trackPageview']);

(function () {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

