function ajax_submit_story(){
  var nick = document.getElementById('submit_story_nick_input').value;
  var story =  document.getElementById('submit_story_textarea').value;
  var sex = document.getElementById('submit_story_select_sex');
  

  
  if(sex){
    sex = sex.options[sex.selectedIndex].value;
    sex = "&sex="+sex;
  }
  else
    sex = '';
  var cat = document.getElementById('submit_story_select_category');
  cat = cat.options[cat.selectedIndex].value;
  var type = document.getElementById('submit_story_select_type');
  type = type.options[type.selectedIndex].value;
  var anon_email = document.getElementById('submit_story_anon_email').value;
  
  if(cat == 'nogo'){
    alert('no category selected');
    document.getElementById('ajax_wait_popup').style.display = 'none';
    document.getElementById('submit_story_div').style.display = 'block';  
    return false;
  }

  document.getElementById('ajax_wait_popup').style.display = 'block';
  document.getElementById('submit_story_div').style.display = 'none'; 
  
  var string = 'action=new_story&nick='+encodeURI(nick)+'&story='+encodeURI(story)+sex+'&cat='+encodeURI(cat);
  string += '&type=' + encodeURI(type) + '&email=' + encodeURI(anon_email);
  //alert(string);
  ajaxFunction(string);
}


var global_id_clicked;
function digg(story_id, which, id){ // which = 1 means UP 0 means DOWN
  var string = 'action=digg&id='+story_id+"&which="+which; 
  global_id_clicked = id;
  ajaxFunction(string);
}


function report_spam(story_id,which, id){ /* could be comment or story */
  var string = 'action=report_spam&id='+story_id+'&which=' + which;
  global_id_clicked = id;
  ajaxFunction(string);
}

function rate_comment(comment_id,which,id){
  var string = 'action=rate_comment&id='+comment_id+'&which=' + which;
  global_id_clicked = id;
  ajaxFunction(string);
  //alert('voted : ' +which);
}

function submit_suggestion(){
  var suggestion = document.getElementById('suggestion_box_textarea').value;
  var string = 'action=suggestion_box&suggestion='+suggestion;
  
  close_popup('suggestion_box');
  open_popup('ajax_wait_popup');
  
  ajaxFunction(string);
}




function ajaxFunction(stringToServe){

	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Something just broke, refresh the page and try again..sorry for the inconvenience...");
				return false;
			}
		}
	}
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var holdResult = ajaxRequest.responseText;
			//alert(holdResult);
			handleServerData(holdResult);
		}
	}
	
	// WHERE STUFF NEEDS TO BE SENT TO THE SERVER
		//alert("serving up :"  + stringToServe);
	      //ajaxRequest.open("POST", "/includes/js/handle_ajax.php" + "?" + stringToServe, true);
        ajaxRequest.open("POST", "/includes/js/handle_ajax.php", true);
        ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxRequest.setRequestHeader("Content-length", stringToServe.length);
        ajaxRequest.setRequestHeader("Connection", "close");
	      ajaxRequest.send(stringToServe);
}


function handleServerData(stringFromServer){

	var data = stringFromServer.split(":");
  var action = data.shift();
	switch(action)
	{
		case 'new_story':
		  new_story_return(data);
		  break;    
		case 'digg':
		  handle_digg(data);
		  break;
		case 'report_spam':
		  handle_report_spam(data);
		  break;
		case 'check_unique':
		  handle_check_unique(data);
		  break;
		case 'check_captcha':
      handle_check_captcha(data);
      break;  
    case 'registration_check_all':
      handle_registration_check_all(data);
      break;
		case 'suggestion_box':
		  handle_suggestion_box(data);
		  break;
		case 'update_avatar':
		  handle_update_avatar(data);
		  break;
		case 'update_password':
		  handle_update_password(data);
		  break;
		case 'recover_account':
		  handle_recover_account(data);
		  break;
		case 'rate_comment':
      handle_rate_comment(data);
      break;  
    case 'update_settings':
      handle_update_settings(data);
      break;
		default:
			alert("server error, refresh and try again.. if problem occurs repeatedly please email admin@pessimisticlove.com. Thanks!" + stringFromServer);
	}
}

function new_story_return(data){
  if(data[0] == 1){
    document.getElementById('ajax_wait_popup').style.display = 'none';
    document.getElementById('submit_success_popup').style.display = 'block';
  }
  else
  {
    document.getElementById('ajax_wait_popup').style.display = 'none';
    document.getElementById('server_error_popup').style.display = 'block';
  }
}

