/* Author: Nathan Sego */

$(function(){ // Start jQuery
	
	// Toggle lead form on Pro Plus results
	$('#leadFormToggle').click(function(evt){
		evt.preventDefault();
		$('#leadForm').toggleClass("hidden");
	});
	
	function testForZero( testNumber )
	{
		if( testNumber < 0 )
		{
			return 0;
		}
		else
		{
			return testNumber;
		}
	}
	
	$('#planSelectPrint').click(function(evt){
		evt.preventDefault();
		_gaq.push(['_trackEvent', 'Selector Tool', 'print', 'Useage Amount', $('#totalPerMonth').text() ]);
		void( window.print() );
	});
	
	// Package Selector Tool
	// Vars for Selection Tool in Mbs
	var period = 30; // days in period
	var emailSize = .01; // MB emails a day
	var webSize = 10; // MB hours a day
	var fileSize = 3; // MB files a week
	var streamSize = 6; // MB minutes a week
	var movieSize = 750; // MB hours a week
	var chatSize = 1.6; // MB minutes a week
	var musicSize = 35; // MB hours a day
	var gameSize = 60; // MB hours a day
	
	function calcUsage()
	{
		var package;
		var emailEstimate = Math.round( ( $( "#emailSlider" ).slider( "option", "value" ) * emailSize ) * period );
		var movieEstimate = Math.round($( "#movieSlider" ).slider( "option", "value" ) * movieSize);
		var webEstimate = Math.round( ( $( "#webSlider" ).slider( "option", "value" ) * webSize ) * period );
		var chatEstimate = Math.round( ( ( $( "#chatSlider" ).slider( "option", "value" ) * chatSize ) / 7 ) * period );
		var fileEstimate = Math.round( ( ( $( "#fileSlider" ).slider( "option", "value" ) * fileSize ) / 7 ) * period );
		var musicEstimate = Math.round( ( $( "#musicSlider" ).slider( "option", "value" ) * musicSize ) * period );
		var streamEstimate = Math.round( ( ( $( "#streamSlider" ).slider( "option", "value" ) * streamSize ) / 7 ) * period );
		var gameEstimate = Math.round( ( ( $( "#gameSlider" ).slider( "option", "value" ) * gameSize ) / 7 ) * period );
		var estimateTotal = ( emailEstimate + movieEstimate + webEstimate + chatEstimate + fileEstimate + musicEstimate + streamEstimate + gameEstimate ) / 1000;
		
		$('#resultPackage1, #resultPackage2, #resultPackage3').removeClass('current');
		
		if( estimateTotal > 15)
		{
			$('#resultPackage3').addClass('current');
		}
		else if( estimateTotal < 7.5 )
		{
			$('#resultPackage1').addClass('current');
		}
		else
		{
			$('#resultPackage2').addClass('current');
		}
		$('#totalPerMonth').text( estimateTotal );
	}
	
	// Slider
	$('#emailSlider').slider({value: 0, step: 10, min: 0, max: 200, animate: true, range: 'min', slide: function(evt, ui){ $('#emailTotal').text( testForZero( ui.value ) ) } });
	$('#movieSlider').slider({value: 0, step: 1, min: 0, max: 12, animate: true, range: 'min', slide: function(evt, ui){ $('#movieTotal').text( testForZero( ui.value ) ) } });
	$('#webSlider').slider({value: 0, step: 1, min: 0, max: 8, animate: true, range: 'min', slide: function(evt, ui){ $('#webTotal').text( testForZero( ui.value ) ) } });
	$('#chatSlider').slider({value: 0, step: 1, min: 0, max: 120, animate: true, range: 'min', slide: function(evt, ui){ $('#chatTotal').text( testForZero( ui.value ) ) } });
	$('#fileSlider').slider({value: 0, step: 5, min: 0, max: 100, animate: true, range: 'min', slide: function(evt, ui){ $('#fileTotal').text( testForZero( ui.value ) ) } });
	$('#musicSlider').slider({value: 0, step: 1, min: 0, max: 8, animate: true, range: 'min', slide: function(evt, ui){ $('#musicTotal').text( testForZero( ui.value ) ) } });
	$('#streamSlider').slider({value: 0, step: 10, min: 0, max: 120, animate: true, range: 'min', slide: function(evt, ui){ $('#streamTotal').text( testForZero( ui.value ) ) } });
	$('#gameSlider').slider({value: 0, step: 1, min: 0, max: 12, animate: true, range: 'min', slide: function(evt, ui){ $('#gameTotal').text( testForZero( ui.value ) ) } });

	$( "#emailSlider, #movieSlider, #webSlider, #chatSlider, #fileSlider, #musicSlider, #streamSlider, #gameSlider" ).bind( "slidechange", function(event, ui) {
		calcUsage();
	});

	// Tabs in Content
	$('.tabs').tabs();
	// popover demo
    $("a[rel=popover]").popover().click(function(e) { e.preventDefault() });

	// Print Button
	$('.printPage').click(function(evt){
		evt.preventDefault();
		void( window.print() );
	});

	// Search Submit
	$('#sendSearchBtn').click(function(event){
		event.preventDefault();
		var theValue = $.trim( $('#s').val() );
		if( !( theValue == '' ) )
		{
			$('form#searchForm').submit();
		}
	});
	
	// inject Flash with SWF Object
	$('div.embedFlash').each(function(e){
		
		var flashObj = $(this);
		var flashData = flashObj.data();
		var flashID = '#' + flashObj.attr('id');
		
		$( flashID ).flash({
			swf: flashData.swf ,
			width: flashData.width,
			height: flashData.height,
			params: {wmode: 'transparent'}
		});
		
	});
		
	// Close popup boxes
	$('a.close').bind('click', function(evt){
		evt.preventDefault();
		$(this).closest('.alert-message').addClass( 'hidden' );
	});
	
	// Validate Full Address for Service Availability
	$('#customerType1, #customerType2').change(function(){
		
		$('#wholeForm').removeClass('hidden');
		
		var showForm = $('input:radio[name=customerType]:checked').val();
		if(showForm == 'customer')
		{
			$('#forDropDown').addClass('hidden');
			$('#subjectDropDown, #messageHolder').removeClass('hidden');
		}
		else 
		{
			$('#forDropDown').removeClass('hidden');
			$('#subjectDropDown, #messageHolder').addClass('hidden');
		}
	});
	
	$('#serviceSubmit, ').bind('click',function(evt){
		$('#showError').addClass('hidden');
		var isErrorFree = true;
		
		// Iterate through 'reqire' fields
		$('input.required, select.required, textarea.required').each(function(){
			if(validateElement.isValid(this) == false)
			{
				isErrorFree = false;
			}
		});
		
		if(isErrorFree) // valid
		{ 
			_gaq.push(['_trackEvent', 'availability', 'submit', 'Zip code lookup', $('#serviceZip').val() ]);
			$('#serviceSubmit').val('Loading...');
			$('form#serviceForm').submit();
		}
		else // Not Valid
		{
			$('#showError').removeClass('hidden');
			return false;
		}
	});

	// Validate contact us from
	$('#contactSubmit').bind('click',function(evt){
		evt.preventDefault();
		$('#showError, #showSuccess').addClass('hidden');
		var isErrorFree = true;
		
		// Iterate through 'reqire' fields
		$('input.required, select.required, textarea.required').each(function(){
			if(validateElement.isValid(this) == false)
			{
				isErrorFree = false;
			}
		});
		
		if(isErrorFree) // valid
		{ 
			
			var formData = {};
			formData.action = 'my_ajax';
			formData.customerType = $('input[name=customerType]:checked').val();
			formData.firstName = $('#contactFirstName').val();
			formData.lastName = $('#contactLastName').val();
			formData.address = $('#contactAddress').val();
			formData.city = $('#contactCity').val();
			formData.state = $('#contactState').val();
			formData.zip = $('#contactZip').val();
			formData.email = $('#contactEmail').val();
			formData.phone = $('#contactPhone').val();
			formData.subject = $('#contactSendTo').val();
			formData.isFor = $('#contactSubject').val();
			formData.message = $('#contactMessage').val();
						
			if( formData.customerType == 'lead' )
			{
				var myRecord = new Object();
				
				//assign values to object using same name as fields in trackvia (notice underscore for any spaces).
				myRecord.first_name = formData.firstName;
				myRecord.last_name = formData.lastName;
				myRecord.address = formData.address;
				myRecord.city = formData.city;
				myRecord.state = formData.state;
				myRecord.zip_code = formData.zip;
				myRecord.phone = formData.phone;
				myRecord.email = formData.email;
				myRecord.service_for = formData.isFor;
				myRecord.source_code = 'Exede Customer Inquiry Form';
				
				//pass the new object into the TrackVia API utility.
				TRACKVIA.API.data = myRecord;
				
				//give the TrackVia API Utility the other parameters required.
				TRACKVIA.API.action = 'addrecord';
				TRACKVIA.API.accountid = 25463;
				TRACKVIA.API.apikey = 'KPRSM5efmdePIq6K6dXy';
				TRACKVIA.API.tableid = 69368;
						
				TRACKVIA.API.callback = function () {
					if (TRACKVIA.API.error) {
						//Set action to be done if there is an error.
						alert('There was an error: '+TRACKVIA.API.error);
					} else {
						
						
						_gaq.push(['_trackEvent', 'lead', 'success', 'Dealer Lead' ]);
						$('#showSuccess').removeClass('hidden');
						$('#wholeForm').addClass('hidden');
						validateElement.resetAllFields();
						console.log( 'Sent to Track Via' );
						_gaq.push(['_trackPageview', '/contact-wildblue/dealer-thank-you']);

						$.post(
							'/wp-admin/admin-ajax.php', 
							{
								action : 'my_ajax_response',
								firstName : myRecord.first_name,
								lastName : myRecord.last_name,
								email : myRecord.email
							}, 
							function(response)
							{
								console.log(response);
							}
						);		
										
					}
				};
				
				TRACKVIA.API.ajaxSend();	
				
			}
			else if( formData.customerType == 'customer' )
			{
				$.post(
					'/wp-admin/admin-ajax.php', 
					formData, 
					function(response)
					{
						_gaq.push(['_trackEvent', 'lead', 'success', 'Customer Care Lead' ]);
						$('#showSuccess').removeClass('hidden');
						$('#wholeForm').addClass('hidden');
						validateElement.resetAllFields();
						console.log(response);
						
						$.post(
							'/wp-admin/admin-ajax.php', 
							{
								action : 'my_ajax_response',
								firstName : myRecord.first_name,
								lastName : myRecord.last_name,
								email : myRecord.email
							}, 
							function(response)
							{
								console.log(response);
							}
						);		
						
					}
				);
			}
			else
			{
				$('#showSuccess').removeClass('hidden');
				$('#wholeForm').addClass('hidden');
				validateElement.resetAllFields();
				console.log( 'Sent to Track Via' );
			}
		}
		else // Not Valid
		{
			$('#showError').removeClass('hidden');
		}
	});
	
	// Validate Lead from
	$('#leadSubmit').bind('click',function(evt){
		evt.preventDefault();
		$('#showError, #showSuccess').addClass('hidden');
		var isErrorFree = true;
		
		// Iterate through 'reqire' fields
		$('input.required, select.required, textarea.required').each(function(){
			if(validateElement.isValid(this) == false)
			{
				isErrorFree = false;
			}
		});
		
		if(isErrorFree) // valid
		{ 
			var myRecord = new Object();
			
			//assign values to object using same name as fields in trackvia (notice underscore for any spaces).
			myRecord.first_name = $('#contactFirstName').val();
			myRecord.last_name = $('#contactLastName').val();
			myRecord.street = $('#contactAddress').val();
			myRecord.city = $('#contactCity').val();
			myRecord.state = $('#contactState').val();
			myRecord.zip = $('#contactZip').val();
			myRecord.phone = $('#contactPhone').val();
			myRecord.email = $('#contactEmail').val();
			
			if ($('#contactCustomer:checked').val() !== undefined) {
				myRecord.current_customer = 'Yes';
			}
			else
			{
				myRecord.current_customer = 'No';
			}
					
			myRecord.contact_time = $('#contactTime').val();
			myRecord.source_code = 'Exede Splash Page';
			
			console.log( myRecord );
			
			//pass the new object into the TrackVia API utility.
			TRACKVIA.API.data = myRecord;
			
			//give the TrackVia API Utility the other parameters required.
			TRACKVIA.API.action = 'addrecord';
			TRACKVIA.API.accountid = 25463;
			TRACKVIA.API.apikey = 'KPRSM5efmdePIq6K6dXy';
			TRACKVIA.API.tableid = 73687;
					
			TRACKVIA.API.callback = function () {
				if (TRACKVIA.API.error) {
					//Set action to be done if there is an error.
					alert('There was an error: '+TRACKVIA.API.error);
				} else {
					if ( $('#contactCustomer:checked').val() !== undefined )
					{
						_gaq.push(['_trackEvent', 'lead', 'success', 'Customer Care Lead' ]);
					}
					else
					{
						_gaq.push(['_trackEvent', 'lead', 'success', 'Dealer Lead' ]);
					}					
					$('#showSuccess').removeClass('hidden');
					validateElement.resetAllFields();
					$.post(
						'/wp-admin/admin-ajax.php', 
						{
							action : 'my_ajax_response',
							firstName : myRecord.first_name,
							lastName : myRecord.last_name,
							email : myRecord.email
						}, 
						function(response)
						{
							console.log(response);
						}
					);		
				}
			};
			
			TRACKVIA.API.ajaxSend();
				
		}
		else // Not Valid
		{
			$('#showError').removeClass('hidden');
		}
	});

	// Validation Object
	var validateElement = 
	{
		resetReqiredFields: function(){
		},
		
		stripWhiteSpace: function(str){
			return str.replace(/\s/g, '');
		},
		
		resetAllFields: function(){
			$('input:text, select, textarea').each(function(){
				$(this).val('');
			});
			
			$('input:checkbox').each(function(){
				$(this).attr('checked', '');
			});
			
			$('input:radio:checked').attr('checked', false);
		},
		
		isValid: function(element){
			var isValid = true;
			var emailPattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var phonePattern = /^\d{3}-\d{3}-\d{4}$/;
			var zipPattern = /(\d{5}$)|(^\d{5}-\d{4})/;
			var $element = $(element);
			var id = $element.attr('id');
			var name = $element.attr('name');
			var value = $element.val();
			var type = $element[0].type.toLowerCase();  // normalize input types
			var validate = $element.data('validate');
			
			switch(type){
				case 'text':
				case 'password':
				case 'textarea':
				case 'file':
					if( this.stripWhiteSpace(value).length == 0 )
					{
						isValid = false;
					};
					break;
				case 'select-one':
				case 'select-multiple':
					if(!value){ isValid = false; }
					break;
				case 'checkbox':
				case 'radio':
					if($('input[name="' + name + '"]:checked').length == 0)
					{
						isValid = false;
					}
					break;
				case 'email':
					if( this.stripWhiteSpace(value).length == 0 || !emailPattern.test(value) )
					{
						isValid = false;
					};
					break;
			};
			
			if( validate == 'email')
			{
				if( !emailPattern.test( this.stripWhiteSpace( value ) ) )
				{
					isValid = false;
				};
			}
			
			if( validate == 'zip')
			{
				if( !zipPattern.test( this.stripWhiteSpace( value ) ) )
				{
					isValid = false;
				};
			}
			
			if( validate == 'captcha')
			{
				if( this.stripWhiteSpace( value.toLowerCase() ) !== 'satellite' )
				{
					isValid = false;
				};
			}
			
			if( validate == 'phone')
			{
				if( !phonePattern.test( this.stripWhiteSpace( value ) ) )
				{
					isValid = false;
				};
			}
			
			var method = isValid ? 'removeClass' : 'addClass';
			$element.closest('div.inputBox')[method]('error');
			
			return isValid;
		}
	};

	
}); // End jQuery
