
//------------------- helper variables ---------------------------------

var _vars = {
	links		: null,		// to match links id and href
	ssIds		: null,		// home page slide show - slide ids
	ssIndex 	: 1,		// home page slide show - slide index
	newsIds		: null,		// home page news ticker - slide ids
	newsIndex 	: 1,		// home page news ticker - slide index
	g			: null,		// stores gallery object
	toPage		: ''		// where page being transferred after link click
};

//------------------- handler functions ---------------------------------

var call = {

	toggleTbl: function( id, n ) {
		var tbl 	= ( _vars && _vars.tbl ? _vars.tbl[id] : null );
		if( tbl ) {
			if( n < 0 ) {
				if( tbl.toggleTable() ) {
					//makeCorners();
				}
			} else {
				if( tbl.toggleRow( n ) ) {		// showed  a new row
					//makeCorners();
				}
			}
		}
	},	

	startGScroll: function( el, dn ) {
		anim.arrow.press( el );
		_vars.g._timeout = setInterval( function() { call.gScroll( dn ); }, 200 );
	},

	stopGScroll: function( el ) {
		anim.arrow.release( el );
		clearInterval( _vars.g._timeout );
	},

	gScroll: function( dn ) {
		_vars.g.scroll( dn, null );
	},

	gMove: function( el, x0, x1, cb ) {
		var callback 	= function() { cb(); anim.progressBar.update() };
		var m 			= new Fx.Morph( el, { 
			duration: 		150, 
			transition: 	'sine:out',
			onComplete:		callback 
		} );
		
		m.start( { 'left': x1 } );
	},
	
	fSubmit: function( id ) {
		var f = document.getElementById( id );
		if( f && validate( f ) ) {
			//alert( 'Thank you for submitting your information. Our representative will contact you shortly.' );
			f.submit();
		}
	}
	
}

//-------------------  shortcut  functions to make objects ---------------------------------

