
// Switch to no conflict mode
jQuery.noConflict();

// Slidebox function
(function ($) {
  /* Add a function to jQuery to slidebox any elements */
  jQuery.fn.slidebox = function() {
    var slidebox = this;
    var originalPosition = slidebox.css('right');
    var boxAnimations = {
      open: function() {
        slidebox.animate({
          'right': '0px'
        }, 200);
      },
      close: function() {
        slidebox.stop(true).animate({
          'right': originalPosition
        }, 50);
      }
    }

    $(window).scroll(function() {
      var distanceTop = $('#last').offset().top - $(window).height();

      if ($(window).scrollTop() > distanceTop) {
        boxAnimations.open();
      } else {
        boxAnimations.close();
      }
    });
  }

  $(function() { /* onload */
    if (jQuery('#last').length > 0) {
      $('#slidebox').slidebox();
      $('#close').click(function() {
        $('#slidebox').hide();
      });
    }
  });
})(jQuery);

// What is BMI? panel
function what_is_bmi_panel() {

    // Set default cookie    
  var what_is_bmi = jQuery.cookie('what_is_bmi');
  if (what_is_bmi == null) {
    jQuery.cookie('what_is_bmi', 'show', { path: '/', domain: 'bmi.com', expires: 3650 });
    var what_is_bmi = jQuery.cookie('what_is_bmi');
  }
  
  // Show panel if user hasn't closed it
  if (what_is_bmi == 'show') {
    jQuery('.what_is_bmi').css('display','block');
  }
  
  // Hide panel when close box is clicked
  jQuery('.what_is_bmi img').click(function() {
    jQuery('.what_is_bmi').slideUp(400);
    jQuery.cookie('what_is_bmi', 'hide', { path: '/', domain: 'bmi.com', expires: 3650 });
  });
  
}

// Show header panel
function show_header_panel() {

  var fade_tab_on_tab_hover_out;
  var fade_panel_on_tab_hover_out;
  var fade_panel_on_panel_hover_out;

  // Preload header images
  var image1 = jQuery('<img />').attr('src', '/images/app/header_line.gif');
  var image2 = jQuery('<img />').attr('src', '/images/app/header_line_hover.gif');
  var image3 = jQuery('<img />').attr('src', '/images/app/header_panel.png');
  var image4 = jQuery('<img />').attr('src', '/images/app/go.png');
  var image5 = jQuery('<img />').attr('src', '/images/app/button_left.png');
  var image6 = jQuery('<img />').attr('src', '/images/app/button_right.png');

  // TABS
  jQuery("#nav li").hover(
    
    // HOVER OVER
    function () {
      
      // Get active tab/panel
      var active = jQuery(this).attr("id");
      
      // If active panel is fading out, stop fade and reset opacity
      clearTimeout(fade_panel_on_panel_hover_out); 
      jQuery('#panels .panel.' + active).stop();
      jQuery('#panels .panel.' + active).css('opacity', '1');
      
      // Remove highlight from other tabs
      jQuery('#nav li').each(function (i) {
        if (jQuery(this).attr("id") != active) {
          jQuery(this).removeClass('hovered');
        }
      });
            
      // Hide all panels (except the panel for the selected tab)
      jQuery('#panels .panel').each(function (i) {
        if (jQuery(this).attr("class").split(' ')[0] != active) {
          jQuery(this).hide();
        }
      });
      
      // Show active panel
      jQuery('#panels .' + active).show();
    }, 
    
    // HOVER OUT
    function () {
      
      // Get active tab/panel
      var active = jQuery(this).attr("id");
      
      // Remove highlight from tab
      fade_tab_on_tab_hover_out = setTimeout(function() {jQuery('#' + active).removeClass('hovered');}, 50);       
      
      // Fade out panel (if tab or panel isn't selected)
      fade_panel_on_tab_hover_out = setTimeout(function() {jQuery('#panels .panel.' + active).fadeOut(500);}, 50);             
      
    }
  );
  
  // PANELS
  jQuery("#panels .panel").hover(
    
    // HOVER OVER
    function () {
      
      // Get active tab/panel
      var active = jQuery(this).attr("class").split(' ')[0];
            
      // Stop panels from fading (if mousing down from tabs)
      clearTimeout(fade_tab_on_tab_hover_out); 
      clearTimeout(fade_panel_on_tab_hover_out);
      clearTimeout(fade_panel_on_panel_hover_out); 
      
      // If panel is fading out, stop fade and reset opacity
      jQuery('#panels .panel').stop();
      jQuery('#panels .panel').css('opacity', '1');
    
      // Select tab (since we're not hovering over it)
      jQuery("#" + active).addClass('hovered');
            
    }, 
    
    // HOVER OUT
    function () {
      // Get active tab/panel
      var active = jQuery(this).attr("class").split(' ')[0];
            
      // Fade out panel and tab
      fade_panel_on_panel_hover_out = setTimeout(function() {
        
        jQuery("#" + active).removeClass('hovered');
        jQuery('#panels .panel.' + active).fadeOut(250);
        
      }, 500);       
      
    }
  );
  
}

