﻿
var anchors = document.getElementsByTagName('a');
var pageIsInEditMode = false;
	window.onresize = function () {
		FixWorkspaceHeight();
	};
function toggleDiv(div, img) {
    var a = document.getElementById(div);
    if (a.style.display == "none") {
        a.style.display = "block";
        document.getElementById(img).src = "/PublishingImages/minus.png";
    }
    else {
        a.style.display = "none";
        document.getElementById(img).src = "/PublishingImages/plus.png";
    }
}

function IsExternalSite(site)
{
		//if (site=="mycti.cti.depaul.edu" || site == "prerelease.cti.depaul.edu" || site == "clinton.cs.depaul.edu" || site == "securestore.cti.depaul.edu" || site == "authenticate.cti.depaul.edu")
		//	{return true;}
		return false;
}

function IsExternalSiteNoIcon(site)
{
		if (site == "blogs.cti.depaul.edu")
			{return true;}
}

//clean way of disabling the name.dll activex control
function ProcessImn() {}

function ExternalLink(event)
{
	var targ;
	if (!e)
	  {
	  var e=window.event;
	  }
	if (e.target)
	  {
	  targ=e.target;
	  }
	else if (e.srcElement)
	  {
	  targ=e.srcElement;
	  }
	if (targ.nodeType==3) // defeat Safari bug
	  {
	  targ = targ.parentNode;
	  }
	if (IsExternalSite(targ.hostname))
	{
		targ.target = '_blank';
	}
}

function CTIHacks()
{
	FixSearchBar();
	FixWorkspaceHeight();
	CheckRelatedLinks();
	CheckSidebar();
	removeStylesFromANames();
	ChangeClassName();
	GetCDMExtendedCourseInfo();
	ToggleCourseList();
	ToggleSection();
	ToggleLSSection();
	GetLegendInfo();
	/*Temp Hack
	$('.requirementTitle').append(' 2009-2010');*/
	ToggleTechnicalReportsList();
	/*$('body').supersleight({shim: '/PublishingImages/x.gif'});*/
	GetLabAvailability();
	$('#slider').nivoSlider();

	
}
function FixWorkspaceHeight()
{
	if (isProd != null && isProd !=true)
		$('#s4-workspaceCDM').height($(window).height() - $('#s4-ribbonrow').height());
}
function GetLabAvailability()
{
	$(".CDMLabStatus").each(
		function(i)
		{
			var labName = $(this).text();
			if (labName !="NONE")
			{
				var url="/_layouts/CDM/LabAvailability.aspx?LabName=" + labName;
				getLabAvailability(url, this);			
			}
			else
			{
				getLabAvailability("NONE", this);
			}
			//alert(url);
		});

}

function getLabAvailability(url,ref)
{
	    var parent = $(ref).parent();
	
		if(url=="NONE")
		{
			$(parent).append("<img src='/PublishingImages/lab-gry.png' height='18' width='18' alt='No data for this lab'> Status unvailable");
		}
		else
		{
					$.get(url, function(data){
							var child = $(data).children(0);
							var total = $(child).attr("Total");
							var available = $(child).attr("Available");
							var percentage = 0;
							var percentWhole =0;
							if (available ==0)
							{
								$(parent).append("<img src='/PublishingImages/lab-red.png' height='18' width='18' alt='No seats free'> No Seats");
							}
							else
							{
								percentage = available/total;
								percentWhole = parseInt(percentage*100);
								if(percentage >= .5)
								{
									$(parent).append("<img src='/PublishingImages/lab-grn.png' height='18' width='19' alt='Over 50% of seats are free'> " + available + "/" + total  +" seats open");
								}
								else if(percentage < .5 && percentage > .25)
								{
									$(parent).append("<img src='/PublishingImages/lab-ylo.png' height='18' width='18' alt='Between 25% and 50% of seats are free'> "  + available + "/" + total  +" seats open");
								
								}
								else 
								{
									$(parent).append("<img src='/PublishingImages/lab-red.png' height='18' width='18' alt='Less than 25% of seats are free'> "  + available + "/" + total  +" seats open");
								}
				
							}
				 		});
 		}
}


function FixSearchBar()
{
	var sb = document.getElementById('ctl00_SearchBox_S6F789EBA_InputKeywords');
	if(sb!=null)
	{
					sb.value = 'Search...';
					sb.onfocus = function () {
						sb.value = "";
					};
	}
}

