var TwoConnect = {

	start: function(){
		if( $('myajaxmenu') ) TwoConnect.headerLinks();
		if( $('footer') ) TwoConnect.footerLinks();
		if( $('flashGames_Navigation') ) TwoConnect.FlashGames.sideBarNavigation();
		if( $('canvasArea') ) {
			TwoConnect.canvasAreaTabs();
			TwoConnect.canvasAreaLinks();
			TwoConnect.columnLinks();
			TwoConnect.canvasSwitch( TwoConnect.getURLParam() );
			//TwoConnect.drawForm();
			TwoConnect.canvasProductIconBounce();
			TwoConnect.banner_mpls();
			TwoConnect.banner_Olympics();
			//TwoConnect.banner_Products();
			//console.log('we are before 1st wifi');
			if(!$('WiFi'))
			{
				TwoConnect.canvasDescriptionSlides();
				TwoConnect.serviceIcons();
			
			}
		}
		TwoConnect.formActiveFields();
	    if(!$('WiFi'))
	    {
	    TwoConnect.searchForm();
	    TwoConnect.customerLoginForm();
	    }

		TwoConnect.initializeMultiBox();
		TwoConnect.initializeEmptyOverlay();
				
		if( $('CallMe') ){
			TwoConnect.form_CallMe();
		}
		//console.log('we are before 2nd wifi');
		if($('WiFi'))
		{
			//console.log( "wifi present: begin" );
			TwoConnect.form_WiFiSignUp();
			//console.log( "wifi present: end" );
		}
		
		if( $('NewsletterSubscribe') ){
			TwoConnect.form_NewsletterSubscribe();
		}
		
		if( $('products-and-services' ) )
		{
			TwoConnect.productsAndServices();
			TwoConnect.generalProductIconBounce();
			//TwoConnect.banner_Products();	
		}
		try{
		if($('ad_products')) // if the products div exists in the page call banner_Products() to add slide effect
		{
			TwoConnect.banner_Products();			
		}
		}
		catch(e)
		{
			//console.log(e);
		}
		if( $('YouTube-Videos') ) TwoConnect.YouTubeVideos();
		if( $$('table') ) 
			TwoConnect.colorTables();
		TwoConnect.loadAssets();
		
		// Calling Card Rates
		if( $('CallingCardRates') ){
			TwoConnect.Rates.assignClickActions();
		}
		
		if($('gameList'))
		{
			TwoConnect.FlashGames.toolTips();
			TwoConnect.FlashGames.runGame();
		}
	},

	loadAssets: function(){
		var spinner = new Asset.image( 'assets/images/templates/2connect/images/spinner.gif' );
		var accept = new Asset.image( 'assets/images/templates/2connect/images/check.png' );
		var deny = new Asset.image( 'assets/images/templates/2connect/images/error.png' );
	},
	
	getURLParam: function()
	{
		var url = parent.location.href
		var anchorPosition = url.lastIndexOf( '#' )+1;
		var result = url.substr( anchorPosition, url.length-anchorPosition );
		return result;
	/*
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	*/
	},
	
	gup: function( name ){
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	},
	
	canvasSwitch: function( target )
	{
		canvasTabs.activate( target );
	},
	
	footerLinks: function(){
		var fLinks = new slidingDoorButtons( 'footer', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:11, activeClass:'current', duration: 75 } );
	}, // end of footer links modification

	
	/* Modify the top navigation bar */
	headerLinks: function(){
		
		var timer = 0;
		var topLinks = $$('ul#myajaxmenu li a');

		var topLinksFXs = [];

		topLinks.each(function(el, i){
			
			el.setStyle('margin-top', '-100px');
			timer += 150;
			
			topLinksFXs[i] = new Fx.Style(el, 'margin-top', {
				duration: 400,
				transition: Fx.Transitions.backOut,
				wait: false
			});
			
			topLinksFXs[i].start.delay(timer, topLinksFXs[i], 0);
			
		});
		
		//*
		var ajaxMenu = $$('ul#myajaxmenu li a');
		ajaxMenu.each( function(el,i){
			
			var overFx = new Fx.Styles( el, {duration: 0, wait: false});
			
			if( !el.getParent().hasClass('current') )
			{
				el.addEvent( 'mouseenter', function(el){
					overFx.start({
						'border-bottom-width': 5
					});
				});
				
				el.addEvent( 'mouseleave', function(el){
					overFx.start({
						'border-bottom-width': 0
					});
				});
			}
		});
		//*/
	},//end of header links modification
	
	canvasAreaTabs: function(){
		canvasTabs = new mootabs('canvasArea', { 
			width: '744px', 
			height: '306px', 
			changeTransition: Fx.Transitions.Quad.easeOut,
			changeTransition: 'none',
			mouseOverClass: 'active',
			disableOver:	true,
			useAjax: false,
			// ajaxUrl: 'assets/templates/2connect/sendData.php',
			ajaxUrl: 'index.php',
			ajaxOptions: {method: 'get', data: {id: 47}},
			ajaxLoadingText: '<div style="width: 100%; height: 100%; margin: auto; text-align: center;"><p><img style="border: none;" src="assets/templates/2connect/animation-load.gif"></p></div>'
		}); 
	},
	
	canvasAreaLinks: function(){
		var cLinks = new slidingDoorButtons( 'main_navigation', {buttonHeight:34, buttonFinalPosition: -136, rightImageWidth:6, activeClass:'active', deactivateLinks:true, buttonFinalPosition: -136, scrollToElement:'canvasArea'} );
	},
	

	columnLinks: function(){
		//var col1Links = new slidingDoorButtons( 'column1', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:11, activeClass:'current', duration: 75} );
		//var col2Links = new slidingDoorButtons( 'column2', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:10, activeClass:'current', duration: 75} );
		var col3Links = new slidingDoorButtons( 'column3', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:11, activeClass:'current', duration: 75} );
		var col4Links = new slidingDoorButtons( 'column4', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:11, activeClass:'current', duration: 75} );
	
	},
	
	canvasProductIconBounce: function(){
		
		var containerID = 'canvas';
		var container = $(containerID);
		var productList = $$('#canvas ul.productList li' );
		var productIcons = $$('#canvas ul.productList li a img' );
		productIcons.each( function( el, idx ){
			el.fx = new Fx.Styles( el, {duration: 500, wait: false, transition: Fx.Transitions.Circ.easeOut } );
			productList[idx].addEvents({
				'mouseenter': function(){
					el.fx.start( { 'margin-top': '-8px' } );
					productIcons.each( function( element, index ) {
						if( index != idx ){
							element.fx.start( { 'margin-top': '0px' } );
						}
					});
				},
				'mouseleave': function(){
					el.fx.start( { 'margin-top': '0px' } );
				}
			});
		});
	},
	
	generalProductIconBounce: function(){
		var containerID = 'products-and-services'
		///var containerID = 'productList';
		var container = $(containerID);
		var productList = $$('#' + containerID + ' ul.productList li img' );
		productList.each( function( el, idx ){
			el.fx = new Fx.Style( el, 'margin-top', {duration: 350, wait: false, transition: Fx.Transitions.Circ.easeOut } );
			el.initialPaddingTop = '0px';
			el.addEvents({
				'mouseenter': function(){
					el.fx.start( '-8px' );
					productList.each( function(element, index){
						if( index != idx ){
							element.fx.start( el.initialPaddingTop );
						}
					});
				},
				'mouseleave': function(){
					el.fx.start( el.initialPaddingTop );
				}
			});
		});
		
	},
	
	canvasDescriptionSlides: function(){
		var pList = $$('.productList li');
		var holder = $('descriptionIntroduction');
		holder.fx = new Fx.Style( holder, 'opacity', {duration: 1000, wait: false} );
		
		pList.each( function(e, i){
			e.fxSlide = new Fx.Slide( e.title, {duration: 750, wait: false, mode: 'vertical'});
			e.fxFade = new Fx.Style( e.title, 'opacity', {duration: 250, wait: false } );
			e.fxSlide.hide();
			e.addEvents( {
				'mouseenter': function( event ){
					event = new Event( event );
					holder.fx.start( 0 );
					e.fxSlide.slideIn();
					e.fxFade.set( 1 );
					pList.each( function(el,ind){ if( el.title!=e.title ){ el.fxSlide.slideOut(); el.fxFade.hide(); } } );
					event.stop();
				},
				'mouseleave': function( event ){
					event = new Event( event );
					holder.fx.start( 1 );
					e.fxSlide.slideOut();
					e.fxFade.hide();
					event.stop();
				}
			});
		});
	},
	
	appearText: function(){
		var timer = 0;
		var topLinks = $$('#sidebar li');

		var slidefxs = [];
		var colorfxs = [];

		sideblocks.each(function(el, i){
			
			el.setStyle('margin-left', '-155px');
			timer += 150;
			
			slidefxs[i] = new Fx.Style(el, 'margin-left', {
				duration: 400,
				transition: Fx.Transitions.backOut,
				wait: false
			});
			
			slidefxs[i].start.delay(timer, slidefxs[i], 0);
			
		}, this);
	},
	
	formActiveFields: function(){
		// Add Color change behaviour for INPUT elements
		input = $$('input', 'select', 'textarea');
		
		input.each( function( e, i ){
			e.addEvents({
				'focus': function(){
					e.addClass('active');
				},
				'blur': function() {
					e.removeClass('active');
				}
			});
		});	
	},
	
	drawForm: function(){
		
		formID = 'draw_form';
		
		// Add Dynamic form
		$( formID ).addEvent('submit', function(e){
			new Event(e).stop();
			var target = $('drawResult');
			var errors = [];
			this.send({
				update: target,
				onComplete: function( returnedData ) {
					TwoConnect.afterFormSubmit( Json.evaluate( returnedData ), target, '' );
					target.removeClass('ajax-loading');
				}
			});
			target.empty().addClass('ajax-loading');
		});
		
	},
	
	customerLoginForm: function(){
		var loginForm = $('customer_login');
		var loginFormHandle = $('login_instructions');
		var collapsePosition = loginFormHandle.getSize().size.y - loginForm.getSize().size.y;
		
		loginForm.positions = [ collapsePosition, 0, collapsePosition ];
		loginForm.fx = new Fx.Style( loginForm, 'margin-top', { duration: 1000, wait: false } );
		
		loginForm.fx.start.delay(1000, loginForm.fx, loginForm.positions[0] );

		loginFormFunction = function(){
			if( loginForm.positions[2] == loginForm.positions[0] ){ 
					window.overlay.show();
					TwoConnect.hideAllFlash();
					loginForm.fx.start( loginForm.positions[1] ); 
					loginForm.positions[2] = loginForm.positions[1]; 
					$('login_instructions').innerHTML = 'CLOSE';
					$('customerLoginForm').txtLogin.focus();
					$('customer_login').style.zIndex = 10;
				}else{ 
					window.overlay.hide();
					TwoConnect.showAllFlash();
					loginForm.fx.start( loginForm.positions[0] ).chain(function(){$('customer_login').style.zIndex = 1}); 
					loginForm.positions[2] = loginForm.positions[0]; 
					$('login_instructions').innerHTML = 'CUSTOMER LOGIN';
				}
		};
		
		
		var footerLink = '';
		var my2cLoginLink = $$('#footer .sdNavigation a');
		my2cLoginLink.each( function( el, indx ){
			if( el.title == 'My2Connect Login' )
			{
				el.href = "javascript: void(0);";
				footerLink = el;
			}
		});
		
		[ loginFormHandle, footerLink ].each( function(e){
			e.addEvent( 'click', loginFormFunction );
			
		});
	},
	
	form_CallMe: function(){
		// The Call Me Form
		var formID = 'CallMe';
		
		// Add error holders
		inputFields = $$('#CallMe input', '#CallMe select', '#CallMe textarea');
		errorDivs = new Array();
		
		for( i=0; i<inputFields.length; i++)
		{
			if( $(inputFields[i].name) != null ){
				//console.log( $(inputFields[i].name) );
				errorDivs[i] = new Element( 'span', {
					'class': 'fixtThis',
					'id': 'errorsDiv_' + inputFields[i].name
				});
				errorDivs[i].injectBefore( inputFields[i].name );
			}
		}
		delete errorDivs;
		
		var rules=new Array();

		rules[0] = 'fName:First Name|required';
		rules[1] = 'fName|alphaspace';
		rules[2] = 'lName:Last Name|required';
		rules[3] = 'lName|alphaspace';
		rules[4] = 'company:Company|required';
		// rules[5] = 'company|alphaspace';
		rules[5] = 'title:Title|required';
		rules[6] = 'title|alphaspace';
		rules[7] = 'mobile:Mobile Number|required';
		//rules[8] = 'mobile|numeric';
		rules[9] = 'email:Email|required';
		rules[10] = 'email|email';
		rules[11] = 'productOfInterest:Product Of Interest|notequal|Select One';
		rules[12] = 'productOfInterest:Product Of Interest|required';

		// Add Dynamic form
		$( formID ).addEvent('submit', function(e){
			new Event(e).stop();
			if( performCheck('CallMe', rules, 'inline' ) )
			{
				var target = $('CallMeResult');
				var errors = [];
				this.send({
					update: target,
					onComplete: function( returnedData ) {
						TwoConnect.afterFormSubmit( Json.evaluate( returnedData ), target );
						target.removeClass('ajax-loading');
					},
					onFailure: function(){
						TwoConnect.afterFormSubmit( Json.evaluate( '{ "fail": true, "success": false, "message":"Failed" }' ), target );
						target.removeClass('ajax-loading');
					}
				});
				target.style.display = 'block';
				target.empty().addClass('ajax-loading');
				target.innerHTML = "<p>&nbsp;&nbsp;&nbsp; Please wait while we process your request. This may take a while.... </p>";
			}
		});
		
		/*
		 * Select the product automatically if coming from a products page
		 * A URL GET parameter 'product' will be used
		 */
		var product = TwoConnect.gup( 'product' ); // gup=Get URL Parameter
		if( product != '' )
		{
			var selectList = $(formID);
			var productListValues = new Array(
				Array( '2CALL', 1 ),
				Array( 'INTERNET', 2 ),
				Array( 'CALLINGCARDS', 3 ),
				Array( 'CPS', 4 ),
				Array( 'FIXEDLINETELEPHONY', 5 ),
				Array( 'HOSTING', 6 ),
				Array( 'IPLC', 7 ),
				Array( 'MPLS', 8 )
			);
			
			productListValues.each( function( el ){
				if( el[0] == product )
				{
					$(formID).productOfInterest.selectedIndex = el[1];
				}
			});
			
			
			
		}
	},
	form_WiFiSignUp: function(){
		// The Call Me Form	
		var formID = 'WiFi';
		//console.log('WiFi AJAX');
		// Add error holders
		inputFields = $$('#WiFi input', '#WiFi select', '#WiFi textarea');
		errorDivs = new Array();
		
		for( i=0; i<inputFields.length; i++)
		{
			if( $(inputFields[i].name) != null ){
				//console.log( $(inputFields[i].name) );
				errorDivs[i] = new Element( 'span', {
					'class': 'fixtThis',
					'id': 'errorsDiv_' + inputFields[i].name
				});
				errorDivs[i].injectBefore( inputFields[i].name );
			}
		}
		delete errorDivs;
/*		
		var validateMobileNumber = function() {
		    var msg;
		    console.log('Mobile Validation');
		    var reg_1 = new RegExp("^3[689][0-9]{6}$");
		    if ( reg_1.test($('mobileNumber').value) ) {
				msg = null;
			} else {
			    msg = 'Mobile Number Invalid.';
			}
			return msg;
		}
*/		
		var rules=new Array();

		rules[0] = 'fName:First Name|required';
		rules[1] = 'fName|alphaspace';
		rules[2] = 'lName:Last Name|required';
		rules[3] = 'lName|alphaspace';
		rules[4] = 'mobileNumber:Mobile Number|required';
		//rules[5] = 'mobileNumber|numeric';
		rules[5] = 'mobileNumber|regexp|^3[689][0-9]{6}$|Please enter a valid Bahrain Mobile Number';
		rules[6] = 'email:Email|required';
		rules[7] = 'email|email';
		
		//console.log('before add help');
		//yav.addHelp('WiFimobileNumber', 'Mobile phone number made out of 7 digits starting with the number 3 ');
		// Add Dynamic form
		$( formID ).addEvent('submit', function(e){
			new Event(e).stop(); //console.log('before check');
			if( performCheck('WiFi', rules, 'inline') )
			{
				//console.log('passed check');
				var target = $('WiFiResult');
				var errors = [];
				this.send({
					update: target,
					onComplete: function( returnedData ) {
						TwoConnect.afterFormSubmit( Json.evaluate( returnedData ), target );
						target.removeClass('ajax-loading');
						$('wifi_registration_container').style.display = 'none';
						//console.log('hide');
					},
					onFailure: function(){
						TwoConnect.afterFormSubmit( Json.evaluate( '{ "fail": true, "success": false, "message":"Failed" }' ), target );
						target.removeClass('ajax-loading');
					}
				});
				target.style.display = 'block';
				target.empty().addClass('ajax-loading');
				target.innerHTML = "<p>&nbsp;&nbsp;&nbsp; Please wait while we process your request. This may take a while.... </p>";
			}
		});
		
	},
