/**********************************************************************************************

  CSS on Sails Framework
  Title: Site Name
  Author: XHTMLized (http://www.xhtmlized.com/)
  Date: March 2010

***********************************************************************************************/

// DD_belatedPNG fix for IE6
var PNG_fix_selectors = [
  '#top li',
  '#navigation .dropdown-top',
  '#navigation .dropdown-bottom',
  '#navigation .dropdown-middle',
  '#intro .free-trial img',
  '#footer .follow-us li img',
  '#content .quote-horizontal .photo',
  '.custom-select ul',
  '.custom-select .bottom',
  '#navigation a.ir span'
]; 
/*@cc_on 
  if (@_jscript_version == 5.6 || (@_jscript_version == 5.7 && !window.XMLHttpRequest)) {
    DD_belatedPNG.fix(PNG_fix_selectors.join(','));
  }    
@*/


/**
 * AppFolio User Interface
 */   
var AppFolio = {

  /**
   * Init UI
   */       
	init: function () {
		
		if ($$('#intro .tabs').length) {
			AppFolio.tabsInstance = new AppFolio.Rotator('#intro .tabs .nav a');
		}
		
		if ($$('#content ul.home-testimonials li.slide').length) {
			AppFolio.quotesInstance = new AppFolio.Rotator('#content ul.home-testimonials li.slide', {
				interval: 7000,
				delay: 300
			});
		}
		
		// Custom select
		$$('select.custom-select').each(AppFolio.Form.Select);
		
		// Placeholder text
		$$('input[placeholder]').each(AppFolio.Form.Placeholder);

		// Focus first field in the contact form 
		if ($$('#content form.contact-form').length) {
		  $('first_name').focus();
		}

		// Emulate hover in IE 6
		/*@cc_on 
		if (@_jscript_version == 5.6 || (@_jscript_version == 5.7 && !window.XMLHttpRequest)) {
		  AppFolio.Utils.emulateHover($$('#navigation li'));
		}    
		@*/
		
		// Images rollovers
		AppFolio.Utils.rollovers($$('.home .more-testimonials img, .home .video .watchvideo img, .more img'));
		
		// Preload images
		AppFolio.Utils.preloadImages(["/images/html/btn_more_testimonials_over.png",
                                  "/images/html/btn_more_videos_over.png",
								"/images/html/btn_learn_more_gray_over.png",
							"/images/html/btn_watch_video_over.png"
    ]);
    
    // Privacy popup
    AppFolio.Utils.openPopup($$('.contact-form .privacy a'), 500, 500, 100, 100, ',scrollbars=1');
    AppFolio.Utils.closePopup();
    
    // Fix search inputs in Mac FF
    if (AppFolio.Utils.detectMacFF()) {
      $$('#search').each(function(){
        this.addClassName('macff');
      });
      $$('#search2').each(function(){
        this.addClassName('macff');
      })
    } 

    // Open  rel = external in another window
    $$('a[rel="external"]').each(function(elm){
      Event.observe(elm, 'click', function(event){
        window.open(elm.href);
        Event.stop(event);
      });
    });
	}
};


Event.observe(document, 'dom:loaded', AppFolio.init);

/**
 * AppFolio Rotate content
 * 
 */  
AppFolio.Rotator = function (tabs, options) {
	
	// Construct an object if we're called as a function
	if (this.constructor === window.constructor) {
		return new arguments.callee(tabs, container, options);
	}
	
	
	this.options = $H(this.options).merge(options).toObject();

	this.currentSlide = 0;
	
	tabs = $$(tabs);
	
	// No actual tabs
	if (tabs.first().hasClassName('slide')) {
		this.slides = tabs;
		this.tabs = null;
	}
	else {
		this.tabs = tabs;
		this.slides = this.tabs.map(this.getSlidesFromTabs, this);
		
		this.tabs[this.currentSlide].addClassName('current');
	}
	
	this.slides[this.currentSlide].addClassName('current');
	
	this.slides.slice(1).invoke('hide');
	
	this.slides.invoke('observe', 'mouseenter', this.handleMouseEnter.bind(this));
	
	if (!this.tabs) {
		this.slides.invoke('observe', 'mouseleave', this.setupInterval.bind(this));
	}
	
	this.rotatingTo = 0;
	
	this.setupInterval();
	
	document.observe('lightview:opened', this.cancelInterval.bind(this));
	document.observe('lightview:hidden', this.setupInterval.bind(this));
	
};

