﻿//set up server for DOT download as referenced in pictage.productsPut.js
var downloadsServerUrl = 'http://downloads.pictage.com';

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

jQuery(document).ready(function() {
	// launch DOT download
	jQuery('.launch-dot-link').click(function(e){
		e.preventDefault();
		doLaunchDOT();
	});
	
	simpleAccordion('ul.accordion > li > h3',1);
	
	tableHiddenRows();
	
	freeTrialForm();
	
	formValidator();
	
	if (jQuery('#sidebars').height() < jQuery('#content_box').height()) {
		if (jQuery('body').hasClass('partnerCon-2011')) {
			/*jQuery('#sidebars').css('height',(jQuery('#content').outerHeight()));*/
		} else {
			jQuery('#sidebars').css('height',(jQuery('#content_box').css('height')));
		}
	}
	jQuery('.textwidget > object, .textwidget > object > embed').attr('height','270').attr('width','270');
	jQuery('.tblank').attr('target','_blank');
	pictageTvVideoSelector();
	hideMorePodcastPage();
	modalActivatorActiveClass();
	modalActivatorURL();
	modalActivatorURLQuery('c');
	modalActivatorClick();
	animatedRotator(5000,'.animRotator');
	
	checkQueryStringPartnerCon();
	
	// display and hide search field
	jQuery('.pictageBlogMenu li.search').toggle(function(){
		jQuery(this).children('ul').css('visibility','visible');
	},function(){
		jQuery(this).children('ul').css('visibility','');
	});
	jQuery('.pictageBlogMenu li.search input').focus(function(){
		jQuery(this).closest('li.search > ul').css('visibility','visible');
	});
	jQuery('.pictageBlogMenu li.search input').blur(function(){
		jQuery(this).closest('li.search > ul').css('visibility','');
	});
	
	jQuery('.form-submit').click(function(){
		jQuery(this).closest('form').submit();
	});
	
	if (jQuery('body').hasClass('dispatchsignup')) {
		var q = jQuery.parseQuery();
		jQuery('.dispatch-signup-form #signup_email').val(jQuery.parseQuery().email);
	}
	
	jQuery('body.the-brand-called-we .view-comments').click(function(e){
		e.preventDefault();
		jQuery(this).html(jQuery(this).html()=='View Comments'?'Hide Comments':'View Comments').siblings('.comments-section-body').slideToggle('slow');
		
	});
	
	// Pictage Plans page - Plan Calculator
	jQuery('.callout-container').hover(function(){
		jQuery(this).find('.callout').show();
	},
	function() {
		jQuery(this).find('.callout').hide();
	}).find('.callout-activator').click(function(e){
		e.preventDefault();
	});
	
	// Plan Calculator
	if(jQuery('#plan-calculator-form').length > 0) {
		calculatePlan();
		setupPlanCalculatorForm();
	}
	simpleAccordion('.plan-breakdowns table');
	jQuery('.plan-breakdowns table').click(function(){
		var thisLi = jQuery(this).parents('.plan-breakdowns > li');
		thisLi.toggleClass('active');
		if (thisLi.hasClass('active')) {
			thisLi.animate({'width':'566px'}, 500);
		} else {
			thisLi.animate({'width':'330px'}, 500);
		}
	});

//stupid hack because the Liberated Syndication player (in sidebar widget) won't obey it's own instructions for height and width
	//twitterLink();

	
	// Setting up cookies for contact form
	var todayPlus180 = new Date().getTime();
	todayPlus180 += 180*24*60*60*1000;
	todayPlus180 = new Date(todayPlus180);
	//Setting the Cookies for Origin and Campaign values based on URL Parameters
	setCookie( 'origin', gup('o'), todayPlus180);
	//if ( getCookie( 'origin' ) ) alert( getCookie('origin'));
					
	setCookie( 'campaign', gup('c'), todayPlus180 );
	//if ( getCookie( 'campaign' ) ) alert( getCookie('campaign'));

	//Setting the Cookie for the referring website domain (ref_source) and the type of referral (ref_channel)
	if (document.referrer !=''){
		var new_ref_source = (document.referrer).match(/:\/\/(.[^/]+)/)[1];
		if (getCookie('ref_source')==null) {setCookie('ref_source','none',todayPlus180); }
		var ref_source = new_ref_source.indexOf('newaccounts.pictage.com')>=0?getCookie('ref_source'):new_ref_source;
		var ref_channel = 'organic';
		ref_source = ref_source.indexOf('google')>=0?'google':ref_source;
		ref_source = ref_source.indexOf('yahoo')>=0?'yahoo':ref_source;
		ref_source = ref_source.indexOf('msn')>=0?'bing':ref_source;
		ref_source = ref_source.indexOf('bing')>=0?'bing':ref_source;
		ref_source = ref_source.indexOf('youtube')>=0?'youtube':ref_source;
		ref_source = ref_source.indexOf('facebook')>=0?'facebook':ref_source;
		ref_source = ref_source.indexOf('twitter')>=0?'twitter':ref_source;
		ref_source = ref_source.indexOf('linkedin')>=0?'linkedin':ref_source;
		ref_source = ref_source.indexOf('flickr')>=0?'flickr':ref_source;
		ref_source = ref_source.indexOf('digg')>=0?'digg':ref_source;
		
		ref_channel = (ref_source === 'youtube'||ref_source === 'facebook'||ref_source === 'twitter'||ref_source === 'linkedin'||ref_source === 'flickr'||ref_source === 'digg')?'social':ref_channel;
		ref_channel = (getCookie('origin')==='google'||getCookie('origin')==='yahoo'||getCookie('origin')==='msn')?'paid':ref_channel;
		
		setCookie('ref_source',ref_source,todayPlus180);
		setCookie('ref_channel',ref_channel,todayPlus180);
	}
	
	// Sets hidden field values for Campaign, Origin, Lead Source, and Lead Channel in contact forms
	jQuery('#contact_00N50000001KfHC').val(getCookie('origin'));
	jQuery('#contact_00N700000021DS3').val(getCookie('campaign'));
	jQuery('#contact_00N70000002enCn').val(getCookie('ref_source'));
	jQuery('#contact_00N70000002enCs').val(getCookie('ref_channel'));
	// Adds current date to sales form "Last Contact Date" hidden input
	jQuery('#contact_lastContactDate').val(new Date());
});
/*
function twitterLink() {
	jQuery.get('http://tinyurl.com/api-create.php?url='+document.location, function() {
		jQuery('.twitter').attr('href','http://twitter.com/home?status=Check+out+%22'+document.title+'%22+on+the+Pictage+Blog-'+data);
	});
	jQuery('.twitter').attr('href','http://twitter.com/home?status=Check+out+%22'+document.title+'%22+on+the+Pictage+Blog-');
};*/

