                
var isPromo = false;  
// reset the events cookie

$(document).ready(function(){  
    
  addLocationReady( function() {
    $(".paymentPlans ." + userLoc.currency.toLowerCase()).show();
    
    if(perform.isLoggedIn()) {
      $("#step-5 legend").text($("#step-5 legend").text().replace("5","2"));
      $("#step-1, #step-5").show();    
    } else {
      $("#step-1, #step-2, #step-3, #step-4, #step-5").show();
    }
  
    $(".paymentPlans input:radio").bind("change", function(e) {
      if ($(this).attr("checked")) {
        $("p.choice span").html($(this).next("label").html());
      }
      var paymentMethod = $(this).attr("class").split(" ");
      var paymentMethodSize = paymentMethod.length;     
      
      if (jQuery.inArray("perform", paymentMethod)!=-1) {
        isPromo = true;
        addValidation("#registration_promobox", {
          required: true,
          messages: {
            required: "Insert your promo code"
          }
        });
      } else {
        isPromo = false;
        removeValidation("#registration_promobox");
      }
      
      if(isPromo) {
        $(".payment").hide();
        $(".promo").show();
        $("#registrationFormSubmit").val("Activate Subscription Code");
        if(perform.isLoggedIn()) {
          $("#step-5 legend").text("Step 2 : Activate Subscription Code");
        } else {
          $("#step-5 legend").text("Step 5 : Activate Subscription Code");
        }                        
      } else {
        $(".promo").hide();        
        $(".payment").show();        
        $("#registrationFormSubmit").val("Continue to secure payment");
        if(perform.isLoggedIn()) {
          $("#step-5 legend").text("Step 2 : Choose method of payment");
        } else {
          $("#step-5 legend").text("Step 5 : Choose method of payment");
        }
      }
      
      $(".paymentMethod li").hide();
      for (i=0; i<paymentMethodSize; i++) {
        $(".paymentMethod li." + paymentMethod[i]).show();
      }

      var checkedPaymentMethod = $(".paymentMethod input:radio:checked");
      if (!checkedPaymentMethod.is(":visible")) {
        $(".paymentMethod input:radio:visible:first").attr("checked","checked");
      }
      checkedPaymentMethod.change();
      changePaymentUrl();
    });

    $(".paymentMethod input:radio").bind("change", function(e) {
      if ($(this).attr("checked")) {
        changePaymentUrl();
      }
    });
  
    $(".paymentPlans li:visible input:radio").each(function(index) {       
      if(querystring("checkout").length==1) {
        $(".paymentPlans li:visible #" + querystring("checkout")).attr("checked","checked").change();
        $(".paymentMethod li." + querystring("provider") + " input:radio").attr("checked","checked");
      } else if(index==0) {
        $(".paymentPlans li:visible input:radio:eq("+index+")").attr("checked","checked").change();
      }
      if ($(this).attr('checked')) {
        changePaymentUrl();
        $(this).change();
        $("p.choice span").html($(this).next("label").html());
      }
    }); 
    
    $("#registration_promobox").change(function() {
      changePaymentUrl();
    });
  
    $(".field input:checkbox").bind("change", function(e) {
      if ($(this).attr("checked")) {
        $(this).attr("value","true");
      } else {
        $(this).attr("value","false");
      }
    });

  });

    $("#registration-video-demo").jqm(); 
  
    $(".view-test-video").click(function() { 
       testVideo(); 
    });                 

      
      if(perform.isLoggedIn()) {
        var rules = {};
        var messages = {};
      } else {                
        var rules = {  
          "registration_title": {
              required: true,
              notEqualToValue: "Choose"
          },
          "registration_firstName": "required",
          "registration_lastName": "required",
          "registration_email": {
              required: true,
              email: true
          },
          "registration_emailConfirmation": {
              required: true,
              email: true,
              equalTo: "#registration_email"
          },
          "registration_password": {
              required: true,
              minlength: 6
          },
          "registration_passwordConfirmation": {
              required: true,
              equalTo: "#registration_password",
              minlength: 6
          },
          "registration_passwordReminder": "required",
          "registration_viewTestVideo": "required",
          "registration_acceptTermsAndConditions": "required"
      };    


      var messages = {
          "registration_title": "Choose your title",
          "registration_firstName": "Insert your first name",
          "registration_lastName": "Insert your last name",
          "registration_email": {
              required : "Insert your email",
              email: "Incorrect format"
          },
          "registration_emailConfirmation": {
              required: "Confirm your email",
              email: "Incorrect format",
              equalTo: "The two emails don't match"
          },
          "registration_password": {
              required: "Insert your password",
              minlength: "The password must be at least 6 characters long"
          },
          "registration_passwordConfirmation": {
              required: "Confirm your password",
              equalTo: "The two passwords don't match",
              minlength: "The password must be at least 6 characters long"        
          },
          "registration_passwordReminder": "Insert your password reminder",
          "registration_viewTestVideo": "Confirm you have seen the test video",
          "registration_acceptTermsAndConditions": "Accept the terms &amp; conditions"
        };
      }                  
              
      if(!perform.isLoggedIn()) {
        var validator = validatorFactory.getValidator('#userRegistration', rules, messages, function(form) {          
            $("input[type='submit']").attr('disabled', true);  
            var options = { 
              success: showResponse,
              dataType: 'xml',
              data: { registration_username: $('#registration_email').val() }
            }   
            $(form).ajaxSubmit(options);        
          }, { 
          invalidHandler: function(form, validator) {
            $("input[type='submit']").removeAttr('disabled');              
          } 
        });              
      } else {
        $("#userRegistration").validate();
      }
    
      $('select.error, input[type=checkbox].error').live({
          mouseenter: function() {
              $(this).nextAll('label.error').children('div.message').addClass('show-tooltip');
          }, 
          mouseleave: function() {
              $(this).nextAll('label.error').children('div.message').removeClass('show-tooltip');
          }
      });
  
});

