if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() { } }; 

//for register form
function disableEnterKey(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}

/* Main Page Loading Code */

  var currentPage = '';
  var registerForm;
  Event.observe(window,"load", function() {
    load(location.hash.substring(1));
    registerForm = new RobotForm("registerForm", {submit_btn: "register_btn", onSubmit: function() {}, onSuccess:function() {alert("Thank you for registering")}});
  });
  
  function getHash() {
    return location.hash.substring(1) ;
  }
  
  function checkHash() {
    var page = location.hash.substring(1);
    if (currentPage != page) {
      load(page); 
      
    }
    else {
      setTimeout("checkHash()",200); 
    }
  }

  var newContent;

  var contentReady;
  var outroReady;
  var imagesReady;
  
  var next_p;
  var prev_p;
  
  var imageCache;
  
  var loadCount = 0;
  var firstLoad = true;
  
  function play_sound() {
    Sound.play("/audio/BeachLife-full.mp3");
    setTimeout("play_sound()", 159000);
  }
  
  function preloadImages(page, path) {
    // if contentReady is set to true, call new_intro, otherwise, defer to outro.
    //clear cache array to free up memory, rely on browser for future gets
    delete imageCache;
    imageCache = new Array();
    //get list of images needed to load
    var imageList = Pages.get(page).images;
    if (typeof imageList == "undefined") {
      imagesReady = true;
    }
    else 
    {
      loadCount = imageList.length;
      if (loadCount ==0) {
        imagesReady = true;
      }
      else {
        var i = 0;
        imageList.each(function (image) {
          imageCache[i] = new Image();
          imageCache[i].onload = imageLoaded.bind(i);
          //console.log("Loading: " + "/grouped-images" + path + "/" + image);
          imageCache[i].src= "/grouped-images" + path + "/" + image;
          i++;
          });
        }
      }

  }
  
  function imageLoaded() {
    var image = this;
    loadCount--;
    if (loadCount <= 0) {
      //give it a beat
      imagesReady = true;
      updateContent(next_p);        
      setTimeout("imageLoadingComplete()", 500);
    }
  }
 
  function imageLoadingComplete() {

  }
  
  function load(page) {
  
    var uri = page;
    if (page == '') {
      uri = '/home';
    }  
    prev_p = Pages.get(currentPage);
    next_p = Pages.get(page);
    if (typeof(Pages.get(page)) == "undefined") {
      //console.log(page);
      try {
      pageTracker._trackPageview(uri);
      pageTracker2._trackPageview(uri);
      } catch(err) {};
      alert("Page not ready yet...");
      window.location = "#" + currentPage;
    }
    else {
      contentReady = false;
      imagesReady = false;
      outroReady = false;
      //start loading content for new page, 
      preloadImages(page, uri);
      
      new Ajax.Request(uri + "/index.php", {
        method:"GET",
        onSuccess: function(t){
          newContent=t.responseText;
          contentReady = true;
          //console.log("Page Content loaded");
          updateContent(next_p);
          if (firstLoad) {
            play_sound();
          }
        },
        onFailure: function(t){
          newContent= "<h1>Error</h1>";
          contentReady = true;
          updateContent(next_p);
        }
      });
      if (firstLoad) {
        outroReady = true;
      }
      else {
        if (typeof prev_p.cleanUp == "function") {
          prev_p.cleanUp();
        }
        if (prev_p.group == next_p.group && prev_p.group != "none") {
          prev_p.outro(next_p);  
        }
        else {
          prev_p.major_outro(next_p);  
        }
      }
      currentPage = page; 
    }
    setTimeout("checkHash()",200); 
 }
function updateContent(page_vars) {
    if (outroReady && contentReady && imagesReady) {
      $("box_2_content").update(newContent);
     
      if (prev_p.group == next_p.group && prev_p.group != "none" && firstLoad == false) {
        page_vars.intro(page_vars);
      }
      else {
         page_vars.major_intro(page_vars);
      }      

      firstLoad = false;
  }
}


var ss;

var Pages = new Hash();

//home
Pages.set('', {
  bg: '/grouped-images/home/caspi-splash.jpg',
  group: 'home',
  tallpage:"true",
  intro: home_intro,
  outro: home_outro,
  major_intro: home_major_intro,
  major_outro: home_major_outro,
  afterFinish: function() {
    ss = new SlideShow("home-ss", {
      initialState: "play",
      interval:4500,
      transitionDuration:1.5
      });
  },
  cleanUp: function() {
    ss.pause();
  },
  images: new Array("intl_home2.jpg", "home-A-01.jpg", "home-A-02.jpg", "home-A-03.jpg", "home-A-04.jpg", "home-A-05.jpg", "home-A-06.jpg",  "genesis-logo-intl-home.png","heradura-logo-intl-home.png", "intl-home-current-projects.png","intl-home-logo-small.png")
});


