// --- SiteTools --- //

var site_tools; // instance var

var SiteTools = Class.create();
SiteTools.prototype = {
  initialize: function(params) {
    this.search_timeout = '';
    this.search_interval = 1000;
    this.search_container = $('search_container');
    this.search_toggle = $('search_toggle');
    this.search_input = $('search');
    this.search_url = '/search';
    this.search_results_container = $('search_results_container');
    this.loader = $('nikepedia_search_loader');
    this.region_container = $('region_container');
    this.region_toggle = $('region_toggle');
    if (params.search_container) {
      this.search_container = $(params.search_container);
    }
    if (params.search_toggle) {
      this.search_toggle = $(params.search_toggle);
    }
    if (params.search_input) {
      this.search_input = $(params.search_input);
    }
    if (params.search_url) {
      this.search_url = params.search_url;
    }
    if (params.search_results_container) {
      this.search_results_container = $(params.search_results_container);
    }
    if (params.loader) {
      this.loader = $(params.loader);
    }
    if (params.region_container) {
      this.region_container = $(params.region_container);
    }
    if (params.region_toggle) {
      this.region_toggle = $(params.region_toggle);
    }
    this.default_search_value = this.search_input.value;
    this.setupObservers();
  },
  
  toggleRegionBox: function() {
    if (!this.region_container.visible()) {
      if (this.search_container.visible()) {
        this.toggleSearchBox();
      }
      new Effect.Appear(this.region_container, {duration: 0.4});
      Element.addClassName(this.region_toggle,'active');
    } else {
      new Effect.Fade(this.region_container, {duration: 0.4});
      Element.removeClassName(this.region_toggle,'active');
    }
  },
  
  toggleSearchBox: function() {
    if (!this.search_container.visible()) {
      if (this.region_container.visible()) {
        this.toggleRegionBox();
      }
      new Effect.Appear(this.search_container, {duration: 0.4});
      Element.addClassName(this.search_toggle,'active');
      this.search_toggle.zIndex = 99;
    } else {
      new Effect.Fade(this.search_container, {duration: 0.4});
      Element.removeClassName(this.search_toggle,'active');
      this.search_toggle.zIndex = 98;
      this.search_input.value = this.default_search_value;
      if (this.search_results_container.visible()) {
        new Effect.Fade(this.search_results_container, {duration: 0.4});
      }
    }
  },
  
  searchHandler: function(e) {
    clearTimeout(this.search_timeout);
    if (e.keyCode == Event.KEY_ESC) {
      this.toggleSearchBox();
      return;
    }
    this.search_timeout = setTimeout(function(){this.search()}.bind(this),this.search_interval);
  },
  
  search: function(e) {
    this.showLoader();
    new Ajax.Request(this.search_url,{asynchronous:true, evalScripts:true, parameters:{search: this.search_input.value}, onComplete: function(result) {
      this.resultsHandler(result.responseText);
    }.bind(this)});
  },

  resultsHandler: function(results) {
    this.search_results_container.innerHTML = results;
    this.showResults();
  },
  
  showResults: function() {
    if (!this.search_results_container.visible()) {
      new Effect.Appear(this.search_results_container, {duration: 0.2});
    }
    this.hideLoader();
  },

  hideResults: function() {
    if (this.search_results_container.visible()) {
      new Effect.Fade(this.search_results_container, {duration: 0.2});
    }
  },

  showLoader: function() {
    this.loader.show();
  },
  
  hideLoader: function() {
    this.loader.hide();
  },
  
  setupObservers: function() {
    Event.observe(this.region_toggle,'click',function() { this.toggleRegionBox() }.bind(this));
    Event.observe(this.search_toggle,'click',function() { this.toggleSearchBox() }.bind(this));
    Event.observe(this.search_input,'focus',function() { this.search_input.value == this.default_search_value ? this.search_input.value = '':''; }.bind(this));
    Event.observe(this.search_input,'keyup',function(e) { this.searchHandler(e) }.bind(this));
    Element.ancestors($(this.search_input)).each(function(a) { // stop the form from being submitted
      if (a.tagName.toLowerCase() == 'form') {
        Event.observe(a,'submit',function(e) {
          Event.stop(e);
          return false;
        });
        return;
      }
    });
    Element.nextSiblings($(this.search_input)).each(function(a) { // hide the submit button
      if (a.getAttribute('type') == 'submit' || a.getAttribute('type') == 'image') {
        a.hide();
        return;
      }
    });
  }
}

