/*
-----------------------------------------------------------------
This javascript was written, compiled, organized, and molested
by Nate Cavanaugh. All of it, every line, is available to be 
tampered with for any and all reasons.
Most of it requires the Prototype framework (We love you Sam!)
(http://prototype.conio.net) as well as the DOMReady prototype
extension.
If you somehow find yourself in a spot where any of this is
useful, don't hesitate to use it.
If there is anything that doesnt make any sense, shoot us an
email at http://expansecms.com/?p=contact

Oh yeah, buy Expanse!
=================================================================
*/

/*
------------------------------------------------------------
Smoothly resizes certain boxes, but it's deprecated.
============================================================
*/
var resizer = {
	init : function(){
	if(!$('licenses') && !$('message')){return;}
	var container = domEl('div', '', {id : 'sizerLinks'});
	var plus = domEl('a', '+ More Room', {id:'plus', href:'javascript:;'});
	var minus = domEl('a', '- Less Room', {id:'minus', href:'javascript:;'});
	var domainBox = $('licenses');
	if($('message') && !domainBox){
		domainBox = $('message');
		}
	remDescr = new fx.RememberHeight(domainBox, 365, {duration: 400});
	Event.observe(plus, 'click',  function(){if(this.offsetHeight < 480){remDescr.resize(100);}}.bindAsEventListener(domainBox));
	Event.observe(plus, 'focus',  function(){this.blur();}.bindAsEventListener(plus));
	container.appendChild(plus);
	Event.observe(minus, 'click',  function(){if(this.offsetHeight > 200){remDescr.resize(-100);}}.bindAsEventListener(domainBox));
	Event.observe(minus, 'focus',  function(){this.blur();}.bindAsEventListener(minus));
	container.appendChild(minus);
	insertAfter(domainBox.id, container);
		}
	};
/*
------------------------------------------------------------
This just adds the charity info to the order form.
Reads the title from the options, and sets it into a div
below the select field.
============================================================
*/
var charityDetails = {
	init : function(){
		if(!$('charities')){return;}
		if(!$('charityInfo')){
			this.createInfoDiv();
			}
		this.charitySelect = $('charities');
		this.charityInfo = $('charityInfo');
		Event.observe(this.charitySelect, 'change', function(){
					charityDetails.insertLink(this)
					}.bindAsEventListener(this.charitySelect));
		},
	createInfoDiv : function(){
		var infoDiv = domEl('div', '', {id:'charityInfo'});
		insertAfter($('charities'), infoDiv);
		},
	insertLink : function(obj){
		
		var url = obj.options[obj.selectedIndex].title;	
		if(url != ''){
			if(url.indexOf('http://') == -1 && url.indexOf('https://') == -1){
				url = 'http://'+url;
				}
			charityDetails.charityInfo.innerHTML = 'Find out more about this charity at: <a href="'+url+'" target="_blank">'+url+'</a>';
			}
		else {
			charityDetails.charityInfo.innerHTML = '';
			}
		}
	};

/*
------------------------------------------------------------
Since IE doesnt allow the :hover or :focus psuedo-classes for any other
elements except links, this is a nice little object to 
switch the image out of the image submit buttons.
Requires that the off image be named something like
FILENAME_off.gif
and that the hover state image be named something like
FILENAME_on.gif
============================================================
*/
var inputOvers = {
	init : function(){
		var inputs = document.getElementsByClassName('submit_image');
		$A(inputs).each(
						function(obj){
							Event.observe(obj, 'mouseover', inputOvers.over.bindAsEventListener(obj));
							Event.observe(obj, 'focus', inputOvers.over.bindAsEventListener(obj));
							
							Event.observe(obj, 'mouseout', inputOvers.out.bindAsEventListener(obj));
							Event.observe(obj, 'blur', inputOvers.out.bindAsEventListener(obj));
							}
						);
		},
	over : function(){
		var pattern = new RegExp('_off','gi');
		this.src = this.src.replace(pattern, '_off');
		},
	out : function(){
		var pattern = new RegExp('_on','gi');
		this.src = this.src.replace(pattern, '_off');
		}
	};