/*	validateMobileNumber: function() {
	    var msg;
	    console.log('Mobile Validation');
	    var reg_1 = new RegExp("^3[689][0-9]{6}$");
	    if ( reg_1.test($('mobileNumber').value) ) {
			msg = null;
		} else {
		    msg = 'Mobile Number Invalid.';
		}
		return msg;
	},
*/	
	form_NewsletterSubscribe: function(){
		// The Call Me Form
		var formID = 'NewsletterSubscribe';
		
		// Add error holders
		inputFields = $$( '#NewsletterSubscribe input' );
		errorDivs = new Array();
		
		for( i=0; i<inputFields.length; i++)
		{
			if( $(inputFields[i].name) != null ){
				//console.log( $(inputFields[i].name) );
				errorDivs[i] = new Element( 'span', {
					'class': 'fixtThis',
					'id': 'errorsDiv_' + inputFields[i].name
				});
				errorDivs[i].injectBefore( inputFields[i].name );
			}
		}
		delete errorDivs;
		
		var rules=new Array();
		rules[0] = 'newsletter_email:Email|required';
		rules[1] = 'newsletter_email:Email|email';

		// Add Dynamic form
		$( formID ).addEvent('submit', function(e){
			new Event(e).stop();
			
			if( performCheck('NewsletterSubscribe', rules, 'inline' ) )
			{
				var target = $('NewsletterSubscribeResult');
				var errors = [];
				this.send({
					update: target,
					onComplete: function( returnedData ) {
						target.removeClass('ajaxLoading');
						TwoConnect.afterFormSubmit( Json.evaluate( returnedData ), target, $('NewsletterSubscribe') );
					}
				});
				target.style.display = 'block';
				target.empty().addClass('ajaxLoading');
			}
		});
		
	},
	
	afterFormSubmit: function( data, target, hideTarget )
	{
		
		if( data.fail == true ){
			target.setHTML( '<div class="error">' + data.message + '</div><div style="clear:both;">&nbsp;</div>' );
		}else if( data.success == true ){
			target.setHTML( '<div class="success">' + data.message + '</div><div style="clear:both;">&nbsp;</div>' );
			target.removeClass('ajax-loading');
			if( hideTarget ){ hideTarget.style.display = 'none'; }
		}else{
			target.setHTML( '<div class="error"> There was a critical error in processing the information. Please contact the webmaster. </div><div style="clear:both;">&nbsp;</div>' );
		}
	},
	
	productsAndServices: function(){
		var list_LI = $$('#products-and-services ul li');
		var target = $('product-others-title');
		list_LI.each( function(el, idx){
			el.addEvents({
				'mouseenter': function(){ 
					target.style.display = 'none';
				},
				'mouseleave': function(){
					target.style.display= 'block';
				}
			});
		});
	},
	
	banner_mpls: function(){
		var containerID = 'ad_mpls';
		var myGallery = new gallery( $( containerID ), {
			timed: true,
			showArrows: false,
			showInfopane: false,
			showCarousel: false,
			embedLinks: true,
			delay: 4000
		});
	},
	banner_Products: function(){
		try{
		var containerID = 'ad_products';
		var myGallery = new gallery( $( containerID ), {
			timed: true,
			showArrows: false,
			showInfopane: false,
			showCarousel: false,
			embedLinks: true,
			delay: 6250
		});
		}
		catch(e)
		{
			alert(e);
		}
	},
	banner_Olympics: function(){
		var containerID = 'ad_Olympics';
		var myGallery = new gallery( $( containerID ), {
			timed: true,
			showArrows: false,
			showInfopane: false,
			showCarousel: false,
			embedLinks: true,
			delay: 6250
		});
	},
	serviceIcons: function(){
		var container = $('service-icons');
		var myGallery = new gallery( container, {
			timed: true,
			showArrows: false,
			showInfopane: false,
			showCarousel: false,
			embedLinks: false,
			delay: 1500,
			defaultTransition: 'crossfade'
		});
		
		var random = function(){ return Math.floor( (Math.random()+1) * 10000 ); } // value in 10's (11-19)
		var clearMovement = myGallery.clearTimer.delay( random(), myGallery);
		
		container.addEvent( 'click', function(){
			var restartMovement = myGallery.prepareTimer();
			clearMovement = myGallery.clearTimer.delay( random(), myGallery);
		});

	},
	
	searchForm: function(){
		var searchForm = $('search');
		var searchFormTrigger = $('search_trigger');
		var searchFormClose = $('search_close');
		
		var searchFormBox = searchFormTrigger.getParent();
		searchFormBox.innerHTML = searchFormTrigger.innerHTML;
		searchFormClose.href = "javascript:void(0);";

		searchFormBox.addEvents({
			'click': function( event ){
				// searchForm.modal.modalShow();
				// window.mbox.overlay.show();
				window.overlay.show();
				searchForm.style.display = 'block';
				$('ajaxSearch_input').focus();
				TwoConnect.hideAllFlash();
			}
		});
		
		searchFormClose.addEvents({
			'click': function( event ){
				// searchForm.modal.modalHide();
				window.overlay.hide();
				searchForm.style.display = 'none';
				TwoConnect.showAllFlash(); 
			}
		});
	},
	
	initializeMultiBox: function(){
		window.mbox = new MultiBox('mb', {	
			useOverlay: true, 
			onOpen: function(){
				TwoConnect.activateModalContest();
				TwoConnect.hideAllFlash();
			},
			onClose: TwoConnect.showAllFlash,
			openFromLink: false,
			showControls: false,
			fixedTop: '35px'
		});
	},
	
	activateModalContest: function(){
		var formId = 'draw_form';
		var check = function( id ){ 
			if( $(id) ){
				var timer = window.myTimer;
				//TwoConnect.drawForm();
				$clear(timer);
			}
		};
		window.myTimer = check.periodical( 1000, null, formId );
	},
	
	initializeEmptyOverlay: function(){
		window.overlay = new Overlay({
			container: document.body, 
			onClick: function(){ 
				window.overlay.hide(); 
				TwoConnect.closeModalBoxes();
			}
		});
	},
	
	closeModalBoxes: function(){
		var loginForm = $('customer_login');
		$('search').style.display = 'none';
		loginForm.fx.start( loginForm.positions[0] ).chain(function(){$('customer_login').style.zIndex = 1}); 
		loginForm.positions[2] = loginForm.positions[0]; 
		$('login_instructions').innerHTML = 'CUSTOMER LOGIN';
		TwoConnect.showAllFlash();
	},
	
	YouTubeVideos: function(){
		$('YouTube-Videos').innerHTML = '<object width="530" height="370" class="flash"><param name="movie" value="http://www.youtube.com/p/8EACB317CA79370F"></param><embed src="http://www.youtube.com/p/8EACB317CA79370F" type="application/x-shockwave-flash" width="530" height="370"></embed></object>';
	},
	
	hideAllFlash: function(){
		$$('.flash').each( function(e){ e.style.display = 'none'; } );
	},
	
	showAllFlash: function(){
		$$('.flash').each( function(e){ e.style.display = 'block'; } );
	},
	
	colorTables: function(){

		$$('table').each( function(table,tindex){

			// Color the tBody 
			$A(table.tBodies[0].rows).each( function(row,rindex){
				if( rindex % 2 ){
					row.className = 'odd';
				} 
			}); 

			// Color the tHead
			if( table.tHead ){
				$A(table.tHead.rows).each( function(row,rindex){
					if( rindex % 2 ){
						row.className = 'odd';
					} 
				}); 
			}
		});
	},
	
	Rates: {
		
		assignClickActions: function(){
			// <a href="" class="cardRatesCountry">2Connect</a>
			var links_countries = $$('a.cardRatesCountry');
			var target_codes = $('CodeList'); // Container to display list of country codes
			var target_rates = $('RateDetails'); // Container to display the rate details
						
			/*
			 * function $: get a single element with ID 
			 * function $$: get list of items with CSS class, and store as an array
			 */

			
			links_countries.each( function(e,i){
			// Execute code on each link element
				e.addEvent( 'click', function(event){
					event = new Event( event ).stop();
					// Add Dynamic form
					target_codes.empty();
					target_codes.addClass('ajax-loading')
					new Ajax(
						e.href,
						{
							method: 'get',
							update: target_codes,
							data: {
								'action': 'getcodes',
								'country': e.id
							},
							onComplete: function(){
								target_codes.removeClass('ajax-loading')
								/*
								 * Assignaa behaviour to Country Code list here
								 */
								var links_codes = $$('a.cardRatesCode'); // Get list of all country code links
								links_codes.each( function(e,i){
									e.addEvent( 'click', function(event){
										event = new Event(event).stop();
										target_rates.empty();
										target_rates.src = 'marketing-promotions/rates.html?action=getrates&countryCode='+e.id+'&productType='+ e.href.substring([e.href.indexOf('productType=')+12]);
									});
								});
								
							}
						}
					).request();

				});
			});
		
		},
		
		getCountries: function(  )
		{
				//alert(cardName);
				var xmlHttp;
				try
				{
				// Firefox, Opera 8.0+, Safari
				xmlHttp=new XMLHttpRequest();
				}
				catch (e)
				{
			// Internet Explorer
				try
    			{
    			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    			}
				catch (e)
   				{
   				 try
  			     {
    			  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     			 }
    			catch (e)
     			 { 
     				 alert("Your browser does not support AJAX!");
      					return;
      			 }
    			}
				}
			xmlHttp.onreadystatechange=function()
			{
			if(xmlHttp.readyState==4)
			{
			//$("Country List").innerHTML = xmlHttp.responseText;
			}		
			}
				xmlHttp.open("GET","/2connectbahrain/marketing-promotions/rates.html?action=getcountries",true);
				//http://localhost/2connectbahrain/marketing-promotions/rates.html
  				xmlHttp.send(null);		
		},
		
		getRates: function( cardName, countryId )
		{
		
		}
	},
	
	//tips for flash games
	FlashGames: {
		toolTips: function(){
			$$('.gameThumb').each( function(e,i){
			// Execute code on each link element
				//console.log( 'adding enter event' );
				new Tips(e);
				/*
				e.addEvent( 'mouseenter', function(event){
					console.log(e); 
					new Tips(e, {
						onShow: function(toolTip) {
							console.log( 'show' );
						},
						onHide: function(toolTip) {
							console.log( 'hide' );
						}
					});
				});
				*/
			});		
		},
		runGame: function()
		{
				$$('.gameThumb').each( function(e,i){
			// Execute code on each link element
				//console.log( 'adding on click event' );
			e.addEvent('click', function(event){
				var eParent = e.getParent();
				window.open(eParent.href,'_blank','yes,no,no,,,no,no,no,no,no,no,no,,','');
				eParent.href="javascript:void(0);";	
			});
	
				//end of adding on click
			});	
			
		},
		
		sideBarNavigation: function(){
			var fLinks = new slidingDoorButtons( 'flashGames_Navigation', {buttonHeight:25, buttonFinalPosition: -100, rightImageWidth:11, activeClass:'current', duration: 75 } );
		}
		//code this be tha place to add pop up behaivure
		
		
	}
};

