// ustawienia
var maxLength = 73; //maksymalna dlugosc smsa
var limit = 4; // ilosc wyswietlanych wiadomosci
var txtFail = 'Cos poszlo nie tak.';
var txtLimit = 'Wyslales juz zbyt duzo smsow.';
var txtBan = 'Jestes na czarnej liscie. Nie mozesz wysylac smsow. Zglos problem inna droga.';
var txtToken = 'Test na inteligencję niezdany.';





var lastnumber = limit;
var lastquery = '';
var intval = '';
var http_request = new Array();
addEvent(window, "load", registerEvents);

function addEvent(obj, event, func) {
	if(obj.addEventListener) {
		obj.addEventListener(event, func, false);
	} else {
		obj.attachEvent("on"+event, func);
	}
}

function elem(objName) {
	return document.getElementById(objName);
}

function registerEvents() {
	addEvent(elem('smshelpbtn'), "click", helpMe);
	addEvent(elem('helpclose'), "click", closeHelp);
	addEvent(elem('helpsend'), "click", send);
	addEvent(elem('helpDesc'), "keyup", change);
	addEvent(elem('helpLogin'), "keyup", change);
}

function helpMe() {
  ajaxAction('/wp-content/themes/rootnode/sms/readsms.php?ln='+lastnumber, 'print');
  intval = setInterval("ajaxAction('/wp-content/themes/rootnode/sms/readsms.php?ln="+lastnumber+"', 'printint');", 60000);
  change();
  elem('smshelpwrapper').style.opacity = 0;
  elem('smshelpwrapper').style.display = 'block';
  $("#smshelpwrapper").fadeTo("fast", 0.8);
  elem('smshelp').style.display = 'block';
  $("#smshelp").fadeIn("normal");
}

function send() {
  var desc = php_urlencode(elem('helpDesc').value);
  var login = php_urlencode(elem('helpLogin').value);
  var token = php_urlencode(elem('helpInt').value);
  var sms = login + ': ' + desc;
  if(login == '') $("#helpLogin").animate({ borderTopColor : "red", borderBottomColor : "red", borderLeftColor : "red", borderRightColor : "red", backgroundColor : "#fffdcb" }, "fast").animate({ borderTopColor : "black", borderBottomColor : "black", borderLeftColor : "black", borderRightColor : "black", backgroundColor : "white" }, 3000);
  else if(desc == '') $("#helpDesc").animate({ borderTopColor : "red", borderBottomColor : "red", borderLeftColor : "red", borderRightColor : "red", backgroundColor : "#fffdcb" }, "fast").animate({ borderTopColor : "black", borderBottomColor : "black", borderLeftColor : "black", borderRightColor : "black", backgroundColor : "white" }, 3000);
  else {
    lastnumber++;
	  clearInterval(intval);
	  intval = '';
    ajaxAction('/wp-content/themes/rootnode/sms/sendsms.php?text='+ desc + '&login=' + login + '&token=' + token, 'send');
  }
}

function closeHelp() {
  $("#smshelpwrapper").fadeOut("fast");
  $("#smshelp").fadeOut("normal");
  clearInterval(intval);
  intval = '';
  lastnumber = limit;
}

