// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// From: http://simonwillison.net/2006/Jan/20/escape/
RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

String.prototype.parameterize = function(sep){
  if (sep == undefined || sep == null) var sep = '-';

  // Turn unwanted chars into the seperator
  var parameterized_string = this.replace(/[^a-z0-9\-_\+]+/i, sep);

  if (sep) {
    re_sep = RegExp.escape(sep);
    // No more than one of the separator in a row.
    parameterized_string = parameterized_string.replace(new RegExp(re_sep + '{2,}'), sep);
    // Remove leading/trailing separator.
    parameterized_string = parameterized_string.replace(new RegExp('^' + re_sep + '|' + re_sep + '$', 'i'), '');
  }
  return parameterized_string.toLowerCase();
}

jQuery(document).ready(function() {
  
  dropDownMenu = jQuery(".usoc #dropdown .dropdown");
  dropDownMenuLink = jQuery(" > a", dropDownMenu)
  originalTextLink = dropDownMenuLink.html();
  
  dropDownMenu.hover(
    function() {
      dropDownMenuLink.html("Choose a Sport");
    },
    function() {
      dropDownMenuLink.html(originalTextLink);
    }
  );
  
});

var HeadBarTout = {
  touts: [],
  current: 0,
  last: 0,
  timer: null,

  init: function(){
    this.touts = jQuery('#tout-bar .tout a');
    this.timer = setInterval("HeadBarTout.cycle()", 5000);
    this.last = this.touts.length - 1;
  },
  cycle: function(){
    if (this.current < this.last){ this.current++ }
    else { this.current = 0 }
    if (this.touts[this.current] != undefined){
      this.touts.hide();
      jQuery(this.touts[this.current]).show();
    }
  }
}

jQuery().ready(function(){ if(jQuery('#tout-bar').length > 0) HeadBarTout.init() });

function highlightRows() {
   if(!document.getElementsByTagName) return false;
   var rows = $$('tbody tr');
   
   for (var i=0; i<rows .length; i++) {
       //Event.observe(rows[i], 'mouseover', function() { $(this).addClassName('highlight');});
       //Event.observe(rows[i], 'mouseout', function() { $(this).removeClassName('highlight');});
       rows[i].onmouseover = function() { $(this).addClassName('highlight');}
       rows[i].onmouseout = function() { $(this).removeClassName('highlight');}
   }
}

/*
Clear default form value script- by JavaScriptKit.com
Featured on JavaScript Kit (http://javascriptkit.com)
Visit javascriptkit.com for 400+ free scripts!
*/

function clearText(thefield){
  if (thefield.defaultValue==thefield.value)
  thefield.value = ""
} 

Event.observe(window, 'load', function(e) {
  $$('#flash.notice').each(function(n) {
    n.fade({delay:5});
  })
});

Event.observe(window, 'load', function(e) {
  if (jQuery.cookie("sponsor_poll_voted") == "true") {
    jQuery(".sponsor-poll-form").addClass("sponsor_poll_hidden");
  }
  else
  {
    jQuery(".sponsorpoll-results").addClass("sponsor_poll_hidden");
  }
});

var getPageSize = function(){
  var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) { // all except Explorer
            if(document.documentElement.clientWidth){
                    windowWidth = document.documentElement.clientWidth;
            } else {
                    windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
            pageHeight = windowHeight;
    } else {
            pageHeight = yScroll;
    }


    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
            pageWidth = xScroll;
    } else {
            pageWidth = windowWidth;
    }

    var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
};

/* News tinyMCE templates with light box script */
jQuery().ready(function() {
  jQuery('img.lightbox').live('click', function(){
    jQuery('body').append("<div class='lightbox-wrap'><div class='modal-overlay'></div><div class='modal-window-wrap'><div class='modal-window modal-content'><img src='/images/layout/caption-placeholder.gif' /><a class='close'>Close</a></div></div></div>");
    jQuery('.lightbox-wrap').show(); 
    var image_id = jQuery(this).attr('id');

    if (jQuery('#'+image_id+'_full').length > 0){
      var img = jQuery('#'+image_id+'_full').attr('src');
    } else {
      var img = jQuery(this).attr('src');
    }
    
    jQuery('.modal-window img').attr('src', img)
    var w = jQuery('.modal-window img').width();
    jQuery('.modal-window').css({width: w+"px"});
  });
  jQuery('.modal-window a.close').live('click', function(){ jQuery('.lightbox-wrap').remove() });
});

