/**
 * ---------------------- Subversion Information ------------------------------
 * ****************************************************************************
 * $Date: 2008-05-12 18:37:00 -0700 (Mon, 12 May 2008) $
 * $Rev: 269 $
 * $Author: steven $
 *
 * SVN URL of this file
 * $HeadURL: http://intranet/svn/cms/trunk/backend/inc/js/listings/listings.js $
 * ****************************************************************************
 *
 * @copyright Real Estate Webmasters 2008
 */

/* Format Functions */

function formatCurrency(field) {
	var x = stripChars(document.getElementById(field).value);
	x = x.toString();
	iLen = x.length;
	pos = x.indexOf(".");
	if (pos > -1){
		iLen = pos;
	}
	var temp = "";
	temp = x.substring(0, iLen);
	for (var i = 0; i < Math.floor((temp.length-(1+i))/3); i++){
		temp = temp.substring(0,temp.length-(4*i+3))+','+temp.substring(temp.length-(4*i+3));
	}
	document.getElementById(field).value = '$' + temp;
}

function formatNumber(field) {
	var x = stripChars(document.getElementById(field).value);
	x = x.toString();
	iLen = x.length;
	pos = x.indexOf(".");
	if (pos > -1){
		iLen = pos;
	}
	var temp = "";
	temp = x.substring(0, iLen);
	for (var i = 0; i < Math.floor((temp.length-(1+i))/3); i++){
		temp = temp.substring(0,temp.length-(4*i+3))+','+temp.substring(temp.length-(4*i+3));
	}
	document.getElementById(field).value = temp;
}

function stripChars(sourceStr){
	var chars = "0123456789";
	var stripped = "";
	for (var i = 0; i < sourceStr.length; i++){
		if (chars.indexOf(sourceStr.charAt(i)) != -1){
			stripped += chars.indexOf(sourceStr.charAt(i));
		}
	}
	return stripped;
}

/* Lookup Manager */

function toggleLookupManager(managerId)
{
	var button = $('#' + managerId + '-link');
	$('#' + managerId).toggle("normal");
	if (button.text() == "Manage") {
		button.text('Hide');
	} else {
	    button.text('Manage');
	}
}

function addLocation(managerId)
{
    var locationSelect   = $('#locationSelect option');
    var selectedLocation = $('#locationSelect').get(0);
    var state = locationSelect.get(selectedLocation.selectedIndex).value;
    if (state == '') {
        alert('You must select a State / Province before adding a new location.');
        return;
    }
    var local = $('#' + managerId + '-add').val();
	if ((local != '') && (state != '')) {
    	$.getJSON("/inc/php/rental_server.php", { action: "addLocation", state: state, local: local, q: true },
    		function(json) {
    		    if (json.returnCode == 200) {
        			$('<option value="' + local + '">' + local + '</option>').appendTo('#' + managerId + '-selected');
        			$('<option value="' + json.id + '">' + local + ', ' + state + '</option>').appendTo('#' + managerId + '-remove');
        			$('#' + managerId + '-selected').fadeIn();
        			$('#' + managerId + '-add').val('');
//        			toggleLookupManager(managerId);
    		    }
    		    alert(json.message);
    		}
    	);
	}
}

function removeLocation(managerId) {
    var locationId = $('#' + managerId + '-remove').val();
    if (locationId != '') {
    	$.getJSON("/inc/php/rental_server.php", {
    			action: "removeLocation",
    			q: locationId
    	}, function(json) {
    		if (json.returnCode == 200) {
    			var optionText;
    			var removeOptions = $('#' + managerId + '-remove option');
    			var removeSelect = $('#' + managerId + '-remove').get(0);
    			optionText = removeOptions.get(removeSelect.selectedIndex).text;
    			removeOptions.eq(removeSelect.selectedIndex).remove();
    			removeOptions.get(0).selected = true;
    			if (removeSelect.length == 0) {
    				$('#' + managerId + ' div.remove-controls').fadeOut();
    			}
    			var selectedOptions = $('#' + managerId + '-selected option');
    			var selectedSelect = $('#' + managerId + '-selected').get(0);
    			for (var i = 0; i < selectedOptions.length; i++) {
    				if (selectedOptions.get(i).text == json.local) {
    					if (selectedOptions.get(i).selected) {
    						selectedOptions.get(0).selected = true;
    					}
    					selectedOptions.eq(i).remove();
    				}
    			}
    			if (selectedSelect.length == 0) {
    				selectedSelect.fadeOut();
    			}
    			alert(json.message);
    		} else {
    			alert ("error: " + json.message);
    		}
    	});
    }
}

