function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



$(function(){

		$(document).pngFix();


		$('#getMap').live('click',function(){
			var uno = $('#loc').val().replace(/\,/g,'');
			var dose = uno.replace(/\./g,'');
			var tres = dose.replace(/ /g,'-');
			$('#search_form').attr('action','http://www.antennapoint.com/'+tres+'.html');			
		});

  	var loc = window.location.pathname.replace('.html','');
  	loc = loc.replace('/','');

		function get_comments(){
			if($('#cords').html().length > 10){
						$.getJSON('buttons.php?get_comments='+$('#cords').html(),function(data){
						var comments = '<div id="comments">';
						if(data=="nada"){
							comments = comments + '<p>There are no comments near your location.  Be the first to comment by clicking the link below.</p>';
						}else{
							$.each(eval(data), function(i, item){
								comments = comments + '<div id="username">'+this.username+'</div><div id="comments">'+this.comments+'</div><div id="posted">'+this.posted+'</div><hr>'
							});
						}
						comments = comments +'<a href="javascript:void(0)" id="post_comment">Add Commenton this location</a></div>';
						$('#post_comments_c').html(comments);
				})
			}else{
				var comments = 'You must search for a location before you can see the posts';
				$('#post_comments_c').html(comments);
			}
		}

		function get_stations(){
				var stations = '';
				$.getJSON('buttons.php?get_stations=true',function(data){
						$.each(eval(data), function(i, item){
							if(this[0] != ""){
								stations = stations+'<tr class="newCity"><td>'+this[0];
							}else{
								stations = stations+'<tr><td>&nbsp;';
							}
							stations = stations + '</td><td>'+this[1]+'</td><td>'+this[2]+'</td><td>'+this[3]+'</td></tr>';
						});
						$('#stationsTable tbody').html(stations);
				})
			}




		//Post Comments
		$('#post_comment').live('click',function(){
				if($('#post_comment_form_c').is(":hidden")){$('#post_comment_form_c').toggle();}
				if($('#post_comments_c').is(":visible")){$('#post_comments_c').toggle();}
				if($('#cap').is(":hidden")){$('#cap').toggle();}
		});

		//Button Function
		$('#button').live('click',function(){
			if($(this).attr("id")=="footer"){
				var btn = "contact";
			}else{;
			var btn = $(this).closest("div").attr("id");
			}
			var btns = ["default_c","post_comment_form_c","post_comments_c","mobile_tools_c","resources_c","contact_c","station_search_c","cap"];
			for(var i in btns){
				if($('#'+btns[i]).is(":visible")){$('#'+btns[i]).toggle();}
			}
			if($('#'+btn+'_c').is(":hidden")){$('#'+btn+'_c').toggle();}

			if(btn == 'comments'){
				get_comments();
				if($('#post_comments_c').is(":hidden")){$('#post_comments_c').toggle();}
			}else if(btn == 'station_search'){
				get_stations();
			}else if(btn == 'contact'){
				if($('#cap').is(":hidden")){$('#cap').toggle();}
			}

		});

		if(loc != "" && loc != "index.php"){

		//loose the map background
		$('#map').css('background-image','none');
		
		
		if($('#searched').is(":hidden")){$('#searched').toggle();}
		if($('#chart').is(":hidden")){$('#chart').toggle();}


		var StationTblRows = '';
					//get the antennas from the database
					$.getJSON('fetch.php?loc='+loc,function(data){
							var longitude = data['cords'].longitude;
	        		var latitude = data['cords'].latitude;
	        		//put cords in hidden div
	        		$('#cords').html(data['cords'].latitude+','+data['cords'].longitude);

	        		//set up map
	        		var map = new GMap2($('#mapField').get(0));
			        map.setCenter(new GLatLng(latitude,longitude),6);
							map.setUIToDefault();
							map.setMapType(G_PHYSICAL_MAP);
							var bounds = new GLatLngBounds();

					    // Creates a marker at the given point
					    // Clicking the marker will hide it
					    function createMarker(latlng, windowHTML) {
					      var marker = new GMarker(latlng);
					      GEvent.addListener(marker,"click", function() {
					        map.openInfoWindowHtml(latlng, windowHTML);
					      });
					      return marker;
					  	}

							$.each(eval(data.antenna), function(i, item){
								var marker = new GLatLng(this.latitude,this.longitude);
								
								//get the band
								if(this.post_dtv_channel <= 6){
									var band = 'Low VHF';
								}else if(this.post_dtv_channel >= 14){
									var band = 'UHF';
								}else{
									var band = 'High VHF';
								}								
								
								map.addOverlay(createMarker(marker,'<b>Digital Channel:</b> ' + this.post_dtv_channel + '<br/><b>Call Sign:</b> ' + this.sign + '<br/><b>Distance:</b> ' + this.distance + ' miles.<br/><b>Heading:</b> ' + this.degree + '<br/><b>Power:</b> ' + this.erp + ' kW<br/><b>Band:</b> ' + band));
								map.addOverlay(new GPolyline([new GLatLng(latitude,longitude),new GLatLng(this.latitude,this.longitude)],this.color,1,1.0));
								bounds.extend(marker);

								// build out the table rows for later
								StationTblRows += '<tr><td>'+this.sign+'</td><td>'+this.post_dtv_channel+'</td><td>'+this.ntsc_channel+'</td><td>'+this.erp+'</td><td>'+band+'</td><td>'+this.city+'</td><td>'+this.distance+'</td><td>'+this.degree+'</td></tr>';



							});//end foreach loop

							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());

							if(document.domain == 'antennapoint.com'){
									var StationTbl = '<table id="StationTbl"><thead><tr><th>Sign</th><th>Ch.</th><th>Virt.Ch.</th><th>Pwr</th><th>Band</th><th>City</th><th>Dist</th><th>Heading</th></tr></thead><tbody>';
							}else{
									var StationTbl = '<table id="StationTbl"><thead><tr><th>Sign</th><th>Ch.</th><th>Virt.Ch.</th><th>Pwr</th><th>Band</th><th>City</th><th>Dist</th><th>Heading</th></tr></thead><tbody>';
							}
							StationTbl += StationTblRows;
							StationTbl += '</tbody></table>';
							$('#chartContent').html(StationTbl);

							$('#chart').show();
							$('#StationTbl').tablesorter();

							var fifth = data.antenna[4].distance;
							if(fifth <= 10){
								$('#ad-img').attr("src", 'images/ad-2.jpg');
								$('#ad-href').attr("href", 'http://www.antennasdirect.com/C1-Clearstream-Convertible-DTV-antenna.html?utm_source=AntennaPoint&utm_medium=banner&utm_content=C1C&utm_campaign=ClearStream');
							}else if (fifth > 25){
								$('#ad-img').attr("src", 'images/ad-4.jpg');
								$('#ad-href').attr("href", 'http://www.antennasdirect.com/C4-Clearstream-DTV-antenna.html?utm_source=AntennaPoint&utm_medium=banner&utm_content=C4&utm_campaign=ClearStream');
							}else {
								$('#ad-img').attr("src", 'images/ad-3.jpg');
								$('#ad-href').attr("href", 'http://www.antennasdirect.com/C2-Clearstream-DTV-antenna.html?utm_source=AntennaPoint&utm_medium=banner&utm_content=C2&utm_campaign=ClearStream');
								}

							});//end getJSON



				};//end getmap click

			});//end document ready

