<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="Beans.*;" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Main UI</title>
<style>
	body {
	  width: 90%;
	  margin: 100px auto 0 auto;
	  font-family: Arial, Helvetica;
	  font-size: small;
	  background-color: #eee;
	  background-image: url(data:image/gif;base64,R0lGODlhCHAIAJEAAMzMzP///////wAAACH5BAEHAAIALAAAAAAIAAgAAAINhG4nudroGJBRsYcxKAA7);
	}
</style>
<link type="text/css" rel="stylesheet" href="css/ui-lightness/jquery-ui-1.9.2.custom.css"/>
<link type="text/css" rel="stylesheet" href="css/tabs.css"/>
<link type="text/css" rel="stylesheet"  media="screen" href="css/ui.jqgrid.css" />
<link type="text/css" rel="stylesheet"  media="screen" href="css/jquery-ui-timepicker-addon.css" />
</head>
<body>
<%
session = request.getSession(false);

R2UserBean user = (R2UserBean)session.getAttribute("currentSessionUser");
if(user != null)
{
%>
  <div align="right">Hi, <%=user.getFirstName() %> | <a href="#">Tell a friend</a> | <a href="#">Help</a> | <a href="MainHandler?handler=logout">Log out</a></div>
  <ul id="tabs">
      <li><a href="#" name="#tab1">Main</a></li>
      <li><a href="#" name="#tab2">Plot1</a></li>
      <li><a href="#" name="#tab3">Plot2</a></li>
      <li><a href="#" name="#tab4">Plot3</a></li>
      <li><a href="#" name="#tab5">Plot4</a></li>    
  </ul>

  <div id="content">
      <div id="tab1" align="center">
        <table id="grid1" width="100%"></table>
		<div id="grid1_pager"></div>
		<div><input type="button" id="addReceipt" value="add receipt" /><input type="button" id="addItem" value="add item" /></div>
      </div>
      <div id="tab2" align="center">
          <div id="plot1" style="min-width: 800px; height: 400px; margin: 0 auto"></div>   
      </div>
      <div id="tab3" align="center">
          <div id="plot2" style="min-width: 800px; height: 400px; margin: 0 auto"></div>
      </div>
      <div id="tab4" align="center">
          <div id="plot3" style="min-width: 800px; height: 400px; margin: 0 auto"></div> 
      </div>
      <div id="tab5" align="center">
          <div id="plot4" style="min-width: 800px; height: 400px; margin: 0 auto"></div>
      </div>
  </div>
  <div id="newReceiptDialog" title="New Receipt Dialog" style="display:none">
  	<table>
  		<tr>
  			<td>Merchant</td>
  			<td><select id="merchant"><option value="">loading...</option></select></td>
  		</tr>
  		<tr>
  			<td>Card</td>
  			<td><select id="cards"><option value="">loading...</option></select></td>
  		</tr>
  		<tr>
  			<td>Date</td>
  			<td><input type="text" id="purchaseDate" size="20"/></td>
  		</tr>  		
  	</table>
  </div>
  <div id="newItemDialog" title="New Item Dialog" style="display:none">
  	<table>
  		<tr>
  			<td>Receipt</td><td><select id="rid"><option value="">loading...</option></select></td>
  		</tr>
  		<tr>
  			<td>Name</td><td><input type="text" id="itemName" size="20" /></td>
  		</tr>
  		<tr>
  			<td>Price</td><td><input type="text" id="itemPrice" size="10" /></td>
  		</tr>
  		<tr>
  			<td>Qty</td><td><input type="text" id="itemQty" size="10" /></td>
  		</tr>
  		<tr>
  			<td>Tax Rate</td><td><input type="text" id="taxRate" size="10" /></td>
  		</tr>
  	</table>
  </div>
<%
}
else
{
	response.sendRedirect("InvalidLogin.jsp"); //error page 
}
%>
</body>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript" src="js/grid.locale-en.js"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="js/highcharts/highcharts.js"></script>
<script type="text/javascript" src="js/highcharts/modules/exporting.js"></script>
<script type="text/javascript" src="js/jquery-ui-timepicker-addon.js"></script>

<script>
var plot1, plot2, plot3, plot4;
var newReceiptDialog = null;
var newItemDialog = null;
function resetTabs(){
    $("#content > div").hide(); //Hide all content
    $("#tabs a").attr("id",""); //Reset id's      
}

function getStatPie(){
	$.ajax({
        url : 'MainHandler?handler=getStatPie',
        dataType : "json",
        success: function(data) {
        	plot3.series[0].setData(data);
        },
        cache: false
    });
}

$(document).ready(function(){
	    var myUrl = window.location.href; //get URL
	    var myUrlTab = myUrl.substring(myUrl.indexOf("#")); // For localhost/tabs.html#tab2, myUrlTab = #tab2     
	    var myUrlTabName = myUrlTab.substring(0,4); // For the above example, myUrlTabName = #tab
		$("#content > div").hide(); // Initially hide all content
	    $("#tabs li:first a").attr("id","current"); // Activate first tab
	    $("#content > div:first").fadeIn(); // Show first tab content
	        
	    $("#tabs a").on("click",function(e) {
	            e.preventDefault();
	            if ($(this).attr("id") == "current"){ //detection for current tab
	             return       
	            }
	            else{             
	            resetTabs();
	            $(this).attr("id","current"); // Activate this
	            $($(this).attr('name')).fadeIn(); // Show content for current tab
	            }
	     });

	     for (var i = 1; i <= $("#tabs li").length; i++) {
	          if (myUrlTab == myUrlTabName + i) {
	              resetTabs();
	              $("a[name='"+myUrlTab+"']").attr("id","current"); // Activate url tab
	              $(myUrlTab).fadeIn(); // Show url tab content        
	          }
	     }		
	        
	     // init grid
	     var grid1 = jQuery("#grid1");
	    	grid1.jqGrid({ 
	    		url:'MainHandler?handler=getHisotry',
	    		datatype: "json", 
	    		colNames:['RID', 'Item','MerchantName', 'Price', 'Qty', 'TaxRate', 'Total', 'Card', 'Date'], 
	    		colModel:[
						   {name:'rid', hidden : true, sortable:false, editable:false, index : 'rid'}, 
	    		           {name:'item', width:150, sortable:true, align : 'center'}, 
	    		           {name:'merchantName', width:100, sortable:true,align : 'center'}, 
	    		           {name:'price', width:60, sortable:true, align : 'center', searchtype : 'number'}, 
	    		           {name:'qty', width:40, sortable:true, align : 'center', searchtype : 'integer'}, 
	    		           {name:'taxRate', width:50, sortable:true, align : 'center', searchtype : 'number'}, 
	    		           {name:'total', width:80, sortable:true, align : 'center', searchtype : 'number'}, 
	    		           {name:'card', width:80, sortable:true, align : 'center', searchtype : 'number'}, 
	    		           {name:'date', width:120, sortable:true, align : 'center', searchtype : 'date'} 
	    		         ],
	    		rowNum:5, 
	    		rowList:[10,20,30], 
	    		pager: '#grid1_pager', 
	    		viewrecords: true, 
	    		caption:"Shopping History",
	    		ondblClickRow: function(id){ 
	    			if(id)
	    			{
	    			}
	    		},
	    		jsonReader : {
	    		    cell : "",
	    		    id : 0
	    		}
	    	}); 
	    	grid1.jqGrid('navGrid','#grid1_pager',
	    		{
	    			edit:false,
	    			del:false, 
	    			add : false
	    		},
	    		{},
	    		{
	    			onclickSubmit : function(params, posdata) { 
	    				return null;
	    			}
	    		},
	    		{},
	    		{}
	    	);
			
	    	// add button
	    	$("#addReceipt").button().click(function(){
	    		// init dialogs
	    		if(newReceiptDialog == null)
	    		{
	    			newReceiptDialog = $("#newReceiptDialog").dialog({
			    		width : 300,
			    		autoOpen : false,
			    		modal : true,
			    		draggable : false,
			    		buttons: {
			    	        "Submit": function() {
			    	        	$.post(
			    	        			"MainHandler?handler=addReceipt", 
			    	        			{merchant : $("#merchant").val(), card : $("#cards").val(), purchaseDate : $("#purchaseDate").val()},
			    	        			function(data){
			    	        				
			    	        			},
			    	        			"json"
			    	        		  );
			    	          $( this ).dialog( "close" );
			    	        },
			    	        Cancel: function() {
			    	          $( this ).dialog( "close" );
			    	        }
			    	      }
			    	});
	    			$.post("MainHandler?handler=getMerchants", function(data){
	    				if(data.ret == true)
	    				{
	    					$("#merchant").empty();
	    					$.each(data.merchants, function(key, value) {   
	    					     $("#merchant")
	    					         .append($("<option></option>")
	    					         .attr("value",value)
	    					         .text(key)); 
	    					});
	    				}
	    			}, "json");
	    			$.post("MainHandler?handler=getCards", function(data){
	    				if(data.ret == true)
	    				{
	    					$("#cards").empty();
	    					$.each(data.cards, function(key, value) {   
	    					     $("#cards")
	    					         .append($("<option></option>")
	    					         .attr("value",key)
	    					         .text(value)); 
	    					});
	    				}
	    			}, "json");
	    		}
	    		
	    		newReceiptDialog.dialog( "open" );
	    	});
	    	$("#addItem").button().click(function(){
	    		// init dialogs
	    		if(newItemDialog == null)
	    		{
	    			newItemDialog = $("#newItemDialog").dialog({
			    		width : 500,
			    		autoOpen : false,
			    		modal : true,
			    		draggable : false,
			    		buttons: {
			    	        "Submit": function() {
			    	        	$.post(
			    	        			"MainHandler?handler=addItem", 
			    	        			{
			    	        				rid : $("#rid").val(),
			    	        				name : $("#itemName").val(), 
			    	        				price : $("#itemPrice").val(), 
			    	        				qty : $("#itemQty").val(),
			    	        				taxRate : $("#taxRate").val()
			    	        			},
			    	        			function(data){
			    	        				
			    	        			},
			    	        			"json"
			    	        		  );
			    	          $( this ).dialog( "close" );
			    	        },
			    	        Cancel: function() {
			    	          $( this ).dialog( "close" );
			    	        }
			    	      }
			    	});
	    			$.post("MainHandler?handler=getReceipts", function(data){
	    				if(data.ret == true)
	    				{
	    					$("#rid").empty();
	    					$.each(data.receipts, function(key, value) {   
	    					     $("#rid")
	    					         .append($("<option></option>")
	    					         .attr("value",key)
	    					         .text(value)); 
	    					});
	    				}
	    			}, "json");
	    		}
	    		
	    		newItemDialog.dialog( "open" );
	    	});
	    	
	    	// time picker
	    	$("#purchaseDate").datetimepicker({
	    		dateFormat : "yy-mm-dd"
	    	});
	    	
	    	
	    	// plots
	    	plot1 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'plot1',
	                type: 'area'
	            },
	            title: {
	                text: 'US and USSR nuclear stockpiles'
	            },
	            subtitle: {
	                text: 'Source: <a href="http://thebulletin.metapress.com/content/c4120650912x74k7/fulltext.pdf">'+
	                    'thebulletin.metapress.com</a>'
	            },
	            xAxis: {
	                labels: {
	                    formatter: function() {
	                        return this.value; // clean, unformatted number for year
	                    }
	                }
	            },
	            yAxis: {
	                title: {
	                    text: 'Nuclear weapon states'
	                },
	                labels: {
	                    formatter: function() {
	                        return this.value / 1000 +'k';
	                    }
	                }
	            },
	            tooltip: {
	                formatter: function() {
	                    return this.series.name +' produced <b>'+
	                        Highcharts.numberFormat(this.y, 0) +'</b><br/>warheads in '+ this.x;
	                }
	            },
	            plotOptions: {
	                area: {
	                    pointStart: 1940,
	                    marker: {
	                        enabled: false,
	                        symbol: 'circle',
	                        radius: 2,
	                        states: {
	                            hover: {
	                                enabled: true
	                            }
	                        }
	                    }
	                }
	            },
	            series: [{
	                name: 'USA',
	                data: [null, null, null, null, null, 6 , 11, 32, 110, 235, 369, 640,
	                    1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126,
	                    27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662,
	                    26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
	                    24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586,
	                    22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
	                    10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104 ]
	            }, {
	                name: 'USSR/Russia',
	                data: [null, null, null, null, null, null, null , null , null ,null,
	                5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322,
	                4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478,
	                15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049,
	                33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
	                35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
	                21000, 20000, 19000, 18000, 18000, 17000, 16000]
	            }]
	        });
	    	
	    	plot2 = new Highcharts.Chart({
	    	    
	            chart: {
	                renderTo: 'plot2',
	                type: 'column'
	            },
	    
	            title: {
	                text: 'Total fruit consumtion, grouped by gender'
	            },
	    
	            xAxis: {
	                categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
	            },
	    
	            yAxis: {
	                allowDecimals: false,
	                min: 0,
	                title: {
	                    text: 'Number of fruits'
	                }
	            },
	    
	            tooltip: {
	                formatter: function() {
	                    return '<b>'+ this.x +'</b><br/>'+
	                        this.series.name +': '+ this.y +'<br/>'+
	                        'Total: '+ this.point.stackTotal;
	                }
	            },
	    
	            plotOptions: {
	                column: {
	                    stacking: 'normal'
	                }
	            },
	    
	            series: [{
	                name: 'John',
	                data: [5, 3, 4, 7, 2],
	                stack: 'male'
	            }, {
	                name: 'Joe',
	                data: [3, 4, 4, 2, 5],
	                stack: 'male'
	            }, {
	                name: 'Jane',
	                data: [2, 5, 6, 2, 1],
	                stack: 'female'
	            }, {
	                name: 'Janet',
	                data: [3, 0, 4, 4, 3],
	                stack: 'female'
	            }]
	        });
	    	
	    	
	    	plot3 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'plot3',
	                plotBackgroundColor: null,
	                plotBorderWidth: null,
	                plotShadow: false,
	                events :{
	                	load : getStatPie
	                }
	            },
	            title: {
	                text: 'Spending Shares By Category'
	            },
	            tooltip: {
	        	    pointFormat: '{series.name}: <b>{point.percentage}%</b>',
	        	    percentageDecimals: 1
	            },
	            plotOptions: {
	                pie: {
	                    allowPointSelect: true,
	                    cursor: 'pointer',
	                    dataLabels: {
	                        enabled: true,
	                        color: '#000000',
	                        connectorColor: '#000000',
	                        formatter: function() {
	                            return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(2) +' %';
	                        }
	                    }
	                }
	            },
	            series: [{
	                type: 'pie',
	                name: 'Browser share',
	                data: [
	                    /* ['Firefox',   45.0],
	                    ['IE',       26.8],
	                    {
	                        name: 'Chrome',
	                        y: 12.8,
	                        sliced: true,
	                        selected: true
	                    },
	                    ['Safari',    8.5],
	                    ['Opera',     6.2],
	                    ['Others',   0.7] */
	                ]
	            }]
	        });
	    	
	    	
	    	plot4 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'plot4',
	                type: 'line',
	                marginRight: 130,
	                marginBottom: 25
	            },
	            title: {
	                text: 'Monthly Average Temperature',
	                x: -20 //center
	            },
	            subtitle: {
	                text: 'Source: WorldClimate.com',
	                x: -20
	            },
	            xAxis: {
	                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
	            },
	            yAxis: {
	                title: {
	                    text: 'Temperature (°C)'
	                },
	                plotLines: [{
	                    value: 0,
	                    width: 1,
	                    color: '#808080'
	                }]
	            },
	            tooltip: {
	                formatter: function() {
	                        return '<b>'+ this.series.name +'</b><br/>'+
	                        this.x +': '+ this.y +'°C';
	                }
	            },
	            legend: {
	                layout: 'vertical',
	                align: 'right',
	                verticalAlign: 'top',
	                x: -10,
	                y: 100,
	                borderWidth: 0
	            },
	            series: [{
	                name: 'Tokyo',
	                data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
	            }, {
	                name: 'New York',
	                data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
	            }, {
	                name: 'Berlin',
	                data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
	            }, {
	                name: 'London',
	                data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
	            }]
	        });
});
</script>
</html>