function handle_digg(data){
  if(data[0] == 1){
    var count = data[1];
    var id = global_id_clicked;
    
    //disable anymore clicking on any of the links for that particular story
    var count_up_link = document.getElementById('count_up_link_'+id);
    var count_down_link = document.getElementById('count_down_link_'+id);
    var count_up_link_text = document.getElementById('count_up_link_text_'+id);
    var count_down_link_text = document.getElementById('count_down_link_text_'+id);
    
    count_up_link.href='javascript:void(0)';
    count_up_link.disabled=1;
    count_up_link.onclick = '';
    count_up_link.style.cursor = 'auto';
    
    count_down_link.href='javascript:void(0)';
    count_down_link.disabled=1;
    count_down_link.onclick = '';
    count_down_link.style.cursor = 'auto';
    
    count_up_link_text.href='javascript:void(0)';
    count_up_link_text.disabled=1;
    count_up_link_text.onclick = '';
    count_up_link_text.className = "icon_text no_click";
    
    count_down_link_text.href='javascript:void(0)';
    count_down_link_text.disabled=1;
    count_down_link_text.onclick = '';
    count_down_link_text.className = "icon_text no_click";
    
    //show an update for whatever was set based on data[3] .. 0 = down 1 = up
        
    if(data[2] == '0'){
      document.getElementById('count_down_'+id).innerHTML = data[1];
    }
    else{
      document.getElementById('count_up_'+id).innerHTML = data[1];    
    }
    
    
  }
  else{
    alert('server error .. ' + data[1]);
  }
}

function handle_report_spam(data){
  if(data[0] == 1){
    var id = global_id_clicked;
    
    if(data[1] == 'story'){

      var spam_link_icon = document.getElementById('report_spam_icon_' + id);
      var spam_link_text = document.getElementById('report_spam_text_' + id);
      
      spam_link_icon.href='javascript:void(0)';
      spam_link_icon.disabled=1;
      spam_link_icon.onclick = '';
      spam_link_icon.style.cursor = 'auto';
  
      spam_link_text.href='javascript:void(0)';
      spam_link_text.disabled=1;
      spam_link_text.onclick = '';
      spam_link_text.className = "icon_text no_click";  
    }
    else{
      var spam_link_text = document.getElementById('comment_spam_' + id);    
      spam_link_text.href='javascript:void(0)';
      spam_link_text.disabled=1;
      spam_link_text.onclick = '';
      spam_link_text.className = "no_click";      
    }  
    
  }
  else{
    alert('server_error .. ' + data[1]);
  }

}

function handle_check_unique(data){
  if(data[0] == 1){
    var what = data[1];
    if(data[2] == 1){
      alert('was unique');
    }
    else{
      alert('not unique');
    }
  }
  else{
    alert('server error .. ' + data[1]);
  }
}

function handle_check_captcha(data){
  if(data[0] == 1){
    if(data[1] == 1){
      alert('captcha correct');
    }
    else{
      alert('captcha false .. ' + data[2]);
    }
  }
  else{
    alert('server error which checking captcha');
  }
}

