$(document).ready(function(){
	var $tooltip = new Tooltips();
	var $signup = new Signup();
	
	$tooltip.Init();
    $signup.Init();
});

function Signup(){
	var $self = this;
	var $addCreditButton = null;
	var $addCreditForm = null;
	var $signup = null;
        var $mvtClickable = null;
	
	this.Init = function(){
		$isGca = $("form[id=gcasignup], form[id=gcaaddcredit]");//Global Calling Account Signup
		$isGcaConfirmation = $('#gcaconfirmation'); //GCA Confirmation
		$isDla = $("form[id=dlasignup], form[id=dlaaddcredit]");//Direct Line Account Signup
		$isDlaConfirmation = $('#dlaconfirmation'); //DLA Confirmation
		
		if($isGca instanceof jQuery && $isGca.length > 0){
			Logger.log("Initiating Global Calling Account");
			$signup = new GlobalCallingAccount('gca', 'gca');
			$addCreditButton = $("#gcaaddcreditbutton label.title");
			$addCreditForm = $("form#gcaaddcredit");
			$mvtClickable = $(".gcamvtclickable");
		}else if($isGcaConfirmation instanceof jQuery && $isGcaConfirmation.length > 0){
			Logger.log("Initiating Global Calling Account Confirmation");
			$confirmation = new GlobalCallingAccount('gca', 'gca');
			$confirmation.InitConfirmation();
		}else if($isDla instanceof jQuery && $isDla.length > 0){
			Logger.log("Initiating Direct Line Account");
			$signup = new DirectLineAccount('dla', 'dla');
			$addCreditButton = $("#dlaaddcreditbutton label.title");
			$addCreditForm = $("form#dlaaddcredit");
		}

		if($signup != undefined || $signup != null){
			$signup.Init();
			var $mvtAddCreditButton = $addCreditButton.val();
			if($mvtAddCreditButton != null || $mvtAddCreditButton != undefined){
		 		//Hide Add Credit Form Initially
		 		$signup.ToggleAddCreditForm(false);
				
				//Listen to Add Credit Button Click
				this.ListenAddCreditButtonClick();		
			}
		}
	};
	
	this.ListenAddCreditButtonClick = function(){
		$addCreditButton.click(function(){
			if($signup != null || $signup != undefined){
				$signup.ToggleAddCreditForm();
			}
		});
		$mvtClickable.click(function(){
			if($signup != null || $signup != undefined){
				$signup.ToggleAddCreditForm();
			}
		});
	};
};

function GlobalCallingAccount($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "gca";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "gca";
	}
	var $gcaSignupForm = $("form[id=" + $idPrefix + "signup]");
	var $gcaAddCreditForm = $("form[id=" + $idPrefix + "addcredit]");
	var $gcaAddCreditToggleContent = $gcaAddCreditForm.find("fieldset." + $cssPrefix + "box");
	
	var $oneClickSignup = new OneClickSignup($idPrefix, $cssPrefix);
	var $promotion = new PromotionCode($idPrefix, $cssPrefix);
	var $paymentAmount = new SignupPaymentAmount($idPrefix, $cssPrefix);
	var $contact = new SignupContact($idPrefix, $cssPrefix);
	var $leadSource = new SignupLeadSource($idPrefix, $cssPrefix);
	
	this.Init = function(){
		this.ListenFormSubmit();
		
		$oneClickSignup.Init();
		$promotion.Init();
		$paymentAmount.Init();
		$contact.Init();
		$leadSource.Init();
	};
	
	this.InitConfirmation = function(){
		var $signupConfirmation = new SignupConfirmation($idPrefix, $cssPrefix);
		$signupConfirmation.Init();
	};
	
	this.ListenFormSubmit = function(){
		$gcaSignupForm.submit(function(evt){
			var $validator = new ValidateForm($idPrefix, $cssPrefix);
			var $result = $validator.Validate();
			Logger.log("Form Validated = " . $result);
			return $result.form();
		});
		
		$gcaAddCreditForm.submit(function(evt){
			var $validator = new ValidateForm($idPrefix, $cssPrefix);
			var $result = $validator.Validate();
			Logger.log("Form Validated = " . $result);
			return $result.form();
		});
	};
	
	this.ToggleAddCreditForm = function($show){
		if($show != undefined && $show == false){
			if($gcaAddCreditToggleContent != undefined && $gcaAddCreditToggleContent != null){
				$gcaAddCreditToggleContent.parent().hide();
			}
		}else{
			var $element = $gcaAddCreditToggleContent.parent().slideToggle('normal', function(){
				if($element.is(':visible')){
					$('html, body').animate({
						scrollTop: $element.offset().top
					}, 1000);
				}else{
					$('html, body').animate({
					    scrollTop: $('body').offset().top
					}, 1000);
				}
			});
		}
	};
};