function showResponse(responseText, statusText, xhr, $form)  { 
  $(responseText).find('userregistration').each(function () {
    if ($(this).attr('success') == 'false') {
      $(responseText).find('field').each(function () {
        if ($(this).attr('errorCode') == 'ALREADY_IN_USE') {
          $("input[type='submit']").removeAttr('disabled');
          alert("Email address is already taken, please sign up with a different address");
        } 
      });
      $("input[type='submit']").attr('disabled', false);
    } else {
      document.location.href = $('#target').val();
    } 
  });
}
                                               
function changePaymentUrl() {
  if(isPromo) {
    // build promo url
    paymentURL = "/system/payments/checkout/" + $(".paymentPlans li:visible input:radio:checked").val(); 
    if (!$(".paymentPlans li:visible input:radio:checked").hasClass("perform")) {
      paymentURL = paymentURL + $(".paymentMethod input:radio:checked").val();
    } else {
      paymentURL = paymentURL + "/PERFORM";
    }
    paymentURL = paymentURL + "?payments.voucherCode=" + $("#registration_promobox").val() + "&payments.failureRedirectUrl=/buy";      
  } else {
    // build payment url
    paymentURL = "/system/payments/checkout/" + $(".paymentPlans li:visible input:radio:checked").val() + $(".paymentMethod input:radio:checked").val();
  }
  if(!perform.isLoggedIn()) {
    $("#target").val(paymentURL);
  } else {
    $("#userRegistration").attr("action",paymentURL);
  }
}

function addValidation(input,settings) {
  $(input).rules("add", settings);
}

function removeValidation(input) {
  $(input).rules("remove");
  $(input).removeClass("error");  
}

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
   return r;
}
  
function testVideo() {
  
  $("#registration-video-demo").jqmShow();
  $("#registration-video-demo").jqmAddClose('.registration-lightbox-close');
  
  if (swfobject.hasFlashPlayerVersion("10")) {
    var params = {
      wmode:"transparent",
      allowScriptAccess:"always",
      base:"/flash/unifiedplayer/",
      bgcolor: "#ffffff",
      allowFullScreen:"true"
    };
 
    var flashVars = {
      configXML: "/configXml",
      selectedBandwidth:"high",
      setPlayerType:"vod",
      locale:"en-GB",
      resourceLocalePath:"/ptvFlash/unifiedplayer/assets/resources/",
      useMetaSizing:"true",
      disableControls:"false",
      omnitureAccount: s_account,
      useInitialSplashScreen: "false",            
      
      clipId:1779700
    }; 
    
    swfobject.embedSWF("/flash/unifiedplayer/UnifiedPlayer.swf", "registration-flash-video", "640", "360", "10", false, flashVars, params, {})
  }
 
  $("#registration-flash-video").css("display","block");
  swfobject.registerObject("registration-flash-video", "10.0.0", "/ptvFlash/SWFObject/SWFObject2_2/expressInstall.swf");
  $("#registration-flash-video").css("visibility","visible");

}

  
// Rendered: 22/02/2012 22:12:43 GMT