var make = {

	gallery: function( itemsId, itemId, leftArrowId, rightArrowId ) {
		_vars.g = new PA.widgets.scrollableGallery( document, itemsId, itemId, leftArrowId, rightArrowId, anim.arrow.on, anim.arrow.off, call.gMove );
		_vars.g.init( anim.progressBar.update );
		setup.gItemsHover();	
	},

	collapsibleTable: function( targetId, nRows, uncollapsibleRows ) {	// handles creation of table for already rendered html
		var rows 	= new Array( nRows );
		for( var i in uncollapsibleRows ) {
			rows[ uncollapsibleRows[i] ]	= [ 0,0,1 ];
		}
		var state 	= ( -1 == uncollapsibleRows ? -1 : 1 );
		
		make._collapsibleTable( 'tbl', targetId, targetId, rows, 
								[ '<div class="rowToggle show" onclick="call.toggleTbl(\'' + targetId + '\')"><big>&nbsp;&nbsp;&nbsp;</big></div>expand all&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 
								'<div class="rowToggle hide" onclick="call.toggleTbl(\'' + targetId + '\')"><big>&nbsp;&nbsp;&nbsp;</big></div>collapse all&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
								], state, 1 );		
	},

	_collapsibleTable: function( tblClass, tblId, targetId, contentHtml, captionHtml, expanded, shown ) {
		if( !_vars.tbl ) {
			_vars.tbl 	= {};
		}
		var tbl 		= _vars.tbl[tblId] 	= new top.PA.widgets.CollapsibleTable( document, 'call.toggleTbl', tblId, targetId, tblClass, '', [ 'rowEven', 'rowOdd' ], [ 'tblCaptionLeft', 'tblCaptionRight' ], contentHtml, captionHtml, expanded, shown );
		//tbl.render();
		return tbl;
	},

	imageFlow: function( id ) {
		var noReflect 	= ( PA.utils.DOM.isChrome() );		// glitch: in IE, reflections don't show, and in Chrome reflection is 100%...
		var mf 			= new MooFlow( $( id ), {
			startIndex:			3,
			//useSlider: 			true,			// no slider
			loop:				true,		// note: if using loop, must not use slider... (b/c loop works only in positive direction + scrollbar is not peridic)
			//useAutoPlay: 		true,				// no buttons
			useCaption: 		true,
			useResize:	 		false,
			useMouseWheel: 		false,
			useKeyInput:	 	false,
			useViewer: 			true,
			useWindowResize: 	true,
			offsetY: 			20,
			heightRatio: 		( noReflect ? 0.5 : 0.55 )
		} );
		mf.play();	// start autoplay on load
	},

	imageZoomer: function( selectors ) {
		window.addEvent( 'load', function() { 
			ReMooz.assign( selectors, {
				'origin': 			'img',
				'shadow': 			'onOpenEnd',
				'resizeFactor': 	0.8,
				'cutOut': 			false,
				'opacityResize': 	0.4,
				'dragging': 		false,
				'centered': 		true
			} );
			
			setup.thumbsHover();
		} );
	},
	
	autocomplete: function( id, tokens, pages, hints, hintsRef ) {
		var addEntry = function( token ) {
			var choice 			= new Element( 'li' );
			new Element( 'a', { 
				'html': 	this.markQueryValue( token ),
				'href':		( pages[token] || null ),
				'target': 	'_self',
				'id':		token + '_'
			} ).inject( choice );
			
			new Element( 'a', {
				'class': 	'searchHint',
				'html': 	hints[token],
				'href':  	( hintsRef[token] || null ),
				'target': 	'_self',
				'id':		token
			} ).inject( choice );
			choice.inputValue 	= token;
			this.addChoiceEvents( choice ).inject( this.choices );
/////			setup.links( true );		// NOTE this callback, in order to switch pages nicely
		}

		new Autocompleter.Local( id, tokens, {
			'minLength': 		1, // We wait for at least one character
	//		'overflow': true // Overflow for more entries
			'minLength': 		1,
			'selectMode': 		'pick',
			'injectChoice': 	addEntry,
			width: 				250,
			filterSubset : 		true,
			leftOffset: 		0,
			topOffset: 			-1
		} );		
	},
	
	randomHTMLContent: function( id, arr ) {
		if( !arr || !arr.length ) {
			return;
		}
		var n 				= Math.floor( Math.random() * arr.length );
		$( id ).innerHTML 	= arr[n]; 
	},
		
	video: function( doc, targetId, nameVid, nameImg, nameSkin, nameCfg, w, h ) {
		return make._video( doc, targetId, 'media/videos/jw_player/jw_flv_player.swf', '../' + nameVid, 'media/videos/' + nameImg, 'media/videos/jw_player/'+nameSkin, 'media/videos/jw_player/' + nameCfg, w, h );
	},
	
	_video: function( doc, targetId, pathPlayer, pathVid, pathImg, pathSkin, pathCfg, w, h ) {
		var v = new SWFObject( pathPlayer, targetId + '_obj', w, h, '9' );	// pathPlayer relative to the page with video
		v.addParam( 'allowfullscreen', 		'true' );
		v.addParam( 'allowscriptaccess', 	'always' );
		v.addParam( 'wmode', 				'opaque');
		v.addParam( 'author', 				'QoE Systems');
		v.addParam( 'flashvars', 			'file=' + pathVid + 	// relative to the swf player
											'&image=' + pathImg + 	// relative to the page with video
											'&skin=' + pathSkin + 	// Hmm for some reason doesn't work...
											'&config=' + pathCfg	// relative to the page with video
					);
		
		v.write( doc.getElementById( targetId ) );
		return v;
	}
	

}

//------------------- animations ---------------------------------

