var $ = jQuery; //Remove No Conflict		
$(function(){	
	$('#tab1').click(showQ1);
	$('#tab2').click(showQ2);
	
	var sPath = window.location.pathname;
	if(sPath[sPath.length-1] == '/')
		sPath = sPath.substring(0,sPath.length-1);
	
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	
	if(sPage == '')
		initHome();
	else if(sPage == 'clinical-trials')
		initTrials();	
	if(typeof(site) !== 'undefined'){	
		if(site == 1) //If site is achieve	
			acheive_init();		
	}
});

function acheive_init(){
	/*
	if(!$.cookie('openhouse')){
         $.cookie('openhouse',1, {expires: 60});
		 var popup = '<div id=myPopupContainer></div><div id=popupImg><img src="/_Images/popup_openhouse.png"></div>';
		 $('body').append(popup);
		 $('#popupImg').click(function(){ $('#myPopupContainer, #popupImg').remove()  });
		 $('#myPopupContainer').show();
	}
	*/
}

function initHome(){
	
	//PopulateSelect('/_control/Trials.php?act=getIndicators&site='+site,'Search_Indication','<option value=all>- All -</option>','Name','IndicatorID', '', '');
	//PopulateSelect('/_control/Trials.php?act=getIndicators&site='+site,'indicationsLst,.indicationList','<option value=all>- All -</option>','Name','Name', '', '');
	
	if(typeof chosen_trial != 'undefined'){
		$('.indicationList').val(chosen_trial);
	}
	
	$('#q2_Search').click(gotoTrialsByIndication);
	$('#Q1_Search').click(gotoTrialsByQualifications);
	
	$('.numeric').keypress(function(e){  
		if(e.which!=8 && (e.wich<48 || e.which>57))
			return false;
	});
}

function gotoTrialsByIndication(){
	var v = $('#Search_Indication').val();
	var t = $('#Search_Indication option:selected').text();
	
	t = t.replace(/ /g,'-');
	t = t.replace(/[(]/g,'');
	t = t.replace(/[)]/g,'');
	t = t.replace(/[:]/g,'');
	t = t.replace(/[,]/g,'');
	t = t.replace(/&/g,'');
	t = t.toLowerCase();
	if(v=='all')
		t = '';
	var newLoc = '/'+'clinical-trials/'+t;
	
	document.location = newLoc;	
}
function gotoTrialsByQualifications(){
	var data = $('#form_qualifcations').serialize();
	document.location = '/clinical-trials?'+data;
	return false; //Needed for some reason
}

function initTrials(){
	PopulateSelect('/_control/Trials.php?act=getIndicators&site='+site,'Search_Indication','<option value=all>- All -</option>','Name','IndicatorID', '', '');
	PopulateSelect('/_control/Trials.php?act=getAgeRanges','age_range','<option value=all>- All -</option>','AgeRange','AgeRangeID', '', '');
	
	$('#search').click(getTrials);
	
	var indicator = $.url.param("indicator");
	
	$('#Search_Indication').val(indicator);
	
	$('#height_ft_id').val($.url.param("height_ft"));
	$('#height_in_id').val($.url.param("height_inch"));
	$('#weight_id').val($.url.param("weight"));
	
	if($.url.param("overnight")=='Yes')
		$('input[name=overnight][value=1]').attr("checked",true);
	if($.url.param("smoke")=='Yes')
		$('input[name=smoke][value=1]').attr("checked",true);
	
	$('#age_range').val($.url.param("age"));
	
	getTrials(); 
}

function getTrials(){	
	var form = '&act=getTrials&';
	form += $('#trialform').serialize();
	form += '&indicator='+$('#indication').val();
	form += '&site='+site;
	if($('#physician_id').val()!='ALL')
		form += '&physician='+$('#physician_id').val();
	$.getJSON('/_control/Trials.php', form ,function(j){
		var r = "";
		var cols = $('table.triallist thead tr th').length;
		for(i=0;i<j.length;i++)
		{
			var t = j[i];
			if(cols==4)
				r += '<tr><td><a href="/trial/'+t.TrialID+'">'+t.Name+'</a></td><td>'+t.AgeRange+'</td><td>'+((t.Overnight == 1)?'Inpatient':'Outpatient')+'</td><td>'+t.Status+'</td></tr>';			
			else
				r += '<tr><td><a href="/trial/'+t.TrialID+'">'+t.Name+'</a></td><td>'+t.AgeRange+'</td><td>'+((t.Overnight == 1)?'Inpatient':'Outpatient')+'</td><td>'+t.City+'</td><td>'+t.State+'</td><td>'+t.Status+'</td></tr>';			
		}
		if(j.length ==0)
			r = "<tr style='background-color:#F9F9F9;'><td colspan=6>No Results Found</td></tr>";
		else
			r+= '<tr style="background-color:#F9F9F9;"><td colspan=6>'+j.length+' Results Found</td></tr>';
		$('#trial_results').html(r).tablesorter();		
		
		$('table.triallist tr:nth-child(odd)').addClass('odd');
		
	});
}

