// JavaScript Document

function clearText(thefield) {
  if(thefield.defaultValue==thefield.value) { thefield.value = "" }
}

function replaceText(thefield) {
  if(thefield.value=="") { thefield.value = thefield.defaultValue }
}

function preloadImages() {
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}


function tabSelect(id){
	if(id == 'search_tab_places'){
		$("#advanced_options_event").slideUp(300);
		$(".start_hidden").hide();
		$("#searchfor_label").html("Search for Places (Advanced Options)");
		var opp = 'search_tab_events';
		var val = 'places';
	}else if(id == 'search_tab_events'){
		$("#advanced_options_event").slideDown(300);
		$(".start_hidden").show();
		$("#searchfor_label").html("Search for Events (Advanced Options)");
		var opp = 'search_tab_places';
		var val = 'events';
	}
	
	$("#"+id+"").attr({"class": "search_tab_selected"});
	$("#"+opp+"").attr({"class": "search_tab_unselected"});
	$("#search_type").val(val);
}

function srch(){
	var val = $("#search_val").val();
	var type = $("#search_type").val();
	if(val == 'Enter City, State or ZIP Code'){
		$("#search_val").val("Please Enter A Search Term!");
	}else{
		window.location = "search/"+type+"/"+escape(val)+"/";
	}
}

function changeFrequency(selected){
	if(selected == 1){
		$("#freq_weekly").slideUp(300);
		$("#freq_monthly").slideUp(300);
		$("#freq_once").slideDown(300);
	}else if(selected == 2){
		$("#freq_once").slideUp(300);
		$("#freq_monthly").slideUp(300);
		$("#freq_weekly").slideDown(300);
	}else if(selected == 3){
		$("#freq_weekly").slideUp(300);
		$("#freq_once").slideUp(300);
		$("#freq_monthly").slideDown(300);
	}
}

var count_times = 1;
function addTime(){
	if(count_times == 3) return false;
	var html = $("#times").html();
	$("#time_table").append("<tr><td>&nbsp;</td><td>"+html+"</td></tr>");
	count_times++;
}

var count_clone = 1;
function cloneArea(area,target,mx){
	
}

var count_deals = 1;
function addDeal(){
	if(count_deals > 5) return false;
	var html = $("#deals").html().replace(/deal_amount_[0-9]/g,"deal_amount_"+count_deals+"").replace(/deal_type_sub_[0-9]/g,"deal_type_sub_"+count_deals+"").replace(/mini dollar/g,"mini percent");
	$("#deal_table").append("<tr><td>&nbsp;</td><td>"+html+"</td></tr>");
	count_deals++;
}

function changeDealType(val,id){
	if(val == 1){
		$("#"+id+"").attr({"class":"big_forms mini percent"});
	}else{
		$("#"+id+"").attr({"class":"big_forms mini dollar"});
	}
	
	if(val == 4){
		$("#"+id+"").val('0.00');
	}
}

function addFavorite(val,type){
	$.getJSON('ajax.php?call=addFavorite&target='+escape(val)+'&type='+escape(type)+'',
	function(data){
		if(data.status == 'ok'){
			$("#"+type+"favorite_"+val+"").fadeOut(300,function(){
				$("#"+type+"favorite_"+val+"").html('Added!');
				$("#"+type+"favorite_"+val+"").attr({'onclick':'return false;'});
				$("#"+type+"favorite_"+val+"").fadeIn(300);
			});
			if(type == 'estab'){
				$("#favorite_est").slideUp(300,function(){
					$("#favorite_est div.wrapper").prepend("<p class=\"list\"><span><a href=\"view/"+data.est_info.est_id+"/\">"+data.est_info.est_name+"</a> "+data.est_info.est_city+"</span></p>");
					$("#favorite_est").slideDown(300);
				});
			}else if(type == 'event'){
				$("#favorite_events").slideUp(300,function(){
					$("#favorite_events div.wrapper").prepend("<p class=\"list\"><a href=\"event/"+data.event_info.event_id+"/\">"+data.event_info.event_name+"</a><span>"+data.event_info.est_name+"</span></p>");
					$("#favorite_events").slideDown(300);
				});
			}
		}else{
			window.location="signup.php?status=erroraccess";
		}
	});
}

