function progressMeter () {
  var title    = $('#title').val();
  var forename = $('#first-name').val();
  var surname  = $('#surname').val();

  var progress = 10; // We always have email

  // name fields
  if(  title    != ""
    && forename != ""
    && surname  != "" ) {
    progress    += 20;
  }

  // other demographic fields.
  var demo = new Array( $('#address').val(), $('#town').val(), $('#postcode').val(), $('#tel_eve').val(), $('#sms').val() );
  for ( var i = 0; i < demo.length; i++ ) {
    if( demo[i] != "" ) {
      progress +=10;
    }
  }

  // Check if photo is placeholder.
  var photo = $('#profile-photo').attr('src');
  if(photo!=null) {
    var haveDefault = photo.match(/photo-placeholder/);
    if( haveDefault == null ) {
      progress += 20;
    }
  }

  $('#progress-meter').html(progress);
};

function call_me_now () {
      $.ajax({
        type : "POST",
        url  : "/vites/rf/my2_callme",
        data : { title    : $('#call-title').val(),
                 forename : $('#call-forename').val(),
                 surname  : $('#call-surname').val(),
                 tel_eve  : $('#call-telephone').val()
        },
        dataType: "text",
        complete : function(data) {
          // Initialise div states.
          $('#failtitle').removeClass('fail');
          $('#failforename').removeClass('fail');
          $('#failsurname').removeClass('fail');
          $('#failtel_eve').removeClass('fail');
          $('#c2cfailresponse').removeClass('title fail');
          $('#c2cfailresponse').hide();
          $('#validfailresponse').hide();
          $('#callback-form').show();
          $('#callback-thanks').hide();
          var pattern = RegExp("(yes|no(:.+))");
          var c2c = data.responseText;
          var result = c2c.match(pattern);
          if( result != null ) {
            var status = result[0];
            var reason = result[1];
            if (status != "yes") { //c2c failed
              if(reason == "no:c2c") {
                $('#c2cfailresponse').show();
                $('#c2cfailresponse').addClass('title fail');
              }
              else {
                var invalid = reason.split(/[,:]/);
                for ( field in invalid ) {
                  switch(invalid[field]) {
                    case 'title' :
                      $('#failtitle').addClass('fail');
                      break;
                    case 'forename' :
                      $('#failforename').addClass('fail');
                      break;
                    case 'surname' :
                      $('#failsurname').addClass('fail');
                      break;
                    case 'tel_eve' :
                      $('#failtel_eve').addClass('fail');
                      break;
                    default :  
                      break;
                  } 
                }
                $('#validfailresponse').show();
              }
            }
            else {
              $('#callback-form').hide();
              $('#callback-thanks').show();
            }
          }
          else {
            $('#c2cfailresponse').show();
            $('#c2cfailresponse').addClass('title fail');
          }
        }
      });

  return false;
};

function faq_answer (index) {
  $(this).hide();
};

function faq_question () {
		// Hide all 
		//
		$('.answer').each(function(index) {
	   		$(this).slideUp();
  		});
   		
   		// Get the answer div ID
   		//
 		var thisQuID = $(this).attr("id");
     		
   		var thisAnID = thisQuID.replace(/-q/i, "-a");
   		
   		// If it's visible hide it, otherwise vice versa
   		//
   		if ($("#"+thisAnID).is(":visible")){
   			$("#"+thisAnID).slideUp();
   		}
   		else {
   			$("#"+thisAnID).slideDown();   			
   		}
   		
   		return false;
};

function doMGM ()
{
	  $(this).addClass('loading');
      $.ajax({
        type : "POST",
        url  : "/vites/rf/my2_mgm_tell",
        data : { friend_forename : $('#fforename').val(),
                 friend_surname  : $('#fsurname').val(),
                 friend_address  : $('#faddress').val(),
                 friend_email    : $('#femail').val(),
                 friend_comment  : $('#fcomment').val() },
        dataType : "text",
        complete : function(data){
          $('div#my-mgm').replaceWith(data.responseText);
          $("p.hide-show span").click(function () {
            __ShowHide($(this));
          });

          __ShowHide($("div#my-mgm p.hide-show span.show"));
          $('#goMGM').click(doMGM);
        }
      });
      return false;
};

