// By Zef for Property Scroller project

function updateProperty (pictureSource, propertyName, propertyDescription, propertyLink) {    
	document.images['SelectedPropertyPicture'].src=pictureSource;
	$('SelectedPropertyName').innerHTML=propertyName;
	$('SelectedPropertyDesription').innerHTML=propertyDescription;
	$('SelectedPropertyImgLink').href=propertyLink;
}

function toggle_thumb(obj) {
	var classItems = $$('.PSthumb');
	for(i=0;i<classItems.length;i++) {
		var element = classItems[i];
		element.style.border = "2px solid #bbb";
		document.getElementById(obj).style.border = "2px solid #666";
	}
}

// Copyright (c) 2006 Sébastien Gruhier (http://xilinus.com, http://itseb.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 0.26

var Carousel = Class.create();
Carousel.prototype = {
  // Constructor
  initialize: function(carouselElemID) {
    this.carouselElemID = carouselElemID;
    
    this.options = Object.extend({
      numVisible:           3,
      scrollInc:            3,
      animParameters:      {},
      buttonStateHandler:  null,
      animHandler:         null,
      ajaxHandler:         null,
      initDoneHandler:     null,
      queue:               "carousel",
      size:                0,
      prevElementID:       "prev-arrow",
      nextElementID:       "next-arrow",
      ajaxParameters:      null,
      url:                 null
		}, arguments[1] || {});

		this.initDone = false;
		this.animRunning = "none";
    this.requestIsRunning = false;
    
		// add afterFinish options to animParameters (store old function)
		this.animAfterFinish = this.options.animParameters.afterFinish;
		Object.extend(this.options.animParameters, {afterFinish:  this._animDone.bind(this), queue: { position:'end', scope: this.options.queue }});
	  
		// Event bindings
		this.prevScroll = this._prevScroll.bindAsEventListener(this);
		this.nextScroll = this._nextScroll.bindAsEventListener(this);
		this.onComplete = this._onComplete.bindAsEventListener(this);
		this.onFailure  = this._onFailure.bindAsEventListener(this);

		Event.observe(this.options.prevElementID, "click", this.prevScroll);
		Event.observe(this.options.nextElementID, "click", this.nextScroll);
		
		// Get DOM UL element
		var carouselListClass = "carousel-list";
		this.carouselList = document.getElementsByClassName(carouselListClass, $(carouselElemID))[0]
		this.options.size =  $(this.carouselList.getElementsByTagName("li")).length;
		// Init data
		this._init();
  },
  
  // Destructor
 	destroy: function() {
  	Event.stopObserving(this.options.prevElementID, "click", this.prevScroll);
  	Event.stopObserving(this.options.nextElementID, "click", this.nextScroll);
	},
	
	scrollTo: function(newStart) {
		var old_inc = this.options.scrollInc;
		this.ignoreNoMoreImages = true;
		if(newStart > this.currentIndex) {
			this.options.scrollInc = newStart - this.currentIndex;
			this._nextScroll(this);
		} else {
			this.options.scrollInc = this.currentIndex - newStart;
			this._prevScroll(this);
		}
    this.options.scrollInc = old_inc;
	},
	
  /* "Private" functions */
  _init: function() {
    this.currentIndex = 0;
      
    // Ajax content
    if (this.options.url)
  	  this._request(this.currentIndex, this.options.numVisible);
	  // Static content
  	else {
  	  this._getLiElementSize();
  		this._updateButtonStateHandler(this.options.prevElementID, false);
  		this._updateButtonStateHandler(this.options.nextElementID, this.options.size > this.options.numVisible);
  	}
  },
  
  _prevScroll: function(event) {
    if (this.animRunning != "none" || this.currentIndex == 0)
      return;

    var inc = this.options.scrollInc;

    if (this.currentIndex - inc < 0)
      inc = this.currentIndex;

    this._scroll(inc)		  
	  return false;
  },
  
  _nextScroll: function(event) {    
    if (this.animRunning != "none")
      return false;
            
    // Check if there are enough elements in cache
    if (this.currentIndex + this.options.numVisible + this.options.scrollInc <= this.options.size) 
      this._scroll(-this.options.scrollInc);
    else {
      // Compute how many are in the cache
      this.nbInCache = this.options.size - (this.currentIndex + this.options.numVisible);
      if (this.options.url && this.noMoreImages == false) 
		    this._request(this.currentIndex + this.options.numVisible + this.nbInCache, this.options.scrollInc - this.nbInCache);
	    else  {
	      if (this.nbInCache > 0)
          this._scroll(-this.nbInCache);
        }
	  }
	  return false;
  },
  
  _request: function(start, nb) {
    if (this.options.url && ! this.requestIsRunning) {
      this.requestIsRunning = true;
      
      if (this.options.ajaxHandler)
        this.options.ajaxHandler(this, "before");
      
      var params = "start=" + start + "&nb=" + nb;
      if (this.options.ajaxParameters != null)
        params += "&" + this.options.ajaxParameters
      
  		new Ajax.Request(this.options.url, {parameters: params, onComplete: this.onComplete, onFailure: this.onFailure});
		}
  },
  
  _onComplete: function(originalRequest){
    this.requestIsRunning = false;
    this.carouselList.innerHTML += originalRequest.responseText;
    // Compute how many new elements we have
    var size = this.options.size;
    this.options.size = this.carouselList.getElementsByTagName("li").length;
    var inc = this.options.size - size;
    
		// First run, compute li size
		if (this.initDone == false) {
  		this._getLiElementSize()
  		this.currentIndex = 0;
  		this.initDone = true;
      if (this.options.initDoneHandler) 
        this.options.initDoneHandler(this);
         
  		// Update button states
		  this._updateButtonStateHandler(this.options.prevElementID, false);
		  this._updateButtonStateHandler(this.options.nextElementID, this.options.size == this.options.numVisible);
		  this.noMoreImages = this.options.size < this.options.numVisible
		}
		// Add images
		else {
		  if (!this.ignoreNoMoreImages)
		    this.noMoreImages = inc != this.options.scrollInc;
		  else
		    this.ignoreNoMoreImages = false;
		  // Add images
		  if (inc > 0) {
        this._scroll(-inc, this.noMoreImages)
      }
      // No more images, disable next button
		  else {
		    if (this.nbInCache >0)
          this._scroll(-this.nbInCache, true);
		    
		    this._updateButtonStateHandler(this.options.nextElementID, false);
	    }
		}
		if (this.options.ajaxHandler)
      this.options.ajaxHandler(this, "after");
  },
  
  _onFailure: function(originalRequest){    
    this.requestIsRunning = false;
  },

  _animDone: function(event){   
    if (this.options.animHandler)
      this.options.animHandler(this.carouselElemID, "after", this.animRunning);
     
    this.animRunning = "none";
    // Call animAfterFinish if exists
    if (this.animAfterFinish)
      this.animAfterFinish(event);
  },
  
  _updateButtonStateHandler: function(button, state) {
		if (this.options.buttonStateHandler) 
		    this.options.buttonStateHandler(button, state)
   },
  
  _scroll: function(delta, forceDisableNext) {      
    this.animRunning = delta > 0 ? "prev" : "next";
    
    if (this.options.animHandler)
      this.options.animHandler(this.carouselElemID, "before", this.animRunning);

    new Effect.MoveBy(this.carouselList, 0, delta * this.elementSize, this.options.animParameters);
    this.currentIndex -= delta;
    this._updateButtonStateHandler(this.options.prevElementID, this.currentIndex != 0);
    
    if (this.options.url && this.noMoreImages == false)
      enable = true;
    else
      enable = (this.currentIndex + this.options.numVisible < this.options.size);
    this._updateButtonStateHandler(this.options.nextElementID, (forceDisableNext ? false : enable));
  },
  
  _getLiElementSize: function() {
    var li = $(this.carouselList.getElementsByTagName("li")[0]);
		this.elementSize = li.getDimensions().width + parseFloat(li.getStyle("margin-left")) + parseFloat(li.getStyle("margin-right"));
  }
}
	