function DirectLineAccount($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "dla";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "dla";
	}
	var $dlaSignupForm = $("form[id=" + $idPrefix + "signup]");
	var $dlaAddCreditForm = $("form[id=" + $idPrefix + "addcredit]");
	var $dlaAddCreditToggleContent = $dlaAddCreditForm.find("fieldset." + $cssPrefix + "box:not(#dladirectlinesection)");
	
	var $directLineSelection = new DirectLineSelection($idPrefix, $cssPrefix);
	var $oneClickSignup = new OneClickSignup($idPrefix, $cssPrefix);
	var $promotion = new PromotionCode($idPrefix, $cssPrefix);
	var $paymentAmount = new SignupPaymentAmount($idPrefix, $cssPrefix);
	var $contact = new SignupContact($idPrefix, $cssPrefix);
	var $leadSource = new SignupLeadSource($idPrefix, $cssPrefix);
	
	this.Init = function(){
		this.ListenFormSubmit();
		
		$directLineSelection.Init();
		$oneClickSignup.Init();
		$promotion.Init();
		$paymentAmount.Init();
		$contact.Init();
		$leadSource.Init();
	};
	
	this.ListenFormSubmit = function(){
		$dlaSignupForm.submit(function(){
			var $validator = new ValidateForm($idPrefix, $cssPrefix);
			var $result = $validator.Validate();
			Logger.log("Form Validated = " . $result);
			return $result.form();
		});
		
		$dlaAddCreditForm.submit(function(){
			var $validator = new ValidateForm($idPrefix, $cssPrefix);
			var $result = $validator.Validate();
			Logger.log("Form Validated = " . $result);
			return $result.form();
		});
	};
	
	this.ToggleAddCreditForm = function($show){
		if($show != undefined && $show == false){
			if($dlaAddCreditToggleContent != undefined && $dlaAddCreditToggleContent != null){
				$dlaAddCreditToggleContent.each(function(){
					if($(this).is(':visible')){
						$(this).hide();
					}
				});
			}
		}else{
			var $firstChild = $($dlaAddCreditToggleContent[0]);
			$dlaAddCreditToggleContent.each(function($index, $value){
				$(this).slideToggle('normal', function(){
					if($index == ($dlaAddCreditToggleContent.length - 1)){
						$contact.Init();
						if($firstChild != null || $firstChild != undefined){
							if($firstChild.is(':visible')){
								$('html, body').animate({
									scrollTop: $firstChild.offset().top
								}, 1000);
							}else{
								$('html, body').animate({
								    scrollTop: $('body').offset().top
								}, 1000);
							}
						};
					}
				});
			});
		}
	};
};

function Tooltips(){
	var $self = this;
	var $tooltips = $('.tooltip');
	
	this.Init = function(){
		this.Show();
	};
	
	this.Show = function(){
		$tooltips.each(function(){
			$(this).qtip({
				content:{attr:'title'},
				position:{my:'top left',target:'mouse',viewport: $(window),adjust:{x:10,y:10}},
				hide:{fixed:true},
				style:'ui-tooltip-shadow'
			});
		});
	};
};

