﻿var Ajax = {
   create : function(url, options) {
      var XHR = Ajax.getXHR();
      var method = $Opt(options, "method", Ajax.method.GET);
      var params = $Opt(options, "params", null);

      if (params != undefined && method != Ajax.method.POST) {
         url += "?" + params;
      }
      XHR.open(method, url, true);
      XHR.onreadystatechange = function() {
         if (XHR.readyState==4)
            if (XHR.status==200)
               Ajax.answer(XHR, options)
      }
      if (method == Ajax.method.POST) {
         XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
      }
      XHR.send(params);
      var loading = $Opt(options, "loading");
      if (loading != undefined) {
         Ajax.loading(loading, true);
      }
   },
   getXHR : function() {
      var request = false;
      if (window.XMLHttpRequest) {
         request = new XMLHttpRequest();
      } else {
         if (ActiveXObject) {
            var versions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
            for (var i = 0; i < versions.length; i++) {
               try {
                  request = new ActiveXObject(versions[i]);
                  return request;
               } catch(e) {
               }
            }
         }
      }
      return request;
   },
   answer : function(XHR, options){
      var loading = $Opt(options, "loading");
      if (loading != undefined) {
         Ajax.loading(loading, false);
      }
      var onFinish = $Opt(options, "onFinish");
      if (onFinish != undefined) {
         var responseType = $Opt(options, "responseType", Ajax.type.TEXT);
         switch(responseType) {
            case Ajax.type.TEXT:
               onFinish(XHR.responseText);
            break;
            case Ajax.type.XML:
               onFinish(XHR.responseXML);
            break;
            case Ajax.type.JSON:
               var objekt;
               try {
                  objekt = evalJSON(XHR.responseText);
               } catch(e) {
                  Ajax.error('JSON Nieprawidłowy');
                  return;
               }
               onFinish(objekt);
         }
      }
   },
   loading : function(elemID, visible) {
      if(visible) {
        $(elemID).style.display = 'block';
      } else {
        $(elemID).style.display = 'none';
      }
   },
   error : function(e) {
      alert(e)
   },
   type : {
      XML : 0,
      TEXT : 1,
      JSON : 2
   },
   method : {
      GET : "GET",
      POST : "POST"
   }
}

function $Opt(collection, param, def) {
	if (collection == undefined) {
		return def;
	} else {
		if (collection[param] == undefined) {
			return def;
		} else {
			return collection[param];
		}
	}
}
function sendSMS(type){
	$('#sendsms_'+type).removeClass('ui-state-focus');
	$('#dialog').dialog('open');
	$('#dialog_text').html('<div class=\"ajax_loader\"><img src="img/ajax-loader.gif"></div>');

	if (type==0) {
		var mytimestamp = 0;
		if ($('input#sms_schedule_'+type).val()==1) {
			var arDate=$('input#time_'+type).val().split('/');
			var datum = new Date(arDate[0],arDate[1]-1,arDate[2],$('select#hour_'+type).val(),$('select#min_'+type).val(),'00'); 
			mytimestamp = datum.getTime()/1000;
		}
		var datacoding = '';
		if ($('input#gsm_'+type+':checked').val()==1) datacoding='gsm';
		Ajax.create("api/send.do", {
			method : Ajax.method.POST,
			responseType : Ajax.type.TEXT,
			params : 	"&from=" + encodeURIComponent($('select#sms_from_'+type).val()) + 
						"&to=" + encodeURIComponent($('textarea#sms_to_'+type).val()) + 
						"&message=" + encodeURIComponent($('textarea#sms_text_'+type).val()) +
						"&date=" + encodeURIComponent(mytimestamp) +
						"&schedule=" + encodeURIComponent($('select#schedule_'+type).val()*3600) +
						"&flash=" + encodeURIComponent($('input#flash_'+type+':checked').val()) +
						"&datacoding=" + encodeURIComponent(datacoding) +
						"&eco=" + encodeURIComponent($('input#eco_'+type+':checked').val()) +
						"&vcard=" + encodeURIComponent($('input#vcard_'+type+':checked').val()) +
						"&encoding=utf-8" +
						"&auth=1" +
						"&type=0",
			onFinish : function(text) {
				arResult=text.split(':');
				if (arResult[0]=='ERROR') {
					error = check_error(arResult[1]);
					error_type = 'Błąd: ';
				} else if (arResult[0]=='OK') {
					error_type = 'Wiadomość wysłano poprawnie!';
					error = '';
					num = $('#points').val() - arResult[2];
					pointsy = Math.floor(num);
					$('#points').val(num.toFixed(4));
					$('#propoints').val(pointsy);
					$('#ecopoints').val(Math.floor(num*2));
				}
				$('#dialog_text').html('<div class=\"ajax_loader\"><strong>'+error_type+'</strong>'+error+'</div>');
				$('#dialog').dialog('option','buttons', {'Ok': function() {	$(this).dialog('close'); }} );
			}
		});
	}
}
function getPrefix(pref){
	Ajax.create("premium_conf.html", {
		method : Ajax.method.POST,
		responseType : Ajax.type.TEXT,
		params : "la=" + pref,
		onFinish : function(text) {
			$('prefixy').innerHTML = '<option value="0">- wybierz prefix -</option>'+text;
			$('in_catch').value  = '';
			$('in_catch_err').innerHTML = '';
		}
	})
}
function getCatch(pref){
	Ajax.create("premium_conf.html", {
		method : Ajax.method.POST,
		responseType : Ajax.type.TEXT,
		params : "prefix=" + pref,
		onFinish : function(text) {
			if (text == '#error#') {
				$('in_catch_err').className  = 'in_catch in_catch_err';
				$('in_catch_err').innerHTML = 'Podany prefix jest nieprawidĹ‚owy!';
			} else if (text == '#taken#') {
				$('in_catch_err').className  = 'in_catch in_catch_err';
				$('in_catch_err').innerHTML = 'Podany prefix jest juĹĽ zajÄ™ty!';
			} else {
				$('in_catch').value  = text;
				$('in_catch_err').className  = 'in_catch in_catch_correct';
				$('in_catch_err').innerHTML = "<div class=\"button_blue\" style=\"display: inline;\"><button type=\"button\" class=\"button_link\" onClick=\"$('add_prefix').value='1'; document.add_client_names.submit();\">Zamawiam</button></div>";
			}
		}
	})
}
function allow_submit(type) {
	if (type=='1') {
		$('in_catch_err').innerHTML='';
		$('but_premium').disabled='';
		$('div_but_premium').className='button_blue';
		$('but_premium').className='button_link'
	} else {
		$('in_catch_err').innerHTML='';
		$('but_premium').disabled='disabled';
		$('div_but_premium').className='button_gray';
		$('but_premium').className='button_link_gray'
	}
}