// Show form hints (with inputs using "title" attribute)
function show_form_hints() {
  var el = jQuery('input[Title]');

  // Show display text
  el.each(function(i) {
    jQuery(this).attr('value', jQuery(this).attr('title'));
  });

  // Hook up the blur & focus
  el.focus(function() {
    if (jQuery(this).attr('value') == jQuery(this).attr('title'))
      jQuery(this).attr('value', '');
  }).blur(function() {
    if (jQuery(this).attr('value') == '')
      jQuery(this).attr('value', jQuery(this).attr('title'));
  });
}

// Switches content in tab sets
function switch_tabs() {
  
  jQuery('#flipbox a').hover(
    function() {
    
    // Get a list of tab names
    var tab_names = Array();
    jQuery('#flipbox a').map(function(){
      tab_names.push(jQuery(this).attr("id").replace("tab_",""));
    });

    // Hide all tabs
    for (i = 0; i < tab_names.length; i++) {
      jQuery('#' + tab_names[i]).hide();
      jQuery('#tab_' + tab_names[i]).parent().removeClass('active');
    }
    
    // Show the selected tab
    jQuery(jQuery(this).attr("id").replace("tab_","#")).show();
    jQuery(this).parent().addClass('active');
    
    },
    
    function() {
    }
  );
  
}

// Toggles visibility of sidebar lists
// in News, Events, Benefits, etc.
function toggle_sidebar_lists() {
  
  // Toggle single list
  jQuery('div h6').click(function() {
    jQuery(this).next().toggle();
  });
  
  // Toggle all lists
  jQuery('.toggle').click(function() {
    if (jQuery('.toggle a').text() == 'expand') {
      jQuery('.toggle a').text('collapse');
      jQuery('div h6').next().show();
    } else {
      jQuery('.toggle a').text('expand');
      jQuery('div h6').next().hide();
    }
  });
  
}

// Highlights the Events mini calendar on hover
function highlight_mini_calendar_on_hover() {
  
  jQuery('#highlight_mini_calendar').hover(
    function() {
      jQuery('#highlight_mini_calendar table').addClass('mini_calendar_over');
    }, function() {
      jQuery('#highlight_mini_calendar table').removeClass('mini_calendar_over');
    }
  );

}

// Grab the next musicworld article for the slidebox
function get_next_musicworld_article() {
  
  if (jQuery('#slidebox').length > 0) {

    if (jQuery('#current').parent().next().attr("class") == "ad") {
      var next_page = jQuery('#current').parent().next().next().find("a").attr("href");
      var next_title = jQuery('#current').parent().next().next().find("span").text();
      var next_image = jQuery('#current').parent().next().next().find("img").attr("src");
    } else {
      var next_page = jQuery('#current').parent().next().find("a").attr("href");
      var next_title = jQuery('#current').parent().next().find("span").text();
      var next_image = jQuery('#current').parent().next().find("img").attr("src");
    }
    
    if (next_page == undefined) {
      next_page = '/musicworld/';
      next_title = "View the current issue of MusicWorld";
    }
    
    jQuery("#slidebox #next_page a").html(next_title + " &raquo;");
    jQuery("#slidebox #next_page a").attr("href", next_page);
    
    if (next_page == '/musicworld/') {
      jQuery("#slidebox #next_image").hide();
    } else {
      jQuery("#slidebox #next_image").html('<a href="' + next_page + '"></a>');
      jQuery("#slidebox #next_image a").html('<img src="' + next_image + '" width="225" height="128" />');
    }
  }
  
}

// Switches the Events calendar to the selected month
function switch_calendar_to_selected_month() {
  
  jQuery('#calendar_selector').change(function() {
  	location.href = jQuery('#calendar_selector').val();
  });
  
  jQuery('#highlight_mini_calendar').click(function() {
  	location.href = jQuery('#highlight_mini_calendar').attr('href');
  });
  
}