Event.observe(window, 'load', function(e) {
  var options = {
    url: '/sponsorpoll',
    clearForm: true,
    type: 'post', 
    success: function(){
      jQuery(".sponsor-poll").addClass("sponsor_poll_hidden");
      jQuery(".sponsor-poll-results").removeClass("sponsor_poll_hidden");
    }
  };
  
  jQuery(".sponsor-poll-form").ajaxForm(options);
  
})

// form field focus

window.onload = focusForm;

function focusForm(){
/*   if(document.getElementById("email")){
      document.getElementById("email").focus();
   } */
}

// Framekiller
if (top !== self) top.location.replace(self.location.href);

// site nav drop-downs
if (Prototype.Browser.IE) {
	Event.observe(window, 'load', function() {
	  $$('.dropdowns li').each(function(node) {
	    Event.observe(node, 'mouseenter', function(event) { node.addClassName('over') });
	    Event.observe(node, 'mouseleave', function(event) { node.removeClassName('over') });
	  });
	});
} else {
	Event.observe(window, 'load', function() {
	  $$('.dropdowns li').each(function(node) {
	    Event.observe(node, 'mouseover', function(event) { node.addClassName('over') });
	    Event.observe(node, 'mouseout', function(event) { node.removeClassName('over') });
	  });
	});
}

/*
$j().ready(function() {
  $j('.dropdowns li').hover(
    function() { $j(this).addClass('over') },
    function() { $j(this).removeClass('over') })
});
*/

var ghettoGallery = {
  gallery_id : null,
  init: function(image_paths_array, video_id, video_thumb) {
    // Assign random ID, so we avoid ID conflicts (in retrospect probably not neccesary
    // as I don't think we'll be putting multiple galleries on 1 page)
    this.gallery_id = "gallery_" + Math.floor(Math.random()*1001);
    
    if(video_thumb == null) {
      video_thumb = '/images/hof/video_thumb.jpg';
    }
          
    document.write('<div id="'+this.gallery_id+'"><div id="'+this.gallery_id+'_thumbs"></div></div>');
    this.gallery_id = "#" + this.gallery_id
    
    if(video_id != null)
    {
      jQuery(document).ready(function(){
        jQuery("div.feature-video").append('<div id="flashcontent_'+video_id+'" class="player"></div>');
        var player_code = "<script type=\"text/javascript\">so = new FlashObject(\"http://natalie.feedroom.com/usoc/natoneclip/Player.swf\",\"Player\", \"320\", \"240\", \"8\", \"#CCCCCC\");so.addVariable(\"skin\", \"natoneclip\");so.addVariable(\"site\", \"usoc\");so.addVariable(\"fr_story\", \""+video_id+"\");so.addVariable(\"auto_play\", \"false\");so.addVariable(\"mute\", \"false\");so.addVariable(\"setvolume\", \"50\");so.addVariable(\"hostURL\", document.location.href);so.addParam(\"quality\", \"high\");so.addParam(\"allowFullScreen\", \"true\");so.addParam(\"allowScriptAccess\",\"always\");so.addParam(\"menu\", \"false\");so.addParam(\"wmode\", \"transparent\");so.addParam(\"swLiveConnect\", \"true\");so.write(\"flashcontent_"+video_id+"\");</script>";
        jQuery("div.feature-video div.player").html(player_code);
        jQuery("div.feature-video").css({'display' : 'block'});
      });
      
      jQuery(ghettoGallery.gallery_id + "_thumbs").append('<img src="'+video_thumb+'" id="hof_video" class="current" alt="Video Thumbnail" />');
      jQuery(ghettoGallery.gallery_id + "_thumbs" + " #hof_video").bind("click", function(e){
        jQuery(ghettoGallery.gallery_id+ " img.hof_full").css({'display':'none'});
        jQuery("div.feature-video").css({'display' : 'block'});
        jQuery(ghettoGallery.gallery_id + "_thumbs img").each(function(){
          jQuery(this).removeClass("current");
        });
        jQuery(this).addClass("current");
      });
    }
    
    jQuery(image_paths_array).each(function(i) {
      full_path = this;
      dot_index = full_path.lastIndexOf('.');
      if (dot_index == -1) {
        console.debug("Bad image path, image #"+i+"!");
        thumb_path = '';
      } else {
        thumb_path = full_path.substring(0,dot_index)+"_thumb"+full_path.substring(dot_index, full_path.length);
      }

      // Add full size images
      jQuery(ghettoGallery.gallery_id).append('<img src="'+this+'" id="hof_full_'+i+'" class="hof_full" alt="Image'+i+'" style="display:none;" />');

      // Add thumbnails
      jQuery(ghettoGallery.gallery_id + "_thumbs").append('<img src="'+thumb_path+'" id="hof_thumb_'+i+'" class="hof_thumb" alt="Thumbnail" />')
      jQuery(ghettoGallery.gallery_id + "_thumbs #hof_thumb_"+i).bind("click", function(e){
        ghettoGallery.show_image(i);
        jQuery(ghettoGallery.gallery_id + "_thumbs img").each(function(){
          jQuery(this).removeClass("current");
        });
        jQuery(this).addClass("current");
      });
    });
  },
  show_image: function(i){
    //console.debug("show image clicked: " + i);
    jQuery("div.feature-video").css({'display' : 'none'});
    jQuery(ghettoGallery.gallery_id+ " img.hof_full").css({'display':'none'});
    jQuery(ghettoGallery.gallery_id+ " img#hof_full_"+i).css({'display':'block'});
  }
}