function validateCaptcha()
{
    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    //alert(challengeField);
    //alert(responseField);
    //return false;
    var html = $.ajax({
    type: "POST",
    url: "includes/check_captcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
    async: false
    }).responseText;
    if(html == "success")
    {
				if($('#post_comment_form_c').is(":visible")){
					//Submit Commnets
					$.post('buttons.php?new_comment=true&cords='+$('#cords').html()+'&username='+$('#post_username').val()+'&comments='+$('#post_comments').val(), function(data) {});

					$.getJSON('buttons.php?get_comments='+$('#cords').html(),function(data){
							var comments = '<div id="comments">';
								$.each(eval(data), function(i, item){
									comments = comments + '<div id="username">'+this.username+'</div><div id="comments">'+this.comments+'</div><div id="posted">'+this.posted+'</div><hr>'
								});
							comments = comments +'<a href="javascript:void(0)" id="post_comment">Add Commenton this location</a></div>';
							$('#post_comments_c').html(comments);
					});

					$('#post_comment_form_c').toggle();
					$('#post_comments_c').toggle();
					vars = '&type=post&post_username='+$('#post_username').val()+'&post_comments='+$('#post_comments').val();
					pageTracker._trackPageview($(this).attr('href')+'/comment-posted/');
					YWATracker.setAction("03");
				}else if($('#company').is(":visible")){

					vars = '&type=adver&name='+$('#name').val()+'&email='+$('#email').val()+'&company='+$('#company').val()+'&comment_comments='+$('#comment_comments').val();
					$('#usr_msg').html("Thank you!  We will review your message shortly.");
					$('#usr_msg').fadeOut(2000);
					pageTracker._trackPageview($(this).attr('href')+'/advertising-form-submited/');
					YWATracker.setAction("04");
					}else{
					$('#usr_msg').html("Thank you!  We will review your message shortly.");
					vars = '&type=comments&name='+$('#name').val()+'&email='+$('#email').val()+'&comment_comments='+$('#comment_comments').val();
					pageTracker._trackPageview($(this).attr('href')+'/comment-form-submited/');
					YWATracker.setAction("05");
				}

				$.post('contact.php?do_work=true'+vars, function(data) {});


				if($('#cap').is(":visible")){$('#cap').toggle();}
        return true;
    }
    else
    {
        if($('#captchaStatus').is(":hidden")){$('#captchaStatus').toggle()}
        $("#captchaStatus").html("Your captcha is incorrect. Please try again").fadeOut(2000);

        //return false;
    }
    Recaptcha.reload();
}