
/**
 * global.js
 * ---------
 * Main javascript for site wide use
 * 
*/

/* =============================================================================
	UTILITY FUNCTIONS
	========================================================================== */

function group_number(number) {

	var string = number.toString();
	var formattedString = '';
	if(string.length > 3) {
		formattedString = string.substr(0, string.length - 3)+','+string.substr(string.length-3);
	}
	return formattedString;
}

function exists(selector) {
	if ( $(selector).length > 0 ) {
		return true;
	}
	return false;
}

/* =============================================================================
	UI ENHANCEMENTS
	========================================================================== */

var UI = {
	
	init : function () {
		
		this.placeholders();
		
		if ( ! $('html').hasClass('ie7')) {
			this.toggleLoginMenu();
		}
		this.showloginError();
		
		this.carousel('#sidebar .success-stories');
		this.carousel('#content .success-stories');
		
		return this;
	},
	
	placeholders: function () {
		
		$('input[placeholder], textarea[placeholder]').placeholder();
	},
	
	toggleLoginMenu : function () {	
		
		var $menu = $('#login-dropdown');
		var $trigger = $('#top-menu ul li.login-toggle a');
			
		$('#top-menu li.login-toggle a, #login-dropdown').mouseover(function () {
			$menu.show();
			$trigger.addClass('active');
		});

		$('#top-menu li.login-toggle a, #login-dropdown').mouseout(function () {
			$menu.hide();
			$trigger.removeClass('active');
		});
	},
	
	// Show login dropdown and display error
	// message when login is unsuccessful
	showloginError : function () {

		var queryStrings = window.location.search;
		var fullURL = window.location.href;
		var dropdown = $('#login-dropdown');
		var trigger = $('#top-menu ul li.login-toggle a');

		if ( ! fullURL.match('login') && queryStrings.match('error=yes') ) {
			dropdown.show();
			trigger.addClass('active');
			dropdown.find('p.error').show();
		}
	},
	
	carousel : function(selector) {

		var slides = $(selector+' .slides'); 

		slides.cycle({
			fx: 'scrollHorz',
			speed: 600,
			timeout: 5000,
			next: $(selector+' .next'),
			prev: $(selector+' .prev')
		});
	}
	
}

/* =============================================================================
	FORMS
	========================================================================== */
	
var FormObj = {
	
	init : function () {
		
		this.triggerSubmit('.submit-button');
		this.validate();
		
		return this;
	},
	
	triggerSubmit : function (trigger) {
		
		$(trigger).click(function (e) {
			e.preventDefault();
			$(this).closest('form').submit();
		});
		
	},
	
	validate : function () {
		$('form.validate').validate();
	}
	
}


/* =============================================================================
	FINANCING SLIDERS
	========================================================================== */