function DirectLineSelection($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	var $ajaxURI = '/myaccount/directLine_ajax.php';
	var $ajaxLoader = $(document.createElement("img")).attr({src:'/images/myaccount/ajax-loader.gif', border:'0'});
	
	var $pDirectLineType = $('#' + $idPrefix + 'directlinetype');
	var $sDirectLineType = $('#' + $idPrefix + 'sdirectlinetype');
	var $sDirectLineNumber = $('#' + $idPrefix + 'sdirectlinenumber');
	var $tTerminatingNumber = $('#' + $idPrefix + 'tterminatingnumber');
	var $lPerMinuteCharge = $('#' + $idPrefix + 'lperminutecharge');
	
	this.Init = function(){
		this.numOfRefreshClick = 0;
		this.HandleSelectTypeChange();
		this.ListenTerminationNumberTextChange();
	};
	
	this.HandleSelectTypeChange = function(){
        $sDirectLineType.change(function(){
            var $type = $sDirectLineType.children('option:selected').val();
            $self.LoadDirectLineNumbers($type, $sDirectLineNumber);
        });
    };
    
    this.ListenTerminationNumberTextChange = function(){
    	var $isNumberSelected = $sDirectLineNumber.val();
    	$tTerminatingNumber.bind("blur keyup", function(event){
    		var $terminatingNumberLength = $(this).val().length;
    		if($terminatingNumberLength > 4){
    			$self.HandleTerminationNumberChange();
    		}
    	});
    };
    
    this.HandleTerminationNumberChange = function(){
        $selectedType = $sDirectLineType.val();
        $selectedNumber = $sDirectLineNumber.val();
        $terminatingNumber = jQuery.trim($tTerminatingNumber.val());
        
        if($terminatingNumber.length >= 0 &&  /^((1[0-9]{10})|(011{1}[0-9]+))$/i.test($terminatingNumber)){
            $self.GetPerMinuteCharge($selectedType, $selectedNumber, $terminatingNumber, $lPerMinuteCharge);
        }
    };
    
    this.LoadDirectLineNumbers = function($type, $target){
        $firstOption = "<option value='undefined'>Select...</option>";
        $numberOptions = $firstOption;
        $.ajax({
            type:'POST',
            url:$ajaxURI,
            data:({
                func:'signup_getAvailableNumbers',
                page:$self.numOfRefreshClick,
                type:$type
            }),
            beforeSend:function(){
                this.tempLoader = $ajaxLoader;
                $pDirectLineType.append(this.tempLoader);
                $target.html($firstOption);
            },
            complete:function(){
                this.tempLoader.remove();
            },
            cache:false,
            success:function(data){
                var $obj = jQuery.parseJSON(data);
                delete(data);
                
                if($obj!=null){
                	if($.isArray($obj)){
                		$.each($obj, function(i,item){
                			$numberOptions += "<option value=" + item.ddi + ">"+ item.number + "</option>";
                		});
                    }else{
                        $numberOptions += "<option value=" + $obj.ddi + " selected>"+ $obj.number + "</option>";
                    }
                }
                $target.html($numberOptions);
                $target.trigger("liszt:updated");
            }
        });
    };
    
    this.GetPerMinuteCharge = function($type, $ddi, $number, $target){
        if($number == null || $number == '' || $ddi == null || $ddi == ''){
            $target.html('0.00');
            return;
        }
        var $number = jQuery.trim($number);
        var $testIndex = $number.search('011');
        if($testIndex == 0){
            $number = $number.substring(3);
        }
        $number = parseInt($number);
        if(!isNaN($number)){
            $.ajax({
                type:'POST',
                url:$ajaxURI,
                data:({
                    func:'signup_getPerMinuteCharge',
                    type:$type,
                    ddi:$ddi,
                    number:$number
                }),
                success:function(data){
                    $target.html(data);
                }                
            });
        };
    };
};

function OneClickSignup($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	var $tFirstName = $('#' + $idPrefix + 'tfirstname');
	var $tLastName = $('#' + $idPrefix + 'tlastname');
	var $paymentCard = new PaymentCard($idPrefix, $cssPrefix);
	
	this.Init = function(){
		this.ListenNameTextChange();
	};
	
	this.ListenNameTextChange = function(){
		var $enteredName = '';
		$tFirstName.keyup(function(){
			$enteredName = $(this).val() + " " + $tLastName.val();
			$paymentCard.PopulateNameOnCard($enteredName);
		});
		$tLastName.keyup(function(){
			$enteredName = $tFirstName.val() + " " + $(this).val();
			$paymentCard.PopulateNameOnCard($enteredName);
		});
	};
};