// changed interval from 5000 to 500000 to simulate non-rotation

AppFolio.Rotator.prototype.options = {
	interval: 500000,
	duration: 300,
	delay: 0
};

AppFolio.Rotator.prototype.getSlidesFromTabs = function (el, index) {

	var tab = $(el);
		slide = $(tab.readAttribute('href').replace('#','')).writeAttribute('id', '');
	
	tab.observe('mouseenter', this.handleMouseEnter.bind(this));
	
	return slide;
};

AppFolio.Rotator.prototype.handleMouseEnter = function(event) {

	this.cancelInterval();
	
	var target = event.findElement('a'),
		index = this.tabs ? this.tabs.indexOf(target) : -1;
		
	if (index !== -1) {	
		this.rotateTo(index);
	}

};

AppFolio.Rotator.prototype.cancelInterval = function () {
	window.clearInterval(this.timeout);
};

AppFolio.Rotator.prototype.setupInterval = function() {
	this.timeout = window.setInterval(this.rotate.bind(this), this.options.interval); 
};

AppFolio.Rotator.prototype.rotate = function () {

	var next = this.currentSlide + 1;
	if (next >= this.slides.length) {
		next = 0;
	}
	
	this.rotateTo(next);

};

AppFolio.Rotator.prototype.rotateTo = function (index) {

	if (this.rotatingTo === index) {
		return;
	}
	else {
		this.rotatingTo = index;
	}

	var oldSlide = this.slides[this.currentSlide],
		newSlide = this.slides[index],
		oldTab = this.tabs ? this.tabs[this.currentSlide] : null,
		newTab = this.tabs ? this.tabs[index] : null;
	
	if (this.fade) {
		this.fade.cancel();
		this.fade.element.hide();
	}
	
	if (this.appear) {
		this.appear.cancel();
		this.appear.element.hide();
	}
	
	if (oldTab) {
		oldTab.removeClassName('current');
	}
	oldSlide.removeClassName('current');
	
	if (newTab) {
		newTab.addClassName('current');
	}
	newSlide.addClassName('current');
	
	this.fade = new Effect.Fade(oldSlide, {
		duration: this.options.duration / 1000
	});
	
	this.currentSlide = index;
	
	this.appear = new Effect.Appear(newSlide, {
		duration: this.options.duration / 1000,
		delay: this.options.delay / 1000
	});
};


/**
 * AppFolio custom form elements
 */ 
AppFolio.Form = {}

AppFolio.Form.Select = function Select(element, options) {

	// Construct an object if we're called as a function
	if (this.constructor === window.constructor) {
		return new arguments.callee(element);
	}

	this.element = $(element);
	
	this.options = $H(this.options).merge(options || {}).toObject();
	
	this.isOpen = false;
	
	this.styleElement();
	
	this.element.observe('focus', this.grabFocus.bind(this));
	
	document.observe('focus', this.grabFocus.bind(this));
};

AppFolio.Form.Select.prototype.options = {
	containerClass: 'custom-select',
	wrapperClass: 'custom-select-wrapper'
};

AppFolio.Form.Select.prototype.styleElement = function styleElement() {

	this.container = new Element('div', {
		className: this.options.containerClass
	});
	
	this.wrapper = new Element('div', {
		className: this.options.wrapperClass
	}).update('<ul></ul><div class="bottom"></div>');
	
	this.selected = new Element('a', {
		className: 'current-selected',
		href: '#',
		tabIndex: this.element.readAttribute('tabIndex')
	}).update(this.element.options[this.element.selectedIndex].text);
	
	
	this.container.appendChild(this.selected).up().appendChild(this.wrapper);

	this.element.hide().writeAttribute('tabIndex','-1').insert({before: this.container});

	this.optList = this.wrapper.select('ul')[0];
	
	this.optListEntries = $A(this.element.options).map(this.addOption, this);

	this.selected.observe('click', this.toggle.bindAsEventListener(this));
	this.selected.observe('keydown', this.keydown.bindAsEventListener(this));
	this.optList.observe('click', this.click.bindAsEventListener(this));
};