// --- COLOR FIELD --- //

var ColorField = Class.create();

ColorField.prototype = {
 
  initialize: function(valueField) {
    if (!$(valueField)) {
      return;
    }
    this.valueField = $(valueField);
    this.setupColorField();
    this.watchValueField();
  },
 
  setupColorField: function() {
    var colorSpan = new Element('span', { 'class': 'color_box', 'id': 'colorSpan' });
    Element.insert(this.valueField, {after: colorSpan});
    this.colorSpan = $('colorSpan');
    this.changeFieldColor();
  },
 
  watchValueField: function() {
    Event.observe(this.valueField, 'keyup', function() { this.changeFieldColor(); }.bind(this));
  },
 
  changeFieldColor: function() {
    if (this.valueField.value.replace(/^#/,'').length == 6) {
      this.colorSpan.style.backgroundColor = '#' + this.valueField.value.replace(/^#/,'');
      this.valueField.value = this.valueField.value.replace(/^#/,'');
    }
  }
}

// --- TABS --- //

var TabManager = Class.create();

TabManager.prototype = {
  
  initialize: function() {
    this.tabs = this.findTabs();
    this.tab_links = this.findTabLinks();
    this.setupTabLinks();
    this.hideAllTabs();
    this.showDefaultTab();
    SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function(e) { this.showTab($(e.path.replace(/\//g,''))); }.bind(this));
  },
  
  findTabs: function() {
	var ary = [];
	for(var i=0, len = document.getElementsByClassName('tab').length; i < len; i++){
		ary.push(document.getElementsByClassName('tab')[i]);
	}
	return ary;
  },
  
  findTabLinks: function() {
	var ary = [];
	for(var i=0, len = document.getElementsByClassName('tab_link').length; i < len; i++){
		ary.push(document.getElementsByClassName('tab_link')[i]);
	}
	return ary;
  },
  
  getTabLink: function(rel) {
    var return_link = false;
    this.tab_links.each(function(tab_link) {
      if (tab_link.getAttribute('rel') == rel) {
        return_link = tab_link;
      }
    });
    return return_link;
  },
  
  setupTabLinks: function() {
	this.tabs.each(function(tab) {
      var tab_link = this.getTabLink(tab.id);
      if (tab_link) {
        Event.observe(tab_link,'click',function() { SWFAddress.setValue(tab.id) }.bind(this).bind(tab))
      }
    }.bind(this));
  },
  
  showTab: function(tab) {
    this.hideAllTabs();
    if (tab != undefined) {
      tab.show();
      Element.addClassName(this.getTabLink(tab.id),'active');
    } else {
      this.showDefaultTab();
    }
  },
  
  hideAllTabs: function() {
    this.tabs.each(function(tab) {
      tab.hide();
      Element.removeClassName(this.getTabLink(tab.id),'active');
    }.bind(this));
  },
  
  showDefaultTab: function() {
    this.showTab(this.tabs.first());
  }
}


// --- FORMS --- //

function clearFieldValue() {
  for (i = 0; i < arguments.length; i++) {
    $(arguments[i]).value = '';
  }
}

// --- TRANSITIONS --- //

// --- used for category, story, and search grid layouts --- //
function cellOver(target) {
  new Effect.Morph(target.parentNode,{
    style:'background-color: #dddddd;',
    duration:0.2
  });
}

function cellOut(target) {
  new Effect.Morph(target.parentNode,{
    style:'background-color: #efefef;',
    duration:0.2
  });
}

function toggleOptions() {
  $('options').getElementsByClassName('option').each(function(item) {
    if (item.visible()) {
      item.hide();
      $('options_toggle_link').innerHTML = '+';
    } else {
      item.show();
      $('options_toggle_link').innerHTML = '-';
    }
  });
}

function toggleVisibility(link, target) {
  var link_class = (link.className == "expand") ? 'collapse' : 'expand';
  new Effect.toggle(target, "appear", {
    duration: 0.3,
    afterFinish: function() {
      link.className = link_class;
    }})
}

// --- LIST STATE MANAGEMENT --- //

// Get all elements with a particular class name inside a particular element and remove the requested class
function removeClasses(element,class_name)
{
  var children = document.getElementsByClassName(class_name,element);
  if (children.length) {
    for (i = 0; i < children.length; i++) {
      children[i].removeClassName(class_name);
    }
  }
}

// Sets a list item class name to 'active'
// List item is expected to be an <a> element
// Before setting te class name, this will go up two nodes
// in the DOM tree and clear all other elements with the class name 'active'
// Assumes element is nested like so: <ul><li><a></li></ul>
function setActiveListItem(element)
{
  if (!$(element))
  {
    return;
  }
  removeClasses($(element).parentNode.parentNode,'active');
  Element.addClassName($(element),'active');
}

function fadeRemove(element) {
  element = $(element);
  new Effect.Fade(element, {duration: 0.4, afterFinish: function() {
    Element.remove(element);
  }.bind(element)});
}

// --- FORM FILES --- //

if (!window.SI) { var SI = {}; };

SI.Files = {
  
	htmlClass : 'SI-FILES-STYLIZED',
	fileClass : 'file',
	wrapClass : 'file_container',
	
	fini : false,
	able : false,
	init : function() {
	  
		this.fini = true;
		
		var ie = 0 //@cc_on + @_jscript_version
		if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
		this.able = true;
		
		var html = document.getElementsByTagName('html')[0];
		html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
	},
	
	stylize : function(elem) {
	  
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		elem.parentNode.file = elem;
		elem.parentNode.onmousemove = function(e) {
		  
			if (typeof e == 'undefined') e = window.event;
			if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement) {
				e.pageX = e.clientX + document.documentElement.scrollLeft;
				e.pageY = e.clientY + document.documentElement.scrollTop;
			};

			var ox = oy = 0;
			var elem = this;
			if (elem.offsetParent) {
				ox = elem.offsetLeft;
				oy = elem.offsetTop;
				while (elem = elem.offsetParent) {
					ox += elem.offsetLeft;
					oy += elem.offsetTop;
				};
			};

			var x = e.pageX - ox;
			var y = e.pageY - oy;
			var w = this.file.offsetWidth;
			var h = this.file.offsetHeight;

			this.file.style.top		= y - (h / 2)  + 'px';
			this.file.style.left	= x - (w - 30) + 'px';
		};
	},
	
	stylizeById : function(id) {
		this.stylize(document.getElementById(id));
		Event.observe(document.getElementById(id),'change',function(e) {
		  var el = $(Event.element(e));
		  var path = el.value.split(/[\\\/]/);
		  $(el.parentNode.parentNode).select('span.file_name').first().innerHTML = path[path.length-1];
		});
	},
	
	stylizeAll : function() {
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		var inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1) {
				this.stylize(input);
				Event.observe(input,'change',function(e) {
				  var el = $(Event.element(e));
				  var path = el.value.split(/[\\\/]/);
				  $(el.parentNode.parentNode).select('span.file_name').first().innerHTML = path[path.length-1];
				});
			}
		}
	}
};

// --- EVENTS --- //

function resize() {}

function init() {
  
  if ($('assigned_stories')) {
    $('assigned_stories').getElementsByClassName('hit_area').each(function(el) {
      Event.observe(el,'mouseover',function(e) {cellOver(el);});
      Event.observe(el,'mouseout',function(e) {cellOut(el);});
    });
  }
  
  if ($('favorite_stories')) {
    $('favorite_stories').getElementsByClassName('hit_area').each(function(el) {
      Event.observe(el,'mouseover',function(e) {cellOver(el);});
      Event.observe(el,'mouseout',function(e) {cellOut(el);});
    });
  }
  
  if ($('stories')) {
    $('stories').getElementsByClassName('hit_area').each(function(el) {
      Event.observe(el,'mouseover',function(e) {cellOver(el);});
      Event.observe(el,'mouseout',function(e) {cellOut(el);});
    });
  }
  
  if ($('categories')) {
    $('categories').getElementsByClassName('hit_area').each(function(el) {
      Event.observe(el,'mouseover',function(e) {cellOver(el);});
      Event.observe(el,'mouseout',function(e) {cellOut(el);});
    });
  }
  
  site_tools = new SiteTools({
    search_container: 'nikepedia_search_box',
    search_toggle: 'search_toggle',
    search_input: 'search',
    search_results_container: 'nikepedia_search_results',
    region_container: 'nikepedia_region_box',
    region_toggle: 'region_toggle',
    search_url: '/search/ajax'
  });
  
}

Event.observe(window,'load',init);
Event.observe(window,'resize',resize);