function ajax_submit_comment(obj) {
  var content = obj.getElementsByClassName('input_text_switcher')[0].value;
  if (content.gsub(/Enter your comment here| /,'')!='') {
    new Ajax.Request('/account/submit_comment', {asynchronous:true, evalScripts:true, parameters:Form.serialize(obj)});
    obj.getElementsByClassName('submit')[0].disabled = true;
  }
  return false;
}

  function notice_to_element(address,howto) {
    if (readCookie('notice_'+address)!=null) {
      switch(howto) {
      case 'update':
        $('notice_'+address).update(readCookie('notice_'+address));
        break;
      case 'innerhtml':
        $('notice_'+address).innerHTML = readCookie('notice_'+address);
        break;
      case 'value':
        $('notice_'+address).value = readCookie('notice_'+address);
        break;
      default:
        $('notice_'+address).update(readCookie('notice_'+address));
      }
      eraseCookie('notice_'+address);
    }
  }

function comments_forgot_password_switcher() {
	if ($('popup_forgot_password').style.display!='block') {
		$('popup_forgot_password').style.display='block';
		$('popup_login_or_register').style.display='none';
		$('forgot_password_user_email').value = $('login_user_email').value;
	} else {
		$('popup_forgot_password').style.display='none';
		$('popup_login_or_register').style.display='block';
		$('login_user_email').value = $('forgot_password_user_email').value;
	}
}

function populate_user_immediate_tags()
{
  $('user_immediates').innerHTML = readCookie('user_immediates');
}

function forgot_password_switcher() {
	if ($('orthodox_forgot_password').style.display!='block') {
		$('orthodox_forgot_password').style.display='block';
		$('orthodox_login_and_registration').style.display='none';
		$('forgot_password_user_email').value = $('login_user_email').value;
	} else {
		$('orthodox_forgot_password').style.display='none';
		$('orthodox_login_and_registration').style.display='block';
		$('login_user_email').value = $('forgot_password_user_email').value;
	}
}
/*
function login_forgot_password(){
	var forgot_password_link, orthodox_login_and_registration, orthodox_forgot_password;
	forgot_password_link = $('forgot_password');
	orthodox_login_and_registration = $('orthodox_login_and_registration');
	orthodox_forgot_password = $('orthodox_forgot_password');
	forgot_password_link.observe('click', function(event){
		orthodox_login_and_registration.style.display = 'none';
		orthodox_forgot_password.style.display = 'block';
	});
}
*/
function copy_form_elements(src,dst) {
  inpts = document.forms[src].elements;
  for (i=0;i<inpts.length;i++) {
    var inpt = document.createElement("input");
    inpt.type = "hidden";
    inpt.name = inpts[i].name;
    inpt.value = inpts[i].value;
    document.forms[dst].appendChild(inpt);
  }
}

function edit_nick_for_comment(obj_ptr) {
  $('user_nick_'+obj_ptr).disabled = false;
  $('user_nick_'+obj_ptr).focus();
  $('edit_nick_button_'+obj_ptr).style.display = 'none';
}

function update_user_nick_state(obj_ptr) {
  if (readCookie('user_nick')!=null && readCookie('user_nick')!='') {
    $('user_nick_'+obj_ptr).value = readCookie('user_nick');
    $('user_nick_'+obj_ptr).disabled = true;
    $('edit_nick_button_'+obj_ptr).style.display = 'inline';
  }
}

function switch_classes(obj,class1,class2,one_way) {
  if (one_way) {
    obj.className = class2;
    obj.onclick = '';
  } else {
    obj.className = obj.className==class1 ? class2 : class1;
  }
}


function get_radio_value(form_name,radio_button_name) {
  radio_button = document.forms[form_name].elements[radio_button_name];
  for (var i=0; i < radio_button.length; i++)
   {
   if (radio_button[i].checked)
      {
      var rad_val = radio_button[i].value;
      }
   }
   return rad_val;
}

function initialize_tabs() {
	var tabbed_boxes, tabs, tabbed_content;
	tabbed_boxes = document.getElementsByClassName("tabbed_list");
	tabbed_boxes.each( function (e,i) {
		$(e).immediateDescendants().each(function(e,i) {
			$(e).observe('click', function(event){
				e.addClassName('active_tab');
				e.siblings().each(function(e,i){
					$(e).removeClassName('active_tab');
				});
			});
		});
	});
}

function initialize_search_and_email_focus(){
	var input_text_switchers;
	input_text_switchers = document.getElementsByClassName("input_text_switcher");
	input_text_switchers.each( function (e,i) {
		if (e.value == ''){	e.value = e.title; }
		$(e).observe('focus', function(event){ if (e.value == e.title){ e.value = ''; }});
		$(e).observe('blur',  function(event){ if (e.value == '')     {	e.value = e.title; }});
	});
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length)).gsub(/\+/,' ');
	}
	return null;
}

function flush_all_notice_cookies() {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf('notice_') == 0) {
			eraseCookie(c.substring(0,c.indexOf('=')));
		}
	}
	return null;

//	document.cookie = document.cookie.gsub(/notice_.*(;|$)/,'');
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function is_user_subscribed_to(slug) {
	return readCookie('user_slugs').split(',').grep(slug).length==1;
}

