// File: main.js
// Contains all major javascript functions 
/*
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 2.4
 * Last Modified: 3/22/2009
 * 
 * Copyright 2009 Trent Richardson
 * Dual licensed under the MIT and GPL licenses.
 * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt
 * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt
 * This code is used for the prompt that is shown when navigating to an external site
 */
(function($){$.prompt=function(m,o){o=$.extend({},$.prompt.defaults,o);$.prompt.currentPrefix=o.prefix;var ie6=($.browser.msie&&$.browser.version<7);var b=$(document.body);var w=$(window);var msgbox='<div class="'+o.prefix+'box" id="'+o.prefix+'box">';if(o.useiframe&&(($('object, applet').length>0)||ie6))msgbox+='<iframe src="javascript:;" class="'+o.prefix+'fade" id="'+o.prefix+'fade"></iframe>';else{if(ie6)$('select').css('visibility','hidden');msgbox+='<div class="'+o.prefix+'fade" id="'+o.prefix+'fade"></div>';}msgbox+='<div class="'+o.prefix+'" id="'+o.prefix+'"><div class="'+o.prefix+'container"><div class="'+o.prefix+'close">X</div><div id="'+o.prefix+'states"></div>';+'</div></div></div>';var jqib=$(msgbox).appendTo(b);var jqi=jqib.children('#'+o.prefix);var jqif=jqib.children('#'+o.prefix+'fade');if(m.constructor==String){m={state0:{html:m,buttons:o.buttons,focus:o.focus,submit:o.submit}};}var states="";$.each(m,function(statename,stateobj){stateobj=$.extend({},$.prompt.defaults.state,stateobj);m[statename]=stateobj;states+='<div id="'+o.prefix+'_state_'+statename+'" class="'+o.prefix+'_state" style="display:none;"><div class="'+o.prefix+'message">'+stateobj.html+'</div><div class="'+o.prefix+'buttons">';$.each(stateobj.buttons,function(k,v){states+='<button name="'+o.prefix+'_'+statename+'_button'+k+'" id="'+o.prefix+'_'+statename+'_button'+k+'" value="'+v+'">'+k+'</button>';});states+='</div></div>';});jqi.find('#'+o.prefix+'states').html(states).children('.'+o.prefix+'_state:first').css('display','block');jqi.find('.'+o.prefix+'buttons:empty').css('display','none');$.each(m,function(statename,stateobj){var state=jqi.find('#'+o.prefix+'_state_'+statename);state.children('.'+o.prefix+'buttons').children('button').click(function(){var msg=state.children('.'+o.prefix+'message');var clicked=stateobj.buttons[$(this).text()];var forminputs={};$.each(jqi.find('#'+o.prefix+'states :input').serializeArray(),function(i,obj){if(forminputs[obj.name]==undefined)forminputs[obj.name]=obj.value;else if(typeof forminputs[obj.name]==Array)forminputs[obj.name].push(obj.value);else forminputs[obj.name]=[forminputs[obj.name],obj.value];});if(stateobj.submit(clicked,msg,forminputs))removePrompt(true,clicked,msg,forminputs);});state.find('.'+o.prefix+'buttons button:eq('+stateobj.focus+')').addClass(o.prefix+'defaultbutton');});var ie6scroll=function(){jqib.css({top:w.scrollTop()});};var fadeClicked=function(){if(o.persistent){var i=0;jqib.addClass(o.prefix+'warning');var intervalid=setInterval(function(){jqib.toggleClass(o.prefix+'warning');if(i++>1){clearInterval(intervalid);jqib.removeClass(o.prefix+'warning');}},100);}else removePrompt();};var escapeKeyClosePrompt=function(e){var key=(window.event)?event.keyCode:e.keyCode;if(key==27)removePrompt();};var positionPrompt=function(){jqib.css({position:(ie6)?"absolute":"fixed",height:w.height(),width:"100%",top:(ie6)?w.scrollTop():0,left:0,right:0,bottom:0});jqif.css({position:"absolute",height:w.height(),width:"100%",top:0,left:0,right:0,bottom:0});jqi.css({position:"absolute",top:o.top,left:"50%",marginLeft:((jqi.outerWidth()/2)*-1)});};var stylePrompt=function(){jqif.css({zIndex:o.zIndex,display:"none",opacity:o.opacity});jqi.css({zIndex:o.zIndex+1,display:"none"});jqib.css({zIndex:o.zIndex});};var removePrompt=function(callCallback,clicked,msg,formvals){jqi.remove();if(ie6)b.unbind('scroll',ie6scroll);w.unbind('resize',positionPrompt);jqif.fadeOut(o.overlayspeed,function(){jqif.unbind('click',fadeClicked);jqif.remove();if(callCallback)o.callback(clicked,msg,formvals);jqib.unbind('keypress',escapeKeyClosePrompt);jqib.remove();if(ie6&&!o.useiframe)$('select').css('visibility','visible');});};positionPrompt();stylePrompt();if(ie6)w.scroll(ie6scroll);jqif.click(fadeClicked);w.resize(positionPrompt);jqib.keypress(escapeKeyClosePrompt);jqi.find('.'+o.prefix+'close').click(removePrompt);jqif.fadeIn(o.overlayspeed);jqi[o.show](o.promptspeed,o.loaded);jqi.find('#'+o.prefix+'states .'+o.prefix+'_state:first .'+o.prefix+'defaultbutton').focus();return jqib;};$.prompt.defaults={prefix:'jqi',buttons:{Ok:true},loaded:function(){},submit:function(){return true;},callback:function(){},opacity:0.6,zIndex:999,overlayspeed:'slow',promptspeed:'fast',show:'fadeIn',focus:0,useiframe:false,top:"15%",persistent:true,state:{html:'',buttons:{Ok:true},focus:0,submit:function(){return true;}}};$.prompt.currentPrefix=$.prompt.defaults.prefix;$.prompt.setDefaults=function(o){$.prompt.defaults=$.extend({},$.prompt.defaults,o);};$.prompt.setStateDefaults=function(o){$.prompt.defaults.state=$.extend({},$.prompt.defaults.state,o);};$.prompt.getStateContent=function(state){return $('#'+$.prompt.currentPrefix+'_state_'+state);};$.prompt.goToState=function(state){$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');$('#'+$.prompt.currentPrefix+'_state_'+state).slideDown('slow',function(){$(this).find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.nextState=function(){var next=$('.'+$.prompt.currentPrefix+'_state:visible').next();$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');next.slideDown('slow',function(){$(this).find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.prevState=function(){var next=$('.'+$.prompt.currentPrefix+'_state:visible').prev();$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');next.slideDown('slow',function(){$(this).find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.close=function(){$('#'+$.prompt.currentPrefix+'box').fadeOut('fast',function(){$(this).remove();});};})(jQuery);						   
 
// Start function when DOM has completely loaded 
$(document).ready(function(){ 

	$('.r-url').each(function() {
		if (new String(window.location).indexOf('//dev-') != -1) {
			$(this).attr('href', $(this).attr('href').replace('www.', 'dev-www.').replace('apps.', 'dev-apps.'));
		} else if (new String(window.location).indexOf('//test-') != -1) {
			$(this).attr('href', $(this).attr('href').replace('www.', 'test-www.').replace('apps.', 'test-apps.'));
		} else if (new String(window.location).indexOf('//qa-') != -1) {
			$(this).attr('href', $(this).attr('href').replace('www.', 'qa-www.').replace('apps.', 'qa-apps.'));
		}
	});
	
	// Get path to determine which sections to load
	var path = document.location.pathname;
	
	// Load Google Search
	if (path == "/search/") {
		new google_search();
	}
	
	// States AJAX
	if(path == '/about-availity/where-are-we-now/availability/') {
		var states = getURLParam('states');
		if(states) {
			$('#states').val(states);
			get_xml(states);
		}
	}
	
	// Salesforce
	if(path == '/about-availity/contact-us/') {
		if (new String(window.location).indexOf('//dev-') != -1) {
			$('#contact_availity').attr('action', 'https://cs1.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8');
			$('#sf_oid').val('00DS0000000EO2L');
			$('#sf_retURL').val('http://dev-www.availity.com/about-availity/contact-us/thank-you/');
		} else if (new String(window.location).indexOf('//test-') != -1) {
			$('#contact_availity').attr('action', 'https://cs1.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8');
			$('#sf_oid').val('00DS0000000EO2L');
			$('#sf_retURL').val('http://test-www.availity.com/about-availity/contact-us/thank-you/');
		} else if (new String(window.location).indexOf('//qa-') != -1) {
			$('#contact_availity').attr('action', 'https://cs1.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8');
			$('#sf_oid').val('00DS0000000EO2L');
			$('#sf_retURL').val('http://qa-www.availity.com/about-availity/contact-us/thank-you/');
		} else {
			$('#contact_availity').attr('action', 'https://na4.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8');
			$('#sf_oid').val('00D300000000I3W');
			$('#sf_retURL').val('http://www.availity.com/about-availity/contact-us/thank-you/');
		}
	}
	
    //////////////////////////////////////////////////////////
    // BACK TO TOP - Scroll Smoothly
    //////////////////////////////////////////////////////////

	// back to top links
    $(".top a").click(function(){
      $('html, body').animate({scrollTop:0}, 'slow'); 
      return false;
    });
	
    //////////////////////////////////////////////////////////
    // Sliding Content
    //////////////////////////////////////////////////////////

	// "sliding" sidebar callout
    $("#callout-slide-trigger").click(function(){
      $('#callout-slide').slideToggle(); 
      return false;
    });
 
	// "sliding" sidebar callout 2
    $("#callout-slide-trigger2").click(function(){
      $('#callout-slide2').slideToggle(); 
      return false;
    });

	//////////////////////////////////////////////////////////
    // Open Links in a new window
    //////////////////////////////////////////////////////////	
	
	// This is to due to the XHTML stricht deprecation of target="_blank"
	$('a.new-window').click( function() { 
            window.open(this.href);  
            return false; 
    });
	
	//////////////////////////////////////////////////////////
    // Handles links to external sites
    //////////////////////////////////////////////////////////

	function externalPrompt(l){
		var txt = 'You are about to leave Availity\'s secure site and enter a third-party site, which may require a separate log-in. Availity provides the link to this site for your convenience and reference only.  Availity cannot control such sites, does not necessarily endorse and is not responsible for their content, products, or services.';
		
		$.prompt(txt,{ 
			buttons:{'I agree':true, Cancel:false},
			callback: function(v,m,f){
				
				if(v){
					window.open(l);
				}
				else{}
				
			}
		});
	}
	
	var safeList = new Array('availity.com', 'apps.availity.com');
	$.extend($.expr[':'], {
		external: function(a, i, m) {
			if (!a.href) { return false; }
			if (a.hostname && a.hostname !== window.location.hostname) {
				var fixedHostname = a.hostname.replace(/^\s+|\s+$/g, '').replace('www.', '').toLowerCase();
				if (jQuery.inArray(fixedHostname, safeList) >= 0) {
					return false;
				}
				else return true;
			}
			else return false;
		}
	});
    
	$('a:external:not(.r-url)').unbind("click");
	$('a:external:not(.r-url)').click(function(e) {
		externalPrompt(this.href);
    	return false;
	}); // Selects all anchors which link to external site/page


	

    //////////////////////////////////////////////////////////
    // AJAX - Availability Page
	if (path == "/about-availity/where-are-we-now/availability/") {
   //////////////////////////////////////////////////////////

		// When a state is selected, pass it to the XML function
		$("#states").change(function() {

			// get xml data based on user selection
			user_state = $('option:selected', this).val();
			get_xml(user_state);
			
		 });
	}	
	
    //////////////////////////////////////////////////////////
    // TABS
	if (path == "/about-availity/what-is-availity/products-services/") {  
   //////////////////////////////////////////////////////////

		// Setting the initial height to prevent window "jumping"
		$("#tabs").height(950);
 
		// admin is clicked
	    $("#admin-trigger").click(function (event) {event.preventDefault();
	
			$("#financial-content").fadeOut('fast', function(){
				$("#clinical-content").fadeOut('fast', function(){ 
					$("#admin-content").fadeIn();
					$("#admin-trigger").addClass("active");
					$("#financial-trigger").removeClass("active");
					$("#clinical-trigger").removeClass("active");
					$("#tabs").height(950);
				});
			}); 
	    });
 
		// financial is clicked	   
	    $("#financial-trigger").click(function (event) {event.preventDefault();
	
			$("#admin-content").fadeOut('fast', function(){
				$("#clinical-content").fadeOut('fast', function(){ 
					$("#financial-content").fadeIn();
					$("#financial-trigger").addClass("active");
					$("#admin-trigger").removeClass("active");
					$("#clinical-trigger").removeClass("active");
					$("#tabs").height(400);
				});
			}); 
	    });
 
		// clinical is clicked
	    $("#clinical-trigger").click(function (event) {event.preventDefault();
	
			$("#admin-content").fadeOut('fast', function(){
				$("#financial-content").fadeOut('fast', function(){ 
					$("#clinical-content").fadeIn();
					$("#clinical-trigger").addClass("active");
					$("#financial-trigger").removeClass("active");
					$("#admin-trigger").removeClass("active");
					$("#tabs").height(400);
				});
			}); 
	    });
	}	
 
    //////////////////////////////////////////////////////////
    // Contact Form Validation
	if (path == "/about-availity/contact-us/") {
    //////////////////////////////////////////////////////////
	
		$("#contact_availity").validate({

		   messages: {
			 '00N30000000n4PN': "<p class='error'>Please choose your affiliation.</p>", 
		     first_name: "<p class='error'>Please provide a first name.</p>",
			 last_name: "<p class='error'>Please provide a last name.</p>",
			 company: "<p class='error'>Please provide an organization name.</p>",
			 title: "<p class='error'>Please provide a job title.</p>",
			 phone: "<p class='error'>Please provide a phone number.</p>",
			 '00N60000001f7fb' : "<p class='error'>Please choose a subject.</p>",
			 
		     email: {
		       required: "<p class='error'>Please enter your e-mail address.</p>",
		       email: "<p class='error'>Please enter a valid e-mail address.</p>"
		     }
		   },
		   		errorPlacement: function(error, element) {
	     		error.prependTo( element.parent("fieldset") );
	   		}
		});
	}

    //////////////////////////////////////////////////////////
    // Custom Accordion
	// This was developed due to the erratic behavior of the 
	// jQuery UI Accordion plugin in IE 6 and 7
	if (path == "/demo/") {
    //////////////////////////////////////////////////////////

		new accordion($("h3.accord-label"), $("ul.link-list"), function() {  }); 
	}

});

function getURLParam(strParamName){
	var strReturn = "";
	var strHref = window.location.href;
	var bFound=false;
	var cmpstring = strParamName + "=";
	var cmplen = cmpstring.length;
	if ( strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?")+1);
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				bFound=true;
				break;
			}   
		}
	}
	if (bFound==false) return null;
	return strReturn;
}