function addLookup(managerId, lookupType)
{
	var typeName = $('#' + managerId + '-add').val();
	if (typeName != '') {
    	$.getJSON("/inc/php/rental_server.php", { action: "addLookup", type: lookupType, q: typeName },
    		function(json) {
    			$('<option value="' + typeName + '">' + typeName + '</option>').appendTo('#' + managerId + '-selected');
    			$('<option value="' + typeName + '">' + typeName + '</option>').appendTo('#' + managerId + '-remove');
    			$('#' + managerId + '-selected').fadeIn();
    			$('#' + managerId + '-add').val('');
//    			toggleLookupManager(managerId);
    		}
    	);
	}
}

function removeLookup(managerId, lookupType) {
    var typeName = $('#' + managerId + '-remove').val();
    if (typeName != '') {
    	$.getJSON("/inc/php/rental_server.php", {
    			action: "removeLookup",
    			type: lookupType,
    			q: typeName
    	}, function(json) {
    		if (json.returnCode == 200) {
    			var optionText;
    			var removeOptions = $('#' + managerId + '-remove option');
    			var removeSelect = $('#' + managerId + '-remove').get(0);
    			optionText = removeOptions.get(removeSelect.selectedIndex).text;
    			removeOptions.eq(removeSelect.selectedIndex).remove();
    			removeOptions.get(0).selected = true;
    			if (removeSelect.length == 0) {
    				$('#' + managerId + ' div.remove-controls').fadeOut();
    			}
    			var selectedOptions = $('#' + managerId + '-selected option');
    			var selectedSelect = $('#' + managerId + '-selected').get(0);
    			for (var i = 0; i < selectedOptions.length; i++) {
    				if (selectedOptions.get(i).text == optionText) {
    					if (selectedOptions.get(i).selected) {
    						selectedOptions.get(0).selected = true;
    					}
    					selectedOptions.eq(i).remove();
    				}
    			}
    			if (selectedSelect.length == 0) {
    				selectedSelect.fadeOut();
    			}
    			alert(json.message);
    		} else {
    			alert ("error: " + json.message);
    		}
    	});
    }
}

/** Property Features Manager */

function addFeature(managerId, fieldName, lookupType) {
	var featureName = $('#' + managerId + '-add').val();
	if (featureName != '') {
    	$.getJSON("/inc/php/rental_server.php", { action: "addLookup", type: lookupType, q: featureName },
    		function(json) {
    		    $('<li><input style="margin-right: 5px;" name="' + fieldName + '[]" value="' + featureName + '" type="checkbox" checked="checked">' + featureName + '</li>').appendTo('#' + managerId + '-list');
    		    $('<option value="' + featureName + '">' + featureName + '</option>').appendTo('#' + managerId + '-remove');
    		    $('#' + managerId + '-add').val('');
    		}
    	);
	}
}


function removeFeature(managerId, fieldName, lookupType) {
    var featureName = $('#' + managerId + '-remove').val();
    if (featureName != '') {
    	$.getJSON("/inc/php/rental_server.php", {
    			action: "removeLookup",
    			type: lookupType,
    			q: featureName
    	}, function(json) {
    		if (json.returnCode == 200) {
    			var optionText;
    			var removeOptions = $('#' + managerId + '-remove option');
    			var removeSelect = $('#' + managerId + '-remove').get(0);
    			optionText = removeOptions.get(removeSelect.selectedIndex).text;
    			removeOptions.eq(removeSelect.selectedIndex).remove();
    			removeOptions.get(0).selected = true;
    			$('#' + managerId + '-list > li > input').each(function (i) {
    		        if ($(this).val() == featureName) {
    		            $(this).parent().remove();
    		        }
    			});
    			//alert(json.message);
    		} else {
    			alert ("error: " + json.message);
    		}
    	});
    }
}

/** Sortables **/