function SignupContact($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	var $countryUS = 'United States';
    var $countryUSValue = 224;
    
    var $tbBillingStreet1 = $('#' + $idPrefix + 'tbillingstreet1');
    var $tbBillingStreetUnit = $('#' + $idPrefix + 'tbillingstreetunit');
    var $tbBillingCity = $('#' + $idPrefix + 'tbillingcity');
    var $pBillingState = $('#' + $idPrefix + 'rowbillingstate');
    var $sBillingState = $('#' + $idPrefix + 'sbillingstate');
    var $pBillingStateText = $('#' + $idPrefix + 'rowbillingstatetext');
    var $tbBillingState = $('#' + $idPrefix + 'tbillingstate');
    var $tbBillingZipCode = $('#' + $idPrefix + 'tbillingzipcode');
    var $sBillingCountry = $('#' + $idPrefix + 'sbillingcountry');
    var $tbBillingPhone = $('#' + $idPrefix + 'tbillingphone');
    var $cbSameAsContact = $('#' + $idPrefix + 'csameascontact');
    
    var $fsGeneralContactSection = $('#' + $idPrefix + 'generalcontactsection');
    var $pGeneralState = $('#' + $idPrefix + 'rowgeneralstate');
    var $pGeneralStateText = $('#' + $idPrefix + 'rowgeneralstatetext');
    var $tbGeneralStreet1 = $('#' + $idPrefix + 'tgeneralstreet1');
    var $tbGeneralStreetUnit = $('#' + $idPrefix + 'generalstreetunit');
    var $tbGeneralCity = $('#' + $idPrefix + 'tgeneralcity');
    var $sGeneralState = $('#' + $idPrefix + 'sgeneralstate');
    var $tGeneralState = $('#' + $idPrefix + 'tgeneralstate');
    var $tbGeneralZipCode = $('#' + $idPrefix + 'tgeneralzipcode');
    var $sGeneralCountry = $('#' + $idPrefix + 'sgeneralcountry');
    var $tbGeneralPhone = $('#' + $idPrefix + 'tgeneralphone');
    
    this.Init = function(){
    	this.InitializeBillingCountryState();
    	this.InitializeGeneralCountryState();
    	//Check for selected Country to toggle state inputs
    	this.ListenBillingCountryChange();
    	this.ListenGeneralCountryChange();
    	
    	this.ListenGeneralContactCheckChange();
    	//Hide Geneneral Contact Initially
    	this.ToggleGeneralContactSection(false);
    };
    
    this.ListenGeneralContactCheckChange = function(){
    	$cbSameAsContact.change(function(){
    		var $is_checked = $(this).is(':checked');
    		$self.ToggleGeneralContactSection(!$is_checked);
    	});
    };
    this.ToggleGeneralContactSection = function($show){
    	if($show){
    		//--The order of the following two statements is important
    		this.CopyBillingContactToGeneralContact();
    		this.InitializeGeneralCountryState();
    		$fsGeneralContactSection.show();
    	}else{
    		$fsGeneralContactSection.hide();
    	}
    };
    this.CopyBillingContactToGeneralContact = function(){
    	$tbGeneralStreet1.val($tbBillingStreet1.val());
    	$tbGeneralStreetUnit.val($tbBillingStreetUnit.val());
    	$tbGeneralCity.val($tbBillingCity.val());
    	$sGeneralState.val($sBillingState.val());
    	$tGeneralState.val($tbBillingState.val());
    	$sGeneralState.trigger("liszt:updated");
    	$tbGeneralZipCode.val($tbBillingZipCode.val());
    	$sGeneralCountry.val($sBillingCountry.val());
    	$sGeneralCountry.trigger("liszt:updated");
    	$tbGeneralPhone.val($tbBillingPhone.val());
    };
    
    this.InitializeBillingCountryState = function(){
    	if($sBillingCountry.val() == $countryUSValue){
    		$self.ToggleBillingStateInputs(true);
    	}else{
    		$self.ToggleBillingStateInputs(false);
    	}
    };
    this.ListenBillingCountryChange = function(){
    	$sBillingCountry.change(function(){
    		if($(this).val() == $countryUSValue){
    			$self.ToggleBillingStateInputs(true);
    		}else{
    			$self.ToggleBillingStateInputs(false);
    		}
    	});
    };
    this.ToggleBillingStateInputs = function($showSelect){
    	if($showSelect){
    		$pBillingStateText.hide();
    		$pBillingStateText.attr('disabled', 'disabled');
    		$pBillingState.removeAttr('disabled');
    		$pBillingState.show();
    	}else{
    		$pBillingState.hide();
    		$pBillingState.attr('disabled', 'disabled');
    		$pBillingStateText.removeAttr('disabled');
    		$pBillingStateText.show();
    	}
    };
    this.InitializeGeneralCountryState = function(){
    	if($sGeneralCountry.val() == $countryUSValue){
    		$self.ToggleGeneralStateInputs(true);
    	}else{
    		$self.ToggleGeneralStateInputs(false);
    	}
    };
    this.ListenGeneralCountryChange = function(){
    	$sGeneralCountry.change(function(){
    		if($(this).val() == $countryUSValue){
    			$self.ToggleGeneralStateInputs(true);
    		}else{
    			$self.ToggleGeneralStateInputs(false);
    		}
    	});
    };
    this.ToggleGeneralStateInputs = function($showSelect){
    	if($showSelect){
    		$pGeneralStateText.hide();
    		$pGeneralStateText.attr('disabled', 'disabled');
    		$pGeneralState.removeAttr('disabled');
    		$pGeneralState.show();
    	}else{
    		$pGeneralState.hide();
    		$pGeneralState.attr('disabled', 'disabled');
    		$pGeneralStateText.removeAttr('disabled');
    		$pGeneralStateText.show();
    	}
    };
};