function remFavorite(val,type){
	$.getJSON('ajax.php?call=remFavorite&target='+escape(val)+'&type='+escape(type)+'',
	function(data){
		if(data.status == 'ok'){
			$("#"+type+"favorite_"+val+"_rem").fadeOut(300,function(){
				$("#"+type+"favorite_"+val+"_rem").html('Removed!');
				$("#"+type+"favorite_"+val+"_rem").attr({'onclick':'return false;'});
				$("#"+type+"favorite_"+val+"_rem").fadeIn(300);
			});
			$("#list_"+type+"_"+val+"").fadeOut(300);
		}else{
			alert(data.message);
		}
	});
}

function updateEvents(est,num){
	$("#events").attr({style:"opacity:0.4;"});
	$.ajax({
		url: 'ajax.php?call=updateEvents&est='+escape(est)+'&num='+escape(num)+'',
		type: 'GET',
		dataType: 'html',
		success: function(html){
			if(html){
				$("#events").html(html);
			}else{
				alert("There was an error with your last request, please try again");
			}
			$("#events").attr({style:"opacity:1;"});
		}
	});
}

function toggleActivate(id,type,set){
	$.ajax({
		url: 'ajax.php?call=toggleActivate&id='+escape(id)+'&type='+escape(type)+'&set='+escape(set)+'',
		type: 'GET',
		dataType: 'html',
		success: function(html){
			if(html){
				$("#toggleactivate_"+type+"_"+id+"").html(html);
			}else{
				alert("There was an error with your last request, please try again");
			}
		}
	});
}


function showSuccess(html){
	if(html){
		$("#messages").html(html);
	}
	$('p.success').prepend("<a style=\"float: right; margin-left: 10px; color: #040404; padding: 0 2px;\" onclick=\"$('p.success').hide(); return false;\" href=\"#\">X</a>");
	$('p.success').show();
	setTimeout("$('p.success').animate({right:\"10px\"},300)",1000);
	setTimeout("$('p.success').fadeOut(3000)",8000);
}

function getPlacemarksNear(lat,lon,id,animate,is_search,message){
	$.getJSON('ajax.php?call=getPlacemarksNear&lat='+escape(lat)+'&lon='+escape(lon)+'',
	function(data){
		if(data.status == 'ok'){
			var count = 0;
			$.each(data.placemarks,function(i,item) {
				var html = "<strong>"+item.name+"</strong><br />"+item.address+"<br />"+item.city+", "+item.state+" "+item.zip+"<br /><a href=\"view/"+item.est_id+"/\" style=\"font-weight: bold;\">View This Location</a><br /><a href=\"event_add.php?step=2&est="+item.est_id+"\" style=\"font-weight: bold;\">Add An Event at This Location</a>";
                $('#'+id).jmap('AddMarker',{
					'pointLatLng':[item.lat, item.lon],
					'pointHTML': html
				},function(marker){
					if(count == 0){
						marker.openInfoWindowHtml(html);
					}
				});
				
				if(count == 0){
					$('#'+id).jmap("MoveTo",{'mapCenter':[item.lat,item.lon],'centerMethod': "pan"});
				}
				if(is_search == true){
					if(item.is_favorite){
						$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.lat+","+item.lon+"); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 300px;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.name+"</a></strong></td><td>"+item.city+"</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"estabfavorite_"+item.est_id+"_rem\" onclick=\"remFavorite("+item.est_id+",'estab'); return false;\" title=\"Remove from your favorites\" href=\"#\">Remove</a></td></tr>");
					}else{
						$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.lat+","+item.lon+"); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 300px;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.name+"</a></strong></td><td>"+item.city+"</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"estabfavorite_"+item.est_id+"\" onclick=\"addFavorite("+item.est_id+",'estab'); return false;\" title=\"Add to your favorites\" href=\"#\">Add</a></td></tr>");
					}
				}else if(is_search == 'add_event'){
					$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.lat+","+item.lon+",16); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 300px;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.name+"</a></strong></td><td>"+item.city+"</td><td style=\"width: 80px;\"><a href=\"event_add.php?step=2&est="+item.est_id+"\">Add Event</a></td></tr>");
				}
            });
			if(is_search) $("#results").slideDown(300);
			if(message){
				showSuccess(message);
			}else{
				showSuccess("<p class=\"success\" style=\"font-size: 14px; line-height: 18px;\">We found "+data.placemarks[0].results_count+" results and matched the closest location to your search. Move the map to browse for the location you want to add the event to.</p>");	
			}
			return true;
		}else if(data.status == 'no_results' && animate == true){
			$('#'+id).animate({'height': '0px'},function(){
				$(this).jmap('CheckResize');
				$(this).attr({style:"display: none;"});
			});
			showSuccess("<p class=\"success\" style=\"font-size: 14px; line-height: 18px;\">We didn't find any establishments using your search, please use the form below to add this establishment.</p>");
			return true;
		}
	});
}

