var controller;
var sans_video = ['buy', 'support']; // Pages with no video player.
var load_video = true;
var whatisthis;

$(document).ready(function() {
  // Do the very early preparations.
  prepareHeaderLoginForm();
  // Bind various keyboard keys to certain elements of the page.
  //prepareKeyboardBindings();

  controller = new Controller();

  // Prepare the page.
  //controller.prepareHeaderLoginForm();
  controller.prepareLanguageDropdown();
  controller.activateForgotPasswordLink();
  controller.prepareLiveChatWindow();

  // Grab the site settings XML file and instantiate the media player.
  controller.initializeVideoSettings();

  // Determine if the current page has a video player. If not, clicking on a video in the video scroller should perform the default behavior.
  $.each(sans_video, function() {
    if (this == current_page) {
      load_video = false;
    }
  });
  if (load_video) {
    controller.prepareBottomNavVids();
    //controller.prepareVideoScrollerScrollBehavior();
  }

  // Purposely disabled.
  //controller.focusUsernameField();
  //controller.activateScroller();
  //controller.activateScrollerSkin();
  //controller.disableFooterTextLinks();
  //controller.prepareHeaderNavbarHover();
  //controller.addDefaultReflections();
});

function Controller() {
  var $this = this;

  this.player = {};
  this.extraPlayers = [];
  this.mediaPlayerObjID = '';
  this.thumb = '';

  this.scrollerVideos = [];
  this.scrollerAPI = {};
  this.currentVideoIndex = 0;

  // Misc vars
  this.fp_form = ''; // ForgotPassword form.
  this.fp_api = ''; // For controlling the forgot password overlay.

  this.prepareBottomNavVids = function() {
    var bottom_nav = $("#bottom_nav");
    if (bottom_nav.length > 0) { // If the bottom nav is included in the current page...

      // Prepare the click behavior.
      $("#video_scroller div.video_scroller_wrapper").click(function() {
        //alert('Works');

        var url = $(this).attr('rel');
        if (url.length > 1) { // If the url is not '#' or empty
          $this.createJWPlayer(url, $this.mediaPlayerObjID, {autostart: true});
        }
      });

      // Prepare the scrollable ability of the bottom nav.
      bottom_nav.scrollable({
        items: '#video_scroller_wrapper'
      });

      // Prepare the hover behavior (tooltips).
      /*
      $("div.video_scroller_thumb a").tooltip({
        tip: '#video_description',
        offset: [10, 2],
        effect: 'bouncy'
      }).dynamic({
        bottom: {
          direction: 'down',
          bounce: true
        }
      });
      */
    }
  };

  this.focusUsernameField = function() {
    $("input[name=username]").focus();
  };

  this.focusField = function(whichField) {
    $(whichField).focus();
  };

  this.prepareHeaderLoginForm = function() {
    var login_form = $("#header_login form");

    login_form.find('input[name=username]').get(0).onfocus = function() {
      if (this.value == 'or CONF#') {
        this.value = '';
        this.style.color = 'black';
      }
    }
    login_form.find('input[name=username]').get(0).onblur = function() {
      if (this.value.length === 0) {
        this.style.color = 'rgb(203, 194, 194)';
        this.value = 'or CONF#';
      }
    }

    /*
    if (login_form.length > 0) {
      // Set the mouseover/out behavior of the username field.
      login_form.find('input[name=username]').bind('focus', function() {
        if (this.value == 'or CONF#') {
          this.value = '';
          this.style.color = 'black';
        }
      }).bind('blur', function() {
        if (this.value.length === 0) {
          this.style.color = 'rgb(203, 194, 194)';
          this.value = 'or CONF#';
        }
      });
    }
    */
  };

  /**
   * This function takes jQuery objects.
   */
  this.refreshCaptcha = function(imgObj, verifyField) {
    // Get a new encoded CAPTCHA phrase.
    $.get(base_url+'index.php/captcha/generateCaptchaWord', function(response) {
      // Request a new image.
      imgObj.attr('src', base_url+'index.php/captcha/showImage/'+response);

      // Update the hidden verify field.
      verifyField.val(response);
    }, 'text');

    return false;
  };

  this.prepareHeaderNavbarHover = function() {
    // Activate the hover action.
    $("#header_nav ul li").hover(function() {
      if (!$(this).find('a').hasClass('selected')) {
        $(this).find('span').css('background-position', '0 -33px');
      }
    }, function() {
      if (!$(this).find('a').hasClass('selected')) {
        $(this).find('span').css('background-position', '0 -66px');
      }
    });

    // Make sure the sides of the button representing the currently selected page are right.
    $("#header_nav ul li a.selected").parents('li').eq(0).find('span').css('background-position', '0 0');
  };

  this.activateHiddenFeaturesToggle = function() {
    $("a.reveal_features").click(function() {
      var features_div = $(this).parents('div').eq(0).find('div.features');

      features_div.toggleClass('no-show');
      if (features_div.hasClass('no-show')) {
        $(this).text('See Key Features');
      } else {
        $(this).text('Hide Key Features');
      }

      return false;
    });
  }

  this.prepareLanguageDropdown = function() {
    $("#header_top select[name=lang]").change(function() {
      if (this.value.length > 0) {
        document.language_selection.submit();
      }
    });
  };

  this.addDefaultReflections = function() {
    $("#footer div.social_networking img").reflect();
  };
  
  this.activateScroller = function() {
    this.scrollerAPI = $("div.video_scroller").scrollable({
      api: true,
      size: 1,
      items: 'div.videos',
      item: 'div.video_scroller_wrapper',
      loop: true
    });
  };

  this.displayAjaxLoader = function(where) {
    if (!where) {
      // Put up an ajax loader graphic to give visual feedback.
      $('mediaspace').html('<img src="images/ajax-loader.gif" alt="" class="ajaxLoader"/>');
    } else {
      $(where).html('<img src="images/ajax-loader.gif" alt="" class="ajaxLoader"/>');
    }
  };

  this.initializeVideoSettings = function() {
    //$this.displayAjaxLoader(); // Display loading graphic.

    $.get(base_url+'site_settings.xml', function(response) {
      // Get the div ID that the media player should be instantiated into.
      var objID = $(response).find('defaults').find('mediaPlayerObjID').text();
      $this.mediaPlayerObjID = objID; // For future use.

      // Determine the default video for the current page.
      $(response).find('page').each(function() {
        var page = $(this).find('name').text();
        if (page == current_page) {
          // Get the default thumbnail image.
          //var thumb = $(response).find('defaults').find('defaultThumb').text();
          var page_thumb = $(this).find('defaultThumb').text();
          var default_thumb = $(response).find('defaults').find('defaultThumb').text();
          $this.thumb = (page_thumb.length > 0) ? page_thumb : default_thumb;

          var url = $(this).find('defaultVideo').text();
          if (url.length > 0) {
            $this.createJWPlayer(url, objID);
          } else {
            url = $(response).find('defaults').find('defaultVideo').text();
            if (url.length > 0) {
              $this.createJWPlayer(url, objID);
            }
          }

          // Grab this page's videos.
          var videos = $(this).find('videoScroller').find('video');
          if (videos.length > 0) {
            $.each(videos, function() {
              var video = {};

              video.title     = $(this).find('title').text();
              video.url       = $(this).find('url').text();
              video.thumb     = $(this).find('thumb').text();
              video.reference = $(this).find('languageKey').text();

              $this.scrollerVideos.push(video);
            });

            // Prepare the video scroller behavior.
            if ($this.prepareVideoScrollerScrollBehavior()) {
              $this.disableAndShowScrollerNavButtons();
            }
          }

          // Load the video scroller.
          //$this.displayAjaxLoader('#video_scroller');
          /*
          $('#video_scroller').load(base_url+'ajax/loadVideoScroller/'+current_page, function() {
            // Now that the vids are loaded, prepare them to switch out the main video window.
            $this.prepareBottomNavVids();
          });
          */
        }
      });
    }, 'xml');

    return true;
  };

  this.getVideoIndexByLanguageKey = function(languageKey) {
    var index = -1;

    if ($this.scrollerVideos.length > 0 && typeof languageKey == 'string' && languageKey.length > 0) {
      for (var i = 0; i < $this.scrollerVideos.length; i++) {
        if ($this.scrollerVideos[i].reference == languageKey) {
          index = i;
        }
      }
    }

    return index;
  };

  this.prepareVideoScrollerScrollBehavior = function() {
    if ($this.scrollerVideos.length > 5) { // If there are any scrollerVideos for the current page...
      $this.scrollerAPI = $("#video_scroller").scrollable({
        items: '.videos',
        item: 'div.video_scroller_wrapper',
        size: 5,
        api: true
      });
      //$this.scrollerAPI.getRoot().circular();

      return true;
    } else {
      return false;
    }
  };

  this.disableAndShowScrollerNavButtons = function() {
    $this.scrollerAPI.getNaviButtons().css('display', 'block').click(function() {
      return false;
    });
  };

  /**
   * Wrapper function for createJWPlayer
   */
  this.visuallyLoadJWPlayer = function(url) {
    // Display visual feedback.
    $this.displayAjaxLoader();

    // Load the new video.
    var objID = $this.mediaPlayerObjID;
    $this.createJWPlayer(url, objID);
  };

  this.prepareJWPlayer = function(obj) {
    $this.player = document.getElementById(obj.id);
  };

  this.addExtraPlayer = function(obj) {
    $this.extraPlayers.push(document.getElementById(obj.id));
  };

  this.createJWPlayer = function(url, id, params) {
    // Show loading icon.
    //$this.displayAjaxLoader();

    if (typeof id != 'string' || id.length < 1) {
      id = $this.mediaPlayerObjID;
    }

    if (typeof params == 'object') {
      params.autostart = (typeof params.autostart == 'string') ? params.autostart : 'true';
      params.fullScreen  = (typeof params.fullscreen == 'string') ? params.fullscreen : 'true';
      params.width = (typeof params.width == 'string') ? params.width : '480';
      params.height = (typeof params.height == 'string') ? params.height : '347';
    } else {
      params = {
        autostart: 'false',
        fullscreen: 'true',
        width: '480',
        height: '347'
      };
    }

    if (swfobject.getFlashPlayerVersion().major >= 9) {
      var flashParams = {
        allowfullscreen: params.fullscreen,
        allowscriptaccess: 'always',
        wmode: 'opaque',
        scale: 'noscale'
      };
      var flashVars = {
        autostart: params.autostart,
        image: base_url+$this.thumb,
        width: params.width,
        height: params.height,
        file: url
      };
      var flashAttribs = {};

      swfobject.embedSWF(base_url+'player.swf', $this.mediaPlayerObjID, params.width, params.height, '9', false, flashVars, flashParams, flashAttribs);

    } else {
      // No Flash Player installed.
      $('#'+$this.mediaPlayerObjID).append('<a href="http://www.adobe.com/go/getflashplayer">\
						<img style="position: absolute; top: 154px; left: 167px; margin: 0; padding: 0;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>');
    }
  };

  this.disableFooterTextLinks = function() {
    $("#footer_text a").click(function() {
      return false;
    });
  };

  this.changeButtonText = function(whichButton, whatText) {
    var buttonID = '#'+whichButton;
    $(buttonID).find('span.button_text').text(whatText);
  };

  this.activateScrollerSkin = function() {
    $("#video_scroller div.video_scroller_wrapper").click(function() {
      var title = $(this).find('span.video_thumb_title').text();
      alert('Now Playing '+title);
    });
  };

  this.activateForgotPasswordLink = function() {
    $this.fp_api = $("#header_login a.forgotPassword_link").overlay({
      expose: {
        //color: 'rgb(24, 93, 181)',
        color: 'rgb(240, 240, 240)',
        loadSpeed: 300,
        opacity: 0.8
      },
      closeOnClick: false,
      onLoad: function() {
        controller.focusField('#forgot_password input[name=fp_emailAddress]');
      },
      api: true
    });

    // Activate the Forgot Password submit action.
    $(document.forgotPassword).submit(function() {
      // Grab the form.
      $this.fp_form = $(this);

      // Disable the Submit button and change the text to reflect what's happening.
      var submit_text = this.elements.fp_submit.value;

      // Check for a valid email address.
      if (!this.elements.fp_emailAddress.value.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}(?:\.[A-Z]{2})?$/i)) { // The email given was no good.
        alert('The email address you provided is not valid. Please correct it before submitting.');

      } else { // A valid email was given.
        $(this).find('input[name=fp_submit]').attr('disabled', 'disabled').val('Searching...');

        var emailAddress = this.elements.fp_emailAddress.value;
        $.post(base_url+'index.php/support/forgotPassword?passwordRequest', {email: emailAddress}, function(response) {
          // Dumb function - just alert what is fed to you.
          alert(response);
          // Re-enable the Submit button.
          $this.fp_form.find('input[name=fp_submit]').removeAttr('disabled').val(submit_text);
          // Clear the email field.
          $this.fp_form.find('input[name=fp_emailAddress]').val('');
          // Close the overlay.
          $this.fp_api.close();
        }, 'text');
      }

      return false;
    });
  };

  this.preloadImages = function(imageArray) {
    if (imageArray.length > 0) {
      preloaded_images = new Array(imageArray.length);

      $.each(imageArray, function(i, val) {
        preloaded_images[i] = new Image();
        preloaded_images[i].src = '../images/'+val;
      });
    }
  };

  this.prepareLiveChatWindow = function() {
    $("#livechat").popupWindow({
      top: 50,
      left: 50,
      windowName: 'livechat',
      location: false
    });
  };

}

function prepareHeaderLoginForm() {
  var login_form = $("#header_login form");

  login_form.find('input[name=username]').get(0).onfocus = function() {
    if (this.value == 'or CONF#') {
      this.value = '';
      this.style.color = 'black';
    }
  }
  login_form.find('input[name=username]').get(0).onblur = function() {
    if (this.value.length === 0) {
      this.style.color = 'rgb(203, 194, 194)';
      this.value = 'or CONF#';
    }
  }
}

function prepareKeyboardBindings() {
  if (!document.activeElement) return false;

  var username = document.getElementById('header_login').getElementsByTagName('form')[0].elements.username;

    document.onkeypress = function(e) {
      if (document.activeElement != username) { // Nobody could type the letter 'L' without this little check...
        if (!e) e = window.event;
        var keyCode = e.charCode ? e.charCode : e.keyCode;

        // Make "l" or "L" focus the username field in the login form.
        if (keyCode == 108 || keyCode == 76) { // 'l' or 'L'
          username.focus();
          return false;
        }
      }

      return true;
    }

  return true;
}


// create custom animation algorithm for jQuery called "bouncy"
$.easing.bouncy = function (x, t, b, c, d) {
    var s = 1.70158;
    if ((t/=d/2) < 1) {return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;}
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};