/*
------------------------------------------------------------
Adds extra domain fields in the purchase area, 
as well as keeping track of how many domains are entered
============================================================
*/
var addDomains = {
		optField : Object,
		optGroup : Object,
		fields : Array,
		fieldCount : Number,
		optFields : Object,
	init: function(){
		if(!$('domain1')){return;}
			this.optField = $('domain1');
			this.optGroup = this.optField.parentNode;
			this.createGroup();
			this.fields = this.optGroup.getElementsByTagName('input');
			this.fieldCount = this.fields.length;
			this.addText();
			this.assignEvents();
		
		},
	createGroup : function(){
		insertAfter(this.optGroup,domEl('div', '', {id:'domainControls'}));
		},
	addText: function(){
		var domainControls = $('domainControls');
		domEl('a', '+ Add another domain', {style : 'margin:0.3em;', href : 'javascript:;', id : 'addLink'}, domainControls);
		domEl('a', '- Remove a domain', {style : 'margin:0.3em', href : 'javascript:;', id : 'removeLink'}, domainControls);
		domEl('a', 'Clear domains', {style : 'margin:0.3em', href : 'javascript:;', id : 'resetLink'}, domainControls);
		Event.observe($('addLink'), 'mouseover', function(){window.status='Add another domain'; return true;});
		Event.observe($('addLink'), 'mouseout', function(){window.status='';return true;});
		Event.observe($('removeLink'), 'mouseover', function(){window.status='Remove a domain'; return true;});
		Event.observe($('removeLink'), 'mouseout', function(){window.status='';return true;});
		Event.observe($('resetLink'), 'mouseover', function(){window.status='Clear domains'; return true;});
		Event.observe($('resetLink'), 'mouseout', function(){window.status='';return true;});
		Event.observe($('addLink'), 'click', this.addField);	
		Event.observe($('removeLink'), 'click', this.removeFields);	
		Event.observe($('resetLink'), 'click', this.resetFields);	
		},
	addField : function(){
		var clear = document.createElement('br');
		var divGroup = document.createElement('div');
		var label = document.createElement('label');
		var fieldCount = addDomains.countFields();
		fieldCount = fieldCount+1;
		var labelT = document.createTextNode('http://');
		var optID = 'domain'+fieldCount;
		label.setAttribute('for', optID);
		label.appendChild(labelT);
		
		divGroup.id = optID+'Group';
		
		var field = document.createElement('input');
		field.id = optID;
		field.setAttribute('id', optID);
		field.setAttribute('name', 'domains[]');
		field.className = 'text licensed_domains';
		field.setAttribute('autocomplete', 'off');
		
		divGroup.appendChild(label);
		divGroup.appendChild(field);
		divGroup.appendChild(clear);
		addDomains.optGroup.appendChild(divGroup);
		Event.observe(field, 'keyup', addDomains.tallyCost.bindAsEventListener(field));
		},
	resetFields : function(){
		var resetConf = confirm('Are you sure you want to delete all of the domains you\'ve entered?');
		
		if(resetConf){
			var divs = addDomains.optGroup.getElementsByTagName('div');
			divs.length.times(function(n){if(divs[0]){
										 addDomains.optGroup.removeChild(divs[0]);
										 }
										 });
			$('domain1').value = '';
			var tallyDiv = $('tallyDomains')
			if(tallyDiv){
				tallyDiv.innerHTML = '';
				addDomains.hideTally();
				}
		}
	},
	countFields : function(){
		this.Fields = this.optGroup.getElementsByTagName('input');
		return this.fieldCount = this.Fields.length;
	},
	removeFields : function(){
			divs = $A(addDomains.optGroup.getElementsByTagName('div')).last();
			if(divs){
				addDomains.optGroup.removeChild(divs);
				}
			addDomains.domainCount();
			
	},
	tallyCost : function(){
		var domain = $F(this);
		this.value = domain.replace(/([^A-Za-z0-9\-.])/gi,''); 
		addDomains.domainCount();
		},
	domainCount : function(){
		this.domainsTotal = Array();
		var inputs = this.fields;
		$A(this.fields).each(function(el){
		   var val = $F(el).replace(/([^A-Za-z0-9\-.])/gi,'');
		   if(val !== ''){
			this.domainsTotal.push(val);
			   } else {
			this.domainsTotal.without(el);
			}
		   }.bind(this));
		addDomains.insertTally(this.domainsTotal);
		},
	insertTally : function(arr){
		this.create();
		var div = $('tallyDomains');
		var numDomains = arr.length;
		var total = Math.round((numDomains * 15.99)*100)/100;
		var tallyDiv = $('tallyDomains');
		tallyDiv.innerHTML = 'Purchasing <span id="numDomains">'+numDomains+'</span> cop' +((numDomains !== 1) ? 'ies' : 'y')+ ' of Expanse for only <span id="costTotal">&#163;'+total+'</span>';
		if(numDomains == 0){
			addDomains.hideTally();
			} else if(numDomains > 0 && !tallyDiv.visible()){
				addDomains.showTally();
				}
		},
	create : function(){
		if(!$('tallyDomains')){
			var tallyDiv = domEl('div', '', {id:'tallyDomains'});
			insertAfter($('domainControls'), tallyDiv);
			insertAfter(tallyDiv, domEl('br', '',{id:'tallyDomainsClear'}));
			}
		},
	showTally : function(){
		$('tallyDomains').show();
		$('tallyDomainsClear').show();
		},
	hideTally : function(){
		$('tallyDomains').hide();
		$('tallyDomainsClear').hide();
		},
	assignEvents : function(){
			$A(this.fields).each(function(el){
				Event.observe(el, 'keyup', this.tallyCost.bindAsEventListener(el));
			}.bind(this));
		}
	
};
/*
------------------------------------------------------------
This is a proof of concept.
Not used, but might come in handy in the future.
============================================================
*/
var labelize = {
	init : function(){
		var labels = document.getElementsByTagName('label');
		var input, ltext;

		$A(labels).each(function(l){
		 ltext = l.getAttribute('htmlFor') ? l.getAttribute('htmlFor') : l.getAttribute('for');
		 input = $(ltext);
		 if(input.type == 'password'){
			 console.log('password');
			throw $continue;
			 }
		 if(input && input.tagName.toLowerCase() == 'textarea' || input.tagName.toLowerCase() == 'input'){
			input.value = l.firstChild.nodeValue;
			if(l.className == 'required'){
				input.value += '*';
				}
			Event.observe(input,'focus', function(){
			var  fieldText = l.firstChild.nodeValue;
			 if(l.className == 'required'){
				fieldText += '*';
				}
			  if(this.value == fieldText){
				  this.value = '';
				  }
			  }.bindAsEventListener(input));
			Event.observe(input,'blur', function(){
			var  fieldText = l.firstChild.nodeValue;
			 if(l.className == 'required'){
				fieldText += '*';
				}
			  if(this.value == ''){
				  this.value = fieldText;
				  }
			  }.bindAsEventListener(input));
			l.id = 'label_'+input.id;
			 }
			 l.style.visibility = 'hidden';
			
		 });
		}
	};
