var $dateRange = 30;
var $statsType = "sale";






// read the form values so they can be passed to the AJAX request
function get_form_data(formID){
    var data = $("#" + formID).serialize();
    return data;	    
}


// save comment form via ajax
function savecommentform(formid){
	
	var $salerent = $('#' + formid + ' input[name="sale_or_rent"][type="hidden"]').val();
	$salerent = $.trim($salerent);
	
	var $contact_agent_id = $('#' + formid + ' input[name="contact_agent_id"]').val();
	var $record_update_date = $("#" + formid + " input[name='record_update_date'][type='hidden']").val();
	var $agent_id = $("#" + formid + " input[name='agent_id'][type='hidden']").val();
	var $commentText = $("#" + formid + " textarea.commentText").val();

	//alert("$salerent" + $salerent + "\n" + "$contact_agent_id" + $contact_agent_id + "\n" + "$contact_date" + $contact_date + "\n" + "$agent_id" + $agent_id + "\n" + "$commentText" + $commentText + "\n");
	//var form_data = get_form_data(formid);   
    var url = "/leads/index.shtml?ajax=1&sale_or_rent=" + $salerent + "&contact_agent_id=" + $contact_agent_id + "&record_update_date=" + $record_update_date + "&agent_id=" + $agent_id + "&notes=" + $commentText;
	//index.shtml?contact_agent_id=2010072717212639&ajax=1&notes=hello%20there%20from%20paul
	
	
	//var url = "/data/standard.json";
	
	var $loadingIcon = $("#" + formid).find(".commentCricleLoader");
	
	
	$loadingIcon.fadeIn(function() {
			
	    	// Make the data call
			$.ajax({
			  url: url,
			  cache: false,
			  dataType: "json",
			  success: function(d) {
					
					if(d == 1){
						$("#" + formid).find(".commentCricleLoader").hide();
						$("#" + formid).fadeOut(function(){
							
							//alert($("#" + formid).find(".commentText").val());
							
							$("#" + formid).siblings(".commentsText").children(".commentTextPart").html($("#" + formid).find(".commentText").val());
							$("#" + formid).siblings(".commentsText").fadeIn();
	
						});
					} 

					
				}
			});// End data call

	}); //END commentCricleLoader fadeIn
	
}






function updateURLs(){
	
	var detailURL;
	
	detailURL = "?";
	detailURL += "daterange=" + $dateRange + "&";
	detailURL += "sale_or_rent=" + $statsType + "&";
	detailURL += "issale=" + $statsType + "&";
	detailURL += "dateposted=day" + $dateRange;

	
	//detailURL += "page=1&result_page=100";

	$('#homeDashboardStatsLinkPropertiesListed').attr("href", "/my-properties/" + detailURL);
	$('#homeDashboardStatsLinkPropertiesAdded').attr("href", "/my-properties/" + detailURL + "&whenpropadded=" + $dateRange);

	$('#homeDashboardStatsLinkEmailContacts').attr("href", "/leads/index.shtml" + detailURL);
	$('#homeDashboardStatsLinkPhoneContacts').attr("href", "/leads/phone.shtml" + detailURL);
	
	$('#homeDashboardStatsLinkExposureAnalysis').attr("href", "/my-properties/" + detailURL);
	
	
	$("a.dashboardStatsLink").parents("li").addClass("forceCursor");
	
	$("a.dashboardStatsLink").parents("li").click(function(){
		 $linkHREF = $(this).find("a").attr("href");
		 window.location.href = $linkHREF;
	});
	
	
	
}


function changeLoadingMessage() {

	if ($statsType == "sale") {
		$('.statsType').html("Sale");
	} else {
		$('.statsType').html("Rental");
	}
	
	if ($dateRange == 30) {
		$('.dateRange').html("30 days");
	} else {
		$('.dateRange').html("7 days");
	}
	
}