Pages.set('/brokerage', {
  bg: '/grouped-images/home/caspi-splash.jpg',
  group: 'home',
  intro: home_intro,
  outro: home_outro,
  major_intro: home_major_intro,
  major_outro: home_major_outro,
  images: new Array()
});

Pages.set('/about', {
  bg: '/grouped-images/home/caspi-splash.jpg',
  group: 'home',
  intro: home_intro,
  outro: home_outro,
  major_intro: home_major_intro,
  major_outro: home_major_outro,
  images: new Array()
});

Pages.set('/press', {
  bg: '/grouped-images/home/caspi-splash.jpg',
  group: 'home',
  intro: home_intro,
  outro: home_outro,
  major_intro: home_major_intro,
  major_outro: home_major_outro,
  images: new Array()
});

var contactForm;
Pages.set('/contact', {
  bg: '/grouped-images/home/caspi-splash.jpg',
  group: 'home',
  intro: home_intro,
  outro: home_outro,
  major_intro: home_major_intro,
  major_outro: home_major_outro,
  images: new Array(),
  afterFinish: function() {
    //console.log("initializing contact form");
    contactForm = new RobotForm("contactForm");
  }
});

Pages.set('/genesis/overview', {
  nav_index: 0,
  group: 'none',
  bg: "/grouped-images/genesis/overview/bg-overview.jpg",
  headerBg: "#1a5eb3",
  headerOpacity: .7,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: overview_major_intro,
  major_outro: genesis_major_outro,
  images: new Array("bg-overview.jpg","building.jpg","escape.jpg","exclusive.jpg","explore.jpg","overview-a-place-like.png","overview-intro-text-border.png","overview-tab.png","sanctuary.jpg"),
  cleanUp: function() {
    ss.pause();
  }
});

Pages.set('/genesis/location', {
  nav_index: 1,
  group: 'none',
  bg: "/grouped-images/genesis/location/bg-location.jpg",
  headerBg: "#1c4f00",
  headerOpacity: .6,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images: new Array("bg-location.jpg")
});

Pages.set('/genesis/amenities', {
  nav_index: 2,
  group: 'amenities',
  bg: "/grouped-images/genesis/amenities/bg-amenities.jpg",
  headerBg: "#297fcf",
  headerOpacity: .88,
  afterFinish: doMove,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images: new Array("bg-amenities.jpg")
  
});

Pages.set('/genesis/amenities/interiors', {
  nav_index: 2,
  group: 'amenities2',
  bg: "/grouped-images/genesis/amenities/bg-amenities.jpg",
  headerBg: "#297fcf",
  headerOpacity: .88,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images: new Array("interiors-01.jpg", "interiors-02.jpg","interiors-03.jpg","interiors-04.jpg","interiors-05.jpg","interiors-06.jpg"),
  afterFinish: function() {
    ss = new SlideShow("amenities-ss", {
      initialState: "play",
      interval:4500,
      transitionDuration:1.5
      });
  },
  cleanUp: function() {
    ss.pause();
  }

});

Pages.set('/genesis/residences', {
  nav_index: 3,
  group: 'residences',
  bg: "/grouped-images/genesis/residences/bg-residences.jpg",
  images: new Array("bg-residences.jpg","main-bg.jpg"),
  afterFinish:init_residences,
  headerBg: "#68a8e6",
  headerOpacity: .88,
  intro: res_intro,
  outro: res_outro,
  major_intro: res_major_intro,
  major_outro: res_major_outro
});

Pages.set('/genesis/investment', {
  nav_index: 4,
  group: 'none',
  bg: "/grouped-images/genesis/investment/bg-investment.jpg",
  headerBg: "#071125",
  headerOpacity:.88,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  afterFinish: function() { current_id = "main" },
  images:new Array("bg-investment.jpg")
});

Pages.set('/genesis/chicago-title', {
  nav_index: 5,
  group: 'none',
  bg: "/grouped-images/genesis/chicago-title/bg-chicago-title.jpg",
  headerBg: "#000000",
  headerOpacity: 1.0,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images:new Array("bg-chicago-title.jpg")
});

var inquiryForm;

Pages.set('/genesis/inquiries', {
  nav_index: 6,
  group: 'none',
  bg: "/grouped-images/genesis/inquiries/bg-inquiries.jpg",
  headerBg: "#393029",
  headerOpacity:.88,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  afterFinish: function() {
    inquiryForm = new RobotForm("inquriyForm");
  },
  images:new Array("bg-inquiries.jpg")

});

Pages.set('/genesis/architect', {
  nav_index: 7,
  group: 'none',
  bg: "/grouped-images/genesis/architect/bg-architect.jpg",
  headerBg: "#2e5189",
  headerOpacity:.83,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images:new Array("bg-architect.jpg")
});

Pages.set('/genesis/photo-galleries', {
  nav_index: 8,
  group: 'none',
  bg: "/grouped-images/genesis/photo-galleries/bg-photo-galleries.jpg",
  headerBg: "#1a5eb3",
  headerOpacity: .7,
  intro: genesis_intro,
  outro: genesis_outro,
  major_intro: genesis_major_intro,
  major_outro: genesis_major_outro,
  images: new Array("bg-photo-galleries.jpg"),
  afterFinish: initLightViewLinks
});

