<%@ 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">Spending Curve</a></li>
      <li><a href="#" name="#tab4">Spending Pie</a></li>
  </ul>

  <div id="content">
      <div id="tab1" align="center">
        <table id="grid1" width="100%"></table>
		<div id="grid1_pager"></div>
      </div>
      <div id="tab2" align="center">
      	  <div align="left"><label for="recordYears1">Select Year : </label><select id="recordYears1"><option value="">Load...</option></select></div>
          <div id="plot1" style="min-width: 800px; height: 400px; margin: 0 auto"></div>   
      </div>
      <div id="tab4" align="center">
      	  <div align="left"><label for="recordYears2">Select Year : </label><select id="recordYears2"><option value="">Load...</option></select></div>
          <div id="plot3" style="min-width: 800px; height: 400px; margin: 0 auto"></div> 
      </div>
  </div>
  <div id="receiptImgDialog" style="display:none" title="Receipt Image">
  	<img id="receiptImg" src="./receiptImgs/no_photo.jpg"/>
  </div>
  <div id="receiptImgUploadDialog" style="display:none" title="Upload Receipt Image">
  	<form action="MainHandler?handler=uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="myfile"><br>
        <input type="submit" value="Upload">
        <input type="hidden" name="rid" id="rid" />
        <input type="hidden" name="uid" id="uid" />
    </form>
  </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 type="text/javascript" src="js/jquery.form.js"></script>

<script>
var plot1, plot2, plot3, plot4;
var receiptImgDialog = null;
var receiptImgUploadDialog = null;

//probably ugly doing like this
var userid = "<%=user.getUserID() %>";
function resetTabs(){
    $("#content > div").hide(); //Hide all content
    $("#tabs a").attr("id",""); //Reset id's      
}

function getStatPie(year){
	var ajaxdata = "";
	if(year != null && year != undefined)
	{
		ajaxdata += "&year=" + year;
	}
	$.ajax({
        url : 'MainHandler?handler=getStatPieDjon' + ajaxdata,
        dataType : "json",
        success: function(data) {
        	plot3.series[0].setData(data);
        },
        cache: false
    });
}

