SearchForm = {
  defaults: {}
};

HomepageTabs = {
  show: function(tab) {
    var tab_id = tab.getAttribute('id');
    var div_id = tab_id.substr(0, tab_id.length - 4);
    this.clear();
    tab.className = 'active'
    $(div_id).show();
  },

  clear: function() {
    var tab_id, div_id;
    $A($('home-nav').getElementsByTagName('li')).each(function(tab) {
      tab.className = 'inactive'
      tab_id = tab.getAttribute('id');
      div_id = tab_id.substr(0, tab_id.length - 4);
      $(div_id).hide();
    });
  }
}

TabNav = {
  show: function(tab) {
    var tab_id = tab.getAttribute('id');
    if(tab_id == '') return true;
    var fs_id  = tab_id.substr(0, tab_id.length - 4);
    this.clear(tab);
    tab.className = 'active'
    $(fs_id).show();
    return false;
  },
  
  clear: function(tab) {
    var tab_id, fs_id;
    $A(tab.up('ul').getElementsByTagName('li')).each(function(tab) {
      tab.className = 'inactive'
      tab_id = tab.getAttribute('id');
      fs_id  = tab_id.substr(0, tab_id.length - 4);
      $(fs_id).hide();
    });
  }
}

var Episode = {
  subscribe: function(channel_id, anchor) {
    var sub_id = anchor.getAttribute('subscription_id');
    if(sub_id) {
      new Ajax.Request('/subscriptions/' + sub_id, {method:'delete'});
    } else {
      new Ajax.Request('/subscriptions', {parameters: 'subscription[channel_id]=' + channel_id});
    }
  },

  favorite: function(episode_id, anchor) {
    var fave_id = anchor.getAttribute('favorite_id');
    if(fave_id) {
      new Ajax.Request('/favorites/' + fave_id, {method:'delete'});
    } else {
      new Ajax.Request('/favorites', {parameters: 'favorite_episode[episode_id]=' + episode_id});
    }
  },
  
  staff: function(episode_id) {
    var anchor  = $('episode-favorite-button');
    var fave_id = anchor.getAttribute('favorite_id');
    var staff   = $F('staff-favorite');
    if(fave_id) {
      if(staff) {
        new Ajax.Request('/favorites/' + fave_id, {parameters: '_method=put&favorite_episode[staff]=1'});
      } else {
        new Ajax.Request('/favorites/' + fave_id, {parameters: '_method=put&favorite_episode[staff]=0'});
      }
      
    } else {
      new Ajax.Request('/favorites', {parameters: 'favorite_episode[staff]=1&favorite_episode[episode_id]=' + episode_id});
    }
  }
}

var Flash = {
  notice: function(msg) {
    this.show(msg, 'notice');
  },
  
  error: function(msg) {
    this.show(msg, 'error');
  },
  
  show: function(msg, flashType) {
    $('flash-msg').innerHTML = msg;
    $('flash-msg').className = flashType;
    new Effect.Appear('flash-msg');
  },
  
  hide: function() {
    new Effect.Fade('flash-msg');
  }
}

// disables all form buttons
Form.disableButtons = function(form) {
  this.onInputs(form, function(input) {
    if(input.getAttribute('type') == 'button' || input.getAttribute('type') == 'submit') {
      input.disabled = true;
    }
  });
}

// enables all form buttons
Form.enableButtons = function(form) {
  this.onInputs(form, function(input) {
    if(input.getAttribute('type') == 'button' || input.getAttribute('type') == 'submit') {
      input.disabled = false;
    }
  });
}

// calls the method callback on all input/textareas in a form
Form.onInputs = function(form, method) {
  $A($(form).getElementsByTagName('input')).each(method);
  $A($(form).getElementsByTagName('textarea')).each(method);
}

Object.extend(Array.prototype, {
  toQueryString: function(name) {
    return this.collect(function(item) { return name + "[]=" + encodeURIComponent(item) }).join('&');
  }
});

// default effects duration
Effect.DefaultOptions.duration = 0.25;

// Date Select Box stuff
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Date.abbreviatedMonths = Date.monthNames.collect(function(n) { n.substr(0, 3); });

Date.prototype.getMonthName = function() { return Date.monthNames[this.getMonth()]; }
Date.prototype.getAbbreviatedMonthName = function() { return Date.abbreviatedMonths[this.getMonth()]; }

