/* Javascript stylesheet */
document.write("<link rel=\"StyleSheet\" href=\"/bevanBrittanAssets/css/bevanBrittanJs.css\" type=\"text/css\" media=\"screen\" />");

// e3 javascript for Bevan Brittan

// when the document is loaded
$(document).ready(function() {

	//jQuery functions

	fnPageTools();
	fnSliderHome();
	fnSliderFb();
	fnFilterNav();
	if($('#slideshow').length>0){
		promiseSlideShow();
	}
	//dropdownIE6();
	//fnSelectFix();
	/*fnLoadMiniXml();*/

// IE6 Flyout Nav
	if($.browser.msie) {
	 	$(function() {
	 		$('#share-bar').hover(function(){
	 						$(this).addClass('hover');
	 		}, function() {
	 						$(this).removeClass('hover');
	 		});
	 	});
	};
});

/**************************************************************
Function:	fnBrowser
Purpose:	Check we're in a supported browser
Notes:
**************************************************************/
// Global Variables
var iepc,firefox,ns7,ns8,mozilla,safari;
function fnBrowser() {
	var ua = navigator.userAgent.toLowerCase();

	iepc = (((ua.indexOf("msie 7") != -1)||(ua.indexOf("msie 6") != -1)||(ua.indexOf("msie 5.5") != -1))&&(ua.indexOf("windows") != -1)&&(ua.indexOf("opera") == -1))? true:false;
	firefox = ua.indexOf("firefox") != -1 ? true:false; // pc or mac
	ns7 = ua.indexOf("netscape/7") != -1 ? true:false; // firefox mode
	ns8 = ua.indexOf("netscape/8") != -1 ? true:false; // firefox mode
	mozilla = (ua.indexOf("gecko") != -1) && (ua.indexOf("netscape") == -1) ? true:false;
	safari = ua.indexOf("safari") != -1 ? true:false;
	opera = ua.indexOf("opera/9") != -1 ? true:false;
	if (iepc||firefox||mozilla||safari||opera) {
		return true;
	} else {
		return false;
	}
}


// Flash detect. boolean true/false if installed and version number accessed via flash.version
var flash = new Object();
flash.installed = false;

if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x < navigator.plugins.length; x++) {

		if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
			flash.installed = true;
			flash.version = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);
			break;
		}
	}
}
else if (window.ActiveXObject) {
	for (x = 2; x <= 20; x++) {
		try {
			oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
			if(oFlash) {
				flash.installed = true;
				flash.version = x;
			}
		}
		catch(e) {}
	}
}

/********************************************************************************

Name: 				Flash embed
Description:		Writeout flash code. Fixes Eolas update for IE as well.
@param	swf			String path to swf file
@param	width		Number value of movie width
@param	height		Number value of movie height
@param  wmode		Window mode to use for the movie

*********************************************************************************/
flash.insert = function(swf,width,height,flashVer,nonFlashId) {

	if(!flashVer){minVer = 6;}
	else {minVer = flashVer;}
	if(!nonFlashId){nonFlashId = "nonFlashContent";}

// Handle errors
	var errMsg ="";
	if (!fnBrowser()) { // NOT supported browser
		errMsg += '<p class="err">Unfortunately, this website cannot be viewed by your browser. Please go to <a href="http://www.getfirefox.com">www.getfirefox.com</a> or <a href="http://www.microsoft.com/windows/ie/">www.microsoft.com/</a> to download a recommended browser.</p>';
	}
	if (!flash.installed) { // NOT flash
		errMsg += '<p class="err">This website requires the adobe&trade; Flash player. Go to the adobe website to install the <a href="http://www.adobe.com/products/flashplayer/">latest version of flash</a></p>';
	}

	swf = swf.replace(/\./g,"%2E"); // encode periods as %2e

	if(flash.installed && fnBrowser() && flash.version >= minVer) {
		document.write('<embed src="'+swf+'" menu="false" width="'+width+'" height="'+height+'" scale="noscale" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" salign="T" allowfullscreen="true" />');

		fnHide(nonFlashId);
	}
	else {
    fnShow(nonFlashId);
	}
};

function fnHide(id) {
	if(!document.getElementById(id)){return false;};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "absolute";
	oTarg.top = "-5000px";
	oTarg.left = "0";
}

function fnShow(id) {
	if(!document.getElementById(id)){return false;};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "static";
	oTarg.top = "";
	oTarg.left = "";
}

/* SIFR Initiation */

