$(function(){
  /**
   * SWF implementation
   */ 
  embedBackgroundSWF();
	
	/**
   * Scroll fixes
   */    
  replaceScrollAreas('block1');
  replaceScrollAreas('block2');
  
  $('.scroll').jScrollPane();
	
  
  /**
   * Popup
   */     
  if($('#popup').length > 0) {
    $('#popup-close').click(function(e) {
      e.preventDefault();
      $('#popup').fadeOut();
      window.location.hash = '';
    });
  }  
  
  /**
   * Home
   */   
  if($('#playercarroussel').length > 0) {
    // config vars
    var playersInRow = 5;
    var carrousselWidth = 550;
    var playerWidth = 110;
  
    // initial setup
    var $c = $('#playercarroussel-inner li');
    var playerCount = $c.length;
    var animating = false;
    
    $('#playercarroussel-inner').width(playerWidth*(playerCount+1));
    $('#playercarroussel img').attr('title', '');
    
    // next
    $('#players-next').click(function(e) {
      e.preventDefault();
            
      if(animating) return;
      animating = true;
      
      // append first x to the end and animate to it
      $('#playercarroussel-inner').animate({'left': -carrousselWidth}, 1000, function() {
        for(var i=0; i<playersInRow; i++) {
          $('#playercarroussel-inner').append($('#playercarroussel-inner li').first());
        }
        $('#playercarroussel-inner').css('left', 0);
        animating = false;
      });
    });
    
    // previous
    $('#players-previous').click(function(e) {
      e.preventDefault();
      
      if(animating) return;
      animating = true;
      
      // prepend last x elements to beginning and animate to it
      for(var i=0; i<playersInRow; i++) {
        $('#playercarroussel-inner').prepend($('#playercarroussel-inner li').last());
      }
      $('#playercarroussel-inner').css('left', -carrousselWidth);
      $('#playercarroussel-inner').animate({'left': 0}, 1000, function() {
        animating = false;
      }); 
    });
    
    // dynamic load players
    $('#playercarroussel-inner a').click(function(event) {
      event.preventDefault();
      loadInPopup($(this).attr('href'), '');
      
      $('#playercarroussel-inner li').removeClass('active');
      $(this).parent('li').addClass('active');
    });
  }
  
  
  /**
   * Dynamic load
   * Takes care of the popup
   */
   
  // check hash 
  if(window.location.hash.length > 1)  {
    var hash = window.location.hash.split('#/');
    if(hash[1] != "") {
      loadInPopup(BLOG_URL+'/'+hash[1], '');
    }
  } 
   
  // make sure all links inside this site are loaded in popup
  $('#containercontent:not(.home) a').click(function(event) {
    var _href = $(this).attr('href');
    var _target = $(this).attr('target');

    if(_href.indexOf('mailto:') == -1) {
        event.preventDefault();
        loadInPopup(_href, _target);
    }
  });
  
  function loadInPopup(link, t) {
    if (link.indexOf(BLOG_URL) == -1 && t != '_self') {
      if(link != '' && link != '#') {
        window.open(link);
      }
      return false;
      
    } else if(t == '_self') {
        if(link != '' && link != '#') {
            window.location = link;
        }
        return false;
    }
    window.location.hash = link.substring(BLOG_URL.length);
    //log('dynamic loading: ' + link);
    
    $('#popup').fadeOut();
    $('#popup-inner').load(link + ' #popup-inner', function() {
      $('#popup').fadeIn();

      //$('.scroll').jScrollPane();

      var api = $('.scroll').jScrollPane().data('jsp');
      api.reinitialise();

    });
    
  }
  
  /** 
   * Form submits
   */
  
  // contact
  $('#contact-form').live('submit', function(event) {
    event.preventDefault();
    
    if(checkForm('contact-form')) {     
      $.post('/wp/wp-content/plugins/boltsunited/mail.php', $('#contact-form').serialize(), function() {
        $('#contact-form').fadeOut();
        $('#form').text('Thank you, your message was sent.');
      });
    }
  });
  
  // dugout
  $('#dugout-form').live('submit', function(event) {
    event.preventDefault();
    
    if(checkForm('dugout-form')) {   
      $.post('/wp/wp-content/plugins/boltsunited/mail.php', $('#dugout-form').serialize(), function() {
        $('#dugout-form').fadeOut();
        $('#form').text('Thank you, your message was sent.');
      });
    }
  });
});

function checkForm(form) {
  var checkFields = $('#' + form + ' .required').length;
  var correctFields = 0;
  
  $('#' + form + ' label').removeClass('error');
  $('#' + form + ' span').removeClass('error');
  
  $('#' + form + ' .required').each(function() {
    if(trim($(this).val()).length <= 0) {
      var label = $('#' + form + ' label[for=' + $(this).attr('name') + ']');
      var span = $('#' + form + ' span.' + $(this).attr('name'));

      label.addClass('error');
      span.addClass('error');
      
      return false;
    }
    else {
      correctFields++;
    }
  });
  
  if(checkFields == correctFields) {
    return true;
  }  
}

