Echolibre.Properties = {
	goTo: function(propertyId)
	{
		document.location.href = '/property/' + propertyId;
	},

	/**
	 * Get interested Tenants
	 *
	 * @param propertyId   The property id to find interested tenants
	 */
	getInterestedTenants: function(propertyId) {
        var url = '/agents/viewings/ajaxPreviousViewings';
        $.get(url, {property: propertyId}, function(data) {
            $('#tenantsContactContent').html(data);
            $(function() {
                $('#calendar' + propertyId).timepickr();
            });
        });

		var url = '/agents/viewings/ajaxInterestedTenants';
		$.getJSON(url, {property: propertyId}, function(data) {
			var globalHTML = '';
			$.each(data, function(x, y) {
				var div = '<div id="tenants" onclick="Echolibre.Properties.loadTenantAndHistory(\''+data[x].user_id+'\', \''+ propertyId+'\');">';
				div    += ' <p>Name: '+data[x].firstname+' ' +data[x].lastname+ '<br />Phone #: '+data[x].number+'<br />Max Rent: &euro;'+data[x].max_rent+'<br />BedRooms: ' + data[x].rooms;
                if (data[x].area != null) {
                    div    += '<br />Area: ' + data[x].area;
                }
				div    += '</p></div><br />';

				globalHTML += div;
			});
			if (globalHTML == '') {
				globalHTML = '<p>No interested tenant for this property</p>';
			}
			$('#tenantsListingContent').html(globalHTML);
		});

	},

	loadTenantAndHistory: function (tenantId, propertyId) {
		var url = '/agents/viewings/ajaxLoadPropertyViewings';
		$.getJSON(url, {tenant: tenantId, property: propertyId}, function(data) {
			var newURL = '/agents/viewings/ajaxAddViewingDiv';
			$.get(newURL, {tenant: tenantId, property: propertyId}, function(data) {

				$('#tenantsContactContent').prepend(data);
                $('#time').timeEntry({
                    show24Hours: true,
                    timeSteps: [1, 15, 0],
                    useMouseWheel: true,
                    minTime: new Date(0, 0, 0, 6, 0, 0),
                    maxTime: new Date(0, 0, 0, 22, 0, 0)
                });

                $("#date").datepicker({
                    minDate: "0d",
                    maxDate: "3y",
                    duration: "",
                    showOn: "both",
                    buttonImage: "/images/calendar.gif",
                    buttonImageOnly: false,
                    hideIfNoPrevNext: true,
                    dateFormat: 'd M yy'
                });

				$(function() {
					$('#calendar' + propertyId).timepickr();
				});
			});
		});
	},

    cancelAddViewing: function (id)
    {
        $("#" + id + ' > td.me > div.dialog').remove();
        return true;
    },

    addViewing: function (tenantId, date, time) {
        var propertyId = $('#property-' + tenantId + ' :selected').val();
        var url      = '/agents/viewings/ajaxAddViewing';
        var foo      = date.val() + ' ' + time.val();
        var data     = {tenant: tenantId, property: propertyId, time: foo};
        $.get(url, data, function(data) {
            $("#" + tenantId + ' > td.me > div.dialog').remove();
			$('#notification').html('Viewing added').show();
			setTimeout(function() {
				$('#notification').hide();
			}, 3500);
            $('#property-'+tenantId).val('');
        });

		return true;
    },

    initViewing: function (id) {
        if ($('#property-'+id+' :selected').val() == '') {
            return false;
        }

        if ($('#' + id + ' > td.me > div.dialog').length > 0) {
            return false;
        }

        var d = new Date();

        var months = new Array(12);
        months[0]  = "Jan";
        months[1]  = "Feb";
        months[2]  = "Mar";
        months[3]  = "Apr";
        months[4]  = "May";
        months[5]  = "Jun";
        months[6]  = "Jul";
        months[7]  = "Aug";
        months[8]  = "Sep";
        months[9]  = "Oct";
        months[10] = "Nov";
        months[11] = "Dec";

        var month = months[d.getMonth()];
        var date =  d.getDate() + ' ' + month + ' ' + d.getFullYear();
        var time = d.getHours() + ':00';
        var html = '<div class="dialog">';
        html += '    <input id="date-' + id + '" type="text" size="10" value="' + date + '" />';
        html += '    <input id="time-' + id + '" type="text" size="3" value="' + time + '" />';
        html += '    <input id="cancel" type="button" value="Cancel" onclick="Echolibre.Properties.cancelAddViewing(' + id + ');" />';
        html += '    <input id="submit" type="button" value="Save" onclick="Echolibre.Properties.addViewing(' + id + ', $(\'#date-' + id + '\'), $(\'#time-' + id + '\'));" />';
        html += '</div>';
        $('#' + id + ' > td.me').append(html);

        $('#time-' + id).timeEntry({
            show24Hours: true,
            timeSteps: [1, 15, 0],
            useMouseWheel: true,
            minTime: new Date(0, 0, 0, 6, 0, 0),
            maxTime: new Date(0, 0, 0, 22, 0, 0)
        });

        $("#date-" + id).datepicker({
            minDate: "0d",
            maxDate: "3y",
            duration: "",
            showOn: "both",
            buttonImage: "/images/calendar.gif",
            buttonImageOnly: false,
            hideIfNoPrevNext: true,
            dateFormat: 'd M yy'
        });
    },

	saveText: function (date, time) {
        var id = date.parent().parent().attr('id').split(' ');
        var tenantId = id[0];
        var propertyId = id[1];
        var url      = '/agents/viewings/ajaxAddViewing';
        var foo      = date.val() + ' ' + time.val();
        var data     = {tenant: tenantId, property: propertyId, time: foo};
        $.get(url, data, function(data) {
            date.parent().parent().parent().parent().attr('class', 'viewing' + data);
            var html = '<br /><a onclick="Echolibre.Properties.addCommentForm(' + data + ');">Add Comment </a> | <a onclick="Echolibre.Properties.showComments(' + data + ');">(<span class="count">0</span> comments)</a> | <a href="#" onclick="Echolibre.Properties.deleteViewing(' + data + ');">Delete</a>';
            date.parent().parent().append(html);

            var html = '<form method="post" action="" name="messageForm" id="messageForm'+data+'">';
            html += '<label for="msg">Comment</label>';
            html += '         <textarea id="message" name="messsage" cols="80" rows="6"></textarea><br />';
            html += '         <input type="button" value="Add Comment" onclick="Echolibre.Properties.addComment(' + data + ');" />';
            html += '       </form>';
            html += '       <div class="comments"></div>';
            date.parent().parent().parent().append(html);

            $("#date").datepicker('disable');
            $("#time").timeEntry('disable');

            date.css({background: 'transparent', border: 'none', color: 'black'});
            time.css({background: 'transparent', border: 'none', color: 'black'});

            $('.ui-datepicker-trigger').hide();

            $('#submit').hide();
        });

		return true;
	},

	showComments: function(viewingId) {
        $('.viewing' + viewingId + ' .comments').toggle();
	},

    addCommentForm: function(viewingId) {
        $('#messageForm' + viewingId).toggle();
    },

    addComment: function(viewingId) {
        var item = $('.viewing' + viewingId + ' #message');
        var msg  = item.val();

        // Reset and hide the form
        item.val('');
        $('#messageForm' + viewingId).hide();

        var url  = '/agents/viewings/ajaxAddViewingComment';
        var data = {message: msg, viewing: viewingId};
        $.get(url, data, function(data) {
            $.getJSON('/agents/viewings/ajaxGetLoggedInUserInfo', {}, function(profile) {
                var count = $('.viewing' + viewingId + ' .count').text().split(' ');
                count = count[0];
                count++
                $('.viewing' + viewingId + ' .count').text(count);
                var html = '<div style="width: 90%;">Comment by ' + profile.firstname + ' ' + profile.lastname + ' on ' + data + '<br />' + msg + '</div>';
                $('.viewing' + viewingId + ' .comments').prepend(html);
            });
        });
    },

    deleteViewing: function(viewingId) {
        $.get('/agents/viewings/ajaxDeleteViewing', {viewing: viewingId}, function(data) {
            $('.viewing' + viewingId).parent().remove();
        });
    },

    deletePropertyImage: function(propertyId, imageName)
    {
        var url  = '/agents/property/ajaxDeletePropertyImage';
        var data = {name: imageName, property: propertyId};
        $.get(url, data, function(data) {
            $('#' + propertyId + '-' + imageName.substr(0, 20)).parent().remove();
        });
    },

    addTenantDetails: function(propertyId)
    {
        var tenantId = $('#tenant').val();
        var from     = $('#from').val();
        var to       = $('#to').val();

        if (tenantId == undefined || from == '' || to == '') {
            return false;
        }

        var url      = '/agents/property/ajaxAddTenantDetail';
        var data     = {property: propertyId, tenant: tenantId, start: from, end: to};
        $.get(url, data, function(data) {
            var html = '<li id="' + data + '"> - ' + $('#tenant :selected').text() + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
            html += '<strong>From:</strong> ' + from + '  <strong>To:</strong> ' + to + '&nbsp;&nbsp;&nbsp;<a onclick="Echolibre.Properties.deleteTenantDetails(' + data + ', ' + propertyId +', ' + tenantId + ')">Delete</a></li>';
            $('#list').prepend(html);
            $('#tenant :selected').remove();
            $('#from').val('');
            $('#to').val('');
        });

		$.get('/agents/property/ajaxDepositReceipt', {property: propertyId, tenant: tenantId}, function(data, textStatus){
			if (data != '') {
				var href = '<a href="/agents/property/document?id='+data+'">(Download File)</a>';
				var text = '<li>Deposit Receipt Created '+href+'</li>';
				$('#list').append(text);
			}
		});

		$.get('/agents/property/ajaxRentReceipt', {property: propertyId, tenant: tenantId}, function(data, textStatus){
			if (data != '') {
				var href = '<a href="/agents/property/document?id='+data+'">(Download File)</a>';
				var text = '<li>Rent Receipt Created '+href+'</li>';
				$('#list').append(text);
			}
		});

		$.get('/agents/property/ajaxTenancyForm', {property: propertyId, tenant: tenantId}, function(data, textStatus){
			if (data != '') {
				var href = '<a href="/agents/property/document?id='+data+'">(Download File)</a>';
				var text = '<li>Tenancy Form Created '+href+'</li>';
				$('#list').append(text);
			}
		});

		$.get('/agents/property/ajaxHighCourt', {property: propertyId, tenant: tenantId}, function(data, textStatus){
			if (data != '') {
				var href = '<a href="/agents/property/document?id='+data+'">(Download File)</a>';
				var text = '<li>High Court Documents Created '+href+'</li>';
				$('#list').append(text);
			}
		});



    },

    deleteTenantDetails: function(detailId, propertyId, userId)
    {
        var url  = '/agents/property/ajaxDeleteTenantDetail';
        var args = {id: detailId, property: propertyId, user: userId};
        $.getJSON(url, args, function(data) {
            $('#' + detailId).remove();
            $('#tenant').append('<option value="' + data[0].id + '">' + data[0].firstname + ' ' + data[0].lastname + '</option>')
        });
    }
};

