function removeFromCampaign(c_id, i_id){  
	if ($('#investor_'+i_id).hasClass('removed')){
		unremoveFromCampaign(c_id, i_id);
	} else {
		removeInvestor(c_id, i_id);                                                                                                                               
	}
}                                                                                                                                          
function removeInvestor(c_id,i_id){	 
	var el = $('#investor_'+i_id+' button');      
	$('#investor_'+i_id).addClass('removed');
	$(el).removeClass('remove');
	$(el).addClass('removed');
	$(el).html('Unremove');
	$('#investor_'+i_id+' a').addClass('removed');
	$.post('/account/campaigns/'+c_id+'/remove_investor', {investor_key:i_id,'_method':'put'}, function(r){$('#removed_total').html(r);}); 
}
function unremoveFromCampaign(c_id, i_id){
	var el = $('#investor_'+i_id+' button');   
	
	if ($('#investor_'+i_id).length){
		$('#investor_'+i_id).removeClass('removed');
		$(el).addClass('remove');
		$(el).removeClass('removed');
		$(el).html('Remove');
		$('#investor_'+i_id+' a').removeClass('removed');                             
	}
	$.post('/account/campaigns/'+c_id+'/unremove_investor', {investor_id:i_id,'_method':'put'}, function(r){$('#removed_total').html(r);});
}
function unremoveFromCampaignModal(c_id, i_id){                     
	$('#investor_modal_'+i_id).fadeOut('slow', function(){$('#investor_modal_'+i_id).remove();});                                           
	$.post('/account/campaigns/'+c_id+'/unremove_investor', {investor_id:i_id,'_method':'put'}, function(r){$('#removed_total').html(r); refreshCampaignList(c_id);});
}                                                                      
function unremoveBusinessFromCampaignModal(c_id, b_id){     
	$('#business_modal_'+b_id).fadeOut('slow', function(){$('#business_modal_'+b_id).remove();});                                                                                                             
	$.post('/account/campaigns/'+c_id+'/unremove_business', {business_key:b_id,'_method':'put'}, function(r){$('#removed_total').html(r); refreshCampaignList(c_id);});
}

function removeBusinessFromCampaign(c_id, b_id, num){     
	if (confirm('Are you sure? This will remove '+num+' from the campaign.')){
		$.post('/account/campaigns/'+c_id+'/remove_business', {business_key:b_id,'_method':'put'}, function(r){$('#removed_total').html(r);});
		$.each($('#campaign_list_area tr'), function(){  
			if ($(this).attr('data-business-key') == ''+b_id){
				removeInvestor(c_id,$(this).attr('data-investor-key'));
			}
		});
	}
} 

function getCampaignListByLetter(el,c_id){                                                                             
	$('#campaign_list_form_indicator').show();                                                      
	$.get('/account/campaigns/'+c_id+'/step_2', {letter:$(el).attr('data-letter'), field:$('#campaign_property_id').val()}, function(r){$('#campaign_list_area').html(r); makeModalsLive();} );  
	$.each($('#campaign_search_letters a'), function(){$(this).removeClass('focused'); $(this).addClass('not_focused');}); 
	$(el).addClass('focused');
	$(el).removeClass('not_focused');     
}                               
function refreshCampaignList(c_id){  
	var el = $('#campaign_search_letters a.focused');
	getCampaignListByLetter(el,c_id);     
}

function fitMap(bounds) {
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}
function setMapToDefault(){
	removeMarkers();
	resetPolys();
	map.setCenter(new GLatLng(40.16,-96.72), 4);
}

function removeMarkers(){
	$.each(addedMarkers, function(){ e = this; map.removeOverlay(e);});
	addedMarkers = []; //replaced addedMarkers.clear();
	//map.setCenter(new GLatLng(40.16,-96.72),4);      
}
function afterGetVisits(r){
	var jData = parseJSON(r);
	$.each(jData.locations, function(){
		l = this;
		latlng = new GLatLng(parseFloat(l.latitude),parseFloat(l.longitude));
		var marker = new GMarker(latlng, {clickable: true, title:l.full_name});
		map.addOverlay(marker);
		addedMarkers.push(marker);          
		latlng_to_marker.put(latlng, {'object':marker, 'content':l});
		GEvent.addListener(marker, "click", showMarkerPopup);
	});                
}
function showMarkerPopup(latlng){                  
	marker_hash = latlng_to_marker.get(latlng);    
	marker = marker_hash['object'];
	c = marker_hash['content'];
	var wins = [new GInfoWindowTab("Name", c.basic_info), new GInfoWindowTab("Contact Info", c.contact_info)]; 
	if (!isBlank(c.property))
		wins.push(new GInfoWindowTab("Properties", c.property));      
	setTimeout(function(){ $(".marker_area a.group").fancybox({'hideOnContentClick': false, autoDimensions:false, margin:0, frameWidth:860, frameHeight:'80%', overlayShow:true}); $('span.marker_timeago').timeago(); }, 500);    
	marker.openInfoWindowTabsHtml(wins, { maxWidth:300});                                               
}                  
    

