﻿// JavaScript Document
// Selectively apply styles

//broken links ***********************************

function ImgError(source){
	source.src = "/SiteCollectionImages/titles/TheOhioStateUniversityCollegeofMedicine.png";
	source.onerror = "";
	return true;
}

//********************************************************************************************
//******************** Reads the URL for Get variables ************************
//********************************************************************************************
// example:		var allVars = $.getUrlVars();
// example:		var byName = $.getUrlVar('topic');

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});



//********************************************************************************************
//******************** SET COOKIE CODE FROM PLUGIN ************************
//********************************************************************************************

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var host = options.host ? '; host=' + (options.host) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, host, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


$(document).ready( function() {

//Show/hide ribbon in IE7
	if ($.browser.msie && parseInt($.browser.version) == 7) {
	    if($('#s4-ribbonrow').children().length){
			$('#s4-ribbonrow').addClass('show');
		}else{
			$('#s4-ribbonrow').removeClass('show');
		}
	}

// Removes sign in link after signed in           
	if($('#s4-ribbonrow > span > #s4-ribboncont').length){
		$('#sign_in').remove();
	}

//get page and pass it through to the authentication so we end up back on that page
	var getPage = window.location.pathname;
	$('#sign_in a').attr('href', 'https://medstaging.osumc.edu/_layouts/authenticate.aspx?Source='+getPage);

//********************************************************************************************
//******************** removes empty divs ************************
//********************************************************************************************

	if($("div#staticPageWebpartZoneSidebar").children().size() > 0) {
		$("div#staticPageWebpartZoneSidebar").show();
	} else {
		$("div#staticPageWebpartZoneSidebar").remove();
	}
	
	if($("div#staticPageWebpartZone1").children().size() == 0) {
		$("div#staticPageWebpartZone1").remove();
	}

//********************************************************************************************
//******************** Adds bounding box around Tables ************************
//********************************************************************************************

	$('#ctl00_PlaceHolderMain_ctl01_RichHtmlField_displayContent').addClass("ms-rteTableGrid");


//********************************************************************************************
//******************** Remove all ms-WPBody classes ************************
//********************************************************************************************

	$('div').removeClass("ms-WPBody");
	$('div').removeClass("ms-rte-wpbox");


//********************************************************************************************
//******************** Adds Icons to alert boxes ************************
//********************************************************************************************

	$('div.error').prepend('<img src="/SiteCollectionImages/icons/error.png" class="alertImage">');
	$('div.success').prepend('<img src="/SiteCollectionImages/icons/success.png" class="alertImage">');
	$('div.info').prepend('<img src="/SiteCollectionImages/icons/info.png" class="alertImage">');
	$('div.warning').prepend('<img src="/SiteCollectionImages/icons/warning.png" class="alertImage">');

//********************************************************************************************
//******************** Catch Searches ************************
//********************************************************************************************

	// pass through the search parameters to the medctr search page
	$("#aux_topnav .searchbox").keyup(function(e){
		if(e.keyCode == 13){
			window.location.href = "/pages/search.aspx?s=ColMed&k=" + $("#aux_topnav .searchbox").val();
		}
	});
		
	$("#aux_topnav .searchbutton").click(function(){
		window.location.href = "/pages/search.aspx?s=ColMed&k=" + $("#aux_topnav .searchbox").val();
	});
	
	// 404 page
	$("#Search404 .searchbox").keyup(function(e){
		if(e.keyCode == 13){
			window.location.href = "/pages/search.aspx?s=ColMed&k=" + $("#Search404 .searchbox").val();
		}
	});
		
	$("#Search404 .searchbutton").click(function(){
		window.location.href = "/pages/search.aspx?ref=404&s=ColMed&k=" + $("#Search404 .searchbox").val();
	});




//********************************************************************************************
//************* SELECTIVELY ADJUST STYLES ****************
//********************************************************************************************
				
	//add divider to topnav
	var topnavTotal = $('#topnav ul li').length;
	$('#topnav ul li').each( function(i) {
		if((i+1) < topnavTotal){
			$(this).css({"background":"url(/SiteCollectionImages/layout/topnav_divider.png) no-repeat right 4px"});
		}
	});
	
	$('.parentsite_menu li:first').css({"border-left":"1px solid #ccc"});
	$('.parentsite_menu li:last').css({"border":"none"});
	
	//Broken Image Links ***********************************

	//$('#osumc_text img').error( function() {
	//  $(this).unbind("error").attr("src", "/SiteCollectionImages/titles/Students.png");
	//});

//********************************************************************************************
//******* DISPLAY THE PARENT SITE NAV CONTAINTER **********
//********************************************************************************************

	var userOver = 0;
	$('li.thissite').hover(
		function() {
			userOver = 1;
			parentsiteNavAnimate();
		},
		function(){
			userOver = 0;
			window.clearTimeout(nt);
			parentsiteNavAnimate();
		}
	);
	
	function parentsiteNavAnimate () {
		if(userOver > 0){
			nt = window.setTimeout(function(){
				if ($.browser.msie) {
					
					$('.parentsite_menu').slideDown("fast");
					
				}else{
					$('.parentsite_menu').fadeIn("fast");
				}
			}, 200);
		}else{
			if ($.browser.msie) {
				$('.parentsite_menu').slideUp("fast");
			}else{
				$('.parentsite_menu').fadeOut("fast");
			}
		}
	}


//********************************************************************************************		
//************* HOMEPAGE TOP FEATURE ****************
//********************************************************************************************

  	//set a variable to the targeted elements for future reference
	var wF = $('#topFeatureArea #topFeaturesZone .AspNet-WebPart').children('a');
	$('#topFeatureArea #topFeaturesZone .AspNet-WebPart a:first').fadeIn(1000);
	//set a variable to the all the feature images except the first one
	/*var hR = $('#homepage_feature #top_feature_images div').children('a:first').nextAll('a');
	//then hide them
	$(hR).hide();*/
	//find out how many children are in the parent container
    var fTotal = $(wF).length;
    //set the starting index
	var fStart = 1;
	//set the default value of the clicked thumbnail index
	var clickStart = 1;
	//set the origin for later reference against current index
	var fadeOrigin = 1;
	//define values for animation variables
	//clear the animation queue
	var clearQueue = true;
	//finish any current animation
	var gotoEnd = true;
	
	
	//make sure there is more than one image, otherwise, no need to do anything
	if (fTotal > 1) {
		$(wF).each( function(i) {
			$(this).attr({id:"featureimage"+(i+1)});
			//build in nav buttons for multiple features so you can pick them manually
			//rather than watch the default fading loop
			$('.topFeatureNav').append('<span id=navbutton'+(i+1)+'><img src="/SiteCollectionImages/layout/top_feature_nav_button.png" /></span>');
		});
		//highlight the button that equals the starting feature index
		$('#navbutton'+fStart).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button_active.png" />');
		runFades();
	}
		
	function runFades() {
		//check that we haven't incremented past the total number of children
		if (fStart < fTotal) {
			//run the timer for the fade out and set a variable so we can reset the value on click
			t = window.setTimeout(function(){
				//remove the highlight from the previous feature button
				$('#navbutton'+fStart).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button.png" />');

				//fade out the currently displaying feature
				$('#featureimage'+fStart).fadeOut(2000, function() {
					//when the timer is done, increment the id (index) so the next one will fade in/out
					fStart++
					//run this whole function again so we fade them all in sequence
					runFades();
				});
				//fade in the next feature
				$('#featureimage'+(fStart + 1)).fadeIn(2000);
				//highlight the new feature button
				$('#navbutton'+(fStart+1)).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button_active.png" />');

			}, 7000);

		}else{
			//run the timer for the fade out and set a variable so  we can reset the value on click
			t = window.setTimeout(function(){
				//highlight the new feature button
				$('#navbutton'+fadeOrigin).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button_active.png" />');
				//fade in the first feature since we're not on the last one
				$('#featureimage'+fadeOrigin).fadeIn(2000);
				//remove the highlight on the previous feature button
				$('#navbutton'+fStart).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button.png" />');
				//fade out the current feature
				$('#featureimage'+fStart).fadeOut(2000, function() {
					//when the timer is done, increment the id (index) so the next one will fade in/out
					fStart = 1;
					//run this whole function again so we continue to fade them all in sequence
					runFades();
				});
			}, 7000);

		}
	}
	
	//interrupt the fading with a button click action
	function stopFades() {
		window.clearTimeout(t);
		//reset the setTimeout variable
		t=0;
		//stop the animation queue and finish the function for the photo displaying
		$(wF).stop(clearQueue,gotoEnd);
		//quickly fade out the feature that is currently displaying
		$('#featureimage'+fStart).fadeOut(10);
		//quickly fade in the feature that was clicked
		$('#featureimage'+clickStart).fadeIn(10, function(){
			//reset the highlight for the previous feature nav
			$('#navbutton'+fStart).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button.png" />');
			//put the highlight on the feature nav that was clicked
			$('#navbutton'+clickStart).html('<img src="/SiteCollectionImages/layout/top_feature_nav_button_active.png" />');
			//make the fade index match the newly displaying feature so the loop can restart from here
			fStart = clickStart;
			//run the default fading function
			runFades();
		});
	}
	
	//CLICK THUMBNAIL FUNCTION
	//catch the clicks on the feature nav buttons
	$('.topFeatureNav span').click( function() {
		//set a varible to the value of the thumbnail's index
		clickStart = ($('.topFeatureNav span').index(this))+1;
		//run the function for when a button is clicked
		stopFades();
	}
	);
	
//********************************************************************************************
//************* Sub Features ****************************************************
//********************************************************************************************
  	
	jQuery('#homepageSubFeatures #subFeatures').jcarousel({
        vertical: true,
        scroll: 2
    });
    
    jQuery('#landingSubFeatures #subFeatures').jcarousel({
        vertical: true,
        scroll: 1
    });
		
	jQuery('#landingSubFeatures #videoFeatures').jcarousel({
        vertical: false,
        scroll: 1
    });

//********************************************************************************************
//************* News Tabs ****************************************************
//********************************************************************************************

	//When page loads...
	$("#homepageNews .tab_content").hide(); //Hide all content
	$("#homepageNews ul.tabs li:first").addClass("active").show(); //Activate first tab
	$("#homepageNews .tab_content:first").show(); //Show first tab content

	//On Click Event
	$("#homepageNews ul.tabs li").click(function() {

		$("#homepageNews ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$("#homepageNews .tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	//LANDING PAGE SCRIPT

	$("#landingNews .tab_content").hide(); //Hide all content
	$("#landingNews ul.tabs li:first").addClass("active").show(); //Activate first tab
	$("#landingNews .tab_content:first").show(); //Show first tab content

	//On Click Event
	$("#landingNews ul.tabs li").click(function() {

		$("#landingNews ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$("#landingNews .tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});


//********************************************************************************************
//************* Expanding Content Script ****************************************************
//********************************************************************************************


	var helpTopic = '';
  	var helpTopic = $.getUrlVar('topic');
	
	$('#' + helpTopic).addClass('expanded');
	$('#' + helpTopic).next('div').slideToggle();
	
	$('.expandable_content h2').hover(function(){
		$(this).css({"background-color":"#444","color":"#fff"});
	},
	function(){
		if ($(this).hasClass('expanded')) {
			$(this).css({"background-color":"#777","color":"#fff"});
		}else{
			$(this).css({"background-color":"#ffffff","color":"#414141"});
		}
	});
	
	$('.expandable_content h2').click( function() {
			if ($(this).hasClass('expanded')) {
				$('.expanded').next('div').slideUp();
				$('.expanded').removeClass('expanded');
			}else{
				$('.expanded').next('div').slideUp();
				$('.expanded').css({"background-color":"#ffffff","color":"#414141"});
				$('.expanded').removeClass('expanded');
	  			$(this).next('div').slideToggle();
				$(this).addClass('expanded');
			}
	})


//********************************************************************************************
//************* Basic Slideshow Script ****************************************************
//********************************************************************************************

    if($('div').hasClass('slideshowFade')){
		$('.slideshowFade').cycle({ 
			fx:    'fade', 
	        speed:  2500,
	        timeout: 5000
	    });
	}

//********************************************************************************************
//************* Colorbox Image Gallery ****************************************************
//********************************************************************************************
	
	$("a[rel='imgGallery']").colorbox();

});
