﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />
/*global jQuery, $, window,swfobject */
"use strict";

var VIDEO_REVIEWS_COUNT = 87;

$.fn.comboToggle = function () {
	return this.animate({opacity: 'toggle', height: 'toggle'});
};


/* EHR Partner Screenshot Animation (/features) */
var z = 0;
var inAnimation = false;

$(document).ready(function () {
	if ($('#ehr-partners-sshots img').size() > 0) {
		$('#ehr-partners-sshots img').each(function () {
			z++;
			$(this).css('z-index', z);
		});

		window.setInterval(function () { swapFirstLast(true); }, 10000);
	}
	
});

function swapFirstLast(isFirst) {
	if (inAnimation) return false;
	else inAnimation = true;

	var processZindex, direction, newZindex, inDeCrease;

	if (isFirst) { processZindex = z; direction = '-'; newZindex = 1; inDeCrease = 1; }
	else { processZindex = 1; direction = ''; newZindex = z; inDeCrease = -1; }
	
	$('#ehr-partners-sshots img').each(function () {
		if ($(this).css('z-index') == processZindex) {
			$(this).animate({ 'top': direction + $(this).height() + 'px' }, 'slow', function () {
				$(this).css('z-index', newZindex)
			.animate({ 'top': '0' }, 'slow', function () {
				inAnimation = false;
			});
			});
		} else {
			$(this).animate({ 'top': '0' }, 'slow', function () {
				$(this).css('z-index', parseInt($(this).css('z-index')) + inDeCrease);
			});
		}
	});
}

/* LivePerson button support */
/*ignore jslint start*/
// from http://community.liveperson.com/docs/DOC-1045
// BEGIN PASTE
var lpChatConfig = {
	apiKey: '9b20167a816c4e119263958f4a90a1c7',
	lpServer: 'server.iad.liveperson.net',
	lpNumber: '66956820'
	//onLoad: myOnLoad,
	//onInit: myOnInit,
	//onStart: myOnStart,
	//onStop: myOnStop,
	//onState: myOnState,
	//onAgentTyping: myOnTyping,
	//onUrlPush: myOnPush,
	//onLine: myOnLine,
	//onError: myOnError,
	//onAvailability: myOnAvailability,
	//onResume: myOnResume
};
lpChatConfig.lpAddScript = function (src, ignore) { var c = lpChatConfig; if (typeof (c.lpProtocol) == 'undefined') { c.lpProtocol = (document.location.toString().indexOf("https:") == 0) ? "https" : "http"; } if (typeof (src) == 'undefined' || typeof (src) == 'object') { src = c.lpChatSrc ? c.lpChatSrc : '/hcp/html/lpChatAPI.js'; }; if (src.indexOf('http') != 0) { src = c.lpProtocol + "://" + c.lpServer + src + '?site=' + c.lpNumber; } else { if (src.indexOf('site=') < 0) { if (src.indexOf('?') < 0) src = src + '?'; else src = src + '&'; src = src + 'site=' + c.lpNumber; } }; var s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('charset', 'iso-8859-1'); s.setAttribute('src', src); document.getElementsByTagName('head').item(0).appendChild(s); };
//if (window.attachEvent) window.attachEvent('onload', lpChatConfig.lpAddScript);
//else window.addEventListener('load', lpChatConfig.lpAddScript, false);
// END PASTE
/*ignore jslint end*/

(function ($) {

	function onAvailabilityKnown(isAvailable) {
		$(document).ready(function () {
			var anchorElement;

			if (isAvailable) {
				anchorElement = $('<a id="liveperson-button" class="online" href="#">Chat Online Now</a>');
				anchorElement.appendTo('#liveperson-button-container');
				anchorElement.bind('click', onLivePersonButtonClicked);
			} else {
				anchorElement = $('<a id="liveperson-button" class="offline" href="/contact">Contact Us</a>');
				anchorElement.appendTo('#liveperson-button-container');
			}
		});
	}

	function onLivePersonButtonClicked(event) {
		var config = lpChatConfig,
			url = 'http://' + config.lpServer +
					'/hc/' + config.lpNumber + '/' +
					'/?cmd=file&file=visitorWantsToChat&site=' + config.lpNumber +
					'&imageUrl=http://' + document.location.host + '/img/liveperson&referrer=' +
					window.encodeURIComponent(window.document.location.href) +
					'&offlineURL=http://' + document.location.host + '/contact' +
					'&onlineURL=http://' + document.location.host + '/chat';

		if ($.isFunction(window.lpAppendVisitorCookies)) {
			url = window.lpAppendVisitorCookies(url);
		}
		window.open(url, 'chat' + config.lpNumber, 'width=475,height=600,resizable=yes');
		event.preventDefault();
	}

	function getLivePersonAvailability(config, callback) {
		config.onLoad = function () {
			window.lpc = new window.lpChat();
			window.lpc.chatAvailability();
		};
		config.onAvailability = function (availObj) {
			callback(availObj.availability);
		};
		config.onError = function (errorObj) {
			if ($('#liveperson-button').length === 0) {
				callback(false);
			}
		};
	}

	lpChatConfig.lpAddScript();
	getLivePersonAvailability(lpChatConfig, function (isAvailable) {
		onAvailabilityKnown(isAvailable);
	});
} (jQuery));

