/* Radiia Site
*  LimeGreen
*  03.08.11
*/

/** Vars *************************************************************************/
//main image fader
var imgFadeStart = 0;
var imgFadeShowID = '';
var imgFadeHideID;
var imgFadeCounter = 1;
var imgFadeTotal = 0;
var imgFadeInSpeed = 1000;
var imgFadeOutSpeed = 100;
var imgFadeIntervalTime = 12000;  // CHANGE THIS FOR INTERVAL TIMER
var imgFadeIntervalVar;

//img slider
var homecounter = 1;
var hometotal = 0;
var homeChildWidth = 0;
var homeIntervalID;
var homeIntervalTime = 1700;
var homespeed = 650; //800;
var gsvalue;

var dialogid = '';
var disOpen = new Boolean();
var fadeSpeed;
var offset;
var scrolltop;
var overlayOpacity = 0.10; // if color needed = 0.10

var tracer = 0;
var pathname;

/** On Ready *************************************************************************/
$(document).ready(function(){
	//cart across entire site
	pathname = window.location.pathname;
	//changeSideBar();
	
	//forms events
	//$('input[tabindex=1]').focus();
	$('form').submit(function() {
			return false;
		});
	$('form#paypalform').submit(function() {
			return true;
		});
	$('form#gsform1 select#type').change(function() {
  		gsvalue = $(this).val();
		if(gsvalue.length > 0){
			var loc = 'registration.php?gs=' + gsvalue;
			window.location = loc;
		}
	});
	$("form#caseform2 input[name='studytype']").click(function() {
		switchPrice();
	});	   
	$("form#caseform2 input[name='secondopinion']").click(function() {
		$('#secondopinionchk').attr('checked','checked');
	});
	$('#releaseform').live('click', function() {
		alert('need release form');
	});

	//form validates
	if($('form#cform1').length > 0){ cformValidate(); }
	if($('form#Lform1').length > 0){ LformValidate(); }
	if($('form#patientform2').length > 0){ patientform2Validate(); } //patient profile
	if($('form#patientform3').length > 0){ patientform3Validate(); } //physician add patient
	if($('form#gsregform2').length > 0){ gsregformValidate(); }
	if($('form#gsregform3').length > 0){ gsreg3formValidate(); }
	if($('form#caseform2').length > 0){ caseformValidate('form#caseform2'); }
	if($('form#caseform3').length > 0){ caseformValidate('form#caseform3'); }
	if($('form#logform2').length > 0){ logformValidate(); }
	if($('form#Fform1').length > 0){ FformValidate(); }
	if($('form#couponform2').length > 0){ couponform2Validate(); }
	
	//cart events
	$('#coupon-submit a.coupon-btn').live("click",function () { 
		couponController();
	});
	
	$('.update-btn').live("click",function () { 
		var getid = $(this).attr('id');
		window.location = 'add-case.php?id=' + getid;
	});
	
	$('div.examdoorbuttonSmall a.delete').live("click",function () { 
	  	var getid = $(this).attr('id');
	  	editCart('delete', getid, '');
	 });
	$('a.add-cart').live("click",function () { 
	  	var getid = $(this).attr('id');
	  	editCart('add', getid, 1);
		$(this).parent().html('Added to Cart');
	 });
	$('.view-cart').live("click",function () { 
	  	window.location = 'view-cart.php';
	 });
	$('.view-cart-check').live("click",function () { 
	  	window.location = 'view-cart.php';
	 });
	$('.checkout-btn').live("click",function () { 
	  	//alert('p');
		$('form#paypalform').submit();
	 });

	//home images
	if($('.img-swap-wrap').length > 0){
		//homeSlideShowStart();
		imgFaderController();
	}
	
	//pops
	$('#mail').live("click",function () { 
		mailPopUpController();
	 });

	//sdmin click
	$('.client-display').live("click",function () { 
	  	var stat = $(this).attr('id');
		if(stat == 'closed'){
			$(this).attr('id','opened');
			$(this).addClass('clientDisplayOpened');
			$(this).removeClass('clientDisplayClosed');
			$(this).parent().addClass('client-wrap-open');
		}
		if(stat == 'opened'){
			$(this).attr('id','closed');
			
			$(this).removeClass('clientDisplayOpened');
			$(this).addClass('clientDisplayClosed');
			$(this).parent().removeClass('client-wrap-open');
		}
	 });
	
	//bios click
	$('.bios-display').live("click",function () { 
	  	var stat = $(this).attr('id');
		if(stat == 'closed'){
			$(this).attr('id','opened');
			$(this).addClass('biosDisplayOpened');
			$(this).removeClass('biosDisplayClosed');
			$(this).parent().addClass('bios-wrap-open');
		}
		if(stat == 'opened'){
			$(this).attr('id','closed');
			
			$(this).removeClass('biosDisplayOpened');
			$(this).addClass('biosDisplayClosed');
			$(this).parent().removeClass('bios-wrap-open');
		}
	 });
	
	$('a.upload-again').live("click",function () { 
	  	var getid = $(this).attr('id');
	  	window.location = 'lib/inc/upload-again.php?id=' + getid;
	 });
	
}); //eo on ready

