var specials = [-9.5, -3.5, 3.5, 4.5, 5.5, 5.75, 6.5, 8.75, 9.5, 10.5, 11.5, 12.75];

function setup() {
    fillTimeZones();
    
    document.getElementById("LocationInput").value = "Home";
    document.getElementById("TimeZone").value = -(new Date().getTimezoneOffset()) / 60;
    document.getElementById("LatInput").value = 0;
    document.getElementById("LongInput").value = -new Date().getTimezoneOffset() / 12 / 60 * 180;

    document.getElementById("LocationInput").onchange = codeUpdate;
    document.getElementById("TimeZone").onchange = codeUpdate;
    document.getElementById("LatInput").onchange = codeUpdate;
    document.getElementById("LongInput").onchange = codeUpdate;

    document.getElementById("BackgroundInput").onchange = codeUpdate;
    
    parseParameters();
    
    setupMap(document.getElementById("LatInput").value, document.getElementById("LongInput").value);
    codeUpdate();
}

function fillTimeZones() {
  var select = document.getElementById("TimeZone");
  for (var i = -12; i < 12; i++) {
  	var option = document.createElement("option");
  	option.value = i;
  	if (i < 0) {
  	  option.innerHTML = "GMT " + i + ":00";
  	}
  	else {
  	  option.innerHTML = "GMT +" + i + ":00";  	  
  	}
  	select.appendChild(option);  
  }
  for (var i = specials.length - 1; i >= 0; i--) {
  	var option = document.createElement("option");
  	var value = specials[i];
  	option.value = value;
  	var min = Math.abs(parseInt((value - parseInt(value)) * 60));
  	if (value < 0) {
  	  option.innerHTML = "GMT " + parseInt(value) + ":" + min;
  	}
  	else {
  	  option.innerHTML = "GMT +" + parseInt(value) + ":" + min;  	  
  	}
  	var pre = select.options[13 + parseInt(value) + 1];
  	select.add(option, pre);    	
  }
}
    
function setupMap(lat, lng) {
  if (GBrowserIsCompatible()) {
     map = new GMap2(document.getElementById("Map"));
     map.setCenter(new GLatLng(lat, lng), 1);
     map.addControl(new GSmallMapControl());
     map.addControl(new GMapTypeControl());
     map.addControl(new GOverviewMapControl());
     var opts = new Object();
     opts.title = "Current Location";
     marker = new GMarker(new GLatLng(lat, lng), opts);
     map.addOverlay(marker);
     geocoder = new GClientGeocoder();
     
     GEvent.addListener(map, "click", function(ignored, point) {
       document.getElementById("LatInput").value = point.lat();
       document.getElementById("LongInput").value = point.lng();
       marker.setPoint(point);
       codeUpdate();
     });
     
     document.getElementById("MapSearchBtn").onclick = mapSearch;
     document.getElementById("MapSearch").onchange = mapSearch;
     document.getElementById("LatInput").onchange = mapUpdate;
     document.getElementById("LongInput").onchange = mapUpdate;
  }  
}

function mapSearch() {
  var address = document.getElementById("MapSearch").value;
  geocoder.getLatLng(address, function(point) {
    if (!point) {
      alert(address + " not found");
    } else {
      map.setCenter(point, map.getZoom());
      document.getElementById("LatInput").value = point.lat();
      document.getElementById("LongInput").value = point.lng();
      marker.setPoint(point);
    }
  });  
}

function mapUpdate() {
  var obj = parseLatLong(document.getElementById("LatInput"), document.getElementById("LongInput"), marker.getPoint().lat(), marker.getPoint().lng());
  marker.setPoint(new GLatLng(obj.cityLat, obj.cityLong));
  map.setCenter(new GLatLng(obj.cityLat, obj.cityLong), map.getZoom());
  codeUpdate();
}