AppFolio.Form.Select.prototype.grabFocus = function grabFocus() {
	this.selected.focus();
};

AppFolio.Form.Select.prototype.addOption = function addOption(element, i) {
	element = $(element);

	var el = new Element('li', {
		className: element.hasClassName('all') ? 'all' : ''
	}).update(new Element('a', {
		className: element.readAttribute('selected') ? 'selected' : '',
		tabIndex: -1,
		href: '#'
	}).update(element.innerHTML));

	this.optList.appendChild(el);

	return el;

};

AppFolio.Form.Select.prototype.toggle = function toggle(e) {
	e.preventDefault();
	
	if (this.isOpen) {
		this.close(e);
	}
	else {
		this.open(e);
	}
};


AppFolio.Form.Select.prototype.open = function open(e) {
	this.container.addClassName('open');
	this.isOpen = true;
	
	window.setTimeout(this.setupEvents.bind(this), 10);
};

AppFolio.Form.Select.prototype.close = function close(e) {
	this.container.removeClassName('open');
	this.optList.select('.current').invoke('removeClassName', 'current');
	this.isOpen = false;
	
	this.removeEvents(e);
};



AppFolio.Form.Select.prototype.setupEvents = function setupEvents() {
	var that = this;
	if (this.callbacks) {
		return;
	}
	this.callbacks = $H({
		click: this.close,
		keydown: this.keydown,
		mouseover: this.mouseover
	}).map(function (func) {
		var callback = func.value.bindAsEventListener(that);
		document.observe(func.key, callback);
		
		return {key: func.key, value: callback};
	});
};

AppFolio.Form.Select.prototype.removeEvents = function removeEvents(e) {

	if (this.callbacks) {
		this.callbacks.each(function (callback) {
			document.stopObserving(callback.key, callback.value);
		});
	}
	
	this.callbacks = false;
};


AppFolio.Form.Select.prototype.mouseover = function mouseover(e, element) {
	element = e ? Event.element(e) : element;
	
	if (element.nodeName.toLowerCase() === 'a') {
		this.optList.select('.current').invoke('removeClassName', 'current');
		element.addClassName('current');
	}
};

AppFolio.Form.Select.prototype.keydown = function keydown(e) {
	var element = this.optList.select('.current')[0],
		ev_element = Event.element(e),
		currentIndex = element ? this.optListEntries.indexOf(element.up()) : -1,
		newIndex = false;
	
	switch(AppFolio.Utils.keyCode(e)) {
		// Use space to open the Select when it has focus
		case 32:
			if (ev_element === this.selected) {
				e.stop();
				this.open(e);
			}
			break;
	
		case Event.KEY_TAB:
			this.close(e);
			break;
		
		case Event.KEY_ESC:
			this.close(e);
			break;
		
		case Event.KEY_RETURN:
			e.stop();
			if (currentIndex !== -1) {
				this.selectByElement(element);
			}
			this.close(e);
			break;
		
		case Event.KEY_UP:
			e.stop();
			if (this.isOpen) {
				newIndex = currentIndex -1;
			}
			else {
				this.selectByOffset(-1);
			}
			break;
			
		case Event.KEY_DOWN:
			e.stop();
			if (this.isOpen) {
				newIndex = currentIndex +1;
			}
			else {
				this.selectByOffset(1);
			}
			break;
	}
	
	if (newIndex !== false) {
		if (newIndex < 0) {
			newIndex = this.optListEntries.length - 1;
		}
		else if (newIndex >= this.optListEntries.length) {
			newIndex = 0;
		}
		this.mouseover(false, this.optListEntries[newIndex].down('a'));
	}
};

AppFolio.Form.Select.prototype.click = function click(e) {
	var element = e ? Event.element(e) : false;
		
	e.preventDefault();
	
	if (element && element.nodeName.toLowerCase() === 'a') {
		this.selectByElement(element);
		this.close(e);
	}
};


