// ==UserScript==
// @name          Experts-Exchange Blacklisting
// @author        Ciuly  
// @namespace     http://www.ciuly.com
// @description   Blaklists an asker (posts to ciuly.com, unsubscribes from question and updates filter)
// @include       http://www.experts-exchange.com/*/Q_*.html*
// @include       http://www.experts-exchange.com/*/Q-*.html*
// ==/UserScript==

// ************** do not modify the following 8-10 lines unless you know what you are doing

var forms, form, uid, uname, div;
var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') != -1;
var wnd;

if (is_opera)
  wnd = window;
else
  wnd = unsafeWindow;



// ************** START EDITING FROM HERE



  wnd.ciuly_filterID = 384; //you must place correct id in the following line (this is specific to each expert):
  wnd.ciuly_publishBlacklist = true;// set this to true in order to publish your blacklist on http://www.ciuly.com/ee/bl/hall-of-shame.php
  wnd.ciuly_bl_askForReason = true;// if true, this will ask you for a reason to place on the above link. you can leave it to true and just cancel the dialog for particular cases when you don't want a reason published
  wnd.ciuly_bl_password = "bogus";// DO NOT change this to your ciuly.com/ee password, unless your browser does not allow cookies so you cannot maintain logged in status in my site. If you are logged in, bogus password is correct.
  wnd.ciuly_unsubscribe = false;// if true, this will unsubscribe you from the question