// JavaScript Document

// for select onchange, redirect

function ShowHideNews(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

function redirect(optVal){
  if(optVal=="") 
    return false;
  window.location=optVal;
}

function openwindow2(image_path)
{
  window.open(image_path,"mywindow","status=0,scrollbars=0,toolbar=0,menubar=0,location=0,resizable=0,width=400,height=530");
}

function openwindow(image_path) {
  window.open(image_path,"mywindow","status=0,scrollbars=0,toolbar=0,menubar=0,location=0,resizable=0,width=350,height=400");
}
function openwindow_scrollbars(image_path) {
  window.open(image_path,"mywindow","status=0,scrollbars=1,toolbar=0,menubar=0,location=0,resizable=1,width=368,height=530");
}

function openwindow_scrollbars_large(image_path) {
  window.open(image_path,"mywindow","status=0,scrollbars=1,toolbar=0,menubar=0,location=0,resizable=1,width=600,height=800");
}

function openwindow_scrollbars_x_large(image_path) {
  window.open(image_path,"mywindow","status=0,scrollbars=1,toolbar=0,menubar=0,location=0,resizable=1,width=800,height=920");
}

function blankme(me) {
  if ((document.getElementById(me).value == 'username') || (document.getElementById(me).value == 'password')) {
    document.getElementById(me).value='';
    if (me == "password") {
      document.getElementById(me).type='password';
    }
  }
  
}
function init_forms() {
  document.getElementById('username').focus();
  document.getElementById('username').value='username';
  document.getElementById('password').value='password';
}
function changeClass(obj) {
   pageclass = obj.options[obj.selectedIndex].value;
   switch (pageclass) {
    case "a":
      document.getElementById('body').className="userA";
      break;
    case "b":
      document.getElementById('body').className="userB";
      break;
    case "cd": 
      document.getElementById('body').className="userCD";
      break;
    
   }
}
function ShowHide (n,whichLink) {
  if (document.getElementById(n).style.display=='none') {
    document.getElementById(whichLink).innerHTML="hide -";
    new Effect.BlindDown(n,{duration:.5});
  }
  else {
    document.getElementById(whichLink).innerHTML="show +";
    new Effect.BlindUp(n,{duration:.5});
  }
}

// used in adding grocery list to textarea
function add_list( old_list_txt, current_list_text_area_id ){
	if( confirm("Add this grocery?\n\nRemember to save after adding.")){	
		$(current_list_text_area_id).value = $(current_list_text_area_id).getValue() + "\n" + old_list_txt;
		$(current_list_text_area_id).scrollTo();		
	}
}

function manage_new_grocery_list_form(elmnt){
	if($(elmnt).value != "-1"){
		$$(".new_gl_form_elmnt").invoke('show')		
		$('new_grocery_list_description').value = $(elmnt).value
	}
	else
		$$(".new_gl_form_elmnt").invoke('hide')
}

function toggle_gl_text_area(elmnt){
	$(elmnt).up();	
	$(elmnt).up().up().nextSiblings().each(function(el) {
	  toggle_visiblity(el);
	});
}

function toggle_visiblity(elmnt){
	$(elmnt).visible() ? $(elmnt).hide() : $(elmnt).show()
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
		return [curleft,curtop];
  }
}