var photolightwindow;
function initLightViewLinks() {
  
	myLightWindow = new lightwindow({
			classNames : {	
				standard : 'dynamic_lightwindow',
		    action : 'lightwindow_action'
	}});
}


function updateSideNav(nav_index) {
 $$(".side_nav li.current").invoke("removeClassName", "current");
 $$(".nav_item_bg")[nav_index+1].addClassName("current");
 $$(".nav_item_fg")[nav_index+1].addClassName("current");
}


  
function genesis_major_outro(page_vars) {
      if (! (typeof page_vars.nav_index == "undefined")) {
        updateSideNav(page_vars.nav_index);
      }
      new Effect.Appear("frame3", {duration: 1, afterFinish: function() {
      $("content_wrapper").hide();
      $("footer_container_wrapper").hide();

      $("bg").hide();
      new Effect.Fade("frame3", {duration: 1, queue: { position: 'end', scope:'transition' },
       afterFinish: function() {
          outroReady = true;
          updateContent(page_vars);
       }
      });
    }});
}


function home_intro(page_vars){
  set_inner_container(page_vars);
  new Effect.Fade($("frame3"), {duration:.75, queue: { position: 'end', scope:'transition'}, afterFinish: function() {
        $("frame3").setStyle({height:"800px"});
        if (typeof page_vars.afterFinish != "undefined") {
          page_vars.afterFinish();
        }        
  } });
}

function home_outro(page_vars) {
  $("frame3").setStyle({height:"680px"});
  new Effect.Appear($("frame3"), {delay: 0, duration:.75, queue: { position: 'end', scope:'transition'} ,
    afterFinish: function() {
       outroReady = true;
       updateContent(page_vars);
    }
  });
}



function genesis_intro(page_vars){
  set_inner_container(page_vars);
  new Effect.Appear($("box_2_content"), {duration:1, queue: { position: 'end', scope:'transition'}, afterFinish: function() {
      //$$(".right_nav").invoke("appear");
  } });
}

function genesis_outro(page_vars) {
  if (! (typeof page_vars.nav_index == "undefined")) {
    updateSideNav(page_vars.nav_index);
  }
  //$$(".right_nav").invoke("fade");
  new Effect.Fade($("box_2_content"), {delay: .5, duration:2, queue: { position: 'end', scope:'transition'} ,
    afterFinish: function() {
       outroReady = true;
       //console.log("outro ready");
       updateContent(page_vars);
    }
  });
}

function res_intro (page_vars) {
  //need to load sub-page content
  genesis_intro(page_vars);
}

function res_outro (page_vars) {
  //need to load sub-page content
  genesis_outro(page_vars);
}

function res_major_intro(page_vars){
  genesis_major_intro(page_vars); 
}

function res_major_outro (page_vars) {
  //need to load sub-page content
  genesis_major_outro(page_vars);
}



function overview_major_intro(page_vars) {
  
  $("bg").setStyle({backgroundImage:"url(" + page_vars.bg + ")"});
  $("header_container_bg").setStyle({backgroundColor:page_vars.headerBg});
  $("header_container_bg").setStyle({opacity:page_vars.headerOpacity});
  $("phone-black").show(); $("phone-white").hide();
  $("latin-america-footer").hide();
  $("box_1_content").show();
  $("header_container_wrapper").show();
  $("side_nav_fg").show();
  $("side_nav_fg").show();
  set_inner_container(page_vars);
  
  $("frame1").setStyle({backgroundImage:"url(/grouped-images/genesis/overview/overview-intro-text-border.png)"});

  $("frame3").setStyle({backgroundImage:"url(" + page_vars.bg + ")"});
  $("bg").setStyle({backgroundColor:"#FFFFFF"});

  /* footer styles */
  $("footer_container_bg").setOpacity(.8);
  $("footer_container_bg").setStyle({backgroundColor:"#FFFFFF"});
  $$("#footer li a").invoke("setStyle", {color:"#000000"});
  
  new Effect.Morph(document.body, {style:"background-color:#FFFFFF", queue: { position: 'end', scope:'transition' } });
  new Effect.Appear($("bg"), {duration:.5, queue: { position: 'end', scope:'transition'}, afterFinish: function()
    { $("frame3").show();
    }
  });

  new Effect.Appear($("frame1"), {duration:0, queue: { position: 'end', scope:'transition' }});  
  new Effect.Fade($("frame3"), {duration:.75, queue: { position: 'end', scope:'transition' }});  
  
  new Effect.Appear($("frame3"), {delay:.75, duration:.75, queue: { position: 'end', scope:'transition' }});    
  new Effect.Fade($("frame1"), {duration:0, queue: { position: 'end', scope:'transition' }});  
  
  new Effect.Appear($("frame3"), {delay:.2, duration:.75, queue: { position: 'end', scope:'transition' },
    afterFinish: function() {
      $("frame2").hide();
      $("footer_container_wrapper").show();
      $("content_wrapper").show();     
      new Effect.Fade($("frame3"), {delay:.75, duration:2, afterFinish: function() {
        ss = new SlideShow("overview-ss", {
          initialState: "play",
          interval:2500,
          transitionDuration:1.5,
          loop: false,
          afterFinish: function() {
            if (typeof page_vars.afterFinish != "undefined") {
              page_vars.afterFinish();
            }
          }
        });
      }});
    }
  });    
}


