$(document).ready(function(){
	var path = window.location.pathname.split('/');
	rUrl = _spPageContextInfo.siteServerRelativeUrl;

    Global();

	if(path.length == 2 && path[1] == 'home.aspx')
	{
		// Frontpage
		Front();
	}
	else
	{
		// run function with the correct name, for example, Events()
		if(typeof window[path[1]] == 'function')
		{
			window[path[1]](path);
		}
		
		AfterGlobal();
	}
});

/*
    Subsite specific functions
*/

function Front()
{
	// frontpage carousel
	if($(".body-front-carousel-container ul.dfwp-list").anythingSlider)
	{
		// Frontpage carousel
		$('.body-front-carousel-container ul.dfwp-list').anythingSlider({
			buildArrows: false,
			autoPlay: true,
			delay: 7000,
			hashTags: false,
			startText: '<img src="/assets/images/icon-play.png" alt="Play" />',
			stopText: '<img src="/assets/images/icon-pause.png" alt="Stop" />'		});

		// Create correct images for frontpage carousel
		$('.body-front-carousel-container div.front-carousel-img a').each(function() {
			$(this).parent().parent().parent().html('<img src="'+$(this).attr('href')+'" alt="" />');	
		});

		$('div.body-front-carousel-container table.s4-wpTopTable').css('visibility', 'visible');

		$('.body-front-carousel-container div.carousel-description-link').each(function() {
			var html = $(this).html().split(',');
			if(html)
			{
				$(this).html('<a href="'+html[0]+'">'+jQuery.trim(html[1])+'</a>');
			}
		});

		$('.front-feed-date').each(function(){
			$(this).html(parseToDateTime($(this).html()));
		});
	}
	// Check whether to remove selected class if Home menu item is selected & we are not on the Home page
	else if($('.s4-tn li.selected a span span').html() == "Home")
	{
		$('.s4-tn li.selected').removeClass('selected');
	}

	new Accordion();

	$('.front-feed-title a').each(function() {
		var href = $(this).attr('href');
		var patt = /ItemId=[0-9]+/gi;
		var itemId = parseInt(href.match(patt)[0].replace('ItemId=',''));
		if (href.indexOf("F3544048-136E-419B-AFBA-809B0AFD7E1B") > 0)
		{
			$(this).attr('href', '/SafetyAlerts/Lists/Posts/Post.aspx?ID=' + itemId);		
		}
		else
		{
			$(this).attr('href', '/NewsRoom/Lists/Posts/Post.aspx?ID=' + itemId);
		}
	});

}

var NewsRoom = Events = SafetyAlerts = function(path)
{
	$('.ms-PostFooter').each(function() {
		if($(this).children('div').length == 0)
		{
			var html = $(this).html(),
				length = html.length;

			$(this).html(html.substr(0,length-13));
		}
	});
	
	// handle categories page
	var href = document.location.href;
	if(href.indexOf('/Categories/') != -1)
	{
		$('#s4-leftpanel a').each(function() {
			if(this.href == href)
			{
				var a = $(this).addClass('selected').parent().parent().addClass('selected').end().html(),
					text = (a.indexOf('<A ') != -1) ? $(a).html() : a;

				$('.c-page-title span span').html(text);
				return false;
			}
		});
	}
	
	if(path[1] == 'Events' && path[2] == 'default.aspx' && $('.ms-rightblogpost').length == 0)
	{
		$('.body-right-col-page-title').after('<div class="msg-no-rows-found">No upcoming events</div>');
	}
}

/*
    Global functions
*/
function AfterGlobal()
{
	var lastBC = $('.breadcrumb > span > span:last-child'),
		breadcrumbContents = (lastBC.contents().html() == null ) ? lastBC.html() : lastBC.contents().html(),
		pageTitleContents = $('.c-page-title span').contents().html();

	if(breadcrumbContents != pageTitleContents)
	{
		$('.breadcrumb > span').append('<span> / </span><span class="ms-sitemapdirectional">'+pageTitleContents+'</span>');
	}
}