// Replaces breadcrumb page title headline with Flash animation
function animate_page_title() {
	var title = jQuery("#title")[0];
	
	if (title) {
    var flashvars = {};
    var params = {};
    params.wmode = "transparent";
    params.quality = "high";
    params.bgcolor = "#FFFFFF";
    var attributes = {};
    swfobject.embedSWF('/flash/title.swf?title=' + 
                        title.innerHTML, 
                        "title", 
                        "200", 
                        "20", 
                        "8", 
                        false, 
                        flashvars, 
                        params, 
                        attributes);
	}
}

function search_tool() {
  
  // Switch to website search
  jQuery('.website').click(function() {
    jQuery('.repertoire').attr('checked', false);
    jQuery('#website').show();
    jQuery('#repertoire').hide();
  });
  
  // Switch to repertoire search
  jQuery('.repertoire').click(function() {
    jQuery('.website').attr('checked', false);
    jQuery('#website').hide();
    jQuery('#repertoire').show();
  });
  
  // Keep search query fields in sync
  jQuery('#web_search').change(function() {
  	jQuery('#rep_search').val(jQuery('#web_search').val());
  });
  jQuery('#rep_search').change(function() {
  	jQuery('#web_search').val(jQuery('#rep_search').val());
  });

}

function toggle_years_on_timeline() {
  jQuery('#timeline ul').hide();
  jQuery('#timeline h3:first span + span').addClass("minus");
  jQuery('#timeline h3:first span + span').removeClass("plus");
  jQuery('#timeline ul:first').show();
  jQuery('#timeline h3').click(function() {
    if (jQuery(this).next("ul").is(":visible")) {
      jQuery(this).next("ul").slideUp();
      jQuery(this).find("span + span").addClass("plus");
      jQuery(this).find("span + span").removeClass("minus");
    } else {
      jQuery(this).next("ul").slideDown();
      jQuery(this).find("span + span").removeClass("plus");
      jQuery(this).find("span + span").addClass("minus");
    }
  });
}

function make_pngs_work_in_explorer() {
  
  // Set transparent pixel
  jQuery.ifixpng('/images/app/pixel.gif');
  
  // Set pngs to make transparent
  jQuery('img, #overlay, .go').ifixpng();

}

function make_form_submits_work_in_explorer() {
  // http://thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter
  
  // Force IE to submit forms when enter/return is pressed
  // (but on login form check that user and pass are valid)
  jQuery('.ols_login input').keydown(function(e){
            
      // Process enter/return key press
      if (e.keyCode == 13) {
        
        // Login Form
        if (jQuery('.ols_login').length > 0) {
          if (jQuery('#realuser').val() != '' && jQuery('#realpass').val() != '') {
            if (jQuery('#realuser').val() != 'Username' && jQuery('#realpass').val() != 'Password') {
              jQuery(this).parents('form').submit();
            }
          }
        
        // Other forms
        } else {
          jQuery(this).parents('form').submit();
        }
        
        // Disable stupid IE beep sound
        return false;
      }
  });

}

function toggle_login_panel_go_button() {
  
  // Login panel go button
  jQuery('.ols_login input').keyup(function(e){
    
    // Toggle button state if inputs are valid
    if (jQuery('#realuser').val() != '' && jQuery('#realpass').val() != '') {
      if (jQuery('#realuser').val() != 'Username' && jQuery('#realpass').val() != 'Password') {
        jQuery('.ols_login .go').attr('src', '/images/app/go.png');
      } else {
        jQuery('.ols_login .go').attr('src', '/images/app/go_faded.png');
      }
    } else {
      jQuery('.ols_login .go').attr('src', '/images/app/go_faded.png');
    }
          
  }); 
  
}

function slideshow() {

  // Get active image and label
  var $active_image = jQuery('#feature .images li.active');
  var $active_label = jQuery('#feature .labels li.active');

  // Get next image and label
  var $next_image =  $active_image.next().length ? $active_image.next()
      : jQuery('#feature .images li:first');
  var $next_label =  $active_label.next().length ? $active_label.next()
      : jQuery('#feature .labels li:first');
             
  // Animate between images
  $next_image.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 700, function() {
        $active_image.removeClass('active');
    });
  
  // Animate between labels
  $active_label.removeClass('active');
  $next_label.addClass('active');
  $active_label.slideUp(300, function() {
    $active_label.appendTo("#feature .labels").show();
  });
    
}