function changeSecondOpinion(degree){
	 if(degree == 'higher'){
		$('form#caseform2 label#secondopinion span').text('Second Opinion $275.00');
		$('form#caseform2 label#secondopinion input').val('275.00');
	 }
	 if(degree == 'lower'){
		$('form#caseform2 label#secondopinion span').html('Second Opinion $150.00');
		$('form#caseform2 label#secondopinion input').val('150.00');
	 }
 }
 
 /** MAIN IMAGE FADER *************************************************************************/
function imgFaderController(){
	//init
	if(imgFadeStart == 0){
		imgFadeTotal = $('.img-swap-long').children('.img-swap').length;
		$('.img-swap-long div:first-child').css('display', 'block');
		imgFadeStart = 1;
		imgFadeShowID = '#imgswap1';
	}
	
	imgIntervalVar = setInterval(imgFader, imgFadeIntervalTime);
}

function imgFader(){
	clearInterval(imgIntervalVar);
	
	//norm loop
	if(imgFadeCounter == imgFadeTotal){
		imgFadeCounter = 1;	
	}
	else{
		imgFadeCounter++;	
	}
	//alert(imgFadeCounter);
	imgFadeHideID = imgFadeShowID;
	imgFadeShowID = '#imgswap' + imgFadeCounter;
	
	$(imgFadeHideID).fadeOut(imgFadeOutSpeed);
	$(imgFadeShowID).fadeIn(imgFadeInSpeed);
	//alert(imgFadeHideID +' '+ imgFadeShowID);
	//$('.fade-buttons').removeClass('fade-buttons-on');
	//$('#fadebutton' +imgFadeCounter).addClass('fade-buttons-on');
	
	imgIntervalVar = setInterval(imgFader, imgFadeIntervalTime);
}

/** Animation *************************************************************************/
function homeSlideShowStart(){
	homeChildWidth = $('div.img-swap').width();
	origtotal = $('.img-swap-long').children('div.img-swap').length; //how many
	hometotal = origtotal;
	
	/*
	var hloop = homenumberloops - 1;
	while(hloop > 0){
		$('.img-swap-long').append(homeloop);
		hloop--;
	}
	
	homelongwidth = hometotal * 855 ;
	$('.img-swap-long').css({width: homelongwidth +'px'});
	*/
	homeIntervalID = setInterval(homeSlideShowControl,homeIntervalTime);
	//alert(hometotal);
}