AppFolio.Form.Select.prototype.selectByOffset = function selectByOffset(offset) {

	var newIndex = this.element.selectedIndex + offset;
	
	if (newIndex < 0) {
		newIndex = this.optListEntries.length - 1;
	}
	if (newIndex >= this.optListEntries.length) {
		newIndex = 0;
	}
	
	this.selectByIndex(newIndex);

};

AppFolio.Form.Select.prototype.selectByElement = function selectByElement(element) {
	element = $(element);
	
	var index = parseInt(this.optListEntries.indexOf(element.up('li')));
	
	this.selectByIndex(index);

};

AppFolio.Form.Select.prototype.selectByIndex = function selectByIndex(index) {

	if (index >= 0 && index < this.element.options.length) {
		this.element.selectedIndex = index;
		this.selected.update(this.optListEntries[index].select('a').first().innerHTML);
	}

};


/**
 * @class Text field Placeholders
 * @param {HTMLElement} element element ID or element reference to initialise Placeholder on
 * @param {String} [placeholderText] overide the default Placeholder text (read from title attribute) for an Input
 */
AppFolio.Form.Placeholder = function Placeholder(element) {
	
	if (AppFolio.Form.Placeholder.nativeSupport()) {
		return;
	}
	
	// Construct an object if we're called as a function
	if (this.constructor === window.constructor) {
		return new arguments.callee(element);
	}
	
	/**
	 * The Input element
	 * @type HTMLElement
	 */
	this.element = $(element);
	
	/**
	 * The placeholder text (false if none)
	 * @type String|Boolean
	 */
	this.placeholderText = this.element.readAttribute('placeholder');
	
	/**
	 * Indicates if placeholder text is showing
	 * @type Boolean
	 */
	this.active = false;
	
	/**
	 * Indicates if we're dealing with a password field
	 * @type Boolean
	 */
	this.passwordMode = this.element.type === 'password';
	
	
	this.passwordFieldFixed = false;
	
	if (this.placeholderText) {
		this.events();
		this.show();
	}
};

AppFolio.Form.Placeholder.nativeSupport = function nativeSupport() {
	var e = document.createElement('input');
	return 'placeholder' in e;
};

AppFolio.Form.Placeholder.prototype.events = function events() {
	this.element.observe('focus', this.hide.bindAsEventListener(this));
	this.element.up('form').observe('submit', this.hide.bindAsEventListener(this));
	this.element.up('form').observe('reset', this.reset.bindAsEventListener(this));
	this.element.observe('blur', this.show.bindAsEventListener(this));
};


AppFolio.Form.Placeholder.prototype.fixPasswordField = function fixPasswordField() {

	this._element = this.element;
	
	this.otherField = new Element('input', {
		type: 'text',
		className: this.element.className
	}).observe('focus', this.hide.bindAsEventListener(this));	
	
	$$('label[for="' + this.element.id + '"]').invoke('observe', 'click', this.focus.bind(this));
	
	this.element.parentNode.insertBefore(this.otherField, this.element);
	
	this.passwordFieldFixed = true;
};

/**
 * Show the placeholder text
 */
AppFolio.Form.Placeholder.prototype.show = function show() {
	if (!this.element.present()) {
		
		if (this.passwordMode) {
			try {
				this.element.type = 'text';
			}
			catch(e) {
				if (!this.passwordFieldFixed) {
					this.fixPasswordField();	
				}
				
				this.element.hide();
				this.otherField.show();
				
				this.element = this.otherField;
			}
		}
		
		this.element.value = this.placeholderText;
		this.active = true;
	}
};


/**
 * Hide the placeholder text
 */
AppFolio.Form.Placeholder.prototype.hide = function hide() {
	if (this.active) {
		
		if (this.passwordMode) {
			try {
				this.element.type = 'password';
			}
			catch(e) {
				if (!this.passwordFieldFixed) {
					this.fixPasswordField();	
				}
				
				this.otherField.hide();
				this.element = this._element;
				this.element.show().focus();
			}
		}

		
		this.element.value = '';
		var toFocus = false;
		
		this.active = false;
	}
};

