// mYm Functions v 1.2 - brent@mimoymima.com
// last edited: July 25, 2009
// last change: Adding History Plugin, figure out how to use it!

// this needs to stay outside of the document ready function and cannot use $ for some reason...
function fadeFlash() {
	jQuery('.flashmovie').fadeOut('slow', function() {
	jQuery('#clients #Content').fadeIn('slow');
	});
}

// Document ready Function customized to work with prototype which we use for lightview
	
jQuery.noConflict();
jQuery(document).ready(function($) {

//--fix second column spacing for the wp columns
	$('.post_column_1').eq(1).addClass('SecondCol');

//--rollover for thumbnails
	$('.pr ul.thumbs li, .adv ul.thumbs li').hover(
      function () {
        $(this).css('border-color','black');
      }, 
      function () {
        $(this).css('border-color','#C33');
      }
	);

//--hide some content on page load for these pages:
	// - we got rid of the flash so keep this off unless we get another vid for this page - $('#clients #Content').hide();
	
//-----LOAD PLUGINS

	//-----History Plugin (fixes back button and allows deep linking) --by Taku Sano http://www.mikage.to/jquery/jquery_history.html
	jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyIframeSrc:undefined,historyInit:function(callback,src){jQuery.historyCallback=callback;if(src)jQuery.historyIframeSrc=src;var current_hash=location.hash.replace(/\?.*$/,'');jQuery.historyCurrentHash=current_hash;if(jQuery.browser.msie){if(jQuery.historyCurrentHash==''){jQuery.historyCurrentHash='#';} jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+ (jQuery.historyIframeSrc?' src="'+jQuery.historyIframeSrc+'"':'') +'></iframe>');var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=current_hash;} else if(jQuery.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.lastHistoryLength=history.length;jQuery.isFirst=true;} if(current_hash) jQuery.historyCallback(current_hash.replace(/^#/,''));setInterval(jQuery.historyCheck,100);},historyAddHistory:function(hash){jQuery.historyBackStack.push(hash);jQuery.historyForwardStack.length=0;this.isFirst=true;},historyCheck:function(){if(jQuery.browser.msie){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash.replace(/\?.*$/,'');if(current_hash!=jQuery.historyCurrentHash){location.hash=current_hash;jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}else if(jQuery.browser.safari){if(jQuery.lastHistoryLength==history.length&&jQuery.historyBackStack.length>jQuery.lastHistoryLength){jQuery.historyBackStack.shift();} if(!jQuery.dontCheck){var historyDelta=history.length-jQuery.historyBackStack.length;jQuery.lastHistoryLength=history.length;if(historyDelta){jQuery.isFirst=false;if(historyDelta<0){for(var i=0;i<Math.abs(historyDelta);i++)jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());}else{for(var i=0;i<historyDelta;i++)jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());} var cachedHash=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(cachedHash!=undefined){jQuery.historyCurrentHash=location.hash.replace(/\?.*$/,'');jQuery.historyCallback(cachedHash);}}else if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]==undefined&&!jQuery.isFirst){if(location.hash){var current_hash=location.hash;jQuery.historyCallback(location.hash.replace(/^#/,''));}else{var current_hash='';jQuery.historyCallback('');} jQuery.isFirst=true;}}}else{var current_hash=location.hash.replace(/\?.*$/,'');if(current_hash!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}},historyLoad:function(hash){var newhash;hash=decodeURIComponent(hash.replace(/\?.*$/,''));if(jQuery.browser.safari){newhash=hash;} else{newhash='#'+hash;location.hash=newhash;} jQuery.historyCurrentHash=newhash;if(jQuery.browser.msie){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;jQuery.lastHistoryLength=history.length;jQuery.historyCallback(hash);} else if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(hash);var fn=function(){jQuery.dontCheck=false;};window.setTimeout(fn,200);jQuery.historyCallback(hash);location.hash=newhash;} else{jQuery.historyCallback(hash);}}});

	//-----preload CSS Images Plugin -- by Scott Jehl, http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
	//;jQuery.preloadCssImages=function(settings){settings=jQuery.extend({statusTextEl:null,statusBarEl:null,errorDelay:999,simultaneousCacheLoading:2},settings);var allImgs=[],loaded=0,imgUrls=[],thisSheetRules,errorTimer;function onImgComplete(){clearTimeout(errorTimer);if(imgUrls&&imgUrls.length&&imgUrls[loaded]){loaded++;if(settings.statusTextEl){var nowloading=(imgUrls[loaded])?'Now Loading: <span>'+imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length-1]:'Loading complete';jQuery(settings.statusTextEl).html('<span class="numLoaded">'+loaded+'</span> of <span class="numTotal">'+imgUrls.length+'</span> loaded (<span class="percentLoaded">'+(loaded/imgUrls.length*100).toFixed(0)+'%</span>) <span class="currentImg">'+nowloading+'</span></span>')}if(settings.statusBarEl){var barWidth=jQuery(settings.statusBarEl).width();jQuery(settings.statusBarEl).css('background-position',-(barWidth-(barWidth*loaded/imgUrls.length).toFixed(0))+'px 50%')}loadImgs()}}function loadImgs(){if(imgUrls&&imgUrls.length&&imgUrls[loaded]){var img=new Image();img.src=imgUrls[loaded];if(!img.complete){jQuery(img).bind('error load onreadystatechange',onImgComplete)}else{onImgComplete()}errorTimer=setTimeout(onImgComplete,settings.errorDelay)}}function parseCSS(sheets,urls){var w3cImport=false,imported=[],importedSrc=[],baseURL;var sheetIndex=sheets.length;while(sheetIndex--){var cssPile='';if(urls&&urls[sheetIndex]){baseURL=urls[sheetIndex]}else{var csshref=(sheets[sheetIndex].href)?sheets[sheetIndex].href:'window.location.href';var baseURLarr=csshref.split('/');baseURLarr.pop();baseURL=baseURLarr.join('/');if(baseURL){baseURL+='/'}}if(sheets[sheetIndex].cssRules||sheets[sheetIndex].rules){thisSheetRules=(sheets[sheetIndex].cssRules)?sheets[sheetIndex].cssRules:sheets[sheetIndex].rules;var ruleIndex=thisSheetRules.length;while(ruleIndex--){if(thisSheetRules[ruleIndex].style&&thisSheetRules[ruleIndex].style.cssText){var text=thisSheetRules[ruleIndex].style.cssText;if(text.toLowerCase().indexOf('url')!=-1){cssPile+=text}}else if(thisSheetRules[ruleIndex].styleSheet){imported.push(thisSheetRules[ruleIndex].styleSheet);w3cImport=true}}}var tmpImage=cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);if(tmpImage){var i=tmpImage.length;while(i--){var imgSrc=(tmpImage[i].charAt(0)=='/'||tmpImage[i].match('://'))?tmpImage[i]:baseURL+tmpImage[i];if(jQuery.inArray(imgSrc,imgUrls)==-1){imgUrls.push(imgSrc)}}}if(!w3cImport&&sheets[sheetIndex].imports&&sheets[sheetIndex].imports.length){for(var iImport=0,importLen=sheets[sheetIndex].imports.length;iImport<importLen;iImport++){var iHref=sheets[sheetIndex].imports[iImport].href;iHref=iHref.split('/');iHref.pop();iHref=iHref.join('/');if(iHref){iHref+='/'}var iSrc=(iHref.charAt(0)=='/'||iHref.match('://'))?iHref:baseURL+iHref;importedSrc.push(iSrc);imported.push(sheets[sheetIndex].imports[iImport])}}}if(imported.length){parseCSS(imported,importedSrc);return false}var downloads=settings.simultaneousCacheLoading;while(downloads--){setTimeout(loadImgs,downloads)}}parseCSS(document.styleSheets);return imgUrls};
	//$.preloadCssImages();
	
	
	
//-----Cascade Comment Opacity for Wordpress by Brent Lagerman and Jack Hoge
	
	function cascadeBkg(x)
	{
		var bkgColor = $('.commentlist .thread-'+x+' .vcard').css("background-color");
	
		$('.commentlist .thread-'+x).each(function(){
			$(this).find('.vcard').each(function(intIndex){
			  	$(this).css('background', 'none');
			  	$(this).parent()
			  		.before('<span class="thespan" style="background: '+bkgColor+'; position: absolute; top: 0; left: 0; width: 100%; height: 63px;"></span>')
			  		.parent().find('.thespan')
					.fadeTo("0", 1 - intIndex * 0.10);
			});
		});
	}
	//call the cascadeBkg function for even and odd threads
	cascadeBkg('odd');
	cascadeBkg('even');
	
	
//-----Show and Hide Stuff!
	$('.Hide').hide(); // hide anything with the class of .Hide

	$('.Toggle')
		.addClass('MakeLink') // make headings look like links
		.click(function() {
    		$(this).next().slideToggle('normal');
	});
	
	
//-----Hide Javascript Warning when javascript is active
	$('.Indicator').hide();


//-----Use Gallerific on pr and adv pages
	$('.adv .Entry ul').addClass('thumbs');
	$('.adv .Entry ul a').addClass('thumb');
	
	if ($('.adv #gallery').length) {
		$('.adv #gallery').galleriffic('#thumbs', {
			delay: 3000, // in milliseconds
			numThumbs: 20, // The number of thumbnails to show page
			preloadAhead: -1, // Set to -1 to preload all images
			enableTopPager: false,
			enableBottomPager: false,
			imageContainerSel: '#gallery', // The CSS selector for the element within which the main slideshow image should be rendered
			controlsContainerSel: '', // The CSS selector for the element within which the slideshow controls should be rendered
			captionContainerSel: '', // The CSS selector for the element within which the captions should be rendered
			loadingContainerSel: '#gallery', // The CSS selector for the element within which should be shown when an image is loading
			renderSSControls: false, // Specifies whether the slideshow's Play and Pause links should be rendered
			renderNavControls: false, // Specifies whether the slideshow's Next and Previous links should be rendered
			playLinkText: 'Play',
			pauseLinkText: 'Pause',
			prevLinkText: 'Previous',
			nextLinkText: 'Next',
			nextPageLinkText: 'Next &rsaquo;',
			prevPageLinkText: '&lsaquo; Prev',
			enableHistory: false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes 
			autoStart: false, // Specifies whether the slideshow should be playing or paused when the page first loads 
			onChange: undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
			onTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... }
			onTransitionIn: undefined, // accepts a delegate like such: function() { ... }
			onPageTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... }
			onPageTransitionIn: undefined // accepts a delegate like such: function() { ... }
		});
	}
	
//-----Meet The People page-----//
	
	if ($('#person-container').length){ 
		$('#Container').append('<span id="loader">Loading...</span>');
		$('#loader').show();
	}
	
    var hash = window.location.hash.substr(1);
	if(hash.length < 1) { 
			var toLoad = 'chris-spring';
			$('#person-container').fadeOut('fast', showFrames(toLoad));
	}
	
    var href = $('#scrolling-people .ajaxify').each(function(){	
        var href = $(this).attr('href');
        if(hash==href.substr(23,href.length)){
            var toLoad = hash;
			$('#person-container').fadeOut('fast', showFrames(toLoad));
		}
    });
	
	function showFrames(arg){
        $('#person-container').load('/about/meet-the-people/' + arg + ' #PersonContent', function(){
			$('img').load(function(){
				$('#person-container').fadeIn(300, hideLoader);
			});
		});
	}
	
	function hideLoader(){
		$('#scrolling-people').css('visibility', 'visible');
		$('#footer-img').fadeIn('fast');
		$('#loader').fadeOut('normal');
	}

	$('#scrolling-people .ajaxify').click(function(){
		window.location.hash = $(this).attr('href').substr(23,$(this).attr('href').length);
		$('#Container').append('<span id="loader">Loading...</span>');
		$('#person-container, #footer-img').fadeOut(300, loadStuff($(this)));
		$('#loader').show();
		
		function loadStuff(arg){
			var toLoad = arg.attr('href') + ' #PersonContent';
			$('#person-container').load(toLoad, function(){
				$('img').load(function(){
					$('#person-container').fadeIn(1000, hideLoader);
					});
			});
		}
		
		return false;
	});

//-----Apply a carousel to the people's thumbnails on the Meet The People page
	$('#mycarousel').jcarousel({scroll: 6});


//-----Put filetype in parentheses--------//

    // pdfs get applied to all pdf links, not just in .pr or .adv
	$("a[href$='pdf']").append(' (pdf)');

	$(".pr a[href$='mp4']").append(' (video)');
	$(".pr a[href$='mpg']").append(' (video)');
	$(".pr a[href$='flv']").append(' (video)');
	$(".pr a[href$='mov']").append(' (video)');
	$(".pr a[href*='youtube']").append(' (video)');
	
	
	$(".adv a[href$='mp4']").append(' (video)');
	$(".adv a[href$='mpg']").append(' (video)');
	$(".adv a[href$='mov']").append(' (video)');
	$(".adv a[href$='flv']").append(' (video)');
	$(".adv a[href*='youtube']").append(' (video)');

	$(".ClientReview a[href$='mp4']").append(' (video)');
	$(".ClientReview a[href$='mpg']").append(' (video)');
	$(".ClientReview a[href$='flv']").append(' (video)');
	$(".ClientReview a[href$='mov']").append(' (video)');
	$(".ClientReview a[href*='youtube']").append(' (video)');
	
//------Open PDF's in new windows----------//
$("a[href$='pdf']").attr('target', '_blank');
	
//-----Fire Fancybox for YouTube video links-------//
	$("a[href*='youtube']").fancybox({'centerOnScroll': false });


//-----Fire Fancybox for "More Clients" link-------//
	if ($('a#more-clients-from-group').length) {
		$("a#more-clients-from-group").fancybox({
			'hideOnContentClick' : false, 
			'frameWidth':	568,
			'frameHeight':	568,
			'centerOnScroll': false
		});
	}

//------Use qTip and Fancybox on Client Review links------//
  $('.ClientReview a').not("a[href$='pdf']").addClass('iframe');
  
  $('.ClientReview a').not("a[title='']").qtip({
    position: {
	corner: { target: 'topMiddle', tooltip: 'leftMiddle' }
   },
    style: { 
      name: 'light',
      width: 400,
      border: { width: 5, radius: 9 }
    }
  });
  
  $('.ClientReview a.iframe').fancybox({
    frameHeight: .9 * $(window).height(),
    frameWidth: .9 * $(window).width()
  });

//-----Get rid of linking behavior on Work Pages-----//
var im = $('.pr #thumbs img');
var a = im.closest('a');
im.insertBefore(a);
a.remove();

//-----Make popup links open in new window-------//
//	$('#fancy_content .client-box a').click(function(){
//	  window.open(this.href);
//	  return false;
//	});
});