var anim = {
	
	_gItemOn: false,
	
	content: {
	
		fadeIn: function( cb ) {		
/*		
			var els						= $$( '.pageHolder' );
			els.each( function( el ) {
				el.setStyle( 'opacity', 0 );
				el.style.visibility		= 'visible';
				
				el.set( 'tween', { 
////					duration: 	500, 
duration: 	5, 
					transition:	'quad:in',
					onComplete: cb					// TODO: this callback will fire many times..
				} ).tween( 'opacity', 0, 1 );
			} );	
*/			
		},
		
		fadeOut: function( cb ) {
			anim.header._hideMenu();
			var selector = [ '.content', '.footer' ];
			if( !anim._toHomePage() ) {
				selector.push( '.pageHeader .cc' );
			}
			
			$$( selector ).each( function( el ) { 
				el.set( 'tween', { 
////					duration: 	300, 
duration: 	5, 
					transition:	'quad:out',
					onComplete: ( cb ? cb : function() {} )
				} ).tween( 'opacity', 1, 0.01 );		//  don't fade out completely to preserve page layout
			} );
		}
		
	},
	
	header: {
	
		resize: function( cb ) {
			anim.header._hideMenu();
			var expand			= anim._isHomePage();
			var cback	 		= cb;	//function() { anim.content.fadeOut( cb ); };
			if( !expand && !anim._toHomePage() || expand && anim._toHomePage() ) {
				if( cback ) {
					cback();
				}
				return;
			}
			
			anim.header._disablePage();
			var t 				= [ 500, 800 ];	// anim duration
			var stroke			= [ 'quad:in:out', 'cubic:out' ];
			var obj				= [ $$( '.pageHeader .cc' )[0], $( 'pageHolder' ) ];
			var fn				= [ anim.header._vertical, anim.header._horizontal ];
			var callback 		= function() { anim.header._disablePage(); cback(); };
//			obj[0].className 	+= ' expanding';	// for home page header to change
			
			var i 				= ( expand ? 0 : 1 );
			var k 				= ( expand ? 1 : 0 );			
////			fn[i]( obj[i], expand, t[i], stroke[i], function(){ 
////				fn[k]( obj[k], expand, t[k], stroke[k], callback ); 
////			} );
callback();
			
		},

		showTitle: function() {
			setTimeout( function() { 
							new Fx.Morph( $( 'headerTitleCover' ), { duration: 1 } ).start( { width: 0, left: 720 } ); 
						}, 1 );
		},
		
		_vertical: function( el, expand, duration, anim, cb ) {
			var m 		= new Fx.Morph( el, { 
				duration: 		duration, 
				transition: 	anim,
				onComplete: 	cb
			} );			
			m.start( { 'height': ( expand ? 175 : 26 ) } );			// values from header.css
		},

		_horizontal: function( el, expand, duration, anim, cb ) {
			var w 				= parseInt( Math.max( document.body.scrollWidth * 0.90, 930 ) );	// values from canvas.css
			if( !expand ) {
				el.style.width	= w;	// this is for IE (who could think?) not to jerk first frame of animation
			}
			el.set( 'tween', {
				duration: 		duration,
				transition: 	anim,
				onComplete: 	cb
			} );
			el.tween( 'width', ( expand ? w : 950 ) );		// width of home page, canvas.css
		},
		
		_hideMenu: function() {
			$$( '.menu ul' ).each( function( el ) { el.style.visibility = 'hidden'; } );
			//$$( '.menu ul li' ).removeClass( 'hover' );
		},
		
		_disablePage: function() {
			var div 				= document.createElement( 'div' );
			var b					= document.body;
			b.insertBefore( div, b.firstChild );
			div.style.position		= 'absolute';
			div.style.width			= b.scrollWidth + 'px';
			div.style.height		= b.scrollHeight + 'px';
			div.style.zIndex		= 10000;
			div.innerHTML			= '&nbsp;';
			div.id					= '__PAGE_COVER__';
		},

		_enablePage: function() {
			if( document.body.firstChild.id == '__PAGE_COVER__' ) {
				document.body.removeChild( document.body.firstChild );	
			}			
		}		
		
	},
	
	arrow: {
		on: function( el ) {
			new Fx.Morph( el, { duration: 100 } ).start( { width: 24 } ); 					
			//			el.set( 'tween', { duration: 200 } ).tween( 'width', 24 );	// IE breaks here, why?
		},

		off: function( el ) {
			new Fx.Morph( el, { duration: 100 } ).start( { width: 5 } ); 		
			//			el.set( 'tween', { duration: 200 } ).tween( 'width', 5 );	// IE breaks here, why?
		},

		press: function( el ) {
			el.className 	+= ' pressed';
		},

		release: function( el ) {
			el.className	= el.className.replace( / pressed/, '' );
		}
	},
	
	gItem: {	
		
		on: function() {
			anim.gItem._scale( this, 15, 20, -10, -5 );								
		},
		off: function() {
			anim.gItem._scale( this, 0, 0, 0, 0 );
		},
		_scale: function( el, dh, dw, dleft, dtop ) {	// here I take absolute size values from CSS, to make sure image always returns to original size
			new Fx.Morph( el.getElement( 'img' ), { duration: 150 } ).start( { 	
				left: 	0 + dleft, 
				top: 	0 + dtop*2,
				width:	110 + dw,
				height:	80 + dh + dtop
			} ); 
			new Fx.Morph( el.getElement( '.gItemPic' ), { duration: 150 } ).start( { 	
				marginTop: 	0 + dtop
			} ); 			
		}
		
	},
	
	thumb: {	
		
		on: function() {
			anim.thumb._scale( this, 20, 20, -10, -10 );			
		},
		off: function() {
			anim.thumb._scale( this, 0, 0, 0, 0 );
		},
		_scale: function( el, dh, dw, dleft, dtop ) {	// here I take absolute size values from CSS, to make sure image always returns to original size
			new Fx.Morph( el.getElement( 'img' ), { duration: 150 } ).start( { 	
				left: 	10 + dleft, 
				top: 	10 + dtop,
				width:	80 + dw,
				height:	80 + dh
			} ); 					
		}
		
	},
	
	progressBar: {
		update: function() {
			var N						= _vars.g.getNHiddenItems();
			var bar						= document.getElementById( 'gProgressBar' );
			var dots					= bar.childNodes;
			var nDots					= dots.length;
			if( N < nDots ) {
				bar.style.visibility	= 'hidden';
				return;
			}
			var p			 			= _vars.g.getCurrentProgress();
			//var n						= parseInt( Math.floor( ( dots.length - 1 ) * p ) );
			var n						= parseInt( Math.floor( ( nDots - 0.5 ) * ( p + 0.5/nDots ) ) );
			for( var i in dots ) {
				dots[i].className		= ( n == i ? 'active' : 'inactive' );
			}
		}
	},
	
	menu: {
		show: function() {
			var ul			= this.getElement( 'ul' );
			if( ul ) {
				ul.setStyle( 'opacity', 0 );			
				anim.menu._fx	= new Fx.Morph( ul, { duration: 300 } ).start( { opacity: 1 } );
//			ul.set( 'tween', { duration: 2000 } ).tween( 'opacity', 1 );			
			}
		},
		
		hide: function() {
			if( anim.menu._fx ) {
				anim.menu._fx.cancel();
				anim.menu._fx	= null;
			}
			var ul				= this.getElement( 'ul' );
			if( ul ) {
				ul.setStyle( 'opacity', 0 );
			}
		},
		
		_fx: null
	},

	form: {
		toggle: function( f, focused, txt ) {
			if( !f ) {
				return;
			}
			if( focused ) {
				f.className 	= f.className.replace( / blurred/g, '' );
				f.value			= '';
			} else {
				f.className		+= ' blurred';
				if( 'undefined' != typeof( txt ) ) {
					f.value		= txt;
				}
			}
		},
		
		focus: function( f ) {
			if( !f ) {
				return;
			}
			f.className 		= f.className.replace( / blurred/g, '' );
			f.select();
		},

		reset: function( f ) {
			if( !f || !f.form ) {
				return;
			}
			ff 					= f.form.getElementsByTagName( 'input' );
			for( var i in ff ) {
				ff[i].value 	= '';
			}				
		}		
		
	},
	
	_isHomePage: function() {
		return ( window.location.href.indexOf( 'index' ) >= 0 );
	},

	_toHomePage: function () {
		return ( _vars.toPage.indexOf( 'index' ) >= 0 );
	},
	
	slideShow: {
		switchSlide: function() {
			var n				= _vars.ssIds.length;
			_vars.ssIndex 		= _vars.ssIndex % n;
			if( 0 == _vars.ssIndex ) {
				$$( '.content-t-l-slide' ).each( function( el ) { el.style.zIndex = 0; } );
			}
			var el = $$( '#' + _vars.ssIds[_vars.ssIndex] )[0];

			el.style.zIndex		= _vars.ssIndex + 1;
			el.fade( 'hide' );
			new Fx.Morph( el, { duration: 4500, transition: Fx.Transitions.Sine.easeOut } ).start( { 'opacity': 1 } ); 
			_vars.ssIndex++;
		}
	}

}