AppFolio.Form.Placeholder.prototype.focus = function focus() {
	this.element.focus();
};

AppFolio.Form.Placeholder.prototype.reset = function reset() {
	window.setTimeout(this.show.bind(this), 20);
};

/**
 * AppFolio Utils
 */
AppFolio.Utils = {}

AppFolio.Utils.keyCode = function (e) {
  var code = e.keyCode ? e.keyCode : e.which ? e.which : false;
  return code;
}

/**
 * Emulate hover
 */
AppFolio.Utils.emulateHover = function(items) {
  items.each(function (e) {
    e.observe('mouseenter', function() {
        this.addClassName('hover');
    });
    e.observe('mouseleave', function() {
        this.removeClassName('hover');
    });
  });
}

/**
 * Rollovers buttons
 */
AppFolio.Utils.rollovers = function(items) {
  items.each(function (e) {
    e.observe('mouseenter', function() {
        this.writeAttribute('src', this.readAttribute('src').replace(/.png/, '_over.png'));
    });
    e.observe('mouseleave', function() {
        this.writeAttribute('src', this.readAttribute('src').replace(/_over.png/, '.png'));
    });
  });  
}

/**
 * Preload images
 * @param {Array} images array with names of images   
 */               
AppFolio.Utils.preloadImages = function(images) {
  for (var i = 0; i < images.length; i++) {
    var image = new Image();
    image.src = images[i];
  }
}

/**
 * Open link in popup window
 */
AppFolio.Utils.openPopup = function (items, width, height, top, left, param) {
  items.each(function (e) {
    e.observe('click', function(event) {
      window.open(this.href, 'name', 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + param);
      event.stop();
    });
  });
}

/**
 * Close popup
 */
AppFolio.Utils.closePopup = function () {
  if ($('close-popup')) {
    $('close-popup').observe('click', function(event) {
      window.close();
      event.stop();
    });
  }
}

/**
 * Detect Mac Firefox
 */ 
AppFolio.Utils.detectMacFF = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
        return true;
    }
}    

// Make sure FF doesn't use it's bfcache
window.onunload = function () {};




////////////////////////////////////////////////
// Code pulled from the old lp/global.js file //
////////////////////////////////////////////////
function pop_demo() {
	var windowname = window.open('/lp/watch/', 'watch',"width=715,height=530,top=10,left=10,menubar=yes,scrollbars=yes,resizable=yes");
	if (window.focus) {
		windowname.focus();
	}
}


function pop_terms() {
	var windowname = window.open('/lp/terms/', 'terms',"width=525,height=500,top=10,left=10,menubar=yes,scrollbars=yes,resizable=yes");
	if (window.focus) {
		windowname.focus();
	}
}

function pop_termscafe() {
	var windowname = window.open('/lp/termscafe/', 'termscafe',"width=525,height=500,top=10,left=10,menubar=yes,scrollbars=yes,resizable=yes");
	if (window.focus) {
		windowname.focus();
	}
}

function pop_privacy() {
	var windowname = window.open('/lp/privacy/', 'privacy',"width=525,height=500,top=10,left=10,menubar=yes,scrollbars=yes,resizable=yes");
	if (window.focus) {
		windowname.focus();
	}
}

function pop_testimonialVideo() {
	var windowname = window.open('/lp/testimonialVideo/', 'testimonialVideo',"width=525,height=500,top=10,left=10,menubar=yes,scrollbars=yes,resizable=yes");
	if (window.focus) {
		windowname.focus();
	}
}

btnWait = new Image();
btnWait.src = '/images/html/btn_wait.png';
var btn_active = true;
function submitForm() {
	if(btn_active == true) {
		btn_active = false;
		document.getElementById('btn_submit').src = btnWait.src;
		setTimeout('document.getElementById(\'signup\').submit();', 500);
	}
}

function customSubmitForm(form_id) {
	if(btn_active == true) {
		btn_active = false;
		document.getElementById('btn_submit').src = btnWait.src;
		setTimeout("document.getElementById('" + form_id + "').submit();", 500);
	}
}