Builder.selectYear = function(current, options) {
  var now = new Date();
  if(!options) options = {};
  if(!current) current = now.getFullYear();
  if(typeof(current) == 'object') current = current.getFullYear();
  var start = options.startYear || (now.getFullYear()-5);
  var end   = options.endYear   || (now.getFullYear()+5);
  options.startYear = options.endYear = null;

  return $B('select', options, 
    $R(start, end).collect(function(year) {
      return new Option(year, year, year.toString() == current.toString()); 
    })
  );
}

Builder.selectMonth = function(current, options) {
  if(!current) current = (new Date()).getMonth() + 1;
  if(!options) options = {};
  if(typeof(current) == 'object') current = current.getMonth() + 1;
  var monthNames  = options.useShortMonth ? Date.abbreviatedMonths : Date.monthNames;
  var htmlOptions = options;
  ['useShortMonth', 'useMonthNumbers', 'addMonthNumbers'].each(function(s) { htmlOptions[s] = null; });

  return $B('select', htmlOptions, 
    $R(1, 12).collect(function(monthNum) {
      var monthName = '';
      if(options.useMonthNumbers) {
        monthName = monthNum;
      } else if(options.addMonthNumbers) {
        monthName = monthNum + ' - ' + monthNames[monthNum-1];
      } else {
        monthName = monthNames[monthNum-1];
      }

      return new Option(monthName, monthNum, monthNum.toString() == current.toString());
    })
  );
}

var CMHelper = {
  toggle: function(txt, topOffset) {
    if($('ColourMod').visible()) {
      $('ColourMod').hide();
    } else {
      pickcolor('#CM-' + txt, 'backgroundColor', false, txt, this);
      $('ColourMod').style.top = topOffset;
    }
  }
}

Builder.selectDay = function(current, options) {
  if(!options) options = {};
  if(!current) current = (new Date()).getDate();
  if(typeof(current) == 'object') current = current.getDate();
  return $B('select', options, 
    $R(1, 31).collect(function(day) {
      return new Option(day, day, day.toString() == current.toString());
    })
  );
}

