// Initialization
//____________________________________________________________________________



$(document).ready(function(){
  //Test for JS and flash - please leave this at the start of this file.
  var major_flash_version = swfobject.getFlashPlayerVersion().major

  if (major_flash_version < 10) {
    var text;
    if (major_flash_version == 0) {
      text = '<p>Sorry, you need Flash to view this site. Please install the Flash Player and try again.</p>';
      text += '<a href="http://get.adobe.com/flashplayer">http://get.adobe.com/flashplayer</a>';
    }
    else {
      text = '<p>Sorry, you need Flash 10 to view this site but you are currently using Flash ' + major_flash_version + '. Please update your Flash Player and try again</p>';
      text += '<a href="http://get.adobe.com/flashplayer">http://get.adobe.com/flashplayer</a>';
    }
    $('.error_panel .error_message').html(text);
    $('body').css('overflow', 'hidden');
    $('.error_panel').show();
  }
});


// Flash parameters which are used by SWFObject
var flash_handler = {
  authenticity_token: AUTH_TOKEN,
  
  flashvars: {
    basePath: ASSET_HOST,
    dataPath: '',
    as_swf_name: 'content',
    authenticityToken: AUTH_TOKEN,
		cacheId: CACHE_ID 
  },
  
  params: {
    menu: 'false',
    quality: 'best',
    scale: 'noscale',
		allowscriptaccess: 'always',
		allowfullscreen: 'true'
  },
  
  attributes: {
    id: 'flashContent',
    align: 'middle'
  },
  
  swf_ref: null,

  set_user_details_on_flash: function set_user_details_on_flash() {
      if (flash_handler.swf_ref != null && user_helper.connected_user_id != null) {
  			 flash_handler.swf_ref.sendUserDetails(user_helper.connected_user_id, user_helper.connected_user_name, user_helper.connected_user_image_url, user_helper.connected_user_email);
      }
  },
	
	set_authenticity_token: function set_authenticity_token(token){
      flash_handler.authenticity_token = token;
      if (flash_handler.swf_ref != null)
         flash_handler.swf_ref.sendToken(token);
  },

  // gets called from flash when flash is loaded
  on_flash_load: function on_flash_load() {
      flash_handler.set_user_details_on_flash();
  },

  embedSWFCallback: function embedSWFCallback(e) {
      if (e.success) {
          flash_handler.swf_ref = e.ref;
      }
  },
  
  getUrl : function getUrl(){
	  return window.location.href;
  },
  
  getBaseUrl : function getBaseUrl(){
    return window.location.protocol + '//' + window.location.host;
  }  
};

//Function hooks
on_flash_load = flash_handler.on_flash_load
getUrl        = flash_handler.getUrl 

$(document).ready(function(){
  //Add js FX
  styling_controller.AddEffect('#main_menubar a', 'color_fade', 'mouseover', 'mouseout', '#9B3A6A');
});

//General Utils
//____________________________________________________________________________

var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
var isFirefoxWindows = (navigator.userAgent.indexOf('Firefox') > -1 && navigator.userAgent.indexOf('Windows') > -1);

//Styling additions
//____________________________________________________________________________

var styling_controller = {
  fadeDuration: 100,
  
  AddEffect: function AddEffect(cssSelector, type, inEvent, outEvent, additionalArgs){
    //Pulls the trailing arguments off and converts them into a real array object.
    effectArgs = new Array()
    for (var i=4; i<arguments.length; i++) {
      effectArgs.push(arguments[i]);
    }
    
    if(type == "color_fade") {
      $(cssSelector).each(function(i, elem){
        elem.inColor = effectArgs[0];
        elem.outColor = $(elem).css('color');
      });
      
      $(cssSelector).bind(inEvent, function(){styling_controller.FadeColor(this, this.inColor); });
      $(cssSelector).bind(outEvent, function(){styling_controller.FadeColor(this, this.outColor); });
    }
  },
  
  FadeColor: function FadeColor(element, destinationColor){
    $(element).stop();
    $(element).animate({color: destinationColor}, this.fadeDuration, 'linear', null);
  }
}

//Profile Page Handler
//_____________________________________________________________________________