function PromotionCode($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	
	var $rbPromotionCode = $('#' + $idPrefix + 'rpromotioncode');
	var $rbReferral = $('#' + $idPrefix + "rreferral");
	var $tPromotionCode = $('#' + $idPrefix + "tpromotioncode");
	
	this.Init = function(){
		this.InitializePromotionReferralText();
		this.ListenPromotionCodeChange();
		this.HandlePromotionReferralTextFocus();
	};
	
	this.ListenPromotionCodeChange = function(){
        $rbPromotionCode.change(function(){
            var $is_checked = $(this).is(':checked');
            $self.TogglePromotionReferralText($rbPromotionCode, $is_checked);
        });
        $rbReferral.change(function(){
            var $is_checked = $(this).is(':checked');
            $self.TogglePromotionReferralText($rbReferral, $is_checked);
        });
        $tPromotionCode.change(function(){
            if ($rbPromotionCode.is(':checked')) {
                $.ajaxSetup({
                    'beforeSend': function(xhr) {
                        xhr.setRequestHeader("X-Csrf-Token", $('input#csrfToken').val());
                    }
                });
                $.post('/common/promotion_voucher_validator.php',
                    {p: $('input#' + $idPrefix + 'tpromotioncode').val()},
                    function(data) {
                        switch (data.type)
                        {
                            case 'VOUCHER':
                                $('#' + $idPrefix + 'promotiondisplaymessage').html('');
                                $('#' + $idPrefix + 'tpromotioncode').attr('readonly', 'readonly');
                                $('#' + $idPrefix + 'tpromotioncode').unbind('click');
                                $('div#creditCardInfo').remove();
                                $('div#recreditAmount').hide();
                                $('div#contactSame').hide();
                                $('span#sReferral').remove();
                                $($('div.' + $idPrefix + 'separator')[1]).hide();
                                $($('div.' + $idPrefix + 'separator')[0]).hide();
                                $('fieldset#' + $idPrefix + 'paymentsection > legend').text('Contact Information');
                                break;
                            case 'error':
                                $('#' + $idPrefix + 'promotiondisplaymessage').html('<label class="error">Invalid promotion code entered.</label>');
                                break;
                            default:
                                $('#' + $idPrefix + 'promotiondisplaymessage').html('');
                                break;
                        }
                    },
                    "json");
            }
        });
	};
	
	this.HandlePromotionReferralTextFocus = function(){
        $tPromotionCode.click(function(){
                var $instructionText = $.trim($(this).val());
                if($tPromotionCode.val() == $instructionText){
                    $(this).removeClass('fadedtext').val('');
                    $(this).focus();
                }
        });
    };
	
	this.TogglePromotionReferralText = function($element, $show){
		if($show){
			$tPromotionCode.removeAttr('disabled');
    		if($element == $rbPromotionCode){
    			$tPromotionCode.val('Enter Promotion Code').show();
    		}else if($element == $rbReferral){
    			$tPromotionCode.val('Enter 7 digit Account Number').show();
    		}
    		$tPromotionCode.addClass('fadedtext');
    		$tPromotionCode.focus();
    	}else{
    		$tPromotionCode.attr('disabled', 'disabled');
			$tPromotionCode.hide();
    	}
	};
	
	this.InitializePromotionReferralText = function(){
		if($rbPromotionCode.is(':checked') || ($rbReferral.is(':checked')) || ($tPromotionCode.val() != undefined && $tPromotionCode.val() != '')){
			this.TogglePromotionReferralText(null, true);
		}else{
			this.TogglePromotionReferralText(null, false);
		}
	};
};