function getSpendingCurve(year, month){
	var ajaxdata = "";
	if(year != null && year != undefined)
	{
		ajaxdata += "&year=" + year;
	}
	if(month != null && month != undefined)
	{
		ajaxdata += "&month=" + month;
	}
	$.ajax({
        url : 'MainHandler?handler=getSpendingCurveDjon' + ajaxdata,
        dataType : "json",
        success: function(data) {
        	//plot1.series = data;
        	//plot1.redraw();
        	//plot1.series[0].name = data[0].name;
        	//plot1.series[0].setData(data[0].data);
        	while(plot1.series.length > 0)
    		{
        		plot1.series[0].remove(true);
    		}
        	$.each(data, function(i, v){
        		plot1.addSeries(v);
        		//plot1.series[i].name = v.name;
            	//plot1.series[i].setData(v.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=getReceipts2Djon',
	    		datatype: "json", 
	    		colNames:['RID', 'MerchantName', 'Total/$', 'Card', 'Date'], 
	    		colModel:[
						   {name:'rid', hidden : true, sortable:false, index : 'rid'}, 
	    		           {name:'merchantName', width:300, sortable:true, align : 'center', editable: true}, 
	    		           {name:'total', width:100, sortable:true, align : 'center', searchtype : 'number'}, 
	    		           {name:'card', width:100, sortable:true, align : 'center', searchtype : 'number', editable: true}, 
	    		           {name:'date', width:200, sortable:true, align : 'center', searchtype : 'date', editable: true}
	    		         ],
	    		rowNum:10, 
	    		rowList:[10,20,30], 
	    		pager: '#grid1_pager', 
	    		viewrecords: true, 
	    		caption:"Receipts of Shopping History",
	    		ondblClickRow: function(rid){ 
	    			$("#receiptImg").attr("src", "./receiptImgs/no_photo.jpg");
	    			//alert("rid = " + rid + " : userid = " + userid);
	    			if(rid && userid)
	    			{
	    				$("#receiptImg").attr("src", "./receiptImgs/"+userid+"/"+rid+".jpg");
	    				if(receiptImgDialog == null || receiptImgDialog == undefined)
	        			{
	        				receiptImgDialog = $("#receiptImgDialog").dialog({
	    			    		width : 400,
	    			    		height : 400,
	    			    		autoOpen : false,
	    			    		modal : true,
	    			    		draggable : false,
	    			    		buttons: {
	    			    	        Cancel: function() {
	    			    	          $( this ).dialog( "close" );
	    			    	        }
	    			    	    }
	    			    	});
	        			}
	    				
	    				/* $.ajax({
	    	        		url : 'MainHandler?handler=getReceiptImg&rid=' + rid,
	    	        		dataType : "json",
	    	        		success: function(ret) {
	    	        			if(ret.img != null && ret.img != undefined)
	    	        			{
		    	    				$("#receiptImg").attr("src", ret.img);
	    	        			}
	    	        			if(receiptImgDialog == null || receiptImgDialog == undefined)
	    	        			{
	    	        				receiptImgDialog = $("#receiptImgDialog").dialog({
	    	    			    		width : 500,
	    	    			    		autoOpen : true,
	    	    			    		modal : true,
	    	    			    		draggable : false,
	    	    			    		buttons: {
	    	    			    	        Cancel: function() {
	    	    			    	          $( this ).dialog( "close" );
	    	    			    	        }
	    	    			    	    }
	    	    			    	});
	    	        			}
	    	        			receiptImgDialog.dialog( "open" );
	    	        		},
	    	        		cache: false
	    	    		}); */
	    			}
	    			receiptImgDialog.dialog( "open" );
	    		},
	    		jsonReader : {
	    		    cell : "",
	    		    id : 0
	    		},
	    		height: 'auto',
	    	   	sortname: 'rid',
	    		subGrid: true,
	    		subGridRowExpanded: function(subgrid_id, row_id) {
	    			// we pass two parameters
	    			// subgrid_id is a id of the div tag created whitin a table data
	    			// the id of this elemenet is a combination of the "sg_" + id of the row
	    			// the row_id is the id of the row
	    			// If we wan to pass additinal parameters to the url we can use
	    			// a method getRowData(row_id) - which returns associative array in type name-value
	    			// here we can easy construct the flowing
	    			var subgrid_table_id, pager_id;
	    			subgrid_table_id = subgrid_id+"_t";
	    			pager_id = "p_"+subgrid_table_id;
	    			$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
	    			jQuery("#"+subgrid_table_id).jqGrid({
	    				url:"MainHandler?handler=getItemsDjon&rid="+row_id,
	    				datatype: "json",
	    				colNames: ['Item', 'Price', 'Qty','TaxRate','Sub Total'],
	    				colModel: [
	    					{name:"item",index:"item",width:160, align : 'center', editable: true},
	    					{name:"price",index:"price",width:80,align:"center", editable: true},
	    					{name:"qty",index:"qty",width:80,align:"center", editable: true},
	    					{name:"taxRate",index:"taxRate",width:80,align:"center",sortable:false, editable: true},
	    					{name:"total",index:"total",width:80,align:"center",sortable:false}
	    				],
	    				rowNum:5, 
	    	    		rowList:[10,20,30], 
	    			   	pager: pager_id,
	    			   	sortname: 'item',
	    			    sortorder: "asc",
	    			    height: '100%',
	    			    autowidth:true,
	    	    		jsonReader : {
	    	    		    cell : "",
	    	    		    id : 0
	    	    		},
	    			});
	    			$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:true,del:false},
	    					{},
	    					{
	    						url : "MainHandler?handler=addItemDjon&rid="+row_id,
	    						closeAfterAdd : true,
	    		    			onclickSubmit : function(params, posdata) { 
	    		    				//alert("Clicked");
	    		    			}
	    					},
	    					{},
	    					{});
	    		},
	    		subGridRowColapsed: function(subgrid_id, row_id) {
	    			// this function is called before removing the data
	    			//var subgrid_table_id;
	    			//subgrid_table_id = subgrid_id+"_t";
	    			//jQuery("#"+subgrid_table_id).remove();
	    		}
	    	}); 
	    	grid1.jqGrid('navGrid','#grid1_pager',
	    		{
	    			edit:false,
	    			del:false, 
	    			add : true
	    		},
	    		{},
	    		{
	    			url : "MainHandler?handler=addReceiptDjon",
					closeAfterAdd : true,
	    			onclickSubmit : function(params, posdata) { 
	    				//alert("Clicked");
	    			}
	    		},
	    		{},
	    		{}
	    	).navButtonAdd('#grid1_pager',{
	    		   caption:"Upload Image", 
	    		   buttonicon:"ui-icon-image", 
	    		   onClickButton: function(){ 
	    			   var rid = grid1.jqGrid('getGridParam', 'selrow');
	    				$("#rid").val(rid);
	    				$("#uid").val(userid);
	    			   if(receiptImgUploadDialog == null || receiptImgUploadDialog == undefined)
	        		   {
	    				   receiptImgUploadDialog = $("#receiptImgUploadDialog").dialog({
	    			    		width : 400,
	    			    		height : 400,
	    			    		autoOpen : false,
	    			    		modal : true,
	    			    		draggable : false,
	    			    		buttons: {
	    			    	        Cancel: function() {
	    			    	          $( this ).dialog( "close" );
	    			    	        }
	    			    	    }
	    			    	});
	        		   }
	    			   receiptImgUploadDialog.dialog( "open" );
	    		   }, 
	    		   position:"last"
	    	});
	    	
	    	// time picker
	    	/* $("#purchaseDate").datetimepicker({
	    		dateFormat : "yy-mm-dd"
	    	}); */
	    	
	    	// get recorded years
	    	$.ajax({
        		url : 'MainHandler?handler=getRecordYearsDjon',
        		dataType : "json",
        		success: function(data) {
        			$("#recordYears1").empty();
					$.each(data.years, function(key, value) {   
					     $("#recordYears1")
					         .append($("<option></option>")
					         .attr("value",value)
					         .text(value)); 
					});
					$("#recordYears2").empty();
					$("#recordYears2")
			         .append($("<option></option>")
			         .attr("value","all")
			         .text("all"));
					$.each(data.years, function(key, value) {   
					     $("#recordYears2")
					         .append($("<option></option>")
					         .attr("value",value)
					         .text(value)); 
					});
        		},
        		cache: false
    		});
	    	
	    	// bind change event
	    	$("#recordYears1").change(function(){
	    		getSpendingCurve($(this).val());
	    	});
	    	
	    	$("#recordYears2").change(function(){
	    		getStatPie($(this).val());
	    	});
	    	
	    	// plots
	    	// total spending by month
	    	plot1 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'plot1',
	                type: 'line',
	                marginRight: 130,
	                marginBottom: 25,
	                events :{
	                	load : getSpendingCurve
	                }
	            },
	            title: {
	                text: 'Monthly Spendings',
	                x: -20 //center
	            },
	            xAxis: {
	            	title: {
	                    text: 'Month'
	                },
	                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
	            },
	            yAxis: {
	                title: {
	                    text: 'Spendings ($)'
	                },
	                plotLines: [{
	                    value: 0,
	                    width: 1,
	                    color: '#808080'
	                }]
	            },
	            tooltip: {
	                formatter: function() {
	                        return '<b>'+ this.series.name +'</b><br/>'+
	                        this.x +': $'+ this.y;
	                }
	            },
	            legend: {
	                layout: 'vertical',
	                align: 'right',
	                verticalAlign: 'top',
	                x: -10,
	                y: 100,
	                borderWidth: 0
	            },
	            series: []
	        });
	    	
	    	plot3 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'plot3',
	                plotBackgroundColor: null,
	                plotBorderWidth: null,
	                plotShadow: false,
	                events :{
	                	load : getStatPie
	                }
	            },
	            title: {
	                text: 'Spending Shares By Category'
	            },
	            tooltip: {
	        	    pointFormat: '<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: '',
	                data: []
	            }]
	        });
	    	$('form').ajaxForm({
	    	    beforeSend: function() {
	    	    	//alert("before send : rid = " + $("#rid").val());
	    	    	//alert("before send : uid = " + $("#uid").val());
	    	    },
	    	    uploadProgress: function(event, position, total, percentComplete) {
	    	    },
	    	    success: function() {
					alert("done");
					receiptImgUploadDialog.dialog( "close" );
	    	    },
	    		complete: function(xhr) {
	    			status.html(xhr.responseText);
	    		}
	    	}); 
});
</script>
</html>