/* This section adds the ability to use :not in the selectors to filter out anything that shouldn't be replaced */
parseSelector.pseudoClasses = {
  'not': function(nodes, selector) {
    var result = [];
    each: for(var i = 0, node; i < nodes.length; i++) {
      node = nodes[i];
      var ignore = parseSelector(selector, node.parentNode);
      for(var j = 0; j < ignore.length; j++) {
        if(ignore[j] == node) continue each;
      }
      result.push(node);
    }
    return result;
  }
};

	var font = {src: '/bevanBrittanAssets/flash/myriad.swf'};
	
	// You probably want to switch this on, but read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad> first.
	sIFR.useStyleCheck = true;
	sIFR.activate();
	
	
	var frt2 = '.home .fourColInr .col .bdr2:not(.promises-block) h2';

	sIFR.replace(font, {
    selector: frt2
    ,selectable: false
	,forceTextTransform : false
	,wmode: 'opaque'
    ,css: [
      '.sIFR-root { background-color:#28225B ; color: #ffffff; padding:0; margin:0;}'
      ,'a { text-decoration: none; }'
      ,'a:link { color: #ffffff; }'
      ,'a:hover { color: #ffffff; text-decoration: underline; }'
    ]
  });

	
	//selectors to be replaced by the h1 style.
	var frt = '.frt, h1:not(.noFrt), .fb h2, .fb fieldset legend span';
	
	// ajl removed "text-transform:lowercase;" from .sIFR-root
	sIFR.replace(font, {
    selector: frt
    ,selectable: false
	,forceTextTransform : false
	,wmode: 'opaque'
    ,css: [
      '.sIFR-root { background-color:#ffffff; color: #abbf00; padding:0; margin:0;   }'
      ,'a { text-decoration: none; }'
      ,'a:link { color: #abbf00; }'
      ,'a:hover { color: #abbf00; text-decoration: underline; }'
    ]
  });



function fnFav(div){
	if($.browser.msie && ($.browser.version >=6 && $.browser.version <7)){

		div.prepend('<a href="#" class="fav">Add to favourites</a> ');

			$('a.fav').click(function(){
				var url = document.URL;
				var title = document.title;
				window.external.AddFavorite(url, title);
				return false;
			});
	}

}

function fnPrint(div){
	div.append('<li id="print"><a href="#">print</a></li>');

	$('li#print a').click(
		function(){
			window.print();
			return false;
		});
}


function fnPageTools(){

	var div = $('#pageTools');

	//if the pagetools div exists
	if(div.length){
		//fnFav(div);
		fnPrint($("#pageTools ul:first"));
		}
}


/* Popups */
function fnPopup(sUrl, piWidth, piHeight,scrollbars,attributes) {
	if (!scrollbars) {
		scrollbars = "no";
	}
	if (!attributes) {
		attributes = "";
	}
	var iWidth = piWidth;
	var iHeight = piHeight;
	var sScreenX = screen.width;
	var sScreenY = screen.height;
	var x = sScreenX - iWidth;
	var y = sScreenY - iHeight;
	var winLeft = x/2;
	var winTop =  y/2;
	window.open(sUrl,"","width=" + iWidth + ",height="+ iHeight + "," + attributes + ",left=" + winLeft + ",top=" + winTop + ",scrollbars=" + scrollbars + ",resizable=" + scrollbars);
	return false;
}


var items;
var step;
var w;
var h;
var speed;


function fnSliderHome(){

	// config variables - this version assumes there are only 3 max shoes

	items 	= 	1;				// once number of profiles is known update this
	step 	= 	453; 			// pixel width of viewport
	totalW 	= 	0;				// once this is available set this to the width of #profiles
	h		= 	'16.8em';		// sort the css overflow out
	speed	= 	700;			// speed to slide at(ms to completion of movie)


	if($("#profileScroll").length>0){
		//alert('home slider...');

		fnLoadHomeXml();
		fnRecalculate();
		fnCheckSliderPos();

		//prep the current html
	$("#profileScroll #profiles")
		.css({
			overflow: 'hidden',
			height: h
		});

		$('#profileScroll a.prevBtn').click(
			function(){
				$("#profileScroll #profiles").animate({scrollLeft: "-="+step},{ complete: fnCheckSliderPos, duration:speed });
			return false;
		});


		$('#profileScroll a.nextBtn').click(
			function(){
				$("#profileScroll #profiles").animate({scrollLeft: "+="+step},{ complete: fnCheckSliderPos, duration:speed });
			return false;
		});


	}

}