function loadHomeRollovers(destID,element) {
  xCoord="205px";
  yCoord=findPos(element)[1] + "px";
  $('home_rollover_container').style.left=xCoord;
  $('home_rollover_container').style.top=yCoord;
  $('rollover_contents').innerHTML='<img id="roll_spinner" src="/img/loader-a.gif" />';

  
   test= new Ajax.Updater('rollover_contents', '/destinations/dest_pop?id='+destID, {
   asynchronous:true, 
   evalScripts:true, 
   onComplete:function(request){var roll_load=true; /*Effect.Fade('roll_spinner'); */ Element.show('home_rollover_wrap');}, 
   onLoading:function(request){var roll_load=false; /*Effect.Appear('roll_spinner') Element.hide('home_rollover_wrap');*/}});
 return false;
}


function kill_rollover(element){
  if ($(element)) {
	  $(element).style.visibility="hidden";
  }
}
function show_rollover(element){
  $(element).style.visibility='visible';
}


  //<![CDATA[

    function loadGM() {
      if (GBrowserIsCompatible()) {
        
        
        // Creates a marker at the given point with the given number label
        function createMarker(point, text) {
          var marker = new GMarker(point);
          GEvent.addListener(marker, "click", function() {
           marker.openInfoWindowHtml(text);});
          return marker;
        }

        // var map = new google.maps.Map2(document.getElementById("map")); // Google Earth version
        var map = new GMap2(document.getElementById("map")); // non-Google Earth version
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        // map.addMapType(G_SATELLITE_3D_MAP);  // Should enable google "earth" button 
        map.setCenter(new GLatLng(propLat, propLon), 12, G_HYBRID_MAP);
        
        var icon = new GIcon();
         icon.image = "http://maps.google.com/mapfiles/kml/pal2/icon10.png";
         icon.shadow = "http://maps.google.com/mapfiles/kml/pal2/icon10s.png";
         icon.iconSize=new GSize(32,32);
         icon.shadowSize=new GSize(56,32);
         icon.iconAnchor=new GPoint(16,32);
         icon.infoWindowAnchor=new GPoint(16,0);

      
      var point = new GLatLng(propLat, propLon);

      map.addOverlay(new GMarker(point));
      map.addOverlay(createMarker(point, propDest+", "+propName+propAddress, icon));
      
      /*
      map.openInfoWindowHtml(new GLatLng(propLat, propLo), "Los Cabos &mdash; The Casitas<br />Villas Del Mar Palmilla<br />km. 27.5 Carretera Transpeninsular<br />San Jose del Cabo, B.C.S., Mexico, 23400"); 

*/
      }                      
    }

    /*
    // Attempt at getting Google Earth working. Problem is that DOM must be complete before this is called.
    function loadGM() {
      // google.load("earth", "1");  // uncomment to enable the earth stuff.
      google.load("maps", "2", {"callback" : mapsLoaded});
      // google.setOnLoadCallback(initialize);
    }
    */

    //]]>


