var clear_refill = function(element,initial)
{
	var value = $(element).val();
	if(value == initial)
		$(element).val('');
	else if(value == '')
		$(element).val(initial);
};
var show_message = function(message)
{
	alert(message);
};

var show_modal = function(view,html,callback)
{
	// get the view
	if(view)
	{
		$.get('/ajax/view/'+view, function(data){
			$('#overlay').html(data);
			if(callback)
				callback();
			return true;
		});
	}
	else if(html)
	{
		$('#overlay').html(html);
		if(callback)
			callback();
	}
	else
	{
		show_message('Need a view or html for modal');
		return false;
	}
	
	// show the modal
	$('#overlay').show();
};

var hide_modal = function(callback)
{
	$('#overlay,#overlay2').empty().hide(0,callback);
};
var hide_modal2 = function(callback)
{
	$('.modal_wrap .modal_content').empty();
	$('.modal_wrap').hide(0,callback);
};

var show_modal2 = function(view,html,callback)
{
	// get the view
	if(view)
	{
		$.get('/ajax/view/'+view, function(data){
			$('.modal_wrap .modal_content').html(data);
			if(callback)
				callback();
			return true;
		});
	}
	else if(html)
	{
		$('.modal_wrap .modal_content').html(html);
		if(callback)
			callback();
	}
	else
	{
		show_message('Need a view or html for modal');
		return false;
	}
	
	// show the modal
	$('.modal_wrap').show().removeClass('hidden');
};
var show_photo = function(image,title)
{
	var $search_photo_modal = $('#search_photo_modal').clone();

	if(title !== undefined) {
		$search_photo_modal.find('h2').text(title);
	}

	$('<img />').attr('src','http://s3.amazonaws.com/property_images/o_'+image).load(function()
	{
		var width = this.width+22;
		$search_photo_modal.css('width',width+'px').find('.content').html($(this));
		show_modal2(false,$search_photo_modal);
	});
};
var upload_file_complete = function (json)
{
	var data = eval( "(" +json+ ")" );
	
	if(data.status == 'error')
	{
		show_message(data.message);
		$('#upload_image').show();
		$('.spinner').hide();
		$('#black_loading').hide();
		$('#upload_creative').show();
		$('#loading').hide();
	}
	else if(data.status == 'success')
	{
		// hide step 1 and show step 2
		$('#step1,.spinner').hide();
		$('#step2 #image_crop').attr('src', '/temp_uploads/property_images/'+data.file);
		$('#step2').show();
		$('#image_crop').imgAreaSelect({ aspectRatio: '4:3', handles: true, x1: 0, y1: 0, x2: 480, y2: 360, minWidth: 480, minHeight: 360,
				onSelectEnd: function (img, selection) {
					$('#crop_form input[name=x1]').val(selection.x1);
		            $('#crop_form input[name=y1]').val(selection.y1);
		            $('#crop_form input[name=x2]').val(selection.x2);
		            $('#crop_form input[name=y2]').val(selection.y2);
		        } 
		});
	}
};

var billboard = '';
var creative_points = '';
var show_creative_upload_modal = function(billboard,creative_points)
{		
	show_modal2('creative_upload', null, function ()
	{
		$('#creative_upload_modal #image').val(billboard);
		$('#creative_upload_modal #points').val(creative_points);
		
		$('#creative_upload_modal .image_map .map').attr('src', 'http://s3.amazonaws.com/property_images/o_'+billboard).load(function() {  
			$('#creative_upload_modal .recent').css('height',$('#creative_upload_modal .content').height());
		});
		
		// get a users creatives
		$.get('/ajax/user_creatives/'+user_id, function(data)
		{
			if(data.response == 'success')
			{
				if(Object.size(data.creatives) > 0)
				{
					$('#creative_upload_modal .grad').fadeIn();
					
					$.each(data.creatives, function(k, v)
					{
						var $img = $('<img />').attr('src','http://s3.amazonaws.com/user_creatives/thumb_'+v.file);
						$img.click(function ()
						{
							var creative = $(this).attr('src').replace('http://s3.amazonaws.com/user_creatives/thumb_','');

							// get the hash
							$.post('/ajax/creative_hash', {billboard:billboard,image:creative,points:creative_points},
								function(data){
									$('#upload_creative #file, #upload_creative .green_btn').hide();
									$('#upload_creative .loading').show();
									show_creative(data);
								}
							);
						});
						$('#creative_upload_modal .recent').append($img);
					});
				}
				else
				{
					$('#creative_upload_modal .no_recent').show();
				}
			}
		}, 'json');
		
	});
};

var creative_uploaded = function (json)
{
	var data = eval( "(" +json+ ")" );
	
	if(data.status == 'success')
	{		
		show_creative(data.hash,data.creative);
	}
};