function parseLatLong(latInput, lngInput, cityLat, cityLong) {
  var obj = new Object();
  try {
    var lat = parseFloat(latInput.value);
    if (lat > -90 && lat < 90) {
      obj.cityLat = lat;
      //widget.setPreferenceForKey(cityLat, widget.identifier + "-lat");
    }
  }
  catch (e) {
    latInput.value = cityLat;
    obj.cityLat = cityLat;
  }  
  try {
    var lng = parseFloat(lngInput.value);
    if (lng > -180 && lng < 180) {
      obj.cityLong = lng;
      //widget.setPreferenceForKey(cityLong, widget.identifier + "-long");
    }
  }
  catch (e) {
    lngInput.value = cityLong;    
    obj.cityLong = cityLong;
  }
  return obj;  
}

function parseParameters() {
  try {
    var search = location.search;
    if (search != null && search.length > 0) {
      var city = getParameter(search, "city", null);
      if (city != null) {
        var timeZone = parseFloat(getParameter(search, "timeZone", null));
        if (timeZone != null) {
          var lat = parseFloat(getParameter(search, "lat", null));
          if (lat != null) {
            var lng = parseFloat(getParameter(search, "long", null));
            if (lng != null) {
              document.getElementById("LocationInput").value = city;
              document.getElementById("TimeZone").value = timeZone;
              var dst = getParameter(search, "dst", "false") == "true";
              document.getElementById("DstInput").checked = dst;
              document.getElementById("LatInput").value = lat;
              document.getElementById("LongInput").value = lng;
            }
          }
        }
      }
    }
  }
  catch (e) {
    //alert("Failed to parse URL parameters: " + e);
  }
}

function getParameter(src, key, defaultValue) {
  if (src.indexOf("&amp;") >= 0) {
    src = src.replace(/\&amp\;/g, "&");
  }
  var index = src.indexOf("&" + key + "=");
  if (index < 0) {
    index = src.indexOf("?" + key + "=");
  }
  if (index >= 0) {
    var index2 = src.indexOf("&", index + 1);
    if (index2 >= 0) {
      return decode(src.substring(index + key.length + 2, index2));
    }
    return decode(src.substring(index + key.length + 2));
  }
  return defaultValue;   
}

function decode(value) {
  var result = decodeURIComponent(value);
  return result.replace(/(\+)/g, " ");
}

function codeUpdate() {
  var city = document.getElementById("LocationInput").value;
  var zone = document.getElementById("TimeZone").value;
  var dst = document.getElementById("DstInput").checked;
  var lat = document.getElementById("LatInput").value;
  var lng = document.getElementById("LongInput").value;
  var text = '<a href="http://www.worldclockr.com?city=' + encodeURIComponent(city) 
             + '&amp;timeZone=' + zone + '&amp;lat=' + lat 
             + '&amp;long=' + lng + '&amp;dst=' + dst + '">' + city + '</a>';
  document.getElementById("Code").value = text;
  
  var background = document.getElementById("BackgroundInput").value;           
  text = '<iframe src="http://www.worldclockr.com/external.html?city=' + encodeURIComponent(city) 
             + '&amp;timeZone=' + zone + '&amp;lat=' + lat 
             + '&amp;long=' + lng + '&amp;dst=' + dst + '&amp;background=' + encodeURIComponent(background)
             + '"  border="0" frameborder="0" width="322" '
             + 'height="130" scrolling="no"><a href="http://www.worldclockr.com">WorldClockr</a></iframe>';
  document.getElementById("CodeFrame").value = text;
  document.getElementById("Preview").innerHTML = text;
  
  text = 'http://www.widgetop.com?addWorldClock=' + encodeURIComponent(city) 
         + '&amp;timeZone=' + zone + '&amp;lat=' + lat + '&amp;long=' + lng + '&amp;dst=' + dst;
  document.getElementById("CodeWidgetop").value = '<a href="' + text + '">' + city + '</a>';
  document.getElementById("PreviewWidgetop").href = text;       
}
  