/* JS
Author: Simande LLC
Created: 02-01-2010
*/

//Preloading images BEFORE page is done loading
//USE: $.preLoadImages("/image-path.gif");
(function($) {
	var cache = [];
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery);

var theme_image_path = "/wp-content/themes/instamed/images/";
$.preLoadImages(theme_image_path + "banner-full-bg.jpg");
$.preLoadImages(theme_image_path + "subnav-bg-top.png");
$.preLoadImages(theme_image_path + "subnav-bg-btm.png");
$.preLoadImages(theme_image_path + "bg-header.gif");
$.preLoadImages(theme_image_path + "sidebar-module-bg.gif");

if ($.browser.msie) {
	$.preLoadImages(theme_image_path + "bg-header-ie.gif");
	$.preLoadImages(theme_image_path + "carousel-bg-ie.jpg");
	$.preLoadImages(theme_image_path + "carousel-bar-bg-ie6.jpg");
	$.preLoadImages(theme_image_path + "carousel-bg-sm.jpg");
	$.preLoadImages(theme_image_path + "carousel-bar-bg-sm.jpg");
}

var getCookieSet = function(cookieName) {
	var cookies = document.cookie.split(';');
	var cookieList = '';
	for(i = 0; i < cookies.length; i++) {
		var cookie = jQuery.trim(cookies[i]);
		if(cookie.substring(0, cookieName.length) == cookieName) {
			cookieList += decodeURIComponent(cookie.substring(cookieName.length)).replace(/\[/, '&').replace(/\]/, '');
		}
	}
	//removes first ampersand
	if(cookieList) {
		return cookieList.replace(/\&/, '');
	} else { 
		return false;
	}
};

//Action that inserts relevant content into overlay
//Overlay is already initiated by openDialog function
(function($) {

	$.fn.formsPopup = function(options) {
		var config = {
			needsInsert: false
		};
		var opts = $.extend({}, config, options);
		
		var insertOtherInfo = function(ele, pdfName) {
			if(ele != 'pdf') {
				var content = $(ele).attr("name");
			} else {
				content = ele;
			}
			$($("div.hide div." + content)).appendTo($("#dialog"));
			$("#ui-dialog-title-dialog").text($('div.'+content).attr('name'));
			$("#dialog").dialog('open');
			
			//Submits cached user info each time user clicks
			if(getCookieSet('salesforce') != false && ele == 'pdf') {
				$.ajax({
					url: '/wp-content/themes/instamed/pdf-submit.php',
					data: getCookieSet('salesforce') + '&lead_source=Subsequent Download&pdf_name=' + pdfName,
					type: 'post',
					success: function(data) {
						//console.log(data);
					}
				});
			}
		};
		
		var insertFilename = function(val) {
			var filename = val.replace('/pdfs/', '');
			
			$("div.pdf .pdf").text(filename);
			$("div.pdf div.hide a.pdf").attr('href', val);
			$("div.pdf div.hide p.pdf a").text(filename);
			
			var pdfName = '';
			switch(filename) {
				case 'InstaMed-Provider-Solutions.pdf':
					pdfName = "InstaMed Provider Solutions";
					break;
				case 'InstaMed-Payer-Solutions.pdf':
					pdfName = "Payer Solutions";
					break;
				case 'Trends-in-Healthcare-Payments-Annual-Report-2010.pdf':
					pdfName = "Trends in Healthcare Payments Annual Report 2010";
					break;
				case 'InstaMed-Partner-Program.pdf':
					pdfName = "Partner Program";
					break;
				case 'The-Emergence-Of-The-Collaborative-Healthcare-Payments-Model-White-Paper.pdf':
					pdfName = "The Emergence Of The Collaborative Healthcare Payments Model White Paper";
					break;
				case 'InstaMed-Company.pdf':
					pdfName = "Company";
					break;
				case 'Unveiling-The-Truth-Behind-Real-Time-Adjudication-White-Paper.pdf':
					pdfName = "Unveiling The Truth Behind Real-Time Adjudication White Paper";
					break;
				case 'InstaMed-Testimonials.pdf':
					pdfName = "Testimonials";
					break;
				case 'Healthcare-Payments-White-Paper-Providers.pdf':
					pdfName = "Healthcare Payments White Paper Providers";
					break;
				case 'Healthcare-Payments-White-Paper-Payers.pdf':
					pdfName = "Healthcare Payments White Paper Payers";
					break;
				case 'Payer-Solution-Profile-Electronic-Claims-Reimbursement.pdf':
					pdfName = "Payer Solution Profile Electronic Claims Reimbursement";
					break;
				default:
					pdfName = val;
					break;
			}

			$("div.pdf input[name='pdf_name']").val(pdfName);
			insertOtherInfo('pdf', pdfName);
		};
		
		return this.each(function(i, ele) {
			$(this).click(function() {
				if(opts.needsInsert === true) {
					insertOtherInfo(ele);
				} else {
					insertFilename($(this).attr("href"));
				}
				return false;
			});
		});
	}
})(jQuery);

(function($) {

	$.fn.testimonials = function() {
		
		var listCount = this.length;
		var rand = Math.floor(Math.random()*listCount);
		
		return this.each(function(i, ele) {
			if(i == rand) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	}
	
})(jQuery);

var sidebarNews = function() {
	var flipper = 0;
	$("div.module_paginate a").click(function() {
		if(flipper === 0) {
			$("div.module_paginate span").text("2 of 2");
			$("#news ul:eq(0)").hide();
			$("#news ul:eq(1)").show();
			flipper = 1;
		} else {
			$("div.module_paginate span").text("1 of 2");
			$("#news ul:eq(1)").hide();
			$("#news ul:eq(0)").show();
			flipper = 0;
		}
		return false;
	});
}

//Init overlay, makes it invisible
var openDialog = function() {
	$("#dialog").dialog({
		modal: true,
		bgiframe: true,
		width: 533,
		closeText: '',
		autoOpen: false,
		position: 'center',
		open: function() {
			var currentDialog = this;
			$(window).resize(function() {
				$(currentDialog).dialog('option', 'position', ['center', 'center']);
			});
			$('.ui-widget-overlay').click(function() {
				$("#dialog").dialog('close');
			});
		},
		close: function() {
			$($("#dialog div:eq(0)")).appendTo($("div.hide:eq(0)"));
		}
	});
	$("div.btns a").live('click', function() {
		$("#dialog").dialog('close');
	});
};

var changeFormField = function(trigger, val, ele) {
	trigger.change(function() {
		
		if(val == 'type_to_be_hidden') {
			$(this).val() =='support@instamed.com?support' || $(this).val() == 'productmanagement@instamed.com?product' ? ele.hide() : ele.show();
		} else {
			$(this).val() == 'InstaMed Partner' ? $(ele).find('strong').html('Partner') : $(ele).find('strong').html('Other');
			$(this).val() == 'InstaMed Partner' || $(this).val() == 'Other' ?  ele.show() : ele.hide();
		}
	});
};

//Run these AFTER page is done loading
$(document).ready(function() {
	
	//Used globally for main navigation dropdown
	$("#main_nav li").hover(function() {
		$(this).addClass("hover");
	}, function() {
		$(this).removeClass("hover");
	});
	
	//Custom functions
	if($('#dialog').length) { openDialog(); }
	$("#wrapper a.pdf").formsPopup();
	$("a[name='providers'], a[name='payers']").formsPopup({ needsInsert: true });
	sidebarNews();
	
	//Homepage Carousel uses Carousel Plugin
	//Also uses easing plugin and resets the jQuery default here
	if($("#banner").length) {
		jQuery.easing.def = "easeInOutCubic";
		$('a', '#banner ol').carousel({
			items: $("li", "#banner ul"),
			autoStart: true
		});
	}
	
	//For randomizing testimonials
	if($("div.home_module").length) {
		$("div.home_module ul.testimonials").testimonials();
	} else if($("#extra_content ul.testimonials").length) {
		$("#extra_content ul.testimonials li").testimonials();	
	}
	
	
	/**** FOR FORMS ****/
	
	//Contact form remove select dropdown
	
	changeFormField($("select", "#contact_form li.select:eq(0)"), 'type_to_be_hidden', $("li.select:eq(1)", "#contact_form"));
	
	changeFormField($('select[name="source_name"]', "#pdf_form, #video_form, #business_form, #contact_form"), 'Other', $('.other', 'ul'));
	changeFormField($('select[name="source_name"]', "#pdf_form, #video_form, #business_form, #contact_form"), 'InstaMed Partner', $('.other', 'ul'));
	
	//custom method for phone number validation
	$.validator.addMethod("phoneUS", function(phone_number, element) {
		phone_number = phone_number.replace(/\s+/g, ""); 
		return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please specify a valid phone number");
	
	$.validator.setDefaults({ 
		rules: {
			first_name: "required",
			last_name: "required",
			company: "required",
			email: {
				required: true,
				email: true
			},
			source_name: "required",
			source_other: {
				required: function(ele) {
					return $(ele).parents('form').find('select[name="source_name"]').val() == "Other" || $(ele).parents('form').find('select[name="source_name"]').val() == "InstaMed Partner";
				}
			},
			phone: {
				required: true,
				phoneUS: true
			}
		},
		errorPlacement: function(error, element) {
			error.prependTo(element.parent("li"));
		},
		submitHandler: function(form) {
			$.ajax({
				url: '/wp-content/themes/instamed/pdf-submit.php',
				data: 'first_name='+form['first_name'].value+'&last_name='+form['last_name'].value+'&company='+form['company'].value+'&phone='+form['phone'].value+'&email='+form['email'].value+'&source_name='+form['source_name'].value+'&source_other='+form['source_other'].value+'&pdf_name='+form['pdf_name'].value,
				type: 'post',
				success: function(data) {
					$("#dialog form, div.hide div.pdf form").hide();
					$("#dialog div.hide, div.hide div.pdf div.hide").show();
					$("#ui-dialog-title-dialog").text('Thank you');
				}
			});
			$("#dialog div.btns a").live('click', function() {
				$("#dialog").dialog('close');
			});
		}
	});
	
	//Form validation and ajax post for popup
	$("#pdf_form").validate();
	$("#business_form").validate();
	
	
	//video form validation; added 2011Nov22
	$("#video_form").validate();
	
	//Contact form validation
	$("#contact_form").validate({
		rules: {
			inquiry_type: 'required',
			name: 'required',
			email: {
				required: true,
				email: true
			},
			phone: {
				required: true,
				phoneUS: true
			},
			subject: 'required',
			message: 'required',
			source_name: {
				required: function(ele) {
					return $('select[name="inquiry_type"]').val() != "support@instamed.com?support", "productmanagement@instamed.com?product";
				}
			},
			source_other: {
				required: function(ele) {
					return $(ele).parents('form').find('select[name="source_name"]').val() == "Other" || $(ele).parents('form').find('select[name="source_name"]').val() == "InstaMed Partner";
				}
			}
		},
		errorPlacement: function(error, element) {
			error.prependTo(element.parent("li"));
		}
	});
	$('#ip').validate({
		rules: {
			location: 'required',
			connection: 'required',
			location2: {
				required: function(ele) {
					return $("#other_location").is(':checked');
				}
			},
			connection2: {
				required: function(ele) {
					return $("#other_connection").is(':checked');
				}
			},
			InstaMed_Account_Number: 'required'
		},
		errorPlacement: function(error, element) {
			error.insertBefore(element.parent("p"));
		}
	});
});