var show_creative = function (hash,creative)
{
	var $new_image = $('<img />');
	$('#creative_upload_modal .loading').show();
	$new_image.attr('src','http://creative.adstruc.com/creative.php?data='+hash).addClass('map');
	$new_image.load(function ()
	{
		$('.image_map .map').remove();
		$('.image_map').append($new_image);
		$('#upload_creative #file, #upload_creative .green_btn').show();
		$('#creative_upload_modal .loading').hide();
	});
	
	if(creative)
	{
		// add the creative to the side
		var $creative = $('<img />');
		$creative.attr('src','http://s3.amazonaws.com/user_creatives/thumb_'+creative).hide();
		$('#creative_upload_modal .recent').prepend($creative);
		$('#creative_upload_modal .no_recent').hide();
		$creative.fadeIn();
	}
};
// light up which cc company
var credit_card_company = function($val)
{		
	if($val == '')
		$('.cc_icon').removeClass('cc_top');
	else
		$('.cc_icon').addClass('cc_top');
	
	if($val.match(/^4[0-9]{12}(?:[0-9]{3})?$/))
		$('.visa').removeClass('cc_top');
	else if($val.match(/^5[1-5][0-9]{14}$/))
		$('.mastercard').removeClass('cc_top');
	else if($val.match(/^3[47][0-9]{13}$/))
		$('.american_express').removeClass('cc_top');
};
// update totals on proposal generator
var update_totals = function()
{
	var total_properties = 0;
	var total_install = 0;
	$.each(properties, function(key, property)
	{
		total_properties += parseInt(property.price, 10);
		total_install += parseInt(property.installation_price, 10);
	});
	totals.properties = total_properties;
	totals.install = total_install;
	totals.total = total_properties+total_install-totals.discount;

	$.each(totals, function(key,total)
	{
		if(total != null)
			$('#totals .'+key+' span').text('$'+formatCurrency(total));
	});
	return false;
};

var flash_message = function(message,timeout)
{
	$('#flash_message').text(message).show();
	setTimeout("$('#flash_message').fadeOut()", timeout);
};