var profile_page = {
  content_element: null,
  buttons: null,
  user_id: null,
  
  Init: function(user_id){
    $('#report_as_abusive_link').click(profile_page.OpenReportPopup);
    
    
    this.user_id = user_id;
    this.content_element = $('.user_profile .secondary_user_info_block .content');
    this.buttons = $('.user_profile .secondary_user_info_block .nav a');
    
    this.buttons.each(function(){
      this.content_type = this.className;
    });
    
    this.buttons.click(this.ButtonClick);
    
    $(this.buttons[0]).click(); 
  },
  
  ButtonClick: function ButtonClick(){
    profile_page.buttons.removeClass('active');
    $(this).addClass('active');
    profile_page.GetContent(this.content_type);
    clearTimeout(profile_page.timeout_id);
    $('.slider_content', profile_page.content_element).fadeOut(150);
  },
  
  GetContent: function GetContent(content_type){
    var request_url = '/profiles/' + this.user_id + '/show_' + content_type;
    $.get(request_url, null, profile_page.RenderContent, 'html');
  },
  
    
  RenderContent: function RenderContent(content){
    
    window.tmp_div = document.createElement('div');
    tmp_div.innerHTML = content;
    
    $('.slider_content', tmp_div).css('display', 'none');
    profile_page.content_element.html(tmp_div.innerHTML);
    $('img', profile_page.content_element).css({width: '0px', height: '100%', marginLeft: '50%'});
    
    profile_page.content_element.test_images = new Array();
    profile_page.content_element.images = $('img', profile_page.content_element);
    for (var i=0; i<profile_page.content_element.images.length; i++) {
      var test_image = new Image();
      profile_page.content_element.test_images[i] = test_image;
      $(test_image).load(function(){this.loaded = true;});
      test_image.src = profile_page.content_element.images[i].src;
    }
    
    $('.slider_content', profile_page.content_element).fadeIn(500);
                                
    slider.CleanUp();
    slider.Init($('.slider', profile_page.content_element));
    
    profile_page.DoShowImages(0);
  },
  
  timeout_id: null,
  
  DoShowImages: function DoShowImages(index) {
      if (typeof(profile_page.content_element.images[index]) != 'undefined') {
      if (profile_page.content_element.test_images[index].loaded) {
        $(profile_page.content_element.images[index]).animate({width: '100%', marginLeft: '0%'}, 300, 'swing', null);
        profile_page.timeout_id = window.setTimeout("profile_page.DoShowImages(" + (index + 1) + ");", 100);
      }
      else {
        profile_page.timeout_id = window.setTimeout("profile_page.DoShowImages(" + index + ");", 25);
      }
    }
  },
  

  report_popup: null,
  OpenReportPopup: function OpenReportPopup(url){
    url = this.href || url;
    profile_page.report_popup = new popup({
                                      is_iframe: true, 
                                      popup_holder: '#popup_holder', 
                                      frame_width: 350, 
                                      frame_height: 240, 
                                      border_width: 6, 
                                      border_color: '#2B2B2B', 
                                      border_opacity: 1
                                    });
    profile_page.report_popup.Open(url);
    return false;
  },
  CloseReportPopup: function CloseReportPopup(){
    profile_page.report_popup.Close();
    return false;
  }
}

var slider = {
  animation_speed: 500,
  animation_style: 'swing',
  
  
  root_element: null,
  prev_button: null,
  next_button: null,
  pages: null,
  slider: null,
  current_page: 0,
  
  Init: function Init(root_element){
    this.root_element = root_element;
    this.prev_button = $('.prev_page a', root_element);
    this.next_button = $('.next_page a', root_element);
    this.pages = $('.page', root_element);
    this.slider = $('.slider_content', root_element);
    
    if(this.pages.length <= 1) {
      this.prev_button.hide();
      this.next_button.hide();
    }
    else {
      this.prev_button.addClass('passive');
      this.prev_button.click(this.evt_SlideLeft);
      this.next_button.click(this.evt_SlideRight);
    }
  },
  
  evt_SlideLeft: function SlideLeft(){
    slider.SlideToPage(slider.current_page - 1);
  },
  evt_SlideRight: function SlideRight(){
    slider.SlideToPage(slider.current_page + 1);
  },
  
  SlideToPage: function SlideToPage(page){
    if (page < this.pages.length && page >= 0) {
      this.current_page = page;
      this.slider.stop();
      this.slider.animate({left: (0 - this.pages[page].offsetLeft) + 'px'}, this.animation_speed, this.animation_style, null);
      this.DoArrowState();
    }
  },
  
  DoArrowState: function DoArrowState(){
    this.prev_button.removeClass('passive');
    this.next_button.removeClass('passive');
    if (this.current_page == 0)
      this.prev_button.addClass('passive');
    if (this.current_page == this.pages.length - 1)
      this.next_button.addClass('passive');
  },
  
  CleanUp: function CleanUp(){
    this.root_element = null;
    this.prev_button = null;
    this.next_button = null;
    this.pages = null;
    this.current_page = 0;
  }
}

