$(document).ready(function(){

	//swap this out with an interface animation for height.
	var ledgersummaryswitch=function(x){

		if(x=="ledger"){
			$("#ledger").css("height", "280px");
			$("#summary").css("height", "5px");
		}else{
			$("#ledger").css("height", "150px");
			$("#summary").css("height", "160px");
					
		}
		
	}
	
	$("a.edit").click(function(){
		
		var x=$(this).attr('id').split(':');		
		//var url='edit.php?donotcache=' + Math.random() + '&ledgerID=' + x[1];
		$.ajax({
			type: "POST", 
			url: "feeds/editpane.php",
			data: "ledgerID=" + x[1],			
			success: function(msg){
				
				//alert(msg);
				$("#feedback div.jqmWindow").html(msg);
				$("#feedback div.jqmWindow").jqm().jqmShow();
		
			}
		});
		return false;
	
	});


	$("a.catedit").click(function(){
		
		$.ajax({
			type: "POST", 
			url: "feeds/cateditpane.php",
			data: "categoryID=" + $(this).attr('id'),			
			success: function(msg){
				
				//alert(msg);
				$("#feedback div.jqmWindow").html(msg);
				$("#feedback div.jqmWindow").jqm().jqmShow();
		
			}
		});
		return false;
	
	});
	
	$("a.payedit").click(function(){
		
		$.ajax({
			type: "POST", 
			url: "feeds/payeditpane.php",
			data: "payeeID=" + $(this).attr('id'),			
			success: function(msg){
				
				//alert(msg);
				$("#feedback div.jqmWindow").html(msg);
				$("#feedback div.jqmWindow").jqm().jqmShow();
		
			}
		});
		return false;
	
	});
	

	//switch this out with a JSON array so we can add a level of undo.
	var originalvalues=function(){
	
		$("#ledgeradd input.item").each(function(){
		
			$(this).attr("value", "");
		
		});
		
	}
	
	//this recalulates credits, debits etc.  Called when a lineitem is deleted and when 
	var totals=function(){

		$.ajax({
			type: "POST", 
			url: "feeds/totals.php",
			data: "",			
			success: function(msg){
		
				$("#totals").html(msg);
		
			}
		});
	
	}		

	$("input.filter").click(function(){
	
		$.ajax({
			type: "POST", 
			url: "feeds/filter.php",
			data: "v=" + $(this).attr("value"),			
			success: function(msg){
		
				myledger();
				totals();
				ledgersummaryswitch("ledger");
						
			}
		});
		

	
	});
	
	$("input.datefilter").click(function(){
	
		$.ajax({
			type: "POST", 
			url: "feeds/datefilter.php",
			data: "v=" + $(this).attr("value"),			
			success: function(msg){
					
				myledger();
				totals();
				ledgersummaryswitch("ledger");
		
			}
		});
		

	
	});
	
	//if we refocus on another input hide the pick-lists.  There isn't any point for them to be displaying.
	$("input").focus(function(){
	
		$("#list").css("display","none");

	});


	//add a line item scripts, remove current value 
	$("#ledgeradd input.item").toggle(function(){
	
		$(this).attr("value","");	
		ledgersummaryswitch("ledger");//hide the sumary now	
			
	}, function(){
		
		//first click removes data.  Second click does not, but the next one does again.
		ledgersummaryswitch("ledger");//hide the sumary now	
		
	
	});
	
	
	$("#ledgeradd input.update").click(function(){	
	
	var d="";
	var p_in=$("#p_in").val();
	var p_out=$("#p_out").val();
		
	if((p_in != "") || (p_out != "")){//check to make sure that the validation passes for IN or OUT, handle date format in PHP
		
		var data="";
	
		$("#ledgeradd input").each(function(){
					
			data+=$(this).attr("name") + "|" + $(this).attr("value") + ":::"; 
		
		});	
			
		$.ajax({
		  type: "POST",
		  url: "feeds/add.php",
		  data: "arr=" + data,
		  success: function(msg){		    
		  	
		  	//reset the inputs--switch to the original input function
		  	//alert(msg);		  	
		  	originalvalues();	    	    		    
		    myledger();
		    totals();
		    summary("", msg);//use the return insert ID, not the array key!
		    ledgersummaryswitch("");
		    
		    
		  }
		});
	
	}else{
	
		$("#returnmsg").html("Sorry, but you need to choose whether you are paying money out, or taking it in.");
	
	}				
	
	});			
	//END LEDGER ADD AN ITEM 
			
	
	//DROP DOWN LIST!//////////////////////////////////////////////	
	$("#ledgeradd input.item").keyup(function(){
		
		var nm=$(this).attr("name"); 
		var inpt=$(this);
		var x=$(this).val();
		var pos=$(this).offset({ scroll: false });
		var p_top=pos.top;
		var p_left=pos.left;
		var h=$(this).height();
		var w=$(this).width();		
		var url="";
		
		if(nm=="category"){			
			url="categories.php";			
		}else if(nm=="payee"){		
			url="payees.php";	
		}else{//since the input isn't payee or cat then we might as welll make sure that the dropdowns are closed.
			$("#list").css("display","none");
		}	
			
		if( x.length > 0 && url!=""){
		
		$.ajax({
		  type: "POST",		  
		  url: "feeds/" + url,		  
		  data: "v=" + $(this).val(),
		  success: function(msg){		    	
		    	
		    	if(msg!=""){
		    	
		    		//alert( msg );	    	
		    		    	
			    	$("#list").html(msg);
			    	$("#list").css("left", p_left - 2);
					$("#list").css("top", p_top + h + 5);			    	
			    	$("#list").css("display","block");
			    	$("#list").css("position","absolute");
					$("#list").css("width", w - 2);
					
					$("a.chooseitem").click(function(){						
		
						inpt.val($(this).text());
						$("#list").css("display","none");
										
					});					
				
				}			
						    		    			    
		  }			  
		  
		});
		
		}				
	
	});
	//END DROP DOWN LIST!//////////////////////////////////////////////
	
	//ledger scripts//////////////////////////////////////////////////
	function CheckState(x){

		if(x == "Yes"){
	
			return "checked";
		
		}
	
	}	
	
	var tblrows=function(arr){//this function has the normal rows in state
	
		return 	"<td class=\"date\" width=\"12%\">" + arr[0] + "</td>" +
				//"<td class=\"cleared\" width=\"3%\">" + arr[1] + "</td>" +
				"<td class=\"cleared\" width=\"3%\"><input type=\"checkbox\" class=\"checker\" name=\"itemclear|" + arr[8] + "\" " + CheckState(arr[1]) + "></td>" +
				"<td class=\"checkNo\" width=\"10%\">" + arr[2] + "</td>" +
				"<td class=\"description\" width=\"20%\">" + arr[3] + "</td>" +
				"<td class=\"category\" width=\"20%\"><span class=\"mouseover\">" + arr[4] + "</span></td>" +
				"<td class=\"payee\" width=\"15%\"><span class=\"mouseover\">" + arr[5] + "</span></td>"	+
				"<td class=\"p_out\" width=\"10%\">$" + arr[6] + "</td>"	+
				"<td class=\"p_in\" width=\"10%\">$" + arr[7] + "</td>";	
	
	}
	
	
	var summary=function(x, y){
	
		//summary pane
		///alert(x);
		if(x==""){v=y; t="id";}else{v=x; t="key"}
		$.ajax({
		  type: "POST",		  
		  url: "feeds/summary.php",		  
		  data: "v=" + v + "&t=" + t,
		  success: function(msg){	    	
		    
		    //alert(msg); 	
			$("#summary").html(msg);
			
			//this is my delete function.  It can only happen if the summary pane
			//is showing.  add js.modal here so we can get a nice confirm message
			
			$("#delete").click(function(){
			
				//deletes a line item via ajax, recalls the ledger function and 
				//the totals function(?). and the summary function! 
				$.ajax({
					type: "POST", 
					url: "feeds/delete.php", 
					data: "v=" + $(this).attr("rel"), 
					success: function(msg){
					
						//alert(msg);																									
						myledger();	
						totals();
						$("#summary").html("Transaction deleted.");								
							
					}														
					
				});
			
			});
			
			$("a.edit").click(function(){						
				
				
				//alert($(this).attr("rel") );//this is causing me problems. 	
				$.ajax({
					type: "POST", 
					url: "feeds/editpane.php", 
					data: "ledgerID=" + $(this).attr("rel"), 
					success: function(msg){
					
						$("#feedback div.jqmWindow").html(msg);
						$("#feedback div.jqmWindow").jqm().jqmShow();								
							
					}														
					
				});
			
			
			
			});
			
											    		    			    
		  }			  
		  
		});
	
	
	}
	
	var myledger=function(){//this function handles the display ont eh rows and the auto-update.	
	
			$.ajax({type: "POST", url: "feeds/ledger.php", data:"", success: function(msg){	

			$("#ledger table").html(msg);
			
			$("#ledger tr:nth-child(odd)").addClass("odd");
			$("#ledger tr:nth-child(even)").addClass("even");
			
			$("#ledger tr").each(function(){
			
				var x=$(this).attr('rel').split(':');	
				//alert(x);		
				$(this).html( tblrows(x));	
			});
			
			$("#ledger tr").hover(function(){
			
				$(this).addClass("highlight");
			
			},function(){
			
				$(this).removeClass("highlight");	
			
			});
			
			$("input.checker").click(function(){
			
				//alert( $(this).attr("name") );			
				//alert( $(this).attr("checked") );				
				$.ajax({
				 
				  type: "POST",		  
				  url: "feeds/cleared.php",		  
				  data: "v=" + $(this).attr("name") + "|" + $(this).attr("checked"),
				  success: function(msg){			    	
					
					//its been cleared but no feedback is expected as its a checkbox.
								    		    			    
				  }			  
				  
				});	
							
			
			});
			
			$("#ledger tr").click(function(){				
				
				summary($(this).attr("id"), ""); //this uses the array key from the session!
				ledgersummaryswitch("show both"); 					
				
			});
			
						
		
		}//end ajax request success scripts
		
	});	
	
	return false;
	
	}
	
	myledger();	
	totals();
	ledgersummaryswitch("ledger");	

});