var Finance = {
	
	init : function () {
		
		this.makeSliders();
		this.updatePaybackPrice();
		this.toggleTooltip();
		this.toggleSubmitButton();
		
		return this;
	},
	
	makeSliders : function () {
	
		// Financing sliders on all landing pages + content pages
		$('#current-sales .slider').slider({
			range: 'min',
			value: 110000,
			min: 5000,
			max: 200000,
			step: 1000,
			animate: 500,
			create: function(event, ui) {
				var min = $(this).slider('option', 'min');
				var max = $(this).slider('option', 'max');
				var value = $(this).slider('option', 'value');

				var salesParent = $(this).parents('ul.slider-calc');

				salesParent.find('.min').text('$'+group_number(min));
				salesParent.find('.max').text('$'+group_number(max));
				salesParent.find('.value').text('$'+group_number(value));
				// Hidden field
				$('[name=monthly_sales]').val(value); 
			},
			slide: function(event, ui) {
				// Update slider value
				var sliderParent = $(this).parents('ul.slider-calc');
				sliderParent.find('.value').text('$'+group_number(ui.value));
				// Hidden field
				$('[name=monthly_sales]').val(ui.value); 

				var min = $(this).slider('option', 'min');
				var max = $(this).slider('option', 'max');
				var salesValue = ui.value;

				// Update max financing allowed			
				var maxFinancing = salesValue * 1.25;
				if (maxFinancing > 110000) {
					maxFinancing = 110000;
				}
				$('#financing-wanted .slider').slider('option', 'max', maxFinancing);
				$('#financing-wanted').find('.max').text('$'+group_number(maxFinancing));

				// Grab new max and value of financing slider
				var financeMax = $('#financing-wanted').find('.slider').slider('option', 'max');
				var financeValue = $('#financing-wanted').find('.slider').slider('option', 'value');

				// Update the price using the value of the max 
				// instead if value is greater
				if (financeValue > financeMax) {
					$('#financing-wanted').find('.value').text('$'+group_number(financeMax));
					Finance.updatePaybackPrice(ui.value, financeMax);
				} else {
					Finance.updatePaybackPrice();
				}
			},
			stop: function(event, ui) {
				var value = $(this).slider('option', 'value');
				// Hidden field
				$('[name=monthly_sales]').val(value); 
			}
		});

		$('#financing-wanted .slider').slider({
			range: 'min',
			value: 32000,
			min: 5000,
			max: 110000,
			step: 50,
			animate: 500,
			create: function(event, ui) {
				var min = $(this).slider('option', 'min');
				var max = $(this).slider('option', 'max');
				var value = $(this).slider('option', 'value');

				var sliderParent = $(this).parents('ul.slider-calc');

				sliderParent.find('.min').text('$'+group_number(min));
				sliderParent.find('.max').text('$'+group_number(max));
				sliderParent.find('.value').text('$'+group_number(value));
				// Hidden field
				$('[name=advance_request]').val(value); 
			},
			slide: function(event, ui) {
				var sliderParent = $(this).parents('ul.slider-calc');
				sliderParent.find('.value').text('$'+group_number(ui.value));
				// Hidden field
				$('[name=advance_request]').val(ui.value); 

				Finance.updatePaybackPrice();
			}
		});
	},
	
	// Price per debit/credit transaction
	updatePaybackPrice : function(sales, financing) {

		if (!sales) {
			sales = $('#current-sales .slider').slider('option', 'value');
		}
		if (!financing) {
			financing = $('#financing-wanted .slider').slider('option', 'value');
		}
		
		// Multiplier
		var x = 5000; 

		if (sales > 10000 && sales <= 20000) {
			x = 6667;
		} else if (sales > 20000 && sales <= 35000) {
			x = 8750;
		} else if (sales > 35000 && sales <= 50000) {
			x = 10000;
		} else if (sales > 50000 && sales <= 80000) {
			x = 10667;
		} else if (sales > 80000 && sales <= 100000) {
			x = 11111;
		} else if (sales > 100000) {
			x = 16000;
		}

		// Calculate price
		var price = (financing * 1.45) / x;
		price = Math.round(price*100) / 100;
		$('#price').text('$'+price);
		return price;
	},
	
	// Toggle debit/credit info tooltip opacity
	toggleTooltip : function () {
		
		$('.tooltip-closer').click(function() {
			$(this).parent().find('.tooltip').fadeTo('slow', 0);
			$('.tooltip').fadeTo('fast', 0);
		});
		
		$('.tooltip-trigger').click(function() {
			$('.tooltip').fadeTo('fast', 1);
		});
	},
	
	// Toggles the Apply Now button (enabled/disabled) based on whether
	// merchants accept debit and credit cards 
	toggleSubmitButton : function () {

		var applyButton = $('.slider-form input[type="submit"]');
		var section = $('.fat-radio-buttons');
		var form = section.parent().find('form');

		form.hide();
		form.find('.submit-button').hide();
		form.find('.shadow-arrow').hide();

		// Toggle active styles
		section.find('label').mousedown(function() {
			section.find('label').removeClass('active');
			$(this).addClass('active');
		});

		// Click "Yes"
		section.find('label.first').click(function() {
			// $('#apply-now-button').removeClass('disabled').removeAttr('disabled');
			applyButton.removeAttr('disabled').removeClass('disabled');
			// form.find('.submit-button').fadeIn(200);
			form.slideDown('500', function () {
				form.find('.shadow-arrow').fadeIn(400, function () {
					form.find('.submit-button').fadeIn(800);
				});
			});
		});

		// Click "No"
		section.find('label.last').click(function() {
			applyButton.attr('disabled', 'disabled').addClass('disabled');
			form.find('.submit-button').fadeOut(200);
			form.find('.shadow-arrow').fadeOut(200);
			form.slideUp('500');
		});
	}
}


$(function() {
	
	FormObj.init();
	Finance.init();
	UI.init();
});
