//GLOBAL VARS
var map;
var startZoom = 15;
var gdir;
var address;
var state = " NC";
var marker;
var originalDiv;
var navDiv;
var loadQuestion = 0;
//FUNCTIONS CALLED FROM THE PAGE

function mapIt(clickAddress) {
	address = clickAddress;
	address = address.replace(" block of "," ");
	address = address.replace(" Block of "," ");
	if(address.substring((address.length-1),address.length) != ',') {
               address+=',';
          }
	address += state;
	displayAddress = clickAddress.substring(0,(clickAddress.length-1));
	var geoCoder = new GClientGeocoder();
	$("#backgroundPopup").css({  
		"opacity": "0.5"  
	});  
	$("#backgroundPopup").fadeIn("slow");
	$("#directions").html("");  
	showMainDiv($("#mapWindow"),500,700);
	unhideDiv($("#mapWindowControls"),15,698);
	$("#thisAddress").css("width","660px");
	$("#thisAddress").html("Get directions to " + displayAddress);
	unhideDiv($("#directionsPanel"),480,300);
	$("#formControls").html("Enter a starting address below to get directions to this location:");
	unhideDiv($("#directions"),390,290);
	unhideDiv($("#map"),480,384);
	geoCoder.getLatLng(address,init);
	

}

function showQuestionForm() {
	originalDiv = document.getElementById("questionFormPanel").innerHTML;
	$("#backgroundPopup").css({  
		"opacity": "0.5"  
	});  
	$("#backgroundPopup").fadeIn("slow");  
	showMainDiv($("#questionFormWindow"),550,535);
	unhideDiv($("#questionFormWindowControls"),15,530);
	unhideDiv($("#questionFormPanel"),470,515);
}

function showCommentsForm() {
	originalDiv = document.getElementById("commentsFormPanel").innerHTML;
	$("#backgroundPopup").css({  
		"opacity": "0.5"  
	});  
	$("#backgroundPopup").fadeIn("slow");  
	showMainDiv($("#commentsFormWindow"),500,535);
	unhideDiv($("#commentsFormWindowControls"),15,530);
	unhideDiv($("#commentsFormPanel"),470,515);
}

//MAPPING FUNCTIONS

function addMarker(markerll) {
	var marker = new GMarker(markerll);
	map.addOverlay(marker);

	}

function init(markerll) {
      if (GBrowserIsCompatible()) {
 		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.setCenter(markerll, startZoom);
		addMarker(markerll);

	}

}

function setDirections() {
	fromAddress = document.directionsForm.to.value;
	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
	gdir.load("from: " + fromAddress + " to: " + address, { "locale": "en_US" });
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code)
	else alert("An unknown error occurred.");
	   
}

function onGDirectionsLoad(){ 
	map.addOverlay(gdir.getPolyline());
	$("#formControls").html('<a href="#" onclick="printMap()">Format for printing</a>');
//	$("#formPanel").html('<a href="#" onclick="printMap()">Format for printing</a>');
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
}
//FLOATING DIV FUNCTIONS

//SHOWS MAIN WINDOW
function showMainDiv(canvas,divHeight,divWidth) {
	canvas.css("position","absolute");
	canvas.css("zIndex",100);
	var windowWidth;
	var windowHeight;  
	if (parseInt(navigator.appVersion)>3) {
 		if (navigator.appName=="Netscape") {
  			windowWidth = window.innerWidth;
  			windowHeight = window.innerHeight;
		 }
 		if (navigator.appName.indexOf("Microsoft")!=-1) {
  			windowWidth = document.body.offsetWidth;
  			windowHeight = document.body.offsetHeight;
 		}
	}


	var left = (windowWidth - divWidth)/2;  
	canvas.css("top","50px");
	canvas.css("left",left);
	canvas.css("width",divWidth + "px");
	canvas.css("height",divHeight + "px");
	var options = { to: {'width': divWidth,'height': divHeight} };
	canvas.show("clip");
}

//SHOWS CHILD DIVS

function unhideDiv(canvas,divHeight,divWidth) {
	canvas.css("width",divWidth + "px");
	canvas.css("height",divHeight + "px");
}

//HIDES MAIN WINDOW

function hideWindow(thisWindow) {
	$("#" + thisWindow + " > div").css("width", "0px");
	$("#" + thisWindow + " > div").css("height", "0px");
  	$("#" + thisWindow).hide("clip");
	if(loadQuestion == 0) {
		$("#backgroundPopup").fadeOut("slow");
	}
	if(thisWindow == "questionFormWindow" && originalDiv != undefined) {
		document.getElementById("questionFormPanel").innerHTML = originalDiv;
	}
	if(thisWindow == "commentsFormWindow" && originalDiv != undefined) {
		document.getElementById("commentsFormPanel").innerHTML = originalDiv;
	}
}


//PUT FUNCTIONS FOR ENTER/LEAVE HERE!!!

//EXPANDS MAP FOR PRINTING

function printMap() {
	$("#mapWindow").css("top","0px");
	$("#mapWindow").css("left","180px");
	unhideDiv($("#mapWindow"),700,900);
	$("#mapWindowControls").css("width","895px");
	$("#thisAddress").css("width","860px");
	unhideDiv($("#directionsPanel"),670,390);
	unhideDiv($("#directions"),490,380);
	unhideDiv($("#map"),680,495);
	$("#formControls").html('<a href="#" onclick="print()">Print</a>');

}

//HIDES WINDOW IF USER CLICKS MAIN PAGE
//OR PRESSES ESCAPE KEY

$(document).ready(function(){
	$("#backgroundPopup").click(function(){
		hideAll();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27){
			hideAll();
		}
	});

	hideAll();

});

function hideAll() {
	hideWindow('mapWindow');
	hideWindow('commentsFormWindow');
	if(loadQuestion == 0) {
		hideWindow('questionFormWindow');
	}
	else {
		showQuestionForm();
		loadQuestion = 0;
	}

}


//SUBMIT QUESTION

function sendQuestion() {
	if(checkItems(document.questionForm.name.value,document.questionForm.email.value,document.questionForm.question.value)) {
		$('#questionForm button').attr('disabled','true');
		$.post("wp-content/themes/myreporter/askQuestion.php",
			{ name: document.questionForm.name.value, email: document.questionForm.email.value,question: document.questionForm.question.value,permission:document.questionForm.permission.checked },
			function(data){
    				$("#questionFormPanel").html(data);
  			}
		);
	}
	else {
		return false;
	}
}

function sendComment() {
	if(checkItems(document.commentsForm.author.value,document.commentsForm.email.value,document.commentsForm.comment.value)) {
		$.post("wp-comments-post-mr.php",
			{ author: document.commentsForm.author.value, email: document.commentsForm.email.value,comment: document.commentsForm.comment.value,comment_post_ID:document.commentsForm.comment_post_ID.value,comment_parent: document.commentsForm.comment_parent.value },
			function(data){
    				$("#commentsFormPanel").html(data);
  			}
		);
	}
	else {
		return false;
	}
}

function checkItems(name,email,comment){
	if(name == "" || name == undefined) {
		alert("Please include your name.");
		return false;
	}
	if(email == "" || email == undefined) {
		alert("Please include your email.");
		return false;
	}
	if(comment == "" || comment == undefined) {
		alert("Please include a comment or question.");
		return false;
	}
	if (!emailCheck(email)) {
		alert(email + " doesn't appear to be a valid email address.");
		return false;
	}
	return true;

}

function emailCheck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}

	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}
		
	 if (str.indexOf(" ")!=-1){
	 	return false
	 }
	 return true					
}