//main nav img rollovers
$(document).ready(function(){

	$(".rollover").hover(
	 function() {
	  curr = $(this).find("img").attr("src");
	  //alert(curr);
	  overlen = curr.length;
	  over = curr.substr(0, overlen-4);
	  over = over+'_on.gif';
	  $(this).find("img").attr({ src: over});
	 },
	 function() {
	  $(this).find("img").attr({ src: curr});
	 }
	)
	
	$(".rollover").find("img").each(function(i) {
	  temp = this.src;
	  prelen = temp.length;
	  pre = temp.substr(0, prelen-4);
	  pre = pre+'_on.gif';
	  preload_image_object = new Image();
	  preload_image_object.src = pre;
	});

});



      var headline_count;
      var headline_interval;
      var old_headline = 0;
      var current_headline = 0;
      $(document).ready(function(){
        headline_count = $("div.headline").size();
        $("div.headline:eq("+current_headline+")").css('top', '5px');
       
        headline_interval = setInterval(headline_rotate,7000);
        $('#scrollup').hover(function() {
          clearInterval(headline_interval);
        }, function() {
          headline_interval = setInterval(headline_rotate,7000);
          headline_rotate();
        });
      });
       
      function headline_rotate() {
        current_headline = (old_headline + 1) % headline_count;
        $("div.headline:eq(" + old_headline + ")")
          .animate({top: -205},"slow", function() {
            $(this).css('top', '210px');
          });
        $("div.headline:eq(" + current_headline + ")")
          .animate({top: 5},"slow"); 
        old_headline = current_headline;
      }