function replaceScrollAreas(block) {
  var firstHeader = $('.'+block + ' h1').first();
  if($(firstHeader).length == 1) {
    $('.'+block).removeClass('scroll');
    var scrollDiv = $('<div class="'+block+'-inner scroll" />');
        
    $(firstHeader).after(scrollDiv);
    $(scrollDiv).append($(scrollDiv).nextAll());
  }
}


var videoMuted = false;

if(getCookie('bu_videomute') != undefined) {
//	log(getCookie('bu_videomute'));
	videoMuted = getCookie('bu_videomute') == 'true'? true : false;
//	log('cookie:', videoMuted);
}

function embedBackgroundSWF() {
  var flashvars = {};
	// fullpath to each file
	//flashvars.playlist = TEMPLATE_URL + '/backgrounds/video/bg_video1.f4v,'+TEMPLATE_URL + '/backgrounds/images/bg_image1.png';
	flashvars.playlist = FLASH_PLAYLIST;
	flashvars.rasterFile = TEMPLATE_URL + '/backgrounds/images/bg_pattern1.png';
	flashvars.autoplay = true;
	flashvars.loop = false;

	var flashFound = swfobject.hasFlashPlayerVersion("9");

	var params = {};
	params.allowscriptaccess = "always";
	params.allownetworking = "all";
	params.allowfullscreen = "true";
	params.menu = "false";
	params.wmode = 'transparent';

	var attributes = {};
	attributes.id = "video-background";
	attributes.name = "video-background";
  
  if(flashFound) {
  	swfobject.embedSWF(TEMPLATE_URL + '/swf/background.swf', "video-background", '100%', '100%', "9.0.0", TEMPLATE_URL + '/swf/expressInstall.swf', flashvars, params, attributes, function() {
      if(!videoMuted) {
      	setTimeout('backgroundMute()', 1000);
  	  }
  	});
  	
  	// check sound
  	$('#video-mute-button').show();

  	$('#video-mute-button span').text(videoMuted? 'Off' : 'On');
  	$('#video-mute-button a').click(function() {
  	  videoMuted = !videoMuted;
	  setCookie('bu_videomute', videoMuted, 30);
	  
	  $('#video-mute-button span').text(videoMuted? 'Off' : 'On');
  	  backgroundMute();
  	});
  }
  else {
    var background = '';
    if(FLASH_PLAYLIST.indexOf(',')==-1) {
        if(FLASH_PLAYLIST.indexOf('.swf')==-1) {
            background = FLASH_PLAYLIST;
        } else {
            background = TEMPLATE_URL + '/backgrounds/images/01_HOME_1280.jpg';
        }
    } else {
        background = end(FLASH_PLAYLIST.split(','));
    }
    $('#video-background').append('<img src="'+background+'" />');

    /*
     $('#video-background').css({
      background: 'url('+ background + ') fixed no-repeat',
      width: '100%',
      height: '100%'
    });
    */
    
    $('#video-mute-button').hide();

    $(window).load(function() {
            var theWindow        = $(window),
                $bg              = $("#video-background img"),
                aspectRatio      = $bg.width() / $bg.height();

            function resizeBg() {

                    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                        $bg
                            .removeClass()
                            .addClass('bgheight');
                    } else {
                        $bg
                            .removeClass()
                            .addClass('bgwidth');
                    }

            }

            theWindow.resize(function() {
                    resizeBg();
            }).trigger("resize");

    });
  }
}

function end (arr) {
    // Advances array argument's internal pointer to the last element and return it
    //
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/end
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Legaev Andrey
    // +    revised by: J A R
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   restored by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: end({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 1: 'Zonneveld'
    // *     example 2: end(['Kevin', 'van', 'Zonneveld']);
    // *     returns 2: 'Zonneveld'
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.pointers = this.php_js.pointers || [];
    var indexOf = function (value) {
        for (var i = 0, length = this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };
    // END REDUNDANT
    var pointers = this.php_js.pointers;
    if (!pointers.indexOf) {
        pointers.indexOf = indexOf;
    }
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            ct++;
            var val = arr[k];
        }
        if (ct === 0) {
            return false; // Empty
        }
        pointers[arrpos + 1] = ct - 1;
        return val;
    }
    if (arr.length === 0) {
        return false;
    }
    pointers[arrpos + 1] = arr.length - 1;
    return arr[pointers[arrpos + 1]];
}

$(window).load(function() {
  backgroundResize();
});

$(window).resize(function() {
  backgroundResize();
});
