/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
/*
/*		Title: Functions for the ftservice.com website
/*
/*		Author:	Arie L. Stavchansky, Ph.D.
/*
/*		Email: arie@stavchansky.net
/*
/*		Description:	This document contains a set of functions that enables
/*						various interactive elements in the ftservice.com
/*						website.  jQuery-1.6.1.js is used as a base library
/*						to handle all custom written code in this document.
/*
/*		Laste Updated:	09/12/2011
/*
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 


/* GLOBALS */


var _section = '';
var _subpage = '';
var _bannerTimer = '';
var _quoteTimer = '';
var _fragParams = '';

var msgbox = '<div class="gomsg fourRadius"><span></span></div>';
//Function to initialize the page
function init(page)
{
	//keep the global nav bar showing the correct select bg
	
	
	if (page != "agent") {
		$('#'+page).addClass('btnselect');
	} else {
		$('#'+page).addClass('btnselect');
		$('#'+page).addClass('navround_right');
	}
	
	setDeepLinking(page);
}

function initControllers(subNav)
{
		
	//hijack the nivo control nav events and place them on the subnav object?
	if (subNav){
	
		$('#slider').nivoSlider({
	
				directionNav: false, 
				borderRadius: 4,
				roundedOn: 'top',
				keyboardNav: false,
				effect: 'fade'
				
		});
	
		//stop the nivo slider
		//$('#slider').data('nivoslider').stop();
		$('#slider').data('nivoslider').stop();
		
		//pull up the precise image for the header
		$('a[href="#!' + _subpage + '"]').trigger('click');
		
	} else {
	
		//do nothing
		
	}

}

function setDeepLinking(page)
{
	// Keep a mapping of url-to-container for caching purposes.
	  var cache = {};
	  var onSubNav = true;
	  
	  $(window).bind( 'hashchange', function(e) {
	    
	  	var frag = e.fragment;
	  	var _fragParams = fragParams = $.deparam.fragment();	
	  	var query = $.deparam.querystring();
	  	
	  	clearTimeout(_bannerTimer);
	  	clearTimeout(_quoteTimer);
	  	
	  	frag = frag.substr(frag.lastIndexOf('!')+1).split('&')[0];
	  	
	  	//alert("Section is: " + page + ", fragment is: " + frag + ", fragparams are: " + fragParams.scroll + ", section is: " + _section);
	  	
	  	//store the current subpage in global memory
	  	_subpage = frag;
	  		  	
	  	if (frag == '') { 
	  	
	  		onSubNav = false;
			getSubPage(page, query, fragParams, onSubNav);
	  			  			  		
	    } else {
	    
	    	onSubNav = true;
	        getSubPage(frag, query, fragParams, onSubNav);
	        
	    }
	    
	  })
	  
	  // Since the event is only triggered when the hash changes, we need to trigger
	  // the event now, to handle the hash the page may have loaded with.
	  $(window).trigger( 'hashchange' );

}


function slideBanner(pos, timed)
{
	
	var currentLeft = $('#cyclorama').css('left');
	var slideLength = $('.banner').width();
	
	//for some reason, could not get jQuery to select all dots
	$('#dot0').css({background: 'url(images/banners/indicator_normal.png)'});
	$('#dot1').css({background: 'url(images/banners/indicator_normal.png)'});
	$('#dot2').css({background: 'url(images/banners/indicator_normal.png)'});
	$('#dot3').css({background: 'url(images/banners/indicator_normal.png)'});

	//change the selected dot of the current banner
	$('#dot'+pos).css({background: 'url(images/banners/indicator_select.png)'});
	
	//if a dot was clicked, kill the animation cycler timer
	if (!timed)	{ clearTimeout(_bannerTimer) }

	//do the actual animation
	$('#cyclorama').animate({left: -(slideLength*pos)}, 'slow', function(){
		
		if (pos >= 3) { pos = -1 }		
		initBannerCycle(pos);
		
	});
	
	
	//$('#slider').data('nivoslider').start();
	//$('#slider').start();
	
}

function scrollTo(anchor)
{
	//alert("Smooth scroll to anchor: " + anchor);
	$.smoothScroll({
		
		scrollTarget: $(anchor),
		offset: -25
		
	});
}

function initBannerCycle(current, timed)
{

	if (current==0) {$('#dot0').css({background: 'url(images/banners/indicator_select.png)'});}

	_bannerTimer = setTimeout(function(){
	 
	 slideBanner((current+1), true)}, 5000);
}

function slideQuote(pos, timed)
{
	var currentLeft = $('.testimonials').css('left');
	var slideLength = $('.q_module').width();
	
	if (!timed) {clearTimeout(_quoteTimer)}
	
	//do the actual animation
	$('.testimonials').animate({left: -(slideLength*pos)}, 'slow', function(){
		
		if (pos >= 3) { pos = -1 }		
		initQuoteCycle(pos);
		
	});
}

function initQuoteCycle(current, timed)
{
	_quoteTimer = setTimeout(function(){
	
		slideQuote((current + 1), true)}, 8000)
}

