	var Home = new GLatLng(34.028, -118.258);
//	var Mecca = new GLatLng(21.43261686447735, 39.814453125);
	// Fix based on Hamid's code
	var Mecca = new GLatLng(21.42252, 39.82621);
	var strAddress = "";
	var Compass;
	var ghline;
	var map;
	var geocoder;
	var angleDecimals = 0;
	var closeZoom = 18;
	var angleStr = "";
	var ll4Zoom = new Array(150.0, 100.0, 50.0, 24.0, 12.0, 6.0, 6.0, 3.0, 3.0, 3.0, 1.25, 1.25, 1.25, .25, .25, 
							.1, .1, .04, .02, .01, .005, .005, .005, .005);

	// read cookie
	function readCookie(name) {
		var nameEQ = 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(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	}

	// parsing the query string
	var qsParm = new Array();
	function qs() {
		var query = window.location.search.substring(1);
		var parms = query.split('&');
		for (var i = 0; i < parms.length; i++) {
			var pos = parms[i].indexOf('=');
			if (pos > 0) {
				var key = parms[i].substring(0,pos);
				var val = parms[i].substring(pos+1);
				qsParm[key] = val;
			}
		}
	}

function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

	// Init Home
	function InitHome() {
		// parse the parameters Lat and Lon
		qsParm['Lat'] = null;
		qsParm['Lon'] = null;
		qs();
		if (qsParm['Lat'] && qsParm['Lon']) {
			Home = new GLatLng(parseFloat(qsParm['Lat']), parseFloat(qsParm['Lon']));
		} else { // read the cookies
			strLat = readCookie('latit');
			strLon = readCookie('longit');
			strAddress = readCookie('gaddress');
			if (strAddress) // to fix the PHP escape problem
				strAddress = replace(strAddress,'+',' ');
			document.setAddrFrm.address.value = strAddress;
			if (strLat && strLon) {
				Home = new GLatLng(parseFloat(strLat), parseFloat(strLon));
			}
		}
	}

	// help window
	function help() {
		hlpWindow = window.open("Help On Qibla", "HelpWindow", "width=300,height=380,resizable=no");
		hlpWindow.document.write('<HTML><BODY>To find your location:<BR>');
		hlpWindow.document.write('<UL><LI>Type your address and press Go.<BR>Examples of valid addresses:<BR>"Los Angeles"<BR>"Birjand, Iran"<BR>"3376 Motor Ave, Los Angeles, CA 90034"');
		hlpWindow.document.write('<LI><B>OR</B> Click on your desired location on the map.');
		hlpWindow.document.write('<LI><B>OR</B> Drag the compass to your desired location on the map.</UL>');
		hlpWindow.document.write('<P ALIGN=left><INPUT TYPE="button" value="close" onclick="window.close()"/>');
		hlpWindow.document.write('<P ALIGN=right><img src="images/logo.jpg" width="80"/></BODY></HTML>');
	}

	// geocode and move to the address
	function moveToAddress(addr) {
		geocoder.getLatLng(addr,
			function(point) {
			  if (!point) {
				alert('Address <' + addr + '> not found');
			  } else {
					Home = point;
					Compass.setPoint(point);
					map.setZoom(closeZoom);
					map.panTo(point);
					showGheblehOnMap(map, Compass);
			  }
			}
		);
	}

	// A TextualZoomControl is a GControl that displays textual "Zoom In"
	// and "Zoom Out" buttons (as opposed to the iconic buttons used in
	// Google Maps).
	function TextualZoomControl() {
	}
	TextualZoomControl.prototype = new GControl();

	// Creates a one DIV for each of the buttons and places them in a container
	// DIV which is returned as our control element. We add the control to
	// to the map container and return the element for the map class to
	// position properly.
	TextualZoomControl.prototype.initialize = function(map) {
	  var container = document.createElement("div");

	  var mDiv = document.createElement("div");
	  this.setButtonStyle_(mDiv);
	  container.appendChild(mDiv);
	  mDiv.appendChild(document.createTextNode("Map"));
	  GEvent.addDomListener(mDiv, "click", function() {
		map.setMapType(G_NORMAL_MAP);
	  });

	  var sDiv = document.createElement("div");
	  this.setButtonStyle_(sDiv);
	  container.appendChild(sDiv);
	  sDiv.appendChild(document.createTextNode("Sat"));
	  GEvent.addDomListener(sDiv, "click", function() {
		map.setMapType(G_SATELLITE_MAP);
	  });

	  var hDiv = document.createElement("div");
	  this.setButtonStyle_(hDiv);
	  container.appendChild(hDiv);
	  hDiv.appendChild(document.createTextNode("Hyb"));
	  GEvent.addDomListener(hDiv, "click", function() {
		map.setMapType(G_HYBRID_MAP);
	  });

	  map.getContainer().appendChild(container);
	  return container;
	}

	// By default, the control will appear in the top left corner of the
	// map with 7 pixels of padding.
	TextualZoomControl.prototype.getDefaultPosition = function() {
	  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
	}

	// Sets the proper CSS for the given button element.
	TextualZoomControl.prototype.setButtonStyle_ = function(button) {
	  button.style.color = "#0000cc";
	  button.style.backgroundColor = "white";
	  button.style.font = "8pt Arial";
	  button.style.border = "1px solid black";
	  button.style.padding = "2px";
	  button.style.marginBottom = "3px";
	  button.style.textAlign = "center";
	  button.style.width = "3em";
	  button.style.cursor = "pointer";
	}

	function getDirection(P1, P2) {
		P1_x = -1*P1.lngRadians();
		P1_y = P1.latRadians(); // to remove the zero
		P2_x = -1*P2.lngRadians();
		P2_y = P2.latRadians(); // to remove the zero
		
		var difflong = P1_x - P2_x;
		direction = ((180/Math.PI) * Math.atan2( Math.sin(difflong), Math.cos(P1_y) * Math.tan(P2_y) - Math.sin(P1_y) * Math.cos(difflong)));
		if (direction < 0)
			direction = 360 + direction;
//		return direction.toFixed(decimals);
		return direction;
	}

	function drawOnMap(map, x, y, angle) {
//		g = -angle*(Math.PI/180);
//		r = 4;
//		var zoom = map.getZoom()+1;
//		d = ll4Zoom[zoom];

//		ghline = new GPolyline([new GPoint(x, y), new GPoint( x-((d)*Math.sin(g)), y+((d)*Math.cos(g)) ) ], "#0000FF",r);
		var ghline = getLine(map, y, x, angle);
		map.addOverlay(ghline);
	}

//  compute the text showing the angle with the closest main direction
	function writeAngle(angle) {
		angle = (1.0*angle).toFixed(angleDecimals);
		if (angle == 0)
			angleStr = "North";
		else if (angle > 0 && angle < 45)
			angleStr = angle + " degrees from North (clockwise)";
		else if (angle == 45)
			angleStr = "North East";
		else if (angle > 45 && angle < 90)
			angleStr = (90-angle).toFixed(angleDecimals) + " degrees from East (counterclockwise)";
		else if (angle == 90)
			angleStr = "East";
		else if (angle > 90 && angle < 135)
			angleStr = (angle-90).toFixed(angleDecimals) + " degrees from East (clockwise)";
		else if (angle == 135)
			angleStr = "South East";
		else if (angle > 135 && angle < 180)
			angleStr = (180-angle).toFixed(angleDecimals) + " degrees from South (counterclockwise)";
		else if (angle == 180)
			angleStr = "South";
		else if (angle > 180 && angle < 225)
			angleStr = (angle-180).toFixed(angleDecimals) + " degrees from South (clockwise)";
		else if (angle == 225)
			angleStr = "South West";
		else if (angle > 225 && angle < 270)
			angleStr = (270-angle).toFixed(angleDecimals) + " degrees from West (counterclockwise)";
		else if (angle == 270)
			angleStr = "West";
		else if (angle > 270 && angle < 315)
			angleStr = (angle-270).toFixed(angleDecimals) + " degrees from West (clockwise)";
		else if (angle == 315)
			angleStr = "North West";
		else if (angle > 315 && angle < 360)
			angleStr = (360-angle).toFixed(angleDecimals) + " degrees from North (counterclockwise)";
	}

	function showGheblehOnMap(map, cmps) {
		map.clearOverlays();
		dir = getDirection(Home, Mecca);
		var qiblaDir = -getDirection_new(Home.lat(), Home.lng(), Mecca.lat(), Mecca.lng());
		drawOnMap(map, Home.lng(), Home.lat(), qiblaDir);
		map.addOverlay(cmps);
		writeAngle(dir);
		document.setAddrFrm.angleTxt.value = angleStr;
	}

    function load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		geocoder = new GClientGeocoder();
		InitHome();
        map.setCenter(Home, 10);
		map.addControl(new TextualZoomControl());
		map.addControl(new GSmallZoomControl());
//		map.addControl(new GMapTypeControl());


		// Create our "tiny" marker icon
		var icon = new GIcon();
//		icon.image = "images/compass1.gif";
		icon.image = "gebedstijden/images/home.png";
		icon.iconSize = new GSize(40, 40);
		icon.iconAnchor = new GPoint(20, 20);

//		icon.image = "CompassBig.png";
//		icon.iconSize = new GSize(216, 216);
//		icon.iconAnchor = new GPoint(108, 108);
		Compass = new GMarker(Home, {icon: icon, draggable:true});

		GEvent.addListener(Compass, "dragstart", function() {
			map.removeOverlay(ghline);
		});

		GEvent.addListener(Compass, "dragend", function() {
			Home = Compass.getPoint();
			showGheblehOnMap(map, Compass);
		});

		GEvent.addListener(map, "moveend", function() {
			showGheblehOnMap(map, Compass);
		});


		GEvent.addListener(map, "zoomend", function() {
//			Home = map.getCenter();
//			Compass.setPoint(Home);
			showGheblehOnMap(map, Compass);
		});

		GEvent.addListener(map, "click", function(marker, point) {
			Home = point;
			Compass.setPoint(point);
			map.panTo(point);
			showGheblehOnMap(map, Compass);
		});

		showGheblehOnMap(map, Compass);
      }
    }