// Popup form handler for new users to enter their additional details.
// instanciate with something like 'var popup = new popup_iframe({backdrop_color: 'blue', flash_content: '#flash'});'
// Open and Close functions will then be exposed on the new object.
function popup(_options) {
  if (_options == null) var _options = {};
  options = {
    is_iframe: (_options.is_iframe == null) ? true : _options.is_iframe,
    backdrop_color: _options.backdrop_color || 'black',
    backdrop_image: _options.backdrop_image || null,
    backdrop_opacity: _options.backdrop_opacity || 0.5,
    frame_width: _options.frame_width || 450,
    frame_height: _options.frame_height || 460,
    popup_holder: _options.popup_holder || 'body',
    border_width: _options.border_width || 0,
    wrapper_class: _options.wrapper_class || 'popup_wrapper',
    border_color: _options.border_color || 'white',
    border_opacity: _options.border_opacity || 1
  }
  
  this.options = options;
  if (options.flash_content != null) this.flash_frame = $(options.flash_content);

  var backdrop = document.createElement('div');
  backdrop.className = 'backdrop';
  $(backdrop).css({
    display: 'block', 
    width: '100%', 
    height: '100%', 
    top: '0px', 
    left: '0px', 
    position: isIE6 ? 'absolute' : 'fixed', 
    backgroundColor: options.backdrop_color, 
    opacity: options.backdrop_opacity,
    zIndex: 900
  });
  if (options.backdrop_image != null) backdrop.style.backgroundImage = 'url(' + options.background_image + ')';
  this.backdrop = backdrop;

  var wrapper = document.createElement('div');
  $(wrapper).css({
    width: options.frame_width + "px",
    height: options.frame_height + 'px',
    padding: options.border_width,
    top: '50%',
    left: '50%',
    marginTop: (0 - ((options.frame_height + options.border_width) / 2)) + 'px',
    marginLeft: (0 - ((options.frame_width + options.border_width) / 2)) + 'px',
    position: 'absolute',
    zIndex: 930
  });
  wrapper.className = options.wrapper_class;
  this.wrapper = wrapper;
  
  
  if (options.border_width > 0) {
    var border = document.createElement('div');
    border.className = 'popup_border';
    $(border).css({
      width: options.frame_width + (options.border_width * 2) + 'px',
      height: options.frame_height + (options.border_width * 2) + 'px',
      position: 'absolute',
      top: '0px',
      left: '0px',
      'border-radius': options.border_width + 'px',
      '-moz-border-radius': options.border_width + 'px',
      '-webkit-border-radius': options.border_width + 'px',
      backgroundColor: options.border_color,
      opacity: options.border_opacity
    })
    this.border = border;
    $(wrapper).append(border);
  }
  
  if (options.is_iframe) {
    var frame = document.createElement('iframe');
    $(frame).attr('frameBorder', '0');
    $(frame).css({
      width: '100%',
      height: '100%',
      position: 'relative'
    });
    this.frame = frame;
    $(wrapper).append(frame);
  }
  else {
    var frame = document.createElement('div');
    $(frame).css({
      width: '100%',
      height: '100%',
      position: 'relative'
    });
    frame.className = 'frame';
    this.frame = frame;
  }
  
  this.Open = function Open(url_or_data){
    $(this.options.popup_holder).append(this.backdrop);
    if (this.options.is_iframe) {
      this.frame.src = url_or_data;
      $(this.options.popup_holder).append(this.wrapper);
      $(this.wrapper).append(this.frame);
    }
    else {
      $(this.frame).html(url_or_data);
      $(this.wrapper).append(this.frame);
      $(this.options.popup_holder).append(this.wrapper);
    }
  };
  
  this.Close = function Close(){
    $(this.wrapper).remove();
    $(this.backdrop).remove();
  };
  
  this.SetHeight = function SetHeight(height){
    $(this.wrapper).css({
      height: height + 'px',
      marginTop: (0 - (height/2)) + 'px'
    });
    $(this.border).css({
      height: height + (this.options.border_width * 2) + 'px'
    });
  };
}


var browser_fixes = {
  ie6_min_dimensions: {
    add_handler: function add_handler(element, min_width, min_height) {
      if (isIE6) {
        var css_width = element.style.width;
        var css_height = element.style.height;
        function do_resize(){
          element.style.width = css_width;
          if ($(element).width() < min_width) {
            element.style.width = min_width + 'px';
          }
          element.style.height = css_height;
          if ($(element).height() < min_height) {
            element.style.height = min_height + 'px'
          }
        }
        $(window).resize(do_resize)
        do_resize();
      }
    }
  },
  
  ie6_main_bar_height: {
    init: function init(){
      var element = $('#main_menubar')[0];
      if (typeof(element) != 'undefined') {
        var inner_wrapper = $('#main_menubar .menu_bar_wrapper')[0];
        inner_wrapper.style.position = 'absolute';
        
        function do_height(){
          inner_wrapper.style.height = ($('body').height() > 630) ? ($('body').height() - 16) + 'px' : '630px';
          element.style.height = ($('body').height() - 16) + 'px';
        }
        $(window).resize(do_height);
        do_height();
      }
    }
  },
  
  flash_stage_height: {
    init: function init(){
      $(window).resize(function(){
        $('#main object').css('height', $('#main').height() + 'px');
      });
      $('#main object').css('height', $('#main').height() + 'px');
    }
  }
}
if (isIE6) {
  $(document).ready(browser_fixes.ie6_main_bar_height.init);
}