function setPointer(e, onSubNav)
{
	var pointerWidth = '';
	var buttonWidth  = '';
	var buttonPos	 = '';
	var targetPos	 = '';
	
	if (onSubNav)
	{
			
		var pointerWidth = $('#pointer').width();
		var buttonWidth	= $('a[href="#!' + e + '"]').width();
		var buttonPos	= $('a[href="#!' + e + '"]').position().left;
		var targetPos	= buttonPos + buttonWidth - (buttonWidth/2) - (pointerWidth/2);
		
		$('#pointer').css({display: 'block'});
		$('#pointer').animate({left: targetPos, opacity: 1});
		
	} else {	
	
		$('#pointer').animate({opacity: 0, left: 10});
		
	}

}

function setListNav()
{
	//sets the shim's height to the 0th list box;
	$('.shim').css({height: $('#l0').height() + 20});
	
	//captures the pointer's width
	var pointerWidth = $('#modulepointer').width();
	var ptr = $('#modulepointer');
	
	//bind a behavior to all of the buttons
	$('.list_nav li').bind('click', function(e){
		
		var buttonWidth = $(e.target).width();
		var	buttonPos = $(e.target).offset().left - $('.list_nav').offset().left;
		var targetPos = buttonPos + buttonWidth - (buttonWidth/2) - (pointerWidth/2);
		
		var buttonIdx = $(e.currentTarget).index();	
		
		//animate height of the shim shadow insex box
		var targetHeight = $('.listmodule ul:eq('+buttonIdx+')').outerHeight() - 12;
		$('.shim').animate({height: targetHeight}, {

			duration: 'slow',
			step: function(){$('#articles').css({height: $('#page').outerHeight() + 'px' });},
			complete: function(){$('#articles').css({height: $('#page').outerHeight() + 'px' });}
		
		});
			
		//animate the pointer in the list nav
		$('#modulepointer').animate({left: targetPos});
		
		//animate the list box
		var targetListPos = buttonIdx * $('.listmodule ul').outerWidth();
		$('.listmodule').animate({left: -targetListPos }, 'slow')
	
	})
	
}

function swapPage(e, q, fragParams)
{
		//call the server to load correct page.  This uses the pages.php file.  Check there!
		
		//add a loader bar incase there is a stall on loading
		//$('#articles').prepend('<div id="pageloader" style="display: block; width: 220px; margin: auto;opacity: 0; height: 30px;"><img src="images/ui/loader.gif" style="margin-top: 18px"></div>');
	
		//$('#pageloader').animate({opacity: 1}, 'fast');
		
		var dataObject = {subpage : e + '.php'};
		$.extend(dataObject, q);

		$.ajax({
		type: 'GET',
		url: 'pages.php',
		data: dataObject,
		success: function(d){
			//$('#pageloader').remove();
			$('#page').css({display: 'block'});
			$('#page').html(d).animate({opacity: 1}, 'slow');
			$('#articles').animate({height: $('#page').height()}, 'slow');

		},
		dataType: 'html'
		})
}

function getSubPage(targetPage, q, fragParams, onSubNav)
{
	
	//get the height of the articles div currently being viewed
	var articleHeight = $('#articles').height();
	
	//set the height of the articles div for the fade / remove
	$('#articles').height(articleHeight);

	//scroll up the window if the link says to do so
	if (fragParams.scroll=='top') {
		$.smoothScroll()
	} 
	
	//fade out the current page, then swap the page with an ajax call to the server
	$('#page').animate({opacity: 0}, 'slow', function(){swapPage(targetPage, q, fragParams)});
	
	//move the slider over to the appropriate tab
	setPointer(targetPage, onSubNav);
	
	//Trigger the subpages click to swap the image
	if (onSubNav){
		$('a[href="#!' + _subpage + '"]').trigger('click');
	} else {
		$('a[href="#!' + targetPage + '"]').trigger('click');
	}
	
}

function setDrapes(drapeType)
{
	//bind the click even to all classes that are drapes
	if (typeof drapeType == "undefined") {
	
		$('.drape').click(function(e){
		
			var currentDrape = e.currentTarget;
			var currentPane = $(e.currentTarget).find(".pane");
			var currentPaneHeight = $(currentPane).height();	
			
			if ($(currentPane).css('display') === 'none') {
				$(currentDrape).find('.heading').find('.arrow').animate({rotate: '90deg'});
			} else {
				$(currentDrape).find('.heading').find('.arrow').animate({rotate: '0deg'});
			}
			
			$(currentPane).slideToggle(
				{step: function(){	
				
						$('#articles').css({height: $('#page').height() + 'px' });
				
					}
				})
		 
		});
		
	} else if (drapeType == "widget" ){
	
		$('.heading').click(function(e){
		
			var currentDrape = $(e.currentTarget).parent();
			var currentPane = $(currentDrape).find(".pane");
			var currentPaneHeight = $(currentPane).height();	
			
			if ($(currentPane).css('display') === 'none') {
				$(currentDrape).find('.heading').find('.arrow').animate({rotate: '90deg'});
			} else {
				$(currentDrape).find('.heading').find('.arrow').animate({rotate: '0deg'});
			}
			
			$(currentPane).slideToggle(
				{step: function(){	
				
						$('#articles').css({height: $('#page').height() + 'px' });
				
					}
				})
		
		})
	
	}
}