/* LivePerson MonitorTag */
(function ($) {
	var lpMTagConfig = {
		'lpServer': 'server.iad.liveperson.net',
		'lpNumber': '66956820',
		'lpProtocol': (document.location.toString().indexOf('https:') === 0) ? 'https' : 'http'
	};

	function lpAddMonitorTag(src) {
		if (typeof (src) === 'undefined' || typeof (src) === 'object') {
			src = lpMTagConfig.lpMTagSrc ? lpMTagConfig.lpMTagSrc : '/hcp/html/mTag.js';
		}
		if (src.indexOf('http') !== 0) {
			src = lpMTagConfig.lpProtocol + "://" + lpMTagConfig.lpServer + src + '?site=' + lpMTagConfig.lpNumber;
		} else {
			if (src.indexOf('site=') < 0) {
				if (src.indexOf('?') < 0) {
					src = src + '?';
				} else {
					src = src + '&';
				}
				src = src + 'site=' + lpMTagConfig.lpNumber;
			}
		}
		var s = document.createElement('script');
		s.setAttribute('type', 'text/javascript');
		s.setAttribute('charset', 'iso-8859-1');
		s.setAttribute('src', src);
		document.getElementsByTagName('head').item(0).appendChild(s);
	}

	$(function () {
		window.lpMTagConfig = lpMTagConfig;
		lpAddMonitorTag();
	});
}(jQuery));


(function ($) {
	$(function () {
		if ($('body').hasClass('support')) {
			window.uvOptions = {};
			(function() {
				var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
				uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/OkG7rNyBu6y0GEApHXig.js';
				var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
			})();
		}
	});
}(jQuery));

// pattern
//(function () {
//    function init() {
//        $(function() {
//        });
//    }

//    // export api
//    window.kareo = window.kareo || {};
//    window.kareo._______ = {
//        init: init
//    };
//}());