// ************** DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING




  wnd.ciuly_post = function(url, data) {
	var request = new XMLHttpRequest();
	var error = 0;
	while (error!=-1){
		request.open("POST", url, false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.send(data);
	
		var error = request.responseText.indexOf("Sorry, an error occurred.");
		if (error!=-1){
			w = window.open('','');
			w. document.write(request.responseText);
			w.focus();
			if (confirm("Error posting to url. Try again?"))
				; 
			else
				return false;
		}
	}
	return true;
  };

  wnd.ciuly_get = function(url) {
	var request = new XMLHttpRequest();
	var error = 0;
	while (error!=-1){
		request.open("GET", url, false);
//		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.send(null);
	
		var error = request.responseText.indexOf("Sorry, an error occurred.");
		if (error!=-1){
			w = window.open('','');
			w. document.write(request.responseText);
			w.focus();
			if (confirm("Error getting url. Try again?"))
				; 
			else
				return "";
		}
	}
	return request.responseText;
  };

  wnd.ciuly_update_filter = function (title, askers, taids_space, taids_comma, perpage){
	return wnd.ciuly_post( "/experts.jsp?ssfSearchID="+wnd.ciuly_filterID+"&amp;etIndex=2", 
		"q=-asker%3A%28"+encodeURIComponent(askers)+"%29+AND+taid%3A+%28"+encodeURIComponent(taids_space)+"%29+AND+results%3A%28"+perpage+"%29"+
		"&ssfTitle="+encodeURIComponent(title)+
		"&ssfSearchID="+wnd.ciuly_filterID+
		"&ssfEditedSearch=true"+
		"&ssfAlertType=10"+
		"&ssfTermCount=1"+
		"&ssfTermIndex0=0"+
		"&ssfTermInclude0=false"+
		"&ssfTermType0=2"+
		"&ssfTerms0="+encodeURIComponent(askers)+
		"&ssfTermScope0=4"+
		"&ssfConjoiner0=0"+
		"&ssfTAIDs="+encodeURIComponent(taids_comma)+
		"&ssfTAIncludes=true"+
		"&sfDisplayCount="+perpage+
		"&ssfSubmit=1"
	);
  };

/*  wnd.ciuly_PostComment = function(message){
    // change all crlf (no matter the case) into \n
    message = message.replace(/crlf/gi,"\n");
    message = message.replace(/</gi,"&lt;");
    message = message.replace(/>/gi,"&gt;");
    qid = "";
    omnitureData = "";

    forms = document.body.getElementsByTagName("form");
    for (var j=0; j<forms.length; j++){
      form = forms.item(j);
      if ( form.className == "formFactory nameValue" ){
        for (var l=0; l<form.elements.length; l++){
          if (form.elements[l].name == "qid")
            qid = form.elements[l].value;
          else
          if (form.elements[l].name == "omnitureData")
            omnitureData = form.elements[l].value;
        }
        break;
      }
    }

	return wnd.ciuly_post( "answerQuestion.jsp", 
		"answerType=10"+
		"&text="+encodeURIComponent(message)+
		"&codeSnippet="+
		"&extraNotification=0"+
		"&qid="+qid+
		"&omnitureData="+omnitureData+
		"&Submit=1"
	);
  }
*/
  wnd.ciuly_unsubscribe_question = function(bogus){
    if (bogus.length==0)
      bogus = "";
    lis = document.body.getElementsByTagName("li");
    for (var i=0; i<lis.length; i++){
      li = lis.item(i);
      if (li.className == "notifyUnsubscribe"){
        wnd.ciuly_get(li.getElementsByTagName("a").item(0).getAttribute("href"));
        return true;
      }
    }
    return false;
  }

  wnd.htmlDecode = function ( text ) {
    text = text.replace(/&quot;/gi, String.fromCharCode(34));
    text = text.replace(/&amp;/gi, String.fromCharCode(38));
    text = text.replace(/&lt;/gi, String.fromCharCode(60));
    text = text.replace(/&gt;/gi, String.fromCharCode(62));
    return text;
  }

  wnd.ciuly_blacklist_user = function(user){
    askers = wnd.ciuly_get("http://www.experts-exchange.com/experts.jsp?ssfSearchID="+wnd.ciuly_filterID+"&etIndex=2&bogus="+encodeURIComponent(new Date())+"#expertTools");
    i = askers.indexOf("name=\"ssfTitle")+16;
    while (i<askers.length && askers[i]!='"') 
      i++;
    i++;
    title = "";
    while (i<askers.length && askers[i]!='"'){
      title=title+askers[i];
      i++;
    }
    title=wnd.htmlDecode(title);
    
    i = askers.indexOf("addTermQuery(new TermQuery(false,")+33;
    while (i<askers.length && askers[i] != "'")
      i++;
    askers = askers.substr(i+1, askers.length);
    i=0;
    while (i<askers.length && askers[i] != "'")
      i++;
    taids = askers.substr(i, askers.length);
    askers = askers.substr(0, i)+" "+user;
    i=0;
    while (i<taids.length && taids[i]!="]" && taids[i]!=".")
      i++;
    taids_space="";
    if (taids[i]=="]"){
      buff=taids.substr(i+1, taids.length);
      i=0;
      taids="";
      do {
        while (i<buff.length && (buff[i]<"0" || buff[i]>"9"))
          i++;
        while (i<buff.length && buff[i]>="0" && buff[i]<="9"){
          taids = taids + buff[i];
          taids_space = taids_space + buff[i];
          i++;
        }
        taids=taids+",";
	taids_space=taids_space+" ";
        while (i<buff.length && buff[i]!="]" && buff[i]!=".")
          i++;
      } while (buff[i]!=".");
    } else
      taids = "";
    if (taids.length>0) {
      taids=taids.substr(0, taids.length-1);
      taids_space=taids_space.substr(0, taids_space.length-1);
    }
    wnd.ciuly_update_filter(title, askers, taids_space, taids, 25);

    actualaskers = wnd.ciuly_get("http://www.experts-exchange.com/experts.jsp?ssfSearchID="+wnd.ciuly_filterID+"&etIndex=2&bogus="+encodeURIComponent(new Date())+"#expertTools");
    i = actualaskers.indexOf("addTermQuery(new TermQuery(false,")+33;
    while (i<actualaskers.length && actualaskers[i] != "'")
      i++;
    actualaskers = actualaskers.substr(i+1, actualaskers.length);
    i=0;
    while (i<actualaskers.length && actualaskers[i] != "'")
      i++;
    actualaskers = actualaskers.substr(0, i);

    arr = actualaskers.split(" ");
    ok = false;
    for (var i=0; i<arr.length; i++)
      if (arr[i].toLowerCase() == user.toLowerCase()){
        ok=true;
        break;
      }

    if (ok){
      alert("Blacklisting ok.");
      return true;
    }
    else{
      alert("Blacklisting failed for some reason.");
      return false;
    }
  }

  wnd.ciuly_publish_blacklist = function(asker){
    div = document.getElementsByClassName("loginName").item(0);
    expert = div.getElementsByTagName("a").item(0).innerHTML;
    reason = "";
    if (wnd.ciuly_bl_askForReason)
      reason = prompt("Reason (optional)", "");
    if (!reason)
      reason = "";
    url = window.location.href;
    url = url.substr(url.indexOf("/Q_"), url.length);
    i = url.indexOf("?");
    if (i>-1)
      url = url.substr(0, i);
    i = url.indexOf("#");
    if (i>-1)
      url = url.substr(0, i);
    url = "http://www.experts-exchange.com" + url;

    wnd.open("http://www.ciuly.com/ee/bl/add.php?"+
		"asker="+encodeURIComponent(asker)+
		"&expert="+encodeURIComponent(expert)+
//		"&password="+encodeURIComponent(wnd.ciuly_bl_password)+ no password for GET
		"&reason="+encodeURIComponent(reason)+
		"&url="+encodeURIComponent(url)+
		"&submit=submit"
            );
    return true;
/*  XSS is not allowed unfortunatly  
    return wnd.ciuly_post( "http://www.ciuly.com/ee/bl/add.php", 
		"asker="+encodeURIComponent(asker)+
		"&expert="+encodeURIComponent(expert)+
		"&password="+encodeURIComponent(wnd.ciuly_bl_password)+
		"&reason="+encodeURIComponent(reason)+
		"&url="+encodeURIComponent(url)+
		"&submit=submit"
	);*/
  }

  wnd.ciuly_blacklist = function(user){
    if (!wnd.ciuly_blacklist_user(user)){
      alert("Could not blacklist.");
      return false;
    }
/*    if (!wnd.ciuly_PostComment(message)){
      alert("Could not post comment.");
      return false;
    }*/
    if (wnd.ciuly_publishBlacklist && !wnd.ciuly_publish_blacklist(user))
      alert("For some reason could not publish blacklist.");
    if (wnd.ciuly_unsubscribe && !wnd.ciuly_unsubscribe_question(""))
      alert("Seems I could not unsubscribe. You will have to do it manually. Note that the comment was posted and asker was blacklisted.");
    else
      alert("Blacklisting finished ok. You can close this page now.");
    return false;
  }


var asker = "";

spans = document.getElementsByTagName("span");
for (var i=0; i<spans.length; i++){
  span = spans.item(i);
  aas = span.getElementsByTagName("a");
  if (span.className == "value" && aas.length==1){
    asker = aas.item(0).innerHTML;
    break;
  }
}

if (asker.length>0){
  var divs = document.body.getElementsByTagName("div");
  for (var i=0; i<divs.length; i++){
    div = divs.item(i);
    if (div.className == "s shF5FF sgray expGray sectionTwo nestedSection postComment"){
      td = div.getElementsByTagName("table").item(0).getElementsByTagName("td").item(1).getElementsByTagName("span").item(0);
      td.innerHTML = td.innerHTML + "&nbsp;&nbsp;&nbsp;<button class=\"button\" name=\"blacklist\" title=\"Blacklist asker\" onclick=\"return ciuly_blacklist('"+asker+"')\">BlackList</button>";
    }
  }
}