
/*
	setup_toggle()	
	James Dacosta 03/07 d0
	function that hides and shows form elements
	DEPENDENCIES:
		uses EJ written by Robert Nyman, http://www.robertnyman.com
		standard.js
		uses addLoadEvent written by Simon Willison

	USAGE:
	
		the associated function init_toggle() initialises the
		id's involved in the toggle
		

		id's of the element to be toggled
		toggle[0].elements			=  ["element1","element2",element3];

		id of the element which triggers the toggle
		toggle[0].trigger			= "trigger2";

		id of the element which reverses the toggle
		toggle[0].reverse			= "reverse2";

		id's of the elements which should be made required when made visible
		elements 1 & 3 will be made required and element 2 will remain optional
		toggle[0].required			= ["element1",false,"element3"];

		function init_toggle() {
			var toggle = new Array();
			var risk = toggle[0] = [];
			risk.elements			= ["section-date","section-premium"];
			risk.trigger			= "risk-insurance_0";
			risk.reverse			= "risk-insurance_1";
			risk.required			= ["date","premium"];
			...
			setup_toggle(toggle);
		}
*/
function setup_toggle(toggle) {
	for (var ix = 0; ix < toggle.length; ix ++) {
		_setup_single_toggle(toggle[ix]);
	}
}

function _setup_single_toggle(toggle) {

	for (var n = 0; n < toggle.elements.length; n++) {
		var el = jQuery('#' + toggle.elements[n]);
		if (!el) {
			return false;
		}
		el.addClass('tab-section');

		// initially hide the element to be toggled

		if (!jQuery('#' + toggle.trigger)[0].checked) {
			el.addClass('hidden');
		} else if (toggle.required && toggle.required[n]) {
			if(!jQuery('#' + toggle.elements[n])) {
				return false;
			}
			var label = el.find("label")[0];
			if (label) {
				var required = document.createElement("em");
				var requiredText = document.createTextNode("required");
				required.appendChild(requiredText);
				label.appendChild(required);
			}
		}
	}

	if (toggle.trigger == toggle.reverse) {
		// Toggle on a checkbox element
		jQuery('#' + toggle.trigger).click(function () {
			switch_toggle = (this.checked) ? _open_toggle : _close_toggle;
			switch_toggle(toggle);
		});
	} else {
		jQuery('#' + toggle.trigger).click(function() { _open_toggle(toggle); });
		if (toggle.reverse) {
			jQuery('#' + toggle.reverse).click(function() { _close_toggle(toggle); });
		}
	}
}

// add/remove classes depending on element clicked
function _open_toggle(toggle) {

	for (var n = 0; n < toggle.elements.length; n++) {
		el = jQuery('#' + toggle.elements[n])
		if (!el) {
			return false;
		}
		el.addClass('tab-section');
		el.show()

		if (toggle.required[n]) {
			// writes "<em>Required</em>" inside the associated label tag for this field
			// optional fields cannot be set as required in the database but they can be 
			// dynamically added to the required fields array (see example usage above)
			var label = el.find("label")[0];
			if (label) {
				var required = document.createElement("em");
				var requiredText = document.createTextNode("required");
				required.appendChild(requiredText);
				label.appendChild(required);
			}
		}
	}
}


function _close_toggle(toggle) {

	var fieldTypes = ['input','textarea','select','radio'];
	for (var n = 0; n < toggle.elements.length; n++) {

		var el = jQuery('#' + toggle.elements[n]);
		if (!el) {
			return false;
		}
		for (var k = 0; k < fieldTypes.length; k++) {

			// reset the value/selected index of the hidden field
			if (el.find(fieldTypes[k]).length > 0) {

				var e = el.find(fieldTypes[k])[0];

				if (e.type=='radio' || e.type=='checkbox') {
					el.find(fieldTypes[k]).each(
						function () { this.checked = false; }
					);
				} 
				switch (fieldTypes[k]) {
					case 'input':
						e.value = "";
						break;
					case 'textarea':
						e.value = "";
						break;
					case 'select':
						e.selectedIndex = 0;
						break;
				}
			}
		}

		el.hide();

		if (toggle.required[n]) {	
			if (!jQuery('#' + toggle.required[n])) {
				return false;
			}
		}
	}
}