function reshuffle_slides(selected_label) {
  
  // Reshuffle (only if new label is clicked)
  if (jQuery('#feature .labels li.active').attr("id") != selected_label.attr("id")) {
    
    // IMAGES

      // Grab active image
      var $active_image = jQuery('#feature .images li.active');
  
      // Grab next image
      if (selected_label.attr("id").length > 6) {
        next = "#image" + selected_label.attr("id").substring(5,7);
      } else {
        next = "#image" + selected_label.attr("id").substring(5,6);
      }
      
      var $next_image = jQuery(next);
  
      // Animate between images
      $next_image.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 300, function() {
            $active_image.removeClass('active');
        });
      
    // LABELS
    
      // Grab active label
      var $active_label = jQuery('#feature .labels li.active');
        
      // Remove active class
      $active_label.removeClass('active');
      
      // Set active class to selected label
      selected_label.addClass('active');
      
      // Move previous labels to bottom of stack
      jQuery(jQuery.makeArray(selected_label.prevAll()).reverse()).each(function() {
        jQuery(this).slideUp(200, function() {
          jQuery(this).appendTo("#feature .labels").show();
        });
      });
  
  }

}

function genres_slideshow() {
  
  // Get active image and label
  var $active_image = jQuery('#features.genres .feature.active');

  // Get next image and label
  var $next_image =  $active_image.next().length ? $active_image.next()
      : jQuery('#features.genres .feature:first');
             
  // Animate between images
  $next_image.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 700, function() {
        $active_image.removeClass('active');
    });
  
}

function rotate_indie_album_sets() {

  if (jQuery("#set1").is(':visible')) {
    jQuery("#set1").fadeOut(500);
    jQuery("#set2").fadeIn(500);
  } else {
    jQuery("#set1").fadeIn(500);
    jQuery("#set2").fadeOut(500);      
  }

}

function setup_video(carousel_id) {
  stepcarousel.setup({
    galleryid: carousel_id, //id of carousel DIV
    beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'panel3', //class of panel DIVs each holding content
    autostep: {enable:false, moveby:1, pause:3000},
    panelbehavior: {speed:500, wraparound:false, persist:true},
    defaultbuttons: {enable: true, moveby: 1, leftnav: ['/images/app/arrow_gray_left.png', -20, 40], rightnav: ['/images/app/arrow_gray_right.png', 5, 40]},
    statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
    contenttype: ['inline'] //content setting ['inline'] or ['ajax', 'path_to_external_file']
  });
}

function show_video_carousels() {
  
  // Setup default video carousel if available
  if (jQuery("#video_carousel").length && jQuery(".dynamic_carousel").length == 0) {
    setup_video("video_carousel");
  }
  
  // Spawn fancybox for video carousels
  jQuery(".stepcarousel .youtube_video a").live('click', function() {
   jQuery.fancybox({
     'padding'   : 0,
     'autoScale'   : false,
     'transitionIn'  : 'none',
     'transitionOut' : 'none',
     'title'     : this.title,
     'width'   : 680,
     'height'    : 495,
     'href'      : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
     'type'      : 'swf',
     'swf'     : {
       'wmode'   : 'transparent',
       'allowfullscreen' : 'true'
     }
   });
  
   return false;
  });
  
  // Play icon opacity rollovers
  jQuery('.youtube_video .overlay img').live('mouseover mouseout',function() {
    if (event.type == "mouseover") {
      jQuery(this).css('opacity', '0.4');
    } else {
      jQuery(this).css('opacity', '1.0');
    }
  });
  
}

function make_community_links_open_new_windows() {
  
  if (window.location.pathname.match(/^\/community/i)) {
    jQuery(".thread .post .container a").each(function() {
      if (jQuery(this).attr("href").match(/bmi.com/) == null && jQuery(this).attr("target") == '') {
        jQuery(this).attr("target", "_blank");
        jQuery(this).addClass("offsite");
      }
    });
  }
  
}