$(document).ready(function() {	
	/*
		register
	*/
	// dis-allow some keys
	$('#register_form #username').keypress(function (e)
	{
		if(e.which >= 91 && e.which <= 94 || e.which == 96)
			return false;
			
		if(e.which <= 122 && e.which >= 65 || e.which >= 48 && e.which <= 57 || e.which == 8 || e.which == 0)
			return true;
			
		return false;
	});
	// $('#show_register').click(function ()
	// {
	// 	$('#nav').hide();
	// 	$('#register_select').fadeIn();
	// 	$('#action_overlay').show().click(function ()
	// 	{
	// 		$('#action_overlay,#register_select').hide().unbind('click');
	// 		$('#nav').fadeIn();
	// 	});
	// 	return false;
	// });
	
	$('.orange_bold_btn.signup').click(function() {
		$('#nav').hide();
		$('#register_select').removeClass('hidden');
		return false;
	});
	
	$(document).click(function(e) {
		var $target = $(e.target);
		if(!$target.is('.register')) {
			if($target.closest('.register').length == 0) {
				$('#nav').show();
				$('.register').addClass('hidden');
			}
		}
	});
	
	/*
		end register
	*/
	
	/*
		login
	*/
	
	// set the user type
	$('.user_type').click(function ()
	{
		$('.user_type').removeClass('selected');
		$('#user_type').val(this.id.replace('user_type_', ''));
		$(this).addClass('selected');
	});
	$('.u_type').click(function ()
	{
		$('#user_type').val(this.id.replace('user_type_', ''));
		$('#buyer_seller').submit();
	});
	$('#login_container #email').focus(function() { clear_refill(this,'Email'); });
	$('#login_container #email').blur(function() { clear_refill(this,'Email'); });
	$('#login_container #password_cover').focus(function()
	{
		$(this).hide();
		$('#password').show().focus();
	});
	$('#login_container #password').blur(function()
	{
		if($(this).val() == '') {
			$(this).hide();
			$('#login_container #password_cover').show();
		}
	});
	/*
		end login
	*/
	
	/*
		Uplaod logo
	*/
	$('#uplaod_logo input[type="file"]').change(function ()
	{
		$('#upload_logo').submit();
	});
	
	/*
		modal
	*/
	$('#overlay,#overlay2,.modal_wrap').click(function (e)
	{
		var $target = $(e.target);
		if($target.attr('id') == 'overlay' || $target.attr('id') == 'overlay2')
			hide_modal();
		else if($target.hasClass('modal_background'))
			hide_modal2();
	});
	$('.hide_modal').live('click', function (){	hide_modal(); return false;	});
	$('.hide_modal2').live('click', function (){ hide_modal2(); return false;});
	$('.refresh').live('click', function ()
	{
		window.location = window.location;
	});
	/*
		end modal
	*/
	
	/*
		Uplaod Image 
	*/
	$('#change_photo').click(function() {
		show_modal2('properties/change_photo/'+property_id);
		return false;
	});
	$('#upload_image').live('submit',function ()
	{
		var file = $('#upload_image #file').val();
		
		if(file == '')
			show_message('Please select a file to upload');
		else if(!file.match(/(.png|.jpg|.JPG|.PNG)$/))
			show_message('Invalid file type, .jpg and .png only.');
		else
		{
			$('#upload_image').hide();
			$('.spinner').show();
			// upload the image via the iframe
			document.getElementById('upload_image').target = 'upload_image_iframe';
			document.getElementById('upload_image').submit();
		}
		
		return false;
	});
	$('#crop_form').live('submit',function ()
	{
		var data = {
						x1: $('#crop_form input[name=x1]').val(),
						y1: $('#crop_form input[name=y1]').val(),
						x2: $('#crop_form input[name=x2]').val(),
						y2: $('#crop_form input[name=y2]').val(),
						property_id: $('#crop_form input[name=property_id]').val(),
						unique_key: $('#crop_form input[name=unique_key]').val(),
						file: $('#image_crop').attr('src')
					};
		
		if(data.x1 == data.x2 && data.y1 == data.y2)
			show_message('Select a crop area');
		else
		{
			$('#image_crop').imgAreaSelect({ hide: true});
			$('#step2 #image_crop,#crop_form').hide();
			$('.spinner').show();
			$.post('/ajax/crop_image', data,
				function(json){
					if(json.status == 'success')
					{
						// change any medium prop images on the page
						$('.m_image').attr('src','http://s3.amazonaws.com/property_images/m_'+json.image_name);
						
						// hide the photo upload modal and show the creative points modal
						hide_modal2(function () {
							image = json.image_name;
							image_id = json.image_id;
							show_modal2("properties/creative_points/"+property_id+"/"+json.image_id+"/"+json.image_name);
						});
					}
					else
						show_message('There was an error');
				},
				'json'
			);
		}
		return false;
	});
	$('#remove_image').click(function ()
	{
		if(confirm('Delete image?'))
		{
			// get the pid from the uplaod form
			var property_id = $('#crop_form input[name=property_id]').val();
			
			$.get('/ajax/remove_image/'+property_id, 
			function(json){
				if(json.status == 'success')
					$('#remove_image').parent().html('Image removed from property!');
				else
					show_message('Property image could not be removed');
			},'json');
		}
		return false;
	});
	/* 
		end upload image
	*/
	
	/* 
		view property
	*/
	// show the image options on hover
	$('#item_view_container .image').hover(function ()
	{
		$('.zoom,.creative,.cog').fadeIn('fast');
	},
	function ()
	{
		$('.zoom,.creative,.cog').fadeOut('fast');
	});
	$('.zoom').click(function ()
	{
		// clean this up later
		show_modal(false,$('.view_image_template').html());
		
		return false;
	});
	if($('.description').height() > 230){ $('#view_full').show();}
	$('#view_full a').click(function ()
	{
		$('#description_container').css('height', $('.description').height());
		$('#view_full').hide();
	});
	/* 
		end view property
	*/
	
	/* 
		manager
	*/
	var qv_pid = null;
	$('#manager .show_quick_view').hover(function ()
	{
		var $qv = $(this);
		// show the quick view if it has been loaded before
		if($qv.hasClass('loaded'))
			$qv.next().show();
		else
		{
			// show the quick view, buy wait a few to load the data
			$qv.next().show();
			var $parent = $qv.parent();
			var id = $parent.attr('id');
			var clean_id = id.replace('property_','');
			qv_pid = setTimeout(function ()
			{
				$.get('/ajax/property_quick_view/'+clean_id, 
				function(data){
					if(data == 'error')
						show_message('There was an error.');
					else
					{
						$('#'+id+' .content').html(data);
						$qv.addClass('loaded');
					}
				});
			}, 500);
		}
	},
	function ()
	{
		clearTimeout(qv_pid);
		$(this).next().fadeOut('fast');
	});
	// show the search
	$('.toggle_search').toggle(function ()
	{
		$(this).text('Hide Search');
		$('#search').fadeIn('fast');
		$('#show_search').hide();
	},
	function ()
	{
		$(this).text('Search');
		$('#search').fadeOut('fast');
		$('#show_search').show();
	});
	$('#manager .bulk_upload').click(function(event){
		show_modal2('properties/bulk_upload_btn');
		event.stopPropagation();
		return false;
	});
	/* 
		end manager
	*/
	
	/* 
		Creative points
	*/
	var set_point = function (point,image,e)
	{
		var x = e.pageX - image.offset().left;
		var y = e.pageY - image.offset().top;
		$('#point_'+point).css({left:x-20,top:y-20}).fadeIn('fast');
		points[point] = x+','+y;
		return x+','+y;
	};
	var points = new Array(4);
	$('#image img').live('click',function (e)
	{
		var $this = $(this);
		$.each(points, function(k, v)
		{
			if(!points[k])
			{
				set_point(k,$this,e);
				if(k == 0)
					$('#points_container .title').text('Select the top right corner');
				else if(k == 1)
					$('#points_container .title').text('Select the bottom left corner');
				else if(k == 2)
					$('#points_container .title').text('Select the bottom right corner');
				else if(k == 3)
				{
					$('#points_container .title').text('All four points selected');
					$('#points_container #save').fadeIn('fast');
				}
					
				return false;
			}
		});
		if(points[0] && !points[1])
			$('#points_container #reset').fadeIn();
	});
	$('#save').live('click',function ()
	{
		$('#points_container .toolbar img').show();
		$('#points_container .btn').hide();
		$.post('/ajax/set_points', {property_id:property_id,image_id:image_id,points:points},
			function(data){
				if(data.status == 'error')
					show_message('There was an error and your points could not be saved.');
				if(data.status == 'success')
					window.location = '/properties/view/'+property_id;
			}, 
		'json');
	});
	$('#points_container #reset').live('click',function ()
	{
		points = new Array(4);
		$('.point, #reset, #save').fadeOut('fast');
		$('#points_container .title').text('Select the top left corner');
	});
	// creative upload
	$('#upload_creative').live('submit', function ()
	{
		var file = $('#upload_creative #file').val();
		
		if(file == '')
			show_message('Select a file');
		else if(!file.match(/(.jpg|.JPG)$/))
			show_message('Invalid file type, .jpg only.');
		else
		{
			$('#upload_creative #file, #upload_creative .green_btn').hide();
			$('#creative_upload_modal .loading').show();
			// upload the creative via the iframe
			document.getElementById('upload_creative').target = 'upload_creative_iframe';
			document.getElementById('upload_creative').submit();
		}
		
		return false;
	});
	$("*[data-creative-upload]").click(function ()
	{
		var data = $(this).attr('data-creative-upload').split('=');
		show_creative_upload_modal(data[0],data[1]);
		return false;	
	});
	/*
		End creative points
	*/
	
	/*
		Request form
	*/
	$('#request_form textarea').focus(function ()
	{
		if($(this).val() == 'Message to seller')
			$(this).val('');
	});
	// decline
	$('.action .ignore').click(function ()
	{	
		var access_id = this.id.replace('ignore_', '');
		var post_url = '/ajax/ignore_access';
		var $this = $(this);
				
		$.post(post_url, {access_id: access_id},
			function(data){
				if(data.status == 'error')
					show_message('There was an error');
				if(data.status == 'success')
				{
					$this.closest('li').find('.top .expires').text('Ignored').css('color','red');
					$this.closest('.info').hide();
				}
			}, 
		'json');
		
		return false;
	});
	// accept
	$('.action .grant').click(function ()
	{
		if(!confirm('Are you sure you want to grant access to this buyer?'))
			return false;
		
		var access_id = this.id.replace('grant_', '');
		var post_url = '/ajax/grant_access';
		var $this = $(this);
				
		$.post(post_url, {access_id: access_id},
			function(data){
				if(data.status == 'error')
					show_message('There was an error');
				if(data.status == 'success')
				{
					$this.closest('li').find('.top .expires').text('Access Granted!').css('color','green');
					$this.closest('.info').hide();
				}
			}, 
		'json');
		
		return false;
	});
	/*
		End Request form
	*/
	
	/* 
		Bid
	*/
	$('#place_bid_modal').click(function ()
	{
		show_modal('place_bid');
	});
	$('#place_bid').live('submit', function ()
	{
		var bid = $('#place_bid #bid_amount').val();
		
		if(bid == '')
		{
			show_message('Please enter a bid.');
			return false;
		}
		
		bid = parseFloat(bid.replace(/,/, ''));

		// make sure the bid is greater than the new bid
		if(bid < new_bid)
		{
			show_message('Your bid must be greater than or equal to $'+formatCurrency(new_bid));
			return false;
		}			
	});
	
	/*
		End Bid
	*/
	
	/*
		Delete a property
	*/
	$('#delete_property').click(function ()
	{
		if(!confirm('Are you sure you want to delete this property?'))
			return false;
		
		var post_url = '/ajax/delete_property';
				
		$.post(post_url, {property_id: property_id,unique_key: unique_key},
			function(data){
				if(data.status == 'error')
					show_message('There was an error and this property could not be deleted');
				if(data.status == 'success')
					window.location = '/properties';
			}, 
		'json');
	});
	
	/*
		End Delete a property
	*/
	
	/*
		Proposals
	*/
	// show the actions dropdown
	$('#build_header .actions').click(function ()
	{
		$('#build_header #action_list').fadeIn('fast');
		$('#action_overlay').show().click(function ()
		{
			$('#action_overlay,#build_header #action_list').hide().unbind('click');
		});		
	});
	$('#action_list li').click(function()
	{
		if(this.id == 'archive' || this.id == 'delete')
			return false;
		show_modal('proposal/update/'+this.id);
		$('#action_overlay,#build_header #action_list').hide().unbind('click');
	});
	// switch to grid view
	// should use classes!
	$('#grid_up').click(function()
	{
		$('#prop_list').hide().attr('id', 'grid_prop_list').fadeIn();
		$(this).attr('id','grid_down').find('.tooltip').hide();
		$('#list_down').attr('id','list_up');
	});
	$('#list_up').live('click', function()
	{
		$('#grid_prop_list').hide().attr('id', 'prop_list').fadeIn();
		$(this).attr('id','list_down').find('.tooltip').hide();
		$('#grid_down').attr('id','grid_up');
	});
	// tooltips
	$('.toggle').hover(
		function()
		{
			$(this).find('.tooltip').fadeIn('fast');
		},
		function()
		{
			$(this).find('.tooltip').hide();
		}
	);
	// search properties
	search_criteria = {};
	var build_search_criteria = function()
	{
		selects = $('#search_criteria select,#search_criteria input');
		inputs = $('#search_criteria input');
		// put all search criteria into an object
		search_criteria = {};
		$.each(selects, function(k,select)
		{
			if($(select).val() == 0 || $(select).val() == 'Tags' || $(select).val() == 'Reach' || $(select).val() == 'Unit #')
				return true;
			search_criteria[$(select).attr('name')] = $(select).val();
		});
				
		return search_criteria;
	};
	var reset_search_criteria = function()
	{
		$('#search_criteria select').val('0');
		$('#search_criteria input[name|="reach"]').val('Reach');
		$('#search_criteria input[name|="tags"]').val('Tags');
		$('#search_criteria input[name|="unit"]').val('Unit #');
		$('.search_activity .reset').hide();
		$('#zero_results,#prop_list').hide();
		$('#live_search').fadeIn();
		search_criteria = {};
		return false;
	};
	var show_reset = function()
	{
		// show the reset
		if(Object.size(search_criteria) > 0)
			$('.search_activity .reset').fadeIn();
		else
			$('.search_activity .reset').fadeOut();
	};
	// show full description of property
	$('#prop_list .view_full').live('click',function ()
	{
		var $full_desc = $('<div></div>').attr('style','padding: 10px;max-height:400px;overflow:auto;').html($(this).parent().next().html());
		var $modal = $('<div></div>').addClass('modal').append('<h1>Full Description<a class="hide_modal" href="#"></a></h1>');
		$modal.append($full_desc);
		show_modal(null,$modal);
		return false;
	});
	// reset form button
	$('.search_activity .reset').click(reset_search_criteria);
	
	// do search
	$('#search_criteria select,#search_criteria input').change(function ()
	{
		$('.search_activity .updating').show(null,$('.search_activity .reset').hide());
		$('#prop_list,#zero_results').hide();
		search_object = build_search_criteria();
		
		// make sure the search object isn't empty
		if(Object.size(search_object) == 0)
		{
			reset_search_criteria();
			$('.search_activity .updating').fadeOut();
			return false;
		}
		
		search_object.unique_key = unique_key;
		search_object.current_properties = current_property_ids();
		search_object.select = 'title,location,price,description,image';
		// search for the properties
		$.post('/ajax/search_properties', search_object,
			function(data){
				if(data.status == 'error')
					window.location = window.location;
				else if(data.status == 'success')
				{
					$('#live_search').hide();
					
					// populate the prop_list
					$('#prop_list').empty();
					
					var prop_number = 1;
					$.each(data.properties, function(key,prop)
					{
						// add the prop to #prop_list
						var $li = $('#prop_list_templates #search_prop').clone();
						$li.attr('id',prop._id).find('.description h2').text(prop.title);
						if(prop.location.address != null) $li.find('.description h3').append(prop.location.address+' - ');
						if(prop.location.city != null) $li.find('.description h3').append(prop.location.city+', ');
						if(prop.location.state != null) $li.find('.description h3').append(prop.location.state);
						if(prop.location.zip != null) $li.find('.description h3').append(' '+prop.location.zip);
						$li.find('.content').text(prop.description.substring(0, 180));
						if(prop.description.length > 180)
							$li.find('.content').append('...');
						$li.find('.full_description').val(prop.description);
						$li.find('.number').text(prop_number);
						if(prop.image)
							$li.find('.image img').attr('src','http://s3.amazonaws.com/property_images/s_'+prop.image);
						$('#prop_list').append($li).fadeIn();
						++prop_number;
					});
				}
				else if(data.status == 'no-matches')
				{
					$('#live_search').hide();
					$('#zero_results').fadeIn();
				}
				// show the search reset
				$('.search_activity .updating').fadeOut(null,show_reset);
			}, 
		'json');
	});
	
	$('#search_criteria #reach').focus(function (){ clear_refill(this,'Reach'); });
	$('#search_criteria #reach').blur(function (){ clear_refill(this,'Reach'); });
	$('#search_criteria #tags').focus(function (){ clear_refill(this,'Tags'); });
	$('#search_criteria #tags').blur(function (){ clear_refill(this,'Tags'); });
	$('#search_criteria #unit').focus(function (){ clear_refill(this,'Unit #'); });
	$('#search_criteria #unit').blur(function (){ clear_refill(this,'Unit #'); });
	
	// add a property to a proposal
	$('.add_prop').live('click', function ()
	{
		var $li = $(this).closest('li');
		show_modal('proposal/add_property',null,function()
		{
			$('#proposal_modal input[name|="title"]').val($li.find('.description h2').text());
			$('#proposal_modal textarea[name|="description"]').val($li.find('.full_description').val());
			$('#proposal_modal #prop_img').attr('src', $li.find('img').attr('src'));
			$('#proposal_modal input[name|="prop_id"]').val($li.attr('id'));
			$('#proposal_modal input[name|="price"]').focus();
		});
	});
	$('#proposal_modal #add_prop').live('submit', function ()
	{
		var prop = {};
		prop.title = $('#proposal_modal input[name|="title"]').val();
		prop.price = $('#proposal_modal input[name|="price"]').val();
		prop.installation_price = $('#proposal_modal input[name|="installation_price"]').val();
		prop.flight = {};
		prop.flight.start = $('#proposal_modal #flight_start').val();
		prop.flight.end = $('#proposal_modal #flight_end').val();
		prop.description = $('#proposal_modal textarea[name|="description"]').val();
		prop.property_id = $('#proposal_modal input[name|="prop_id"]').val();


		// validate
		if(prop.title == '')
			var error = 'Please enter a title';
		else if(prop.price == '')
			var error = 'Please enter a price';
		else if(prop.installation_price == '')
			var error = 'Please enter an installation price';
		else if(prop.description == '')
			var error = 'Please enter a description';
			
		if(error)
		{
			show_message(error);
			return false;
		}
		
		prop.proposal_id = proposal_id;
		prop.unique_key = unique_key;
		
		// lock the form
		$('#proposal_modal input[name|="add"]').val('Adding...').removeClass('blue_btn').css('background','#929292');
		$('#proposal_modal input, #proposal_modal textarea').attr('disabled','disabled').css('color', '#cfcfcf');
		
		// add the property to the proposal
		$.post('/ajax/proposal_add_prop', prop, function(data) 
		{
			if(data.status == 'success')
			{
				properties[data.property.property_id] = data.property;
				add_current_property(data.property,true,true);
				// add the property to the map/markers
				add_marker(data.property.property_id,data.property.location.latitude,data.property.location.longitude,map);
				map.setCenter(set_marker_boundry());

					
				update_totals();
				hide_modal();
				$('#current_properties #current_added').show(0,function () { setTimeout("$('#current_properties #current_added').fadeOut();",2000); });
				$('#'+prop.property_id).slideUp();
			}
			else if(data.status == 'error')
			{
				show_message('There was an error and this property could not be added to this proposal.');
				// unlock form
				$('#proposal_modal input[name|="add"]').val('Add +').removeClass('blue_btn').css('background','#929292');
				$('#proposal_modal input, #proposal_modal textarea').attr('disabled','disabled').css('color', '#cfcfcf');
			}
		},
		'json');
		return false;
	});
	
	// add a property to the current property list
	var add_current_property = function(property,top,fade)
	{
		var $li = $('#prop_list_templates #current_property').clone();
		$li.addClass('hidden').attr('id',property.id);
		$li.prepend(property.title).find('.price').text('$'+formatCurrency(property.price)+' - Unit #'+property.unit);
		if(top)
			$('#current_properties ul').prepend($li);
		else
			$('#current_properties ul').append($li);

		if(fade)
			$li.fadeIn();
		else
			$li.show();
	};	
	// build out the current list of propertys from the properties obj
	var build_current_properties = function(fade)
	{
		// clear current properties
		$('#current_properties ul').empty();
		
		// rebuild each property and add
		$.each(properties, function(key, property)
		{
			add_current_property(property,true,true);
		});
	};
	
	// returns an array of the current property ids
	var current_property_ids = function()
	{
		var ids = [];
		$.each(properties, function(key, property)
		{
			ids.push(property.property_id);
		});
		return ids;
	};
	
	var build_properties = function()
	{
		// populate the prop_list
		$('#prop_list').empty();

		var prop_number = 1;
		$.each(properties, function(key,prop)
		{
			// add the prop to #prop_list
			var $li = $('#prop_list_templates #list_prop').clone();
			$li.attr('id',prop.property_id).find('.description h2').text(prop.title);
			if(prop.location.address) $li.find('.description h3').append(prop.location.address+' - ');
			if(prop.location.city) $li.find('.description h3').append(prop.location.city+', ');
			if(prop.location.state) $li.find('.description h3').append(prop.location.state);
			if(prop.location.zip) $li.find('.description h3').append(' '+prop.location.zip);
			$li.find('.content').text(prop.description.substring(0, 180));
			$li.find('.full_content').html(nl2br(prop.description));
			if(prop.description.length > 180)
				$li.find('.content').append(' (<a class="view_full" href="#">More</a>)');
			$li.find('.full_description').val(prop.description);
			$li.find('.price').text('$'+formatCurrency(prop.price));
			$li.find('.number').text(prop_number);
			if(prop.image)
				$li.find('.image img').attr('src','http://s3.amazonaws.com/property_images/s_'+prop.image);
			$('#prop_list').append($li).fadeIn();
			++prop_number;
		});
	};
	
	// show/hide property search
	var prop_search = false;
	var show_search = function()
	{
		if(prop_search)
		{
			// hide the search
			reset_search_criteria();
			$('#live_search,#search_properties,#current_properties').hide();
			build_properties();
			$('#build_sorting_bar,#client_save,#detailed_info,#prop_list').fadeIn();
			if(Object.size(properties) == 0)
				$('#no_properties').fadeIn(); 
			if(Object.size(markers) == 1)
				map.setZoom(13);
			else
				map.fitBounds(bounds);
			prop_search = false;
		}
		else
		{
			// show the search
			$('#build_sorting_bar,#client_save,#detailed_info,#prop_list,#no_properties').hide();
			build_current_properties();
			$('#live_search,#search_properties,#current_properties').fadeIn();
			prop_search = true;
		}
		return false;
	};
	$('.show_search,.hide_search').click(show_search);
	// show search close
	$('#search_properties').hover(
	function()
	{
		$('#search_properties h3 span').show();
	},
	function() 
	{
		$('#search_properties h3 span').hide();
	});
	$('#prop_list .edit_property').live('click', function()
	{
		display_detailed_info();
		show_modal('proposal/edit_property/'+$(this).parent().attr('id'));
	});
	
	// show the detailed info on a property
	var single_marker;
	var current_detailed_property;
	var display_property_info = function(property)
	{
		current_detailed_property = property;
		// remove current markers
		remove_map_markers(markers);
		if(single_marker)
		{
			single_marker.setMap(null);
			single_marker = null;
		}
		
		reset_tab_bar();
		
		// fill out the information
		var property = properties[property];
		var info = {"dec": "DEC",
		            "showing": "Showing",
		            "facing": "Facing",
		            "illuminated": "Illuminated",
		            "reach": "Reach",
		            "age": "Age",
		            "average_income": "Avg. Income",
		            "population": "Population",
		            "gender": "Gender"};
		var boom;
		$.each(info, function(key, val)
		{
			if(property['info'][key])
				 $('#detailed_info #property .'+key+' span').text(property['info'][key]);
			else
				$('#detailed_info #property .'+key+' span').text('-');
		});
		// set some other info
		$('#detailed_info #property .unit span').text('#'+property['unit']);
		$('#detailed_info #property .flight span').text(' - ');
		if(property['flight'])
		{
			if(property['flight']['start'] != '')
			{
				var flight = new Date(property['flight']['start']*1000);
				$('#detailed_info #property .flight span').prepend(flight.getUTCMonth()+1+'/'+flight.getUTCDate()+'/'+flight.getUTCFullYear());
			}
			if(property['flight']['end'] != '')
			{
				var flight = new Date(property['flight']['end']*1000);
				$('#detailed_info #property .flight span').append(flight.getUTCMonth()+1+'/'+flight.getUTCDate()+'/'+flight.getUTCFullYear());
			}
		}
		$('#detailed_info #property .price span').text('$'+formatCurrency(property['price']));
		$('#detailed_info #property .install span').text('$'+formatCurrency(property['installation_price']));
		$('#detailed_info #property .total span').text('$'+formatCurrency(parseInt(property['price'],10)+parseInt(property['installation_price'],10)));
		
		// set the map
		if(property['location']['latitude'])
		{
			var latlng = new google.maps.LatLng(property['location']['latitude'],property['location']['longitude']);
			var options = {
							draggable: false,
							position: latlng,
							map: map,
							icon: '/images/map_markers/default.png'
						  };
			single_marker = new google.maps.Marker(options);
			map.setCenter(latlng);
			map.setZoom(13);
		}
		
		$('#detailed_info #overview').hide();
		$('#detailed_info #property').fadeIn();
	};
	// show street view
	var panorama;
	$('#map_tab_bar .street_view').click(function()
	{
		$('#map_tab_bar .arrow').hide();
		$(this).find('.arrow').fadeIn();
		// hide the map marker
		single_marker.setMap(null);

		var property = properties[current_detailed_property];
		
		var panoOptions = {
			addressControl: false,
			panControl: false,
			linksControl: false,
			zoomControlOptions: {
			  style: google.maps.ZoomControlStyle.SMALL
			},
			enableCloseButton: false
		};
		
		var latlng = new google.maps.LatLng(property['location']['latitude'],property['location']['longitude']);
		panorama = map.getStreetView();
		panorama.setOptions(panoOptions);
		panorama.setPosition(latlng);
		panorama.setPov({
			heading: 265,
			zoom: 1,
			pitch:0
		});
		// show the street view
		panorama.setVisible(true);
	});
	$('#map_tab_bar .map').click(function()
	{
		$('#map_tab_bar .arrow').hide();
		$(this).find('.arrow').fadeIn();
		
		// hide SV
		if(panorama)
			panorama.setVisible(false);
		single_marker.setMap(map);
	});
	// show the detailed info on a property
	var display_detailed_info = function()
	{
		plot_markers(markers,map);
		if(Object.size(markers) == 1)
			map.setZoom(13);
		else
			map.fitBounds(bounds);
		$('#detailed_info #property').hide();
		$('#detailed_info #overview').fadeIn();
		reset_tab_bar();
		$('.hide_info_btn').text('Detailed Info »').removeClass('hide_info_btn').addClass('detailed_info_btn');
	};
	var reset_tab_bar = function()
	{
		// reset tab bar
		if(panorama)
			panorama.setVisible(false);
		$('#map_tab_bar .arrow').hide();
		$('#map_tab_bar .map .arrow').show();
	};
	$('.detailed_info_btn').live('click',function()
	{
		var $this = $(this);
		display_property_info($this.parent().attr('id'));
		$('.hide_info_btn').text('Detailed Info »').removeClass('hide_info_btn').addClass('detailed_info_btn');
		$this.text('Hide Info -').removeClass('detailed_info_btn').addClass('hide_info_btn');
	});
	$('.hide_info_btn').live('click', function()
	{
		display_detailed_info();
	});
	// show large image
	$('#map_tab_bar .picture').click(function ()
	{
		if(properties[current_detailed_property]['image'])
		{
			$('.view_image_template img').attr('src','http://s3.amazonaws.com/property_images/o_'+properties[current_detailed_property]['image']);
			show_modal(false,$('.view_image_template').html());
		}
		else
			show_message('This property does not have an image.');
		
		return false;
	});
	
	// archive proposal
	$('#action_list #archive').click(function ()
	{
		if(!confirm('Are you sure you want to archive this proposal?'))
			return false;
			
		$.post('/ajax/archive_proposal', {proposal_id: proposal_id,unique_key: unique_key},
			function(data){
				if(data.status == 'error')
					show_message('There was an error');
				if(data.status == 'success')
					window.location = window.location;
			}, 
		'json');

		return false;
	});
	$('#action_list #delete,#actions #delete').click(function ()
	{
		if(!confirm('Are you sure you want to delete this proposal? This cannot be un-done.'))
			return false;
		
		delete_proposal(proposal_id);
		return false;
	});
	$('.manager_delete_proposal').click(function ()
	{
		if(!confirm('Are you sure you want to delete this proposal? This cannot be un-done.'))
			return false;
		
		delete_proposal(this.id);
		return false;
	});
	var delete_proposal = function(proposal_id)
	{
		$.post('/ajax/delete_proposal', {proposal_id: proposal_id,unique_key: unique_key},
			function(data){
				if(data.status == 'error')
					show_message('There was an error');
				if(data.status == 'success')
					window.location = '/proposals';
			}, 
		'json');
	};
	// un-archive proposal
	$('.unarchive').click(function ()
	{
		if(!confirm('Are you sure you want to un-archive this proposal?'))
			return false;
			
		$.post('/ajax/unarchive_proposal', {proposal_id: proposal_id,unique_key: unique_key},
			function(data){
				if(data.status == 'error')
					show_message('There was an error');
				if(data.status == 'success')
					window.location = window.location;
			}, 
		'json');

		return false;
	});
	$('#actions .send_client').click(function() { show_modal('proposal/send'); });
	/*
		End Proposals
	*/
	
	/*
		Messages
	*/
	$('.send_message_modal').click(function ()
	{
		show_modal2('send_message');
	});
	
	/*
		Photos
	*/
	$("*[data-show-photo]").click(function ()
	{
		var data = $(this).attr('data-show-photo').split('|');
		show_photo(data[0],data[1]);
		return false;	
	});
});