/*
	setup_transfers()	
	James Dacosta 03/07 d0
	function that copies data from/to specified fields
	DEPENDANCIES: uses EJ written by Robert Nyman, http://www.robertnyman.com
				  standard.js
				  
				  Also uses addLoadEvent written by Simon Willison
	USAGE:
			the associated function init_transfers() initialises the
			fields involved in data transfer and the triggers/reverse elements
			
			list of source fields
			transfers[0].from			= ['name',		'address1'];
			
			list of target fields
			transfers[0].to				= ['targ_name',	'targ_address1'];
			
			id's of elements to trigger the copy and cut of the data
			transfers[0].trigger		= ['trigger1'];
			transfers[0].reverse		= ['reverse1'];
			
			
			function init_transfers()
			{
				
				var transfers = new Array();
				
				transfers[0]				= [];
				transfers[0].from			= ['name',		'address1'];
				transfers[0].to				= ['targ_name',	'targ_address1'];
				transfers[0].trigger		= ['trigger1'];
				transfers[0].reverse		= ['reverse1'];
				
				transfers[1]				= [];
				transfers[1].from			= ['postcode'];
				transfers[1].to				= ['comment'];
				transfers[1].trigger		= ['is-invoice-address'];
				transfers[1].reverse		= ['is-not-invoice-address'];
				
				// easier way  (one reference to index)
				var addressCopy = transfers[2] = [];
				addressCopy.from			= ['home-postcode'];
				addressCopy.to				= ['business-postcode'];
				addressCopy.trigger			= "trigger-id";
				addressCopy.reverse			= "reverse-id";
				
				setup_transfers(transfers);
				
			}	
*/

function setup_transfers(transfers) {
	for (var i = 0; i < transfers.length; i++) {
	
		// check for the existence of key objects
		if (!$(transfers[i].trigger) || !$(transfers[i].reverse)) {
			return false; 
		}
	
		//assign the current object to props for referencing within onclick
		$(transfers[i].trigger).props = $(transfers[i].reverse).props = transfers[i];
		
		//copy all the values across
		$(transfers[i].trigger).onclick = function() {
			var k = 0;
			while(k < this.props.to.length) {
				$(this.props.to[k]).value = $(this.props.from[k]).value;
				k++;
			}
		}
		//remove all the values
		$(transfers[i].reverse).onclick = function() {
			var k = 0;
			while(k < this.props.to.length) {
				$(this.props.to[k]).value = "";
				k++;
			}
		}
	}
}