function Global()
{
	/*
		ADD CSS CLASSES
	*/
	var path = window.location.pathname, pathArr = path.split('\/');
	if(pathArr[1] && pathArr[1].indexOf('.') == -1)
	{
		// we can assume that we are not on the first level

		$(document.body).addClass('not-front '+pathArr[1].toLowerCase());
		if(pathArr[2] && pathArr[2].indexOf('.') == -1)
		{
			$(document.body).addClass(pathArr[2].replace('%20', '-').toLowerCase());
		}
	}
	else if(pathArr.length = 2)
	{
		// first level / frontpage
		$(document.body).addClass('front');
	}

	// delete for anonymous
	$('#zz2_CurrentNav').remove();

	if($('#main-content-left .related-links').length > 0)
	{
		$('#main-content-left .article-content').css('width', 490);
	}
	
	// Since author info is hidden in the search results, trim the spaces from before the results
	if($('.srch-Metadata2').length > 0)
	{
		$('.srch-Metadata2').html($('.srch-Metadata2').html().trim());
	}

	var rightCol = $('#main-content-left > table table > tbody > tr > td[width="30%"]');

	if(rightCol.length == 1)
	{
		rightCol.remove();
		$('#main-content-left > table table > tbody > tr > td[width="70%"]').css('width', '100%');
	}	
	
    // hide ribbon (for IE7)
	if(!$(document.getElementById('s4-ribbonrow')).children().length)
	{
		$(document.getElementById('s4-ribbonrow')).css('display', 'none');
	}

	// add classes
	$('ul li:first-child, table > tbody > tr:first-child').addClass('first-child');
	$('ul li:last-child, table > tbody > tr:last-child').addClass('last-child');

	// breadcrumb
	$('.breadcrumb > span > span:first-child > a').html('Home');
	$('.breadcrumb').css('visibility', 'visible');

	// only execute when not in edit mode
	if($('#MSOLayout_InDesignMode').val() != "1")
	{
	}
	
	// open external links in new window
    $('a').click(handleLinkClick);

}

function parseToDateTime(dateTimeString)
{
	var dateArr = dateTimeString.split(' ');
	if(dateArr.length == 2)
	{
		var dayArr = dateArr[0].split('-');
		var dateDay = dayArr[2],
			dateMonth = dayArr[1],
			dateYear = dayArr[0];
	}
	else
	{
		var date = new Date(Date.parse(dateTimeString)), dateString = '';
		var dateDay = (parseInt(date.getDate()) < 10) ? '0'+date.getDate() : date.getDate();
		var month = date.getMonth() + 1
		var dateMonth = (parseInt(month ) < 10) ? '0'+month : month ;
		var dateYear = date.getFullYear();
	}

	dateString = dateDay + '/' + dateMonth + '/' + dateYear ;
	
	return dateString;
}