function is_users_cookie_exists() {
	return readCookie('user_id')!=null;
}

function unless_cookie_exists_update_element(id,content) {
  if (!is_users_cookie_exists()) {
	$(id).update(content);
	$(id).style.display='block';
  }	
}

function if_cookie_exists_update_element(id,content) {
  if (is_users_cookie_exists()) {
	$(id).update(content);
	$(id).style.display='block';
  }	
}

function set_login_and_registration_header() {
  if (is_users_cookie_exists()) {
	$('login_and_registration_header').update('\
    	<strong>My Seeking Alpha</strong> \
      <ul> \
        <li><a href="/page/email-preferences">My Alerts</a></li> \
        <li><a href="/page/account-preferences">My Account</a></li> \
        <li><a href="/account/logout">Logout</a></li> \
      </ul>');
	$('login_and_registration_header').style.display='block';
	$('header').className='';
  }	
}

function update_user_nick(id) {
  if (readCookie('user_nick')!=null) {
    $(id).value = readCookie('user_nick');
  }
}
/* pending reparsing
function enable_quotes(){
	var blockquote_elements, start_quotes, end_quotes, quote_paragraph, quote_content, unwanted_br;
	blockquote_elements = document.getElementsByClassName('quote');
	blockquote_elements.each(function(e,i){
		start_quotes = document.createElement('strong');
		end_quotes = document.createElement('strong');
		quote_content = document.createElement('span');
		start_quotes.innerHTML = '&#147;&nbsp;'
		end_quotes.innerHTML = '&#148;'
		quote_paragraph = e.immediateDescendants()[0];
		quote_content.innerHTML = quote_paragraph.innerHTML;
		unwanted_br = quote_content.getElementsByTagName('br')[0];
		quote_content.removeChild(unwanted_br);
		e.removeChild(quote_paragraph);
		e.appendChild(start_quotes);
		e.appendChild(quote_content);
		e.appendChild(end_quotes);
	});
}
*/
function enable_email_change(change_button){
	change_button.addClassName('hidden');
	change_button.previous(0).removeClassName('disabled');
	change_button.previous(0).enable();
}
function enable_password_change(change_button){
	change_button.addClassName('hidden');
	change_button.previous(0).removeClassName('disabled');
	change_button.previous(0).enable();
	change_button.ancestors()[0].nextSiblings().each( function (e,i) {
		e.removeClassName('hidden');
	});
}

function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return '';
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }	
}

function queryString(key){
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}

function get_word_count_for_tinymce()
{
  var x=tinyMCE.getContent();
    var regex=/<[^>]*>/gi;
    //outputstr=x.replace(regex,"").split(" ");
    word_count = x.replace(regex,"").split(" ").length

    return word_count
}

function validate_contribute_form()
{
  check = true
  if($('article_title').value == "")
  {
    alert('Article Title can not be empty');
    check = false;
  }
  else if (get_word_count_for_tinymce() < 100 && $('article_url').value != '')
  {
    alert('Article word count must be more than 100 words');
    check = false;
  }
  return check;
}

function tinymce_word_count_sentinal(keydown)
{
    word_limit = 100;
    word_count = get_word_count_for_tinymce();

    if(word_count < word_limit)
    {
      $('char_notice').style.display = "inline";
      //$('submit_page').disabled = true;
      $('char_notice').innerHTML = "<span style='color:red;font-weight:bold;'>" + word_count + "</span> of <span style='color:red;font-weight:bold;'>" + word_limit + "</span> minimum words limit"
      $('seperator_pipe').style.display = "inline";
    }
    else
    {
     // $('submit_page').disabled = false;
      $('char_notice').style.display = "none";
      $('seperator_pipe').style.display = "none";
    }
}

// Populate the form in the account preferences page with the user cookie data
function populate_account_preferences()
{
  $('user_email').value = readCookie('user_email');
  $('vocation').selectedIndex = (readCookie('user_vocation') - 1);
  $('nick').value = readCookie('user_nick');ajax_submit_comment
}

function nick_was_taken_alert() {
  if (confirm('The name/pseudonym you chose had already been taken.\nDo you want to go to your account preferences to choose a different name/pseudonym?')) {
    location.href = '/page/account-preferences'
  } else {
    return false;
  }
}

function nick_was_taken_alert_by_querystring() {
  if (queryString('nick_was_taken')=='nick_was_taken') { nick_was_taken_alert(); }  
}

function jump_to_anchor(anchor_name) {
  window.location.hash = anchor_name; 
}

function application_init(){
  initialize_tabs();
  initialize_search_and_email_focus();
  nick_was_taken_alert_by_querystring();
  // enable_quotes();
  flush_all_notice_cookies();
//  load_css_files();
}

function change_location(href) {
  location.href = href;
}
function load_css_files(){
	var body_element;
	body_element = document.getElementsByTagName('body')[0];
	body_element.innerHTML += '<link href="/stylesheets/print.css?1191242221" media="print" rel="Stylesheet" type="text/css" /><link href="/stylesheets/redbox.css?1186912246" media="screen" rel="Stylesheet" type="text/css" /><link href="/stylesheets/lightbox.css?1188017091" media="screen" rel="Stylesheet" type="text/css" />';
}
Event.observe(window, 'load', function() { application_init(); });