function homeSlideShowControl(){
	clearInterval(homeIntervalID);
	
	//per counter => what next
	var gg = hometotal-1;
	if(homecounter == gg){ 
		homecounter = 0; 
		/*$('.img-swap-long').animate({left: '+=' +(855 * (hometotal-1))}, homespeed, 'easeInElastic', function() {
			// Animation complete
		  });*/
		$('.img-swap-long').animate({left: '-=' +homeChildWidth +'px'}, homespeed, function() {
			// Animation complete
			$('.img-swap-long').css('left','0px');
		  });
	}
	else{
		$('.img-swap-long').animate({left: '-=' +homeChildWidth +'px'}, homespeed, function() {
			// Animation complete
		  });
	}
	homecounter++;
	
	homeIntervalID = setInterval(homeSlideShowControl,homeIntervalTime);
}

/** Cart Functions **************************************************/
function showCart(op){
	var textStatus;
	$.ajax({
		url: "lib/inc/cart-session.php"
		,cache: false
	   ,type: "POST"
		,data: ({
			action: op
		})
	   ,dataType: "html"
	   ,error: function(XMLHttpRequest, textStatus, errorThrown){
			// alert(textStatus);
			 alert('The connection was lost. Please try again.');
		  }
		,success: function(textStatus){
			$('#full-cart-view').html(textStatus);
			//changeSideBar();
		}
	 }); //eo ajax
}//eo showCart

function editCart(op, id, num){
	$.ajax({
		url: "lib/inc/cart-session.php"
		,cache: false
	   ,type: "POST"
		,data: ({
			id: id,
			quantity: num,
			action: op
		})
	   ,dataType: "html"
	   ,error: function(XMLHttpRequest, textStatus, errorThrown){
			// alert(textStatus);
			 alert('The connection was lost. Please try again.');
		  }
		,success: function(textStatus){
			if(op == 'update'){
				$('#donate-cart-view').html(textStatus);
			}
			showCart('view');
			changeSideBar();
		}
	 }); //eo ajax
}//eo addToCart

function totalAllUp(){
	$.ajax({
		url: "lib/inc/cart-session.php"
		,cache: false
	   ,type: "POST"
		,data: ({
			action: 'get-total'
		})
	   ,dataType: "html"
	   ,error: function(XMLHttpRequest, textStatus, errorThrown){
			// alert(textStatus);
			 alert('The connection was lost. Please try again.');
		  }
		,success: function(textStatus){
				var tty = 'Total Donation: ' + textStatus;
				$('#product-purchase').html(tty);
		}
	 }); //eo ajax
}//eo addToCart


function changeSideBar(){	
	pathname = window.location.pathname;
	
	var ss = pathname.search('client/');
	var aa = pathname.search('admin/');
	var url;
	
	if(ss < 0){ url = 'client/lib/inc/cart-session.php'; } //=> public
	else{ url = 'lib/inc/cart-session.php'; }

	if(aa < 0){ 
		$.ajax({
			url: url
			,cache: false
		   ,type: "POST"
			,data: ({
				action: 'icon',
				path: pathname
			})
		   ,dataType: "html"
		   ,error: function(XMLHttpRequest, textStatus, errorThrown){
				// alert(textStatus);
				 alert('The connection was lost. Please try again.');
			  }
			,success: function(data){
				//alert(data);
				//$('div#cart').remove();
				$('div#ycartbtn').html(data);
			}
		 }); //eo ajax
	}
}

