<script type="text/javascript">
	var index2 = 0;
	var url = '/';
	
	$("#but-setting").bind("click",function(){
		$("#settings").slideToggle();
		if( $("#but-setting").html() == "Show Settings" ){
			$("#but-setting").html("Hide Settings")
		}else{
			$("#but-setting").html("Show Settings")
		}
	});
		
	/*=====================================================================================*/
	//validate
	$("#send").bind("click",function(){
		var ports = [];
		var checked_len = $("input[name=port]:checked").length;
		
		if( index2 >= checked_len ){
			index2 = 0;
		}
				
		$("[name=port]:checked").each(function(){
			ports[ports.length] = $(this).val();
		});
		
		if( ports == '' ){
			$("#send_waring").html('<span style="color:red;">Please select ports.</span>');
			return false;
		}else{
			$("#send_waring").html('');
		}
		
		var numbers = $("#sms_number").val();
		var how = [",",";"," ","\n"];
		var len = how.length;
		var _numbers = [] ,howto=[],_temp=[],_numbers_final = [];
		var _next = '',_next2='',_temp2=[];
		//
		var preg_phone2 = /\d+/gi;
		_numbers = numbers.match(preg_phone2);
		
		/*
		for(var i=0;i<len;i++){
			if( numbers.indexOf(how[i]) > 0 ){
				_numbers = numbers.split(how[i]);
				//break;
			}
		}
		*/

		if( _numbers == '' ){
			_numbers[0] = numbers;
		}
		/*
		if( _numbers.length > 0 ){
			var preg_phone = /^\d+$/;
			for(var i=0;i<_numbers.length;i++){
				if( _numbers[i].match(preg_phone) ){
					//
					_numbers_final[_numbers_final.length] = _numbers[i];
				}
			}
		}
		*/
		_numbers_final = _numbers;
		if( $("#sms_number").val() == '' ){
			$("#sms_number_msg").html('Please input Phone Number.');
			return false;
		}
		
		if( $("#sms_content").val() == '' ){
			$("#sms_content_msg").html('Please input message');
			return false;
		}
		
		$("#sms_detail").show();
		
		//ajax
		if( _numbers_final.length >=1  ){
			var gsm_index = 0 + index2;
			var index = 0;
			var port_str = '';
			
			for(var i=0;i<_numbers_final.length;i++){
				var data = '';
					data += 'state=send_msg';
					data += '&sms_ip='+$("#sms_ip").val();
					data += "&sms_number="+_numbers_final[i];
					data += "&sms_content="+$("#sms_content").val();
					data += "&sms_username="+$("#sms_username").val();
					data += "&sms_password="+$("#sms_password").val();
					
				if( ports.length > 1 ){
					//if( gsm_index >= (_numbers_final.length-1)  ){
					if( gsm_index >= (ports.length)  ){
						gsm_index = 0;
					}
					
					data += "&sms_port="+ports[gsm_index];
					port_str = ports[gsm_index];
					gsm_index++;					
				}else{
					data += "&sms_port="+ports[0];
				}
					
				if( ports.length > 1 ){
					//alert(port_str);
					//var str = "<tr class='add'><td>"+$("#sms_content").val()+"</td><td>"+_numbers_final[i]+"</td><td>"+ports[index]+"</td><td class='send_state'><img class='loading-img' src='/images/loading.gif' /></td></tr>";
					var str = "<tr class='add'><td>"+$("#sms_content").val()+"</td><td>"+_numbers_final[i]+"</td><td>"+port_str+"</td><td class='send_state'><img class='loading-img' src='/images/loading.gif' /></td></tr>";
					index++;
					if( index >= ports.length  ){
						index = 0;
					}
				}else{
					var str = "<tr class='add'><td>"+$("#sms_content").val()+"</td><td>"+_numbers_final[i]+"</td><td>"+ports[0]+"</td><td class='send_state'><img class='loading-img' src='/images/loading.gif' /></td></tr>";
				}
								
				$("#sms_detail").append(str);
				//alert(data);
				$.ajax({
					//url:"/?menu=pbxconfig&type=setup&display=smserver",
					url:"/?display=smsender",
					type:"post",
					data:data,
					success:function(data_back){
						//alert(data_back);
						var preg = /\"result\":\"(.*)\"/;
						var result = data_back.match(preg);
						
						if( !result || !data){
							$("#sms_detail tr").find('td.send_state').html('send message failed ,please check your settings.').removeAttr("class");
							return false;
						}

						handle_return(data_back);
					}					
				});
				
				function handle_return(data_back){
					var json = eval("("+data_back+")");
					var back_msg = json.message;
					var back_port = json.report[0][0][0].port;
					var back_number = json.report[0][0][0].phonenumber;
					var back_result = json.report[0][0][0].result;
					
					$("#sms_detail tr").each(function(i){
						//if( $(this).has('img').filter(":contains('"+back_number+"') :contains('"+back_port+"') :contains('"+back_msg+"')").html() !== null){
						//console.log($(this))
						if( $(this).has('img').children().eq(1).html() == back_number ){
							if( $(this).children().eq(0).html() == back_msg ){
								if( $(this).children().eq(2).html() == back_port ){
								//alert( $(this).has('img').children().eq(1).html() );
								//alert( $(this).children().eq(0).html() );
								//alert( $(this).children().eq(2).html() );
								
								var _index = $("#sms_detail tr").index($(this))-1;
								var str = '';
								//alert(_index);
								
								if( back_result == "success" ){
									str = 'SUCCESS';
								}else if( back_result == "sending" ){
									str = 'sending';
								}else{
									str = 'send message failed ,please check your phone numbers or settings.';
								}
								
								$("#sms_detail tr.add").eq(_index).find('td.send_state').html(str);
								//$("#sms_detail tr.add").eq(_index).removeAttr("class");								
								//$("#sms_detail tr").eq(_index).removeAttr("class");
							
								//return false;
							}
						}
					}
					});
				}
			}
				
			$("#sms_content").val('');
			$(document).scrollTop($(document).scrollTop()+100);
		}
		
		index2++;
		return false;
	});
	
	$("#board").bind("change",function(){
		var count_port = $(this).val()/4;
		var str = '';
		var chk = '';
		var index3 = 0;
		
		for(var i=1;i<=count_port;i++){
			str += '<div>';
			for(var j=1;j<=4;j++){
				var _port = 'gsm-'+i+'.'+j;				
				
				if( index3 >= settings_port.length ){
					index3=0;
				}
				
				if( _port  == settings_port[index3] ){
					chk = 'checked="checked"';
				}else{
					chk = '';
				}
				
				//str += '&nbsp;&nbsp;<input type="checkbox" '+chk+' name="port" value="gsm-'+i+'.'+j+'" />gsm-'+i+'.'+j+'&nbsp;&nbsp;';	
				str += '&nbsp;&nbsp;<input type="checkbox" name="port" value="gsm-'+i+'.'+j+'" />gsm-'+i+'.'+j+'&nbsp;&nbsp;';	
				index3++;
			}
			str += '</div>';
		}
		
		$("#port_opt").empty();
		$(str).appendTo("#port_opt");
	});
	$("#board").change();
	
	/*=====================================================================================*/
	$("#btn-sub").bind("click",function(event){
		var data = {};
		var ports = "";
		
		$("[name='port']:checked").each(function(){
			ports += $(this).val() + ",";
		});
		
		ports = ports.substr(0,ports.length-1);
		data.state = $("[name='state']").val()
		data.username = $("[name='username']").val();
		data.password = $("[name='password']").val();
		data.port = ports;
		data.ip_addr = $("#sms_ip").val();
		data.board = $("#board").val();
		
		//$.post("http://172.16.8.121/?display=smserver",data,function(data2){
		$.post(url+"?display=smsender",data,function(data2){
			var result = eval( "("+data2+")" );
			
			if(result.user_settings == "ok"){
				var msg = "Settings have been changed.";
				$("#settings_msg").html(msg);
				setTimeout(function(){
					$("#settings_msg").fadeOut("slow").remove();
				},3000);
			}
		});
		
		event.preventDefault();
	});
	
	$("#btn-sub-all").bind("click",function(){
		$("input[name=port]").each(function(){
			if( $(this).attr("checked") ){
				$(this).removeAttr("checked");
			}else{
				$(this).attr("checked",true);
			}
		});
		
		return false;
	});
	/*=====================================================================================*/
	$("#save_ip").bind("click",function(){
		var status = $(this).next(".ip_status").html();
		
		if( status == 'Do not save IP.' ){
			$.get("/?menu=pbxconfig&type=setup&display=smsender&save_ip=save&ip_addr=",function(data){
				//alert(data);
			});
		}else{
			var ip_addr = $("#sms_ip").val();
			$.get("/?menu=pbxconfig&type=setup&display=smsender&save_ip=save&ip_addr="+ip_addr,function(data){
				//alert(data);
			});
		}
	});
	
	/*=====================================================================================*/	
	/*
	function del_sms(obj,index){
		if( !confirm('Are you sure to DELETE this message?') ){
			return false;
		}
		
		$.ajax({
			url:"?display=smserver&del_sms=del_sms&index="+index,
			type:"get",
			success:function(data){
				if( data >= 1 ){
					$(obj).parents("tr.row").remove();
				}else{
					alert('Delete message failed.');
				}
			}
		});
		
		return false;
	}
	*/
	
	/*=====================================================================================*/	
	/*
	function get_sms(obj,index){
		$(obj).addClass('bold').siblings().removeClass('bold');
		
		$.ajax({
			type:"get",
			url:"?display=smserver&sms_page=sms_page&where="+index,
			success:function(data){
				sms_row(data);
			}
		})
		return false;
	}
	*/
	
	$("#receive_box").bind("click",function(){
		window.open('?type=setup&display=smsender&menu=pbxconfig&receivesms=receivesms');
	});
	
	/*=====================================================================================*/	
	//del msg
	$("#del_all_msg").bind("click",function(){
		$("#sms_inbox input[name='del_msg']").each(function(){
			if( $(this).attr("checked") ){
				$(this).removeAttr("checked");
			}else{
				$(this).attr("checked",true);
			}
		});
	});
	
	$("#del_msg").bind("click",function(){
			
		var get_checked = [];
		$("#sms_inbox input[name='del_msg']").each(function(){
			if( $(this).attr("checked") ){
				get_checked[get_checked.length] = $(this).val();
			}
		});
		
		if( get_checked == '' ){
			return false;
		}
		
		if( !confirm("Are you sure to delete the messages selected?") ){
			return false;
		}
		
		$.ajax({
			type:"get",
			url:"?display=smsender&receivesms=receivesms&del_msg=del_msg&id="+get_checked,
			success:function(data){
				if( data >= 1 ){
					window.location.reload();
				}else{
					alert("Delete messages failed!");
				}
			}
		})
	
	});
	
	//clean up
	$("#cleanup").bind("click",function(){
		if( !confirm("Are you sure to delete all sms?") ){
			return false;
		}
		$.ajax({
			type:"get",
			url:"?display=smsender&receivesms=receivesms&cleanup=cleanup",
			success:function(data){
				if( data >= 1 ){
					window.location.reload();
				}else{
					alert("Delete messages failed!");
				}
			}
		})
	});
	
	$("#fresh").bind("click",function(){
		window.location.reload();
	});
	
	function sms_row(data){
		$("#sms_inbox .row").remove();
		$("#sms_inbox").append(data);
	}
	
	function readfiles(){
		var files = document.getElementById('num_file').files;
		
		if (!files.length) {
			alert('Please select a file!');
			return;
		}
		var file = files[0];
		var reader = new FileReader();
	
		// If we use onloadend, we need to check the readyState.
		reader.onloadend = function(evt) {
			if (evt.target.readyState == FileReader.DONE) { // DONE == 2
				document.getElementById('byte_content').textContent = evt.target.result;
				//document.getElementById('byte_range').textContent = ['Read bytes: ', ' 0 ', ' - ', ' file end ',' of ', file.size, ' byte file'].join('');
			}
		};

		reader.readAsBinaryString(file);
		reader.onload=function(e){
			document.getElementById("sms_number").value=this.result;
		}
		return;
	}
	
	/*=====================================================================================*/	
	
	if( $("#but-setting").html() == "Show Settings" ){
			$("#but-setting").html("Hide Settings")
	}else{
		$("#but-setting").html("Show Settings")
	}
	
	$("#sms_content").keyup(function(){
		$("#sms_content_msg").html('');
	});
	
	$("#sms_number").keyup(function(){
		$("#sms_number_msg").html('');
	});
	
	$("#send_sms").click(function(){
		window.open(url+'?menu=pbxconfig&type=setup&display=smsender');
	})
	
	$("[name=port]").change(function(){
		$("#send_waring").html('');
	})
</script>