function showQ2(){ $('#quote-in').hide(); $('#quote-in2').show(); }
function showQ1(){ $('#quote-in').show(); $('#quote-in2').hide(); }
function PopulateSelect(q,id,options,name,value,callback,selected){
	jQuery.ajax({
		async: false,
		url:q,
		dataType: 'json',
		cache: false,
		success: function(j,s){
			if(!options)
					options="";
				if(!name)
					name="name";
				if(!value)
					value="id";

				for (var i = 0; i < j.length; i++)
				{
					options += '<option value="'+j[i][value]+'"';
					if(j[i][value] == selected )
						options+= ' SELECTED';
					options += '>'+j[i][name]+'</option>';
				}
				jQuery('#'+id).html(options);
				
				if(callback)	
					callback();
		}
		
	});
}

function SQL_TO_JS_Date(sqlDate){ return sqlDate.replace(/^(....).(..).(.{11}).*$/, "$1/$2/$3") }

function popup(url,w,h){
	var top = screen.height/2 - h/2;
	var left = screen.width/2 - w/2;
	var popup = window.open(url,"accel_popup",'menubar=0,scrollbars=yes,width='+w+',height='+h+',top='+top+',left='+left);
	if(popup)
		popup.focus();
}


//Dec 20,2010 Moving this here so it can work for all sites
function validateForm(){
			var valid=true;
			$('#gs_mail,#gs_name,#gs_phone').css('background-color','white');
			if(!isEmail($('#gs_mail').val())){
				$('#gs_mail').css('background-color','#FFCCD6');
				valid=false;
			}
			var name = $('#gs_name').val();
			
			if(name=='' || name.length < 2){
				$('#gs_name').css('background-color','#FFCCD6');
				valid=false;
			}
			
			var phone = $('#gs_phone').val();
			var regex1 = new RegExp('-','g');
			var regex2 = new RegExp(' ','g');
			phone = phone.replace(regex1, '');
			phone = phone.replace(regex2, '');
			//$('#gs_phone').val(phone);
			if(phone.length != 10 || phone.charAt(0) == 0){
				$('#gs_phone').css('background-color','#FFCCD6');
				valid = false;
				alert('Phone number must be entered using the following format: XXXXXXXXXX or XXX-XXX-XXXX \r\nEntered'+phone);
			}	
			else if(!valid) //Only show one message for invalid phone #
				alert('Please correct the highlighted fields before submitting.');
			
			return valid;
		}
/*--------------------From new Form---------------*/

$(document).ready(function () {
        $("div.tabBox div.tabs div.tab:eq(0)").click(function () {
            $("div.tabContent div.tabContentTwo").hide();
            $("div.tabContent div.tabContentOne").show();
            $("div.tabBox div.tabs div.tab:eq(1)").removeClass("tabActive");
            $(this).addClass("tabActive");
        });
        $("div.tabBox div.tabs div.tab:eq(1)").click(function () {
            $("div.tabContent div.tabContentOne").hide();
            $("div.tabContent div.tabContentTwo").show();
            $("div.tabBox div.tabs div.tab:eq(0)").removeClass("tabActive");
            $(this).addClass("tabActive");
        });

        $(".button").hover(function () {
            var strSrc = $(this).attr("src");
            var extIndex = strSrc.lastIndexOf(".");
            var firstPart = strSrc.substr(0, extIndex);
            var secondPart = strSrc.substr(extIndex, (strSrc.length - 1));
            $(this).attr("src", firstPart + "_hover" + secondPart);
        }, function () {
            var strSrc = $(this).attr("src");
            var extIndex = strSrc.lastIndexOf(".");
            var firstPart = strSrc.substr(0, (extIndex - 6));
            var secondPart = strSrc.substr(extIndex, (strSrc.length - 1));
            $(this).attr("src", firstPart + secondPart);
        });


        $(".btnCallMeNow").mouseover(function () {
            $(this).css("background-position", "0 -58px");
        }).mouseout(function(){
            $(this).css("background-position", "0 0");
        });

        $(".btnSubmitMyInfo").mouseover(function () {
            $(this).css("background-position", "0 -51px");
        }).mouseout(function () {
            $(this).css("background-position", "0 0");
        });
});		
/*----------------------------------------------------------------------------*/		
		
/*Added - 9/22/2010 - Robert*/
function SQLDate2JS(sqlDate){ return new Date(sqlDate.replace(/^(....).(..).(.{11}).*$/, "$1/$2/$3")); }
function SQLDateFormat(sqldate, format){
	var d;
	if(!sqldate || sqldate.length < 1)
		return '-';
	try{
		var date = SQLDate2JS(sqldate);
		if(format)
			d = date.format(format);
		else
			d = date.format('m/d/yyyy');
		return d;
	}catch(err){
		if(console){
			console.log(err); 
			console.log(sqldate); 
		}
		return '?';
	}
}   
function SQLDateTimeFormat(sqldate){ return SQLDateFormat(sqldate, 'm/d/yyyy h:MMtt'); }
function isEmail(e){
	var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
	return regex.test(e);	
}

function doCall(reqType){
			if(!validateForm())
				return false;
			$('#reqType').val(reqType);
			
			$.ajax({
				url: '/_Control/LandingSubmit.PHP',
				data: $('#moreInfo').serialize(),
				method: 'GET',
				success: function(){
					if($('#form_lang').val() == 'spanish')
						document.location = '/gracias';
					else if($('#reqType').val() == 'Now')
						document.location = '/thanks-click2call';
					else
						document.location = '/thanks';
					
				}
			});
			return false; //Prevent double submit
		}











