if (!window.Dartmoor) {
  window.Dartmoor = {
    newsList: [],
    side_bar_link: [],
    gmarkers: [],
    htmls: [],
	to_htmls: [],
	from_htmls: [],
    map: [],
    gdir: []
  }
}

$.extend(window.Dartmoor, {
  init: function () {

    var $teaserContainer = $(".teaser_block .teaser"),
        timeout = 0,
        closetimer = 0,
        ddmenuitem = 0;

    initiateSlideshow();
    fixLastLiWidth();

    $('#dropdown > li').bind('mouseover', dropdown_open);
    $('#dropdown > li').bind('mouseout',  dropdown_timer);

    function dropdown_open() {
      dropdown_canceltimer();
      dropdown_close();
	  ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');}

    function dropdown_close(){
      if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
    }

    function dropdown_timer() {
      closetimer = window.setTimeout(dropdown_close, timeout);
    }

    function dropdown_canceltimer() {
      if(closetimer) {
        window.clearTimeout(closetimer);
		closetimer = null;}
    }

	function initiateSlideshow() {
	  $("img:gt(0)", $teaserContainer).hide();
      setInterval(function(){
        $(":first-child", $teaserContainer).fadeOut()
         .next('img').fadeIn()
         .end().appendTo($teaserContainer)},
        5000);
	}

    function fixLastLiWidth(){
      var $lastLi = $("#dropdown > li.last"),
          $pageContainer = $(".page_container"),
          desiredWidth = $pageContainer.width() - ($lastLi.prev().offset().left + $lastLi.prev().width() - $pageContainer.offset().left + 3);
          $lastLi.css("width",desiredWidth);
    }

    jQuery.validator.setDefaults({
      success: "valid"
    });

    /*Inquiry form validation rules*/
    $("#inquiry_form").validate({
   	  rules: {
        name: "required",
        phone: "required",
        email: {
          required: true,
          email: true
        }        
      },

      messages: {
        name: "Please enter your name.",
        email: "Please enter your email address.",
        phone: "Please enter your phone number."
      },

      submitHandler: function(form) {
        $.ajax({
          url: "/sendInquiry.html",
          type: "POST",
          data: ({
            salutation: form.salutation.value,
            name: form.name.value,
            phone: form.phone.value,
            phone_type: form.phone_type.value,
            alternate_phone: form.alternate_phone.value,
            alternate_phone_type: form.alternate_phone_type.value,
        	email: form.email.value,
        	comments: form.comments.value
          }),

          success: function(response) {
            alert("Your inquiry has been sent. Thank you.");
          },

          error: function(response) {
            alert(response.responseText);
          }
        });
      }
    });

    $("a.news_read_more").click(function(event){
      $("#dartmoor_news_" + this.id.split("news_id_")[1]).dialog({ modal: true, width: 500 });
	  event.preventDefault();
    });

  },

  addNews: function(newsId, newsBody) {
	  var self = this;
	  self.newsList[newsId] = newsBody;
  },

  myclick: function(i) {
    this.gmarkers[i].openInfoWindowHtml(this.htmls[i]);
  },

  tohere: function(i) {
    this.gmarkers[i].openInfoWindowHtml(this.to_htmls[i]);
  },

  fromhere: function(i) {
    this.gmarkers[i].openInfoWindowHtml(this.from_htmls[i]);
  },

  getDirections: function() {
      var opts = {},
	      saddr = document.getElementById("saddr").value,
          daddr = document.getElementById("daddr").value;

	  if (document.getElementById("walk").checked) {
        opts.travelMode = G_TRAVEL_MODE_WALKING;
      }
      if (document.getElementById("highways").checked) {
        opts.avoidHighways = true;
      }
      this.gdir.load("from: "+saddr+" to: "+daddr, opts);
   },

   createMarker: function(point,name,html,image) {
     var self = this,
         marker = new GMarker(point),
	      i = self.gmarkers.length;

      self.to_htmls[i] = html + '<br />Directions: <b>To here<\/b> - <a href="javascript:Dartmoor.fromhere(' + i + ')">From here<\/a>' +
           '<br />Start address:<form action="javascript:Dartmoor.getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br />' +
           '<INPUT value="Get Directions" TYPE="SUBMIT"><br />' +
           'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
           '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
           '"/>';
      self.from_htmls[i] = html + '<br />Directions: <a href="javascript:Dartmoor.tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
           '<br />End address:<form action="javascript:Dartmoor.getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br />' +
           '<INPUT value="Get Directions" TYPE="SUBMIT"><br />' +
           'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
           '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
           '"/>';
      html = html + '<br />Directions: <a href="javascript:Dartmoor.tohere('+i+')">To here<\/a> - <a href="javascript:Dartmoor.fromhere('+i+')">From here<\/a>';

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      self.gmarkers.push(marker);
      self.htmls[i] = html;
      self.side_bar_link += '<a href="javascript:Dartmoor.myclick(' + i + ')">' + name;
	  self.side_bar_link += "<img alt=\""+name+"\" src=\""+image+"\" /><\/a>";
      return marker;
    },

  initGoogleMaps: function(){
    var self = this,
		request = GXmlHttp.create(),
		xmlDoc,markers,lat,lng,point,html,label,image,marker;

    self.map = new GMap2(document.getElementById("map"));
    self.gdir = new GDirections(self.map, document.getElementById("directions"));

    self.map.addControl(new GLargeMapControl());
    self.map.addControl(new GMapTypeControl());
    self.map.setCenter(new GLatLng(47.622327,-122.160941), 10);

	request.open("GET", "/xml/markers.xml", true);
    request.onreadystatechange = function() {
      if (request.readyState == 4) {
        xmlDoc = GXml.parse(request.responseText);
        markers = xmlDoc.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
          lat = parseFloat(markers[i].getAttribute("lat"));
          lng = parseFloat(markers[i].getAttribute("lng"));
          point = new GLatLng(lat,lng);
          html = markers[i].getAttribute("html");
          label = markers[i].getAttribute("label");
		  image = markers[i].getAttribute("image");
          marker = self.createMarker(point,label,html,image);
          self.map.addOverlay(marker);
        }
        document.getElementById("side_bar").innerHTML = self.side_bar_link;
      }
    }
	request.send(null);

  }
});