function CheckRelatedLinks()
{
	var rl = document.getElementById('CTISidebarRelatedLinksContent');
	if (rl != null)
	{
		var tmp = rl.innerHTML;
		tmp.replace(/<[^>]*>/,'');
		if (rl.innerHTML == "" || rl.innerHTML == null || rl.innerHTML.length == 2 || tmp.length == 0)
		{
			document.getElementById('CTISidebarRelatedLinksContainer').style.display = 'none';
		}
	}
}
function CheckSidebar()
{
	var tmp = $("#CTISidebarContent").text();
	tmp.replace(/<[^>]*>/,'');
	//tmp.replace(/\s+/,'');
	var tmp2 = $("#CTISidebarTitle").text();
	tmp2.replace(/<[^>]*>/,'');
	//tmp2.replace(/\s+/,'');
	if ($("#CTISidebarTitle").text().length <= 3 || $("#SidebarContent").text().length <= 3 || tmp.length < 1 || tmp2.length < 1)
	{
		$("#CTISidebarTitle").hide();
		$("#SidebarContent").hide();
	}
}
function DetectEditMode()
{
}

function getMaxDivHeight()
{

	try
	{
		var rightHeight = document.getElementById('ctl00_PageRightColumContainer').offsetHeight;
		var mainHeight = document.getElementById('ctl00_PageBody').offsetHeight;
		if (rightHeight > mainHeight)
		{
			var diff = rightHeight-mainHeight + 120;
			document.getElementById('ctl00_PageFooter').style.paddingTop = diff + 'px';
			
		}
		else if ((mainHeight > rightHeight) && (pageIsInEditMode == false) && (mainHeight < 1200))
		{
			document.getElementById('ctl00_PageRightColumn').style.height = mainHeight - 10 + 'px';
		}
	}
	catch (err) {}
}
			
function removeStylesFromANames()
{
	var anchors = document.getElementsByTagName('a');
	var tmp = '';
	for (var i = 0; i < anchors.length; i++)
	{
		if (anchors[i].href == '')
		{
			anchors[i].style.color = 'black';
			anchors[i].style.textDecoration = 'none';
		}
	}
}

function ChangeClassName()
{
	for (i = 0; i < anchors.length; i++)
	{
		if(anchors[i].href != 'https://mycti.cti.depaul.edu/cti/advising/login.asp')
		{
			if (IsExternalSite(anchors[i].hostname))
			{
				anchors[i].className = 'external';
				anchors[i].target = '_blank';
			}
			if (IsExternalSiteNoIcon(anchors[i].hostname))
			{
				anchors[i].target= '_blank';
			}
		}
	}
}

/*
function GetCDMExtendedCourseInfo()
{
	$(".CDMExtendedCourseInfo").each(
		function(i)
		{
			$(this).replaceWith(test(this));
		});
}

function test(i)
{
	var retval = this;

	$.get("/legacy/GetCDMCourseInfoProxy.aspx", function(data){
 		 return data;
		});

	//alert($(i).html());
	//return data;	
}
*/
function toggleDivNoImageHook() {
$(".CDMProgramLinks").parent().children('div').hide();
$(".CDMProgramLinks").prepend('<img src = "/PublishingImages/plus.png" border="0" /> ');
$(".CDMProgramLinks").each(
		function(i)
		{
 		 	$(this).click(function(event){
 		 	event.preventDefault();
 		 	//toggleDivNoImage($(this).text());
 		 	$(this).next('div').toggle();

 			 	}
 			);
			}
		);
}
function togglePlusMinus(icon)
{
	if (icon.src)
	{
		if (icon.src == "/PublishingImages/plus.png")
			return '<img src = "/PublishingImages/minus.png" /> ';
		else
			return '<img src = "/PublishingImages/plus.png" /> ';
	}
	else
		return '<img src = "/PublishingImages/plus.png" /> ';
}
function toggleDivNoImage(div)
{
    var a = document.getElementById(div);
    if (a.style.display == "none") {
        a.style.display = "block";
    }
    else {
        a.style.display = "none";
    }

}

