var FoodArena = FoodArena || {}

FoodArena.locationManager = (function ($) {
    "use strict";
	var currentCoordinates = 0;
	var currentZIP = 0;

    var getCurrentLocation = function () {
		navigator.geolocation.getCurrentPosition(onSuccess, onError);
		//console.log("coord:" + currentCoordinates);
    };
		var onSuccess = function(position) {
	 		currentCoordinates = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			//alert('Success');
			
			var currentCoordinates = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			//console.log('lat='+ position.coords.latitude+' long='+position.coords.longitude);
			FoodArena.locationManager.getZipByCoord(currentCoordinates);
		
		
			//console.log("coord3:" + currentCoordinates);
		  /*  alert('Latitude: '          + position.coords.latitude          + '\n' +
				  'Longitude: '         + position.coords.longitude         + '\n' +
				  'Altitude: '          + position.coords.altitude          + '\n' +
				  'Accuracy: '          + position.coords.accuracy          + '\n' +
				  'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
				  'Heading: '           + position.coords.heading           + '\n' +
				  'Speed: '             + position.coords.speed             + '\n' +
				  'Timestamp: '         + new Date(position.timestamp)      + '\n');
		*/
		};

// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

    var getCurrentCoordinates = function () {
		return currentCoordinates;
	}
	
    var getCurrentZIP = function () {
		return currentZIP;
	}
	
	
	//*********GEOCODING*************8


    var getZipByCoord = function (latlng) {
		//console.log("START");
		var zip1;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode ({
			'latLng': latlng
		}, function(results, status) {
			//console.log("STATUS:" + status);
			currentZIP = findZipInResult(results);
			//console.log("ZIP:" + currentZIP);
			//alert(currentZIP);
		});
		//console.log("FINISH");
		
	}
	
	var  findZipInResult = function (results) {
		//console.log("------------" + results.length);
		var result, component, output = "", property;
		for (result in  results) {
			//console.log("    --------" + result.length);
			for (component in  results[result]) {
				//console.log("        ----" + results[result][component]);
				if (results[result][component] + "" == 'postal_code') {
					var address = results[result].address_components;
					var zipcode = address[0].long_name;
					if (zipcode.length > 0) return zipcode;
				}
				
			}
			
		}
		//console.log("RESULT:" + output);
		
		return "zip not found";
	}
	
	function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}
	
    var init = function () {
        //locationsStorageKey = storageKey;
       // getLastLocations();
    };

    var pub = {
        init: init,
		getCurrentLocation:getCurrentLocation,
		getCurrentCoordinates:getCurrentCoordinates,
		getZipByCoord:getZipByCoord,
		getCurrentZIP:getCurrentZIP
        //locationsStorageKey: locationsStorageKey//,
       // getNotesList: getNotesList,
       // saveNote: saveNote,
       // deleteNote: deleteNote
    };

    return pub;

} (jQuery));