Event.addBehavior({
  // search boxes
  '#search_terms:focus,#top_search_terms:focus': function() {
    if($F(this) == SearchForm.defaults[this.getAttribute('id')]) this.value = '';
  },

  '#search_terms:blur,#top_search_terms:blur': function() {
    if($F(this) == '') this.value = SearchForm.defaults[this.getAttribute('id')];
  },
  
  // Video Upload Thangs
  '#episode_toggle:click': function() {
    new Effect.toggle($('series_options'), 'blind', {duration: 0.2});
    return false;
  },
  
  // Downloader
  
  '#download-episode-size:mouseover': function() {
    $('download-episode-size').style.backgroundPosition = '0% 100%';
  },
  
  '#download-episode-size:mouseout': function() {
    $('download-episode-size').style.backgroundPosition = '0% 0%';
  },
  
  '#download-episode-size:click': function() {
    new Effect.toggle($('download-options'), 'blind');
  },
  
  // Series Purchase Info Toggle
  '#purchase-series a.buy:click': function() {
    new Effect.toggle($('purchase-series-info'), 'blind');
  },
  
  // Smart Search Toggle
  '#smart-toggle:click': function() {
    new Effect.toggle($('smart_search'), 'blind', {duration: .75});
  },
  
  // Channel Style Preferences
  '#change-logo:mouseover,#cancel-change:mouseover': function() {
    this.style.backgroundColor = '#f60';
    this.style.color = '#fff';
  },

  '#change-logo:mouseout,#cancel-change:mouseout': function() {
    this.style.backgroundColor = '#fff';
    this.style.color = '#f60';
  },
  
  '#change-logo:click': function() {
    Element.hide('change-logo');
    Element.show('uploader');
  },
  
  '#cancel-change:click': function() {
    Element.hide('uploader');
    Element.show('change-logo')
  },
  
  '#home-nav li:click': function() {
    HomepageTabs.show(this); 
  },
  
  '.tab-nav a:click': function() {
    return TabNav.show(this.parentNode);
  },
  
  '#rating-archive-button:click': function() {
    var day   = this.previous('select');
    var month = day.previous('select');
    var year  = month.previous('select');
    var values = [year, month, day].collect(function(sel) { return sel.options[sel.selectedIndex].value; });
    location.href = "/ratings/" + values[0] + '/' + values[1] + '/' + values[2];
  },

  // user stripe episode/channel drop downs
  '#episode-creator-toggle:click,#channel-selector-toggle:click': function() {
    this.hide();
    this.next('select').show();
  },

	// User Stripe Search Box

	'#show-search:mouseover' : function() {
		$('show-search').style.color = "#900";
	},
	
	'#show-search:mouseout' : function() {
		$('show-search').style.color = "#fff";
	},
	
	'#show-search:click' : function() {
	  var search = $('search-box');
		if (search.visible()) {
			search.hide();
			$('top_search_terms').value = '';
		} else {
			search.show();
			$('top_search_terms').focus();
		}
	},
	
	'#CM-channel_background_color:click' 	: function() {new Effect.toggle($('channel_background_color_picker'), 'blind')},
	'#CM-channel_type_color:click' 				: function() {new Effect.toggle($('channel_type_color_picker'), 'blind')},
	'#CM-channel_link_color:click' 				: function() {new Effect.toggle($('channel_link_color_picker'), 'blind')},
	'#CM-channel_heading_color:click' 		: function() {new Effect.toggle($('channel_heading_color_picker'), 'blind')},
				
	'#channel_background_color:blur' : function() {
		$('pseudo-body').style.backgroundColor = this.value;
	},

	'#channel_type_color:blur' : function() {
		$('pseudo-text').style.color = this.value;
	},

	'#channel_link_color:blur' : function() {
		$('pseudo-link').style.color = this.value;
	},

	'#channel_heading_color:blur' : function() {
		$('pseudo-head').style.color = this.value;
	},

	'#channel_background_color_picker td:click' : function() {
		var colorRGB = (Element.getStyle(this, 'background-color'));
		$('pseudo-body').style.backgroundColor = colorRGB;
		$('channel_background_color').value = colorConverter(colorRGB);
	},
	
	'#channel_type_color_picker td:click' : function() {
		var colorRGB = (Element.getStyle(this, 'background-color'));
		$('pseudo-text').style.color = colorRGB;
		$('channel_type_color').value = colorConverter(colorRGB);
	},
	
	'#channel_link_color_picker td:click' : function() {
		var colorRGB = (Element.getStyle(this, 'background-color'));
		$('pseudo-link').style.color = colorRGB;
		$('channel_link_color').value = colorConverter(colorRGB);
	},
	
	'#channel_heading_color_picker td:click' : function() {
		var colorRGB = (Element.getStyle(this, 'background-color'));
		$('pseudo-head').style.color = colorRGB;
		$('channel_heading_color').value = colorConverter(colorRGB);
	},
	
	'#em-btn a:click': function() { $('dl-opts').hide(); Effect.toggle('embed', 'blind', {duration: 0.2}); return false; },

  '.highlight:focus': function() { this.focus();this.select() },
  
  '#reset-password-link:click': function() { Effect.toggle('reset-password', 'blind'); return false; },
  
  // Make intro blocks clickable
  '#watcher:click': function() { document.location = "http://wowtv.tv/ratings" },
  '#producer:click': function() { document.location = "http://wowtv.tv/signup"}
});

Event.onReady(function() {
  if(Prototype.Browser.WebKit) {
    document.body.className = 'safari';
  }
  
  if($('episode_access')) {
    Event.observe($('episode_access'), 'change', function() {
      var access = $F('episode_access');
      if(access == 'Protected' && !$('price_options').visible())
        $('price_options').show();
      else if(access != 'Protected' && $('price_options').visible())
        $('price_options').hide();
    })
  }
  
  [$('search_terms'), $('top_search_terms')].compact().each(function(txt) {
    SearchForm.defaults[txt.getAttribute('id')] = $F(txt);
  });
});

function colorConverter(colorRGB) {
	var leftStrip = colorRGB.split('\(');
	var rightStrip = leftStrip[1].split('\)');
	var finalStrip = rightStrip[0].split(',');
	var R = finalStrip[0];
	var G = finalStrip[1];
	var B = finalStrip[2];
	var colorHex = RGBtoHex(R,G,B);
	return colorHex;
}

function RGBtoHex(R,G,B) {var colorHex =  toHex(R)+toHex(G)+toHex(B); return colorHex}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}