function moveToMarker(id,lat,lon,zoom){
	$('#'+id+'').jmap("MoveTo",{mapCenter:[lat, lon],mapZoom:zoom});
	$.scrollTo('#'+id+'');
}

function loadToSidebar(html){
	if(html) $("#side_slave").html(html);
	$("#side_main").slideUp(300);
	$("#side_slave").slideDown(300);
}

function searchNearby(lat,lon,id,limit,label,message,method){
	$.getJSON('ajax.php?call=getPlacemarksNear&lat='+escape(lat)+'&lon='+escape(lon)+'&limit='+escape(limit)+'',
	function(data){
		if(data.status == 'ok'){
			if(!label) label = "Search Results";
			var count = 0;
			var side = "";
			$.each(data.placemarks,function(i,item) {
                $('#'+id).jmap('AddMarker',{
					'pointLatLng':[item.lat, item.lon],
					'pointHTML': "<strong><a href=\"view/"+item.est_id+"/\" style=\"font-weight: bold;\">"+item.name+"</a></strong><br />"+item.address+"<br />"+item.city+", "+item.state+" "+item.zip+""
				});
				side += "<p class='list'><span><img src=\"images/placemark.gif\" alt=\"\" style=\"cursor: pointer; vertical-align: middle; margin-right: 5px;\" title=\"View on Map\" onclick=\"moveToMarker('"+id+"',"+item.lat+","+item.lon+",18);\" /> <a href=\"view/"+this.est_id+"/\"> "+this.name+"</a> "+this.city+"</span></p>";
				if(count == 0){
					$('#'+id).jmap("MoveTo",{'mapCenter':[item.lat,item.lon],'mapZoom':10});
				}
            });
			if(method == 'prepend'){
				$("#side_main").prepend('<div class="inner_cell border"><h5>'+label+'</h5><div class="wrapper">'+side+'</div></div>');
			}else{
				$("#side_slave").html('<div class="inner_cell border"><h5>'+label+'</h5><div class="wrapper">'+side+'</div></div>');
				$("#side_main").slideUp(300);
				$("#side_slave").slideDown(300);
			}
			if(message){
				showSuccess(message);
			}else{
				showSuccess("<p class=\"success\" style=\"font-size: 14px; line-height: 18px;\">We found "+data.placemarks[0].results_count+" results and matched the closest location to your search. Move the map to browse for the location you want to move to.</p>");	
			}
			return true;
		}
	});
}