var dhtmlHistory={WAIT_TIME:200,currentWaitTime:0,initialize:function(){if(Prototype.Browser.WebKit){return false;}historyStorage.init();this.currentLocation=this.getCurrentLocation();if(Prototype.Browser.IE){this.iframe=$(document.createElement("IFRAME")).hide();this.iframe.name=this.iframe.id="DhtmlHistoryFrame";this.iframe.src="javascript:false;";document.body.appendChild(this.iframe);this.writeIframe(this.currentLocation);this.WAIT_TIME=400;this.ignoreLocationChange=true;}Event.observe(window,"unload",function(){this.firstLoad=false;}.bind(this));this.isFirstLoad();setInterval(this.checkLocation.bind(this),100);return true;},addListener:function(_1){this.listener=_1;if(this.fireOnNewListener){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false;}},add:function(_2,_3){if(Prototype.Browser.WebKit){return;}setTimeout(this.addImpl.bind(this,_2,_3),this.currentWaitTime);this.currentWaitTime+=this.WAIT_TIME;},getCurrentLocation:function(){return this.removeHash(unescape(location.hash));},addImpl:function(_4,_5){if(this.currentWaitTime){this.currentWaitTime-=this.WAIT_TIME;}if($("newLoc")){return;}var _4=this.removeHash(_4);historyStorage.put(_4,_5);this.ignoreLocationChange=this.ieAtomicLocationChange=true;this.currentLocation=_4;location.hash=escape(_4);if(Prototype.Browser.IE){this.writeIframe(_4);}this.ieAtomicLocationChange=false;},isFirstLoad:function(){if(historyStorage.hasKey("DhtmlHistory_pageLoaded")==false){if(Prototype.Browser.IE){this.fireOnNewListener=false;}else{this.ignoreLocationChange=true;}this.firstLoad=true;historyStorage.put("DhtmlHistory_pageLoaded",true);}else{if(Prototype.Browser.IE){this.firstLoad=false;}else{this.ignoreLocationChange=false;}this.fireOnNewListener=true;}},fireHistoryEvent:function(_6){this.listener.call(null,_6,historyStorage.get(_6));},checkLocation:function(){if(!Prototype.Browser.IE){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return;}}else{if(this.ieAtomicLocationChange){return;}}var _7=this.getCurrentLocation();if(_7==this.currentLocation){return;}this.ieAtomicLocationChange=true;if(Prototype.Browser.IE){if(this.iframe.contentWindow.l==_7){return;}this.writeIframe(_7);}this.currentLocation=_7;this.ieAtomicLocationChange=false;this.fireHistoryEvent(_7);},removeHash:function(h){if(h==null||h==undefined){return null;}else{if(h.length&&h.charAt(0)=="#"){if(h.length==1){return"";}else{return h.substring(1);}}}return h;},iframeLoaded:function(_9){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return;}location.hash=escape(_9);this.fireHistoryEvent(_9);},writeIframe:function(l){var d=this.iframe.contentWindow.document;d.open();d.write("<html><script type=\"text/javascript\">var l=\""+l+"\";function pageLoaded(){window.parent.dhtmlHistory.iframeLoaded(l);}</script><body onload=\"pageLoaded()\"></body></html>");d.close();}};var historyStorage={put:function(_c,_d){this.loadHashTable();this.storageHash[_c]=_d;this.saveHashTable();},get:function(_e){this.loadHashTable();var _f=this.storageHash[_e];return(_f==undefined)?null:_f;},remove:function(key){this.loadHashTable();delete this.storageHash[key];this.saveHashTable();},reset:function(){this.storageField.value="";this.storageHash=$H();},hasKey:function(key){this.loadHashTable();return!(typeof this.storageHash[key]==undefined);},init:function(){var _12=$(document.createElement("FORM")).hide();document.body.appendChild(_12);var ta=$(document.createElement("TEXTAREA"));ta.id="historyStorageField";_12.appendChild(ta);this.storageField=$("historyStorageField");},loadHashTable:function(){if(!this.storageHash){this.storageHash=(this.storageField.value)?this.storageField.value.evalJSON():$H();}},saveHashTable:function(){this.loadHashTable();this.storageField.value=Object.toJSON(this.storageHash);}};