// format a string to our valid uri format
var str_to_clean_uri = function(string)
{
	if(string == null)
		return string;
	string = $.trim(string.toLowerCase());
	string = string.replace(/[^0-9a-zA-Z']/gi, ' ');
	string = string.replace(/'/gi, '_');
	string = string.replace(/\s/gi, '-');
	return string;
};

// probably not the best way to do this...
var nl2br = function (string)
{
	return string.replace(/\n/g,'<br />');
};
function formatCurrency(num,show_cents) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	if(cents > 0 || show_cents == true)
		return (((sign)?'':'-') + num + '.' + cents);
	else
		return (((sign)?'':'-') + num);
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

//reads cookie by name
function readCookie(name) {
    var cookiename = name + "=";  
    var ca = document.cookie.split(';');  
    for(var i=0;i < ca.length;i++)  
    {  
        var c = ca[i];  
        while (c.charAt(0)==' ') c = c.substring(1,c.length);  
        if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);  
    }  
    return null;  
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

jQuery.fn.exists = function(){return jQuery(this).length>0;};

/* store the offset between the client and the server (allows for clocks to be off) */
// By Josh Fraser
function set_time_correction(ts_on_server) {
	var today = new Date();
	var ts_today = today.getTime();
	time_correction = Math.floor(ts_on_server - (ts_today/1000));
}

function get_server_timestamp() {
	var current = new Date().getTime();
	var server_timestamp = Math.floor(current/1000 + time_correction);
	return server_timestamp;
}

// display relative timestamps
function pretty_time(abrev,fire_again) {
	jQuery.each($(".pretty_time"),function(obj) {

		ts = (time_correction == null) ? parseInt($(this).attr("id"), 10) : (parseInt($(this).attr('data-timestamp'), 10) - parseInt(time_correction, 10));

		var today = new Date();
		var date_today = today.getDate();
		var month_today = today.getMonth()+1;
		var year_today = today.getFullYear();
		var ts_today = today.getTime();

		new_time = new Date(ts*1000);
		mins = new_time.getMinutes();
		hours = new_time.getHours();
		date = new_time.getDate();
		month = new_time.getMonth()+1;
		year = new_time.getFullYear();
		ts = new_time.getTime();

		// how long ago was that date/time?
		seconds_ago = Math.abs(Math.round((ts_today - ts)/1000));
		minutes_ago = Math.round(seconds_ago/60);
		hours_ago = Math.round(minutes_ago/60);
		days_ago = Math.round(hours_ago/24);

		// change to 12 hour time
		if (hours > 12) {
			hours = hours - 12;
			am_pm = "pm";
		} else {
			hours = hours;
			am_pm = "am";
		}
		if (hours == 12)
			am_pm = "pm";
		if (hours == 0)
			hours = "12";

		// pad minutes (4:01pm instead of 4:1pm)
		if (mins < 10)
			mins = "0" + mins;

		// text to return
		var time_str = "";
		
        mins_form = (abrev) ? "mins" : "minutes";
        hr_form = (abrev) ? "hr" : "hour";
        hrs_form = (abrev) ? "hrs" : "hours";

   		if (seconds_ago < 30)
   			time_str = (abrev) ? "seconds ago" : "just seconds ago";
   		else if (seconds_ago < 60)
   			time_str = (abrev) ? "half a min ago" : "half a minute ago";
   		else if (minutes_ago == 1)
   			time_str = (abrev) ? "a min ago" : "a minute ago";
   		else if (hours_ago < 1)
   			time_str = minutes_ago + " " +mins_form+" ago";
   		else if (hours_ago == 1)
   			time_str = "1 "+hr_form+" ago";
   		else if (hours_ago <= 12)
   			time_str = hours_ago + " "+hrs_form+" ago";
   		else if (days_ago < 1) {
   			// just because it's within 24 hours, doesn't mean that it's really "today"
   			if (date == date_today)
      				time_str = (abrev) ? "today" :  hours+":"+mins+am_pm+" today";
   			else
       			time_str = (abrev) ? "yesterday" :  hours+":"+mins+am_pm+" yesterday";
   		} else if (days_ago == 1)
   			time_str = (abrev) ? "yesterday" : hours+":"+mins+am_pm+" yesterday";
   		else if (days_ago < 7)
   			time_str = days_ago+" days ago";
   		else if (days_ago == 7)
   			time_str = "1 week ago";
   		else
   			time_str = "on " + month+"/"+date+"/"+year;

		$(this).text(time_str);
	});
	
	if(fire_again)
		setTimeout('pretty_time(null,'+fire_again+')', fire_again*1000);		
}


//cookies
var setCookie = function(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
};

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name)
	    {
	    return unescape(y);
	    }
	 }
}