function searchFor(lat,lon,id,string,add_events,load_message,omitfirst,start){
	if(!load_message) load_message = 'Loading...';
	$('.loader_parent').show();
	$('.loader_cell').html('<img src="images/loading.gif" alt="" style="vertical-align: middle;" /> '+load_message);
	//alert('ajax.php?call=searchFor&lat='+escape(lat)+'&lon='+escape(lon)+''+string);
	$.getJSON('ajax.php?call=searchFor&lat='+escape(lat)+'&lon='+escape(lon)+''+string+'',
	function(data){
		if(data.status == 'ok'){
			$('.loader_cell').hide();
			var count = 0;
			if(data.search_type == 'events'){
				$("div#results table").addClass("events_table");
			}else{
				$("div#results table").removeClass("events_table");
			}
			$.each(data.events,function(i,item) {
				var html = "<a href=\"view/"+item.est_id+"/\" style=\"font-weight: bold;\">"+item.est_name+"</a><br />"+item.est_street_address+"<br />"+item.est_city+", "+item.est_state+" "+item.est_zip+"<br /><strong><em>"+item.distance+" miles away</em></strong><br /><a href=\"event_add.php?step=2&est="+item.est_id+"\" style=\"font-weight: bold;\">Add An Event at This Location</a>";
                $('#'+id).jmap('AddMarker',{
					'pointLatLng':[item.est_lat, item.est_lon],
					'pointHTML': html
				},function(marker){
					if(omitfirst){
						if(i == 1){
							$('#'+id).jmap("MoveTo",{'mapCenter':[item.est_lat,item.est_lon],'mapZoom':17,'centerMethod': "pan"});
							marker.openInfoWindowHtml(html);
						}
					}else{
						if(i == 0){
							$('#'+id).jmap("MoveTo",{'mapCenter':[item.est_lat,item.est_lon],'mapZoom':17,'centerMethod': "pan"});
							marker.openInfoWindowHtml(html);
						}
					}
				});
				if(add_events){
					$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.est_name+"</a></strong></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 120px;\"><a href=\"event_add.php?step=2&est="+item.est_id+"\">Add An Event Here</a></td></tr>");
				}else{
					if(data.search_type == 'events'){
						$("div#results table").append("<tr><td class=\"extras_title\" style=\"padding-left: 10px;\"><a href=\"event/"+item.event_id+"/\">"+item.event_name+"</a><span>"+item.recurred_time+"</span></td><td class=\"extras_times\" style=\"border-left: none;\">at <a href=\"view/"+item.est_id+"/\">"+item.est_name+"</a><br />"+item.distance+" Miles Away</td><td style=\"width: 20px; border-left: none;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td></tr>");
						//$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"event/"+item.event_id+"/\">"+item.event_name+"</a></strong></td><td style=\"width: 100px; overflow: hidden;\"><span class=\"light\">"+item.est_name+"</span></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"eventfavorite_"+item.event_id+"_rem\" onclick=\"remFavorite("+item.event_id+",'event'); return false;\" title=\"Remove from your calendar\" href=\"#\">Remove</a></td></tr>");
						//if(item.is_favorite){
						//	$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"event/"+item.event_id+"/\">"+item.event_name+"</a></strong></td><td style=\"width: 100px; overflow: hidden;\"><span class=\"light\">"+item.est_name+"</span></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"eventfavorite_"+item.event_id+"_rem\" onclick=\"remFavorite("+item.event_id+",'event'); return false;\" title=\"Remove from your calendar\" href=\"#\">Remove</a></td></tr>");
						//}else{
						//	$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"event/"+item.event_id+"/\">"+item.event_name+"</a></strong></td><td style=\"width: 100px; overflow: hidden;\"><span class=\"light\">"+item.est_name+"</span></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"eventfavorite_"+item.event_id+"\" onclick=\"addFavorite("+item.event_id+",'event'); return false;\" title=\"Add to your calendar\" href=\"#\">Add</a></td></tr>");
						//}
					}else if(data.search_type == 'places'){
						if(item.is_favorite){
							$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.est_name+"</a></strong></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"estabfavorite_"+item.est_id+"_rem\" onclick=\"remFavorite("+item.est_id+",'estab'); return false;\" title=\"Remove from your Favorites\" href=\"#\">Remove</a></td></tr>");
						}else{
							$("div#results table").append("<tr><td class=\"t_center\" style=\"width: 30px;\"><a href=\"#\" onclick=\"moveToMarker('"+id+"',"+item.est_lat+","+item.est_lon+",18); return false\" class=\"block\"><img src=\"images/placemark.gif\" alt=\"\" border=\"0\" /></a></td><td style=\"width: 200px; overflow: hidden;\"><strong><a href=\"view/"+item.est_id+"/\">"+item.est_name+"</a></strong></td><td style=\"width: 80px;\">"+item.distance+" Miles</td><td style=\"width: 80px;\"><span class=\"light\">&hearts;</span> <a id=\"estabfavorite_"+item.est_id+"\" onclick=\"addFavorite("+item.est_id+",'estab'); return false;\" title=\"Add to your Favorites\" href=\"#\">Add to Favorites</a></td></tr>");
						}
					}
				}
            });
			if(data.num_results > 20){
				var num_total = data.num_results;
				var num_pages = Math.floor(data.num_results / 20);
				var num_current = start;
				
				$("#pagination").append('<a>Page:</a>');
				for(i=1;i<=num_pages;i++){
					if(i>15 && i<Math.max(num_total - 3)){
						
					}else{
						if(i == Math.max(start / 20) + 1){
							$("#pagination").append("<a style=\"background: #6C1F7F; color: #ffffff;\" href=\"#\" onclick=\"$('#search_start').val('"+Math.max(Math.max(i - 1) * 20)+"'); $('form.search').submit(); return false;\">"+i+"</a>");
						}else{
							$("#pagination").append("<a href=\"#\" onclick=\"$('#search_start').val('"+Math.max(Math.max(i - 1) * 20)+"'); $('form.search').submit(); return false;\">"+i+"</a>");
						}
					}
				}
				if(num_pages > Math.max(start / 20) + 1){
					$("#pagination").append("<a href=\"#\" onclick=\"$('#search_start').val('"+Math.max(start + 20)+"'); $('form.search').submit(); return false;\">Next Page >></a>");
				}
				$("#pagination").append('<div class="clear"></div>');
			}
			$("#results").slideDown(300);
			if(start < 20) showSuccess("<p class=\"success\" style=\"font-size: 14px; line-height: 18px;\">We found "+data.num_results+" results and matched the closest location to your search. You can also use the map to search for nearby locations.</p>");	
			return true;
		}else if(data.status == 'no_results'){
			$('.loader_parent').hide();
			$('.loader_cell').hide();
			showSuccess("<p class=\"success\" style=\"font-size: 14px; line-height: 18px;\">We didn't find any events using your search parameters, please search again.</p>");
			return true;
		}
	});
}

