(function () { eval( JELLY.unpack() );

var SCRIPT_NAME = "faq";
var SPLIT_MARKER = "__RADIO_RUNNER__";
var WORLDPAY_USER = 0;


// so head

Dialog.init('/_assets/images/skin/bg/dialog.png', 
	'/_assets/images/skin/bg/dialog-close.png');
Feedback.init();
Growl.init();
var GET = parseQuery();
var protocol = window.location.protocol;
var checkSessionTimeout = function (r) {
	if ( r.responseText.indexOf('<!--SESSION_INVALID') === 0 ) {
		evalScripts( r.responseText );
		return false;
	}
	return true;
};
var onPageValid = function () {trace( 'onPageValid() unspecified' );};
var onPageInvalid = function () {trace( 'onPageInvalid() unspecified' );};
var dimButton = function (id) { setOpacity( getElement(id), .4 ); };
var undimButton = function (id) { setOpacity( getElement(id), 1 ); };

var getRequest = function ( opts ) {
	var basicOpts = { "onSuccess": checkSessionTimeout, "feedback": Feedback };
	return new Request( extend( basicOpts, opts || {} ) );
};
var request = getRequest( { "cleanUp": false } );
var request2 = getRequest( { "cleanUp": false } );
var windowScroller = new Scroll(window);

var getControlFile = function (href) { return href.replace(/(scripts\/)/, '$1ctrl-'); };
var redirect = function (href) { window.location.href = href; };
var refresh = function (query) { 
	window.location.href = query !== false ? window.location.href : window.location.pathname; 
};

var verifyStep = function (btn, callback) {
	btn = getElement(btn);
	if (btn) { btn.onclick = function (e) { callback.call(btn, e); }; } 
};

var resetClasses = function () {
	toArray( this.getElementsByTagName('*') ).each(function (el) {
		removeClass(el, 'radio-selected');
	});
};
var radioRoutines = function () {
	Q('table.tbl-grid, ul.list-packages').each(function (root) {
		Q(root, 'input[type=radio]:checked').each(function (el) {
			addClass(el.parentNode.parentNode.parentNode, 'radio-selected');
		});
		Q(root, 'span.radio-wrapper').each(function (el) {
			var radio = el.getElementsByTagName('input')[0];
			el.onclick = function () {
				resetClasses.call(root);
				addClass(this.parentNode.parentNode, 'radio-selected');
				radio.checked = true;
			};
			radio.onfocus = function () { addClass(this.parentNode, 'focus'); }
			radio.onblur = function () { removeClass(this.parentNode, 'focus'); }
		});
	});
};
radioRoutines();

if ( 'timeout' in GET && protocol !== 'https:') {
	Growl.show('You are now logged out <br />(Session expired)');
}

//	Station toggling
//
var stationToggling = function ( file, feed, callback ) {
	Q('#list-stations li input').each(function (el) {
		el.onmousedown = stopEvent;
		el.onclick = function (e) {
			e = stopEvent(e);
			if ( request.inProgress || request2.inProgress ) { 
				return false;
			}
			toggleClass(this.parentNode, 'disabled');
			var ids = [];
			Q('#list-stations li:not(.disabled) input').each(function (el) {
				ids.push(el.name.split('btn_stationupdate_')[1]);
			});
			if (! isDefined(ids[0]) ) {
				toggleClass( this.parentNode, 'disabled' );
				alert('You must add at least 1 station to your order');
				return;
			} 
			var data = 'stationupdate=' + ids.join('.');
			if ( isFunction( feed ) ) {
				data += '&' + feed();
			}
			else {
				data += feed ? '&' + feed : '';
			}
			request.post( 'scripts/'+ file +'.php', data, function (r) {
				callback.call(this, r);
				stationToggling( file, feed, callback ); 
			});
		};
	});
};

var updateCosts = function ( voucher, callback ) {
	var file = '/scripts/cost-update.php' + (voucher ? '?voucher=' + voucher : '');
	var updateRequest = getRequest();
	updateRequest.send('get', file, function (r) {
		parseCostUpdateResponse( r.responseText );
		if ( callback ) {
			callback();
		}
	});
};

var parseCostUpdateResponse = function (result) {
	if ( !result ) {
		return;
	}
	trace(result);
	var problems = [],
		voucherDiscountId = 'fee-voucher-discount',
		result = result.trim().split('|');
	if ( result[0] === '' && !isDefined( result[1] ) ) {
		return;
	}
	result.each(function (o) {
		var parts = o.split('::'), m;
		if ( m = /INVALID_([A-Z]{2,})/.exec( parts[0] ) ) {
			problems.push( m[1] );
			if ( m[1] === 'VOUCHER' ) {
				problems.voucherError = parts[1].split('+')[0];
				withElement( voucherDiscountId, function (el) {
					addClass(el.parentNode, 'hide');
					el.innerHTML = '';
				});
			}
		}
		var cost = parts[1].split('+')[0];
		var isVoucher = parts[0] === voucherDiscountId;
		withElement(parts[0], function (el) {
			if ( el.nodeName.toLowerCase() === 'input' ) {
				el.value = cost;
				return;
			} 
			if ( isVoucher ) { 
				removeClass(el.parentNode, 'hide');
			} 
			el.innerHTML = (isVoucher ? '&minus;':'') + '&pound;' + cost.replace(/(\d+)(\d{3})/, '$1,$2');
		});
	});
	
	if ( problems[0] ) {
		problems.each(function (prob) {
			switch ( prob ) {
				case 'COMM': 
					alert( 
						'Your Selected Commercial is not available with this\n' + 
						'station combination during your campaign dates\n\n' + 
						'Please update your commercial choice, or change your station combination'
					);
					break;
				case 'PACKAGE': 
					alert( 
						'Your Selected Airtime Package is not available with this\n' + 
						'station combination during your campaign dates\n\n' + 
						'Please update your airtime package choice, or change your station combination'
					);
					break;
				case 'VOUCHER': 
					alert( problems.voucherError );						
					break;
				case 'TOTAL':
					refresh();
					break;
			}
		});
	} 
	// If no worldpay problems, and there is no worldpay form, reload page
	else if ( !inArray( 'TOTAL', problems ) && WORLDPAY_USER && !getElement( 'worldpay-form' ) ) {
		refresh();
	}
	else {
		Growl.show( 'Costs have been updated' );
	}
};





(function () { // so faq

var commOptionsList;
if ( commOptionsList = getElement('commercial-options') ) {

	var commOptions = Q('#commercial-options li').map(function (el) {
			return { container: el, handle: getFirst(el) };
		}),
		hideCommOption = function (obj) {
			addClass(obj.container, 'collapsed-faq');
		},
		showCommOption = function (obj) {
			removeClass(obj.container, 'collapsed-faq');
		};
		
	commOptions.each(function (obj) {
		hideCommOption(obj);
		obj.container.onclick = function (e) {
			e = fixEvent(e);
			addClass( commOptionsList, 'active' )
			var target = e.target.nodeName.toLowerCase();
			if (target === 'select') { return true; }
			if ( !hasClass(this, 'collapsed-faq') && target === 'h2' ) { 
				hideCommOption(obj);
				removeClass(commOptionsList, 'active');
				return; 
			} 
			commOptions.each( hideCommOption );
			showCommOption( obj );
		};
	});
}



})();


(function () { // so cosmetics


// Cosmetic enhancement
//

if (!browser.ie6) { 
	Q('ul.list-fields li:nth-child(even)').each(function (el) {	addClass(el, 'alt'); });
}

if ( Q('table.sortable')[0] ) {
	loadModule( 'JELLY.SortTable', '_assets/js/sorttable.js', 
		function (mod) { 
			mod.init(); 
		});
}

})();


(function () { // so login-dynamics


//
// Login / Logout / Retrieve password / Change password
//
var loginDynamics = function () {
	Q('#login input.text').each(function (el) {
		var label = Q('#login label[for=' + el.id + ']')[0];
		label.style.position = 'absolute';
		label.style.left = '-999em';
		el.defaultText = label.innerHTML;
		el.value = el.defaultText;
		if (el.type === 'password') {
			var passwordClone = createElement( 'input', {
					'type': 'text', 'class': el.className + ' default', 
					'name': el.name, 'id': el.id, 'value': el.value
				}),
				passwordOriginal = replaceElement( el, passwordClone );
			passwordClone.onfocus = function () {
				if ( passwordOriginal.value === passwordOriginal.defaultText ) {
					passwordOriginal.value = '';
				}
				replaceElement( this, passwordOriginal );
				setTimeout( function () {passwordOriginal.focus();}, 10 );
			};
			passwordOriginal.onblur = function () {
				if ( /^\s*$/.test( this.value ) || this.value === this.defaultText ) {
					replaceElement( this, passwordClone );
				}
			};
		} else {
			addClass(el, 'default');
			el.onfocus = function () { 
				if (this.value === this.defaultText) {
					this.value = '';
					removeClass(this, 'default');
				} 
			};
			el.onblur = function () { 
				if (/^\s*$/.test(this.value)) {
					this.value = this.defaultText;
					addClass(this, 'default');
				} 
			};
		}
	});

	var passwordLink = getElement('link-reset-password');
	if ( passwordLink ) { 
		passwordLink.onclick = function (e) {
			stopEvent(e);
			request.send('get', '/scripts/ctrl-forgotten-password.php', function (r) {
				Dialog.setContent( r.responseText ).open( 450 );
				forgottenPassword();
			});
		};
	}

	// allow for 2nd reset link on screen
	var passwordLinkAlt = getElement('link-reset-password-alt');
	if ( passwordLinkAlt ) { 
		passwordLinkAlt.onclick = function (e) {
			stopEvent(e);
			request.send('get', '/scripts/ctrl-forgotten-password.php', function (r) {
				Dialog.setContent( r.responseText ).open( 450 );
				forgottenPassword();
			});
		};
	}

/*
	var loginBtn = getElement('btn-login');
	if ( loginBtn ) { 
		loginBtn.onclick = function (e) {
			stopEvent(e);
			var host = window.location.hostname,
				path = (host === 'location' ? 'http://':'https://') + host + '/scripts/ctrl-login.php';
				data = path + '?' + Request.getFieldData( Q('#login input') );
			request.send('post', data, function (r) {
				var res = r.responseText;
				var testDoc = createElement('div', {setHTML: res});
				if ( Q(testDoc, 'input')[1] ) {
					evalScripts(res);
					getElement('login').innerHTML = res;
					loginDynamics();
				} else {
					refresh(false);
				}
			});
		};
	}
	var logoutLink = getElement('link-logout');
	if ( logoutLink ) { 
		logoutLink.onclick = function (e) {
			stopEvent(e);
			request.send('get', getControlFile( this.href ), function (r) {
				redirect('index.php');
			});
		};
	}*/
};
loginDynamics();

var forgottenPassword = function () {
	withElement('btn-reset-password', function (el) {
		el.onclick = function (e) {
			stopEvent(e);
			var data = Request.getFieldData( Q('#reset-password input') );
			request.send('post', '/scripts/ctrl-forgotten-password.php?' + data, function (r) {
				Dialog.setContent(r.responseText);
				forgottenPassword();
			});
		};
	});
};

withElement('link-change-password', function (el) {
	el.onclick = function (e) {
		stopEvent(e);
		request.send('get', getControlFile( this.href ), function (r) {
			Dialog.setContent(r.responseText).open( 450 );
			changePassword();
		});
	};
});
var changePassword = function () {
	withElement('btn-change-password', function (el) {
		el.onclick = function (e) {
			stopEvent(e);
			var data = Request.getFieldData( Q('#change-password input') );
			request.send('post', '/scripts/ctrl-change-password.php?' + data, function (r) {
				Dialog.setContent(r.responseText);
				changePassword();
			});
		};
	});
};


})();


// so jplayer

var setupJPlayer = function () {
	var mp3Links = Q( 'td.td-listen a' );
	if ( !mp3Links[0] ) return;
	var callback = function () {
		var player = $(containerId);
		var resetClasses = function () { 
			mp3Links.each(function (el) { 
				removeClass(el, 'playing'); 
				el.playing = false;
			});
			player.stop();
		};
		mp3Links.each(function (mp3) {
			mp3.onclick = function (e) {
				e = stopEvent(e);
				if ( !mp3.playing ) { 
					resetClasses();
					player.changeAndPlay( this.href );
					addClass(this, 'playing')
					this.playing = true;
				} else {
					player.stop();
					removeClass( this, 'playing' );
					this.playing = false;
				}
			};
		});
		var playerLoaded = false;
		var feedbackCalled = false;
		player.onSoundComplete( resetClasses );
		player.onProgressChange( function (pc) {
				if ( playerLoaded ) { return; } 
				if ( pc < 100 ) {
					Feedback.start();
				} else if ( pc >= 100 ) {
					Feedback.stop(); 
					playerLoaded = true;
				} 
			});
	};
	var caller = arguments.callee,
		container = 'jPlayerContainer',
		containerId = '#' + container,
		initPlayer = function () {
			$( containerId ).jPlayer({ swfPath: '_assets/jplayer', ready: callback });
		};
	if ( !caller.insert ) {
		insertElement( createElement('div', {'id':container}) );
		caller.insert = true;
	} 
	if (!caller.assetsLoaded) {
		loadModules( ['jQuery', 
					  window.location.protocol + "//ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"],
					 ['jQuery.jPlayerCount', "_assets/jplayer/jquery.jplayer.js"],
				function (success) {
					if (success) { 
						caller.assetsLoaded = true; 
						initPlayer();
					}
				}
			);
	} else {
		initPlayer();
	}
}; 
setupJPlayer();





// so general-ui

var focusFinder = function () {
	var map = {
		'btn-view-packages': ['campaign-length', 'campaign-first-week'],
		'btn-apply-voucher': 'voucher-code',
		'btn-ad-search': 'select-ad-search',
		'btn-search-buscat': 'bus-cat-search',
		'btn-input-geo': 'input-geo'
	};
	for ( var key in map ) {
		if ( !getElement(key) ) {	continue; }
		var els = isArray( map[key] ) ? map[key] : [map[key]];
		els.each(function (el) {
			if ( !(el = getElement(el)) ) { return; }
			if ( browser.firefox ) { 
				el.setAttribute('autocomplete', 'off'); 
			}
			var btn = key; // Need to store in this callback closure
			addEventOnce(el, 'keydown', function (e) {
					//stopEvent(e);
					if ( e.keyCode && e.keyCode === 13 ) { 
						getElement(btn).focus();
					}
				});
		});
	}
};
focusFinder();

var wizardNav = function () {
	var postActive = false;
	Q('#nav-wizard li').each(function (el, i) {
		if ( hasClass(el, 'active') ) { postActive = true; }
		if ( postActive && hasClass(el, 'history') && /step-\d/.test(SCRIPT_NAME) ) {
			el.onclick = function () {
				var message = [
					'Navigating away from this page now will lose any changes you have made',
					'\n\n',
					'To save your changes click Save and proceed',
					'\n'
				].join('');
				return confirm(message);
			}; 
		
		}
	}); 
};
wizardNav();


JELLY.PhatTips = {
	
	tooltip: createElement( '#tooltip' ),
	tooltipTimer: null,
	tooltipInserted: null,
	
	showTip: function ( e, el ) {
		var self = this;
		if ( self.tooltipInserted ) { return; }
		self.tooltip.innerHTML = retrieveData( el, 'titleHTML' );
		self.tooltip.style.top = '';
		self.tooltip.style.left = '';
		insertElement( self.tooltip );
		self.tooltipInserted = true;
		
		var offset = { x: 0, y: 24 },
			viewport = getViewport(),
			viewportWidth = ( viewport[0] - 15 ),
			viewportHeight = viewport[1],
			xPos = e.pageX + offset.x,
			yPos = e.pageY + offset.y,
			tooltipWidth = self.tooltip.offsetWidth;
		
		if ( tooltipWidth > 200 ) {
			//self.tooltip.style.width = '200px';
		}
		if ( ( e.clientX + tooltipWidth ) > viewportWidth ) {
			xPos = e.pageX + 10 - tooltipWidth;
		}

		setXY( self.tooltip, xPos, yPos );
	},
	
	hideTip: function ( el ) {
		var self = this;
		if ( !self.tooltipInserted ) { return; }
		removeElement( self.tooltip );
		self.tooltip.style.width = '';
		self.tooltipInserted = false;
	},
	
	init: function ( str ) {
		var self = this;
		self.tooltipLinks = Q( str );
		
		self.tooltipLinks.each( function (el) {
			storeData( el, 'title', el.title );
			storeData( el, 'titleHTML', el.title.
					replace(/_([^_]+)_/g, '<em>$1</em>').
					replace(/\*([^\*]+)\*/g, '<strong>$1</strong>')				
				);
			
			addEventOnce( el, 'mousemove', function (e) {
				clearTimeout( self.tooltipTimer );
				self.tooltipTimer = setTimeout( function () {
						self.showTip( e, el );
					}, 300 );
			});

			addEventOnce( el, 'mouseenter', function (e) {
				this.setAttribute( 'title', '' );
			});

			addEventOnce( el, 'mouseleave', function (e) {
				this.setAttribute( 'title', retrieveData( this, 'title' ) );
				clearTimeout( self.tooltipTimer );
				self.hideTip( el );
			});
			
		});
	}
};

//JELLY.PhatTips.init( 'a[title]' );







// so konami

addEvent(window, 'load', function () {
	var seq = [38,38,40,40,37,39,37,39,66,65];
	var score = 0;
	var cssText = 'position:fixed;top:18%;right:-200px;';
	var roadRunner = createElement('img', {style: cssText, src: '/_assets/images/skin/roadrunner.png'});
	var kTween = new Tween(roadRunner, {duration: 2000});
	kTween.setTransition('linear').onComplete = function () { 
		removeElement(roadRunner); 
		roadRunner.style.cssText = cssText;
	};
	addEvent(document, 'keydown', function (e) {
		if ( e.keyCode && e.keyCode === seq[score] ) {
			score++;
			if ( !seq[score] ) {
				trace('beep beep');
				insertElement(roadRunner);
				kTween.start('right', 2000);
				score = 0;
			}
		} 
		else { 
			score = 0;
		}
	});
});


})(); // End Closure