function genesis_major_intro(page_vars) {

  updateSideNav(page_vars.nav_index);
  $("bg").setStyle({backgroundImage:"url(" + page_vars.bg + ")"});
  $("frame3").setStyle({backgroundImage:"url(" + page_vars.bg + ")"}); 
  $("header_container_bg").setStyle({backgroundColor:page_vars.headerBg,opacity:page_vars.headerOpacity});

  $("phone-black").show(); $("phone-white").hide();
  $("latin-america-footer").hide();  
  $("box_1_content").show();
  $("header_container_wrapper").show();
  $("side_nav_fg").show();


  $("bg").setStyle({backgroundColor:"#FFFFFF"});
  /* footer styles */
  $("footer_container_bg").setOpacity(.8);
  $("footer_container_bg").setStyle({backgroundColor:"#FFFFFF"});
  $$("#footer li a").invoke("setStyle", {color:"#000000"});

  new Effect.Morph(document.body, {style:"background-color:#FFFFFF", queue: { position: 'end', scope:'transition' } });
  new Effect.Appear($("bg"), {duration:1, queue: { position: 'end', scope:'transition' }, 
    afterFinish: function() {

      $("frame3").show();
      $("content_wrapper").show();
      $("footer_container_wrapper").show();
    
    }});

  new Effect.Fade($("frame3"), {duration:1, queue: { position: 'end', scope:'transition' }, afterFinish: function() {
      if (typeof page_vars.afterFinish != "undefined") {
        page_vars.afterFinish();
      }
    }
  });

}



function home_major_intro(page_vars) {
    set_inner_container(page_vars);
    
    $("footer_container_bg").setOpacity(1);
    $("phone-black").hide(); $("phone-white").show();
    $("latin-america-footer").show();
    
    $("header_container_wrapper").hide();
    $("box_1_content").hide();
    $("side_nav_fg").hide();
    $("side_nav_fg").hide();
    $("frame1").setStyle({backgroundImage:"url(" + page_vars.bg + ")"});

    $("frame3").setStyle({backgroundImage:"url(/grouped-images/home/intl_home2.jpg)"});
    $("bg").setStyle({backgroundImage:"url(/grouped-images/home/intl_home2.jpg)"});
    /* footer styles */
    $("footer_container_bg").setOpacity(1);
    $("footer_container_bg").setStyle({backgroundColor:"#000000"});  
    $$("#footer li a").invoke("setStyle", {color:"#FFFFFF"});
    new Effect.Morph(document.body, {style:"background-color:#000000", afterFinish: function() { 
      new Effect.Appear("frame1", {duration:1.5, afterFinish:function() { 
        new Effect.Fade($("frame1"), {delay:1, duration:.5, afterFinish:function() { 
          //$("frame2").show();
          new Effect.Appear($("bg"), {delay:.5, duration:1, afterFinish: function() {  
            $("frame3").show();
            $("content_wrapper").show();
            $("footer_container_wrapper").show();          
            new Effect.Fade("frame3");  
            if (typeof page_vars.afterFinish != "undefined") {
              page_vars.afterFinish();
            }
          }});
        }});            
      }});    
    }});    
}

function home_major_outro(page_vars) {
      if (! (typeof page_vars.nav_index == "undefined")) {
        updateSideNav(page_vars.nav_index);
      }
      new Effect.Appear("frame3", {duration: .75, afterFinish: function() {
      $("content_wrapper").hide();
      $("footer_container_wrapper").hide();
      $("bg").hide();
      new Effect.Fade("frame3", {duration: .75, queue: { position: 'end', scope:'transition' },
       afterFinish: function() {
          outroReady = true;
          //console.log("outro ready");
          updateContent(page_vars);
       }
      });
    }});
  }


function  set_inner_container(page_vars) {
  if (typeof page_vars.tallpage == "undefined") {
    $$(".box2-content-container")[0].setStyle({height:"580px"});
    $("box_2_content").setStyle({height:"580px"});
    $("inner_wrapper").setStyle({top:"100px"});
    $$(".box2-background-container")[0].setStyle({height:"580px"});
    
  }
  else {
    $$(".box2-content-container")[0].setStyle({height:"680px"});
    $("box_2_content").setStyle({height:"680px"});
    $("inner_wrapper").setStyle({top:"0px"});
    $$(".box2-background-container")[0].setStyle({height:"680px"});

  }
}