/*
------------------------------------------------------------
domEl() was developed primarily by Pawel Knapik
(http://pawel.saikko.com/), but I (Nate Cavanaugh) 
made some nice additions. This essentially allows you to 
easily create DOM nodes.
Personally, I prefer it to the scriptaculous Builder.
============================================================
*/
var domEl = function(e,c,a,p,x) {
if(e||c) {
	c=(typeof c=='string'||(typeof c=='object'&&!c.length))?[c]:c;	
	e=(!e&&c.length==1)?document.createTextNode(c[0]):e;	
	var n = (typeof e=='string')?document.createElement(e) : !(e&&e===c[0])?e.cloneNode(false):e.cloneNode(true);	
	if(e.nodeType!=3) {
		c[0]===e?c[0]='':'';
		for(var i=0,j=c.length;i<j;i++) typeof c[i]=='string'? ((c[i] =='') ? '': n.appendChild(document.createTextNode(c[i]))):n.appendChild(c[i].cloneNode(true));
		if(a) {
			for (var i in a) i=='class'?n.className=a[i]:(i == 'style')?n.style.cssText=a[i]:n.setAttribute(i,a[i]);}
	}
}
	if(!p)return n;
	p=(typeof p=='object'&&!p.length)?[p]:p;
	for(var i=(p.length-1);i>=0;i--) {
		if(x){while(p[i].firstChild)p[i].removeChild(p[i].firstChild);
			if(!e&&!c&&p[i].parentNode)p[i].parentNode.removeChild(p[i]);}
		if(n){
			if(!document.all){
				p[i].appendChild(n.cloneNode(true));
				} else {
				if(n.canHaveChildren){
					p[i].appendChild(n.cloneNode(true));
				} else if(p[i].canHaveChildren) {
				p[i].appendChild(n.cloneNode(false));			
				} else {
					p[i].parentNode.appendChild(n);
					}
				}
			} 
	}	
}
/*
------------------------------------------------------------
Stolen from my man Dustin (dustindiaz.com), but I detect
those cases in which people forget to add the input type
and it defaults to text. Shockingly common.
This adds a class to the input boxes of the type that it is
hence a text box can be styled with input.text and a checkbox
can be styled with input.checkbox, etc etc
============================================================
*/
function appendInputTypeClasses() {
	if ( !document.getElementsByTagName )
	return;
var inputs = document.getElementsByTagName('input');
var inputLen = inputs.length;
var type;
	for ( i=0;i<inputLen;i++ ) {
		if ( inputs[i].getAttribute('type') ){
		type = inputs[i].getAttribute('type');
		type = (type !== '') ? type : 'text';
		inputs[i].className += ' '+inputs[i].getAttribute('type');
		}
	}
}
/*
------------------------------------------------------------
Stolen from my man Dustin (dustindiaz.com) but I shortened
the argument list.
============================================================
*/
function insertAfter(referenceNode, node) {
	referenceNode = $(referenceNode);
	referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}