function doClinic () {
	  $(this).addClass('loading');
      $.ajax({
        type : "POST",
        url  : "/vites/rf/my2_pa_tell",
        data : { pa_message : $('#clinicPaMessage').val(),
                 surname  : $('#clinicSurname').val(),
                 title  : $('#clinicTitle').val() },
        dataType : "text",
        complete : function(data){
          $('div#my-clinic').replaceWith(data.responseText);
          $("p.hide-show span").click(function () {
            __ShowHide($(this));
          });

          __ShowHide($("div#my-clinic p.hide-show span.show"));
          $('#goClinic').click(doClinic);
        }
      });
      return false;
};

function doFaq () {
	  $(this).addClass('loading');
      $.ajax({
        type : "POST",
        url  : "/vites/rf/my2_faq_tell",
        data : { faq_question : $('#faq_question').val(),
                 surname  : $('#faqSurname').val(),
                 title  : $('#faqTitle').val() },
        dataType : "text",
        complete : function(data){
          $('div#my-faq').replaceWith(data.responseText);
          $("p.hide-show span").click(function () {
            __ShowHide($(this));
          });

          __ShowHide($("div#my-faq p.hide-show span.show"));
          $('#faq-question-submit').click(doFaq);
          $('.faq-question').click(faq_question);
	      $('.answer').each(faq_answer);
        }
      });
      return false;
};

function doPersonal () {
	  $(this).addClass('loading');
      $.ajax({
        type : "POST",
        url  : "/vites/rf/my2_personal_details_tell",
        data : { title : $('#title').val(),
                 forename : $('#first-name').val(),
                 surname  : $('#surname').val(),
                 date_of_birth : $('#dob').val(),
                 address1 : $('#address').val(),
                 town : $('#town').val(),
                 postcode : $('#postcode').val(),
                 tel_eve  : $('#tel_eve').val(),
                 tel_mob  : $('#sms').val() },
        dataType : "text",
        complete : function(data){
          $('div#my-details').replaceWith(data.responseText);
          $("p.hide-show span").click(function () {
            __ShowHide($(this));
          });

          __ShowHide($("div#my-details p.hide-show span.show"));
          $('#update-details').click(doPersonal);
          // Set other demographic forms based on this one.
          $('#faqTitle').val( $('#title').val() );
          $('#faqSurname').val( $('#surname').val() );
          $('#clinicTitle').val( $('#title').val() );
          $('#clinicSurname').val( $('#surname').val() );
          // update progress
          progressMeter();
        }
      });
      return false;
};

