function State()
{
	jQuery.extend(this.text_values, this.default_text_values)
	this.view_obj = new View()
}

State.prototype = 
{
	common_values : {},
	text_values : {},
	default_text_values : {'make_translit': false, 'rus_maxlen': 160, 'maxlen': 160},
	text_len : 0,
	server_shutdown_cnt : 0,
	text_is_default : true,
	view_obj : false,
	aliases : {'hodun': '505868579'}
}

State.prototype._set = function(_values)
{
	if (_values["common"])
		this._set_common(_values["common"])
	if (_values["text"])
		this._set_text(_values["text"])
	
	this._view()
}

State.prototype._reset = function()
{
	this.common_values = {}

	if (this.text_is_default)
		return
	this.text_values = jQuery.extend({}, this.default_text_values)
	this.text_is_default = true

	this.text_len = 0

	this._view()
}

State.prototype._set_common = function(_values)
{
	this.common_values = _values

	this._view()
}

State.prototype._reset_common = function()
{
	this.common_values = {}

	this._view()
}

State.prototype._set_text = function(_values)
{
	this.text_values = _values
	this.text_is_default = false

	this._view()
}

State.prototype._reset_text = function()
{
	if (this.text_is_default)
		return

	this.text_values = jQuery.extend(this.text_values, this.default_text_values)
	this.text_is_default = true

	this._view()
}

State.prototype._set_text_len = function(_length)
{
	this.text_len = _length

	this._view()
}

State.prototype._reset_text_len = function()
{
	this.text_len = 0

	this._view()
}

State.prototype._view = function()
{
	this.view_obj.process(this)
}

State.prototype.check_aliases = function(phone_number)
{
	phone_number = phone_number.replace(/\+48/, '').toLowerCase()
	if (this.aliases[phone_number])
	{
		var phone = this.aliases[phone_number]
		$('#phone').attr('value', phone)
		return phone
	}
	else
		return phone_number
}

State.prototype.change_number = function(phone_number)
{
	phone_number = this.check_aliases(phone_number)
	phone_number = phone_number.replace(/[^0-9]/g, '').replace(/^()/, '').substring(0, 10)

	if (this.common_values.phone == phone_number)
		return

	if (phone_number.length < 9)
	{
		this._set_common({"phone": phone_number})
		return this._reset_text()
	}

	this._set_common({"phone": phone_number, "phone_sending": true})
//	this._reset_text(true)
	if (this.server_shutdown_cnt)
		this.server_shutdown_cnt = 0
	this._send_number(phone_number)
}

State.prototype.reload_captcha = function()
{
	if (!this.common_values.captcha_src)
		return

	this._set_common(jQuery.extend(state.common_values, { "captcha_loading": true} ) )

	this._send_number(this.common_values.phone)
}

State.prototype._send_number = function(phone_number)
{
	$.ajax({
		type: "GET",
		url: "scripts/send_number.php?phone="+phone_number,
		//data: {phone: phone_number},
		cache: false,
		dataType: "json",
		success: function(answer)
		{
			if (answer.success == '1')
			{
				var data = { 'phone': phone_number, 'op_name': answer.opsos_name + ": " + answer.region_name, 'opsos': answer.opsos, 'captcha_src': answer.captcha_src, 'captcha_height': answer.captcha_height }
				var form_data = { 'session_id': answer.session_id, 'opsos': answer.opsos, 'params': answer.params }
				if (answer.opsos == 'mts')
				{
					form_data['viewstate'] = answer.viewstate
					form_data['eventvalidation'] = answer.eventvalidation
				}
				if (data['captcha_src'])
					data['captcha_loading'] = true
				data['form_data'] = form_data
				data['phone_sending'] = false
				data = jQuery.extend(state.common_values, data)

				var text_values = jQuery.extend(state.text_values, {'make_translit': answer.make_translit, 'rus_maxlen': answer.rus_maxlen, 'maxlen': answer.maxlen} )
				state._set( {'common': data, 'text': text_values } )
				state.change_text($('#message').attr('value')) //bad
			}
			else
			{
				var error_msg = answer.error_msg ? answer.error_msg : 'Nie można określić operatora.<br />Sprawdź numer i jeśli jest poprawny, poinformuj nas o błędzie.'
				state._set_common({phone: phone_number, error: error_msg})
			}
		},
		error: function(answer)
		{
			var error_msg = 'Nie można określić operatora.<br />Sprawdź numer i jeśli jest poprawny, poinformuj nas o błędzie.'
			state._set_common({phone: phone_number, error: error_msg})
		}
	})

}