function pictageTvVideoSelector() {
	jQuery('body.video .link h2 span, body.video .link .post-thumbnail-container, body.podcast .link h2 span, body.podcast .link .post-thumbnail-container').click(function(e) {
		e.preventDefault();
		jQuery('.post_box.featured').html(jQuery(this).parents('.post_box').html());
		jQuery('html,body').animate({scrollTop:0}, 500);
		hideMorePodcastPage();
	});
}

function hideMorePodcastPage() {
	jQuery('span:regex(id,more-.*)').html('Read More &raquo;').addClass('readMoreLink readMoreActive').click(function(){
		jQuery(this).parent('p').nextAll().toggle();
		if (jQuery(this).hasClass('readMoreActive')) {
			jQuery(this).html('&laquo Hide More').removeClass('readMoreActive');
		} else {
			jQuery(this).html('Read More &raquo').addClass('readMoreActive');
		}
	}).parent('p').nextAll().toggle();
}

function modalActivatorActiveClass() {
	jQuery('.modal.active').each(function(){
		var timeBetweenPopups = !isNaN(jQuery(this).find('.modal-expiration').val())?jQuery(this).find('.modal-expiration').val():3;
		var cookieLifespan = 1000 * 60 * 60 * 24 * timeBetweenPopups;
		var now = new Date().getTime();
		var expires = new Date(now + cookieLifespan);
		if(getCookie(jQuery(this).attr('id')+'-shown') != 'true') {
			modalWindow(('#'+jQuery(this).attr('id')),'url');
			setCookie(jQuery(this).attr('id')+'-shown', 'true', expires);
		}
	});
}
function modalActivatorURL() {
	if (type='querystring') {
		modalWindow(window.location.hash,'url');
	}
}