/*
------------------------------------------------------------
Based upon the work of 
Torsten Baldes (http://medienfreunde.com) from his jQuery
fader. Ported by Nate Cavanaugh for use with MooFX, 
Prototype, and Dean Edwards Base.js
============================================================
*/
var innerfade = Base.extend({
	constructor : function(options){
	this.list = $(options.list);
	this.speed = options.speed || 'normal';
	this.timeout  = options.timeout || 2000;
	this.type = options.type || 'sequence';
	this.containerheight = options.containerheight || 'auto';
	this.guessTimeout = options.guessTimeout || false;
	this.op = Array;
	this.run();
	},
	run : function(){
	var list = this.list;
	var elements = $A(this.list.getElementsByTagName('li'));
	if(elements.length < 1){return;}
	list.parentNode.style.position = 'relative';
	list.style.height = this.containerheight;
	var lquote = new RegExp('“','gi');
	var rquote = new RegExp('”','gi');
	elements.each(function(el, index){
		el.style.zIndex = elements.index - 1;
		el.style.position = 'absolute';
		el.innerHTML = el.innerHTML.replace(lquote, '<span class="quotes ql">“</span>');
		el.innerHTML = el.innerHTML.replace(rquote, '<span class="quotes qr">”</span>');
		this.op[index] = new fx.Opacity(el, {duration: this.speed});
		this.op[index].hide();
	}.bind(this));
	var words = elements[0].innerHTML.split(' ').length;
	this.timeout = (this.guessTimeout == true) ? this.getRate(elements[0]) : this.timeout;
	
	if ( this.type == 'sequence' ) {
				setTimeout(function(){
					this.next(elements, 1, 0, this.op);
				}.bind(this), this.timeout);
				this.op[0].custom(0,100);
			}
			else if ( this.type == 'random' ) {
			
				setTimeout(function(){
					var current;
					do { current = Math.floor ( Math.random ( ) * ( elements.length ) ); } while ( current == 0 )
					this.next(elements, current, 0, this.op);
				}.bind(this), this.timeout);
				this.op[0].custom(0,100);
			}
			else {
				alert('type must either be \'sequence\' or \'random\'');
			}
	},
	next : function(elements, current, last, op){
	op[last].toggle();
	op[current].toggle();
	if ( this.type == 'sequence' ) {
		if ( ( current + 1 ) < elements.length ) {
			current = current + 1;
			last = current - 1;
		}
		else {
			current = 0;
			last = elements.length - 1;
		}
	}
	else if ( this.type == 'random' ) {
		last = current;
		while (	current == last ) {
			current = Math.floor ( Math.random ( ) * ( elements.length ) );
		}
	}
	else {
		alert('type must either be \'sequence\' or \'random\'');
	}
	this.timeout = (this.guessTimeout == true) ? this.getRate(elements[last]) : this.timeout;
	setTimeout((function(){this.next(elements, current, last, op);}.bind(this)), this.timeout);
	},
	getRate : function(el){
	var words = el.innerHTML.split(' ').length;
	var wps = 5;
	
	while(words <= wps*2){
	words += words; 
	}
	return Math.ceil(words/wps) * 1000;
	}

});
Element.addMethods({
      innerfade: function(element,options) { 
	  options.list = element.id;
	  new innerfade(options); 
	  }
    });
var inFade = {
	init : function(){
		if(!$('testimonials')){return;}
		$('testimonials').innerfade({speed: 750,
					timeout: 10000,
					type: 'random',
					containerheight:'11em',
					guessTimeout : true});
		}
	}
/*   Call to sIFR   //-------------------------------*/
var _sIFR = {
	init : function(){
		if(typeof sIFR == "function"){
			sIFR.replaceElement("#page_content h2", named({sFlashSrc: "/css/memphis_bold.swf", sColor: 
"#004A80", sCase: "lower",sHoverColor:'#EE097C'}));

			}
		}
	};
/*   Simple little page loader function wrapper.   //-------------------------------*/
var page = {
	init : function(){
		inFade.init();
		charityDetails.init();
		appendInputTypeClasses();
		inputOvers.init();
		addDomains.init();
		_sIFR.init();
		}
	};
Event.onDOMReady(page.init);