function fnRecalculate(profileDivs, profilesWrap){

	//how many profile divs are there?
	items = $('#profileScroll #profiles .profile').length;

	//set the width of the wrapper to be the number of items multiplied by the width of a step
	$('#profileScroll #profiles #profilesWrap').width(items*step);

	//set the total width to this.
	totalW = $('#profileScroll #profiles #profilesWrap').width();

}



var pQuantity = 10;

function fnCheckSliderPos(){
	//alert('finished')

	var pos = $('#profileScroll #profiles').attr('scrollLeft');
	var oPrev = $('#profileScroll a.prevBtn');
	var oNext = $('#profileScroll a.nextBtn');

	var profNum = Math.floor(pos/step);

	//alert(profNum);

	if(profNum==items-2){
		// build more profiles from the array
		fnBuildSlider(items,pQuantity);
		}

	if(pos <=0){
		fnDisable(oPrev);
		fnEnable(oNext);
	}else if(pos>0 && pos<totalW-step){
		fnEnable(oPrev);
		fnEnable(oNext);
	}else if(pos>=totalW-step){
		fnDisable(oNext);
		fnEnable(oPrev);
	}

}

function fnDisable(obj){
	obj.addClass('disabled');
}

function fnEnable(obj){
	obj.removeClass('disabled');
}


var profileArray = [];

//setup team link, this will be taken from the xml config section
var pTeamLink;

function fnLoadHomeXml(){

  // Default xml is the flat build
  var sProfileXmlUrl = "/bevanBrittanAssets/xml/profiles.xml";

  // If iHomepageProfileStartIndex is set then we're on 'live' then use the sharepoint url
  try {
    // iHomepageProfileStartIndex is the index of the person to start at to pass into feed to make sure the JS starts with the same as the HTML displayed person.
    sProfileXmlUrl = "/_layouts/E3BevanBrittanTemplates/HomepagePeopleFeed.aspx?start=" + iHomepageProfileStartIndex;
  }
  catch (exx) {}

	$.get(sProfileXmlUrl, {},
  			function(xml){

  				pTeamLink = $(xml).find('config teamLink').text();

				var profileTemplate = '\
				<div class="profile">\
					<img src="{img}" alt="{name}" class="photo"/>\
					<div class="profile-info">\
						<h3 class="title ellipsis-overflow">{name}</h3>\
						<h4 class="subtitle ellipsis-overflow">{role}</h4>\
						<p class="tel" class="ellipsis-overflow">{tel}</p>\
						<p class="email"><a href="mailto:{email}" class="ellipsis-overflow">{email}</a></p>\
						<div class="links">\
							<a href="{link}" class="viewProfile">see profile</a>\
							<a href="{teamLink}" class="meetPeople">meet our people</a>\
						</div>\
					</div>\
				</div>';

    			$( 'profile', xml ).each(
    				function ( i ) {
    					var dataMap = {
							name     : $(this).find('name').text(),
	    					img      : $(this).find('homeImage').text(),
	    					dept     : $(this).find('dept').text(),
	    					role     : $(this).find('role').text(),
	    					tel      : $(this).find('tel').text(),
	    					email    : $(this).find('email').text(),
	    					link     : $(this).find('profileLink').text(),
							teamLink : pTeamLink
						};
    					profileArray[i] = profileTemplate.replace( /\{([a-zA-Z0-9_]+)\}/g, function ( fullMatch, tag ) {
							if ( tag in dataMap ) {
								return dataMap[ tag ];
							}
							return '';
						});
    				} //end function(i)
    			); //end each

    			fnRemoveProfiles();

    			fnBuildSlider(0,pQuantity);

	}); // end get

}

function fnRemoveProfiles(){
	$('#profileScroll #profiles .profile').remove();
}


function fnBuildSlider(startPos, quantity){
	for(var i= startPos;i<startPos + quantity; i++){
		$('#profileScroll #profiles #profilesWrap').append(profileArray[i]);
	}
	fnRecalculate();
}


/**** Mini Slider ****/

var profileNav;
var profileCount;
var miniItems;
var miniStep;
var miniTotalW;
var miniH;
var miniSpeed;