function GetCDMExtendedCourseInfo()
{
	var courseArray = {};
	var uriArray = new Array();
	var serviceUri = "/odata/";
	var courseInfoUri = serviceUri + "Courses?$select=CourseTitleLong,SubjectId,CatalogNbr,IsInClassOnly,IsInClassAndOnline,IsOnlineOnly,IsNotOffered&$filter=EffStatus eq 'A' and ";
	var count = 0;
	var courseInfoUriQuery = '';
	$(".CDMExtendedCourseInfo").each(
		function(i)
		{
			var val = $(this).text();
			var vals = val.split(' ');
			var subjectId = vals[0];
			var catalogNbr = vals[1];
			$(this).addClass(subjectId + catalogNbr);
			if (courseArray[subjectId + ' ' + catalogNbr] != 1)
			{
				if (count % 25 != 0 || count == 0)
				{
					if (courseInfoUriQuery != '')
						courseInfoUriQuery += ' or ';
					courseInfoUriQuery += "(SubjectId eq '" + subjectId + "' and CatalogNbr eq '" + catalogNbr + "')";
				}
				else
				{
					if (courseInfoUriQuery != '')
						courseInfoUriQuery += ' or ';
					courseInfoUriQuery += "(SubjectId eq '" + subjectId + "' and CatalogNbr eq '" + catalogNbr + "')";
					uriArray.push(courseInfoUriQuery);
					courseInfoUriQuery = '';
				}
				count++;
			}
			courseArray[subjectId + ' ' + catalogNbr] = 1;
		});
		if (courseInfoUriQuery != '')
			uriArray.push(courseInfoUriQuery);
		for (var q in uriArray)
		{
			OData.read(courseInfoUri + uriArray[q], function (data, request) {
						for (var r = 0; r < data.results.length; r++)
						{
							var currentSubjectId = data.results[r].SubjectId;
							var currentCatalogNbr = data.results[r].CatalogNbr;
							var ref = $('.' + currentSubjectId + currentCatalogNbr);
							var imgUrl = '';
							if (data.results[r].IsInClassOnly)
								imgUrl = '/academics/PublishingImages/iconOffered.gif';
							else if (data.results[r].IsInClassAndOnline)
								imgUrl = '/academics/PublishingImages/iconOfferedOnline.gif';
							else if (data.results[r].IsOnlineOnly)
								imgUrl = '/academics/PublishingImages/iconOfferedOnlineOnly.gif';
							else if (data.results[r].IsNotOffered)
								imgUrl = '/academics/PublishingImages/iconNotOffered.gif';	
							else
								imgUrl = '/academics/PublishingImages/COLiconSpacer.gif';
							$(ref).empty();
							var link = '<img src="' + imgUrl + '" /> <a href="#">' + currentSubjectId  + ' ' + currentCatalogNbr + '</a> ' + data.results[r].CourseTitleLong;
							$(ref).append(link);
							$('.' + currentSubjectId + currentCatalogNbr + ' a').click(function () {
								var thisSubjectId = $(this).text().split(' ')[0];
								var thisCatalogNbr = $(this).text().split(' ')[1];
								var courseInfoDetailUri = serviceUri + "Courses?$filter=EffStatus eq 'A' and SubjectId eq '" + thisSubjectId + "' and CatalogNbr eq '" + thisCatalogNbr + "'";
								var scheduleUri = serviceUri + "ClassMeetings?$filter=SubjectId eq '" + thisSubjectId + "' and CatalogNbr eq '" + thisCatalogNbr + "'";
								if (typeof(termOverride) != "undefined")
									scheduleUri += " and TermId eq '" + termOverride + "'";
								else
									scheduleUri += ' and StrmRank eq 0';
								OData.read(courseInfoDetailUri, function (data, request) {
									OData.read(scheduleUri, function (scheduleData, scheduleRequest) {
										var scheduleBlurb;
										if (!scheduleData || scheduleData.results.length < 1)
										{
											scheduleBlurb = '<p><b>This class is not being offered this quarter.</b></p>';
										}
										else
										{
											scheduleBlurb =  '<p><b>Schedule for ' + scheduleData.results[0].QuarterLongName + '</b></p>';
											for (var i = 0; i < scheduleData.results.length; i++)
											{
												scheduleBlurb += '<p>Section: <b>' + scheduleData.results[i].ClassSection + '</b> ID: <b>' + scheduleData.results[i].ClassNbr + '</b> Day: <b>' + scheduleData.results[i].ClassDays + '</b> Time: <b>' + scheduleData.results[i].ClassStartTime + ' - ' + scheduleData.results[i].ClassEndTime + '</b>';
												var facultyInfo;
												if (scheduleData.results[i].OriginalFacultyId != 0)
													facultyInfo = '<a href="/people/pages/facultyinfo.aspx?fid=' + scheduleData.results[i].OriginalFacultyId + '">' + scheduleData.results[i].FacultyName + '</a>';
												else
													facultyInfo = scheduleData.results[i].FacultyName;
												scheduleBlurb += '<div>Instructor: ' + facultyInfo + ' Room: ' + scheduleData.results[i].Room;
												if (scheduleData.results[i].OriginalFacultyId != 0)
													scheduleBlurb += ' <a href="/academics/pages/classinfo.aspx?Term=' + scheduleData.results[i].TermId + '&ClassNbr=' + scheduleData.results[i].ClassNbr + '&fid=' + scheduleData.results[i].FacultyId + '">Syllabus</a>';
												scheduleBlurb += '</p>';
											}
										}
										$(".simple_popup_div").remove();
							            var strSimple = "<div class='simple_popup_div'><div class='simple_popup_inner'>"
							            strSimple += '<p id="simp_close_x" align="right" class="simple_close"><a href="#">X</a></p><b><a href="/academics/pages/courseinfo.aspx?Subject=' + data.results[0].SubjectId + '&CatalogNbr=' + data.results[0].CatalogNbr + '">' + data.results[0].SubjectId + ' ' + data.results[0].CatalogNbr + '</a> ' + data.results[0].CourseTitleLong + '</b>';
							            strSimple += '<p>' + data.results[0].DescrLong + scheduleBlurb + '</p>'
							            strSimple += "<p align='center' class='simple_close'><a href='#'>CLOSE</a></p></div></div>";
							            $("body").append(strSimple);
							            viewport.init(".simple_popup_div");
							            $(".simple_close").click(function(){
							                $(".simple_popup_div").remove();
							                return false;
			            				});
									});
								});
								return false;
							});
						}
					});
		}
}