function openTab(id, openTo) {
  new Effect.Move(id, {y:openTo, mode:'absolute'});
}

function closeTab(id) {
  new Effect.Move(id, {y:540, mode:'absolute'});
}

function toggleTab(id, openTo) {
  if ($(id).getStyle("top") == "540px") { //closed tab
    openTab(id, openTo);
  }
  else {
    closeTab(id);
  }
}

function doMove() {
  new Effect.Move("amenities-image", {transition:Effect.Transitions.linear, x:-(1666+2408*3), duration:180, afterFinish: function() {

 }});
}

/* location */
function showLocation(link, pane) {
  $$(".tab-nav a").each(function(e) {e.removeClassName("current")});
  $$(".location-pane").each(function(e) {e.hide()});
  $("tab-" + pane).show();
  link.addClassName("current");
}




var currentSN = -1;
function expandRightNav(index) {
  if (index == currentSN) {
    collapseRightNav(currentSN);
  }
  else { 
    collapseRightNav(currentSN);
    $$(".right_sub_nav")[index].show();
    $$(".right_nav>li")[index].addClassName("expanded");
    $$(".right_nav>li")[index].select("a")[0].setOpacity(.8);
    currentSN = index;
  }
}
function collapseRightNav() {
  if (currentSN != -1) {
    $$(".right_sub_nav")[currentSN].hide();
    $$(".right_nav>li")[currentSN].removeClassName("expanded");
    $$(".right_nav>li")[currentSN].select("a")[0].setOpacity(.5);
    currentSN = -1;
  }
}  
  
var currentUnit = "";


function showUnitPlans() {
  $(currentUnit + "-pane-2").show();
  $(currentUnit + "-pane-1").hide();

}

function showFloorPlans() {
  $(currentUnit + "-pane-1").show();
  $(currentUnit + "-pane-2").hide();

}



var highlighted_floor = "";
var floorResetTimeout;

/* Floor hover overs */

function floor_area_over() {
  var c = $w(this.className)[0];
  $("overlay-" + c).show();
  if ($("overlay-" + highlighted_floor)) {
    $("overlay-" + highlighted_floor).hide();
  }
  highlighted_floor = c;
  clearTimeout(floorResetTimeout);
}

function floor_area_out() {
  floorResetTimeout = setTimeout("floor_reset_overlay()",100);
}

function floor_reset_overlay() {
  $("overlay-" + highlighted_floor).hide();
  highlighted_floor = "";
}

function floor_area_click() {
  var currentOver = $w(this.className)[0];
  showFloor(currentOver);
}

function showFloor(floor) {
  clearPanel();
  if (floor == "floor-top") {
    showUnit("caspi-icon");
  }
  else {
    $(floor).show();
    openTab('tab-floorplans',66); 
  }  
}

/* floor plan overlays */

var highlighted_floorplan;
var floorplanResetTimeout;
function floorplan_area_over() {
  var c = $w(this.className)[0];
  //console.log(c);
  $(c).show();
  if ($(highlighted_floorplan)) {
    $( highlighted_floorplan).hide();
  }
  highlighted_floorplan = c;
  clearTimeout(floorplanResetTimeout);
}

function floorplan_area_out() {
  floorplanResetTimeout = setTimeout("floorplan_reset_overlay()",100);

}

function floorplan_area_click() {
  var currentOver = $w(this.className)[0].split("-");
  var unit = currentOver[2];
  if (typeof currentOver[3] != "undefined") {
    unit = unit + "-" + currentOver[3];
  }
  showUnit(unit);
}

function floorplan_reset_overlay() {
  $(highlighted_floorplan).hide();
  highlighted_floorplan = "";
}

function showUnit(unit) {
  clearPanel();
  openTab('tab-floorplans',66);
  //console.log("SHOW UNIT: " + unit);
  $("unit-" + unit).show();
}

function clearPanel() {
  $$(".unitplan").each(function(e){
    e.hide();
  });
  $$(".floorplan").each(function(e){
  e.hide();
});
}

function init_residences() {
  $$("#overlay-map area").each(function(e) {
    Event.observe(e, "mouseover", floor_area_over.bind(e));
    Event.observe(e, "mouseout", floor_area_out.bind(e));
    Event.observe(e, "click", floor_area_click.bind(e));
  });
  $$(".floorplan-map area").each(function(e) {
    Event.observe(e, "mouseover", floorplan_area_over.bind(e));
    Event.observe(e, "mouseout", floorplan_area_out.bind(e));
    Event.observe(e, "click", floorplan_area_click.bind(e));
  });
  initLightViewLinks();
}

var current_id;
function showSubSection(id) {
  if (typeof current_id == "undefined") {
    current_id = "main";
  }
  $(current_id).hide();
  $(id).show();
  current_id = id;
}

/* FORMS.js */