function searchNearbyCities(lat,lon,distance,limit){
	$.getJSON('ajax.php?call=searchNearbyCities&lat='+escape(lat)+'&lon='+escape(lon)+'&distance='+escape(distance)+'&limit='+escape(limit)+'',
	function(data){
		$("#nearby").append("<ul></ul>");
		$.each(data.results,function(i,item) {
			$("#nearby ul").append("<li><a href=\"#\" onclick=\"$('#search_val').val('"+item.city+", "+item.state+" "+item.zip5+"'); $('form.search').submit(); return false;\">"+item.city+", "+item.state+"</a> - "+item.distance+" Miles</li>");
			if(i > 10) return false;
		});
		return true;
	});
}

function deleteItem(id,type){
	if(type == 'estab') var type_name = 'Establishment';
	if(type == 'event') var type_name = 'Event';
	if(confirm("Are you sure you want to delete this "+type_name+"?\nThis action is un-doable!")){
		$.getJSON('ajax.php?call=deleteItem&id='+escape(id)+'&type='+escape(type)+'',
		function(data){
			if(data.status == 'ok'){
				window.location = 'index.php?status=deletesuccess';
			}else{
				alert(data.message);
			}
		});
		return false;
	}else{
		return false;
	}
}

function flagEst(id){
	if(confirm("Are you sure you want to flag this establishment?")){
		$.getJSON('ajax.php?call=flagEst&id='+escape(id)+'',
		function(data){
			if(data.status == 'ok'){
				alert('Thank you for flagging this establishment!');
			}else{
				alert(data.message);
			}
		});
		return false;
	}else{
		return false;
	}
}


function checkSearch(){
	var val = $("#search_val").val();
	if(val == "Enter a Zip Code, City or Street Address"){
		$("#search_required").html("<label class=\"error\"></label>");
		return false;
	}else{
		return true;
	}
}

function editEvent(id){
	$.getJSON('ajax.php?call=editEvent&id='+escape(id)+'',
	function(data){
		if(data.status == 'ok'){
			tb_show('Edit this event','event_edit.php?event='+data.id+'&lightbox=login&height=330&width=700','1');
		}else if(data.status == 'not_logged_in'){
			window.location="signup.php?status=erroraccess";
		}else{
			alert(data.message);
		}
	});
}

function editShowAdvanced(off){
	if(!off){
		$(".advanced").show();
		$(".basic").hide();
		$("#event_edit_advanced").val(1);
	}else{
		$(".advanced").hide();
		$(".basic").show();	
		$("#event_edit_advanced").val(0);
	}
}