var focusGallery = {
  element: "#mini_gallery",
  current: 0,
  last: 0,
  paused: 0,
  timer: '',
  
  init: function()
  { 
    jQuery(focusGallery.element + ' :header').css('display', 'none'); // Set headers to display none
    this.timer = setInterval("focusGallery.cycle()", '2100');
    this.pause();
  },
  
  cycle: function()
  {
    var header = focusGallery.element + ' :header';
    var items = focusGallery.element + ' li';
    var count = jQuery(items).size();
    var current_gallery = jQuery(items).get(focusGallery.current);
    var current_header = jQuery(header).get(focusGallery.current);
    var previous_header = jQuery(header).get(focusGallery.last);
    var previous_gallery = jQuery(items).get(focusGallery.last);
    
    if (focusGallery.paused != 1)
    {
      jQuery(previous_header).css('display', 'none');
      jQuery(previous_gallery).removeClass('over');
      jQuery(current_header).fadeIn('slow');
      jQuery(current_gallery).addClass('over');
        
      if( (focusGallery.current + 1) < count )
      {
        focusGallery.current = focusGallery.current + 1;
        focusGallery.last = focusGallery.current - 1;
      }
      else
      {
        focusGallery.current = 0;
        focusGallery.last = count - 1;
      }
    }
  },
  
  pause: function()
  {
    var items = jQuery(focusGallery.element + ' li');
    var headers = jQuery(focusGallery.element + ' :header');
    
    items.each(function(x){
      this.item = items[x];
      this.header = headers[x];
    }).mouseover(function()
    {
      focusGallery.paused = 1;
      headers.css('display', 'none'); // Clear headers
      items.removeClass('over') // Clear over classes
      jQuery(this.item).addClass('over');
      jQuery(this.header).css('display', 'block');
    }).bind("mouseout", function()
    {
      focusGallery.paused = 0;
      jQuery(this.item).removeClass('over');
      jQuery(this.header).css('display', 'none');
      focusGallery.current = 0;
    });
  }
}

jQuery().ready(function(){ if (jQuery(focusGallery.element).length > 0) focusGallery.init(); });

// Olympic Day related code.

jQuery().ready(function() {
  // Front facing related code
  jQuery(".olympic-day-main-state").change(function() {
    this.form.submit();
  });
  
  jQuery('.caption-each').click(function() {
    jQuery('#global-caption-field').addClass('hidden-element');
    jQuery(".add-photo-caption-field").each(function(i, e) {
      jQuery(e).show();
    })
  })
  
  jQuery(".caption-all").click(function() {
    jQuery('#global-caption-field').removeClass('hidden-element');
    jQuery(".add-photo-caption-field").each(function(i, e) {       
      jQuery(e).hide(); 
    }); 
  });
  
  
  jQuery(".olympicday_reports_dropdown").change(function() {
    this.form.submit();
  });
  
  jQuery(".olympicday_admin_index_dropdown").change(function() {
    this.form.submit();
  })
  
  jQuery(".state_select").change(
    function() {
      jQuery(".event_select").html('');
      jQuery(".city_select").html('');
      jQuery.getJSON("/olympicday/get_cities?id=" + jQuery(this).val(), function(data) {
        jQuery(".city_select").append(jQuery('<option>').text("Select a City"));
        jQuery.each(data, function(i, n) {
          jQuery(".city_select").append(jQuery('<option>').val(n.id).text(n.name));
        })
      });
    });
});