function handle_mobile_clients() {
  
  // Switch to mobile web app (if requested)
  jQuery('.switch_to_mobile').live('click', function(){
    jQuery.cookie('mobile', null, { path: '/', domain: 'bmi.com'});
    location.href = "/mobile";
  });
  
  // Supported mobile browsers
  if (navigator.userAgent.match(/Android/i) ||
      navigator.userAgent.match(/webOS/i) || 
      navigator.userAgent.match(/iPhone/i) || 
      navigator.userAgent.match(/iPod/i)) {
        
      // External links (with target=_blank)
      if (location.href.match(/mobile=skip/i)) {
                
        // Hide switcher
        jQuery(document).ready(function(){
          jQuery("#switcher").hide();
        });
        
      // Normal links
      } else {
        
        // Switch to mobile for some URLs
        var current_path = window.location.pathname;
        var routes = new Array();
        var mobile_enabled = false;

        // List of mobile optimized URLs
        routes.push('/');
        routes.push('/about');
        routes.push('/benefits');
        routes.push('/business');
        routes.push('/creators');
        routes.push('/events');
        routes.push('/license');
        routes.push('/login');
        routes.push('/join');
        routes.push('/musicworld');
        routes.push('/news/all_news');
        routes.push('/search');
        routes.push('/video');

        // Enable mobile app if matching URL is found
        for (x in routes) {
          if (current_path.match("^" + routes[x] + "\/?$")) {
            mobile_enabled = true;
            break;
          }
        }

        // Redirect news entry pages to mobile template
        if (current_path.match('^/news/entry/(\\d+)$')) {
          jQuery("body").hide();
          window.stop();
          window.location.pathname = '/news/entry_mobile/' + RegExp.$1;
          throw new Error('redirecting to mobile');
        }
        
        // Redirect contact page to mobile page
        if (current_path.match('^/about/entry/533331/test')) {
          jQuery("body").hide();
          window.stop();
          window.location.pathname = '/mobile/load/creators_offices';
          throw new Error('redirecting to mobile');
        }

        // Redirect event entry pages to mobile template
        if (current_path.match('^/events/entry/(\\d+)*$')) {
          jQuery("body").hide();
          window.stop();
          window.location.pathname = '/events/entry_mobile/' + RegExp.$1;
          throw new Error('redirecting to mobile');
        }
        
        if (mobile_enabled == true) {
          
          // Add mobile switcher        
          var html = '<p id="switcher"><span>';
          html = html + '<a href="#" class="switch_to_mobile">Switch to mobile version</a></span></p>';
          jQuery("#version_selector").after(html);

          // Show version selector overlay
          if (jQuery.cookie('mobile') == 'skip') {
          } else {
            jQuery("#version_selector").show();

            jQuery("#select_desktop").click(function(event){
              jQuery.cookie("mobile", "skip", { path: '/', domain: 'bmi.com', expires: 30 });
              jQuery("#version_selector").slideUp(300);
            });
            jQuery("#select_mobile").click(function(event){
              jQuery.cookie("mobile", null);
              location.href = "/mobile";
            });
          }

        }

      }
  }
}

// Let's roll!
jQuery(document).ready(function(){
    
  show_header_panel();
  
  show_form_hints();
  
  animate_page_title();
  
  search_tool();

  toggle_years_on_timeline();

  switch_calendar_to_selected_month();
  
  highlight_mini_calendar_on_hover();

  get_next_musicworld_article();
  
  toggle_sidebar_lists();
    
  switch_tabs();

  what_is_bmi_panel();

  toggle_login_panel_go_button();

  make_community_links_open_new_windows();

  show_video_carousels();

  make_pngs_work_in_explorer();
  
  make_form_submits_work_in_explorer();
    
  handle_mobile_clients();
  
  // Show form ghost text
  jQuery(".ghost_text").ghostText();
  
  // Genres slideshow (if slides are present)
  if (jQuery('#features').length) {    
    setInterval("genres_slideshow()", 7000 );
  }
  
  // Slideshow (if slides are present)
  if (jQuery('#feature').length) {
    
    // Slideshow
    slides = setInterval(slideshow, 7000);
    
    // Jump to slide
    jQuery("#feature .labels li").click(function () { 
      
      // Stop slideshow
      clearInterval(slides);

      // Reshuffle slides
      reshuffle_slides(jQuery(this));
                
      // Restart slideshow at current position
      slides =  setInterval(slideshow, 7000);
      
    });
    
  }
  
  // Indie Page album sets
  if (jQuery('#indie_header').length) {

    // Show detail when hovering over album cover
    jQuery("#indie_header .set img").hover(
      function () {
        set = jQuery(this).parent().attr("id").substring(3,4);
        detail = (jQuery(this).parent().children().index(this) + 1);        
        jQuery("#details" + set + " .detail" + detail).fadeIn(100);
      }
    );

    // Hide detail when hovering out
    jQuery("#indie_header .details div").hover(
      function () {
        jQuery('#indie_header .details div').not(this).hide();
        clearInterval(indie_slides);
      },
      function () {
        jQuery(this).fadeOut(100);
        indie_slides = setInterval("rotate_indie_album_sets();", 5000);
      }
    );

    // Rotate slides
    indie_slides = setInterval("rotate_indie_album_sets();", 5000);
  
  }
  
});