function handle_registration_check_all(data){
  if(data[0] == 1){
    if(data[1] == 1){
      document.getElementById('reg_confirm_username_unique_icon').style.backgroundImage = "url(/includes/images/green_check_small.png)";
      document.getElementById('reg_confirm_username_unique_icon').style.display = 'block';    
      if(data[2] == 1){
        document.getElementById('reg_confirm_email_unique_icon').style.backgroundImage = "url(/includes/images/green_check_small.png)";
        document.getElementById('reg_confirm_email_unique_icon').style.display = 'block';    
        if(data[3] == 1){
          document.getElementById('reg_confirm_captcha_icon').style.backgroundImage = "url(/includes/images/green_check_small.png)";
          document.getElementById('reg_confirm_captcha_icon').style.display = 'block';
          document.getElementById('reg_ajax_spinner').style.display = 'none'; 
          
          // yay everything is good .. .time to submit the form!
          document.getElementById('registration_form').submit();
          
          
        }
        else{
        document.getElementById('reg_confirm_captcha_icon').style.backgroundImage = "url(/includes/images/red_x_small.png)";
        document.getElementById('reg_confirm_captcha_icon').style.display = 'block';
        
        var red_x = document.getElementById('reg_captcha_error');
        red_x.style.backgroundImage = "url(/includes/images/red_x_small.png)";
        red_x.style.display = 'block';
        
        document.getElementById('registration_description').innerHTML = 'Incorrect Sercurity Code, please try again.';
        document.getElementById('registration_description').style.visibility = 'visible';
        document.getElementById('reg_ajax_spinner').style.display = 'none';
        }
      }
      else{
      document.getElementById('reg_confirm_email_unique_icon').style.backgroundImage = "url(/includes/images/red_x_small.png)";
      document.getElementById('reg_confirm_email_unique_icon').style.display = 'block';
      
      var red_x = document.getElementById('reg_email_error');
      red_x.style.backgroundImage = "url(/includes/images/red_x_small.png)";
      red_x.style.display = 'block'; 
      
      document.getElementById('registration_description').innerHTML = 'Email is not unique, please use another or <a href=\'#\'>resend account info </a>.';
      document.getElementById('registration_description').style.visibility = 'visible';
      document.getElementById('reg_ajax_spinner').style.display = 'none';
      }
    }
    else{
      document.getElementById('reg_confirm_username_unique_icon').style.backgroundImage = "url(/includes/images/red_x_small.png)";
      document.getElementById('reg_confirm_username_unique_icon').style.display = 'block';
      
      var red_x = document.getElementById('reg_username_error');
      red_x.style.backgroundImage = "url(/includes/images/red_x_small.png)";
      red_x.style.display = 'block';       
      
      document.getElementById('registration_description').innerHTML = 'Username is not unique, please pick another.';
      document.getElementById('registration_description').style.visibility = 'visible';
      document.getElementById('reg_ajax_spinner').style.display = 'none';
    }  
  }
  else{
    alert('server error while checking all');
  }

}

  function handle_suggestion_box(data){
    if(data[0] == 1){
    close_popup('ajax_wait_popup');
    open_popup('submit_success_popup');
    }
    else{
      alert('server error w/suggestion box .. please refresh and try again');
    }
  
  }

  function handle_update_avatar(data){
    if(data[0] == 1){
      var gender = data[1];
      var hair   = data[2];
      var skin   = data[3];
      var shirt  = data[4];
      
      document.getElementById('my_avatar_skin').style.backgroundImage = 'url(/includes/images/avatar_parts/'+gender+'/skin/'+skin+'.png)';
      document.getElementById('my_avatar_shirt').style.backgroundImage = 'url(/includes/images/avatar_parts/'+gender+'/shirt/'+shirt+'.png)';
      document.getElementById('my_avatar_hair').style.backgroundImage = 'url(/includes/images/avatar_parts/'+gender+'/hair/'+hair+'.png)';
      
      document.getElementById('my_ajax_loader').style.display = 'none';
      document.getElementById('my_info_personal').style.display = 'block';      
    
    }
    else{
      alert('server error w/update avatar .. refresh and try again');
    }
  }

  function handle_update_password(data){
    if(data[0] == 1){
      alert(data[1] == 1);
      if(data[1] == 1){
        document.getElementById('update_pass_error').innerHTML = "Password updated.";
        document.getElementById('update_pass_error').style.color = 'green';
        document.getElementById('update_pass_error').style.display = 'block';      
      }
      else{ //error
        document.getElementById('update_pass_error').innerHTML = data[2];
        document.getElementById('update_pass_error').style.color = 'red';
        document.getElementById('update_pass_error').style.display = 'block';
      }
    
    }
    else{
      alert('server error w/update password... refresh and try again');
    }
  
  
  }

  function handle_recover_account(data){
    if(data[0] == 1){
      if(data[1] == 1){ // email was sent
        document.getElementById('forget_pass_error_message').innerHTML = "Email was sent, follow instructions for account recovery.";
        document.getElementById('forget_pass_error_message').style.visibility = 'visible';
      }
      else{ // account not found
        document.getElementById('forget_pass_error_message').innerHTML = "No account was found associated with that email.";
        document.getElementById('forget_pass_error_message').style.visibility = 'visible';      
      }
    
    }
    else{
      alert('server error w/send email ... refresh and try again');
    }
  
  }


  function handle_rate_comment(data){
    if(data[0] == 1){
      var id = global_id_clicked;
    
      //disable anymore clicking on any of the links for that particular story
      var count_up_link = document.getElementById('vote_comment_up_'+id);
      var count_down_link = document.getElementById('vote_comment_down_'+id);
      var count_up_link_text = document.getElementById('vote_comment_up_text_'+id);
      var count_down_link_text = document.getElementById('vote_comment_down_text_'+id);
      
      count_up_link_text.href='javascript:void(0)';
      count_up_link_text.disabled=1;
      count_up_link_text.onclick = '';
      count_up_link_text.className = "no_click";
      
      count_down_link_text.href='javascript:void(0)';
      count_down_link_text.disabled=1;
      count_down_link_text.onclick = '';
      count_down_link_text.className = "no_click";
      
      //show an update for whatever was set based on data[1] .. 0 = down 1 = up
          
      if(data[1] == '0'){
        var count = parseInt(count_down_link.innerHTML);
        count += 1;
        count_down_link.innerHTML = count;
      }
      else{
        var count = parseInt(count_up_link.innerHTML);   
        count += 1;
        count_up_link.innerHTML = count; 
      }
    
    }
    else{
      alert('server error/w rate comment ... refresh and try again');
    }
  
  }


  function handle_update_settings(data){
    if(data[0] == 1){
      var newsletter      = data[1];
      var comment_email   = data[2];

      var checked = newsletter == 1 ? true : false;
      document.getElementById('my_info_receive_newsletter_checkbox').checked = checked;
      
      switch(comment_email){
        case 0:
          document.getElementById('my_info_email_comment_option1').checked = false;
          document.getElementById('my_info_email_comment_option2').checked = false;      
          document.getElementById('my_info_email_comment_option3').checked = true;  
    
        case 1:
          document.getElementById('my_info_email_comment_option1').checked = true;
          document.getElementById('my_info_email_comment_option2').checked = false;
          document.getElementById('my_info_email_comment_option3').checked = false;  
          break;
        case 2:
          document.getElementById('my_info_email_comment_option1').checked = false;
          document.getElementById('my_info_email_comment_option2').checked = true;
          document.getElementById('my_info_email_comment_option3').checked = false; 
          break;
      }
           
      document.getElementById('my_ajax_loader').style.display = 'none';
      document.getElementById('my_info_personal').style.display = 'block';      
    
    }
    else{
      alert('server error w/update avatar .. refresh and try again');
    }    
  
  }