/** ADDED BY Dave Ringoen, September 2007 */
/** Initialize all of our objects now. */

var subnav_url_base = '';

/** Create init methods for the Homes Sub Nav */
function initialize_dthml_history_tabs() {
  // initialize our DHTML history
  dhtmlHistory.initialize();
  // subscribe to DHTML history change
  // events
  dhtmlHistory.addListener(handleHistoryChange);
}

function initialize_basic_tabs() {
  var tab = location.hash.replace('#', '');
  if (tab !== '') {
    if (tab == 'arriving') { // not so dry, but call the loadGM() Google Maps function if we're on that tab.    
      new Ajax.Updater('content-inner', subnav_url_base.replace('xyzzy_action',tab), {asynchronous:true, evalScripts:true, 
        onLoading:function(request){$('loading').show();},
        onComplete:function(request){$('loading').hide(); activate_sub_nav_links(tab); loadGM(); ('loading').hide();}}); // seem to need to call .hide twice. DRR
    }
    else {
      new Ajax.Updater('content-inner', subnav_url_base.replace('xyzzy_action',tab), {asynchronous:true, evalScripts:true, 
        onLoading:function(request){$('loading').show();},
        onComplete:function(request){$('loading').hide(); activate_sub_nav_links(tab); $('loading').hide(); }});  // maybe do it twice here, this case doesn't seem reliable either.
    }
  }
}

function set_subnav_url_base(url_base) {
  //alert('set_subnav_url_base ' + url_base);
  subnav_url_base = url_base;
}

/** Our callback to receive history
    change events. */
function handleHistoryChange(pageId, pageData) {
  if (!pageData) return;
  var info = pageId.split(':');
  var id = info[0];
  //pageData += '';
  if (id == 'arriving') { // not so dry, but call the loadGM() Google Maps function if we're on that tab.
  new Ajax.Updater('content-inner', pageData, {asynchronous:true, evalScripts:true, 
    onLoading:function(request){$('loading').show();},
    onComplete:function(request){$('loading').hide(); activate_sub_nav_links(id); loadGM();}});
  }
  else {
    new Ajax.Updater('content-inner', pageData, {asynchronous:true, evalScripts:true, 
      onLoading:function(request){$('loading').show();},
      onComplete:function(request){$('loading').hide(); activate_sub_nav_links(id);}});    
  }
}

function addQuintessPageToHistory(url, subPage) {
  // var array = url.split('?');
  // var qs = new Querystring(array[1]);
  // var sort = qs.get('sort')
  // var dir = qs.get('sort_direction')
  //   var page = qs.get('page')
  // if (sort || dir || page) dhtmlHistory.add(active_scaffold_id+":"+page+":"+sort+":"+dir, url);

  // following line needed to drive dhtml history
  // dhtmlHistory.add(subPage, url);
  
  // needed for basic tabs
  location.hash = subPage;
  
  activate_sub_nav_links(subPage);
	return true;
}

function activate_sub_nav_links(id)
{
	$$('.content-link').each(function(element) {
	  Element.removeClassName(element, 'selected');
  })
	Element.addClassName(id + '-link', 'selected');
}


/** set onload handler */
//Event.observe(window, 'load', initialize_dthml_history_tabs, false);
Event.observe(window, 'load', initialize_basic_tabs, false);