function ajaxAction(url, action) {
	http_request[action] = false;
	if (window.XMLHttpRequest) {
		http_request[action] = new XMLHttpRequest();
		if (http_request[action].overrideMimeType) {
			http_request[action].overrideMimeType('text/html; charset=UTF-8');
		}
	} else if (window.ActiveXObject) {
		try {
			http_request[action] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request[action] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request[action]) {
		return false;
	}
	http_request[action].onreadystatechange = function() {
    if(action == 'print') printSMSs(http_request[action]);
    if(action == 'printint') printSMSs(http_request[action], false);
    if(action == 'send') sendSMS(http_request[action]);
  };
	http_request[action].open('GET', url, true);
	http_request[action].send(null);
}

function printSMSs(http_request, anim) {
  if(anim == null) anim = true;
  if (http_request.readyState == (0 || 1)) {
    if(anim) {
      $("#helplast").fadeTo("fast", .5);
      elem('ajaxLoader').style.display = 'block';
    }
	}
	if (http_request.readyState == 4) {
	  if(anim) {
	    elem('ajaxLoader').style.display = 'none';
	    $("#helplast").fadeTo("fast", 1);
	  }
	  if(lastquery != http_request.responseText) {
	    lastquery = http_request.responseText;
	    $("helplast").fadeOut("fast");
      elem('helplast').innerHTML = lastquery;
      $("helplast").fadeIn("fast");
    }
	}
}

function sendSMS(http_request) {
  if (http_request.readyState == (0 || 1)) {
    $("#helplast").fadeTo("fast", .5);
		elem('ajaxLoader').style.display = 'block';
	}
	if (http_request.readyState == 4) {
	  var answer = http_request.responseText;
	  elem('ajaxLoader').style.display = 'none';
	  $("#helplast").fadeTo("fast", 1);
	  if(answer == "OK") {
	    elem('helplast').innerHTML = '<p class="helpadded"><span class="helplogin">'+elem('helpLogin').value+'</span> <span class="helpdate">(przed chwilą)</span>: '+elem('helpDesc').value+'</p>' + elem('helplast').innerHTML;
	    $(".helpadded").show("slow").animate({opacity: 1.0}, 1000).animate({ backgroundColor : "#ffffff" }, "slow");
    } else {
      var erroralert = "";
      if(answer == "LIMIT") erroralert = txtLimit;
      else if(answer == "BAN") erroralert = txtBan;
      else if(answer == "TOKEN") erroralert = txtToken;
      else erroralert = txtFail;
      elem('helplast').innerHTML = '<p class="helperroralert">' + erroralert + '</p>' + elem('helplast').innerHTML;
      $(".helperroralert").show("slow").animate({opacity: 1.0}, 1000).animate({ backgroundColor : "#ffffff" }, "slow");
      lastnumber--;
    }
	  elem('helpDesc').value = '';
    elem('helpLogin').value = '';
    elem('helpInt').value = '';
    change();
    setTimeout("ajaxAction('/wp-content/themes/rootnode/sms/readsms.php?ln="+lastnumber+"', 'printint');", 10000);
    intval = setInterval("ajaxAction('/wp-content/themes/rootnode/sms/readsms.php?ln="+lastnumber+"', 'printint');", 60000);
	}
}

function php_urlencode(str) {
  str;
  return str.replace(/[*+\/@żółćęśąźńŻÓŁĆĘŚĄŹŃ]|%20/g, function (s) {
    switch (s) {
    case "*": s = "%2A"; break;
    case "+": s = "%2B"; break;
    case "/": s = "%2F"; break;
    case "@": s = "%40"; break;
    case "%20": s = "+"; break;
    case "ż": s = "z"; break;
    case "ó": s = "o"; break;
    case "ł": s = "l"; break;
    case "ć": s = "c"; break;
    case "ę": s = "e"; break;
    case "ś": s = "s"; break;
    case "ą": s = "a"; break;
    case "ź": s = "z"; break;
    case "ń": s = "n"; break;
    case "Ż": s = "Z"; break;
    case "Ó": s = "O"; break;
    case "Ł": s = "L"; break;
    case "Ć": s = "C"; break;
    case "Ę": s = "E"; break;
    case "Ś": s = "S"; break;
    case "Ą": s = "A"; break;
    case "Ź": s = "Z"; break;
    case "Ń": s = "N"; break;
    }
    return s;
  });
}

function smsLength() {
  var desc = php_urlencode(elem('helpDesc').value);
  var login = php_urlencode(elem('helpLogin').value);
  var sms = login + ': ' + desc;
  return sms.length;
}

function change() {
  var textChars = '';
  var charsNumber = maxLength - smsLength() - 1;
  if(charsNumber <= 10) textChars += '<span class="lessChars">';
  textChars += 'Zostało ' + charsNumber + ' znaków.';
  if(charsNumber <= 10) textChars += '</span>';
  elem('helpchars').innerHTML = textChars;
  if(charsNumber < 0) elem('helpDesc').value = elem('helpDesc').value.substring(0, maxLength - elem('helpLogin').value.length - 3);
}