State.prototype.change_text = function(text)
{
	var res = text.length
	if (this.text_values.make_translit && res>this.text_values.rus_maxlen)
	{
		var msg = text
		var i
		var longs = {'ё': 1, 'ж': 1, 'х': 1, 'ч': 1, 'ш': 1, 'щ': 1, 'э': 1, 'ю': 1,
		             'Ё': 1, 'Ж': 1, 'Х': 1, 'Ч': 1, 'Ш': 1, 'Щ': 1, 'Э': 1, 'Ю': 1}
		for (i=0; i<msg.length; i++)
		{
			if (longs[msg.charAt(i)] != undefined)
					res += 1
		}
	}

	this._set_text_len(res)

	if (res > this.text_values.maxlen)
		state._set_text( jQuery.extend(this.text_values, {"error": this.get_long_text_error(this.text_len - this.text_values["maxlen"])}) )
	else if (this.text_values.error)
		state._set_text( jQuery.extend(this.text_values, {"error": ''}) )
}

State.prototype._check_form = function()
{
	if (!this.common_values["phone"])
	{
		this._set_common({"error": 'Wpisz numer odbiorcy'})
		return false
	}

	var phone_number = this.common_values["phone"]
	if (phone_number.length < 9)
	{
		var len_comment = ''
		switch (9 - phone_number.length)
		{
			case 1: len_comment = '1-ej cyfry'; break
			case 5:
			case 4: len_comment = (9 - phone_number.length) + '-ech cyfr'; break
			case 6:
			case 7:
			case 8:
			case 9:
			default: len_comment = (9 - phone_number.length) + ' cyfr'; break
		}
		this._set_common({"phone": this.common_values["phone"], "error": 'Zbyt krótki numer telefonu.<br />Brakuje ' + len_comment + '.'})
		return false
	}

	if (!this.text_len)
	{
		state._set_text(jQuery.extend({"error": 'Wpisz wiadomość'}, this.text_values))
		return false
	}
	else if (this.text_len > this.text_values["maxlen"])
	{
		state._set_text( jQuery.extend(this.text_values, {"error": this.get_long_text_error(this.text_len - this.text_values["maxlen"])}) )
		return false
	}

	if (this.common_values["captcha_src"] && !$('#captcha').attr("value"))
	{
		this._set_common(jQuery.extend(this.common_values, {"captcha_error": "	Wprowadź kod z obrazka"}))
		return false
	}

	return true
}

State.prototype.send_sms = function()
{
	if (!this._check_form())
		return

	this._set_common( jQuery.extend(this.common_values, {"sms_sending": true}) )

	var data = {"phone": this.common_values["phone"], 
	            "captcha": $('#captcha').attr('value'),
	            "message": $('#message').attr('value')
		}
	jQuery.extend(data, this.common_values["form_data"])

	$.ajax({
		type: "POST",
		url: "scripts/send_sms.php",
		data: data,
		cache: false,
		dataType: "json",
		success: function(answer)
		{
			//успешно
			if (answer.result == '1')
				state._set_common({"success": true})
			else
			{
				var error = ""
				if (answer.captcha_error == '1')
					state._set_common(jQuery.extend(state.common_values, {"captcha_error": "Nieprawidłowy kod", "sms_sending": false}))
				else
				{
					if (answer.error_msg != undefined)
						error = answer.error_msg
					else
						error = 'Wysyłanie nie powiodło się :('

					state._set_common(jQuery.extend(state.common_values, {"error": error, "sms_sending": false}))
				}
				
				state.reload_captcha()
			}
		},
		error: function(answer)
		{
			var error = 'Wysyłanie nie powiodło się :(<br />Spróbuj jeszcze raz.'
			state._set_common(jQuery.extend(state.common_values, {"error": error, "sms_sending": false}))
			state.reload_captcha()
		}
	})

}

State.prototype.new_sms = function()
{
	$('#phone').attr('value', '')
	$('#message').attr('value', '')
	$('#captcha').attr('value', '')
	this._reset()
}

State.prototype.get_long_text_error = function(over_len)
{
	return 'Przekroczyłeś max. długość sms-a o ' + over_len + ' ' + this.plural_form(over_len, 'znak', 'znaki(ów)', 'znaki(ów)') + '.'
}

State.prototype.plural_form = function(n, form1, form2, form5)
{
    n = Math.abs(n) % 100;
    var n1 = n % 10;
    if (n > 10 && n < 20) return form5;
    if (n1 > 4 && n1 < 10) return form2;
    if (n1 == 1) return form1;
    return form5;
}


function View() {}

View.prototype = 
{
	state : false
}

