var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
var map;

function select(buttonId) {
  document.getElementById("hand_b").className="unselected";
  // document.getElementById("shape_b").className="unselected";
  document.getElementById("line_b").className="unselected";
  document.getElementById("placemark_b").className="unselected";
  document.getElementById(buttonId).className="selected";
}

function stopEditing() {
  select("hand_b");
}

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function getIcon(color) {
  var icon = new GIcon();
  icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
  icon.iconSize = new GSize(32, 32);
  icon.iconAnchor = new GPoint(15, 32);
  return icon;
}

function startShape() {
  select("shape_b");
  var color = getColor(false);
  var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);
  startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
    var cell = this;
    var area = polygon.getArea();
    cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
  }, color);
}

function startLine() {
  select("line_b");
  var color = getColor(false);
  var line = new GPolyline([], color);
  startDrawing(line, "Line " + (++lineCounter_), function() {
  }, color);
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}

                    function placeMarker() {
                      select("placemark_b");
                      var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
                        if (latlng) {
                          select("hand_b");
                          GEvent.removeListener(listener);
                          var color = getColor(true);
                          tmp_marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
                          $('#marker_dialog').dialog('open');
                        }
                      });
                    }

function updateMarker(marker, cells, opt_changeColor) {
  if (opt_changeColor) {
    var color = getColor(true);
    marker.setImage(getIcon(color).image);
    cells.color.style.backgroundColor = color;
  }
  var latlng = marker.getPoint();
  cells.desc.innerHTML = "(" + Math.round(latlng.y * 100) / 100 + ", " +
  Math.round(latlng.x * 100) / 100 + ")";
}

$(function() {
var title = $("#tmp_title"),
            description = $("#tmp_description")
            allFields = $([]).add(title).add(description),
            tips = $("#validateTips");

        function updateTips(t) {
            tips.text(t).effect("highlight",{},1500);
        }

        function checkLength(o,n,min,max) {

            if ( o.val().length > max || o.val().length < min ) {
                o.addClass('ui-state-error');
                updateTips("Length of " + n + " must be between "+min+" and "+max+".");
                return false;
            } else {
                return true;
            }

        }

        function checkRegexp(o,regexp,n) {

            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass('ui-state-error');
                updateTips(n);
                return false;
            } else {
                return true;
            }

        }

        $("#marker_dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 300,
            modal: true,
            buttons: {
                'Add marker': function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    // bValid = bValid && checkLength(,"username",3,16);

                    // bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    // bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
                    // bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");

                    if (bValid) {
                        $('').val(title.val());
                        $('').val(description.val());
                        map.addOverlay(tmp_marker);
                        $(this).dialog('close');
                    }
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
                allFields.val('').removeClass('ui-state-error');
                tmp_marker = null;
            }
        });
});

function setup_fancybox() {
    $('a.fancybox, a.fancybox_big').unbind('click');
    $('a.fancybox, a.fancybox_big').unbind('click.fb');
    $('a.fancybox').fancybox({
        hideOnContentClick: false,
        callbackOnClose: function() {
            top.location.hash = '';
        }
    });
    $('a.fancybox_big').fancybox({
        hideOnContentClick: false,
        frameHeight: 600,
        frameWidth: 800,
        callbackOnClose: function() {
            top.location.hash = '';
        }
    });
    $('a.fancybox, a.fancybox_big').bind('click.fb', function() {
        top.location.hash = this.href.replace(/http:\/\/[\w\.:]*/g, '').replace('?iframe', '');
    });
}
window.setup_fancybox = setup_fancybox

function initialize() {
    if (GBrowserIsCompatible() && document.getElementById("map_canvas")) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(59.939039, 30.315785), 13);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.clearOverlays();
    }
    setup_fancybox();
    
    if ($.cookie('waiter_seen') != '1') {
        var el = $('<a href="#wait"></a>');
        el.fancybox({
            showCloseButton: false,
            hideOnOverlayClick: false,
            hideOnContentClick: false,
            callbackOnShow: function() {
                $('#fancy_div a').click(function() {
                    $.cookie('waiter_seen', '1', {expires: 365});
                    $.fn.fancybox.close();
                });
            }
        })
        el.trigger('click.fb');
    }
    
    if (top.location.hash) {
         var a = top.location.hash.substring(1) + '?iframe';
         $('a[href$='+a+']').trigger('click.fb');
    }
    
    if (window.route_url) {
        kml = new GGeoXml(window.route_url);
        map.setCenter(window.route_center, map.getBoundsZoomLevel(window.route_bounds));
        
        map.addOverlay(kml);
        GEvent.addListener(kml, "load", function() {
            this.show();
            // this.fd[0] is our polyline
            // this.fd[0].enableEditing();
        });
    }
    
    if (window.locations) {
        var bounds = new GLatLngBounds( )
        for (id in window.locations) {
            l = window.locations[id];
            marker = new GMarker(l.latlng);
            GEvent.addListener(marker, "click", function() {
                this.openInfoWindowHtml(l.title+" <a href='"+l.owner.url+"'>"+l.owner.name+"</a> ("+l.updated+")")
            });
            bounds.extend(l.latlng);
            map.addOverlay(marker);
        }
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }
}
