// == DEBUG SETUP =========================================
if(window['debug'] === undefined) {
  window.debug = function(q,w,e,r){  
    try { if (typeof console != 'undefined') console.log.apply(console,arguments); } 
    catch(err){ if (typeof console != 'undefined')  console.log(q,w,e,r); }
  }
}

// ===============
// = OBJECT: MANCC =
// ===============
window.MANCC = {
	
	// common domready code that runs on all pages
	common:{
		
		// code effecting visual look of the page (reason why it fires first / inits)
		init:function()
		{
			var deviceIphone = "iphone";
			var deviceIpod = "ipod";
			var deviceIpad = "ipad";
			var uagent = navigator.userAgent.toLowerCase();
			
			// set the ie6 variable to true if they're using ie7
			jQuery.browser.ie7 = (jQuery.browser.msie && jQuery.browser.version == 7);
			jQuery.browser.ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);
			jQuery.browser.ios = (uagent.search(deviceIphone) > -1 || uagent.search(deviceIpad) > -1 || uagent.search(deviceIpod) > -1)
			if (jQuery.browser.ie6){ jQuery('body').addClass('ie6'); }; // MANCC.common.pngfix('');
			if (jQuery.browser.ie7){ jQuery('body').addClass('ie7') };
			if (jQuery.browser.msie){ jQuery('body').addClass('ie') };
			if (jQuery.browser.ios){ jQuery('body').addClass('ios') };

			//fire bug lite - to activate firebug lite, add "?fbug=true" to URL as querystring
			if (!!document.location.search.match(/fbug=true/)){ jQuery.getScript('https://getfirebug.com/releases/lite/beta/firebug.jgz',function(){ firebug.init(); }); }

			// catch ajax errors
			jQuery(document).ajaxError(function(){ debug('ajax error:',arguments); });

      // set up embedded vimeo videos
      if(jQuery('div.vimeo').length){ MANCC.common.setup_videos() }
      
      // set up mp3 flash players
      if(jQuery('div.flash_mp3').length){ MANCC.common.setup_mp3s() }
      
      // split the artist list into columns
      jQuery('#nav .artists div ul').easyListSplitter({ colNumber: 5 });
      
      // anything slider
      jQuery('#main_artist .slideshow ul').anythingSlider({
        autoPlay            : false,
        buildNavigation     : false,
        animationTime       : 350
      });
      // add a description span based on the alt tag
      jQuery('#main_artist .slideshow li img').each(function(){
        alt = this.alt
        jQuery(this).closest('li').append('<span class="alt">'+ alt +'</span>');
      });

      // set click events for utility tabs
      jQuery('#util h3 a').click(function(){
        parentLI = jQuery(this).closest('li');
        if(parentLI.hasClass('open')){
          parentLI.removeClass('open')
        } else {
          jQuery('#util li').removeClass('open');
          parentLI.addClass('open');
        }
      });
      
      jQuery("#util input[type='text'], #util input[type='password']").clearField();

      jQuery("#util form").bind("submit", function(event){
        // if there are any invalid fields in here bail on submission
        if(jQuery(this).find(".vanadium-invalid").length > 0){ return false; }
      });
      
      jQuery('#newsletter form input[type="submit"]').bind("click", function(event){
          // set as invalid if value is "Name"
          if(jQuery('#newsletter input#name').val()=="Name"){ jQuery('#newsletter input#name').addClass(':required vanadium-invalid clearFieldBlurred'); }
      });
      
      
      jQuery( "#content_wrapper" ).bind("mouseenter", function(event){ 
        jQuery('#util li').removeClass('open');
      });
      
      jQuery( "#nav > li, #footer li.investors, #footer li.fsu" ).hover(
        function(){
          hoverLI = jQuery(this)
          hoverLI.addClass('open')
        },
        function(){
          hoverLI = jQuery(this)
          hoverLI.removeClass('open');
        }
      );
      
      // remove the unecessary commas
      jQuery('p.tags').each(function(){
        jQuery(this).html(jQuery(this).html().replace(/,/g,''));
      });
      jQuery('p.tags a').bind('click', function(){ return false; })
      
      
      jQuery('a.news').click(function(){
        target = this.href
        jQuery('iframe#blog_post')[0].src = target
        setTimeout(function(){ jQuery('#post_container').show() }, 600);
        return false;
      })
      
      jQuery('#post_container').click( function(){jQuery(this).hide();} );
      
      jQuery('#content_wrapper').bind('click', function() {
        if(jQuery('#main_artist.out').length > 0)
        {
          MANCC.common.hide_main_artist();
        }
      });
      
		},
		
		//code that doesn't effect the look of the page (hence, "finalize")
		finalize: function()
		{		
      if(window.location.href.indexOf('grid') > 0)
      {
        jQuery('body').addClass('grid');
      }
		},
		
		// pngfix for legacy POS browsers
		// USE: MANCC.common.pngfix('img.bigProdShot,a.thumb');
		pngfix: function(sel)
		{
			// ensure that conditional comments pull in the DD_belatedPNG js. Otherwise this will just return.
			if (typeof DD_belatedPNG == 'undefined'){  
				return; 
			} else {
				// delay pngfix until window onload
				jQuery(window).load(function(){ 
					jQuery(sel).each(function(){ 
						DD_belatedPNG.fixPng(arguments[1]); 
					});
				}); 
			}
		}, // MANCC.common.pngfix

    show_main_artist: function(){
      
      jQuery('a.handle').click(function(){
        jQuery('#main_artist').animate({
          left: '46px'
        },{
          duration: 760, 
          specialEasing: { left: 'easeOutQuad' }, 
          complete: function(){
            jQuery('a.handle').hide()
          }
        }).addClass('out');
        return false;
      });
      
    },
    
    hide_main_artist: function(){
      
      jQuery('#main_artist').animate({
        left: '-450px'
      },{
        duration: 650, 
        specialEasing: { left: 'easeOutQuad' }, 
        complete: function(){
          jQuery('a.handle').show()
        }
      }).removeClass('out');
      
    },
		
		setup_videos: function()
		{
		  videos = jQuery('div.vimeo');
		  videos.each(function(){
		    
			this.id = "video"+String(Math.ceil(100*Math.random()));
			video_width = jQuery(this).width();
			video_height = jQuery(this).height();
			vimeo_url = this.className;
			vimeo_url = vimeo_url.split('/');
			vimeo_id  = vimeo_url[vimeo_url.length-1];
        
			var flashvars = {
			  'clip_id': vimeo_id,
			  'server': 'vimeo.com',
			  'show_title': 0,
			  'show_byline': 0,
			  'show_portrait': 0,
			  'fullscreen': 1,
			  'js_api': 1
			}
			var parObj = {
			  'swliveconnect': true,
			  'fullscreen': 1,
			  'allowscriptaccess': 'always',
			  'allowfullscreen': true,
			  'wmode': 'transparent'
			};
			var attObj = {}
			//swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf", this.id, video_width, video_height, "9.0.28",'',flashvars, parObj, attObj);
			jQuery(this).html('<iframe src="http://player.vimeo.com/video/'+vimeo_id+'?title=0&byline=0&portrait=0" width="'+video_width+'" height="'+video_height+'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>');
        
		  })

		},
		
		setup_mp3s: function()
		{
		  mp3s = jQuery('.flash_mp3');
		  mp3s.each(function(){
		    this.id = "mp3"+String(Math.ceil(100*Math.random()));
        mp3_width  = jQuery(this).width();
    		mp3_height = jQuery(this).height();
    		
    		var flashvars = {
          'artist'    : this.getAttribute("data-artist"),
      		'title'     : this.getAttribute("data-title"),
      		'still'     : this.getAttribute("data-still"),
      		'mp3'       : this.getAttribute("data-mp3"),
      		'textcolor' : this.getAttribute("data-color")
        }
        var parObj = {
          'allowfullscreen': true,
          'wmode': 'transparent'
        };
        var attObj = {}
        swfobject.embedSWF("/flash/audioplayer.swf", this.id, mp3_width, mp3_height, "9.0.28",'',flashvars, parObj, attObj);
		  })
		  

  		

		}

	}, // end of MANCC.common
	
	// ===========================================================================
	// = The following are for the pages. They're defined by the 'id' in <body>. =
	// = MANCC.Util Looks to see what body id is and then fires off         =
	// = the page-specific methods.                                              =
	// ===========================================================================
	
	home:{
		
		init: function()
		{
			//homepage specific PNGFIX ... same thing for the rest of the id's below, mgmt, news, etc	
			if (jQuery.browser.ie6){ /* MANCC.common.pngfix('#'); */ }
			
			jQuery('#featured_artists ul').cycle({ 
          next:   '#next', 
          speed:  'fast',
          timeout: 0
      });
      
      if(jQuery('#featured_artists li').length < 2)
      {
        jQuery('#featured_artists').addClass('solo').find('h2');
      }
		
		}	
		
	}, // end MANCC.homepage()

  news:{
    
    init: function()
    {
      jQuery('#tours a.tag:contains("Tour"),#misc a.tag:contains("Tour"),#tours a.tag:contains("Entrypoints"),#misc a.tag:contains("Entrypoints"),#tours a.tag:contains("Research Needs"),#misc a.tag:contains("Research Needs")').remove();
      MANCC.common.show_main_artist();
    }
    
  },

  artist:{
    init: function()
    {
      var social_media_sites=["facebook","twitter","blogger","flickr","delicious","linkedin","email","myspace","stumbleupon","google","rss","wordpress","vimeo"];
      var links = jQuery("#links a");
      links.each(function(){
        for(i=0;i<social_media_sites.length;i++)
        {
          if(this.href.indexOf(social_media_sites[i])>0)
          {
            this.className = "external "+social_media_sites[i];
          }
        }
        jQuery(this).attr('target', '_blank');
      });
      
      // set up the handle on the left side of the screen to pull out the main artist info
      MANCC.common.show_main_artist();
      
      jQuery('#bio p, .post .details p').expander({
        slicePoint:410,
        userCollapseText: 'collapse',
        userCollapsePrefix: '&nbsp;&nbsp;&nbsp;',
      });
      
      if(jQuery('#content_wrapper').height() < jQuery('#sidebar').height())
      {
        current_height = jQuery('#content_wrapper').css('min-height',jQuery('#sidebar').height()+"px");
      }
      
      // set up carousel, add active class to first child, move up the dom and find all anchor tags and set their href to numbered panels
      jQuery(".carousel li:first-child").addClass("active")
      jQuery(".carousel").carousel( { dispItems: 5 } ).each(function(){
	jQuery(this).find('a').each(function(index){
	  this.href="#outerpanel"+index;
	});
      });
      
      jQuery(".carousel-wrap a").click(function(){
        i = this.href.split('#')[1];
        i = parseInt(i.replace('outerpanel',''));

	// details_div is the top parent element for these projects. 
	// if we don't hitch our events and work to that anchor then we'll be acting
	// on elements across the whole page - not in the context of the project.
	// so, nutshell, we've created a context for each project's thumbnail interaction

	details_div = jQuery(this).closest('.details');
        
        // remove active class from the panel and the thumbnail carousel
	details_div.find('.multimedia > .outerpanel').removeClass('active');
	details_div.find('.carousel-wrap li').removeClass('active');
        
        // add active class to the main panel we're targeting
        jQuery(details_div.find('.multimedia > .outerpanel')[i-1]).addClass('active');
        jQuery(details_div.find('.carousel-wrap li')[i-1]).addClass('active');
  
        // set up the anything slider for the main panel if that's what's showing up

        jQuery('.outerpanel.slideshow ul:visible').anythingSlider({
          autoPlay            : false,
          buildNavigation     : false
        })
        
        // set up video if that's what's showing up
        MANCC.common.setup_videos();

        // set up mp3 if that's what's showing up        
        MANCC.common.setup_mp3s();

        return false
      });

      
      jQuery(".multimedia .outerpanel:first-child").addClass("active");
      
      if(jQuery('div.vimeo:visible').length){ MANCC.common.setup_videos(); }
      if(jQuery('div.flash_mp3:visible').length){ MANCC.common.setup_mp3s(); }
      
      // add description from alt tag to a span
      jQuery('.outerpanel.slideshow li img').each(function(){
        alt = this.alt
        jQuery(this).closest('li').append('<span class="alt">'+ alt +'</span>');
      })
      
      // anything slider
      jQuery('.outerpanel.slideshow.active ul').anythingSlider({
        autoPlay            : false,
        buildNavigation     : false
      })
      
    }
  },
	
	artists:{
		init: function()
		{
		  // set up the handle on the left side of the screen to pull out the main artist info
      MANCC.common.show_main_artist();
		  		  
		  jQuery('#info p .description').html(jQuery('#media .description').html());
		  jQuery("#key_filter ul li label").tooltip({
        relative: true,
        position: 'bottom right',
        offset: [-5, -15]
      }).find('input').click(function(){
        // now work with the checkboxes in the labels
        dept = this.id
        if (jQuery(this).is(":checked")){
          jQuery("#artists_list li."+dept).fadeIn('slow');
        } else {
          jQuery("#artists_list li."+dept).fadeOut('slow');
        }
        jQuery(this).blur();
      });
      jQuery("abbr").each(function(){ if(this.innerHTML == "()"){ jQuery(this).remove(); }});
      jQuery('#artists_list ul').easyListSplitter({ colNumber: 4 });

      // anything slider
      setTimeout("artists_slider()", 3000);

      
		}
	},
	
	supporting_main:{
	  init: function()
	  {
	    jQuery("input.text, textarea").clearField();
	    MANCC.common.show_main_artist();
	    
	    // if the querystring is the same as a value in the select drop-down, set it and forget it
	    qs = window.location.href.split("contact?");
	    if(qs[1]){
	      qs = qs[1].replace("%20", " ");
	      jQuery('option[value="'+ qs +'"]').attr('selected', true);
	    }
	    
	  }
	},
	
	supporting_sub:{
	  init: function()
	  {
	    MANCC.common.show_main_artist();
	    
	    // anything slider
      jQuery('#large_slideshow ul').anythingSlider({
        autoPlay            : false,
        buildNavigation     : false
      });
      // add a description span based on the alt tag
      jQuery('#large_slideshow li img').each(function(){
        alt = this.alt
        jQuery(this).closest('li').append('<span class="alt">'+ alt +'</span>');
      });
      
	  }
	}
	
} // END OF the MANCC object literal

// ==========================================================================================
// = Here's the magic that triggers the dom ready code based on page id.                    =
// = Based on Paul Irish's exceptional code:                                                =
// = http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/  =
// ==========================================================================================

// ... don't touch!  Tsk tsk.

UTIL = {

	fire: function(func,funcname, args)
	{
		var namespace = MANCC;  // indicate your obj literal namespace here
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function')
		{
  			namespace[func][funcname](args);
		} 
	}, // end of MANCC.util.fire

	loadEvents: function()
	{

		var bodyId = document.body.id;

		// hit up common first.
		UTIL.fire('common');

		//hit page specific via  body ID
		UTIL.fire(bodyId);
		UTIL.fire('common','finalize');

	}

} // end of UTIL

// LET 'ER RIP! ===================
jQuery(document).ready(UTIL.loadEvents);
// ================================


function artists_slider()
{
  jQuery('#media .slideshow ul').anythingSlider({
    autoPlay : false,
    resizeContents : false
  });
}