// TwoConnect.Rates.getCountries( id );




var mootabs = new Class({
	
	initialize: function(element, options) {
		this.options = Object.extend({
			width:				'300px',
			height:				'200px',
			changeTransition:	Fx.Transitions.Bounce.easeOut,
			duration:			1000,
			mouseOverClass:		'active',
			activateOnLoad:		'first',
			useAjax: 			false,
			ajaxUrl: 			'',
			ajaxOptions: 		{method:'get'},
			ajaxLoadingText: 	'Loading...',
			disableOver:		false
		}, options || {});
		
		this.el = $(element);
		this.elid = element;
		
		this.el.setStyles({
			height: this.options.height,
			width: this.options.width
		});
		
				
		this.titles = $$('#' + this.elid + ' ul.mootabs_title li');
		this.panelHeight = this.el.getSize().size.y - (this.titles[0].getSize().size.y + 4);
		this.panels = $$('#' + this.elid + ' .mootabs_panel');

		
		this.panels.setStyle('height', this.panelHeight);
		
		this.titles.each(function(item) {
			item.addEvent('click', function(){
					item.removeClass(this.options.mouseOverClass);
					this.activate(item);

				}.bind(this)
			);
			if( !this.options.disableOver ){ // check if need to disable the over effect
				item.addEvent('mouseenter', function() {
					if(item != this.activeTitle)
					{
						item.addClass(this.options.mouseOverClass);
					}
				}.bind(this));
			} // end disable over effect
			item.addEvent('mouseleave', function() {
				if(item != this.activeTitle)
				{
					item.removeClass(this.options.mouseOverClass);
				}
			}.bind(this));
		}.bind(this));
		
		if(this.options.activateOnLoad != 'none')
		{
			if(this.options.activateOnLoad == 'first')
			{
				this.activate(this.titles[0], true);
			}
			else
			{
				this.activate(this.options.activateOnLoad, true);	
			}
		}
	},
	
	activate: function(tab, skipAnim){
		if(! $defined(skipAnim))
		{
			skipAnim = false;
		}
		if($type(tab) == 'string') 
		{
			myTab = $$('#' + this.elid + ' ul li').filterByAttribute('title', '=', tab)[0];
			tab = myTab;
		}
		
		if($type(tab) == 'element')
		{
			var newTab = tab.getProperty('title');
			this.panels.removeClass('active');
			
			this.activePanel = this.panels.filterById(newTab)[0];
			
			this.activePanel.addClass('active');
			
			if(this.options.changeTransition != 'none' && skipAnim==false)
			{
				this.panels.filterById(newTab).setStyle('height', 0);
				var changeEffect = new Fx.Elements(this.panels.filterById(newTab), {duration: this.options.duration, transition: this.options.changeTransition});
				changeEffect.start({
					'0': {
						'height': [0, this.panelHeight]
					}
				});
			}
			
			this.titles.removeClass('active');
				
			tab.addClass('active');
			
			this.activeTitle = tab;
			
			if(this.options.useAjax)
			{
				this._getContent();
			}
		}
	},
	
	_getContent: function(){
		this.activePanel.setHTML(this.options.ajaxLoadingText);
		var newOptions = {update: this.activePanel.getProperty('id')};
		this.options.ajaxOptions = Object.extend(this.options.ajaxOptions, newOptions || {});
		var tabRequest = new Ajax(this.options.ajaxUrl + '?tab=' + this.activeTitle.getProperty('title'), this.options.ajaxOptions);
		tabRequest.request();
	},
	
	addTab: function(title, label, content){
		//the new title
		var newTitle = new Element('li', {
			'title': title
		});
		newTitle.appendText(label);
		this.titles.include(newTitle);
		$$('#' + this.elid + ' ul').adopt(newTitle);
		newTitle.addEvent('click', function() {
			this.activate(newTitle);
		}.bind(this));
		
		
		if( !this.options.disableOver ){ // check if need to disable mouse over
			newTitle.addEvent('mouseover', function() {
				if(newTitle != this.activeTitle)
				{
					newTitle.addClass(this.options.mouseOverClass);
				}
			}.bind(this));
		} //check if need to disable mouse over
		
		newTitle.addEvent('mouseout', function() {
			if(newTitle != this.activeTitle)
			{
				newTitle.removeClass(this.options.mouseOverClass);
			}
		}.bind(this));
		
		//the new panel
		var newPanel = new Element('div', {
			'style': {'height': this.options.panelHeight},
			'id': title,
			'class': 'mootabs_panel'
		});
		if(!this.options.useAjax)
		{
			newPanel.setHTML(content);
		}
		this.panels.include(newPanel);
		this.el.adopt(newPanel);
	},
	
	removeTab: function(title){
		if(this.activeTitle.title == title)
		{
			this.activate(this.titles[0]);
		}
		$$('#' + this.elid + ' ul li').filterByAttribute('title', '=', title)[0].remove();
		
		$$('#' + this.elid + ' .mootabs_panel').filterById(title)[0].remove();
	},
	
	next: function(){
		var nextTab = this.activeTitle.getNext();
		if(!nextTab) {
			nextTab = this.titles[0];
		}
		this.activate(nextTab);
	},
	
	previous: function(){
		var previousTab = this.activeTitle.getPrevious();
		if(!previousTab) {
			previousTab = this.titles[this.titles.length - 1];
		}
		this.activate(previousTab);
	}
});