//function to return a pagination array 
function pagination(current_page, total_pages)
{
	var page_array = [];
	
	if(current_page > total_pages || current_page < 1)
		return false;
	
	if(total_pages <= 7)
	{
		for(i=1; i<=total_pages; i++)
			page_array.push(i);
	}
	else if(total_pages > 8)
	{
		if(current_page < 5)
		{
			for(i=1; i<=5; i++)
			 	page_array.push(i);
			
			page_array.push('...');
			page_array.push(total_pages);
		}
		else if(current_page > (total_pages - 4))
		{
			page_array.push(1);
			page_array.push('...');
			
			for(i=(total_pages - 3); i<=total_pages; i++)
				page_array.push(i);
		}
		else
		{
			page_array.push(1);
			page_array.push('...');
			page_array.push(current_page-1);
			page_array.push(current_page);
			page_array.push(current_page+1);
			page_array.push('...');
			page_array.push(total_pages);
		}
	}
	
	return page_array;
}

/**
 *
 * @param integer str
 * @return string
 */
function addCommas(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
        output = amount[i] + output;
        if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
}

/*
* @param integer amount - amount by which to increase or decrease the total
* @param string action - add, subtract
* @param jquery object $element - the element with the total text
*/
var updateTotal = function(amount, action, $element) {
	var total = parseInt($element.text().replace(/\$|,|\s/g, ''), 10);
	
	if(action == 'add')
		total += amount;
	else if(action == 'subtract')
		total -= amount;
	else return false;

	$element.text('$'+addCommas(total));
};