font = {
	'sizeVar': 1.2,
	'sizeCount': 0,
	'maxZoom': 2,
	'elements': '#s4-bodyContainer :not(:has(:first-child)):visible',
	'makeSmaller': function()
	{
		if(this.sizeCount <= (this.maxZoom*-1))
		{
			return;
		}

		--this.sizeCount;

		var els = $(this.elements);
		$('#s4-bodyContainer br:visible, #s4-bodyContainer a:visible, #s4-bodyContainer strong:visible').parent().each(function() {
			els.push(this);
		});
		
		var isIE = ($.browser.msie) ? true : false;
		
		$(els).each(function(a,b,c) {
			// change style directly because normal jquery styling doesn't allow for the use of !important
			var patt1= (isIE) ? /font-size: [0-9]+px !important/gi : /font-size: [0-9]+px !important; /gi;
			var newSize = Math.round(parseFloat((parseFloat($(this).css('font-size')) / font.sizeVar).toFixed(2)));
			var newStyle = (typeof $(this).attr('style') == 'undefined') ? 'font-size: '+newSize+'px !important; ' : 'font-size: '+newSize+'px !important; '+ $(this).attr('style').replace(patt1,'');

			$(this).attr('style', newStyle );
		});
	},
	'makeNormal': function()
	{
		var els = $(this.elements);
		$('#s4-bodyContainer br:visible, #s4-bodyContainer a:visible, #s4-bodyContainer strong:visible').parent().each(function() {
			els.push(this);
		});

		$(els).each(function(a,b,c){
	  		var newSize = parseFloat($(this).css('font-size'));
  			var fontSize = Math.abs(font.sizeCount );
			if(font.sizeCount < 0)
			{
				for(var x = 0; x < fontSize ; ++x)
				{
					newSize = newSize * font.sizeVar;
				}
			}
			else
			{
				for(var x = 0; x < fontSize ; ++x)
				{
					newSize = newSize / font.sizeVar;
				}
			}

			var isIE = ($.browser.msie) ? true : false;
		
			var patt1= (isIE) ? /font-size: [0-9]+px !important/gi : /font-size: [0-9]+px !important; /gi;
			newSize = Math.round(parseFloat(parseFloat(newSize).toFixed(2)));
			var newStyle = (typeof $(this).attr('style') == 'undefined') ? 'font-size: '+newSize+'px !important; ' : 'font-size: '+newSize+'px !important; '+ $(this).attr('style').replace(patt1,'');
			// change style directly because normal jquery styling doesn't allow for the use of !important
			$(this).attr('style', newStyle );
		});

		font.sizeCount = 0;
	},
	'makeLarger': function()
	{
		if(this.sizeCount >= this.maxZoom)
		{
			return;
		}

		++this.sizeCount;

		var els = $(this.elements);
		$('#s4-bodyContainer br:visible, #s4-bodyContainer a:visible, #s4-bodyContainer strong:visible').parent().each(function() {
			els.push(this);
		});

		var isIE = ($.browser.msie) ? true : false;
		
		$(els).each(function(a,b,c){
			var curSize = parseFloat($(this).css('font-size'));
			var newSize = curSize * font.sizeVar;

			// change style directly because normal jquery styling doesn't allow for the use of !important
			var patt1= (isIE) ? /font-size: [0-9]+px !important/gi : /font-size: [0-9]+px !important; /gi;
			var newStyle = (typeof $(this).attr('style') == 'undefined') ? 'font-size: '+Math.round(parseFloat(newSize.toFixed(2)))+'px !important; ' : 'font-size: '+Math.round(parseFloat(newSize.toFixed(2)))+'px !important; '+ $(this).attr('style').replace(patt1,'');

			$(this).attr('style', newStyle );
		});
	}
}

function handleLinkClick()
{
    var href = $(this).attr('href');

    if(typeof href != 'undefined' &&
       href.indexOf('http://') != -1 &&
       href.indexOf(window.location.host) == -1)
    {
                    window.open(href);
                    return false;
    }
    
    var dotSplit = this.href.split('.'),
                    fileExt = dotSplit[dotSplit.length-1].toLowerCase();
    switch(fileExt)
    {
                    case 'pdf':
                    case 'doc':
                    case 'docx':
                    case 'ppt':
                    case 'txt':
                    case 'dot':
                                    window.open(href);
                                    return false;
                    break;
    }
}


/*
	ACCORDION
*/

function Accordion()
{
	this.classTitle = '.accordion-row-title';
	this.classContent = '.accordion-row-content';

	var a = this;
	$(this.classTitle).click(function(){a.handleTitleClick(this);});

	$('.accordion-row.first .accordion-row-content').slideDown('slow', function(){$(this)}).parent().addClass('open');
}

Accordion.prototype.handleTitleClick = function(el)
{
	if($('.accordion-row.open').length)
	{
		$('.accordion-row.open > .accordion-row-content').slideUp('slow', function(){$(this)}).parent().removeClass('open')
	}

	$(el).next().is(':visible') ?
		$(el).next().slideUp('slow', function(){$(this)}).parent().removeClass('open') :
		$(el).next().slideDown('slow', function(){$(this)}).parent().addClass('open');
}