function openWidget(elem)
{
	//open the calculator heading
	if($(elem).find(".pane").is(":hidden"))
	{
	    $(elem + " .heading").trigger('click');
	}
		
	//scroll to that area
	scrollTo(elem);
	
}

function setCalculator()
{
	
	var volume = $('#vol').val();
	var level	= $('#level').val();
	
	var monthlySavings	= Math.ceil((volume * 0.03) - (volume * 0.0225));
	var annualSavings	= Math.ceil(monthlySavings * 12);
	var monthlyProfit	= Math.ceil((volume * 0.004) * (level/100));
	var annualProfit	= Math.ceil(monthlyProfit * 12);
	
	//alert("Volume entered was: " + volume + " and profit level entered was: " + level);
	if ( isNaN(monthlySavings) || isNaN(annualProfit) ) {
		
		$('#save_monthly').html(0);
		$('#save_annual').html(0);
		$('#profit_monthly').html(0);
		$('#profit_annual').html(0);	
		
		return
		
	} else {
	
		$('#save_monthly').html(monthlySavings);
		$('#save_annual').html(annualSavings);
		$('#profit_monthly').html(monthlyProfit);
		$('#profit_annual').html(annualProfit);	

	
	}	
}

function ajaxBeforeValidation(form, options)
{
	if (typeof options.mask === 'undefined') { 
		
		options.mask="#main";
		options.maskradius="6px 6px 6px 6px";
		
	} else {
	
		options.maskradius = "0px 0px 0px 0px";
		
	}
		
	$(form).validationEngine('hideAll');
	var overlayW	= $(options.mask).outerWidth();
	var overlayH	= $(options.mask).outerHeight();

	var overlayTop	= $(options.mask).position().top - 75;
	var overlayLeft	= $(options.mask).position().left;
	
//	var overlayTop	= $(options.mask).offset().top;
//	var overlayLeft	= $(options.mask).offset().left;
	
	//console.log(options.mask + " top : " + overlayTop);
	//console.log(options.mask + " left: " + overlayLeft);
	//console.log(options.mask + " radius: " + options.maskradius);
	
	if (typeof options.waitmsg === 'undefined') { options.waitmsg = '' }
	
	$(options.mask).append('<div class="overlay" style="width: '+ overlayW + 'px; height: ' + overlayH + 'px"><div class="overlay_bg"></div><div class="pleasewait">' +  options.waitmsg + '</div></div>');	
	
	$('.overlay').css({
		top: overlayTop, 
		left: overlayLeft
	});
	
	$('.overlay').css("-webkit-border-radius", options.maskradius);
	$('.overlay').css("-moz-border-radius", options.maskradius);
	$('.overlay').css("border-radius", options.maskradius);
	
	$(window).resize(function() {
	
		$('.overlay').css({
		
			top: ($(options.mask).position().top - 75) + 'px',
			left: $(options.mask).position().left + 'px'
			
		});
	
	});
	
	if (options.opacity) { $('.overlay_bg').css("opacity", options.opacity) } 
	
	$('.overlay').hide().fadeIn();
	
}

function processingForm(status, form, errors, options)
{


	//Remove the progress bar
	$('.pleasewait').fadeOut('slow', function(){
	
		$('.pleasewait').remove();
		$(window).resize(function () {});
		
		if (status)
    	{
    		//Append a positive looking message below the submit button with instructions for the user
    		$('.overlay').append(msgbox);
    		$('.gomsg span').html(options.successHeadline);
    		$('.gomsg').css({
    			'font-size'	: 18,
    			'left'	: '7px',
    			'width'	: $('.overlay').outerWidth()-60,
    			'margin-top': -( $('.gomsg').outerHeight()/2 )
    		});
    		
			$('.gomsg').hide().fadeIn('slow', function(){
			
				$(this).delay(options.successMsgDelay).fadeOut('slow', function(){
				
					if (options.relocateAfterMsg) {
						window.location=options.relocateURL;
					} else {						
						$('.overlay').fadeOut('slow', function(){
								$('.overlay').remove();
								if (options.onSuccess) {options.onSuccess(options.mask) }
						});			
					}
									
				});
			
			});
			
		} else {
		
			$('.overlay').fadeOut('fast', function(){
			
				if (options.onFail) { options.onFail() }
				$('.overlay').remove();
				
			});
			
		}

	});

}

function prepForm(formID, validationConf)
{
	//If a recaptcha is in the passed form, then add the validation class to the recaptcha widget
	if ($('#recaptcha_response_field'))
	{
		$('#recaptcha_response_field').addClass('validate[required]');
	}
				
	// binds form submission and fields to the validation engine
    $(formID).validationEngine('attach', validationConf);

}