/*
SAMPLE USAGE:
var contactForm = new RobotForm("form")


<form id="contact_form" method="XHR" action="/robot/lib/handleform.php">

  <input type="text" name="first_name" class="required text"/>
  <input type="text" name="last_name" class="required text"/>
  <input type="text" name="zip" class="required numeric"/>
</form>

*/
var RobotForm = Class.create();

RobotForm.prototype = {
  initialize: function (form_id, options) {
    this.id = form_id;
    this.options = Object.extend({
      onSuccess: this.onSuccess,
      onSubmit: this.onSubmit,
      onFailure: this.onFailure,
      server_error_msg: "There was a server problem.",
      input_error_msg: "Please check the form for errors.",
      success_msg: "Thank you for contacting us.",
      posting_msg: "Submitting form...",
      submit_btn: "submit_btn",
      message_div: "message_div"
    }, options || {});
    //collect all form elements
    this.fields = $A($(this.id).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
            elements.push(Element.extend(child));
         return elements;
       });
    //register events
    Event.observe(this.options.submit_btn, "click", this.do_submit.bindAsEventListener(this));
  },
  validate: function() {
    var valid = true;
    for (var i = 0; i < this.fields.length; i++) {
      if (!this.validate_field(this.fields[i])) {
        valid = false;
      }
    }
    if (valid) {
      
    }
    else {
    
    }
    return valid;
  },
  onSubmit: function(obj) {
    $(obj.id).hide();
    $(obj.options.message_div).update(obj.options.posting_msg);
  },
  onSuccess: function() {
    $(this.options.message_div).update(this.options.success_msg);
  },
  onFailure: function() {
    $(this.options.error_message).show(this.options.success_msg);  
  },
  validate_field: function(f) {
    //get validation classes
    var classes = $w(f.className);
    var valid = true;
    for (var c=0; c < classes.length; c++) {
      if (typeof Validators[classes[c]] == "function") {
        if (!Validators[classes[c]](f)) {
          valid = false;
          break;
        }
      }
    }
    if (valid) {
      f.removeClassName("invalid");
    }
    else {
      f.addClassName("invalid");    
    }
    return valid;
  },
  do_submit: function() {
    if (this.validate()) {
      if ($(this.id).getAttribute("method").toUpperCase() == "POST") {
        $(this.id).submit();
      }
      else {
        this.options.onSubmit(this);
        new Ajax.Request($(this.id).getAttribute("action"), {
          postBody: $(this.id).serialize(),
          method:"POST",
          onSuccess: this.options.onSuccess.bind(this),
          onFailure: this.options.onFailure.bind(this)
       
        });
      }
    }
  } 
  
}