function fnSliderFb(){

	// config variables

	miniItems 	= 	1;				// once number of profiles is known update this
	miniStep 	= 	200; 			// pixel width of viewport
	miniTotalW 	= 	0;				// once this is available set this to the width of #profiles
	miniH		= 	'13.75em';			// sort the css overflow out
	miniSpeed	= 	300;			// speed to slide at(ms to completion of movie)


	//is there a meet the team feature block
	if($('#meetTheTeam').length>0){

		if($('#meetTheTeam .profiles .profileSml').length>1){

			miniItems = $('#meetTheTeam .profiles .profileSml').length;

			profileNav = '<div class="profileNav"><a href="#" class="prev" title="Previous team member">previous</a> <a href="#" class="next" title="Next team member">next</a><div class="clr"></div></div>';

			$('#meetTheTeam .profiles').after(profileNav);

			fnRecalculateFb();
			fnCheckSliderPosFb();


			//prep the current html
	$("#meetTheTeam .profiles")
		.css({
			overflow: 'hidden',
			height: miniH
		});

		$('#meetTheTeam .profileNav a.prev').click(
			function(){
				$("#meetTheTeam .profiles").animate({scrollLeft: "-="+miniStep},{ complete: fnCheckSliderPosFb, duration:miniSpeed });
			return false;
		});


		$('#meetTheTeam .profileNav a.next').click(
			function(){
				$("#meetTheTeam .profiles").animate({scrollLeft: "+="+miniStep},{ complete: fnCheckSliderPosFb, duration:miniSpeed });
			return false;
		});

		}//end if

	}//end if
}

function fnRecalculateFb(){

	//how many profile divs are there?
	miniItems = $('#meetTheTeam .profiles .profileSml').length;

	//set the width of the wrapper to be the number of items multiplied by the width of a step
	$('#meetTheTeam .profiles .profilesWrap').width(miniItems*miniStep);

	//set the total width to this.
	miniTotalW = $('#meetTheTeam .profiles .profilesWrap').width();

}


var hDefaultTeamMembersHeading = null;

function fnCheckSliderPosFb(){
	//alert('finished')

	var pos = $('#meetTheTeam .profiles').attr('scrollLeft');
	var oPrev = $('#meetTheTeam .profileNav a.prev');
	var oNext = $('#meetTheTeam .profileNav a.next');

	var oHeading = $('#meetTheTeam #otherMembers');

	// Set the default heading to whatever is in there when the page loads.
	// This is so that it can say "team members" or "other team members" depending on whether there was a Team Head.
	if (hDefaultTeamMembersHeading == null) {
	    hDefaultTeamMembersHeading = oHeading.text() + ' - ';
	}

	var profNum = Math.floor(pos/miniStep);


	oHeading.text(hDefaultTeamMembersHeading + (profNum + 1) + " of " + miniItems);

	//alert(profNum);



	if(pos <=0){
		fnDisable(oPrev);
		fnEnable(oNext);
	}else if(pos>0 && pos<miniTotalW-miniStep){
		fnEnable(oPrev);
		fnEnable(oNext);
	}else if(pos>=miniTotalW-miniStep){
		fnDisable(oNext);
		fnEnable(oPrev);
	}

}

/*
var mpName;
var mpimg;
var mpDept;
var mpRole;
var mpTel;
var mpEmail;
var mpLink;
var mpVcard;

var miniProfileArray = new Array;
*/
/*
function fnLoadMiniXml(){

	$.get("/bevanBrittanAssets/xml/profiles.xml", {},
  			function(xml){

    			$('profile name:contains("Matthew Waters")', xml).each(
    				function(i){

    					var mp = $(this).parent();

    					var mpName = mp.find('name').text();
    					//create html for profiles

    					miniProfileArray[i] = mpName +" " +i;

    				}//end function(i)
    			);//end each



    			//fnRemoveProfiles();

    			//fnBuildSlider(0,pQuantity);

	}); // end get

}*/

/*
 * Replaces the values in the Services/Markets drop downs with the ones stored in the array
 * for the selected Service/Market Area.
 */
function fnUpdateExpertiseSelector(oSA, oS, oHashToUse)
{
    // oHashServices hashtable contains key = URL of Service Area, value = delimited services.
    if (!oHashToUse) oHashToUse = oHashServices;

    // Clear existing services including Please Select.
    oS.options.length = 0;

    // Only add more options if you didn't select Please select service area.
    if (oSA.selectedIndex > 0) {

        // Add please select element.
        var y3=document.createElement('option');
        y3.value = "";
        y3.text = "Please select";
        try {
            oS.add(y3, null); // standards compliant
        } catch(ex) {
            oS.add(y3);       // IE only
        }

        // Get array of services to add
        var sServices = oHashToUse[oSA.options[oSA.selectedIndex].value];

        var aServices = sServices.split('`');
        for (var i = 0; i < aServices.length; i++) {

            var aService = aServices[i].split('|');

            // check it has the text and value
            if (aService.length >= 2) {

                // Add option
                var y=document.createElement('option');
                y.value = aService[0];
                y.text = aService[1];
                try {
                    oS.add(y, null); // standards compliant
                } catch(ex) {
                    oS.add(y);       // IE only
                }
            }
        }

        // Show services drop down row.
        $(oS).parent().parent().show();
    }
    else {
        // selected Please Select service area...

        // Add please select element.
        var y2=document.createElement('option');
        y2.value = "";
        y2.text = "Please select an area first";
        try {
            oS.add(y2, null); // standards compliant
        } catch(ex) {
            oS.add(y2);       // IE only
        }

        // Hide services drop down row.
        $(oS).parent().parent().hide();
    }

}