function onPolyClick(latlng){         
	//map.closeInfoWindow();           
	resetPolys();          
	found = $.grep(poly_infos.values(), function(pi){   
		return pi['object'].Contains(latlng);
	});                      
	if (found.length > 0){     
		item = found[0];           
		var url = '/account/region_markers';     
		vs = {'region_name':item['name'], 'visit_type':lastViewedMapMetric()}                                                                                  
		$.get(url, vs, afterGetVisits);        
		fitMap(item['object'].getBounds());       
		item['object'].hide();      
		item['hidden'] = true;       
	}                   
}
function resetPolys(){
	removeMarkers();
	$.each(poly_infos.values(), function(){ pi = this; if (pi['hidden'] == true){pi['object'].show(); pi['hidden'] = false;} });
}
function pollCampaignUpdate(){
	var url = '/account/campaigns/news';
	var pars = {'_method':'get', 'last_viewed_visit_id':$('#user_last_viewed_visit_id').val(), 'visit_type':lastViewedMapMetric()};           
	$.post(url, pars, afterPollCampaignUpdate);  
}
function updateVisitTypeQuantity(el_id, quantity, focused){
	var re = new RegExp(/.+\((\d+)\)/);
	curr_stripped = $(el_id).innerHTML.replace("<b>", "").replace("</b>", "");
	var m = re.exec(curr_stripped);

	changed = (m[1] != quantity);
	if (changed){
		new_label = curr_stripped.replace(/\(\d+\)/, "("+quantity+")");
		label = (focused ? new_label : '<b>'+new_label+'</b>');
		$(el_id).update(label);
	}
}
function refreshMap(){                                  
	//map.closeInfoWindow();
	setMapToDefault();                                     
	$.each(poly_infos.keys(), function(){
		var label = this+'';                                   
		var poly = poly_infos.get(label);
		var hits = map_db[label][lastViewedMapMetric()];                    
		if (isBlank(hits))
			hits = 0;
		var c = hits_to_color(hits); 
		if (poly['color'] != c){
			poly['color'] = c;
			poly['object'].setFillStyle({color:c, opacity:hits_to_opacity(hits)});
		}
		    
	});
}	           
	
function iam(){
	$.each(updateJData.state_updates, function(){
		x = this;
		poly = poly_infos.get(x[0]);
		//this check is necessary b/c we may define states on the backend not defined on the map
		if (poly){
			if (poly['color'] != x[1]){
				poly['color'] = x[1];
				poly['object'].setFillStyle({color:x[1]});
			}
		}
	});

	var map_metric_label = $('#map_metric_label_'+lastViewedMapMetric());
	if (map_metric_label.innerHTML.include("<b>")){
		if (updateJData.needs_notification){
			latlng = new GLatLng(parseFloat(updateJData.notification_lat),parseFloat(updateJData.notification_lng));
			map.openInfoWindowHtml(latlng, updateJData.notification);
			map_metric_label.update(map_metric_label.innerHTML.gsub(/\<\/?b\>/, ""));
		}
	}         
	
}
function afterRefreshMap(req){      
}
function lastViewedMapMetric(){
	return $("input[name=user[last_map_metric]]:checked").val()
}         


function hits_to_color(hits){
	if (hits == 0){
		return "#ffffff";
	} else if (hits <= 10){
		return "#B1CCF8"
	} else if (hits <= 20){
		return "#1565EA"
	} else {
		return "#0E439C";
	}
}              
function hits_to_opacity(hits){
	if (hits == 0) 
	  	return 0.7;
	else if (hits <= 10)
		return 0.7;
	else if (hits <= 20) 
		return 0.7; 
	return 0.9;
}