/*
	init_helptext()	
	James Dacosta 03/07 d0
	function that prepares help popups
	USAGE:
		add the class "help" to a tags next to input fields e.g. 
		<input class="text" id="address1" /> <a href="#help1" title="helpful information" id="helpfor_input-element-id" class="help">help</a>
		
		use dl constructs for each help panel and give each an id related to the a tag e.g.
		
		<dl id="help1">
			<dt>this is the title or query</dt>
			<dd>this is the explanation</dd>
		</dl>
		
		then add:
		addLoadEvent(init_helptext); or onload="init_helptext();"
		
		users without javascript will be jumped to the associated help - users with javascript will have the popup
		
	EXTRAS:
	
		Give the help link an id of "helpfor_" + the associated input field id
		uncomment the link in the closehelp() function //$(associatedFieldId).focus();
		when the help panel is closed the associated help panel will get focus();
		 
*/
function init_helptext(transfers) {

	// Remove anchor if there is one
	var this_page = document.location.href.replace( /\#.*/, '' );

	jQuery('#helpnotes dl').addClass('hide-help');
	jQuery('a.help').each(function() {

		// transforms http://url/#id to id
		var currentHelpPopup = this.href.replace(this_page, '').replace("#", '');
		
		// pass the id of the current popup to the current object 
		this.currentHelpPopup = currentHelpPopup;
		
		// initialise a global reference to the last popup
		document.lastHelpPopup;
		
		// add onclick events for all the help links
		this.onclick = function() {
			if (!jQuery('#' + this.currentHelpPopup).length) {
				return false;
			}
			
			var currentHelpPopupHelp = jQuery('#' + this.currentHelpPopup)[0];
			var lastHelpPopup = jQuery('#' + document.lastHelpPopup)[0];
			var currentlHelpLink = this;
			var currentQuestion = jQuery(currentHelpPopupHelp, 'a')[0];
			
			var close_help = function () {
				jQuery(currentHelpPopupHelp).addClass('hide-help');
				jQuery(currentHelpPopupHelp).removeClass('show-help');
				currentHelpPopupHelp.status = !currentHelpPopupHelp.status;
				return false;
			}
			currentQuestion.onclick = close_help;

			//only create the close link once
			if (!currentHelpPopupHelp.hasClose) {
				var closeLink = document.createElement("a");
				closeLink.href = "#";
				jQuery(closeLink).addClass("close");
				var closeText = document.createTextNode("close");
				closeLink.onclick = close_help;
				closeLink.appendChild(closeText);
				currentHelpPopupHelp.appendChild(closeLink);
				currentHelpPopupHelp.hasClose = true;
			}
			
			// if there was previously a popup and it's not the currently
			// requested popup then hide the previous popup and set its status to false
			if (lastHelpPopup && (lastHelpPopup.id != currentHelpPopupHelp.id)) {
				jQuery(lastHelpPopup).removeClass("show-help");
				jQuery(lastHelpPopup).addClass("hide-help");
				lastHelpPopup.status = false;
			}
			
			// every requested popup should be false initially
			// if not hide the current popup
			if (currentHelpPopupHelp.status) {
				jQuery(currentHelpPopupHelp).addClass('hide-help');
				jQuery(currentHelpPopupHelp).removeClass('show-help');
			} else {
				//otherwise position the requested popup and show it
				var labelID = this.id.replace("helpfor_", 'helpLocatorfor_' );
				currentHelpPopupHelp.style.top = (
					jQuery('#' + labelID).offset().top
					- jQuery('#quoteForm').offset().top
				) + "px";
				currentHelpPopupHelp.style.right = "60px";
				jQuery(currentHelpPopupHelp).addClass('show-help');
				jQuery(currentHelpPopupHelp).removeClass('hide-help');
				jQuery('#helpnotes').addClass('show-block');
			}
			// assign the current popup to the last popup global
			document.lastHelpPopup = this.currentHelpPopup;
			
			// switch the status of the currently requested popup
			currentHelpPopupHelp.status = !currentHelpPopupHelp.status;
			return false;
		}
	});
}


function init_buttons_altext() {
	if (!$('page-nav')) {
		return false;
	}
	var b = $('page-nav').getElementsByTagName('input');
	
	if (b) {
		var i;
		for (i = 0; i < b.length; i++) {
			
			b[i].onmouseover = function() {
				if (!document.getElementById('top-buttons')) return false;
				altText = document.createTextNode(this.value);
				alt.className="alt-text";
				alt.appendChild(altText);
				document.getElementById('top-buttons').appendChild(alt);
			}

			b[i].onmouseout = function() {
				if (!document.getElementById('top-buttons')) return false;
				document.getElementById('top-buttons').removeChild(alt);
			}
		}
	}
}

// function to give hover effects to input buttons
function init_buttons() {
	var b1 = $('submit').getElementsByTagName('input');
	if (b1) {
		var i;
		for (i = 0; i < b1.length; i++) {
			b1[i].onmouseover = function(){
				this.src = this.src.replace('.gif','_over.gif');
			}
			b1[i].onmouseout = function(){
				this.src = this.src.replace('_over.gif','.gif');
			}
		}
	}
}

 // give alternate rows the class 'altrow' for styling
function stripeForm() {
	jQuery('#quoteForm ol li').each(function (ix) {
		if (this.id != 'submit' && ix % 2 == 1) {
			jQuery(this).addClass("altrow")
		}
	});
}

// attaches an onclick for the Need help? link
function helpPopup() {
	if (!document.getElementById("formhelp") || !document.getElementById("footerhelp") || !document.getElementById("footerhelpicon")) return false;
	var helplink = document.getElementById("formhelp").getElementsByTagName("A")[0];
	var helplink2 = document.getElementById("footerhelp");
	var helplink3 = document.getElementById("footerhelpicon");
	helplink2.onclick = helplink3.onclick = helplink.onclick = function(){
		window.open("/static/form_help.html","_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=yes, width=550, height=690")
		return false;
	}
}

function highlightErrors() {
	jQuery('strong.error').parents('li').addClass('highlight-error');
}