function fnFilterNav(){

	//does the subnav have categories?
	if($('#subNav .category').length>0){

    // use the sub nav heading as the filter by text (should be articles or events)
    var intro = '<p class="intro">use the filters to narrow your choice of ' + $('#subNav h2:first').text() + '</p>';

		$('#subNav .category:first').before(intro);
		$('#subNav .category:last').addClass('last');
		$('#subNav').addClass('filterList');

		// all categories
		$('.category').each(function(){

			$('h3',this).css({'cursor':'pointer'}).click(
				function(){
					$(this).parent().find('.catList').slideToggle();

					$('.category.open').not($(this).parents('.category')).toggleClass('closed').toggleClass('open')
					.find('.catList').slideToggle();

					$(this).parents('.category').toggleClass('closed').toggleClass('open');
				});
		});

		//If not open then close them
		$('.category:not(.open)').each(function(){
			$('.catList', this).hide();
			$(this).addClass('closed');
		});

	}
}

/*
*
* IE6 Fix for Floated elements (nav) positioned over <select> dropdown boxes
* INCOMPLETE
*
*/

// function fnSelectFix(){
// 	//if($.browser.msie && ($.browser.version >=6 && $.browser.version <7)){
// 		var w,h;
// 		var iF = '<iframe id="ie6Fix"></iframe>';
//
// 		var targs = [$('#navMarkets'),$('#navAbout')];
//
// 		$(targs) .each(function(index) {
//
// 			$(this).hover(function() {
// 			//add iframe
// 			$(this).prepend(iF);
// 			//get w,h
//
// 			//assign w,h
// 			$('#ie6Fix').css({width: w, height: h})
// 			}, function() {
// 				$(this).find('iframe').remove();
// 			});
//
// 			//console.log($(this));
// 			//this.innerHTML = this + " is the element, " + index + " is the position";
// 		});
//
//
// 	//}
//
// }

// function dropdownIE6() {
// 	$("#mainNav li").bind("mouseenter", ie6menu.enter);
// 	$("#mainNav li").bind("mouseleave", ie6menu.leave);
// }
// var ie6menu = {
// 	enter:function() {
// 		$(this).addClass("hover");
// 		var ul = $(this).find("ul:first");
// 		var iframe = ul.find("iframe:first");
//
// 		if (iframe.length > 0)
// 		iframe.height(ul.height()).width(ul.width());
// 		alert(iframe.height());
// 	},
// 	leave:function() {
// 		$(this).removeClass("hover");
// 		var ul = $(this).find("ul:first");
// 		var iframe = ul.children("iframe:fr");
// 		if (iframe.length > 0)
// 		iframe.height(0).width(0);
// 	}
// }


function promiseSlideShow() {

	$( '#slideshow.promiseList li' ).each( function () {
		var html = $.trim( this.innerHTML );
		if ( html.indexOf( '...' ) !== 0 ) {
			html = '... ' + html;
		}
		this.innerHTML = html.toLowerCase();
	});

    $('#slideshow').after( '\
		<div class="slideshow-pager">\
			<a href="#" id="slideshow-prev">Previous</a>\
			<a href="#" id="slideshow-next">Next</a>\
		</div>\
	').cycle({
        fx:     'fade',
        speed:  'fast',
        timeout: 5000,
        // pager:  '#nav'
		next:   '#slideshow-next',
		prev:   '#slideshow-prev'
    });

}

/*
 * Function solely to open the share this buttons in a nicely sized window.
 */
function fnAddToSharingService(sLink) {

  switch(sLink.id) {
    case 'share-delicious':
      fnPopup(sLink.href, 550, 550);
      return false;
      break;
    case 'share-link':
      fnPopup(sLink.href, 520, 570);
      return false;
      break;
    case 'share-stumble':       // do it normal like (target=_blank)
      break;
    case 'share-digg':
      break;
    case 'share-reddit':
      break;
    case 'share-twitter':
      break;
  }

  // if you get to here then you've not opened a window, probably...
  return true;

}