// window.kareo.practiceFusion
(function () {
	function init() {
		$(function () {
			$(".pflinktyperadio").click(function () {
				var selected = $(this).val(),
					id = selected.split("-")[2];
				$(".pflinker-" + id + " div").slideUp();
				$("." + this.value).slideDown();
			});

			// Loop through each radio button to process the selected
			$(".pflinktyperadio").each(function () {
				var child = $(this),
					selected,
					id;

				if (child.is(":radio:checked")) {
					selected = child.attr("value");
					id = selected.split("-")[2];
					$(".pflinker-" + id + " div").slideUp();
					$("." + this.value).slideDown();
				}
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.practiceFusion = {
		init: init
	};
}());

// window.kareo.customerReferralProgram
(function () {
	function init() {
		$(function () {
			// Toggle Details on Referral Page
			$('#referraldetails-toggle').click(function (event) {
				$('#referraldetails').comboToggle();
				event.preventDefault();
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.customerReferralProgram = {
		init: init
	};
}());

// window.kareo.faqs
(function () {
	function init() {
		$(function () {
			$("ul.faqs li h4, ul.faqs li h5").click(function () {
				$(this).siblings('p').slideToggle("fast");
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.faqs = {
		init: init
	};
}());

// window.kareo.hint
(function () {
	function init() {
		$(function () {
			$(".hint").tooltip({
				track: true,
				delay: 0,
				showURL: false,
				showBody: " - ",
				fade: 250
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.hint = {
		init: init
	};
}());

// window.kareo.jqm
(function () {
	function onHideFun(hash) {
		hash.w.hide();
		hash.w.html("");
		if (hash.o) {
			hash.o.remove();
		}
	}

	function init() {
		$(function () {
			// Homepage Videos
			var videoCount = VIDEO_REVIEWS_COUNT,
				videoNumber;

			for (videoNumber = 1; videoNumber <= videoCount; videoNumber++) {
				$('#video_' + videoNumber + '_modal').jqm({ toTop: true, trigger: 'a.video_' + videoNumber + '_trigger', closeClass: "video_close", ajax: "@href", onHide: onHideFun });
			}
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.jqm = {
		init: init
	};
}());

// window.kareo.demos
(function () {
	var GOGGLE_ANALYTICS_EVENT_CATEGORY = 'Demos Center',
		GOGGLE_ANALYTICS_EVENT_ACTION = 'Play Demo Video',
		config = {
			autoPlay: false,
			videos: [],
			youTubeId: null
		},
		youTubePlayer,
		youTubePlayerStates = {
			unstarted: -1,
			ended: 0,
			playing: 1,
			paused: 2,
			buffering: 3,
			videoCued: 5
		},
		playerOverlayElement,
		currentVideo,
		ensureHighestQuality = false,
		autoPlay = false;

	function findVideoByPropertyValue(property, value) {
		var i, v;
		for (i = 0; i < config.videos.length; i++)
		{
			v = config.videos[i];
			if (v[property] === value) {
				return v;
			}
		}
		return null;
	}

	function ensureHighestPlaybackQuality() {
		var availableQualities = youTubePlayer.getAvailableQualityLevels();
		if (availableQualities[0] && availableQualities[0] !== youTubePlayer.getPlaybackQuality()) {
			youTubePlayer.setPlaybackQuality(availableQualities[0]);
		}
	}

	function createGoogleAnalyticsEvent() {
		window.pageTracker._trackEvent(
			GOGGLE_ANALYTICS_EVENT_CATEGORY,
			GOGGLE_ANALYTICS_EVENT_ACTION,
			currentVideo.groupId + '/' + currentVideo.videoId
		);
	}

	function onYouTubePlayerStateChange(state) {
		switch (state) {
		case youTubePlayerStates.videoCued:
			if (autoPlay) {
				autoPlay = false;
				youTubePlayer.playVideo();
			}
			if (currentVideo.stillImageUrl) {
				playerOverlayElement.find('.still-image').attr('src', currentVideo.stillImageUrl);
				playerOverlayElement.show();
			} else {
				playerOverlayElement.hide();
			}
			break;

		case youTubePlayerStates.playing:
			playerOverlayElement.hide();
			if (ensureHighestQuality) {
				ensureHighestQuality = false;
				ensureHighestPlaybackQuality();
				createGoogleAnalyticsEvent();
			}
			break;
		}
	}

	function initializeYouTubePlayer(videoId, callback) {
		var containerId = 'youtube-player-container',
			playerId = 'youTubePlayer';

		window.onYouTubePlayerReady = function (readyPlayerId) {
			if (readyPlayerId === playerId) {
				if (callback) {
					callback(playerId);
				}
			}
		};

		swfobject.embedSWF('http://www.youtube.com/v/' + videoId + 
						   '?rel=0&enablejsapi=1&playerapiid=' + playerId + '&fs=1&hd=1&showsearch=0&showinfo=0', 
						   containerId, '640', '505', '8', null, null,
						   { allowScriptAccess: 'always', wmode: 'opaque' }, { id: playerId });
	}

	function initializeYouTubeOverlay() {
		var player = $('#youtube-player-container');
		
		playerOverlayElement = $('<div class="youtube-player-overlay" style="width: 640px; height: 480px; background-image: url(/img/introducing-kareo-video-still.png); position: absolute; display: none; cursor: pointer;" />');
		playerOverlayElement.bind('click', function () {
			youTubePlayer.playVideo();
		});
		playerOverlayElement.bind('mouseenter', function () {
			playerOverlayElement.css('background-position', '-640px 0');
		});
		playerOverlayElement.bind('mouseleave', function () {
			playerOverlayElement.css('background-position', '0 0');
		});
		player.parent().prepend(playerOverlayElement);
	}

	function playVideo(video) {
		if (!currentVideo || currentVideo.groupId !== video.groupId || currentVideo.videoId !== video.videoId) {
			currentVideo = video;
			ensureHighestQuality = true;
			if (youTubePlayer.getPlayerState() === youTubePlayerStates.videoCued) {
				youTubePlayer.cueVideoById(video.youTubeId);
				onYouTubePlayerStateChange(youTubePlayerStates.videoCued);
			} else {
				youTubePlayer.cueVideoById(video.youTubeId);
			}
			$('#headline h1').text(video.h1);
			$('#headline h2').text(video.h2);
		}
	}

	function onTabClicked(event) {
		var anchor = $(this),
			demoPicker = $('#demo-picker');

		if (!anchor.parent('li').hasClass('on')) {
			demoPicker.find('.group-videos:visible').hide();
			demoPicker.find(anchor.attr('href')).show();
			demoPicker.find('.demo-picker-nav .on').removeClass('on');
			anchor.parent('li').addClass('on');
		}
		event.preventDefault();
	}

	function initializeTabs() {
		var demoPicker = $('#demo-picker'),
			nav = $('<ul class="demo-picker-nav" />').prependTo(demoPicker);

		// modify dom
		demoPicker.find('h3').each(function () {
			var h3 = $(this),
				li = $('<li />').appendTo(nav);
			h3.contents().appendTo(li);
			h3.remove();
		});

		// support tab selection
		nav.find('a').bind('click', onTabClicked);
		// set the active tab
		nav.find('a').eq(0).triggerHandler('click');
	}

	function selectTab(groupId) {
		$('#demo-picker .demo-picker-nav a[href="#' + groupId + '"]').triggerHandler('click');
	}

	function onHashChanged() {
		var video = (window.location.hash && window.location.hash.length > 0) ?
			findVideoByPropertyValue('hashUrl', window.location.pathname + window.location.hash) :
			findVideoByPropertyValue('youTubeId', config.youTubeId);

		selectTab(video.groupId);
		playVideo(video);
	}

	function ensurePlayerVisible() {
		var isViewPortLargerTallerThanPlayer,
			isPlayerCompletelyVisible,
			$window = $(window),
			$youTubePlayer = $(youTubePlayer);

		isViewPortLargerTallerThanPlayer = $window.height() > $youTubePlayer.outerHeight();
		if (isViewPortLargerTallerThanPlayer) {
			isPlayerCompletelyVisible = ($window.scrollTop() < $youTubePlayer.offset().top) && (($youTubePlayer.offset().top + $youTubePlayer.outerHeight()) < ($window.scrollTop() + $window.height()));
			if (!isPlayerCompletelyVisible) {
				$.scrollTo($('#demo-view'), 250);
			} 
		}
	}

	function onVideoLinkClicked(event) {
		var anchor = $(this),
			url = anchor.attr('href'),
			video = findVideoByPropertyValue('url', url);

		event.preventDefault();
		autoPlay = true;
		window.location.href = video.hashUrl;
		ensurePlayerVisible();
	}

	function onRequestButtonClick(event) {
		$('#demo-request').block({
			message: '<h1>Please wait...</h1>',
			css: {
				width: '80%'
			}
		});

		// post the form via ajax
		$('#demo-request form').ajaxSubmit({
			cache: false,
			dataType: 'text',
			error: function () {
				// resubmit the form without ajax so the user is aware of the error
				$('#demo-request form').submit();
			},
			success: function (data) {
				$('#demo-request').unblock().html(data);
				window.kareo.trackConversion('Lead');
				// TODO: scroll top of #demo-request into view
			}
		});

		event.preventDefault();
	}

	function init(options) {
		$.extend(config, options);
		$(function () {
			// tabs UI
			initializeTabs();
			// ajax form
			$('#demo-request button').live('click', onRequestButtonClick);
			// create overlays to show custom video thumbnails in youtube player
			initializeYouTubeOverlay();
			// load the video
			autoPlay = config.autoPlay;
			currentVideo = findVideoByPropertyValue('hashUrl', window.location.pathname + window.location.hash);
			if (currentVideo) {
				$('#headline h1').text(currentVideo.h1);
				$('#headline h2').text(currentVideo.h2);
			} else {
				currentVideo = findVideoByPropertyValue('youTubeId', config.youTubeId);
			}
			initializeYouTubePlayer(currentVideo.youTubeId, function (playerId) {
				youTubePlayer = $('#' + playerId)[0];
				youTubePlayer.addEventListener('onStateChange', 'window.kareo.demos.onYouTubePlayerStateChange');
				
				// enable hash url support
				$(window).bind('hashchange', onHashChanged);
				$('#demo-picker a.playable-demo').bind('click', onVideoLinkClicked);
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.demos = {
		init: init,
		onYouTubePlayerStateChange: onYouTubePlayerStateChange
	};
}());

// window.kareo.contact
(function () {
	var config = {
			isNotCurrentCustomerId: null,
			isCurrentCustomerId: null,
			jobTitleId: null,
			businessTypeId: null,
			postalCodeId: null,
			postalCodeValidatorId: null,
			referralSourceId: null,
			referralSourceValidatorId: null,
			sendContactFormButtonId: null
		};

	function onIsCurrentCustomerChanged(event) {
		var isCurrentCustomer = $('#' + config.isCurrentCustomerId).is(':checked'),
			selectors = [
				'#' + config.jobTitleId,
				'#' + config.businessTypeId,
				'#' + config.postalCodeId,
				'#' + config.referralSourceId
			];

		$.each(selectors, function (index, selector) {
			if (isCurrentCustomer) {
				$(selector).parent('li').hide('fast');
			} else {
				$(selector).parent('li').show('fast');
			}
		});
		window.ValidatorEnable($('#' + config.postalCodeValidatorId)[0], !isCurrentCustomer);
		window.ValidatorEnable($('#' + config.referralSourceValidatorId)[0], !isCurrentCustomer);
		$('#' + config.postalCodeValidatorId).hide();
		$('#' + config.referralSourceValidatorId).hide();
		if ($(this).is(':radio')) {
			$(this).focus();
		}
	}

	function init(options) {
		$.extend(config, options);
		$(function () {
			$('#JavaScriptUnavailable').val('false');

			$('#' + config.sendContactFormButtonId).bind('click', function (event) {
				event.preventDefault();
			});

			$('#' + config.isNotCurrentCustomerId).bind('click', onIsCurrentCustomerChanged);
			$('#' + config.isCurrentCustomerId).bind('click', onIsCurrentCustomerChanged);
			onIsCurrentCustomerChanged();
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.contact = {
		init: init
	};
}());

// window.kareo.pricing
(function () {
	function onAskButtonClick(event) {
		$('#pricing-request').block({
			message: '<h1>Please wait...</h1>',
			css: {
				width: '80%'
			}
		});

		// post the form via ajax
		$('#pricing-request form').ajaxSubmit({
			cache: false,
			dataType: 'text',
			error: function () {
				// resubmit the form without ajax so the user is aware of the error
				$('#pricing-request form').submit();
			},
			success: function (data) {
				$('#pricing-request').unblock().html(data);
				window.kareo.trackConversion('Lead');
			},
			complete: function (request) {
				$('#pricing-request').unblock();
			}
		});

		event.preventDefault();
	}

	function init() {
		$(function () {
			// ajax form
			$('#pricing-request button').live('click', onAskButtonClick);
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.pricing = {
		init: init
	};
}());

// window.kareo.reviews
(function () {

	function initializeAnythingSlider() {
		$('.anythingSlider').fadeIn();

		$('.anythingSlider').anythingSlider({
			easing: "swing",
			autoPlay: false,
			animationTime: 0,              // How long the slide transition takes
			hashTags: true,                // Should links change the hashtag in the URL?
			buildNavigation: false         // If true, builds and list of anchor links to link to each slide
		});

		var videoCnt = $(".anythingSlider li:not(.cloned)").length,
			randomVid = Math.ceil(Math.random() * videoCnt);

		$('.anythingSlider').anythingSlider(randomVid);
		$('.anythingSlider').data('AnythingSlider').options.animationTime = 600;
	}

	function hasClass(element, classes) {
		for (var i = 0; i < classes.length; i++) {
			if (element.hasClass(classes[i])) {
				return true;
			}
		}
		return false;
	}

	function onFilterChanged() {
		var reviewTypeFilters = [],
			specialtyFilters = [],
			reviews;

		// populate filters
		$('#filter .review-type-filters input:checkbox:checked').each(function () {
			var filter = $(this).attr('id').split('-')[1];
			reviewTypeFilters.push(filter);
		});
		$('#filter .specialty-filters input:checkbox:checked').each(function () {
			var filter = $(this).attr('id').split('-')[1];
			specialtyFilters.push(filter);
		});
		// hide/show reviews
		reviews = $('.review');
		reviews.hide();
		if (reviewTypeFilters.length !== 0 && specialtyFilters.length !== 0) {
			reviews = reviews.filter(function () {
				// return true to show this element
				var self = $(this);
				return hasClass(self, reviewTypeFilters) && hasClass(self, specialtyFilters);
			});
			reviews.show();
		}
	}

	function onHashChanged(event) {
		var filter;

		filter = window.location.hash || '#/all';
		filter = filter.substr(2);
		//Remove the 'active' class from all the filter links
		$('#scope li a').removeClass('active');
		//Add it to this one.
		$('#scope li a[href="#' + filter +'"]').addClass('active');
		//If we clicked the "all" link...
		if (filter === 'all') {
			//Show all the feedback items
			$('#results .result-set').show();
		} else {
			//...then show just the ones who's ID matches the feedback items class
			$('#results .result-set').hide();
			$('.result-set#' + filter).fadeIn();
		}
	}

	function replaceHash(value) {
		var url = window.location.toString(),
			hashIndex = url.indexOf('#');

		if (hashIndex >= 0) {
			url = url.substr(0, hashIndex);
		}
		url = url + '#/' + value;
		window.location.replace(url);
	}

	function init() {
		$(function () {
			initializeAnythingSlider();

			$(window).bind('hashchange', onHashChanged);
			$(window).trigger('hashchange');

			$('#scope li a').click(function (event) {
				var currentHash = window.location.hash,
					selection = $(this).attr('href').substr(1);

				if (currentHash !== '#/' + selection) {
					$('#results .result-set').fadeOut();
					replaceHash(selection);
				}
				event.preventDefault();
			});


			$('#filter input:checkbox').click(function () {
				onFilterChanged();
			});
			
			$("#checkboxall").click(function (event) {
				var isSelectingAll = $(this).text() === 'Select All';
				if (isSelectingAll) {
					$('#tocheckall input:checkbox').attr('checked', 'checked');
				} else {
					$('#tocheckall input:checkbox').removeAttr('checked');
				}
				$(this).text(isSelectingAll ? 'Deselect All' : 'Select All');
				onFilterChanged();
				event.preventDefault();
			});
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.reviews = {
		init: init
	};
} ());

// window.kareo.seo
(function () {
	function init() {
		// Details Panel
		// Move to Bottom
		$('#detail_panel_wrap').hide();
		$('#seo-target').append($('#detail_panel_wrap'));
		$('#detail_panel_wrap').show();
		$('#detail_panel_wrap').addClass('loaded');
		//Hide More details on page load
		$('.detail_panel_more, .detail_linkage_more').hide();

		//Click Read More
		$('.panel_more').click(function () {
			$(this).fadeOut('fast');
			$('.detail_panel_more, .detail_linkage_more').comboToggle();
			return false;
		});

		//Click Collapse
		$('.panel_less').click(function () {
			$('.detail_panel_more, .detail_linkage_more').comboToggle();
			$('.panel_more').fadeIn('fast');
			return false;
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.seo = {
		init: init
	};
}());

// window.kareo.home
(function () {
	function initializeAnythingSlider() {
		$('.anythingSlider').fadeIn();
		
		$('.anythingSlider').anythingSlider({
			easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
			autoPlay: false,
			animationTime: 0,             // How long the slide transition takes
			hashTags: false,                // Should links change the hashtag in the URL?
			buildNavigation: false         // If true, builds and list of anchor links to link to each slide
		});
   
		var videoCnt = $(".anythingSlider li:not(.cloned)").length,
			randomVid = Math.ceil(Math.random() * videoCnt);
		$('.anythingSlider').anythingSlider(randomVid);
		$('.anythingSlider').data('AnythingSlider').options.animationTime = 600;
	}

	function init() {
		$(function () {
			var hint = 'Enter your email address...',
				inputElement = $('#subscribe-to-newsletter-form input[name=emailaddress]'),
				submitElement = $('#subscribe-to-newsletter-form input[type=submit]');

			inputElement.val(hint);
			inputElement.focus(function () {
				if ($(this).val() === hint) {
					$(this).val('');
				}
			});
		
			submitElement.click(function (event) {
				if (inputElement.val() === hint) {
					inputElement.val('');
				}
			});

			initializeAnythingSlider();
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.home = {
		init: init
	};
}());

// window.kareo.billingTip
(function () {
	function init() {
		$(function () {
			$(document).ready(function () {
				var validator = $("#billingTipForm").validate();

				$("#billingTipForm").submit(function () {
					if (validator.form() == false) {
						return false;
					}

					$.post(
								$("#billingTipForm").attr("action"),
								$("#billingTipForm").serialize()
							);

					$("#billingTipForm").slideUp("normal", function () {
						$("#billingTipForm").before('<h2>Thanks for the tip!</h2>');
					});

					return false;
				});
			});
		});
	}
	// export api
	window.kareo = window.kareo || {};
	window.kareo.billingTips = {
		init: init
	};
} ());

// window.kareo.landingPage
(function () {

	function onRequestDemo_Error()
	{
		$('form').submit();
	}

	function onRequestDemo_Success(html)
	{
		try {
			var o = JSON.parse(html);
			if (o && o.redirectTo) {
				window.location = o.redirectTo;
			}
		} catch (e) { }

		$('#form .replaced-via-ajax').parent('div.replace-container').html(html);
		$.unblockUI();
		window.kareo.trackConversion('Lead');
	}

	function onSubmitButton_Clicked(event)
	{
		$.blockUI({
			message: $('#blockUI')
		});
		$('form').ajaxSubmit({
			cache: false,
			error: onRequestDemo_Error,
			success: onRequestDemo_Success
		});
		event.preventDefault();
	}

	function init() {
		$(function () {
			$('form button').live('click', onSubmitButton_Clicked);
		});
	}

	// export api
	window.kareo = window.kareo || {};
	window.kareo.landingPage = {
		init: init
	};
}());

(function ($) {
	window.kareo = window.kareo || {};
	window.kareo.trackConversion = function(type) {

		function loadSearchForceScript(callback) {
			var searchForceScriptUrl = ((document.location.toString().indexOf('https:') === 0) ? 'https' : 'http') + '://sftrack.searchforce.net/SFConversionTracking/CTCommon.js';
			$.getScript(searchForceScriptUrl, callback);
		}

		function trackConversionCore() {

			// enforce context            
			if (this !== window) {
				trackConversionCore.call(window);
				return;
			}

			// BEGIN Searchforce
			SFCookie.include();
			window.jconversion_type = type;
			window.jValue = '';
			window.jOrderID = '';
			ImageJSConversionProcess();
			// END Searchforce

			// BEGIN Capterra
			var capterra_vkey = "369f6fab525ba70e647466c8a46ff4b4";
			var capterra_vid = "2028482";
			var capterra_prefix  = (("https:" == document.location.protocol) ? "https://ct.capterra.com" : "http://ct.capterra.com");
			$.getScript(capterra_prefix + '/capterra_tracker.js?vid=' + capterra_vid + '&vkey=' + capterra_vkey);
			// END Capterra
		}

		// ensure a #sf_fl_content element exists
		if ($('#sf_fl_content').length === 0) {
			$('<div id="sf_fl_content"></div>').appendTo('body');
		}

		if (typeof SFCookie === 'undefined') {
			loadSearchForceScript(trackConversionCore);
		} else {
			trackConversionCore();
		}
	};
}(jQuery));

// window.kareo.signup
(function ($) {
	window.kareo = window.kareo || {};
	window.kareo.signup = {
		init: function () {

			$(function () {
				$('input:checkbox,select').uniform();
				$('select').each(function () {
					$(this).height($(this).parent().height() - 2);
					$(this).css({
						'line-height': $(this).parent().css('line-height'),
						'margin-left': '2px'
					});
				});
			});

			$(function () {
				var buttons = $('#plandetails .showinfo');
				buttons.parents('dt').next('dd').hide();
				buttons.show()
				buttons.bind('click', function () {
					$(this).parents('dt').next('dd').comboToggle();
				});
			});

			// replace payment method radio buttons with a toggle button
			$(function () {
				var button = $('.js-togglePaymentMethodButton'),
					radioButtons = $('input[name="PaymentByCreditCard"]'),
					hidden = $('<input type="hidden" id="PaymentByCreditCard" name="PaymentByCreditCard">'),
					debitFields = $('.js-debitFields'),
					creditFields = $('.js-creditFields');

				hidden.appendTo(radioButtons.parents('form'));
				hidden.bind('change', function () {
					var isCredit = (hidden.val() === 'True');
					button.text(isCredit ? 'Use Direct Debit' : 'Use Credit Card');
					creditFields[isCredit ? 'show' : 'hide']();
					debitFields[isCredit ? 'hide' : 'show']();
				});

				hidden.val(radioButtons.filter(':checked').attr('value'));
				hidden.trigger('change');

				button.show();
				button.bind('click', function () {
					var isCredit = hidden.val() === 'True';
					hidden.val(isCredit ? 'False' : 'True');
					$('.js-creditFields input, .js-debitFields input').val('');
					hidden.trigger('change');
				});

				radioButtons.each(function () {
					var labels = $('label[for="' + this.id + '"]');
					labels.remove();
				});
				radioButtons.remove();
			});

			$(function () {
				function updatePlanDetail() {
					$('dt.js-support-none')[$('#emailsupport').is(':checked') ? 'show' : 'hide']();
					$('dt.js-support-phone')[$('#phonesupport').is(':checked') ? 'show' : 'hide']();
					$('dd.js-support').hide();
				}

				$('.js-support-noscript').hide();
				$('input[name="SupportTypeID"]').bind('click', updatePlanDetail);
				updatePlanDetail();
			});

			$(function () {                
				$('.js-toggleReferralCodeButton').show().bind('click', function () {
					$('.js-signupCodeField').comboToggle();
				});

				if ($('.js-toggleReferralCodeButton').length !== 0 && !$('.js-signupCodeField input').val())
					$('.js-signupCodeField').hide();
			});

			$(function () {
				var agreedCheckBox = $('.js-agreedToTermsCheckbox'),
					submitButton = $('.js-createAccountButton');

				function updateSubmitButton() {
					submitButton.toggleClass('disabled', !agreedCheckBox.is(':checked'));
				}

				function onSubmitButtonClicked(e) {
					if (!agreedCheckBox.is(':checked')) {
						e.preventDefault();
						$('form').valid();
						$('#agreementconfirm').toggleClass('attn', true);
						$('#createaccount').toggleClass('error', true);
					}
				}

				function onAgreedCheckBoxChanged(e) {
					updateSubmitButton();
					if (agreedCheckBox.is(':checked')) {
						$('#createaccount').toggleClass('error', false);
					}
				}

                function onSubmitted(e) {
                    if ($('form').valid()) {
					    // block duplicate submissions for 90s
					    var now = (new Date()).getTime(),
						    lastSubmit = (onSubmitted.lastSubmit || 0);

					    if (now - lastSubmit < 90000) {
						    e.preventDefault();
						    if (console && typeof console.log === 'function')
							    console.log('skipping');
						    return;
					    }

					    onSubmitted.lastSubmit = now;
					    if (console && typeof console.log === 'function')
						    console.log('submitting');
                    }
				}

				updateSubmitButton();
				agreedCheckBox.bind('click', onAgreedCheckBoxChanged);
				submitButton.bind('click', onSubmitButtonClicked);
				submitButton.parents('form').bind('submit', onSubmitted);
			});

			(function ($) {
				$.validator.addMethod('requiredif', function (value, element, params) {

					var dependentVal = ($('#' + params['dependentProperty']).val() || '').toLowerCase(),
						targetValues = params['targetValues'].split(','),
						i;
					for (i = 0; i < targetValues.length; i++) {
						if (dependentVal == targetValues[i].toLowerCase()) {
							return $.trim(value).length > 0;
						}
					}
					return true;

				}, 'not used');

				$.validator.unobtrusive.adapters.add('requiredif', ['dependentProperty', 'targetValues'], function (options) {

					options.rules['requiredif'] = options.params;
					if (options.message) {
						options.messages['requiredif'] = options.message;
					}

				});
			} (jQuery));

			(function ($) {
				$.validator.addMethod('equalToValue', function (value, element, params) {

					element = $(element);
					if (element.is(':checkbox'))
						value = element.is(':checked');
					value = '' + value;
					params = '' + params;
					return value.toLowerCase() == params.toLowerCase();

				}, 'not used');

				$.validator.unobtrusive.adapters.add('equaltovalue', ['value'], function (options) {

					options.rules['equalToValue'] = options.params['value'];
					if (options.message) {
						options.messages['equalToValue'] = options.message;
					}

				});

			} (jQuery));

			// care360 providers
			$(function () {
				var template = $('.care360provider-listitem').eq(0).clone();

				// whenever a provider row is added or removed
				// this function will be called to update the id
				// and name attributes of the user input elements
				// in order to maintain consecutive indexing
				function updateIndexes() {
					var items = $('.care360provider-listitem');
					items.each(function(index) {
						$(this).find('input,select').each(function () {
							var field = $(this).attr('name').match(/Providers\[(?:\d)*\].(.*)/)[1];
							$(this).attr('id', 'Providers_' + index + '__' + field);
							$(this).attr('name', 'Providers[' + index + '].' + field);
						});

						// hide any validation messages which might have been showing on the source of the clone
						$(this).find('.field-validation-error').toggleClass('field-validation-error', false).toggleClass('field-validation-valid', true).empty();

						$(this).find('.field-validation-valid').each(function () {
							var field = $(this).attr('data-valmsg-for').match(/Providers\[(?:\d)*\].(.*)/)[1];
							$(this).attr('data-valmsg-for', 'Providers[' + index + '].' + field);
						});
					});
				}

				$('.add-provider').bind('click', function () {
					var clone = template.clone();
					$('#care360provider-list').append(clone);
					updateIndexes();

					// tidy up junk that the 'uniform' plugin adds
					clone.find('select').siblings().remove().end().unwrap().uniform();

					// attach validation logic
					clone.find('input,select').each(function () {
						$.validator.unobtrusive.parseDynamicContent(this);
					});

					clone.find('input,select').eq(0).focus();
				});

				$('.remove-provider').live('click', function () {
					$(this).parents('.care360provider-listitem').remove();
					updateIndexes();
				});

			});
		}
	};
}(jQuery));