function couponController(){
	var ccode = $('#coupon-data input#coupon').val();
	$.ajax({
		url: 'lib/inc/add-coupon345.php'
		,cache: false
	   ,type: "POST"
		,data: ({
				code: ccode
			})
	   ,dataType: "text"
	   ,error: function(XMLHttpRequest, textStatus, errorThrown){
			 alert('The connection was lost. Please try again.');
		  }
	   ,success: function(text, textStatus){
			if(textStatus == 'success'){
				if(text != '0'){
					$('.coupon-error').remove();
					$('#coupon-wrap').html('<h2>The Discount Code Was Accepted.  You Will Receive '+text+'% Off All Services.</h2>');
					var tot = parseInt($('#quick-hide').text());
					var per = parseInt(text)/100;
					var subtot = parseFloat(tot).toFixed(2);
					
					var dif = tot * per;
					var pdif = parseFloat(tot * per).toFixed(2);
					var newtot = parseFloat(tot - dif).toFixed(2);
					
					//out
					$('#subtotal-label').html('<span>Subtotal:</span> &nbsp;&nbsp; $' +subtot);
					$('#couptotal-label').html('<span>Discount:</span> &nbsp;&nbsp; -$' +pdif);
					$('#total-label').html('<span>Total:</span> &nbsp;&nbsp; $' +newtot);
					
					//adjust paypal
					var ppcnt = $('input.cart-item-ct').length;
					$('.cart-discount-rate').val(text);
					
					//add code to show in PP
					$('.item_number').each(function(index) {
						var tname = $(this).attr('name');
						var rrt = tname.split('item_number_')
						var int = rrt[1];
						
						var iic = '<input type="hidden" name="on4_' +int+ '" value="Coupon" /><input type="hidden" name="os4_' +int+ '" value="' +ccode+ '" />';
						$('.coupon_after_' +int).after(iic);
						
					  });
				}
				if(text == '0'){
					if($('.coupon-error').length == 0){
						$('#coupon-wrap').before('<label class="coupon-error">The discount code was not accepted.  Please enter the correct code.</label>');
					}
				}
			}//eo success
		}
	 }); //eo ajax
	
}
/** Forms *************************************************************************/
function submitForm(id){
	var furl;
	var serializedData;
	if(id == 'form#cform1'){
		serializedData = wrapFormValues('form#cform1');
		furl = 'lib/inc/e3mail.php';
	}
	if(id == 'form#gsregform2'){
		serializedData = wrapFormValues('form#gsregform2');
		furl = 'lib/inc/reg345.php';
	}
	if(id == 'form#gsregform3'){
		serializedData = wrapFormValues('form#gsregform3');
		furl = 'lib/inc/reg345.php';
	}
	$.ajax({
		url: furl
		,cache: false
	   ,type: "POST"
		,data: ({
			submitdata: serializedData
		})
	   ,dataType: "text"
	   ,error: function(XMLHttpRequest, textStatus, errorThrown){
			 alert('The connection was lost. Please try again.');
		  }
	   ,success: function(text, textStatus){
			if(textStatus == 'success'){
				if(id == 'form#cform1'){
					//$('input.button').css('display', 'none');
					//$('div#ethanks').html('<span>Thank you.</span> Your email has been sent.');
					window.location = 'thankyou-contact.php';
				}
				if(id == 'form#gsregform2' || id == 'form#gsregform3'){
					//var loc = 'upload-login.php?sc=4';
					window.location = 'thankyou-registering.php';
				}
			}//eo success
		}
	 }); //eo ajax
}

function wrapFormValues(form){ 
    form = $(form).serializeArray();
    var dataArray = new Object();
    for(index in form){   
    	dataArray[form[index].name] = form[index].value;        
    }           
    return dataArray; 
}

function switchPrice(){
	stvalue = $("form#caseform2 input[name='studytype']:checked").val();
	switch(stvalue){
		case 'MRI':
		  changeSecondOpinion('higher');
		  break;
		case 'CT':
		  changeSecondOpinion('higher');
		  break;
		case 'Mammogram':
		  changeSecondOpinion('higher');
		  break;
		case 'NM':
		  changeSecondOpinion('higher');
		  break;
		case 'Ultrasound':
		  changeSecondOpinion('lower');
		  break;
		case 'X-Ray':
		  changeSecondOpinion('lower');
		  break;
		default:
		  //nothing
	}
}//eo switchPrice()


/** FORM VALIDATION *************************************************************************/
function cformValidate(){
$('form#cform1').validate({  //lazy init -> call here
		submitHandler: function(form) {
			submitForm('form#cform1');
		}
	});
}

function LformValidate(){
	$('form#Lform1').validate({  //lazy init -> call here
		submitHandler: function(form) {
			form.submit();
		}
	});
}