function setupSortables() {
	$('#photos').Sortable({
	    //ghosting: true,
	    //floats: true,
		accept: 'photo',
		//axis: 'vertically',
		//handle: '.photoHandle',
		tolerance: 'pointer',
		onChange : function(obj) {
		    $.getJSON('/inc/php/rental_server.php', { action : "orderPhotos", q : serialize()}, function (response) {
		        //alert(response.message);
		    });
		}
	});
}

function serialize(s) {
    serial = $.SortSerialize(s);
    return serial.hash;
}

/** Photo Manager */

function deletePhoto (photo) {
    if (confirm('Are you sure you want to delete this photo?')) {
	    $.getJSON('/inc/php/rental_server.php', { action : "removePhoto", q : photo}, function (response) {
	        if (response.returnCode == 200) {
	           $('#photo' + photo).fadeOut("slow");
	        } else {
	            alert(response.message);
	        }
	    });
    }
    return false;
}

function uploadPhoto() {
	var dataServer;
	$('#uploadPhotoControl').hide();
	$('#uploadPhotoProgress').show();
	dataServer  = '/inc/php/rental_server.php?action=addPhoto';
	$.ajaxFileUpload({
			url: dataServer,
			secureuri: false,
			fileElementId: 'file',
			dataType: 'json',
			success: function (data, status) {
				$('#uploadPhotoControl').show();
				$('#uploadPhotoProgress').hide();
				if (data.returnCode == 200) {
					var thumbAttr = calculateThumbAttr(64, data.width, data.height);
					var pathThb = '/images/listings/thumbs/';
					$('<li class="photo" id="photo' + data.photoId + '"><div class="propertyPhoto"><img src="' + pathThb + data.image + '" alt="Property Photo" width="' + thumbAttr.width + '" height="' + thumbAttr.height + '" style="cursor: move;" /></div><div><a href="javascript:void(0);" onclick="return deletePhoto(' + data.photoId + ');" title="Remove Photo"><img src="/backend/img/ui/btn-delete.gif" alt="Delete" /></a></div><input type="hidden" name="image[' + data.photoId + ']" value="' + data.image + '" /></li>').appendTo('#photos');
					setupSortables();
				} else if (data.returnCode == 350) {
					alert("Your image was too large for the server to process.  Please reduce the image and try again.");
				} else if (data.returnCode == 351) {
					alert("The server encountered an error attempting to calculate image memory usage.");
				} else if (data.returnCode == 352) {
					alert("The server failed attempt to resize the image you uploaded.  Perhaps try a smaller size.");
				} else {
					alert('error: ' + data.message);
				}
			},
			error: function (data, status, e) {
				$('#uploadPhotoControl').show();
				$('#uploadPhotoProgress').hide();
				alert(data.responseText);
				alert(e);
			}
		}
	);
}

function calculateThumbAttr(maxDim, width, height) {
	var tWidth, tHeight;
	if (width > height) {
		tWidth = maxDim;
		tHeight = height * tWidth / width;
	} else if (width < height) {
		tWidth = width * tHeight / height;
		tHeight = maxDim;
	} else {
		tWidth = tHeight = 64;
	}
	return { width: Math.round(tWidth), height: Math.round(tHeight) };
}

function PhotoManager()
{
	this.nextId = 0;
	this.photos = [];

	this.addPhoto = function(serverIndex) {
		this.photos[this.nextId] =  {
			clientId: this.nextId,
			serverId: serverIndex
		}
		// return ID of new photo and increment
		return this.nextId++;
	};

	this.getPhotoById = function(index)
	{
		for (var i in this.photos) {
			if (this.photos[i].clientId == index) return this.photos[i];
		}
		return false;
	};

	this.removePhoto = function(clientIndex)
	{
		var newArray = [];
		for (var i in this.photos) {
			if (this.photos[i].clientId != clientIndex) newArray.push(this.photos[i]);
		}
		this.photos = newArray;
	};

	this.getServerIndex = function(clientIndex)
	{
		return this.photos[clientIndex];
	};
}

var photoManager = new PhotoManager();

/** Document Ready */

$(document).ready(function() {
    // prevent certain text fields from submitting on enter
	$('.manager-input').add('input[@type=file]').keypress(
		function(event) {
			if (event.which == 13) return false;
		}
	);
	// setup sortables
	setupSortables();
});