$(document).ready(function () {
    // call-me-back sections
    $('#c2cfailresponse').hide();
    $('#validfailresponse').hide();
    $('#callback-thanks').hide();
    $('.cta-button').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });
    $('.cta-content').hide();
    $('#' + defaultCTAId + ' .cta-button').addClass('open');
    $('#' + defaultCTAId + ' .cta-content').slideDown();
    $('.cta-button').click(function () {
        $('.cta-button').removeClass('open');
        $('.cta-content').slideUp();
        $(this).addClass('open');
        $(this).siblings('.cta-content').eq(0).slideDown();
    });
    obs.init($);
    //widget.init($);
    //microWidget.init($);
	$('#uk-link').click(function(){
      // jps-v1.13 changed from window.open to location.href so opens in same window   
	  location.href("http://www.ultralase.com/vites/home/");
	  return false;
	}); 
	$('#irl-link').click(function(){
      // jps-v1.13 changed from window.open to location.href so opens in same window
      location.href("http://www.ultralase.ie/vites/home/");
      return false;
	});
	
	// Log in panel (ACH - 21.01.2011)
	//	
	// on load, hide both logged in and logged out elements
	//
	$("#logged-in").hide();
	$("#logged-out").hide();
	
	// Need different behaviour depending on if logged in...
	//
	var loginCheckVar = $("#logInCheck").val();
	
	// If logged in hover over the area to open the logout buttons
	// click on the logo to go to the myul page
	//
	if (loginCheckVar) {
		$('#my-ultralase-login').bind('mouseenter mouseleave', function() {
			$("#logged-in").slideToggle();	
			return false;
		});
 		$('a.login-section').click(function(){
			window.location.href = "/home.myul";
			return false;
		});


	} else {
	// if NOT logged in, click to open, click to close
	//
		$('a.login-section').click(function(){
			if ($("#logged-out").is(":visible")){
				$("#logged-out").slideUp();	
			} else {
				$("#logged-out").slideDown();	
			}
			return false;
		});
	
	}
	
	
	
	// Tabbed content (forum posts) events
	//
	// on load, hide all the navigation tabs, show the first one
	//
	$('.posts-content').each(function(index) {
   		$(this).hide();
  	});
  	
  	$("#tab-latest-posts").show();
  	
  	// set the class for the tab link
  	//
  	$("#link-latest-posts").addClass("selected");


	// Create the click event for the tab links
	//
	$('.post-tab').click(function() {
   		
   		var thisID = $(this).attr("id");
   		
   		var thisTabID;
   		thisTabID = thisID.replace(/link/i, "tab");
   		
		$('.posts-content').each(function(index) {
   			$(this).hide();
  		});

  		$("#"+thisTabID).show();
   		
   		$(".post-tab").removeClass("selected");
   		$("#"+thisID).addClass("selected");
   		
   		return false;
  	});		
	
  	// Click events for FAQ list
  	//
  	// First, hide all questions on load
  	//
	$('.answer').each(faq_answer);//function(index) {
   		//$(this).hide();
  	//});
  		
	// Now add the event when a question is clicked
	//
    $('.faq-question').click(faq_question);

	// MyUL Popups
	//
	
	// My Appointments
	//
	if ($( "#popMyAppointments" ).length){
		$( "#popMyAppointments" ).dialog({
			autoOpen: false,
			modal: true
		});
	}
	// Change Picture
	//
	if ($( "#popChangeMyPicture" ).length){
		$( "#popChangeMyPicture" ).dialog({
			autoOpen: false,
			modal: true
		});
	}
	// Change Password
	//
	if ($( "#popChangeMyPassword" ).length){
		$( "#popChangeMyPassword" ).dialog({
			autoOpen: false,
			modal: true
		});
	}
	// Clinic Selector
	//
	if ($( "#popClinicSelector" ).length){
		$( "#popClinicSelector" ).dialog({
			autoOpen: false,
			modal: true,
			width: '700px'
		});
	}

    // Reset password
    //
    if( $( "#popResetPassword" ).length){
        $( "#popResetPassword" ).dialog({
           autoOpen: false,
           modal: true
        });
    }

    // Registration form
    //
    if ($( "#popRegister" ).length) {
        $( "#popRegister" ).dialog({
            autoOpen: false,
            modal: true
        });
    }

	// Add Events which open the various popup windows
	//
	// New Profile Image
	$('#butNewImage').click(function() {
   		$("#popChangeMyPicture").dialog('open')
   		return false;
  	});

    // Reset password
    $('#butResetPassword').click(function() {
        $("#popResetPassword").dialog('open')
        return false;
    });

	// Change Password
	$('#butChangePassword').click(function() {
   		$("#popChangeMyPassword").dialog('open')
   		return false;
  	});		

	// MyAppointment CallBack
	$('#butMyApptCallback').click(function() {
   		$("#popMyAppointments").dialog('open')
   		return false;
  	});		

	// Clinic Selector
	$('#butClinicSelector').click(function() {
   		$("#popClinicSelector").dialog('open')
   		return false;
  	});		

    $('#butRegister').click(function() {
        $('#popRegister').dialog('open')
        return false;
    });

	// Prescription sliders
	//
	if ($( "#sliderRight" ).length){
		$( "#sliderRight" ).slider({
				value:0,
				min: -15,
				max: +15,
				step: 0.25,
				slide: function( event, ui ) {
					var labelVal = ui.value.toFixed(2);
					$("#sliderRight a.ui-slider-handle").html("<span>" + labelVal + "</span>");
					$("#right-eye-vites").val(labelVal);				
				}
			});
		}
	if ($( "#sliderLeft" ).length){
		$( "#sliderLeft" ).slider({
				value:0,
				min: -15,
				max: +15,
				step: 0.25,
				slide: function( event, ui ) {
					var labelVal = ui.value.toFixed(2);
					$("#sliderLeft a.ui-slider-handle").html("<span>" + labelVal + "</span>");
					$("#left-eye-vites").val(labelVal);
				}
			});
		}
	// Set initial values	
	//
	if ($( "#sliderRight" ).length){
		$("#sliderRight a.ui-slider-handle").html("<span>0.00</span>");
		$("#right-eye-vites").val(0);
	}
	if ($( "#sliderLeft" ).length){
		$("#sliderLeft a.ui-slider-handle").html("<span>0.00</span>");
		$("#left-eye-vites").val(0);
	}

    $('#goResetPassword').click(function() {

      $.ajax({
        type : 'POST',
        url : '/vites/rf/my2_reset_password',
        data : { email : $('#resetEmail').val() },
        dataType : "text",
        complete : function(data) {
          $("#resetOutput").html(data.responseText);
        }
      });
      return false;
    });

	// Change Password button
	//
	$('#goChangePassword').click(function() {

   		var dataToSend = "";
   		dataToSend+="t_email_p="+$("#t_email_p").val();
   		dataToSend+="&t_existing_p="+$("#t_existing_p").val();
   		dataToSend+="&t_new_p="+$("#t_new_p").val();
   		dataToSend+="&t_new_p2="+$("#t_new_p2").val();
   		
   		$.ajax({
			type : 'POST',
			url : '/vites/rf/my2_change_password/',
			data: dataToSend,
			dataType:"text",
			complete : function(data){
				$("#pwdReturnMessage").html(data.responseText);
			}
		});
   		return false;
  	});	

    // Register button
    //
    $('#goRegister').click(function() {
   		var dataToSend = "";
   		dataToSend+="email="+$("#reg_email").val();
   		dataToSend+="&password="+$("#reg_password").val();
   		
   		$.ajax({
			type : 'POST',
			url : '/login.myul',
			data: dataToSend,
			dataType:"text",
			complete : function(data){
                location.href='/home.myul';
			}
		});
   		return false;
  	});	

    $('#goCallMeNow').click(call_me_now);

    // am-i-suitable can't find prescription.
    $("#aisFind").hide();
    $('#aisDontKnow').hide();

    $('.goAISFind').click(function() {
      $('#aisFind').show();
      $('#aisDontKnow').hide();
      $('.aisShowSliders').hide();
      return false;
    });

    $('.goAISDontKnow').click(function() {
      $('#aisFind').hide();
      $('#aisDontKnow').show();
      $('.aisShowSliders').hide();
      return false;
    });

    $('.goAISShowSliders').click(function() {
      $('#aisFind').hide();
      $('#aisDontKnow').hide();
      $('.aisShowSliders').show();
      return false;
    });

    $('#goMGM').click(doMGM);
    $('#goClinic').click(doClinic);
    $('#faq-question-submit').click(doFaq);
    $('#update-details').click(doPersonal);

	$("#uploadForm").submit(function() {
		$("input.submit").addClass('loading');
	});
	
    // Initialise form uploader.
    $('#uploadForm').ajaxForm({
      success : function(data) {
        $("input.submit").removeClass('loading');
        var res = $(data).find('#photoResponse').text();
        var ok  = res.match(/image will be visible/);
        if(ok != null) {
          location.href='/home.myul';
        }
        else {
          $('#uploadOutput').html(res);
        }
      }
    });

    // AJAX call to set preferred clinic when clinic popup links are selected.
    $('#popClinicSelector a').each(function(index,el) {
      var myurl = $(el).attr('href');
      var path = myurl.match(/\/vites\/clinic\/(.+?)\/$/);
      if( path != null ) {
        $(el).click( function(e) {
          $('#popClinicSelector').dialog('close');
          $.ajax({
            type : "POST",
            url  : "/vites/rf/setsession/",
            data : { "preferred_clinic" : path[1] },
            dataType: "text",
            complete : function(data) {
              location.href = '/home.myul';
            }
          });
          e.preventDefault();
        });
      }
    });

    $('#clinicFormPop .submit').click(function(e) {
      $('#popClinicSelector').dialog('close');
      e.preventDefault();
      $.ajax({
        type : "POST",
        url  : "/vites/rf/find_clinic_ajax",
        data : { "postcode_stub" : $('#fcPostcodeStub').val(),
                 "t_page"        : "my_mgm_ajax" },
        dataType : "text",
        complete : function(data) {
          var res = data.responseText;
          if( data == "none" ) { //Failed
            $('#popClinicSelector').dialog('open');
          }
          else { // ok, show clinic
            location.href = '/home.myul';
          }
        }
      });
    });

    $("input.submit").click(function() {
    	$(this).addClass('loading');
    });

    progressMeter();
})