//----------------------------- interface setup functions -------------------------------

var setup = {

	links: function( refresh ) {		// to precede switching page with animation
		if( !refresh ) {
			_vars.links					= {};
		}
		var links 					= $$( 'a', 'map area' );
		for( var i=0; i<links.length; i++ ) {
			var l 					= links[i];
			if( l.id && !_vars.links[ l.id ] ) {		// presence of id is criterion for page content animation on click (e.g. header collapse)
				_vars.links[ l.id ] = l.href;
				l.href 				= '#';
				l.onclick 			= function() { _leavePage( this.id ); };
			}
		}
	},

	menuIE6: function() {
		if( !PA.utils.DOM.ltIE7() ) {
			return;
		}		
		$$( '#nav li' ).each( function( el ) {
			el.onmouseover		= function( el ) {
				if( el ) {
					el.addClass( 'hover' );
					$( el.getFirst( 'ul' ) ).setStyle( 'visibility', 'visible' );
				}
			}
			el.onmouseout		= function( el ) {
				if( el ) {
					el.addClass( 'hover' );
					$( el.getFirst( 'ul' ) ).setStyle( 'visibility', 'hidden' );
				}
			}
		} );
	},
	
	submenuHover: function() {
		if( !PA.utils.DOM.isIE() ) {		// in IE it's too slow...
			$$( '.menu:first-child li' ).each( function( el ) {	// have to use MooTool's mouseEnter not to mess css hovers with onMouseOver
				el.addEvents( { mouseenter: anim.menu.show, mouseleave: anim.menu.hide } );
			} );
		}
	},

	gItemsHover: function() {
		$$( '.gItem' ).each( function( el ) {	// have to use MooTool's mouseEnter to prevent trembling on mouse move with onMouseOver
			el.addEvents( { mouseenter: anim.gItem.on, mouseleave: anim.gItem.off } );
		} );
	},

	thumbsHover: function() {
		$$( '.thumbs li' ).each( function( el ) {	// have to use MooTool's mouseEnter to prevent trembling on mouse move with onMouseOver
			el.addEvents( { mouseenter: anim.thumb.on, mouseleave: anim.thumb.off } );
		} );
	},

	autocomplete: function() {
		var tokens 	= [ 	'Q-Master Video Software', 
							'Q-Master Speech Software',
							'Q-Master Video System',
							'Q-Master Voice System',
//							'NETQUAL Monitoring',
							'PESQ Algorithm',
							'PESQ Basic Plus Algorithm',
							'PESQ Advanced Algorithm'//,
//							'NQ-Lab System'						
						];
		var _pages 	= [ 	'QMasterVideoSW.html',  
							'QMasterSpeechSW.html',
							'QMasterVideoSystem.html',
							'QMasterVoiceSystem.html',
//							'NETQUAL.html',
							'PESQ.html',
							'PESQBasicPlus.html',
							'PESQAdvanced.html'//,
//							'NQLab.html'						
						];
		var _hints 	= [ 	'Video',  
							'Audio',
							'Video',
							'Audio',
//							'Audio',
							'Audio',
							'Audio',
							'Audio'//,
//							'Audio'
						];
		var _hintsRef 	= _pages;
		var pages 		= {};
		var hints 		= {};
		var hintsRef 	= {};
		for( var i=0; i<tokens.length; i++ ) {
			pages[ tokens[i] ] 		= _pages[i];
			hints[ tokens[i] ] 		= _hints[i];
			hintsRef[ tokens[i] ] 	= _hintsRef[i];
		}		
		make.autocomplete( 'search_box', tokens, pages, hints, hintsRef );
	},
	
	slideShow: function() {	
		mySlideShow = new SlideShow( 'slideShow', {
			delay: 		6000,
			transition: 'fade',
			duration: 	500,
			autoplay: 	true
		} );	
		mySlideShow.play(); 
		
		_vars.ssIds = [];
		$$( '.content-t-l-slide' ).each( function( el ) {	_vars.ssIds.push( el.id ); } );
		var n 					= _vars.ssIds.length - 1;
		if( n > 0 ) {
			$$( '.content-t-l-slide' )[0].style.zIndex = 1;
			setInterval( anim.slideShow.switchSlide, 6000 );
		}	
		
	},

	newsTicker: function() {
		$( 'newsTickers' ).playSlideShow( { delay: 6000, transition: 'pushDown' } );
	}
	
}