function SignupPaymentAmount($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	var $amountValues = new Array(100, 50, 25, 10, 5);
	var $sAmount = $('#' + $idPrefix + 'samount');
	var $tbAmount = $('#' + $idPrefix + 'tamount');
	
	this.Init = function(){
		this.ListenAmountSelectionChange();
		this.ListenAmountTextChange();
	};
	
	this.ListenAmountSelectionChange = function(){
		$sAmount.change(function(){
			$tbAmount.val($sAmount.val());
		});
	};
	this.ListenAmountTextChange = function(){
		var $enteredText, $changeSelection=false;
		$tbAmount.keyup(function(){
			$enteredText = new Number($tbAmount.val());
			$sAmount.children("option").each(function(){
				if($enteredText.toFixed(2) == $(this).val()){
					$changeSelection = true;
					return false;
				}
			});
			$self.CopyTextAmountToSelect($changeSelection);
		});
	};
	this.CopyTextAmountToSelect = function($changeSelection){
		var $enteredNum = new Number($tbAmount.val());
		if($changeSelection){
			$sAmount.val($enteredNum.toFixed(2));
		}else{
			$sAmount.val('');
		}
		$sAmount.trigger("liszt:updated");
	};
};

function PaymentCard($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = "";
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = "";
	}
	var $tNameOnCard = $('#' + $idPrefix + 'tnameoncard'); 
	this.Init = function(){
		//Nothing to be done yet.
	};
	
	this.PopulateNameOnCard = function($name){
		$tNameOnCard.val();
		$tNameOnCard.val($name);
	};
};

function SignupLeadSource($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = '';
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = '';
	}
	var $showOtherFor = new Array("internet", "other");
	var $pLeadSource = $('#' + $idPrefix + 'rowleadsource');
	var $pOtherLeadSource = $('#' + $idPrefix + 'rowotherleadsource');
	var $sLeadSource = $('#' + $idPrefix + 'sleadsource');
	var $tOtherLeadSource = $('#' + $idPrefix + 'totherleadsource');
	
	this.Init = function(){
		this.InitializeLeadSource();
		this.ListenLeadSourceChange();
	};
	
	this.InitializeLeadSource = function(){
		$showOther = false;
		$.each($showOtherFor, function(index, value){
			if(value == $sLeadSource.val()){
				$showOther = true;
				return false;
			}
		});
		$self.ToggleOtherLeadSource($showOther);
	};
	
	this.ListenLeadSourceChange = function(){
		$sLeadSource.change(function(){
			$selectedVal = $(this).val();
			$showOther = false;
			$.each($showOtherFor, function(index, value){
				if(value == $selectedVal){
					$showOther = true;
					return false;
				}
			});
			$self.ToggleOtherLeadSource($showOther);
		});
	};
	this.ToggleOtherLeadSource = function($show){
		if($show){
			$pOtherLeadSource.removeAttr('disabled');
			$pOtherLeadSource.show();
			$tOtherLeadSource.focus();
		}else{
			$pOtherLeadSource.attr('disabled', 'disabled');
			$pOtherLeadSource.hide();
		}
	};
};

function SignupConfirmation($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = '';
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = '';
	}
	
	var $aPrintReceipt = $('#' + $idPrefix + 'printreceipt');
	var $aPrintPage = $('#' + $idPrefix + 'printpage');
	var $dReceipt = $('#' + $idPrefix + 'receipt');
	
	this.Init = function(){
		this.ListenPrintActionsClick();
	};
	
	this.ListenPrintActionsClick = function(){
		$aPrintReceipt.click(function(){
			$self.PrintReceipt();
		});
		$aPrintPage.click(function(){
			window.print();
			return false;
		});
	};
	
	this.PrintReceipt = function(){
		var $receipt =  window.open('','Receipt','width=600,height=600');
		var $css = '<link rel=\"stylesheet\" href=\"/css/misc.css\" type=\"text/css\" />';
	    var $html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><title>Your Signup Receipt</title>'+$css+'</head><body>' + $('<div />').append($dReceipt.clone()).html() + '</body></html>';
	    
	    $receipt.document.open();
	    $receipt.document.write($html);
	    $receipt.document.close();
	    return false;
	};
	
	this.PrintTransaction = function(){
		//$("a[rel='transaction_detail']").colorbox({width:"60%", height:"50%", opacity:0.5, inline:true, href:"#transaction_detail"});
	};
	
	this.PrintPage = function(){
		
	};
};