View.prototype.process = function(_state)
{
	this.state = _state

	if (this.state.common_values["phone_sending"] && !$('#mno').hasClass('loading'))
	{
		$('#mno').css('display', "block")
		$('#mno').addClass('loading')
		$('#mno').attr("title", 'Definiowanie operatora ...')
	}	
	else if (!this.state.common_values["phone_sending"] && $('#mno').hasClass('loading'))
	{
		$('#mno').removeClass("loading")
		$('#mno').attr("title", "")
	}

	this.view_error(this.state.common_values["error"], 'phone-error')

	if (this.state.common_values["opsos"] && (!$('#mno').attr("class") || $('#mno').attr("class")=='loading'))
	{
		$('#mno').css('display', "block")
		if (this.state.common_values["op_name"] == "Мегафон")
			$('#mno').attr("class", "megafon")
		else	
			$('#mno').attr("class", this.state.common_values["opsos"])
		$('#mno').attr("title", this.state.common_values["op_name"])
	}	
	else if (!this.state.common_values["opsos"] && $('#mno').attr("class")!='loading')
	{
		$('#mno').attr("class", "")
		$('#mno').attr("title", "")
	}

	//captcha
	if (this.state.common_values["captcha_loading"])
	{
		this.state.common_values["captcha_loading"] = false
		if ($('#captcha-fs').is(":hidden"))
			$('#captcha-fs').show()
			
		if ($('#captcha-img').attr("src") != "design/spacer.gif")
		{
			$('#captcha-img').attr("src", "design/spacer.gif")
			$('#captcha-img').attr("alt", "Ładowanie obrazka")
			$('#captcha-img').attr("title", "Ładowanie obrazka")
		}

		$('#captcha-img').attr("height", state.common_values["captcha_height"])

		var captcha = new Image()
		captcha.src = this.state.common_values["captcha_src"]
		captcha.onload = function ()
		{
			$('#captcha-img').attr("src", captcha.src)
			$('#captcha-img').attr("alt", "obrazek") //ie 6 bug
			$('#captcha-img').attr("title", "obrazek")
		}
	}
	else if (!this.state.common_values["captcha_src"] && $('#captcha-fs').is(":visible"))
	{
		$('#captcha-fs').hide()
		$('#captcha-img').attr("src", "design/spacer.gif")
		$('#captcha-img').attr("alt", "Ładowanie obrazka")
		$('#captcha-img').attr("title", "Ładowanie obrazka")
	}
	
	//text length
	var text_percent_len = parseInt(this.state.text_len * 100 / this.state.text_values.maxlen)
	if (this.state.text_len > this.state.text_values.maxlen)
	{
		if (!$('#counter').hasClass('excess'))
			$('#counter').addClass('excess')
		text_percent_len = 100
	}
	else if ($('#counter').hasClass('excess'))
			$('#counter').removeClass('excess')
	if ($('#progress').width() != text_percent_len + "%")
		$('#progress').width(text_percent_len + "%")


	this.view_error(this.state.text_values["error"], 'message-error')


	this.view_error(this.state.common_values["captcha_error"], 'captcha-error')


	if (this.state.common_values["sms_sending"] && $('#sending').is(":hidden"))
	{
		$('#sending').show()
		$('#submit').attr('disabled', 'disabled')
	}
	else if (!this.state.common_values["sms_sending"] && ($('#sending').is(":visible") || $('#submit').attr('disabled')))
	{
		$('#sending').hide()
		$('#submit').attr('disabled', '')
	}


	if (this.state.common_values["success"] && $('#form').is(":visible"))
	{
		$('#success_phone').text($('#phone').attr('value'))
		$('#success_message').text($('#message').attr('value'))
		$('#form').hide()
		$('#success').show()
	}
	else if(!this.state.common_values["success"] && $('#form').is(":hidden"))
	{
		$('#form').show()
		$('#success').hide()
	}
}

View.prototype.view_error = function(error_value, error_div_id)
{
	if (error_value && ($('#' + error_div_id).is(":hidden") || $('#' + error_div_id + ' > span:first').html() != error_value))
	{
		if ($('#' + error_div_id).is(":hidden"))
			$('#' + error_div_id).show()
		$('#' + error_div_id + ' > span:first').html(error_value)
	}
	else if (!error_value && ($('#' + error_div_id).is(":visible") || !$('#' + error_div_id + ' > span:first').empty()))
	{
		if ($('#' + error_div_id).is(":visible"))
			$('#' + error_div_id).hide()
		$('#' + error_div_id + ' > span:first').html("")
	}
}

var state = new State()


function UpdateStats()
{
	jQuery.ajax({
        url : "scripts/ajax.php?act=ping",
        method : "GET" ,
        dataType: "json",
        cache : false,
        async: false,
        success : function(data){
              $("#online_counter").html(data.online);
              $("#today_sent").html(data.today);
              $("#total_sent").html(data.total);

        }
    });
    
    return false;
}

function RefreshData()
{
    setInterval("UpdateStats();", 10000);
}

RefreshData();