function modalActivatorURLQuery(query) {
	if (type='querystring') {
		var thisQuery = getQuerystring(query);
		modalWindow(queryList(thisQuery));
	} else {
		modalWindow(window.location.hash,'url');
	}
}

function modalActivatorClick() {
	jQuery('.modal-activator').click(function(e){
		e.preventDefault();
		modalWindow(jQuery(this).attr('href'));
	});
}

function modalWindow(modalID,source,position) {
	if (jQuery(modalID).hasClass('modal')) {
		if (jQuery('.modal-opaque').length < 1) {
			jQuery('.modals').append('<div class="modal-opaque"></div>');
		}	
		jQuery(modalID).siblings('.modal-opaque').fadeIn(source=='url'?1:400).click(function() {
			jQuery(this).fadeOut();
			jQuery('.modal').fadeOut();
		});
		if (position != 'absolute') {
			jQuery(modalID).css({
				'margin-top':((jQuery(modalID).outerHeight()/2)*-1),
				'margin-left':((jQuery(modalID).outerWidth()/2)*-1)
			});
		} else {
			jQuery(modalID).addClass('absolute').css('margin-left',((jQuery(modalID).outerWidth()/2)*-1));
		}
		jQuery(modalID).fadeIn(source=='url'?1:400,function(){
			if (source=='url') {
				jQuery('html,body').scrollTop(0);
			}
		});
		if (jQuery(modalID).find('.close').length < 1) {
			jQuery(modalID).append('<a class="close">Close</a>');
		}
		jQuery(modalID+' .close').click(function(e){
			e.preventDefault();
			jQuery('.modal-opaque').fadeOut();
			jQuery('.modal').fadeOut();
		});
	}
}
// query string parsing function
function gup(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];
}
function getQuerystring(key, default_) {
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
function queryList(query) {
	switch(query) {
		case 'wppi':
			return '#wppi-2011-leads-modal';
			break;
	}
}

/* Animated gallery rotator function
interval = the amount of time on each slide
container = css selector for the parent element of all the slides
*/
animatedRotator = function (interval,container){
	// checks whether there is more than one slide before running animation
	if (jQuery(container).children().length > 1) {
		//randomizes first slide if ".animRotatorActive" class hasn't been given to one of them
		if (jQuery(container).find('.animRotatorActive').length < 1) {
			var numSlides = jQuery(container).children().length;
			var firstSlideNumber = Math.floor(Math.random()*numSlides) + 1;
			var firstSlide = jQuery(container).find('li:nth-child(' + firstSlideNumber + ')');
			jQuery(container).height(firstSlide.innerHeight());
			firstSlide.addClass('animRotatorActive');
		} else {
			jQuery(container).height(jQuery('.animRotatorActive').innerHeight());
		}
		setInterval(function(){
			var active = jQuery(container +' > .animRotatorActive');
			var next = (active.next()[0])? active.next() : jQuery(container).children('*:first-child');
			active.siblings().css('visibility','hidden');
			next.css('visibility','visible');
			jQuery(container).animate({
				height:next.innerHeight()
			},1000);
			active.fadeOut(1000, function() {
				active.removeClass('animRotatorActive').css('display','block');
				next.addClass('animRotatorActive');
			});
		},interval);
	}
};

// Simple Accordion
function simpleAccordion (activator,firstOpen,limitOne) {
	jQuery(activator).click(function() {
		jQuery(this).toggleClass('closed').next().toggle(500);
		// if this is true, only one item will be permitted to be open at a time
		if (limitOne === true) {
			jQuery(activator).not(jQuery(this)).addClass('closed').next().hide(500);
		}
		return false;
	});
	// if there is a hash (#) in the url, tests to see if it points to one of the activators, and opens that activator if it is
	// then tests to see whether the url hash points to an ID inside one of the accordion content areas, and opens that one if it does
	if (window.location.hash) {
		var activatorHasId = 0;
		jQuery(activator).each(function(){
			if (('#'+jQuery(this).attr('id')) === window.location.hash){
				jQuery(activator).not(jQuery(window.location.hash)).addClass('closed').next().hide();
				activatorHasId = 1;
				return;
			}
		});
		if (activatorHasId != 1){
			jQuery(activator).not(jQuery(window.location.hash).parents().prev(activator)).addClass('closed').next().hide();
		}
	// if firstOpen is an integer, then it will select an item by index (1-based) to be open on load
	} else if (firstOpen === parseInt(firstOpen)) {
		jQuery(activator+':not(:eq('+(firstOpen-1)+'))').addClass('closed').next().hide();
	// if firstOpen is true, the first item will be open on load
	} else if (firstOpen === true) {
		jQuery(activator).filter(':not(:first)').addClass('closed').next().hide();
	// otherwise firstOpen will be accepted as a css selector for the item (or items) to be open on load, and where none are present, all items will be closed on load
	} else {
		jQuery(activator+':not('+firstOpen+')').addClass('closed').next().hide();
	}
}

// cookies

function getCookie(Name) {
	var aCookie = document.cookie.split("; ");

	for ( var i=0 ; i < aCookie.length ; i++ )
	{
		var aCval = aCookie[i].split("=");
		if ( ( Name == aCval[0]) && ( aCval.length > 1 ) ) return unescape( aCval[1] ) ;
	}

	return false ;
};


function setCookie(Name,Value,Expires) {
	var pvalue   = escape(Value) ;
	var pExpires = Expires ;

	var pPath    = ';Path=/' ;

	// Get subdomain if more than one "." in the host name
	var pDomain  = document.URL;
	pDomain = pDomain.substring( pDomain.indexOf( '//' ) + 2 );
	idx = pDomain.indexOf( ':' );
	if ( idx >= 0 )
		pDomain = pDomain.substring( 0, idx );
	idx = pDomain.indexOf( '/' );
	if ( idx >= 0 )
		pDomain = pDomain.substring( 0, idx );
	idx = pDomain.indexOf( '.' );
	if ( idx != pDomain.lastIndexOf( '.' ) )
		pDomain = ';domain=' + pDomain.substring( idx );
	else
		pDomain = '';

	pExpires = pExpires == "never" ? 'Fri, 31 Dec 2099 23:59:59 GMT;' : (pExpires || '');
	document.cookie = (Name + '=' + pvalue + ';expires=' + pExpires + pPath + pDomain);
};

function tableHiddenRows() {
	jQuery('.accHead').hover(
		function() {
			jQuery(this).addClass('hover');
		},
		function() {
			jQuery(this).removeClass('hover');
		}
	).click(function() {
		if ( jQuery.browser.msie && jQuery.browser.version <= 6 ) {
			jQuery(this).toggleClass('openSwitch').next().toggleClass('closed').toggle();
			//jQuery(this).siblings('.accHead:not(.openSwitch)').addClass('openSwitch').next().addClass('closed').hide();
		} else {
			jQuery(this).toggleClass('openSwitch').next().toggleClass('closed').find('div').slideToggle(500);//jQuery(this).siblings('.accHead:not(.openSwitch)').addClass('openSwitch').next().addClass('closed').find('div').hide(500);
		}
	return false;
	}).addClass('openSwitch').next().addClass('closed').find('div').hide(); 
}

function freeTrialForm() {
	jQuery('#free-trial-form .actions a').click(function(e){
		e.preventDefault();
		if (jQuery(this).attr('id')=='free-trial-button-pictage') {
			var theURL = 'https://secure.pictage.com/photographer/signup-Starter';
			var firstNameKey = 'firstName';
			var lastNameKey = 'lastName';
			var studioNameKey = 'businessName';
		} else {
			var theURL = 'https://atrium.shootq.com/signup/ShootQ/';
			var firstNameKey = 'first-name';
			var lastNameKey = 'last-name';
			var studioNameKey = 'brand-name';
		}
		jQuery('#free-trial-form #free-trial-text-first-name').attr('name',firstNameKey);
		jQuery('#free-trial-form #free-trial-text-last-name').attr('name',lastNameKey);
		jQuery('#free-trial-form #free-trial-text-studio').attr('name',studioNameKey);
		jQuery('#free-trial-form').attr('action',theURL).submit();
		
	});
}

function checkQueryStringPartnerCon() {
	if (getQuerystring('discountcode') == 'welcometothefamily') {
		setCookie('discountcode','welcometothefamily','never');
	}
	if (getCookie('discountcode') == 'welcometothefamily') {
		jQuery('#partnerCon2011-eventbrite').attr('src','http://www.eventbrite.com/tickets-external?eid=1901390109&ref=etckt&discount=welcometothefamily');
	}
}

var planCalc;
function calculatePlan() {
	planCalc = {
		starter : {
			retailCommRate : (jQuery('#starterRetailCommRate').val())/100,
			p3CommRate : (jQuery('#starterP3CommRate').val())/100,
			monthFee : jQuery('#starterMonthFee').val()
		},
		premium : {
			retailCommRate : (jQuery('#premiumRetailCommRate').val())/100,
			p3CommRate : (jQuery('#premiumP3CommRate').val())/100,
			monthFee : jQuery('#premiumMonthFee').val()
		},
		pro : {
			retailCommRate : (jQuery('#proRetailCommRate').val())/100,
			p3CommRate : (jQuery('#proP3CommRate').val())/100,
			monthFee : jQuery('#proMonthFee').val()
		},
		user : {
			numEvent : parseInt(removeDollar(jQuery('#plan-calculator-text-event-num').val()), 10),
			salesPerEvent : parseInt(removeDollar(jQuery('#plan-calculator-text-sales-per-event').val()), 10),
			usingP3 : jQuery('#plan-calculator-radio-p3-yes').is(':checked'),
			packagePrice : parseInt(removeDollar(jQuery('#plan-calculator-text-package-price').val()), 10)
		}
	};
	planCalc.totals = {
		annualSales : planCalc.user.numEvent * planCalc.user.salesPerEvent,
		annualP3 : planCalc.user.usingP3 == true ? planCalc.user.numEvent * planCalc.user.packagePrice : 0
	}
	planCalc.grossRevenue = planCalc.totals.annualSales + planCalc.totals.annualP3;
	
	planCalc.starter.retailComm = planCalc.starter.retailCommRate * planCalc.totals.annualSales;
	planCalc.starter.p3Comm = planCalc.starter.p3CommRate * planCalc.totals.annualP3;
	planCalc.starter.memFee = planCalc.starter.monthFee * 10;
	
	planCalc.premium.retailComm = planCalc.premium.retailCommRate * planCalc.totals.annualSales;
	planCalc.premium.p3Comm = planCalc.premium.p3CommRate * planCalc.totals.annualP3;
	planCalc.premium.memFee = planCalc.premium.monthFee * 10;
	
	planCalc.pro.retailComm = planCalc.pro.retailCommRate * planCalc.totals.annualSales;
	planCalc.pro.p3Comm = planCalc.pro.p3CommRate * planCalc.totals.annualP3;
	planCalc.pro.memFee = planCalc.pro.monthFee * 10;
	
	planCalc.starter.pictageCost = planCalc.starter.retailComm + planCalc.starter.p3Comm + planCalc.starter.memFee;
	planCalc.premium.pictageCost = planCalc.premium.retailComm + planCalc.premium.p3Comm + planCalc.premium.memFee;
	planCalc.pro.pictageCost = planCalc.pro.retailComm + planCalc.pro.p3Comm + planCalc.pro.memFee;
	planCalc.starter.grossProfit = planCalc.grossRevenue - planCalc.starter.pictageCost;
	planCalc.premium.grossProfit = planCalc.grossRevenue - planCalc.premium.pictageCost;
	planCalc.pro.grossProfit = planCalc.grossRevenue - planCalc.pro.pictageCost;
	
	
	jQuery('#plan-calculator-modal .plan-breakdowns > li').each(function(){
		if (jQuery(this).hasClass('plan-starter')) {
			var thisPlanCalc = planCalc.starter;
		} else if (jQuery(this).hasClass('plan-premium')) {
			var thisPlanCalc = planCalc.premium;
		} else {
			var thisPlanCalc = planCalc.pro;
		}
		jQuery(this).find('.plan-profit').text(formatDollars(thisPlanCalc.grossProfit));
		jQuery(this).find('strong.gross-revenue, .gross-revenue .amount').text(formatDollars(planCalc.grossRevenue));
		jQuery(this).find('.retail-sales .amount').text(formatDollars(planCalc.totals.annualSales));
		jQuery(this).find('.p3-revenue .amount').text(formatDollars(planCalc.totals.annualP3));
		jQuery(this).find('strong.pictage-cost, .pictage-cost .amount').text(formatDollars(thisPlanCalc.pictageCost));
		jQuery(this).find('.plan-commission').text(parseInt(thisPlanCalc.retailCommRate*100));
		jQuery(this).find('.plan-p3-commission').text(thisPlanCalc.p3CommRate*100);
		jQuery(this).find('.retail-commission .amount').text(formatDollars(thisPlanCalc.retailComm));
		jQuery(this).find('.p3-commission .amount').text(formatDollars(thisPlanCalc.p3Comm));
		jQuery(this).find('.membership-fee .amount').text(formatDollars(thisPlanCalc.memFee));
	});
		
	recommendedPlan = planCalc.pro.grossProfit > planCalc.premium.grossProfit ? 'pro' : 'premium';
	recommendedPlan = (planCalc.starter.grossProfit > planCalc.pro.grossProfit && planCalc.starter.grossProfit > planCalc.premium.grossProfit) ? 'starter' : recommendedPlan;
	jQuery('#plan-calculator-modal').removeClass('starter premium pro');
	jQuery('#plan-calculator-modal').addClass(recommendedPlan).find('.plan-name').text(recommendedPlan);
}


function setupPlanCalculatorForm() {
	var originalValue;
	jQuery('#plan-calculator-form input').focus(function(){
		originalValue = jQuery(this).val();
	}).blur(function(){
		if (jQuery(this).val() == '') {
			jQuery(this).val(originalValue);
		} else if (jQuery(this).hasClass('money')) {
			if (!isNaN(parseFloat(removeDollar(jQuery(this).val())))) {
				jQuery(this).val('$'+parseFloat(removeDollar(jQuery(this).val())));
			} else {
				//jQuery(this).val(originalValue);
			}
		}
		calculatePlan();
		validatePlanForm();
	});
	
	jQuery('#plan-calculator-find-button').click(function(e){
		e.preventDefault();
		calculatePlan();
		formError = validatePlanForm();
		if (formError == true) {
			return;
		}
		//jQuery('.plan-breakdowns table:not(.closed)').next().hide().parents('.plan-breakdowns > li').css('width','');
		modalWindow('#plan-calculator-modal','click','absolute');
	});

}

function validatePlanForm() {
	//alert('validating');
	var formError = false;
	if(isNaN(planCalc.user.numEvent)) {
		formError = true;
		jQuery('#plan-calculator-text-event-num').addClass('error');
	} else {
		jQuery('#plan-calculator-text-event-num').removeClass('error');
	}
	if(isNaN(planCalc.user.salesPerEvent)) {
		formError = true;
		jQuery('#plan-calculator-text-sales-per-event').addClass('error');
	} else {
		jQuery('#plan-calculator-text-sales-per-event').removeClass('error');
	}
	if(isNaN(planCalc.user.packagePrice) && (planCalc.user.usingP3 == true)) {
		formError = true;
		jQuery('#plan-calculator-text-package-price').addClass('error');
	} else {
		jQuery('#plan-calculator-text-package-price').removeClass('error');
	}
	jQuery('#plan-calculator-form input.error:first').focus();
	return formError;
}
function removeDollar(amount) {
	amount = (amount.indexOf('$') >= 0) ? amount.slice(amount.indexOf('$') + 1) : amount;
	return amount;
}

function formatDollars(value) {
	value = '$'+addCommas(formatCents(value));
	return value;
}
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function formatCents (value) {
	value = is_int(value)?value:value.toFixed(2);
	return value;
}
// checks if a value is an integer
function is_int(value){
	if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
		return true;
	} else {
		return false;
	}
}
function formValidator(){
	jQuery('#aweber-form').keypress(function(e){
		if(e.which == 13){
			jQuery('.form-submit-button').click();
		}
	});
	jQuery('.form-submit-button').click(function(e){
		e.preventDefault();
		var formError = false;
		if(jQuery(this).closest('form').attr('id') == 'aweber-form') {
			function addError(errorItem){
				formError = true;
				jQuery(errorItem).addClass('error').focus();
			}
			if(jQuery('#awf_field-28228952').val() == '' || jQuery('#awf_field-28228952').val() == 'Email' || !validateEmail(jQuery('#awf_field-28228952').val())){
				addError('#awf_field-28228952');
			}
			if(jQuery('#awf_field-28228951-last').val() == '' || jQuery('#awf_field-28228951-last').val() == 'Last Name') {
				addError('#awf_field-28228951-last');
			}
			if(jQuery('#awf_field-28228951-first').val() == '' || jQuery('#awf_field-28228951-first').val() == 'First Name') {
				addError('#awf_field-28228951-first');
			}
			jQuery(this).closest('form').find('.error').blur(function(){
				var validationArray = ['','Email','Last Name','First Name'];
				if(jQuery(this).attr('id')=='awf_field-28228952') {
					if(!validateEmail(jQuery('#awf_field-28228952').val())){
						return;
					}
				}
				if(jQuery.inArray(jQuery(this).val(),validationArray) == -1){
					jQuery(this).removeClass('error');
				};
			});
			
		} else {
			jQuery(this).closest('form').find('input.required').each(function(){
				if ( ( jQuery(this).hasClass('email') && !validateEmail(jQuery(this).val()) ) || jQuery(this).val() == '' ) {
					jQuery(this).addClass('error');
					formError = true;
				}
			});
			jQuery(this).closest('form').find('input.error:first').focus();
			jQuery(this).closest('form').find('.error').blur(function(){
				if(jQuery(this).hasClass('email')) {
					if(!validateEmail(jQuery(this).val())){
						return;
					}
				}
				if(jQuery(this).val()!=''){
					jQuery(this).removeClass('error');
				};
			});
		}
		if(formError == true){return;}
		jQuery(this).closest('form').submit();
	});
}
function validateEmail(value){
	re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)|(\.[0-9]*$)/ ;
	re_two = /^([a-zA-Z0-9_\.\-])+\@(\[?)[a-zA-Z0-9\_\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/ ;
	re_three = /@.*\./g ;
	if ( !value.match(re) && value.match(re_two) && value.match(re_three) ) { return true ; }
	return false ;
} 