function ValidateForm($idPrefix, $cssPrefix){
	var $self = this;
	if($idPrefix == undefined || $idPrefix == null){
		$idPrefix = '';
	}
	if($cssPrefix == undefined || $cssPrefix == null){
		$cssPrefix = '';
	}
	
	var $signupForm = $('form[id=' + $idPrefix + 'signup], form[id=' + $idPrefix + 'addcredit]');
	var $submitButton = $('#' + $idPrefix + 'submitbutton');
	this.Validate = function(){
		$('.chzn-select').bind("change", function(){
			$signupForm.validate().element($(this));
	    });
		
		$.validator.addMethod('defaultInvalid', function(value, element){
			return (value != element.defaultValue);
		}, "");
		$.validator.addMethod("exactLength", function(value, element, params){
			return this.optional(element) || this.getLength($.trim(value), element) == params[0];
		}, $.validator.format("Enter exactly {0} characters.")); 
		
		$.validator.addMethod('directLinePhone', function(value, element){
			var $value = $.trim(value);
			if($value.length >= 0){
				return this.optional(element) || /^((1[0-9]{10})|(((011){1}[0-9]+)))$/i.test(value);
			}
		}, "");
		$.validator.addMethod('signupAmount', function(){
			var $sAmount = $('#' + $idPrefix + 'samount');
			var $tAmount = $('#' + $idPrefix + 'tamount');
			var $minAmount = 5;
            var $promotion = $('#' + $idPrefix + 'promotioncode');
			
			return ($.trim($promotion).length > 0) || (($sAmount.val() >= $minAmount) || ($tAmount.val() >= $minAmount))
		}, "");
		$.validator.addMethod('cardExpiry', function(){
			var $expiryMonth = $('#' + $idPrefix + 'sexpirymonth');
			var $expiryYear = $('#' + $idPrefix + 'sexpiryyear');
			if(($expiryMonth.val() > 0) && ($expiryYear.val() > 0)){
				var $selectedDate = new Date($expiryYear.val(), $expiryMonth.val(), 0, 0, 0);
				var $currentDate = new Date();
				Logger.log("Selected Date = " + $selectedDate + ", Current Date = " + $currentDate);
				return ($selectedDate > $currentDate);
			}
			return false;
		}, "");
		$.validator.addMethod('billingState', function(value, element){
			var $billingCountry = $('#' + $idPrefix + 'sbillingcountry');
			var $selectedCountry = $billingCountry.children(':selected').text();
			Logger.log("Selected Billing Country = " + $selectedCountry);
			if(($selectedCountry == 'United States') && (value != '')) return true;
			return false;
		}, "");
		$.validator.addMethod('generalState', function(value, element){
			var $generalCountry = $('#' + $idPrefix + 'sgeneralcountry');
			var $selectedCountry = $generalCountry.children(':selected').text();
			Logger.log("Selected General Country = " + $selectedCountry);
			if(($selectedCountry == 'United States') && (value != '')) return true;
			return false;
		}, "");
		$.validator.addMethod('leadSource', function(){
			var $sLeadSource = $('#' + $idPrefix + 'sleadsource');
			var $tOtherLeadSource = $('#' + $idPrefix + 'totherleadsource');
			if($tOtherLeadSource.is(':visible')){
				return $tOtherLeadSource.val() != '';
			}else{
				return $sLeadSource.val() != '';
			}
			return false;
		}, "");
		
		Logger.log("Validating " + $signupForm.attr('id'));
		var $cbSameBillingGeneralContact = !$('#' + $idPrefix + 'csameascontact:checked');
		var $rReferral = $('#' + $idPrefix + 'rreferral');
		var $tOtherLeadSource = $('#' + $idPrefix + 'totherleadsource');
		return $signupForm.validate({
			debug:true,
			ignore:".chzn-search>input[type=text]",
			rules:{
				sDirectLineType:{required:true, defaultInvalid:true},
				sDirectLineNumber:{required:true, defaultInvalid:true},
				tTerminatingNumber:{required:true, directLinePhone:true},
				tFirstName:{required:true},
				tLastName:{required:true},
				tEmail:{required:true,email:true},
				tConfirmEmail:{required:true,email:true,equalTo:"input[type=text][name=tEmail]"},
				sAmount:{signupAmount:true, required:true},
				tAmount:{signupAmount:true, required:true},
				tNameOnCard:{required:true,minlength:3},
				sCardType:{required:true},
				tCardNumber:{required:true,creditcard:true},
				sExpiryMonth:{cardExpiry:true,required:true},
				sExpiryYear:{cardExpiry:true,required:true},
				tCardId:{required:true,rangelength:[3,3],digits:true},
				tBillingStreet1:{required:true},
				tBillingCity:{required:true},
				sBillingState:{billingState:true},
				tBillingZipCode:{required:true},
				sBillingCountry:{required:true},
				tBillingPhone:{required:true,minlength:3},
				tGeneralStreet1:{required:{depends:function(element){return $cbSameBillingGeneralContact;}}},
				tGeneralCity:{required:{depends:function(element){return $cbSameBillingGeneralContact;}}},
				sGeneralState:{generalState:{depends:function(element){return $cbSameBillingGeneralContact;}}},
				tGeneralZipCode:{required:{depends:function(element){return $cbSameBillingGeneralContact;}}},
				sGeneralCountry:{required:{depends:function(element){return $cbSameBillingGeneralContact;}}},
				tGeneralPhone:{required:{depends:function(element){return $cbSameBillingGeneralContact;}}, minlength:3},
				sLeadSource:{leadSource:{depends:function(element){return $tOtherLeadSource.not(':visible')}}, required:true},
				tLeadSource:{leadSource:{depends:function(element){return $(element).is(':visible')}}, required:true}
			},
			messages:{
				sDirectLineType:{required:'Required', defaultInvalid:'Required'},
				sDirectLineNumber:{required:'Required', defaultInvalid:'Required'},
				tTerminatingNumber:{required:'Required', directLinePhone:'Invalid'},
				tFirstName:{required:'Required'},
				tLastName:{required:'Required'},
				tEmail:{required:'Required',email:'Invalid Email!'},
				tConfirmEmail:{required:'Required',email:'Invalid Email!',equalTo:'Email addresses must match'},
				sAmount:{required:'Required', signupAmount:'Invalid Amount!'},
				tAmount:{required:'Required', signupAmount:'Invalid Amount!'},
				tNameOnCard:{required:'Required',minlength:'Invalid'},
				sCardType:{required:'Required'},
				tCardNumber:{required:'Required',creditcard:'Invalid Number!'},
				cardExpiry:{required:'Required', cardExpiry:'Invalid Date!'},
				sExpiryMonth:{cardExpiry:'Invalid Date!',required:'Required'},
				sExpiryYear:{cardExpiry:'Invalid Date!',required:'Required'},
				tCardId:{required:'Required',rangelength:'Invalid',digits:'Invalid'},
				tBillingStreet1:{required:'Required'},
				tBillingCity:{required:'Required'},
				sBillingState:{billingState:'Required', defaultInvalid:'Required'},
				tBillingZipCode:{required:'Required'},
				sBillingCountry:{required:'Required'},
				tBillingPhone:{required:'Required',minlength:'Invalid'},
				tGeneralStreet1:{required:'Required'},
				tGeneralCity:{required:'Required'},
				sGeneralState:{generalState:'Required'},
				tGeneralZipCode:{required:'Required'},
				sGeneralCountry:{required:'Required'},
				tGeneralPhone:{required:'Required',minlength:'Invalid'},
				sLeadSource:{leadSource:'Required', required:'Required'},
				tOtherLeadSource:{leadSource:'Required', required:'Required'}
			},
			groups:{
				signupAmount: 'sAmount tAmount',
				cardExpiry: 'sExpiryMonth sExpiryYear',
				leadSource: 'sLeadSource tOtherLeadSource'
			},
			errorElement:'label',
			errorClass:'error',
			validClass:'success',
			errorPlacement: function(error, element){
				if(element.parent().children('label:last-child') != error){
					element.parent().append(error);
				}
				element.parent().addClass('error');
			},
			success: function(label){
				label.parent().removeClass('error');
			},
			submitHandler: function(form){
				form.submit();
			}
		});
	};
};

var Logger={};
Logger.Debug = false;
Logger.log = function($data){
	if(this.Debug && window.console){try{console.log($data);}catch($err){/*console not defined*/}}
};

