

	function initWidget(id){
		if (window.widgetStates == undefined){
			window.widgetStates = Array();
		}
		window.widgetStates[id] = false;

		$('#discountWidgetInput' + id).keyup(function(){validateInput(id)});
		$('#discountWidgetButton' + id).click(function(){buttonClicked(id)});
	}

	function validateInput(id){
		var phone = $('#discountWidgetInput' + id).val();

		setButton(id, 'OK');
		window.widgetStates[id] = false;

		if (!phone){
	    	disableButton(id);
			setMessage(id, 'Insert your mobile phone number');
		}
		else if (!phone.match(/^\+[0-9]{12}$/)){
			disableButton(id);
			setMessage(id, 'Wrong format. Here is a sample: +420123456789');
		}
		else {
			enableButton(id);	
			setMessage(id, 'Click on <strong>OK</strong> to check whether your number is in our system.');
		}
	}

	function setMessage(id, msg){
		$('#discountWidgetMsg' + id).empty().append(msg);
	}
	function setResult(id, msg){
		$('#discountWidget' + id).empty().append(msg);
	}
	function setButton(id, msg){
		$('#discountWidgetButton' + id).empty().append(msg);
	}
	function enableButton(id){
		$('#discountWidgetButton' + id).removeAttr('disabled');
	}
	function disableButton(id){
		$('#discountWidgetButton' + id).attr('disabled', 'disabled');
	}

	function buttonClicked(id){
		if (window.widgetStates[id]){
			sendDiscount(id);
		}
		else {
			checkDiscount(id);
		}
	}

		
	function makeUrl(path){
		return "http://amcham.mslevy.cz" + path + "?callback=?";
	}

	function checkDiscount(id){
		var phone = $('#discountWidgetInput' + id).val();

		$.getJSON(makeUrl("/code/check"),
				  {id : id, phone : phone},
				  function(data, textStatus){
						if (data == 'OK'){
		   					setButton(id, "SEND");
							setMessage(id, 'The number is in our system! Click on <strong>SEND</strong> to obtain the discount SMS.');
							window.widgetStates[id] = true;
						}
						else {
							setMessage(id, 'Unkown user! Your number is not in our system.');
							disableButton(id);
						}
				});
	}

	function sendDiscount(id){
		disableButton(id);

		var phone = $('#discountWidgetInput' + id).val();

		$.getJSON(makeUrl("/code/send"),
			  {id : id, phone : phone},
			  function(data, textStatus){
					if (data == 'OK'){
		 				setResult(id, "<b>Discount SMS sent.</b>");
					}
					else {
						setResult(id, "<b>Error occured during SMS sending. Please contact us if problem persists.</b>");
					}
			});
	}

    var code = '<div id="discountWidget1612">';
	code += '<span>';
	code += 'Send discount: ';
	code += '<input value="+420" id="discountWidgetInput1612" size="13" type="text"/>';
    code += '<button id="discountWidgetButton1612" disabled="disabled">OK</button>';
	code += '</span><br/>';
	code += '<span id="discountWidgetMsg1612">Insert your mobile phone number</span>';
    code += '</div>';

    document.write(code);

	initWidget(1612);