function loadStats(dateRange, type){
	
	//alert(dateRange + " " + type);
	
	//var form_data = get_form_data("figuresFilterCriteria");
    //var url = "post-account-4.shtml?json=1&"+form_data;
	
	var PropAdvertised;
	var PropAdded;
	var ViewsOnSearch;
	var ViewedDetail;
	var DownloadSchedules;
	var EmailAlerts;
	var EmailContacts;
	var PhoneContacts;
	
	
	var url = "/home.cgi?daterange=30&json=1";
	
	if (dateRange == "7") {
		url = "/home.cgi?daterange=7&json=1";
	}
	
	if (dateRange == "30") {
		url = "/home.cgi?daterange=30&json=1";
	}
	
	
	$('#reportLoadingWrapper').hide();

	$('.dashboardContentDataWrapper').fadeOut("fast", function(){

		$('#reportLoadingWrapper').fadeIn(function() {
	
			// Make the data call
			$.ajax({
			  url: url,
			  cache: false,
			  dataType: "json",
			  success: function(d) {
			  	
				
					if (type == "sale"){
						
						$(".dashboardStatsListSchedules").show();
						
						PropAdvertised = d.SalePropAdvertised;
						PropAdded = d.SalePropAdded;
						ViewsOnSearch = d.SaleViewsOnSearch;
						ViewedDetail = d.SaleViewedDetail;
						DownloadSchedules = d.SaleDownloadSchedules;
						EmailAlerts = d.SaleEmailAlerts;
						EmailContacts = d.SaleEmailContacts;
						PhoneContacts = d.SalePhoneContacts;
						
					} else {
						
						$(".dashboardStatsListSchedules").hide();
						
						PropAdvertised = d.RentPropAdvertised;
						PropAdded = d.RentPropAdded;
						ViewsOnSearch = d.RentViewsOnSearch;
						ViewedDetail = d.RentViewedDetail;
						DownloadSchedules = d.RentDownloadSchedules;
						EmailAlerts = d.RentEmailAlerts;
						EmailContacts = d.RentEmailContacts;
						PhoneContacts = d.RentPhoneContacts;
						
					}
					
					$("#dashboardStatsDataPropAdvertised").html(PropAdvertised);
					$("#dashboardStatsDataPropAdded").html(PropAdded);
					$("#dashboardStatsDataViewsOnSearch").html(ViewsOnSearch);
					$("#dashboardStatsDataViewedDetail").html(ViewedDetail);
					$("#dashboardStatsDataDownloadSchedules").html(DownloadSchedules);
					$("#dashboardStatsDataEmailAlerts").html(EmailAlerts);
					$("#dashboardStatsDataEmailContacts").html(EmailContacts);
					$("#dashboardStatsDataPhoneContacts").html(PhoneContacts);
					


						$('#reportLoadingWrapper').fadeOut(function() {
						    	$('.dashboardContentDataWrapper').fadeIn("fast");
						  	})
	

					
	
				}
			});
			// End data call

		});
		
	});
	
}



	$(document).ready(function(){
	
		updateURLs(); //Set the urls on links to the correct parameters
		

		// Click event for dashboard date selection links 
		$('#homeDashboardDateSelectionMenu a.dateRangeLink').click(function(e){
			e.preventDefault(); //Stop the link from changing the page
			
			var $link = $(this);// The link that has been clicked
			var $parentElement= $(this).parents("ul"); // Keep the scope to this dashboard, in cases where ther are more than one on the page 
			
			$parentElement.children("li").removeClass("selected"); //Remove the selected class from any sibling elements
			$(this).parent().addClass("selected"); // Add the selected class to the containing li of the clicked link			
		});
		
		
		
		// Click event for dashboard date selection links 
		$('a.contextLink').click(function(e){
			e.preventDefault(); //Stop the link from changing the page
			
			var $link = $(this);// The link that has been clicked
			var $parentElement= $(this).parents("ul"); // Keep the scope to this dashboard, in cases where ther are more than one on the page 
			
			$parentElement.find(".supplementaryText").html("View stats for");
			$parentElement.children("li").removeClass("selected"); //Remove the selected class from any sibling elements
			
			$(this).children("span.supplementaryText").html("You are viewing stats for");
			$(this).parent().addClass("selected"); // Add the selected class to the containing li of the clicked link
		});
		
		
		// Click event for 7 days
		$('a#homeDateRange7Days').click(function(e){
			$dateRange = 7;
			changeLoadingMessage();	
			updateURLs();
			loadStats(7, $statsType);			
		});
		
		// Click event for 30 days
		$('a#homeDateRange30Days').click(function(e){
			$dateRange = 30;
			changeLoadingMessage();	
			updateURLs();
			loadStats(30, $statsType);			
		});
		
		// Click event for Sale
		$('a#homeSaleContextLink').click(function(e){
			$statsType = "sale";
			changeLoadingMessage();	
			updateURLs();
			loadStats($dateRange, "sale");			
		});
		
		// Click event for Rent
		$('a#homeRentContextLink').click(function(e){
			$statsType = "rent";
			changeLoadingMessage();	
			updateURLs();
			loadStats($dateRange, "rent");			
		});
		





////////////////////////////////////////////////////////////////////////////




	    // Click event for message expansion links 
	    $('.viewFullMessageLink').click(function(e){
	        e.preventDefault(); //Stop the link from changing the page
	        
	        // var $fullMessage = $(this).parent().parent().next('messageExpansion');
	        
	        var $link = $(this);
	        var $containingCell = $(this).parent();
	        var $fullMessage = $containingCell.parent().next();
	        //alert($fullMessage.html());
	        
	        if ($fullMessage.is(":visible")) {
	            $fullMessage.fadeOut("fast");
	            $containingCell.removeClass("highlight");
	            $link.html("[view more]");
	        } else {
	            $fullMessage.fadeIn("fast");
	            $containingCell.addClass("highlight");
	            $link.html("[view less]");
	        }
	
	    });

	    
	    
	    
	    // show the empty forms and hide the ones with text in them
	    // Show the full comments as normal text with an edit link
	    $('.commentText').each(function(index) {
	        
	        if($(this).val().length == 0){
	            $(this).parent("fieldset").show();
	        } else {
	            $(this).parent("fieldset").siblings(".commentsText").show();
	        }
	        
	      });
	      
		  
	      //$(".elasticTextarea").elastic();
		  
		  $('.elasticTextarea').autoResize();
		  
	      //$(".elasticTextarea").css("height", "15px")
	      
	      
	      
	    // Click event for the comment edit link
	    $('.editCommentLink').click(function(e){
	        e.preventDefault(); //Stop the link from changing the page
	        
	        var $thisCommentTextBlock = $(this).parents("div.commentsText");
	        var $thisForm = $thisCommentTextBlock.siblings("fieldset");
	        
	        $thisCommentTextBlock.fadeOut(function(){
	            $thisForm.fadeIn(function(){
	                //$(".elasticTextarea").elastic();
	            });
	        })
	        
	    });

	    
	    // Click event for the comment save buttons
	    $('.saveComment').click(function(e){
	        e.preventDefault(); //Stop the link from changing the page
	        
	        //alert("caught click");
			
			var $thisButtonID = $(this).attr("id");
	        
	        var $thisForm = $(this).parents("fieldset");
	        var thisFormID = $thisForm.attr("id");
	        
	        savecommentform(thisFormID);
	        
	    });




	
	});