//----------------------------- misc functions -------------------------------

function _leavePage( anchorId ) {
	_vars.toPage 		= _vars.links[ anchorId ];
	anim.content.fadeOut( function() { 
		setTimeout( function() { window.location.href = _vars.toPage; }, 50 );		// without timeout page reverts to sustituded href in setup.links()
	} );
}

function preloadImages( path, imgs ) {
	if( document.images ) {
		for( var i=0; i<imgs.length; i++ ) {
			var img 	= new Image();
			img.src 	= path + imgs[i];
		}
	}
}

function validate( f ) {
	function isEmpty( nm ) {
		var f_			= f[nm];
		return ( !f_ || '' == f_.value );
	}
	function isPhone( nm ) {
		var f_			= f[nm];
		var re3digit	= /\d{3}$/;
		return ( f_.value.search( re3digit ) >= 0 );
	}
	function fillEmpty( nm ) {
		var f_			= f[nm];
		if( f_ && '' == f_.value ) {
			f_.value 	= '-';
		}
	}

	var err 		= '';
	var ff, name;
	do {
	
	
	
		name = 'firstName'; 	ff = f[name]; 	if( isEmpty( name ) ) 	{ err 	= 'your first name'; 	break; }
		name = 'lastName'; 		ff = f[name]; 	if( isEmpty( name ) ) 	{ err 	= 'your last name'; 	break; }
		name = 'title'; 		ff = f[name]; 	if( isEmpty( name ) ) 	{ err 	= 'your title'; 		break; }
		name = 'company'; 		ff = f[name]; 	if( isEmpty( name ) ) 	{ err 	= 'your company'; 		break; }
		name = 'phone'; 		ff = f[name]; 	if( isEmpty( name ) || !isPhone( name ) ) 	{ err 	= 'your phone'; 		break; }
		ff 				= f.email;
		if( ff && ( ff.value.indexOf( '@' ) < 0 || ff.value.indexOf( '.' ) < 0 ) ) {
			err 		= 'valid email address';
			break;
		}
		/*ff 				= f.phone;
		temp 			= ( ff ? ff.value : null );
		var numbers		= ( temp ? temp.match( /\d/g ) : [] );
		if( numbers.length != 10 && numbers.length != 11 ) {
			err 		= 'valid phone number';
			break;
		}
		*/		
		fillEmpty( 'title' );
		fillEmpty( 'howFound' );
		fillEmpty( 'plan' );
		fillEmpty( 'hasScanner' );
		fillEmpty( 'newsletter' );
		fillEmpty( 'msg' );		
	} while( false );
	
	if( err ) {
		alert( 'Please enter ' + err + '.' );
		ff.select();
		return false;
	}
	return true;
}














