﻿$jq.namespace('MatchCore.CP');

$jq(document).ready(function() {
	MatchCore.CP.Registration.init();
});

MatchCore.CP.Registration = function() {
	var _handle;
	var _password;
	var _email;
	var _birthDay;
	var _birthMonth;
	var _birthYear;
	var _ageSeekLow;
	var _ageSeekHigh;
	var _postalCode;
	var _countryCode = 0;
	var _cityCode = 0;
	var _stateCode = 0;
	var _gender = 2;
	var _genderSeek = 1;
	var _phoneAreaCode = "";
	var _phoneNumber = "";
	var _emailMatchInfo = true;
	var _emailNewsOffers = false;
	var _emailPartners = false;
	var _platinumContact = false;
	var _failureHandler;
	var _successHandler;
	var _failureDelegate = new MatchCore.Delegate();
	var _successDelegate = new MatchCore.Delegate();
	var _busy = false;
	
	var populateForm = function(){
	    var gender = ($jq.readCookie('MatchSearch') != undefined && $jq.readCookie('MatchSearch')['SC01'] != undefined) ? $jq.readCookie('MatchSearch')['SC01'] : "2";
	    var genderSeek = ($jq.readCookie('MatchSearch') != undefined && $jq.readCookie('MatchSearch')['SC02'] != undefined) ? $jq.readCookie('MatchSearch')['SC02'] : "1"
	    var ageSeekLow = ($jq.readCookie('MatchSearch') != undefined) ? $jq.readCookie('MatchSearch')['SC03'] : null;
	    var ageSeekHigh = ($jq.readCookie('MatchSearch') != undefined) ? $jq.readCookie('MatchSearch')['SC04'] : null;
	    
	    $jq('#formRegistration INPUT[@name="gender"][@value="' + gender + '"]').attr("checked", "checked");
		$jq('#formRegistration INPUT[@name="genderSeek"][@value="'+ genderSeek + '"]').attr("checked", "checked");
		
		
		if (($jq('#formRegistration select[@name="ageSeekLow"]').length) == 1)
		    $jq('#formRegistration select[@name="ageSeekLow"]').val(ageSeekLow).selected = true;
		else
		    $jq('#formRegistration INPUT[@name="ageSeekLow"]').val(ageSeekLow);
		
		
		if (($jq('#formRegistration select[@name="ageSeekHigh"]').length)== 1)
		    $jq('#formRegistration select[@name="ageSeekHigh"]').val(ageSeekHigh).selected = true;
		else 
		    $jq('#formRegistration INPUT[@name="ageSeekHigh"]').val(ageSeekHigh);
		
		try {
			$jq('#formRegistration select[@name="gender"]').val(gender).selected = true;
			$jq('#formRegistration select[@name="genderSeek"]').val(genderSeek).selected = true;
        }
        catch (e){}
		
		var postcode = $jq.readCookie('MatchSearch') != undefined ? $jq.readCookie('MatchSearch')['SC08'] : '';
		if ( postcode != undefined && postcode != '')	{
		  if (IsValidPostalCodeFormat(postcode))
		  $jq('#formRegistration INPUT[@name="postalCode"]').val(postcode);
		}  
		
	}
	
	var consumeForm = function() {
		_handle = $jq('#formRegistration INPUT[@name="handle"]').val();
		_password = $jq('#formRegistration INPUT[@name="password"]').val();
		_email = $jq('#formRegistration INPUT[@name="email"]').val();
		_birthDay = $jq('#formRegistration select[@name="birthDay"]').val();
		_birthMonth = $jq('#formRegistration select[@name="birthMonth"]').val();
		_birthYear = $jq('#formRegistration select[@name="birthYear"]').val();
		_ageSeekLow = ($jq('#formRegistration SELECT[@name="ageSeekLow"]').length) == 1 ? ($jq('#formRegistration SELECT[@name="ageSeekLow"]').val()) : ($jq('#formRegistration INPUT[@name="ageSeekLow"][@checked]').val());
		_ageSeekHigh = ($jq('#formRegistration SELECT[@name="ageSeekHigh"]').length) == 1 ? ($jq('#formRegistration SELECT[@name="ageSeekHigh"]').val()) : ($jq('#formRegistration INPUT[@name="ageSeekHigh"][@checked]').val());
		_postalCode = $jq('#formRegistration INPUT[@name="postalCode"]').val();
		_countryCode = ($jq('#formRegistration INPUT[@name="countryCode"]').length) == 1 ? ($jq('#formRegistration INPUT[@name="countryCode"]').val()) : ($jq('#formRegistration select[@name="countryCode"]').val());
		_stateCode = $jq('#formRegistration select[@name="stateCode"]').val();
		_cityCode = $jq('#formRegistration select[@name="cityCode"]').val();
		_gender = ($jq('#formRegistration SELECT[@name="gender"]').length) == 1 ? ($jq('#formRegistration SELECT[@name="gender"]').val()) : ($jq('#formRegistration INPUT[@name="gender"][@checked]').val());
		_genderSeek = ($jq('#formRegistration SELECT[@name="genderSeek"]').length) == 1 ? ($jq('#formRegistration SELECT[@name="genderSeek"]').val()) : ($jq('#formRegistration INPUT[@name="genderSeek"][@checked]').val());
		_phoneAreaCode = $jq('#formRegistration INPUT[@name="phoneAreaCode"]').val();
		_phoneNumber = $jq('#formRegistration INPUT[@name="phoneNumber"]').val();

		if (document.getElementById('emailMatchInfo') != null)
	    {
	        _emailMatchInfo = ($jq('#formRegistration INPUT[@name="emailMatchInfo"][@checked]').val() != null);
	    }
        _emailNewsOffers = ($jq('#formRegistration INPUT[@name="emailNewsOffers"][@checked]').val() != null);
	    _emailPartners = ($jq('#formRegistration INPUT[@name="emailPartners"][@checked]').val() != null);
	    _platinumContact = ($jq('#formRegistration INPUT[@name="platinumContact"][@checked]').val() != null);
		
	}
	var failure = function (response) {
		if (_failureDelegate.count() > 0)
			_failureDelegate.fire(response);
		else 
			MatchCore.CP.Messaging.show(response.Messages);
	}
	
	var success = function (response) {
		if (_successDelegate.count() > 0)
			_successDelegate.fire(response);
	}
	
	var createSearchCookie = function (){
	    var hash;
	    if ($jq.readCookie('MatchSearch') == undefined)
	    {
	        hash = [];
	        hash['SC07'] = "20"; // 20 miles is default search distance from existing reg, so going with that if no search cookie exists
	    }
	    else
	    {
	        hash = $jq.readCookie('MatchSearch');
	    }
	    hash['SC01'] = _gender;
        hash['SC02'] = _genderSeek;
        hash['SC03'] = _ageSeekLow;
        hash['SC04'] = _ageSeekHigh;
        hash['SC08'] = _postalCode;
        $jq.createCookie('MatchSearch',hash,false,true);
	}

  var USPostalCodeRegex = /^[0-9]{5}$/;
  var CanadianPostalCodeRegex = /^[ABCEGHJKLMNPRSTVXY][0-9][A-Z][\s]*[0-9][A-Z][0-9]$/;
  var UKFullPostalCodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]?[\s]*[0-9][ABDEFGHJLNPQRSTUWXYZ]{2}$/;
  var UKPartialPostalCodeRegex1 = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]?[\s]+[0-9]$/;
  var UKPartialPostalCodeRegex2 = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]?$/;
  var UKPartialPostalCodeRegex3 = /^[A-Z]{1,2}$/;  
  
  var IsValidPostalCodeFormat = function(postalCode){
    
    try {
      postalCode = postalCode.toUpperCase();

      if (USPostalCodeRegex.test(postalCode)) return true;
      
      else if (CanadianPostalCodeRegex.test(postalCode)) return true;

      else if (UKFullPostalCodeRegex.test(postalCode)) return true;

      else if (UKPartialPostalCodeRegex1.test(postalCode) || UKPartialPostalCodeRegex2.test(postalCode) || UKPartialPostalCodeRegex3.test(postalCode))
      {
        return true;
      }
    }
    catch(e) { return false;  }
    
    return false;
    
  }
	
	return {
		init : function(opts) {
			if (opts) {
				if (opts.fail)
					_failureDelegate.add(opts.fail);
					
				if (opts.success)
			        _successDelegate.add(opts.success);
			}
				
			$jq('.btnRegister').bind('click', this.submit);
			MatchCore.CP.CurrentUser.onReady(function() {
				if (!MatchCore.CP.CurrentUser.LoggedIn() && MatchCore.CP.CurrentUser.Registered()) {
					$jq('#formLogin INPUT[@name="handle"]').val(MatchCore.CP.CurrentUser.Handle());
				}
			});
			populateForm(function(){
			return;
			});
		},
		
		submit : function() {
			if (!MatchCore.CP.CurrentUser.LoggedIn()) {
				consumeForm();
				var errors = [];
				
				if (_handle == null || _handle == '') {
					errors.push({ Field : "handle", Text : MatchCore.CP.ClientMessages.RegHandle });
				}
				if (_password == null || _password == '') {
					errors.push({ Field : "password", Text : MatchCore.CP.ClientMessages.RegPassword });
				}
				if (_email == null || _email == ''){
					errors.push({ Field : "email", Text : MatchCore.CP.ClientMessages.RegEmail });
				}
				if (_birthDay == "0" && _birthMonth =="0" && _birthYear == "0"){
					errors.push({ Field : "birthDay", Text : MatchCore.CP.ClientMessages.RegBirthGeneric });
				}
				else
				{
					if (_birthDay == null || _birthDay == '0'){
						errors.push({ Field : "birthDay", Text : MatchCore.CP.ClientMessages.RegBirthDay });
					}
					if (_birthMonth == null || _birthMonth == '0'){
						errors.push({ Field : "birthMonth", Text : MatchCore.CP.ClientMessages.RegBirthMonth });
					}
					if (_birthYear == null || _birthYear == '0'){
						errors.push({ Field : "birthYear", Text : MatchCore.CP.ClientMessages.RegBirthYear });
					}
				}
				if (_countryCode != 1 && _countryCode != 2 && _countryCode != 224)
					_postalCode = '';
			    
				if (_postalCode != undefined){
					if (_postalCode == null || _postalCode == '' && (_countryCode == 1 || _countryCode == 2 || _countryCode == 224))
						errors.push({ Field : "postalCode", Text : MatchCore.CP.ClientMessages.RegPostalcode });
				}
				else
					_postalCode == '';
			        
				if (_ageSeekLow == undefined){
					_ageSeekLow = $jq.readCookie('MatchSearch') != undefined ? $jq.readCookie('MatchSearch')['SC03'] : 25;
				}
				if (_ageSeekHigh == undefined){
					_ageSeekHigh = $jq.readCookie('MatchSearch') != undefined ? $jq.readCookie('MatchSearch')['SC04'] : 45;
				}
			    
				if (isNaN(parseInt(_countryCode))){
					_countryCode = 0;
				}
				if (isNaN(parseInt(_stateCode))){
					_stateCode = 0;
				}
				if (isNaN(parseInt(_cityCode))){
					_cityCode = 0;
				}
			    
				if (_gender == undefined){
				   _gender = $jq.readCookie('MatchSearch') != undefined ? $jq.readCookie('MatchSearch')['SC01'] : 1;
				}
				if (_genderSeek == undefined){
					_genderSeek = $jq.readCookie('MatchSearch') != undefined ? $jq.readCookie('MatchSearch')['SC02'] : 2;
				}
				if (_phoneAreaCode == undefined){
					_phoneAreaCode = "";
				}
				if (_phoneNumber == undefined){
					_phoneNumber = "";
				}
				if (_emailMatchInfo == undefined){
					_emailMatchInfo = true;
				}
				if (_emailNewsOffers == undefined){
					_emailNewsOffers = true;
				}
				if (_emailPartners == undefined){
					_emailPartners = true;
				}
				if (_platinumContact == undefined){
					_platinumContact = false;
				}
				if (errors.length > 0) {
					failure({ "Messages" : errors });
					return;
				}
								
				var postData = {
					"sid" : MatchCore.CP.SID(),
					"theme" : MatchCore.CP.Theme(),
					"handle" : _handle,
					"password" : _password,
					"email" : _email,
					"birthDay" : _birthDay,
					"birthMonth" : _birthMonth,
					"birthYear" : _birthYear,
					"postalCode" : _postalCode,
					"countryCode" : _countryCode,
					"stateCode" : _stateCode,
					"cityCode" : _cityCode,
					"gender" : _gender,
					"genderSeek" : _genderSeek,
					"phoneAreaCode" : _phoneAreaCode,
					"phoneNumber" : _phoneNumber,
					"emailMatchInfo" : _emailMatchInfo,
					"emailNewsOffers" : _emailNewsOffers,
					"emailPartners" : _emailPartners,
					"platinumContact" : _platinumContact,
					"pageID" : MatchCore.CP.PageID(),
					"pageVersion" : MatchCore.CP.PageVersion()
				};
				
				MatchCore.CP.ui_busy();
				
				MatchCore.CP.Services.invoke({
					method : 'Register',
					data : postData,
					verb : 'POST',
					success : function(response) {
						MatchCore.CP.ui_done();
						
						if (response.Success)
						{
							MatchCore.CP.Services.persistCookies(response);
							createSearchCookie();
							success(response);
						}
						else
							failure(response);				
					},
					failure : function(response) {
						MatchCore.CP.ui_done();
						failure({ "Messages" : [{ Text : "There was a problem submitting your registration information." }] });
					}
				});
			}
			else {
				//user already logged in, proceed...
				success({ Success : true });
			}			
		},
		
		onSuccess : function (handler) {
			_successDelegate.add(handler);
		},
		
		onFailure : function (handler) {
			_failureDelegate.add(handler);
		}
	};
}();