Validators = {
  isEmpty: function(f) {
    return ((f.value == null) || (f.value.length == 0));
  },
  verify: function(f) {
    var verifyField = $$("input[name=" + f.name + "-verify]")[0];
    if (f.value == verifyField.value) {
      verifyField.removeClassName("invalid");
      return true;
    }
    else {
      verifyField.addClassName("invalid");
      return false;
    }
  },
  required: function(f) {
    return !Validators.isEmpty(f);
  },
  name: function(f) {
    return Validators.isEmpty(f) ||  /^[a-zA-Z\'\s\-]+$/.test(f.value);  
  },
  alpha: function(f) {
    return Validators.isEmpty(f) ||  /^[a-zA-Z]+$/.test(f.value);  
  },
  alphanum: function(f) {
    return Validators.isEmpty(f) || !/\W/.test(f.value);
  },
  digits: function(f) {
    return Validators.isEmpty(f) || !/[^\d]/.test(f.value) ;
  },
  email: function(f) {
    return Validators.isEmpty(f) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(f.value);  
  },
  password: function(f) {
//    return Validators.isEmpty(f);  
  },
  email: function(f) {
    return Validators.isEmpty(f) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(f.value);  
  },
  phone: function(f) {
    return Validators.isEmpty(f) || /^[0-9\-\(\)]+$/.test(f.value);
  },
  us_phone: function(f) {
    return Validators.isEmpty(f) || /(\d{3}\-\d{3})\-(\d{4})$/.test(f.value);
  }

}

/* SLIDESHOW.JS */


var SlideShow = Class.create();

/* SLIDESHOW STUFF */
SlideShow.prototype = {
  /*
  slideshowElements is an array of elements used in the slideshow. The HTML must be set up properly prior to load.
  */
  initialize: function (containerID, options) {
    this.container = $(containerID);
    this.options = Object.extend({
      data: null,       /* optionally can pass image data as JSON. See docs for format + PHP code */

      captionId: null,  /* element where caption is displayed */
      positionId: null, /* element where position is displayed */
      jsonData: null,
      interval:5000,
      endshow: Prototype.emptyFunction(),
      initialState: "pause",  /* valid options play/pause */
      slider_track_id: null,  /* pass in ids corresponding to a properly set up slider track & handle.  slider.js from scriptaculous is required for this to work */
      slider_handle_id: null,
      groupAttribute: "group", 
      /*loading related */
			replaceImage	: "/images/blank.gif",					// Placeholder image to show instead of the image (best leave unchanged to this blank.gif!)
			loadingImage	: "/images/spinner.gif",				// Loading indicator
			onchange: Prototype.emptyFunction, //generic onchange function
			onplay: Prototype.emptyFunction, //generic onchange function
			onpause: Prototype.emptyFunction, //generic onchange function						
			onplaypause: Prototype.emptyFunction, //generic onchange function									
			TransitionOut: Effect.Fade,
			TransitionIn: Effect.Appear,
			transitionDuration: .5,
			loop: true,
			afterFinish: Prototype.emptyFunction()

    }, options || {});
    

    //console.log(start_index);
    this.loadQueue = new Array()    
    this.current_slide = -1;
    if (this.options.jsonData) {
     //build dom up out of json, and kick off loading...
 
      for (var i=0; i < parseInt(this.options.jsonData.length); i++) {
        var data = this.options.jsonData[i];
        var el = new Element('div', {'class': 'slide', 'style': 'display:none', 'index': i, 'caption': data.caption +"&nbsp;", 'group' : data.group});
        //this.loadQueue.unshift(i);
        this.container.insert(el);
      }
    }

    var hash = self.document.location.hash.substring(1);
    var start_index = 0;
    if (hash !== "") {
      var groups = $$('div['+ this.options.groupAttribute +'=' + hash + ']');
      //See if there's a client with the same name as hash    
      if (groups.length > 0) {
        start_index = parseInt(groups[0].getAttribute("index"));
      }
      else {
        start_index = 0;
      }
    }
    this.slides = this.container.immediateDescendants();
    
    //TODO: RE-ARRANGE QUEUE
    for (var i= start_index; i < parseInt(this.slides.length); i++) {
      this.loadQueue.unshift(i);
    }
    for (var i= 0; i < start_index; i++) {
      this.loadQueue.unshift(i);
    }
    
    if (this.options.jsonData) {
      this.loadImages();
    }
    this.container_height = this.container.getHeight();
    if ($(this.options.prevButton)){
      Event.observe(this.options.prevButton, "click", this.prev.bind(this));
    }
    if ($(this.options.nextButton)){
      Event.observe(this.options.nextButton, "click", this.next.bind(this));
    }
    if ($(this.options.playPause)){
      Event.observe(this.options.playPause, "click", this.playPause.bind(this));
    }
    this.bkeyhandler = this.keyhandler.bindAsEventListener(this);
    //Event.observe(document, 'keypress', this.bkeyhandler);
    

    if (this.slides.length > 0) {
      // init ImageLoading     
      //this.initLoader();
      this.state = this.options.initialState;
     
      if ( $(this.options.slider_track_id) != null && $(this.options.slider_handle_id) != null ) {
         this.initSlider(start_index); 
         this.hasSlider = true;
      }
      else {
        this.hasSlider = false; 
      };

      this.go_to(start_index, true);

    }
  },
  loadImages: function() {
    if (this.loadQueue.length > 0) {
      var i = this.loadQueue.pop();
      var img = this.options.jsonData[i];

      this.slides[i].insert(new Element("img", {'src': this.options.jsonData.basedir + img.subdir + "/" + img.filename}));

      var obj = this;
      setTimeout(function () {obj.loadImages()},200);
    }
  },
  initSlider: function(start_index) {
      this.slider = new Control.Slider($(this.options.slider_handle_id), $(this.options.slider_track_id), {
      range: $R(0, (this.slides.length-1) ),
      values:$A($R(0,this.slides.length-1)),
      sliderValue: start_index,
      onSlide: function(v) {this.go_to(v, false); }.bind(this),
      onChange: function(v) { }
    });        
  },
  destroy: function() {
    this.options.endshow();
    //Event.stopObserving(document, 'keypress', this.bkeyhandler);
  },
  keyhandler: function(e){

  },

  playpause: function() {
    if (this.state == "play") {
      this.pause();
    }
    else {
      this.play();
    }
    this.options.onplaypause(this);
  },
  pause: function() {
    if (this.state == "play") {
      this.state = "pause";
      clearTimeout(this.nextCall);
      //update  (play/pause)
      this.options.onpause(this);
    }
  },

  play: function() {
    if (this.state == "pause") {
      this.state = "play";
      //update  (play/pause)
      this.nextCall = setTimeout(this.next.bind(this), 2000);
      this.options.onplay(this);
    }
  },
  go_to_clicked: function(e, i) {
    var img = e.currentTarget.getAttribute("img");
    var indx;
    for (var i=0; i < this.imagelinks.length; i++) {
      if (this.imagelinks[i] == img) {
        indx = i;
        break;
      }
    }
    this.go_to(indx);

    
  },
  go_to: function(slide, transition) {
    var slideTop = this.slides[slide].getAttribute("top");
    if (slideTop == null) {
      slideTop = "0px"; 
    }
    var slideLeft = this.slides[slide].getAttribute("left");    
    if (slideLeft == null) {
      slideLeft = "0px"; 
    }
    this.slides[slide].setStyle({top:slideTop, left:slideLeft});
    
    clearTimeout(this.nextCall);
    if (this.currentEffect) {
      if (this.currentEffect.cancel) 
      {
        this.currentEffect.cancel();
      }
    }
    if (this.current_slide != -1){
      if (transition == true) {
        new this.options.TransitionOut(this.slides[this.current_slide], {duration: this.options.transitionDuration});
        
      }
      else {
        this.slides[this.current_slide].hide(); 
      }
    }

    if (this.current_slide != -1){
      if (transition == true || this.options.TransitionOut != null) {
        new this.options.TransitionOut(this.slides[this.current_slide], {duration:  this.options.transitionDuration}); 
      }
      else {
        this.slides[this.current_slide].hide();
      }
    }
    if (transition == true)
    {
       new this.options.TransitionIn(this.slides[slide], {duration:  this.options.transitionDuration, afterFinish: effectFactory(this.slides[slide].getAttribute("effect")).bind(this)} );    }
    else {
      this.slides[slide].show();
    }

    this.current_slide = slide;

    if (this.options.captionId) {
      $(this.options.captionId).update(this.slides[this.current_slide].getAttribute("caption"));
    }
    if (this.options.positionId) {
      $(this.options.positionId).update((this.current_slide+1) + "/" + this.slides.length);
    }
    if (this.state == "play") {
      var interval = this.slides[this.current_slide].getAttribute("interval");
      if (!interval) {
        interval = this.options.interval;
      }
      if (interval > 0) {
        this.nextCall = setTimeout(this.next.bind( this), interval);
      }
    }
    var onEnter = this.slides[this.current_slide].getAttribute("onEnter");

    if (onEnter == null || typeof afterFinish != "onEnter") {
      eval(onEnter);
    }
    
    //call the onchange function!
    this.options.onchange(this);
  },
 
  next: function()
  { 
    if (this.current_slide + 1 == this.slides.length) {
      if (this.hasSlider) {
        this.slider.setValue(0);       
      }
      if (this.options.loop) {
        this.go_to(0, true);
      }
      else {
        this.pause();
        this.options.afterFinish();
      }   
    }
    else {
      if (this.hasSlider) {
        this.slider.setValue(this.current_slide+1); 
      }
      this.go_to(this.current_slide+1, true);
    }
  },
  prev: function()
  { 
    if (this.current_slide - 1 == -1) {
      if (this.hasSlider) {
        this.slider.setValue(this.slides.length - 1);
      }
      this.go_to(this.slides.length - 1, true);
    }
    else {
      if (this.hasSlider) {
        this.slider.setValue(this.current_slide - 1);
      }
      this.go_to(this.current_slide-1, true);       
    }
  }
};

function MoveDown() {

    var slideHeight = this.slides[this.current_slide].getHeight();
    var container_height = this.container.getHeight();
    var dur = this.slides[this.current_slide].getAttribute("trans-dur");
    if (!dur) {
      dur = 3.0; 
    }
    this.currentEffect = new Effect.Move(this.slides[this.current_slide], {y:slideHeight-container_height, duration: dur, afterFinish:MoveUp.bind(this)});

}
function MoveUp() {
    var container_height = this.container.getHeight();    
    var slideHeight = this.slides[this.current_slide].getHeight();
    var dur = this.slides[this.current_slide].getAttribute("trans-dur");
    if (!dur) {
      dur = 3.0; 
    }
    this.currentEffect = new Effect.Move(this.slides[this.current_slide], {y: -(slideHeight-container_height), duration: dur, afterFinish:MoveDown.bind(this)});
}


function MoveRight() {
    var slideWidth = this.slides[this.current_slide].getWidth();
    var container_width = this.container.getWidth();
    var dur = this.slides[this.current_slide].getAttribute("trans-dur");
    if (!dur) {
      dur = 3.0; 
    }
    this.currentEffect = new Effect.Move(this.slides[this.current_slide], {x:slideWidth-container_width, duration: dur, afterFinish:MoveLeft.bind(this)});

}
function MoveLeft() {
    var container_width = this.container.getWidth();    
    var slideWidth = this.slides[this.current_slide].getWidth();
    var dur = this.slides[this.current_slide].getAttribute("trans-dur");
    if (!dur) {
      dur = 3.0; 
    }
    this.currentEffect = new Effect.Move(this.slides[this.current_slide], {x: -(slideWidth-container_width), duration: dur, afterFinish:MoveRight.bind(this)});
}



function effectFactory(effectName) {
  switch(effectName) {
    case "pan-up":
      return MoveUp;
      break;
    case "pan-down":
      return MoveDown;
      break;
    case "pan-left":
      return MoveLeft;
      break;
    case "pan-right":
      return MoveRight;
      break;
    default:
      return Prototype.emptyFunction;
  }
}