//there is one problem with this function in that it doesn't call the refesh
function UpdateMe(){

		var data="";
	
		$("#updateledger input, select, textarea").each(function(){
		
				data += $(this).attr("name") + ":" + $(this).attr("value") + "|"
						
		});
		
		$.ajax({
		type: "POST",
		url: "feeds/edit.php",
		data: "arr=" + data,
		success: function(msg){    

			$("#feedback div.jqmWindow").jqm().jqmHide();	    		  
    		  
    		  
		} 
		  		  
		});

	return false;

}

//there is one problem with this function in that it doesn't call the refesh
function UpdateMyCat(){

		var data="";
	
		$("#updatecat input, select, textarea").each(function(){
		
				data += $(this).attr("name") + ":" + $(this).attr("value") + "|"
						
		});

		//alert(data);

		$.ajax({
		type: "POST",
		url: "feeds/catedit.php",
		data: "arr=" + data,
		success: function(msg){    
			alert(msg);
			$("#feedback div.jqmWindow").jqm().jqmHide();	    		  
    		  
    		  
		} 
		  		  
		});

	return false;

}

//there is one problem with this function in that it doesn't call the refesh
function UpdateMyPay(){

		var data="";
	
		$("#updatepay input, select, textarea").each(function(){
		
				data += $(this).attr("name") + ":" + $(this).attr("value") + "|"
						
		});

		//alert(data);

		$.ajax({
		type: "POST",
		url: "feeds/payedit.php",
		data: "arr=" + data,
		success: function(msg){    
			//alert(msg);
			$("#feedback div.jqmWindow").jqm().jqmHide();	    		  
    		  
    		  
		} 
		  		  
		});

	return false;

}

function validateDate(fld) {

    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var errorMessage = 'Please enter date as MM/DD/YY.\nYou may use a slash, hyphen or period to separate the values.';
    if ((fld.value.match(RegExPattern)) && (fld.value!='')) {
        //alert('Date is OK'); 
    } else {
        $("#returnmsg").html(errorMessage);
       	//fld.attr("value", "");
       	fld.value='';
        fld.focus();
    } 
}