//---------------------------------------------------------
/* 
New drawing functions
By: Hamid Zarrabi-Zadeh

These fixes a critical bug in showing qibla direction 
in the above-mentioned two web-sites (Qibla direction shown
in these two web-sites was off by 0 to 12 degrees, as of 
September 15, 2007).

*/
//------------------------- Map Functions -----------------------------

// create a direction line
function getLine(map, lat, lng, angle)
{
	var factor = 8;
	var zoom = map.getZoom();
	var dLng = factor/ Math.pow(2, zoom- 7);
	if (zoom < 7) dLng = factor;

	dLng = dLng* Math.sin(dtr(angle));

	var from = new GPoint(lng, lat);
	var lat2 = getLat(lat, angle, dLng)
	var to = new GPoint(lng+ dLng, lat2);
	if (Math.abs(dLng) > Math.abs(lng- Mecca.lng()))
		to = new GPoint(Mecca.lng(), Mecca.lat());

	var line = new GPolyline([ from, to ], "#000033", 4);
	return line;
}

//-------------------------- Calculating Functions -----------------------


// find the direction
function getDirection_new(lat1, lng1, lat2, lng2) 
{
	var dLng = lng1- lng2;
	return rtd(getDirectionRad(dtr(lat1), dtr(lat2), dtr(dLng)));
}

function getDirectionRad(lat1, lat2, dLng) 
{
	return Math.atan2(Math.sin(dLng), Math.cos(lat1)* Math.tan(lat2)- Math.sin(lat1)* Math.cos(dLng));
}


// find lat2 for a given direction
function getLat(lat1, angle, dLng) 
{
	return rtd(getLatRad(dtr(lat1), dtr(angle), dtr(dLng)));
}

function getLatRad(lat1, angle, dLng) 
{
	return Math.atan((Math.sin(dLng)+ Math.tan(angle)* Math.sin(lat1)* Math.cos(dLng))/ (Math.tan(angle)* Math.cos(lat1)));
}


//-------------------------- Angle Unit Conversion -----------------------


// degree to radian
function dtr(d)
{
    return (d* Math.PI)/ 180.0;
}

// radian to degree
function rtd(r)
{
    return (r* 180.0)/ Math.PI;
}