function makeRecentActionLinksLive(){                                                          
	makeModalsLive();             
	$('span.timeago').timeago();         
}                                 
function makeCaSigningLinksLive(){                                                               
	makeModalsLive();             
}                                 
function makeVisitorLinksLive(){
	makeModalsLive();                                                              
}                       
function makeModalsLive(){                                                                     
	$("a.group").fancybox({'hideOnContentClick': false, autoDimensions:false, margin:0, frameWidth:860, frameHeight:'80%', overlayShow:true});
}                                                                      			
	
function updateDashboardPref(){
	$('#dashboard_prefs_form_indicator').show();
	f = $('#dashboard_prefs_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#dashboard_area').html(resp);$('#dashboard_prefs_form_indicator').hide();})
}
function updateDashboardCasSignedPref(){
	$('#dashboard_cas_signed_form_indicator').show();
	f = $('#dashboard_cas_signed_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#ca_signings_area').html(resp);$('#dashboard_cas_signed_form_indicator').hide();})
}  
function updateDashboardVisitorsPref(){
	$('#dashboard_visitors_form_indicator').show();
	f = $('#dashboard_visitors_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#visitors_area').html(resp);$('#dashboard_visitors_form_indicator').hide();})
}  
function updateDashboardRecentActionsPref(){
	$('#dashboard_recent_actions_form_indicator').show();
	f = $('#dashboard_recent_actions_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#recent_actions_area').html(resp);$('#dashboard_recent_actions_form_indicator').hide();})    
}  
function updateInvestorRecentActionsPref(){
	$('#investor_recent_actions_form_indicator').show();
	f = $('#investor_recent_actions_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#investor_recent_actions_area').html(resp);$('#investor_recent_actions_form_indicator').hide();})
}   
function updateInvestorRemovesPref(){
	$('#investor_removes_form_indicator').show();
	f = $('#investor_removes_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#investor_removes_area').html(resp);$('#investor_removes_form_indicator').hide();})
}                        
function updateCampaignListSizePref(){
	$('#campaign_list_form_indicator').show();
	f = $('#campaign_list_form');
	$.post(f.attr('action'), f.serialize(), function(resp){ $('#campaign_list_area').html(resp);$('#campaign_list_form_indicator').hide();})
}                        

function checkStatCaSigns(){
  
}

function toggleInvolvedInFields(){
	if ($('#investor_principal_true').is(':checked'))
		$('#involved_in_fields').show();
	else
		$('#involved_in_fields').hide();
}

function ajaxDelete(url, confirm_text){   
	if (confirm(confirm_text)){                                             
		$.post(url,{'_method':'delete'});
 		return true;
	}
	return false;
}

function ajaxPut(url){                                                      
	$.post(url,{'_method':'put'});
 	return true;    
}

function findMatches(){                        
	var url = '/account/criterias/matches';                   
	$.post(url, $('#campaign_form').serialize()+"&_method=get",afterFindMatches);    
}               
function afterFindMatches(req){  
	var jData = parseJSON(req.responseText);
	if (jData.num_matches != null){    
		$('#recipient_matches').update(jData.num_matches);                                                                                   
		$('#recipient_matches_area').effect('highlight', {color:'#ffffcc'}, 1500); 
	}
}                           
	
function selectAllItems(el_id){
	els = $$('#'+el_id+' input'); 
	
	els.each( function (el){
		el.checked = true;
	});
}   
	
function deselectAllItems(el_id){         
	els = $$('#'+el_id+' input'); 
	
	els.each( function (el){
		el.checked = false;
	});
}       

function deleteSelectedItems(el_id){                 
	var els = $$('#'+el_id+' input');   
	var sum = 0;
	
	els.each( function (el){ 
		if (el.checked == true)
			sum+=1;
	}); 
	        
	if (sum == 0) {
		alert("There are no items selected.");
	} else {
		if (confirm("Are you sure you want to delete "+sum+" items?")){
			$(el_id).submit();
		}
	}
}                                 

function grantAccess(investor_key){                                                                                
	$('#grant_access_indicator').show();
	$('#grant_access_button').hide();
	var prop_id = $('#grant_access_property_id').val();
	$.post('/account/properties/'+prop_id+'/manual_ca_sign', {'investor_key':investor_key}, function(r){ 	                                                                         
		$('#grant_access_indicator').hide();
		$('#grant_access_button').show();      
		$('#confidential_access').html(r); 		
	});
}