var slidingDoorButtons = new Class({
	options: {
		buttonHeight: 34,				// in pixels
		buttonTotalStops: 4,			// number of slides-1 ( not currently in use )
		buttonFinalPosition: -136,		// in pixels
		buttonCurrentPosition: 0,		// dynamically changing
		rightImageWidth: 6,				// Width of Right Image
		duration: 50,					// time in ms
		periodicalOver: '',				// empty at initialization
		periodicalOut: '',				// empty at initialization
		activeClass: 'active',			// class for the active button
		deactivateLinks: false,
		scrollToElement: false
	},

	initialize: function( id, options ){
		this.setOptions( options );
		this.id = id;
		this.buttons = $$('#' + id + ' li a');

			
		this.Scroll = new Fx.Scroll( window, {
			wait: false,
			transition: Fx.Transitions.Quad.easeInOut
		});
		
			
		this.buttons.each( function(element, index){
		
			element.index = index;
			// element.Parent = element.getParent();
			
			if( this.options.deactivateLinks == true ){
				element.href="javascript:void(0)";
			}
			

			
			// Create options for each element. This will be helpful in storing the current position of the background shift
			element.options = $merge( this.options );
			
			// Initialize the Fx.Style for each element
			this.assignFx( element );
			
			// Add events to each element
			element.addEvents({
				
				// Start the fading IN transition effect for the element
				'mouseenter': function(){
					$clear(element.options.periodicalOut);
					element.options.periodicalOver = this.fadeIn.periodical(element.options.duration, this, element);
					// this.fadeIn( element );
				}.bind(this), // end of 'mouseenter'
				
				// Start the fading OUT effect for the element
				'mouseleave': function(){
					$clear(element.options.periodicalOver);
					element.options.periodicalOut = this.fadeOut.periodical(element.options.duration, this, element);
					// this.fadeOut( element );
				}.bind(this), // end of 'mouseleave'
				
				// When used in combination with MooTabs this will smoothly transition the button to its initial state
				'click': function(){
					this.fadeOutAll( index );
					if( this.options.scrollToElement ){ 
						this.Scroll.toElement( this.options.scrollToElement );
					}
				}.bind(this) // end of 'click'
				
			}, this);
			
		}, this);
		// end each
	},
	
	// Assign the Fx.Style to the elements 
	assignFx: function( element ){
		element.fxLink = ( window.ie )?( new Fx.Style( element, 'background-position-y', {duration: 0, wait: false} ) ):( new Fx.Style( element, 'background-position', {duration: 0, wait: false} ) );
		element.fxList = ( window.ie )?( element.fxList = new Fx.Style( element.getParent(), 'background-position-y', {duration: 0, wait: false}) ):( new Fx.Style( element.getParent(), 'background-position', {duration: 0, wait: false}) );
	},
	
	// Perform the Fade IN effect on the element
	fadeIn: function( element ){
		if( element.options.buttonCurrentPosition > element.options.buttonFinalPosition && !element.getParent().hasClass( this.options.activeClass ) )
		{
			element.$tmp.buttonNewPosition = element.options.buttonCurrentPosition-element.options.buttonHeight;
			element.$tmp.fxA = element.fxLink.start( ( window.ie )?( element.$tmp.buttonNewPosition ):( (element.getSize().size.x-element.options.rightImageWidth) + ' ' + ( element.$tmp.buttonNewPosition ) ) );
			element.$tmp.fxL = element.fxList.start( (window.ie )?( element.$tmp.buttonNewPosition ):( '0 ' + ( element.$tmp.buttonNewPosition ) ) );
			element.options.buttonCurrentPosition = element.$tmp.buttonNewPosition;
		}
		else
		{
			$clear(element.options.periodicalOver);
		}
	},
	
	// Perform the Fade OUT effect on the element
	fadeOut: function( element){
		if( element.options.buttonCurrentPosition < 0 && !element.getParent().hasClass( this.options.activeClass ))
		{
			element.$tmp.buttonNewPosition = element.options.buttonCurrentPosition+element.options.buttonHeight;
			element.$tmp.fxA = element.fxLink.start( ( window.ie )?( element.$tmp.buttonNewPosition ):( (element.getSize().size.x-element.options.rightImageWidth) + ' ' + ( element.$tmp.buttonNewPosition ) ) );
			element.$tmp.fxL = element.fxList.start( ( window.ie )?( element.$tmp.buttonNewPosition ):( '0 ' + ( element.$tmp.buttonNewPosition ) ) );
			element.options.buttonCurrentPosition = element.$tmp.buttonNewPosition;
		}
		else
		{
			$clear(element.options.periodicalOut);
		}
	},	
	// To be used with MooTabs. Deactivate the current tab smoothly.
	fadeOutAll: function( index ){
		this.buttons.each( function(e,i){
			if(index!=i){ e.options.periodicalOut = this.fadeOut.periodical(this.options.duration, this, e); }
		}, this);
	}

});	// end of class definition

// implement certain classes in the base class
slidingDoorButtons.implement(new Options, new Events);
/*
function highlight(el,endcolor,duration) {
	$(el).style.background = '#ffd700';
	var fx = $(el).effects({duration: 1000, transition: Fx.Transitions.linear});
	fx.start.delay(duration/2,fx,{
		'background-color': endcolor
	});
	return false;
}
*/

window.addEvent('domready', TwoConnect.start);
// function  fetch_country_list(){}