/* OTHER HELPER FUNCTIONS */





    function new_story(){
      document.getElementById('transparent_wrapper').style.display = 'block';
      document.getElementById('submit_story_div').style.display = 'block';
    }
    
    function open_register_popup(){
      loadjsfile('/includes/js/registration.js');
      document.getElementById('transparent_wrapper').style.display='block';
      document.getElementById('registration_div').style.display = 'block';    
    }
    
    function submit_story(flag){
      if(flag == 'true'){ //stuff to be saved .. otherwise just close everything
        ajax_submit_story();
        document.getElementById('submit_story_div').style.display = 'none';  
        document.getElementById('ajax_wait_popup').style.display = 'block';
        //should start a timer that will timeout eventually if it takes too long
      }
      else{
        document.getElementById('transparent_wrapper').style.display = 'none';
        document.getElementById('submit_story_div').style.display = 'none';   
        document.getElementById('submit_success_story_div').style.display = 'none';  
        document.getElementById('server_error_popup').style.display = 'none';  
      }
    }
    
    function close_popup(which){
      
      //need to show all the ads
      var ads = getElementsByClassName("ad_container");
      for(var i = 0; i < ads.length; i++){
        ads[i].style.display = 'block';
      }
      
      document.getElementById(which).style.display = 'none';
      document.getElementById('transparent_wrapper').style.display = 'none';
    }
    
    function open_popup(which){
      document.getElementById('transparent_wrapper').style.display = 'block'; 
      document.getElementById(which).style.display = 'block';
      
      //need to hide all the ads
      var ads = getElementsByClassName("ad_container");
      for(var i = 0; i < ads.length; i++){
        ads[i].style.display = 'none';
      }
      javascript:scroll(0,0);
    }
    
    
    function loadjsfile(filename){
      var fileref=document.createElement('script')
      fileref.setAttribute("type","text/javascript")
      fileref.setAttribute("src", filename)

     if (typeof fileref!="undefined")
      document.getElementsByTagName("head")[0].appendChild(fileref)
    }

    function gotourl(url){
      window.location = url;
    }
    
    function external(targetUrl) {
      var props = "location=yes,menubar=yes,resizable=yes,scrollbars =yes,status=yes,toolbar=yes";
      window.open(targetUrl, 'external', props);
      return false;
    }
    
/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
    
loadjsfile('/includes/js/avatar.js');