function cropPropertyImage(property_image_id){ 
	$('#cropper_btn_area').hide();       
	$('#cropping_images_message_area').show();
	$('#cropping_images_message').effect("pulsate", { times:20 }, 1000);       
	var url = '/account/property_images/'+property_image_id+'/save_cropping';
	var pars = {'_method':'put', 'x':$('#x').val(), 'y':$('#y').val(), 'width':$('#width').val(), 'height':$('#height').val()};
	$.post(url, pars, function(r){afterCropPropertyImage(r, property_image_id);}); 
}                                                                                                         
function afterCropPropertyImage(r, old_property_image_id){ 
	data = parseJSON(r);      
	$.fancybox.close();                                                   
	$('#image_'+old_property_image_id).after(data.thumbnail);                
	$('#image_'+old_property_image_id).remove();                             
}  
function showPhotoModal(){
	showModal('photo_modal_area', 'photo_title_area', 'photo_modal_content');                                  
}                        
function hidePhotoModal(){ 
  //Element.hide('photo_modal_area'); 
  $('#photo_modal_indicator').show();  
  $('#photo_modal_content').update('');  
  $('#photo_modal_content').hide();                        
  hideOverlay();        
}                                                                                       
function makePropertyImagesSortable(){	
	$('#property_images').sortable({axis: 'x',update:updatePropertyImagePositions});
	$.each($('.property_images_order'), function(index, el_id){
		$(el_id).val(index);                  
	});
}
function showImageModal(property_image_id){                                                 
	showModal('photo_modal_area', 'photo_title_area', 'photo_modal_content');  
	var url = '/account/property_images/'+property_image_id;
	$.post(url, {'_method':'get'}, function(r){
		$('#photo_modal_content').html(r);
		$('#photo_modal_indicator').hide();
		$('#photo_modal_content').show();
	});
}                  
function deletePropertyImage(property_image_id){
	$('#image_'+property_image_id).fadeOut('slow', function(){$('#image_'+property_image_id).remove(); makePropertyImagesSortable();}); 
	var url = '/account/property_images/'+property_image_id;
	$.post(url,{'_method':'delete'});
}                       
function deletePropertyPublicUpload(property_public_upload_id){
	$('#property_public_upload_'+property_public_upload_id).fadeOut('fast', function(){$('#property_public_upload_'+property_public_upload_id).remove();});
	var url = '/account/property_public_uploads/'+property_public_upload_id;
	$.post(url,{'_method':'delete'});
}                        
function deletePropertyPrivateUpload(property_private_upload_id){
	$('#property_private_upload_'+property_private_upload_id).fadeOut('fast', function(){$('#property_private_upload_'+property_private_upload_id).remove();}); 
	var url = '/account/property_private_uploads/'+property_private_upload_id;
	$.post(url,{'_method':'delete'});
}     
function showCropperForm(property_image_id){
	showModal('cropper_modal_area', 'invite_many_title_area', 'cropper_modal_content');
	var url = '/account/property_images/'+property_image_id+'/crop';		
	
	$.post(url, {'_method':'get'}, function(r){
		$('#cropper_modal_content').html(r);
		$('#cropper_modal_indicator').hide();
		$('#cropper_modal_content').show();
	});                     	
}
function hideCropperForm(){    
  //Element.hide('cropper_modal_area'); 
  $('#cropper_modal_indicator').show();  
  $('#cropper_modal_content').update('');  
  $('#cropper_modal_content').hide();  
  hideOverlay();
}  



function contactToggle(value, index){
	if (value == '-1'){ showModal('invite_many_form_area', 'invite_many_title_area', 'invite_many_input');}
}     
function blurOnEnter (event){
	var code = (event.keyCode ? event.keyCode : event.which);
 	if(code == 13) {
		var target = event.target || event.srcElement;
		target.blur();
	}
}   
   
function toggleContactAll(el, index){
	if (el.is(':checked')){
		$.each($('#contact_boxes_'+index+' input'), function(){
			this.attr('checked',true);
			this.attr('disabled',true);
		});
	} else {                                                                                        
		$.each($('#contact_boxes_'+index+' input'), function(){
			this.attr('checked',false);
			this.attr('disabled',false);
		});        
	}
}