/*
	Code Sample Taken from 
        3.) Simply Centered Informational DIV Popup
    */

    /*
        The viewport object is mainly for the cross-browser mess
        that is unfortunately necessary to get a DIV to center.

        There is also an officially supported plugin called "Dimensions"
        that can manage some of this on your own projects. Check it out at:

        http://jquery.com/plugins/project/dimensions
    */

    var viewport = {
        o: function() {
            if (self.innerHeight) {
    			this.pageYOffset = self.pageYOffset;
    			this.pageXOffset = self.pageXOffset;
    			this.innerHeight = self.innerHeight;
    			this.innerWidth = self.innerWidth;
    		} else if (document.documentElement && document.documentElement.clientHeight) {
    			this.pageYOffset = document.documentElement.scrollTop;
    			this.pageXOffset = document.documentElement.scrollLeft;
    			this.innerHeight = document.documentElement.clientHeight;
    			this.innerWidth = document.documentElement.clientWidth;
    		} else if (document.body) {
    			this.pageYOffset = document.body.scrollTop;
    			this.pageXOffset = document.body.scrollLeft;
    			this.innerHeight = document.body.clientHeight;
    			this.innerWidth = document.body.clientWidth;
    		}
    		return this;
        },
        init: function(el) {
            $(el).css("left",Math.round(viewport.o().innerWidth/2) + viewport.o().pageXOffset - Math.round($(el).width()/2));
            $(el).css("top",Math.round(viewport.o().innerHeight/2) + viewport.o().pageYOffset - Math.round($(el).height()/2));
        }
    };
function GetLegendInfo()
{
	$(".CourseLegend").each(
		function(i)
		{
			getCurrentTermForLegend(this);			
		});
}

function getCurrentTermForLegend(ref)
{
	var url ='';
	if (typeof(termOverride) != "undefined")
		url = "/odata/Quarters?$filter=TermId eq '" + termOverride + "'";
	else
		url = '/odata/Quarters?$filter=StrmRank eq 0 and StrmSubRank eq 0';
	OData.read(url, function (data, request) {
		var kids = $(ref).children();
 		 	$(kids[0]).append("Displaying " + data.results[0].QuarterLongName + " Course Availability" );
	});
}


