function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1009.2513
    // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
    }
    return sa ? s : s[0];
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [ myWidth, myHeight ];
}

/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container get’s applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}

/********************************
 ********************************
 **
 **	Start of custom code
 **
 *****
 *****/

$(function(){

	var pgType = $("body").attr('rel');
	
	if(pgType == 'Case Studies') {
		$("html body div#wrapper div#main div#subNav div.Whatwe p.Whatborder img").attr('src','/images/our_work.png');
	}

	var tmp = $("div.teamMember");
	
	if(tmp.length > 0) {
		isTeamPage = true;
	} else {
		isTeamPage = false;
	}
	
	isNewsPage = false;
	

	$(".Welcometext div ul li").prepend("<span class='absoluteOrange'>&bull;</span> ");

	/********************************
	 *
	 *	Read More link for  home page news
	 *
	 *****/

	//var nml = $("#footer .news ul li a").attr('href');
	
	//$("#footer .news").append(" read more <a href='"+nml+"'>here</a>.");


	/********************************
	 *
	 *	Fix news page links
	 *
	 *****/
	 
	 var loc = document.location+"";
	 var pts = loc.split("/");
	 
	 if(pts[pts.length - 2] == 'news') {
	 	$("div.Whatdotext ul").addClass('recentNews');
	 }
	 
	 var li1 = $("ul.recentNews li")[0];
	 var li2 = $("ul.recentNews li")[1];
	 var li3 = $("ul.recentNews li")[2];
	 var li4 = $("ul.recentNews li")[3];
	 var li5 = $("ul.recentNews li")[4];
	 var li6 = $("ul.recentNews li")[5];
	 
	 $(li1).css({"border-left":"16px solid #888"});
	 $(li2).css({"border-left":"16px solid #999"});
	 $(li3).css({"border-left":"16px solid #AAA"});
	 $(li4).css({"border-left":"16px solid #BBB"});
	 $(li5).css({"border-left":"16px solid #CCC"});
	 $(li6).css({"border-left":"16px solid #DDD"});

	$("ul.recentNews li.active").css({"border-left":"16px solid #EC8000"});
	
	/********************************
	 *
	 *	Need to know if this is a Gallery page or not
	 *
	 *****/
	
	isGallery = false;

	//#galleryMainImages only exists on gallery pages
	if($("#galleryMainImages").length > 0) {
		isGallery = true;
	}

	isGuidePage = false;

	if($(".guideDesc").length > 0) {
		isGuidePage = true;
	}

	/********************************
	 *
	 *	Main menu image rollover
	 *
	 *****/
	
	$('#nav ul li').each(function(){		
		var cls = $('a',$(this)).attr('class');
		$('a',$(this)).removeClass(cls);
		$(this).addClass(cls);		
	});

	$('.Whatdotext ul li').each(function(){		
		var cls = $('a',$(this)).attr('class');
		$('a',$(this)).removeClass(cls);
		$(this).addClass(cls);
	});

	/********************************
	 *
	 *	Fade Out Gallery Viewers
	 *
	 *****/

	if(isGallery) {
		
		$("h1.fadeIn").hide();
		
		setTimeout(function(){
			$('img.Imgbox3').fadeOut(1500);
		},5000);
		
		setTimeout(function(){
			$("h1.fadeIn").fadeIn(1500);
		},5000);
	} else {
		$("#subNav .Whatwe").append("<div style='clear:both; padding-top: 30px;'><img title='Help Moving Office' alt='Help Moving Office' src='/new/img/Approved member - rectangle.png' style='border:0px none;'/><br /></div>");
	}

	/********************************
	 *
	 *	Put image tumbnail navigation in a container
	 *
	 *****/	

	$('ul#thumbs').before("<div id='gThumbs'><ul></ul></div>");
	$('#gThumbs ul').append($('ul#thumbs').html());
	$('ul#thumbs').remove();
	$('#gThumbs ul').attr('id','thumbs');
	
	/********************************
	 *
	 *	Count Thumbnail navigation
	 *
	 *****/
	
	var t_count = $('ul#thumbs li').length;

	/********************************
	 *
	 *	Add Next/Previous buttons if more than 6 thumbnails
	 *
	 *****/

	if(t_count > 6) {

		var t_size = Math.ceil(t_count/2);

		var t_width = t_size * 58;

		$('#gThumbs').css({'width':'175px','height':'143px','overflow':'hidden'});

		$('ul#thumbs').css({'width':t_width+'px','height':'132px'});
	
		$('#gThumbs').after("<div style='float:right; margin-top:-40px;' id='thumbMove'><a title='Previous' href='#' rel='history'><img src='images/arrow-left.png'></a><a title='Next' href='#' rel='history'><img src='images/arrow-right-roll.png'></a></div>");
	}

	/********************************
	 *
	 *	Next/Previous buttons actions
	 *
	 *****/

	$('#thumbMove a').click(function(){
		
		var m = $(this).attr('title');
		
		var offset = $('ul#thumbs').css('margin-left');
		
		offset = parseInt(offset);
		
		if(m == 'Previous') {
			offset = offset + 58;
		}
		
		if(m == 'Next') {
			offset = offset - 58;
		}
		
		$('ul#thumbs').animate({'marginLeft':offset});
		
		return false;
	});

	/********************************
	 *
	 *	gallery functionality
	 *
	 *****/

	$("#galleryMainImages img").hide();
	$("#galleryMainImages img:first").show();
	
	$('ul#thumbs li a').hover(function(){
		
		
		//if(!isGallery && !isGuidePage) {
		//	return true;
		//}
		
		var tgt = $(this).attr('rel');
		//var tgt = $(this).attr('href');

		//tgt = str_replace("%20","-",tgt);
		//tgt = str_replace(" ","-",tgt);

		$("#galleryMainImages img[rel!='"+tgt+"']").fadeOut();
		$("#galleryMainImages img[rel='"+tgt+"']").fadeIn();

		//console.log(tgt+"--");

		//alert(tgt);
		
		return false;
	},function(){return false;});

	$('ul#thumbs li a').click(function(){
		if(!isGallery && !isGuidePage) {
			return true;
		}
		
		return false;
	});

	/********************************
	 *
	 *	Multiple Banner Images Rotate on non-gallery pages
	 *
	 *****/

	if(!isGallery && !isGuidePage && !isTeamPage) {
		/*
		mbis = $("#banner img");
		
		if(mbis.length > 1) {
		
			$("#banner img").hide();
			$("#banner img:first").show();

			i = 1;

			setInterval(function(){

				mbis = $("#banner img");

				if (i == mbis.length) {
					i = 0;
				}

				$("#banner img").fadeOut();

				$(mbis[i]).fadeIn();

				i++;

			},4000);
		
		}
		//*/
		
		
		$("#banner").innerfade({
			'speed':'slow',
			'timeout':8000,
			'containerheight':'407px'
		});
	


	}
	
	/********************************
	 *
	 *	Guide page pop ups
	 *
	 *****/
	
	if(isGuidePage) {
	
		$("#banner img").hide();
		$("#banner img:first").show();
	
		$(".guideDesc").hide();
		
		$('ul#thumbs li a, .Whatdotext ul li a').click(function(){

			//if(!isGallery && !isGuidePage) {
			//	return true;
			//}

			
			$(".guideDesc").hide();
			
			$(".guideDesc[rel='"+$(this).attr('href')+"']").show();
					
			$("#banner img").fadeOut();
			
			/*
			var s = $("img",$(this)).attr('src');
			
			s = str_replace('_thumb','_large',s);
			
			$("#banner img[src='"+s+"']").fadeIn();			
			*/
			
			var i = $(this).index();
			var imgs = $("#banner img");
			$(imgs[i]).fadeIn();
			
			
			return false;
		
		});
	} else {
		$(".popup").hide();
		
		$('ul#thumbs li a, .Whatdotext ul li a').hover(
			function(){
				$(".popup").hide();
				$(".popup[rel='"+$(this).attr('href')+"']").fadeIn();
			},
			function(){
				$(".popup").fadeOut();
			}
		);
	}
	
	$(".guideDesc a").click(function(){
	
		if($("#guideFormWrapper").length == 0) {
			return true;
		}
	
	
		var winSize = getWindowSize();
		var winScroll = getScrollXY();
		
		var overlay_width = 656;
		var overlay_height = 526;
		
		var tp = ((winSize[1] - overlay_height) / 2) + winScroll[1];
		var lf = ((winSize[0] - overlay_width) / 2) + winScroll[0];
		
		var tp = parseInt(tp);
		var lf = parseInt(lf);
		
		$("#guideFormWrapper").css({
			'top':tp+'px',
			'left':lf+'px'
		}).show();
		
		
		
		return false;
	
	});

	/********************************
	 *
	 *	Guide page form ajax submit
	 *
	 *****/
	
	$("form#guideDownloadForm").submit(function(){
	
		var d = $(this).serialize();
		
		$.ajax({
			url:'/download.php',
			data:d,
			type:'POST',
			complete:function(a,b) {
				if(b == 'success') {
					$("form#guideDownloadForm").parent().empty().append("<a href='#'>&nbsp;</a>"+a.responseText);
				}
				
			}
		
		});
	
		return false;
	});
	
	$("#guideFormWrapper a").empty().append("&nbsp;");
	
	$("#guideFormWrapper a").click(function(){
		$("#guideFormWrapper").hide();
		return false;
	});
	
	/********************************
	 *
	 *	Contact Form
	 *
	 *****/

	$("#contactForm").click(function(){
	
		var winSize = getWindowSize();
		var winScroll = getScrollXY();
		
		var overlay_width = 656;
		var overlay_height = 526;
		
		var tp = ((winSize[1] - overlay_height) / 2) + winScroll[1];
		var lf = ((winSize[0] - overlay_width) / 2) + winScroll[0];
		
		var tp = parseInt(tp);
		var lf = parseInt(lf);
		
		$("#contactFormWrapper").css({
			'top':tp+'px',
			'left':lf+'px'
		}).show();
		
		
		
		return false;
	
	});

	$("#contactFormWrapper a").empty().append("&nbsp;");
	
	$("#contactFormWrapper a").click(function(){
		$("#contactFormWrapper").hide();
		return false;
	});
	
	$("form#contactFormForm").submit(function(){
	
		var d = $(this).serialize();
		
		$.ajax({
			url:'/contact.php',
			data:d,
			type:'POST',
			complete:function(a,b) {
				if(b == 'success') {
					$("form#contactFormForm").parent().empty().append("<a href='#'>&nbsp;</a>"+a.responseText);
				}
				
			}
		
		});
	
		return false;
	});


	/********************************
	 *
	 *	 Google Map
	 *
	 *****/

	$("#gMap").click(function(){
	
		var winSize = getWindowSize();
		var winScroll = getScrollXY();
		
		var overlay_width = 924;
		var overlay_height = 743;
		
		var tp = ((winSize[1] - overlay_height) / 2) + winScroll[1];
		var lf = ((winSize[0] - overlay_width) / 2) + winScroll[0];
		
		var tp = parseInt(tp);
		var lf = parseInt(lf);
		
		$("#gMapWrapper").css({
			'top':tp+'px',
			'left':lf+'px'
		}).show();
		
		
		
		return false;
	
	});

	$("#gMapWrapper a").empty().append("&nbsp;");
	
	$("#gMapWrapper a").click(function(){
		$("#gMapWrapper").hide();
		return false;
	});
	
	if(isGuidePage && t_count > 0) {
		$("#gThumbs").prepend("<span class='thumb_instruct'>Please click on the thumbnails to download the guide</span>");
	}

	if(isGallery && t_count > 0) {
		$("#gThumbs").prepend("<span class='thumb_instruct'>Please hover over the thumbnails to see each image</span>");
	}


	if(!isGuidePage && !isGallery && !isTeamPage && t_count > 0) {
		
		var section = $("body").attr('rel');
		
		section = section+'';
		
		if(undefined == section || section == 'section') {
			section = '';
		}
		
		$("#gThumbs").prepend("<span class='thumb_instruct'>Please click on the thumbnails to navigate "+(section != '' ? "<i>"+section+"</i>" : "")+"</span>");
		
		if(section == 'News') {
			isNewsPage = true;
		}
	}
	
	if(isNewsPage) {
		$("div#content div.Welcometext div.Graytext ul li a").addClass('absoluteOrange');
	}



});

