//alert("JS runs!");
var isAndroid = navigator.userAgent.match(/android/i);
var isBlackberry = navigator.userAgent.match(/blackberry/i);
var foundLocations = [ ];
var geo_error;
var geo_success;
var holdForStableLocation;
var startLocationCountdown;
var locationStable;
var mobile_init;
var reverse_geocode;
var zipCodeFail;
var zipCodeSuccess;
var sendMsg;
var show_locate_button;
var bindEvent;
var stableLocationCountdown;


var geo_position = function() {
    if (geo_position_js.init()) {
        var msg = "Attempting to determine location...";
        sendMsg(msg);
        geo_position_js.getCurrentPosition(geo_success, geo_error, { enableHighAccuracy: true });

    } else {
        alert("Your browser does not support geolocation?");
    }
};

var geo_error = function(e) {
    var msg = "Geolocation error! Could not find you.";
    sendMsg(msg);
};

var geo_success = function(p) {
    var msg = "Found you at lat,lng ("+p.coords.latitude+","+p.coords.longitude+").";
    //sendMsg(msg);
    foundLocations.push(p);
    holdForStableLocation();
};

var holdForStableLocation = function() {
          locationStable();
};

var startLocationCountdown = function() {
    if (typeof stableLocationCountdown != "undefined") {
        clearTimeout(stableLocationCountdown);
    }
    stableLocationCountdown = setTimeout(function(){ 
        locationStable();
    }, 6000);
};

var locationStable = function() {
    if (typeof stableLocationCountdown != "undefined") {
        clearTimeout(stableLocationCountdown);
    }


    var loc = foundLocations.pop();
    reverse_geocode(loc);
};

var mobile_init = function() {
    // quit if this function has already been called
    if (arguments.callee.done) { return; }

    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;

    //alert("mobile init runs...");
    // do stuff
    if (document.getElementById && document.getElementById("btn_find_location")) {
        var button = document.getElementById("btn_find_location");
        //button.addEventListener("click", geo_position, false);
        bindEvent({ element: button, action: "click", handler: geo_position, bubble: false });
        
    }
    if (geo_position_js.init()) {
        show_locate_button();
    }
};

/* Reverse Geocode via Google Maps API       *
 * @position: latitude / longitude in object *
 * @outputs Zip Code or error message        */
var geocodeActive = false;
var geocoder = new google.maps.Geocoder();
var reverse_geocode = function(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    var latlng = new google.maps.LatLng(lat,lng);
    var msg;
    if (geocoder && !geocodeActive) {
        geocodeActive = true;
        geocoder.geocode({'latLng': latlng}, function(results, status) {
						console.log("Handling geocoder response")
            //msg = "handling geocoder response...";
            //sendMsg(msg);
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    console.log("Reverse Geocode success: %o",results[0]);
                    //msg = "geocode success, does it have Zip?";
                    //sendMsg(msg);
                    var comps = results[0].address_components;
                    var zip = false;
                    for (var i=0, j=comps.length; i<j; i++) {
                        if (comps[i].types[0] === "postal_code") {
                            zip = comps[i].long_name;
                            zipCodeSuccess(zip);
                        }
                    }
                    if (!zip) {
                        zipCodeFail();
                    }
                }
            } else {
                msg = "Geocoder zip lookup failed due to: " + status;
                sendMsg(msg);
            }
            geocodeActive = false;
        });
    }
};

var zipCodeFail = function() {
    var msg = "Could not determine precise location. Please enter a zip code or try again.";
    sendMsg(msg);
};

var zipCodeSuccess = function(zip) {
      //var msg = "Location with Zip Code determined!";
      //sendMsg(msg);

      // populate the text input with zip code
      var zipEl = document.getElementById("zipcode_mobile_stores");
      if (zipEl) {
          zipEl.value = zip;
      }

      // submit the form
      var form = document.getElementById("form_mobile_stores");
      if (form) {
          form.submit();
      }
};

var sendMsg = function(msg) {
    var messageEl = document.getElementById("message");
    /* concatenate w/ previous output, for "stacked" debugging
    var next = messageEl.innerHTML;
    next += "<br />" + msg;
    messageEl.innerHTML = next;
    */
    messageEl.innerHTML = msg;
};

var show_locate_button = function() {
    var btn = document.getElementById("btn_find_location");
    if (btn) {
        btn.style.display = "";
    }
};

/* event binding */
var bindEvent = function(options) {
    // W3C browsers
    if (options.element.addEventListener) {
        options.element.addEventListener(options.action, options.handler, options.bubble);
    // IE event model
    } else if (options.element.attachEvent) {
        options.element.attachEvent("on"+options.action, options.handler);
    // "traditional" fallback
    } else {
        switch(options.action) {
            case "click":
                options.element.onclick = options.handler;
                break;
            case "change":
                options.element.onchange = options.handler;
                break;
            case "mouseover":
                options.element.onmouseover = options.handler;
                break;
            case "mouseout":
                options.element.onmouseout = options.handler;
                break;
        }
    }
};
/* DOM:loaded in 3 parts, using method by Dean Edwards/Matthias Miller/John Resig
 * http://dean.edwards.name/weblog/2006/06/again/ */

// 1. for W3C browsers: Mozilla, Safari, Chrome and Opera 9 
if (document.addEventListener) {
    //alert("detect Mozilla or Opera browser!");
    document.addEventListener("DOMContentLoaded", mobile_init, false);
}


// 3. For Safari / Chrome
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  //alert("detect WebKit browser!");
  var _timer = setInterval(function() {
      if (/loaded|complete/.test(document.readyState)) {
          clearInterval(_timer);
          mobile_init(); // call the onload handler
      }
  }, 10);
}

// 4. for other browsers
window.onload = mobile_init;