function ToggleCourseList()
{
	$(".collapsedCourseList").children("li").each(
		function(i)
		{
			var a = $(this).children();
			for (var z = 0; z<a.length; z++)
			{
				$(a[z]).hide();
			}
			$(this).click(function()
			{
				
				var b = $(this).children();
				if ($(b[0]).css("display") == "none")
					$(this).css({"list-style-image" : "url('/PublishingImages/minus.png')"});
				else
					$(this).css({"list-style-image" : "url('/PublishingImages/plus.png')"});
				for (var z = 0; z<b.length; z++)
				{
					$(b[z]).toggle();
				}
				return false;
			});
		});
}
function ToggleSection()
{
	$(".collapsedSection").children("li").each(
		function(i)
		{
			var a = $(this).children();
			for (var z = 0; z<a.length; z++)
			{
				$(a[z]).hide();
			}
			$(this).click(function()
			{
				
				var b = $(this).children();
				if ($(b[0]).css("display") == "none")
					$(this).css({"list-style-image" : "url('/PublishingImages/minus.png')"});
				else
					$(this).css({"list-style-image" : "url('/PublishingImages/plus.png')"});
				for (var z = 0; z<b.length; z++)
				{
					$(b[z]).toggle();
				}
				return false;
			});
		});
}

function ToggleLSSection()
{
	$(".collapsedLSGroup").each(
		function(i)
		{
			var a = $(this).children();
			for (var z = 0; z<a.length; z++)
			{
				$(a[z]).hide();
			}
			$(this).click(function()
			{
				var b = $(this).children();
				if ($(b[0]).css("display") == "none")
					$(this).css({"list-style-image" : "url('/PublishingImages/minus.png')"});
				else
					$(this).css({"list-style-image" : "url('/PublishingImages/plus.png')"});
				for (var z = 0; z<b.length; z++)
				{
					$(b[z]).toggle();
				}
				return false;
			});
		});
}
//used for /SoC/research/Pages/TechnicalReports.aspx
function ToggleTechnicalReportsList()
{
	$(".collapsedTechReportList").children('li').each(
		function(i)
		{
			var a = $(this).children('table');
			for (var z = 0; z<a.length; z++)
			{
				$(a[z]).hide();
			}
			$(this).children('span').each(
			function()
			{
				$(this).click(function()
				{
				var b = $(this).siblings('table');
				if ($(b[0]).css("display") == "none")
					$(this).css({"background-image" : "url('/PublishingImages/minus.png')"});
				else
					$(this).css({"background-image" : "url('/PublishingImages/plus.png')"});
				for (var z = 0; z<b.length; z++)
				{
					$(b[z]).slideToggle();
				}

				});
			});
			$(this).click(function()
			{
			});

		});
}
function GetOdataFeed(serviceUrl, callback)
{
	$.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: serviceUrl,
            dataType: "json",
            success: callback
        })
}
function CheckSidebar()
{
	var tmp = $("#CTISidebarContent").text();
	tmp.replace(/<[^>]*>/,'');
	//tmp.replace(/\s+/,'');
	var tmp2 = $("#CTISidebarTitle").text();
	tmp2.replace(/<[^>]*>/,'');
	//tmp2.replace(/\s+/,'');
	if ($("#CTISidebarTitle").text().length <= 3 || $("#SidebarContent").text().length <= 3 || tmp.length < 1 || tmp2.length < 1)
	{
		$("#CTISidebarTitle").hide();
		$("#SidebarContent").hide();
	}
}
//used for /Prospective%20Students/Pages/Graduate-Ambassadors.aspx
function getID(caller){return caller.id;}
            $('#graduateAmbassadors ul li a').click(function(){
                popUpId = $(this).attr('id') + "_popup";
                $('#' + popUpId).bPopup({modal:true, modalColor:'#333', opacity:.3, appendTo:'form', onOpen: function () {
	                $('#' + popUpId + ' a.graduateClose').click(function() {
						 $('#' + popUpId).bPopup().close();
					});
                }
                });
				return false;
			});

//Facebook Social Plugins (Disabled until new homepage is live)

/*

      window.fbAsyncInit = function() {
        FB.init({appId: '105604596166823', status: true, cookie: true,
                 xfbml: true});
      };
      (function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
      
*/