function patientform2Validate(){ //patient profile
	$('form#patientform2').validate({  
		debug: true,
		rules: {
			dob: "required",
			phone: {
				required: true
			},
			medicalhistory: "required",
			agree: "required",
			physician_phone: {
				required: function(element) {
					return $(this).length > 1;
				}
			},
			physician_fax: {
				required: function(element) {
					return $(this).length > 1;
				}
			}
		},
		messages: {
			dob: "Please enter date of birth",
			phone: "Please enter a phone number",
			medicalhistory: "Please enter medical history",
			agree: "Please confirm that you agree with the terms",
			physician_phone: "Please enter a phone number",
			physician_fax: "Please enter a fax number"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});	
}
function patientform3Validate(){ //physician add patient
	$('form#patientform3').validate({  
		debug: true,
		rules: {
			name: "required",
			dob: "required",
			phone: {
				required: true
			},
			medicalhistory: "required"
		},
		messages: {
			name: "Please enter patient name",
			dob: "Please enter date of birth",
			phone: "Please enter a phone number",
			medicalhistory: "Please enter medical history"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});	
}

function gsregformValidate(){
	$('form#gsregform2').validate({  
		debug: true,
		rules: {
			name: {
				required: true,
				minlength: 5
			},
			address: {
				required: true,
				minlength: 5
			},
			city: {
				required: true,
				minlength: 5
			},
			state: "required",
			zip: {
				required: true,
				postalcode: true
			},
			international_address: {
				required: true,
				minlength: 10
			},
			country: {
				required: true,
				minlength: 2
			},
			email: {
				required: true,
				email: true
			},
			phone: {
				required: true
			},
			fax: {
				required: function(element) {
					return $(this).length > 1;
				}
			},
			reports: {
				required: true,
				minlength: 5
			},
			hippa: "required",
			legal: "required"
		},
		messages: {
			name: "Please enter your name",
			address: "Please enter your address",
			city: "Please enter your city",
			state: "Please enter your state",
			zip: "Please enter your zip code",
			international_address: {
				required: "Please enter your address",
				minlength: "Please enter your address"
			},
			country: {
				required: "Please enter your country",
				minlength: "Please enter your country"
			},
			phone: "Please enter a phone number",
			fax: "Please enter a fax number",
			reports: {
				required: "Please enter where reports should be submitted",
				minlength: "Please enter where reports should be submitted"
			},
			hippa: "Please confirm that you agree with the HIPPA Notice of Privacy Practices",
			legal: "Please confirm that you agree with the Legal Terms of Use",
			email: "Please enter a valid email address"
		},
		submitHandler: function(form) {
			submitForm('form#gsregform2');
		}
	});	
} //eo  gsregformValidate()

function gsreg3formValidate(){
	$('form#gsregform3').validate({  
		debug: true,
		rules: {
			name: {
				required: true,
				minlength: 5
			},
			address: {
				required: true,
				minlength: 5
			},
			city: {
				required: true,
				minlength: 5
			},
			state: "required",
			zip: {
				required: true,
				postalcode: true
			},
			international_address: {
				required: true,
				minlength: 10
			},
			country: {
				required: true,
				minlength: 2
			},
			email: {
				required: true,
				email: true
			},
			phone: {
				required: true
			},
			fax: {
				required: function(element) {
					return $(this).length > 1;
				}
			},
			reports: {
				required: true,
				minlength: 5
			},
			legal: "required"
		},
		messages: {
			name: "Please enter your name",
			address: "Please enter your address",
			city: "Please enter your city",
			state: "Please enter your state",
			zip: "Please enter your zip code",
			international_address: {
				required: "Please enter your address",
				minlength: "Please enter your address"
			},
			country: {
				required: "Please enter your country",
				minlength: "Please enter your country"
			},
			phone: "Please enter a phone number",
			fax: "Please enter a fax number",
			reports: {
				required: "Please enter where reports should be submitted",
				minlength: "Please enter where reports should be submitted"
			},
			legal: "Please confirm that you agree with the Legal Terms of Use",
			email: "Please enter a valid email address"
		},
		submitHandler: function(form) {
			submitForm('form#gsregform3');
		}
	});	
} //eo  gsreg3formValidate()

function caseformValidate(id){
	$(id).validate({  
		debug: true,
		rules: {
			name: "required",
			initial: "required",
			reason: "required",
			bodypart: "required",
			bodypartnum: "required",
			studytype: "required",
			deliverytype: "required"
		},
		messages: {
			name: "Please enter a case title",
			initial: "Please enter reason for initial exam",
			reason: "Please enter reason for second opinion",
			bodypart: "Please enter body part",
			bodypartnum: "Please enter body part number"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
} //eo caseformValidate()

function logformValidate(){
	$('form#logform2').validate({  //lazy init -> call here => reg form
		debug: true,
		rules: {
			password: {
				required: true,
				minlength: 5,
				maxlength: 20
			},
			confirm_password: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			}
		},
		messages: {
			password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long",
				maxlength: "Your password must be no more than 20 characters long"
			},
			confirm_password: {
				required: "Please confirm the password",
				minlength: "Your password must be at least 5 characters long",
				maxlength: "Your password must be no more than 20 characters long",
				equalTo: "Please confirm your password"
			}
		},
		submitHandler: function(form) {
			form.submit();
		}
	});	
} //eo logformValidate()


function FformValidate(){
	$('form#Fform1').validate({ 
		debug: true,
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			email: "Please enter a valid email address"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});	
} //eo FformValidate()

function couponform2Validate(){
	$('form#couponform2').validate({ 
		debug: true,
		rules: {
			ccode: {
				required: true,
				nowhitespace: true
			},
			rate: {
				required: true,
				digits: true
			}
		},
		messages: {
			ccode: {
				required: "Please enter a discount code",
				nowhitespace: "Please remove all spaces"
			},
			rate: {
				required: "Please enter a discount rate",
				digits: "Please enter number only"
			}
		},
		submitHandler: function(form) {
			form.submit();
		}
	});	
}


/** DIALOG *************************************************************************/
function showOverlayBox() {
	if( disOpen == false ) return;  //if  not set to open -> do nothing
	$("#" +dialogid).css({display:"block",position:"absolute"});	
	$("#" +dialogid).css("top", ( $(window).height() - $("#" +dialogid).height() ) / 2+$(window).scrollTop()-10 + "px");
    $("#" +dialogid).css("left", ( $(window).width() - $("#" +dialogid).width() ) / 2+$(window).scrollLeft() + "px");
	
	var wrapHeight = $('#wrap').height();
	
	//window background dimension and position for overlay		
	$(".overlay").css({width: $(window).width(),height:wrapHeight}); //doesnt calculate correctly for FF think because of iframe
}

function doOverlayOpen() {
	disOpen = true; //status open
	showOverlayBox(); //show overlay

	// Fade in background
	$(".overlay").fadeIn(fadeSpeed);	

	return false; //don't follow the link : so return false
}

function doOverlayClose(){
	disOpen = false;
	$(".overlay").css({opacity:overlayOpacity});
}

function dialogClose(){
	 $("#" +dialogid).hide(1, function () {
		//isOpen = false;
		$('.overlay').fadeTo(200,0, function () {
			$(".overlay").hide();
			doOverlayClose();
		});
  	});
	
}
function openDialog(){
	$(".overlay").css({opacity:overlayOpacity}); //define opacity
	$(window).bind('resize',showOverlayBox); //window resize control
	doOverlayOpen();
}

function cartPopUpController(){
	dialogid = 'cartadd-popup';
	openDialog();
	$('.dialog-close').click(function() {
		dialogClose();
	});
}

function mailPopUpController(){
	dialogid = 'mail-popup';
	openDialog();
	$('.dialog-close').click(function() {
		dialogClose();
	});
}


